# DBMLX Language — AI Reference

Version: 0.2.3

DBMLX (`.dbmlx`) is a superset of DBML. All standard DBML syntax is valid.
This file documents only the dbmlx-specific extensions that don't exist in standard DBML.

---

## !include — multi-file schemas

Split large schemas across files. Paths are relative to the including file.
Includes are resolved before parsing; the parser sees one stitched document.

```dbmlx
!include "auth/users.dbmlx"
!include "billing/invoices.dbmlx"

Ref: users.id < invoices.user_id
```

---

## DiagramView — named filtered views

Define multiple named views of the same schema. Each view has its own layout file.
Views filter which tables are shown; the underlying schema is unchanged.

```dbmlx
DiagramView auth_context {
  Tables { users, sessions, roles }
}

DiagramView billing_overview {
  TableGroups { billing }
}

DiagramView tenant_schema {
  Schemas { tenant }
}

DiagramView everything {
  Tables { * }
}
```

Sections inside a view:
- `Tables { name, name, ... }` — show only these tables (use `*` for all)
- `TableGroups { name, ... }` — show all tables belonging to these TableGroups
- `Schemas { name, ... }` — show all tables in these schemas

Multiple sections in one view are unioned.

---

## Migration diff annotations

Annotate columns to visualize a schema migration as a before/after diff in the diagram.

### Key rule: write the column in its NEW (post-migration) state.
Record the original values inside the annotation. This means Refs and indexes
always reference the new column name, which is correct for the post-migration schema.

```dbmlx
Table orders {
  id           int           [pk]
  status       varchar(50)

  amount       decimal(10,2) [add]
  // new column being added — rendered with green accent

  total        decimal       [drop]
  // column being removed — rendered with red strikethrough

  customer_id  int           [modify: name="customer", type="varchar(100)"]
  // renamed + retyped: NEW name/type on the line, ORIGINAL name/type in [modify:]
  // rendered as two rows: original (strikethrough) → new (amber)

  email        varchar(255)  [modify: type="varchar(100)"]
  // type change only — omit name= when the column name is unchanged

  user_id      int           [pk, not null, modify: name="uid", pk=false, not_null=false]
  // constraint changes: column was "uid", non-pk, nullable — now "user_id", pk, not null
  // before row shows old name/constraints; after row shows new name/constraints

  notes        text          [not null, drop]
  // [drop] and [add] combine freely with standard column settings
}

// Refs use the NEW column name
Ref: orders.customer_id > customers.id
```

Annotation summary:
- `[add]`  — column or table is being added; does not exist before migration
- `[drop]` — column or table is being removed; will not exist after migration
- `[modify: ...]` — column was changed; write the column in its NEW state, record
  original values inside `modify:`. All keys are optional — omit unchanged ones.
- `[before: ...]` — explicit alias for `modify:`, same keys and behavior; preferred for clarity

`[add]` and `[drop]` work on the Table declaration line to mark an entire table:
```dbmlx
Table audit_log [add] { ... }   // new table — green border + +NEW badge
Table old_cache [drop] { ... }  // removed table — red border + DROP badge
```

### Ref-level annotations

Mark a ref as being added or dropped in a migration:

```dbmlx
// Top-level ref
Ref: orders.user_id > users.id [add]     // new FK
Ref: orders.legacy_id > old.id [drop]    // FK being removed

// Inline ref — prefix the ref: clause with add or drop (no comma between them)
Table orders {
  user_id    int  [add ref: > users.id]              // new FK
  old_id     int  [drop ref: > legacy.id]            // FK being removed
  col        int  [pk, ref: > domains.id, add]       // "add" here = column-level (standalone item)
  tenant_id  int  [add ref: > tenants.id, drop ref: > old_tenants.id]  // ref migration
}
```

Rule: `add ref:` / `drop ref:` (no comma between keyword and `ref:`) = ref annotation.
A standalone `add`/`drop` item elsewhere in the bracket = column annotation (backward compatible).

Ref annotations are visualized when the corresponding view toggle is enabled:
- `[drop]` refs: shown as red dashed lines ("Dropped refs" toggle, default off)
- `[add]` refs: shown as green lines ("Added ref color" toggle, default off)

Side effect — the FK-holder table (the `*`-side that owns the FK column) is marked as modified
(amber left accent + count badge in the header). The referenced PK-side table is unchanged.
1:1 and many-to-many refs flag both endpoints since there is no single FK holder.

`modify:` / `before:` keys (`before:` is a clearer alias for `modify:`, both are identical):

| Key | Format | Records |
|---|---|---|
| `name` | `name="old_name"` | column was named this before |
| `type` | `type="old_type"` | column had this type before |
| `default` | `default="old_val"` | column had this default value before |
| `pk` | `pk=true\|false` | pk status before (true = was pk, false = was not pk) |
| `not_null` | `not_null=true\|false` | not-null status before |
| `unique` | `unique=true\|false` | unique status before |
| `increment` | `increment=true\|false` | auto-increment status before |

All `modify:`/`before:` keys can be combined freely with standard column settings (`pk`, `not null`, `unique`, etc.) in any order.

---

## Editor features

### CodeLens — Focus in diagram

A "Focus in diagram" CodeLens link appears above each `Table` definition in the editor.
Clicking it pans and zooms the open diagram to that table (un-hiding and un-collapsing its group if needed).
Works from both root files and `!include`d module files. Each open diagram is searched directly,
so the lens resolves the table regardless of which file you opened the diagram on.

The Table Groups panel also exposes per-table focus — clicking the focus icon next to a table
opens a small menu with two options: *Focus in diagram* and *Focus in code* (jumps to the
table's source location). Clicking the table name itself still focuses the diagram.

To enable: requires `"editor.codeLens": true` in VS Code settings (default on).

### Ref ↔ inline ref conversion (Code Actions)

The editor offers refactoring lightbulbs that convert between top-level `Ref:` lines and inline `[ref: ...]` settings.

**Top-level Ref → inline ref** (lightbulb on a `Ref:` line):
- Two options: attach the inline ref to the left-side column, or the right-side column. The FK-convention side appears first (right side for `<`, left side for `>`).
- The selected column must be defined in the current file. If it lives in an `!include`d file, the option appears disabled with a message pointing you to that file.
- Migration annotations are preserved: `Ref: a > b [add]` → `[add ref: > b]`. Other settings like `delete: cascade` are preserved alongside the ref clause.
- Composite refs (`a.(c1, c2) > b.(c1, c2)`) are not convertible — DBML inline refs are single-column only. The action shows as disabled with that reason.

**Inline ref → top-level Ref** (lightbulb on a column line with `[ref: ...]`):
- One action per inline ref item on the line (so `[add ref: > a, drop ref: > b]` produces two separate lift actions).
- FK-on-right convention: the column with the inline ref *is* the FK, so when the inline op is `>`, the lift flips both order and operator → `Ref: target < source`. Other operators (`<`, `-`, `<>`) are emitted as-is.
- Schema-qualified and quoted identifiers in the enclosing `Table` and column declaration are preserved verbatim in the source endpoint of the new Ref.
- The new `Ref:` line is inserted right after the table block's closing `}`.

### Column hover highlight

Hovering a column in the diagram highlights all FK relationships connected to it:
- Hovered column and all connected columns get an amber background.
- Related edges turn yellow and thicken; unrelated edges dim.
- Junction dots on merged trunk lines follow the same state.

### Edge hover tooltip

Hovering a relation line shows a tooltip: `source.col → target.col` and cardinality (`N : 1` etc.).
Implemented via a wide transparent hit-area path (stroke-width 12) overlaid on each edge; the tooltip
renders at mouse position using `position: fixed` outside the SVG.

---

## Standard DBML — quick reference

```dbmlx
Table schema.table_name [headercolor: #rrggbb] {
  id           int           [pk, increment]
  name         varchar(255)  [not null, unique]
  status       job_status
  created_at   timestamp     [default: `now()`]
  meta         jsonb         [null, note: 'extra data']
  user_id      int           [ref: > users.id]

  indexes {
    (name, status) [name: "idx_name_status", unique]
  }

  Note: 'Free-form table description'
}

Enum job_status {
  created
  running
  done
  failure [note: 'terminal state']
}

TableGroup billing {
  orders
  invoices
  payments
}

// Refs (can be top-level or inline)
Ref: orders.user_id > users.id     // many-to-one
Ref: users.id < orders.user_id     // one-to-many
Ref: users.id - profiles.user_id   // one-to-one
Ref: tags.id <> posts.id           // many-to-many

// Composite FK
Ref: orders.(user_id, tenant_id) > users.(id, tenant_id)
```
