# Edit database diagrams

Use the ER kit when your editor needs table cards, typed columns, PK/FK badges and relationships attached to particular fields. The sample renders six editable tables, two foreign keys between the same pair, a self-reference and a junction table. It also offers undoable scripted edits and join suggestions during a connection drag.

Start in the project left by your quick start: [JavaScript](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/javascript-quick-start), [React](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/react-quick-start), [Vue](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/vue-quick-start), [Angular](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/angular-quick-start) or [Qwik](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/qwik-quick-start). Keep the starter's entry file, stylesheet imports and configuration. Add this package set if your project does not already have it:

```bash
npm install -D @grafloria/element @grafloria/engine @grafloria/renderer @grafloria/react @grafloria/vue @grafloria/angular @grafloria/qwik
```

## Build editable tables and connect foreign-key columns

1. Add the shared module below as `src/database-editor.ts`. In an Angular project, put it in `src/app/database-editor.ts`; in Qwik, use `src/database-editor.ts`.

[`erDiagram`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-diagram-kit-functions#erdiagram) turns entity specs into HTML cards and relationship specs into orthogonal edges. Use `ENTITY.column` endpoints to attach a relationship to a row, rather than the table's side. The `from` end carries the tail marker; the `to` end carries the head marker. Here the one side is the primary key and the many side is the foreign key.

[`ErDiagramOptions`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-diagram-kit-interfaces#erdiagramoptions) supplies `entities`, `relationships` and the opt-in `editable` flag. The kit spec includes its wiring step: pass the whole result to the host, not only its nodes and edges.

```ts title="src/database-editor.ts"
import {
  bindJoinGuidance,
  ensureDiagramKitStyles,
  erDiagram,
  erRowCenterY,
  erTable,
} from '@grafloria/element';
import type { CardHandle, ErDiagramOptions, ErTable } from '@grafloria/element';
import { PortModel } from '@grafloria/engine';
import type { DiagramInstance } from '@grafloria/renderer';

export function buildDatabaseDiagram() {
  const options: ErDiagramOptions = {
    editable: true,
    entities: [
      { id: 'warehouses', name: 'Warehouses', position: { x: 40, y: 40 }, columns: [
        { name: 'id', type: 'int', pk: true },
        { name: 'code', type: 'varchar' },
      ] },
      { id: 'shipments', name: 'Shipments', position: { x: 370, y: 100 }, columns: [
        { name: 'id', type: 'int', pk: true },
        { name: 'from_warehouse_id', type: 'int', fk: true },
        { name: 'to_warehouse_id', type: 'int', fk: true },
      ] },
      { id: 'employees', name: 'Employees', position: { x: 740, y: 40 }, columns: [
        { name: 'id', type: 'int', pk: true },
        { name: 'manager_id', type: 'int', fk: true },
      ] },
      { id: 'students', name: 'Students', position: { x: 40, y: 360 }, columns: [
        { name: 'id', type: 'int', pk: true },
        { name: 'name', type: 'varchar' },
      ] },
      { id: 'enrollments', name: 'Enrollments', position: { x: 370, y: 330 }, columns: [
        { name: 'id', type: 'int', pk: true },
        { name: 'student_id', type: 'int', fk: true },
        { name: 'course_id', type: 'int', fk: true },
        { name: 'grade', type: 'varchar' },
      ] },
      { id: 'courses', name: 'Courses', position: { x: 740, y: 390 }, columns: [
        { name: 'id', type: 'int', pk: true },
        { name: 'title', type: 'varchar' },
      ] },
    ],
    relationships: [
      { from: 'warehouses.id', to: 'shipments.to_warehouse_id', label: 'ships to', color: '#d97706' },
      { from: 'warehouses.id', to: 'shipments.from_warehouse_id', label: 'ships from', color: '#0d9488' },
      { from: 'employees.id', to: 'employees.manager_id', label: 'reports to', fromSide: 'right', toSide: 'right' },
      { from: 'students.id', to: 'enrollments.student_id', label: 'has', cardinality: 'one-to-zero-or-many' },
      { from: 'courses.id', to: 'enrollments.course_id', label: 'for', cardinality: 'one-to-one-or-many', fromSide: 'left', toSide: 'right' },
    ],
  };
  return erDiagram(options);
}

export function bindDatabaseEditor(api: DiagramInstance): () => void {
  ensureDiagramKitStyles(api.container.ownerDocument);
  const table: ErTable = erTable(api, 'enrollments');
  const card: CardHandle = table;
  const engine = api.getEngine();
  const toolbar = document.createElement('div');
  const status = document.createElement('output');
  toolbar.style.cssText = 'display:flex;gap:8px;flex-wrap:wrap;padding:8px';
  api.container.before(toolbar);

  const action = (label: string, run: () => Promise<void>) => {
    const button = document.createElement('button');
    button.textContent = label;
    button.onclick = () => { void run(); };
    toolbar.append(button);
    return button;
  };
  action('Rename table', async () => { await table.rename('Course registrations'); });
  action('Add date before FK', async () => {
    if (!table.columns.get('enrolled_at')) {
      await table.columns.add({ name: 'enrolled_at', type: 'date' }, { at: 1 });
    }
  });
  action('Rename grade', async () => {
    await table.columns.get('grade')?.rename('final_grade');
  });
  const undo = action('Undo', async () => { await card.undo(); });
  const redo = action('Redo', async () => { await card.redo(); });
  toolbar.append(status);

  const syncHistory = () => {
    undo.disabled = !engine.canUndo();
    redo.disabled = !engine.canRedo();
  };
  const unbindHistory = [
    'command:executed', 'command:undone', 'command:redone',
    'command:merged', 'command:history:cleared',
  ].map((event) => engine.eventBus.on(event, syncHistory));
  syncHistory();
  const unbindRow = table.onRowSelect(({ field }) => {
    status.textContent = field ? `${field.name}: ${field.type ?? 'untyped'}` : '';
  });
  const unbindDrag = api.getModel().on('node:changed', () => {
    const ids = api.getDraggingNodeIds();
    if (ids.length) status.textContent = `Moving: ${ids.join(', ')}`;
  });

  // Add visible column grips alongside the kit's invisible relationship ports.
  // This is initial wiring, not a user edit or a history entry.
  for (const node of api.getModel().getNodes()) {
    const handle = erTable(api, node.id);
    for (const field of handle.columns) {
      for (const side of ['left', 'right'] as const) {
        node.addPort(new PortModel({
          id: `${node.id}__${field.name}__${side}__wire`,
          type: side === 'left' ? 'input' : 'output',
          side,
          layout: {
            strategy: 'absolute',
            args: { units: 'px', x: side === 'left' ? 0 : handle.width, y: erRowCenterY(field.index) },
          },
        }));
      }
    }
  }
  const guidance = bindJoinGuidance(api);
  return () => {
    guidance.dispose();
    unbindRow();
    unbindDrag();
    for (const unbind of unbindHistory) unbind();
    toolbar.remove();
  };
}
```

2. Mount the spec with your framework's kit host. These files add a feature component; import and render it from the existing starter component without removing the starter's wiring. The JavaScript entry mounts directly.

In JavaScript, [`render`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-core#render) returns the mounted [`DiagramInstance`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-diagraminstance). The framework hosts hand that same instance to their ready callback and dispose it on unmount.

React uses [`GrafloriaDiagram`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-react#grafloriadiagram), Vue uses [`GrafloriaDiagram`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-vue#grafloriadiagram), and Qwik uses [`GrafloriaDiagram`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-qwik#grafloriadiagram). Angular uses `GrafloriaDiagramComponent` from [`@grafloria/angular`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-angular-overview). Qwik builds the function-bearing kit spec in the browser through `spec$`; it keeps the cleanup function with `noSerialize()`.

:::code-group
```ts title="JavaScript"
/// <reference types="vite/client" />
// src/main.ts — retain the starter's stylesheet imports above these imports.
import { render } from '@grafloria/element';
import { bindDatabaseEditor, buildDatabaseDiagram } from './database-editor';

const app = document.querySelector<HTMLDivElement>('#app')!;
const host = document.createElement('div');
host.style.height = '640px';
app.append(host);
const api = render(buildDatabaseDiagram(), host);
const unbind = bindDatabaseEditor(api);
if (import.meta.hot) {
  import.meta.hot.dispose(() => { unbind(); api.dispose(); });
}
```
```tsx title="React"
// src/DatabaseEditor.tsx
import { useEffect, useRef } from 'react';
import { GrafloriaDiagram } from '@grafloria/react';
import type { DiagramInstance } from '@grafloria/renderer';
import { bindDatabaseEditor, buildDatabaseDiagram } from './database-editor';

export default function DatabaseEditor() {
  const cleanup = useRef<(() => void) | undefined>(undefined);
  useEffect(() => () => { cleanup.current?.(); }, []);
  const ready = (api: DiagramInstance) => {
    cleanup.current?.();
    cleanup.current = bindDatabaseEditor(api);
  };
  return <GrafloriaDiagram spec={buildDatabaseDiagram()} onReady={ready}
    style={{ height: '640px' }} />;
}
```
```vue title="Vue"
<!-- src/DatabaseEditor.vue -->
<script setup lang="ts">
import { onBeforeUnmount } from 'vue';
import { GrafloriaDiagram } from '@grafloria/vue';
import type { DiagramInstance } from '@grafloria/renderer';
import { bindDatabaseEditor, buildDatabaseDiagram } from './database-editor';

const spec = buildDatabaseDiagram();
let cleanup: (() => void) | undefined;
function ready(api: DiagramInstance) {
  cleanup?.();
  cleanup = bindDatabaseEditor(api);
}
onBeforeUnmount(() => { cleanup?.(); });
</script>
<template>
  <div><GrafloriaDiagram :spec="spec" @ready="ready" style="height:640px" /></div>
</template>
```
```ts title="Angular"
// src/app/database-editor.component.ts
import { Component } from '@angular/core';
import type { OnDestroy } from '@angular/core';
import { GrafloriaDiagramComponent } from '@grafloria/angular';
import type { DiagramInstance } from '@grafloria/renderer';
import { bindDatabaseEditor, buildDatabaseDiagram } from './database-editor';

@Component({
  selector: 'app-database-editor',
  imports: [GrafloriaDiagramComponent],
  template: '<grafloria-diagram [spec]="spec" (ready)="ready($event)" style="height:640px" />',
})
export class DatabaseEditorComponent implements OnDestroy {
  readonly spec = buildDatabaseDiagram();
  private cleanup?: () => void;
  ready(api: DiagramInstance): void {
    this.cleanup?.();
    this.cleanup = bindDatabaseEditor(api);
  }
  ngOnDestroy(): void { this.cleanup?.(); }
}
```
```tsx title="Qwik"
// src/DatabaseEditor.tsx
import { component$, noSerialize, useSignal, useVisibleTask$ } from '@builder.io/qwik';
import type { NoSerialize } from '@builder.io/qwik';
import { GrafloriaDiagram } from '@grafloria/qwik';
import type { DiagramInstance } from '@grafloria/renderer';
import { bindDatabaseEditor, buildDatabaseDiagram } from './database-editor';

export default component$(() => {
  const cleanup = useSignal<NoSerialize<() => void>>();
  useVisibleTask$(({ cleanup: onCleanup }) => {
    onCleanup(() => { cleanup.value?.(); });
  });
  return <div>
    <GrafloriaDiagram style={{ height: '640px' }}
      spec$={() => buildDatabaseDiagram()}
      onReady$={(api: DiagramInstance) => {
        cleanup.value?.();
        cleanup.value = noSerialize(bindDatabaseEditor(api));
      }} />
  </div>;
});
```
:::

JavaScript renders six editable table cards with PK/FK badges and relationship lines.

React renders the same schema with the scripted-edit toolbar above the canvas.

The React toolbar offers Rename table, Add date before FK and Rename grade controls, with Undo and Redo disabled initially.

Vue renders the shipment's two foreign-key relationships in different colors.

In Vue, teal ships from and amber ships to relationships connect Warehouses to Shipments.

Angular renders the junction table between Students and Courses.

In Angular, Enrollments lists student_id and course_id foreign keys with has and for relationships.

Render Qwik's `src/DatabaseEditor.tsx` from your existing route. In React and Vue, add the feature component to your existing `App` component; in Angular, add `DatabaseEditorComponent` to your root component's `imports` and render `<app-database-editor />` in its template.

The canvas shows table headers, typed column rows, key badges and five named relationships. See the [Table / ER diagram demo](https://grafloria.com/demos/diagrams/table-er.html) for the same data-first card rendering without editing chrome.

## Edit tables in the canvas and from your UI

With `editable: true`, double-click a header to rename a table or a column name to rename a field. Enter commits the name; Escape cancels. Click the card's add-column control to insert a column and open its name editor. The row's delete control removes its column and any attached relationships.

The shared sample also provides three scripted edits:

- **Rename table** calls `rename()` on the live table and changes its header to Course registrations.
- **Add date before FK** inserts `enrolled_at` before `student_id`. The foreign-key port follows `student_id` down one row; the relationship remains attached.
- **Rename grade** obtains the field handle and calls its `rename()` method, preserving its type.

[`erTable`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-diagram-kit-functions#ertable) returns an [`ErTable`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-diagram-kit-classes#ertable), the shipped specialization of [`CardHandle`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-diagram-kit-classes#cardhandle). `columns.get()` returns an [`ErField`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-diagram-kit-classes#erfield) or `undefined`. Obtain it again by its new name after renaming: a field handle identifies a column by name, not by a cached row number.

`ErTable.spec` returns a deep copy, not a mutable reference to the live entity. Use `rename()`, `columns.add()` and the field's `setType()`, `setKeys()` or `remove()` for edits. Each mutation enters the engine's history as one step. The sample's Undo and Redo controls call the inherited methods and update their enabled state from command events, including edits made in the canvas. Undo applies to the shared history, not only the table that supplied the handle.

For an application that already constructs a whole column list, [`addColumnAt`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-diagram-kit-functions#addcolumnat) and [`renameColumnAt`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-diagram-kit-functions#renamecolumnat) return new arrays. Pass that array to [`updateEntity`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-diagram-kit-functions#updateentity) in a `columns` delta to apply it to the mounted table as one undoable edit; omitted delta fields stay unchanged. Prefer the handles for individual field edits.

Try the [ERD editor demo](https://grafloria.com/demos/diagrams/erd-editor.html) to see the in-canvas controls and row-pinned relationships together.

## Handle advanced relationships

The shared `relationships` array demonstrates three schema patterns without custom routing code:

- **Multiple foreign keys:** both shipment fields reference `warehouses.id`. The kit spreads repeat landings on the same row and side, so the two markers do not stack.
- **Self-reference:** both endpoints name `employees`, with `fromSide` and `toSide` set to `right`. The relationship loops out of that side and returns to the manager field.
- **Many-to-many through a junction:** students and courses each join enrollments. The student relationship permits zero enrollments; the course relationship requires one or more.

Choose a named `cardinality` for each relationship. It describes marker placement, not a database constraint enforced against records.

| Value | Tail at `from` | Head at `to` |
| --- | --- | --- |
| `one-to-many` | One bar | Crow's foot |
| `one-to-one` | One bar | One bar |
| `many-to-many` | Crow's foot | Crow's foot |
| `one-to-zero-or-many` | One bar | Circle and crow's foot |
| `one-to-one-or-many` | One bar | Bar and crow's foot |

You can also pass an explicit `{ tail, head }` marker object. `fromSide` and `toSide` accept `left`, `right`, `top` or `bottom`; their defaults are `right` and `left`, respectively. Compare the [advanced ER demo](https://grafloria.com/demos/diagrams/er-advanced.html) with the sample's five relationships.

## Add live join guidance for visual SQL

The kit's relationship ports are invisible row anchors. The shared sample adds visible input and output grips to each existing column with [`PortModel`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-models-portmodel). [`erRowCenterY`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-diagram-kit-functions#errowcentery) gives the node-local center of a column row; do not replace it with canvas coordinates. [`ensureDiagramKitStyles`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-diagram-kit-functions#ensurediagramkitstyles) injects the card stylesheet once and is safe to call repeatedly.

[`bindJoinGuidance`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-diagram-kit-functions#bindjoinguidance) subscribes to the mounted engine's connection lifecycle. Drag from a column's right output grip toward another table's left input grip. Candidate rows tint while the connection is live; the source table stays untinted. The hints clear when the connection completes or is cancelled. The sample disposes the guidance subscription when its host unmounts.

| Tier | What you see | How a candidate qualifies |
| --- | --- | --- |
| `top` | Gold row and ★ BEST chip | First highest-scoring candidate, when its score is at least 2 |
| `good` | Green row | Another candidate scoring at least 2 |
| `ok` | Blue row | Same column name, or both names end in `id`, without a stronger match |
| `none` | Dimmed row | No matching rule |

The strongest rule recognizes names such as `students.id` and `enrollments.student_id`, or matching FK names ending in `_id`. A PK flag opposite an FK flag scores next. Guidance ranks candidates; it is not a SQL generator or a replacement for connection validation. Add domain rules through [connection validation](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/validate-connections).

Use the [visual SQL query builder](https://grafloria.com/demos/diagrams/query-builder.html) to see join guidance combined with projected columns, join-type controls and a SQL pane. The [Data modeling studio](https://grafloria.com/demos/diagrams/data-modeling.html) combines editable tables and foreign keys with live SQLite, PostgreSQL and MySQL schema text. Its Run control creates a fresh in-memory database, seeds rows and runs a query; MySQL schemas can run through the SQLite or PostgreSQL alternatives presented there.

## Options and pitfalls

| Option | Type | Default | What it does |
| --- | --- | --- | --- |
| `entities` | Entity spec array | Required | Names tables and their columns |
| `relationships` | Relationship spec array | No relationships | Declares table-level or row-level edges |
| `editable` | `boolean` | `false` | Adds in-canvas rename, add and delete controls |
| `rowSelection` | `boolean` | `true` | Selects a column on click and emits row-selection events; set `false` to opt out |

- A misspelled entity or column in a relationship throws when `erDiagram()` builds the spec. Use entity IDs, not display names.
- Removing a referenced field drops its ports and edges. Undo restores them together.
- Keep the initial spec stable while editing. A changed spec or options value replaces the hosted diagram; use the live handles for edits instead.
- The visible grips in this sample seed the initial columns. An added column gets its editing row, but does not automatically gain a new pair of application-added grips.
- For document persistence, use [save and restore](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/save-and-restore), rather than treating the copied entity specs as a full diagram document.

## Related

- [Arrange ports and connect](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/ports-and-connection-gestures) covers port direction and connection gestures.
- [Commands and history](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/commands-and-history) explains the shared undo stack.
- [Qwik resumable integration](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/qwik-resumable-integration) covers browser-only kit construction and live objects.
