Skip to content
D
Documentation

Edit database diagrams

how-to
7 min readUpdated

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, React, Vue, Angular or Qwik. 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 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 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
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();
  };
}
  1. 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 returns the mounted DiagramInstance. The framework hosts hand that same instance to their ready callback and dispose it on unmount.

React uses GrafloriaDiagram, Vue uses GrafloriaDiagram, and Qwik uses GrafloriaDiagram. Angular uses GrafloriaDiagramComponent from @grafloria/angular. Qwik builds the function-bearing kit spec in the browser through spec$; it keeps the cleanup function with noSerialize().

ts
/// <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(); });
}

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 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 returns an ErTable, the shipped specialization of CardHandle. columns.get() returns an 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 and renameColumnAt return new arrays. Pass that array to 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 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.

ValueTail at fromHead at to
one-to-manyOne barCrow's foot
one-to-oneOne barOne bar
many-to-manyCrow's footCrow's foot
one-to-zero-or-manyOne barCircle and crow's foot
one-to-one-or-manyOne barBar 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 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. erRowCenterY gives the node-local center of a column row; do not replace it with canvas coordinates. ensureDiagramKitStyles injects the card stylesheet once and is safe to call repeatedly.

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.

TierWhat you seeHow a candidate qualifies
topGold row and ★ BEST chipFirst highest-scoring candidate, when its score is at least 2
goodGreen rowAnother candidate scoring at least 2
okBlue rowSame column name, or both names end in id, without a stronger match
noneDimmed rowNo 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.

Use the visual SQL query builder to see join guidance combined with projected columns, join-type controls and a SQL pane. The Data modeling studio 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

OptionTypeDefaultWhat it does
entitiesEntity spec arrayRequiredNames tables and their columns
relationshipsRelationship spec arrayNo relationshipsDeclares table-level or row-level edges
editablebooleanfalseAdds in-canvas rename, add and delete controls
rowSelectionbooleantrueSelects 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, rather than treating the copied entity specs as a full diagram document.

Was this page helpful?