Synertech Web/ui v0.57.5 Site Storybook

Documentation / Advanced

SchemaEditor

Client@synertech/uiOpen in Storybook

A visual database schema editor: tables you move and resize, their columns (type, primary key, unique, index, default value, nullable) and relations drawn from one column to another. The toolbar groups zoom, fit to content, add table, auto layout, undo / redo (Ctrl + Z / Ctrl + Y) and the JSON and SQL (PostgreSQL) exports. A legend and a clickable minimap are shown with legend.

The component is controlled (value + onValueChange) or uncontrolled (defaultValue). editable (true by default) allows editing tables and columns, readOnly freezes the whole schema and hides the toolbar. A ref exposes addTable, addField, addRelation, toSQL, toJSON… and the createDefaultTable, generateSQL and autoLayoutTables utilities are exported. Like WorkflowEditor, the container has no height of its own: pass one through className. A "use client" component.

Examples

Basic usage

Uncontrolled: defaultValue sets the starting schema, autoFit frames it on mount.

Open in a tab
import { SchemaEditor, type SchemaValue } from "@synertech/ui";

const schema: SchemaValue = {
  tables: [
    {
      id: "customers",
      name: "customers",
      x: 40,
      y: 40,
      fields: [
        { id: "c-id", name: "id", type: "serial", primaryKey: true },
        { id: "c-email", name: "email", type: "varchar", unique: true },
        { id: "c-name", name: "name", type: "text", nullable: true },
      ],
    },
    {
      id: "orders",
      name: "orders",
      x: 360,
      y: 40,
      color: "#6366f1",
      fields: [
        { id: "o-id", name: "id", type: "serial", primaryKey: true },
        {
          id: "o-customer",
          name: "customer_id",
          type: "int4",
          indexed: true,
          foreignKey: { tableId: "customers", fieldId: "c-id" },
        },
        { id: "o-total", name: "total", type: "numeric", defaultValue: "0" },
        { id: "o-date", name: "created_at", type: "timestamptz", defaultValue: "now()" },
      ],
    },
  ],
  relations: [
    {
      id: "r1",
      from: { tableId: "orders", fieldId: "o-customer" },
      to: { tableId: "customers", fieldId: "c-id" },
      cardinality: "n:1",
    },
  ],
};

export function Basic() {
  return <SchemaEditor defaultValue={schema} autoFit className="h-[28rem] rounded-lg border" />;
}

Controlled mode and SQL export

onValueChange receives every change; generateSQL turns the schema into CREATE TABLE statements.

Open in a tab
import { useState } from "react";
import { SchemaEditor, generateSQL, type SchemaValue } from "@synertech/ui";

const schema: SchemaValue = {
  tables: [
    {
      id: "customers",
      name: "customers",
      x: 40,
      y: 40,
      fields: [
        { id: "c-id", name: "id", type: "serial", primaryKey: true },
        { id: "c-email", name: "email", type: "varchar", unique: true },
        { id: "c-name", name: "name", type: "text", nullable: true },
      ],
    },
    {
      id: "orders",
      name: "orders",
      x: 360,
      y: 40,
      color: "#6366f1",
      fields: [
        { id: "o-id", name: "id", type: "serial", primaryKey: true },
        {
          id: "o-customer",
          name: "customer_id",
          type: "int4",
          indexed: true,
          foreignKey: { tableId: "customers", fieldId: "c-id" },
        },
        { id: "o-total", name: "total", type: "numeric", defaultValue: "0" },
        { id: "o-date", name: "created_at", type: "timestamptz", defaultValue: "now()" },
      ],
    },
  ],
  relations: [
    {
      id: "r1",
      from: { tableId: "orders", fieldId: "o-customer" },
      to: { tableId: "customers", fieldId: "c-id" },
      cardinality: "n:1",
    },
  ],
};

export function ControlledWithSql() {
  const [value, setValue] = useState(schema);

  return (
    <div className="space-y-3">
      <SchemaEditor
        value={value}
        onValueChange={setValue}
        autoFit
        className="h-96 rounded-lg border"
      />
      <pre className="max-h-48 overflow-auto rounded-md bg-gray-900 p-3 text-xs text-gray-100">
        {generateSQL(value)}
      </pre>
    </div>
  );
}

Driving it through a ref

addTable receives a table built by createDefaultTable (columns id, createdAt, updatedAt).

Open in a tab
import { useRef } from "react";
import { Button, SchemaEditor, createDefaultTable, type SchemaEditorRef, type SchemaValue } from "@synertech/ui";

const schema: SchemaValue = {
  tables: [
    {
      id: "customers",
      name: "customers",
      x: 40,
      y: 40,
      fields: [
        { id: "c-id", name: "id", type: "serial", primaryKey: true },
        { id: "c-email", name: "email", type: "varchar", unique: true },
        { id: "c-name", name: "name", type: "text", nullable: true },
      ],
    },
    {
      id: "orders",
      name: "orders",
      x: 360,
      y: 40,
      color: "#6366f1",
      fields: [
        { id: "o-id", name: "id", type: "serial", primaryKey: true },
        {
          id: "o-customer",
          name: "customer_id",
          type: "int4",
          indexed: true,
          foreignKey: { tableId: "customers", fieldId: "c-id" },
        },
        { id: "o-total", name: "total", type: "numeric", defaultValue: "0" },
        { id: "o-date", name: "created_at", type: "timestamptz", defaultValue: "now()" },
      ],
    },
  ],
  relations: [
    {
      id: "r1",
      from: { tableId: "orders", fieldId: "o-customer" },
      to: { tableId: "customers", fieldId: "c-id" },
      cardinality: "n:1",
    },
  ],
};

export function WithRef() {
  const ref = useRef<SchemaEditorRef>(null);

  return (
    <div className="space-y-2">
      <div className="flex gap-2">
        <Button
          size="sm"
          onClick={() => ref.current?.addTable(createDefaultTable(80, 320, "products"))}
        >
          Ajouter une table
        </Button>
        <Button size="sm" onClick={() => console.log(ref.current?.toSQL())}>
          Copier le SQL
        </Button>
      </div>
      <SchemaEditor
        ref={ref}
        defaultValue={schema}
        toolbar={false}
        className="h-[28rem] rounded-lg border"
      />
    </div>
  );
}

Read-only view

readOnly freezes the schema; legend={false} removes the legend and minimap, onTableClick shows a detail.

Open in a tab
import { useState } from "react";
import { SchemaEditor, type SchemaValue } from "@synertech/ui";

const schema: SchemaValue = {
  tables: [
    {
      id: "customers",
      name: "customers",
      x: 40,
      y: 40,
      fields: [
        { id: "c-id", name: "id", type: "serial", primaryKey: true },
        { id: "c-email", name: "email", type: "varchar", unique: true },
        { id: "c-name", name: "name", type: "text", nullable: true },
      ],
    },
    {
      id: "orders",
      name: "orders",
      x: 360,
      y: 40,
      color: "#6366f1",
      fields: [
        { id: "o-id", name: "id", type: "serial", primaryKey: true },
        {
          id: "o-customer",
          name: "customer_id",
          type: "int4",
          indexed: true,
          foreignKey: { tableId: "customers", fieldId: "c-id" },
        },
        { id: "o-total", name: "total", type: "numeric", defaultValue: "0" },
        { id: "o-date", name: "created_at", type: "timestamptz", defaultValue: "now()" },
      ],
    },
  ],
  relations: [
    {
      id: "r1",
      from: { tableId: "orders", fieldId: "o-customer" },
      to: { tableId: "customers", fieldId: "c-id" },
      cardinality: "n:1",
    },
  ],
};

export function ReadOnly() {
  const [table, setTable] = useState<string | null>(null);

  return (
    <div className="space-y-2">
      <p className="text-sm text-gray-600">Table sélectionnée : {table ?? "aucune"}</p>
      <SchemaEditor
        defaultValue={schema}
        readOnly
        legend={false}
        autoFit
        onTableClick={({ table: clicked }) => setTable(clicked.name)}
        className="h-80 rounded-lg border"
      />
    </div>
  );
}

Restricted column types

fieldTypes limits the list offered when editing a column; snapToGrid aligns the tables.

Open in a tab
import { SchemaEditor, type SchemaValue } from "@synertech/ui";

const schema: SchemaValue = {
  tables: [
    {
      id: "customers",
      name: "customers",
      x: 40,
      y: 40,
      fields: [
        { id: "c-id", name: "id", type: "serial", primaryKey: true },
        { id: "c-email", name: "email", type: "varchar", unique: true },
        { id: "c-name", name: "name", type: "text", nullable: true },
      ],
    },
    {
      id: "orders",
      name: "orders",
      x: 360,
      y: 40,
      color: "#6366f1",
      fields: [
        { id: "o-id", name: "id", type: "serial", primaryKey: true },
        {
          id: "o-customer",
          name: "customer_id",
          type: "int4",
          indexed: true,
          foreignKey: { tableId: "customers", fieldId: "c-id" },
        },
        { id: "o-total", name: "total", type: "numeric", defaultValue: "0" },
        { id: "o-date", name: "created_at", type: "timestamptz", defaultValue: "now()" },
      ],
    },
  ],
  relations: [
    {
      id: "r1",
      from: { tableId: "orders", fieldId: "o-customer" },
      to: { tableId: "customers", fieldId: "c-id" },
      cardinality: "n:1",
    },
  ],
};

export function CustomFieldTypes() {
  return (
    <SchemaEditor
      defaultValue={schema}
      fieldTypes={["uuid", "text", "int4", "numeric", "bool", "timestamptz"]}
      snapToGrid
      gridSize={20}
      className="h-[28rem] rounded-lg border"
    />
  );
}

API reference

Components

SchemaEditor

ComponentClient
import { SchemaEditor } from "@synertech/ui";

Props — SchemaEditorProps

PropTypeDefaultDescription
autoFit boolean false

Fits the view to the tables once, as soon as there are tables to fit: at mount, or when a schema loaded later arrives.

className string —
defaultValue SchemaValue —
disabled boolean false
draggableTables boolean true
editable boolean true
fieldTypes SchemaFieldType[] DEFAULT_FIELD_TYPES
gridSize number 20
labels UILabelsOf<"schemaEditor" | "editor"> —

The strings the editor writes itself, for this instance: any schemaEditor… key of UILabels, and the editor… keys its toolbar shares with WorkflowEditor. Wins over UILabelsProvider.

legend boolean true
maxZoom number 3
minZoom number 0.1
onFieldClick (event: SchemaFieldEvent) => void —

A click on the row of a field. onTableClick follows it: the field is in the table.

onFieldDoubleClick (event: SchemaFieldEvent) => void —

A double click on the row of a field. onTableDoubleClick follows it.

onTableClick (event: SchemaTableEvent) => void —
onTableContextMenu (event: SchemaTableEvent) => void —
onTableDoubleClick (event: SchemaTableEvent) => void —
onValueChange (next: SchemaValue) => void —
panOnDrag boolean true
readOnly boolean false

Nothing of the schema can be changed, and nothing is greyed out: tables and relations can still be selected, clicked and moved through. Where disabled turns the whole editor off.

ref React.Ref<SchemaEditorRef> —
showGrid boolean true
snapToGrid boolean false
toolbar boolean true
value SchemaValue —
zoomOnWheel boolean true

Functions

Simple grid-based auto-layout that arranges tables in rows, placing tables with foreign key dependencies after their referenced tables.

import { autoLayoutTables } from "@synertech/ui";
autoLayoutTables(tables: SchemaTable[], editable: boolean): SchemaTable[]
import { createDefaultField } from "@synertech/ui";
createDefaultField(name?: string): SchemaField
import { createDefaultTable } from "@synertech/ui";
createDefaultTable(x: number, y: number, name?: string): SchemaTable
import { generateFieldId } from "@synertech/ui";
generateFieldId(): string
import { generateRelationId } from "@synertech/ui";
generateRelationId(): string

generateSQL

Function

The schema as a PostgreSQL script. A table is created after the tables it references, its foreign keys written in it; among the tables that can go, the order of the schema is kept. A cycle (two tables that reference each other) has no such order: its keys that point forward are added with ALTER TABLE once every table exists. A key of two columns is one PRIMARY KEY (a, b) of the table.

Nothing in the schema is written as SQL of its own: names are quoted identifiers, a type that is not a type name is quoted as one, and a defaultValue that is not a literal, a keyword or a function of literals is written as a string.

import { generateSQL } from "@synertech/ui";
generateSQL(value: SchemaValue): string
import { generateTableId } from "@synertech/ui";
generateTableId(): string

Constants

import { DEFAULT_FIELD_TYPES } from "@synertech/ui";
const DEFAULT_FIELD_TYPES: SchemaFieldType[]

Types

type SchemaEditorRef = { … }
FieldTypeDefaultDescription
addField• (tableId: string, field: SchemaField) => void —
addRelation• (relation: SchemaRelation) => void —
addTable• (table: SchemaTable) => void —
fitToContent• () => void —
loadJSON• (json: string) => boolean —

Loads a schema written as JSON, and says whether it did: text that is not JSON, or JSON that is not a schema this editor can open, changes nothing.

removeField• (tableId: string, fieldId: string) => void —
removeRelation• (relationId: string) => void —
removeTable• (tableId: string) => void —
resetView• () => void —
toJSON• () => string —
toSQL• () => string —
zoomIn• () => void —
zoomOut• () => void —

SchemaField

Interface
type SchemaField = { … }
FieldTypeDefaultDescription
id• string —
name• string —
type• SchemaFieldType —
defaultValue string —
foreignKey { tableId: string; fieldId: string; } | null —

What the field references. The editor keeps it in step with relations: drawing a relation writes it, and removing the relation, or the table or the field it names, removes it. A key that names something that is gone is ignored: no icon in the table, no constraint in the SQL.

indexed boolean —
nullable boolean —
primaryKey boolean —
unique boolean —
type SchemaFieldEvent = { … }
FieldTypeDefaultDescription
field• SchemaField —
nativeEvent• globalThis.MouseEvent —
table• SchemaTable —

A line between two fields. The editor draws it from the referenced field (from) to the field that holds the key (to). Written the other way round it is read the same: the end whose foreignKey names the other one holds the key and, when neither says so, the end that is not a primary key.

type SchemaRelation = { … }
FieldTypeDefaultDescription
from• { tableId: string; fieldId: string } —
id• string —
to• { tableId: string; fieldId: string } —
cardinality SchemaRelationCardinality —
label string —

Written beside the line, under its cardinality.

SchemaTable

Interface
type SchemaTable = { … }
FieldTypeDefaultDescription
fields• SchemaField[] —
id• string —
name• string —
x• number —
y• number —
collapsed boolean —
color string —
height number —
locked boolean —
notes string —
width number —
type SchemaTableEvent = { … }
FieldTypeDefaultDescription
nativeEvent• globalThis.MouseEvent —
table• SchemaTable —

SchemaValue

Interface
type SchemaValue = { … }
FieldTypeDefaultDescription
relations• SchemaRelation[] —
tables• SchemaTable[] —
viewport SchemaViewport —
type SchemaViewport = { … }
FieldTypeDefaultDescription
x• number —
y• number —
zoom• number —
type SchemaFieldType = | "text"
  | "varchar"
  | "char"
  | "int2"
  | "int4"
  | "int8"
  | "serial"
  | "bigserial"
  | "float4"
  | "float8"
  | "numeric"
  | "decimal"
  | "bool"
  | "date"
  | "time"
  | "timestamp"
  | "timestamptz"
  | "uuid"
  | "json"
  | "jsonb"
  | "bytea"
  | (string & {})
type SchemaRelationCardinality = "1:1" | "1:n" | "n:1" | "n:n"