turbine-orm 0.94.0 → 0.95.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -276,7 +276,7 @@ Going deep on one database means the parts other ORMs push to raw SQL are typed
276
276
 
277
277
  ## Serverless and edge
278
278
 
279
- The core is driver-agnostic: hand any pg-compatible pool to `turbineHttp()` and Turbine runs on Vercel Edge, Cloudflare Workers, Deno Deploy, or anywhere else without TCP. For Neon, `turbine-orm/neon-ws` and `turbine-orm/neon-http` bind its WebSocket `Pool` and its `neon()` HTTP function with their own session rules ([WebSocket](docs/neon-websocket.md), [HTTP](docs/neon-http.md)); both are Experimental. The main entry's import graph is held under **154 kB brotli** (edge entry under **120 kB**) with `pg` external, enforced by `size-limit` in CI at those exact numbers; run `npm run size` for the current figure. MySQL generation emits exact column-local ENUM labels as literal unions and falls back to `string` when catalog labels may be damaged; see [typed ENUM generation](docs/mysql-enum-generation.md) for its boundaries and measured footprint.
279
+ The core is driver-agnostic: hand any pg-compatible pool to `turbineHttp()` and Turbine runs on Vercel Edge, Cloudflare Workers, Deno Deploy, or anywhere else without TCP. For Neon, `turbine-orm/neon-ws` and `turbine-orm/neon-http` bind its WebSocket `Pool` and its `neon()` HTTP function with their own session rules ([WebSocket](docs/neon-websocket.md), [HTTP](docs/neon-http.md)); both are Experimental. The main entry's import graph is held under **156 kB brotli** (edge entry under **120 kB**) with `pg` external, enforced by `size-limit` in CI at those exact numbers; run `npm run size` for the current figure. MySQL generation emits exact column-local ENUM labels as literal unions and falls back to `string` when catalog labels may be damaged; see [typed ENUM generation](docs/mysql-enum-generation.md) for its boundaries and measured footprint.
280
280
 
281
281
  ```typescript
282
282
  import { Pool } from '@neondatabase/serverless';
@@ -384,7 +384,7 @@ It is also built to be extended rather than wrapped. All SQL generation routes t
384
384
  |---|---|---|---|---|---|
385
385
  | **Engine / runtime** | No engine binary (`pg` only) | Client + TS/WASM query compiler | No engine | No engine | Kysely as query runner; SQL built by MikroORM (v7) |
386
386
  | **Runtime deps** | 1 (`pg`) | `@prisma/client` + required driver adapter | 0 | 0 | `@mikro-orm/core` (0 deps) + a driver package |
387
- | **Main bundle (brotli)** | under 154 kB import graph (CI-enforced), `pg` external | ~1.6 MB client (TS/WASM compiler) | ~7 KB core | small | |
387
+ | **Main bundle (brotli)** | under 156 kB import graph (CI-enforced), `pg` external | ~1.6 MB client (TS/WASM compiler) | ~7 KB core | small | |
388
388
  | **Studio** | Read-only by default | Full CRUD, cloud-hosted | Full CRUD; [Gateway](https://gateway.drizzle.team/) self-hosted, free | None | AdminJS integration guide (CRUD panel) |
389
389
  | **Error PII safety** | Keys only by default | Values in messages | Raw pg errors | Raw pg errors | |
390
390
  | **Migrations** | SQL-first, SHA-256 checksums | DSL-generated, shadow DB | SQL or Drizzle Kit | None | Generated by diffing entities against a snapshot or the database; TS/JS classes |
@@ -119,6 +119,15 @@ export interface ForeignKeyEntry {
119
119
  targetTable: string;
120
120
  targetColumns: string[];
121
121
  constraintName: string;
122
+ /**
123
+ * This key's ON DELETE / ON UPDATE, read with the key itself so no other key
124
+ * can supply them. Absent, they are looked up in
125
+ * {@link RelationCatalogFacts.fkActions}.
126
+ */
127
+ actions?: {
128
+ onDelete: ReferentialAction;
129
+ onUpdate: ReferentialAction;
130
+ };
122
131
  }
123
132
  /**
124
133
  * Derive a belongsTo relation name from its FK column. Strips a trailing
@@ -172,11 +181,11 @@ export declare function isUnknownTsType(tsType: string): boolean;
172
181
  * from {@link detectUniqueForeignKeySets}). A reverse relation whose FK column
173
182
  * set EXACTLY matches one of the child's unique sets is emitted as `hasOne`
174
183
  * (to-one) instead of `hasMany`, and named with the SINGULAR of the child
175
- * table (falling back to the legacy plural name on collision). The engine
176
- * introspectors pass a function instead, deciding each foreign key on its own
177
- * (a unique key alone is not enough there: the key must also compare the way
178
- * the join does, which depends on the parent column too). Omit it to keep
179
- * every reverse relation `hasMany`.
184
+ * table (falling back to the legacy plural name on collision).
185
+ * {@link deriveRelations} passes a function instead, deciding each foreign
186
+ * key on its own (on most engines a unique key alone is not enough: the key
187
+ * must also compare the way the join does, which depends on the parent column
188
+ * too). Omit it to keep every reverse relation `hasMany`.
180
189
  */
181
190
  export declare function buildRelationsFromForeignKeys(foreignKeys: ForeignKeyEntry[], columnFieldsByTable: Map<string, Set<string>>, fkActions?: Map<string, {
182
191
  onDelete: ReferentialAction;
@@ -198,6 +207,10 @@ export declare function buildRelationsFromForeignKeys(foreignKeys: ForeignKeyEnt
198
207
  * 3. Each FK's source column is one of J's two key columns.
199
208
  * 4. The two FKs target two DISTINCT tables (A and B).
200
209
  * 5. J has no payload columns beyond the two FK/key columns.
210
+ * 6. Each FK references exactly its target's primary key. The query joins
211
+ * the junction to the target's primary key, so any other referenced
212
+ * column would return rows the junction does not reference. An explicit
213
+ * `manyToMany` declaration is not affected.
201
214
  *
202
215
  * For such a J linking A and B this ADDS a `manyToMany` on A → B and B → A
203
216
  * routed `through` J. It never removes or renames an existing relation:
@@ -210,41 +223,178 @@ export declare function buildRelationsFromForeignKeys(foreignKeys: ForeignKeyEnt
210
223
  */
211
224
  export declare function addAutoManyToManyRelations(tableNames: Iterable<string>, foreignKeys: ForeignKeyEntry[], pkByTable: Map<string, string[]>, columnNamesByTable: Map<string, string[]>, relationsByTable: Map<string, Record<string, RelationDef>>, columnFieldsByTable?: Map<string, Set<string>>, unknownTypedFieldsByTable?: Map<string, Set<string>>, uniqueIndexColsByTable?: Map<string, string[][]>, logger?: TurbineLogger): void;
212
225
  /**
213
- * One-stop relation derivation for the engine introspectors (SQLite / MySQL /
214
- * MSSQL): filters the FK list to the introspected table set, seeds the
215
- * taken-name / json-shadow maps from the engine's column metadata, and runs
216
- * the SAME `buildRelationsFromForeignKeys` + `addAutoManyToManyRelations`
217
- * pipeline as the Postgres introspector, so every engine derives identical
218
- * relation names for the same logical schema (the engines previously carried
219
- * stale copies of a retired naming scheme).
226
+ * An identifier as PostgreSQL stores it: cut to 63 bytes of UTF-8, never
227
+ * inside a character (`truncate_identifier`). Other engines keep longer names
228
+ * (MySQL 64 characters, SQL Server 128), so a name read from their catalogs or
229
+ * DDL is cut the same way before a relation is named from it.
230
+ */
231
+ export declare function postgresIdentifier(name: string): string;
232
+ /**
233
+ * The constraint name PostgreSQL gives a foreign key nobody named:
234
+ * `<table>_<column>[_<column>...]_fkey`, truncated the way PostgreSQL truncates
235
+ * an identifier to 63 bytes (the longer of the two parts first, never inside a
236
+ * character), with a counter after `fkey` while the name is in `taken`.
220
237
  *
221
- * `isToOne` decides, per foreign key, whether the reverse relation is a to-one.
222
- * It must be decided HERE, before naming, and not by flipping the type of a
223
- * relation already named: a to-one is named with the singular of the child
224
- * table (`users.profile`), as PostgreSQL names it, and a flip afterwards kept
225
- * the to-many's plural (`users.profiles`). Omit it (the `legacyToManyUniques`
226
- * opt-out does) to keep every reverse relation `hasMany`.
238
+ * A relation name reads the constraint name in exactly one shape, a COMPOSITE
239
+ * foreign key that shares its target with another foreign key from the same
240
+ * table. Engines disagree about what an unnamed constraint is called (MySQL
241
+ * `orders_ibfk_1`, SQL Server `FK__orders__tenan__1A2B3C4D` with a random
242
+ * suffix, SQLite nothing at all), so an engine introspector names its keys with
243
+ * {@link foreignKeyConstraintNames}, which calls this for each unnamed one, and
244
+ * that shape derives the same relation names as on PostgreSQL.
227
245
  */
228
- export declare function deriveEngineRelations(tableNames: string[], foreignKeys: ForeignKeyEntry[], pkByTable: Map<string, string[]>, columnsByTable: Map<string, Pick<ColumnMetadata, 'name' | 'field' | 'tsType'>[]>, logger?: TurbineLogger, isToOne?: (fk: ForeignKeyEntry) => boolean): Map<string, Record<string, RelationDef>>;
246
+ export declare function defaultForeignKeyConstraintName(table: string, columns: string[], taken?: {
247
+ has(name: string): boolean;
248
+ add(name: string): unknown;
249
+ }): string;
229
250
  /**
230
- * The SQLite to-one test, one foreign key at a time, shared by every SQLite
231
- * introspector (node:sqlite, better-sqlite3, libSQL, D1) so they cannot
232
- * disagree. The child's columns must be exactly a unique key that compares the
233
- * way the join does:
251
+ * One table's foreign-key constraint names, as PostgreSQL names the same
252
+ * declarations: an explicit name is the key's own (cut to 63 bytes, see
253
+ * {@link postgresIdentifier}), and each unnamed key, in declaration order, takes
254
+ * {@link defaultForeignKeyConstraintName}, counting up while the name is taken.
255
+ * On PostgreSQL these are catalog facts, so declaring the same two unnamed keys
256
+ * the other way round gives the `1` suffix to the other one; every engine
257
+ * follows the same rule.
258
+ *
259
+ * What a default must avoid: every other constraint the table carries
260
+ * (`reserved`: PRIMARY KEY, UNIQUE, CHECK and NOT NULL, which PostgreSQL creates
261
+ * before any foreign key, but not a plain index, which it does not consult), and
262
+ * every explicit foreign-key name. All of them are reserved before any default
263
+ * is chosen. PostgreSQL itself names foreign keys one at a time and refuses a
264
+ * statement whose explicit name an earlier unnamed key already took, so for
265
+ * every statement PostgreSQL accepts, reserving first gives its answer; for one
266
+ * it refuses, the explicit key still keeps its name.
267
+ *
268
+ * `taken` holds the foreign-key names of the tables named so far: one set for
269
+ * the whole schema, because PostgreSQL checks a default against every
270
+ * constraint name in it, and it gives the counter to the table created second
271
+ * where two tables' names coincide (the catalog readers name tables in name
272
+ * order, `schemaDefToMetadata` in declaration order). The table's other
273
+ * constraint names are this table's alone and never enter `taken`: on
274
+ * PostgreSQL another table's CHECK counts only if that table was created
275
+ * first, which no other catalog records, and a set shared in name order let a
276
+ * table created later move an earlier table's names. This table's foreign-key
277
+ * names, explicit and chosen, are added to `taken`.
278
+ *
279
+ * @param keys the table's foreign keys in declaration order, `name` undefined
280
+ * for an unnamed one
281
+ * @param reserved the table's other constraint names
282
+ */
283
+ export declare function foreignKeyConstraintNames(table: string, keys: readonly {
284
+ columns: string[];
285
+ name: string | undefined;
286
+ }[], taken: Set<string>, reserved?: Iterable<string>): string[];
287
+ /**
288
+ * A catalog's ON DELETE / ON UPDATE rule (`CASCADE`, `SET NULL`, SQL Server's
289
+ * `NO_ACTION`, ...) as a {@link ReferentialAction}. Anything else is
290
+ * `no action`, the SQL default.
291
+ */
292
+ export declare function referentialActionFromCatalog(rule: unknown): ReferentialAction;
293
+ /** Everything {@link deriveRelations} reads: one engine's catalog facts. */
294
+ export interface RelationCatalogFacts {
295
+ /** The introspected table set, after include / exclude filtering. */
296
+ tableNames: string[];
297
+ /** One entry per foreign-key constraint. One whose source or target is not in `tableNames` is ignored. */
298
+ foreignKeys: ForeignKeyEntry[];
299
+ /** Primary-key columns per table. */
300
+ pkByTable: Map<string, string[]>;
301
+ /** Column metadata per table (only name / field / tsType / pgType are read). */
302
+ columnsByTable: Map<string, Pick<ColumnMetadata, 'name' | 'field' | 'tsType' | 'pgType'>[]>;
303
+ /** Enum types, so an enum column (tsType `unknown` here) is not mistaken for a json/jsonb shadow. */
304
+ enums?: Record<string, readonly string[]>;
305
+ /**
306
+ * Per table, every column set that holds at most one row under the engine's
307
+ * own rules: the primary key, UNIQUE constraints and plain, non-partial
308
+ * UNIQUE indexes. A foreign key whose columns are exactly one of its child
309
+ * table's sets makes the reverse relation to-one.
310
+ */
311
+ uniqueKeysByTable?: Map<string, string[][]>;
312
+ /**
313
+ * Whether the engine compares a foreign key's child and parent columns the
314
+ * way the child's unique key compares them (same type, affinity, collation).
315
+ * When it does not, two children the key keeps apart can match one parent,
316
+ * so the key proves nothing for THAT foreign key. Decided per foreign key: a
317
+ * second foreign key over the same columns that fails it does not change the
318
+ * first one's answer. Absent: always.
319
+ */
320
+ sameKeyComparison?: (fk: ForeignKeyEntry) => boolean;
321
+ /** Two-column UNIQUE keys that stand in for a missing primary key on a junction table. */
322
+ junctionKeysByTable?: Map<string, string[][]>;
323
+ /**
324
+ * Referential actions keyed `<table>::<constraint>`, for a key that carries
325
+ * no {@link ForeignKeyEntry.actions}. Only sound where a name is unique per
326
+ * table, as on PostgreSQL.
327
+ */
328
+ fkActions?: Map<string, {
329
+ onDelete: ReferentialAction;
330
+ onUpdate: ReferentialAction;
331
+ }>;
332
+ /**
333
+ * `tableNames` and `foreignKeys` are already in PostgreSQL's catalog order
334
+ * (source table, then constraint name, as the server orders `name`), so they
335
+ * are taken as given and not sorted again. The PostgreSQL catalog reader sets
336
+ * it, which keeps its output exactly what its own catalog order gives.
337
+ */
338
+ inCatalogOrder?: boolean;
339
+ /** Keep every reverse relation `hasMany` under its plural name, the output before the to-one rule. */
340
+ legacyToManyUniques?: boolean;
341
+ /** Where relation-naming notes go. Defaults to the console logger. */
342
+ logger?: TurbineLogger;
343
+ }
344
+ /**
345
+ * PostgreSQL's order for `name`, which compares bytes: for UTF-8 that is code
346
+ * point order. JavaScript's `<` compares UTF-16 code units instead, which puts a
347
+ * character above U+FFFF (a surrogate pair) BEFORE one in U+E000..U+FFFF, so two
348
+ * differing units at or above U+D800 are compared as the code points they
349
+ * encode.
350
+ */
351
+ export declare function compareCatalogNames(a: string, b: string): number;
352
+ /**
353
+ * THE relation derivation. Every surface that turns a schema into relations
354
+ * calls it with its own catalog facts: the PostgreSQL introspector and the MCP
355
+ * server (via `deriveCatalogRelations`), the SQLite, MySQL, SQL Server, libSQL
356
+ * and D1 introspectors, and `schemaDefToMetadata` for a `defineSchema` schema.
357
+ * The same schema therefore derives the same relations on every engine:
358
+ * `src/test/relation-derivation-parity.test.ts` creates one schema natively on
359
+ * each and holds them all to PostgreSQL's answer.
360
+ *
361
+ * Two things live here rather than in each caller, because each is where the
362
+ * engines used to drift:
363
+ *
364
+ * - CARDINALITY IS DECIDED BEFORE NAMING, one foreign key at a time. A to-one
365
+ * reverse relation is named with the singular of its table
366
+ * (`users.profile`), so the engines that flipped `hasMany` to `hasOne` after
367
+ * naming kept the plural (`profiles`) and accepted a different `with` key
368
+ * than PostgreSQL for the same schema. Each engine states what a unique key
369
+ * is and how its columns compare
370
+ * ({@link RelationCatalogFacts.uniqueKeysByTable},
371
+ * {@link RelationCatalogFacts.sameKeyComparison}) and the decision is made
372
+ * once, here.
373
+ * - FOREIGN KEYS ARE TAKEN IN ONE ORDER, source table then constraint name.
374
+ * The first foreign key to claim a contested name keeps it, and the
375
+ * catalogs return them in different orders (PostgreSQL by table and
376
+ * constraint, MySQL by constraint name, SQLite by PRAGMA id).
377
+ */
378
+ export declare function deriveRelations(facts: RelationCatalogFacts): Map<string, Record<string, RelationDef>>;
379
+ /**
380
+ * SQLite's {@link RelationCatalogFacts.sameKeyComparison}, shared by every
381
+ * SQLite introspector (node:sqlite, better-sqlite3, libSQL, D1) so they cannot
382
+ * disagree. A child's unique key proves a to-one only when the foreign key
383
+ * compares the way the join does:
234
384
  *
235
385
  * - The same comparison affinity on both sides. A TEXT unique FK can store both
236
386
  * '1' and '01', and both match the INTEGER parent 1 after affinity is applied,
237
387
  * so index uniqueness alone cannot justify a to-one.
238
388
  * - No collation that could make two distinct child values match one parent.
239
389
  * Column collations are absent from the catalog, so the test reads the DDL
240
- * and refuses on any `COLLATE` it finds. `relationUniqueByTable` already
241
- * leaves out every child key of a table or index that mentions one. On the
242
- * parent side a key that is the rowid alias needs no such check: it holds
243
- * only integers, which compare as numbers whatever the collation. Any other
244
- * parent key is refused when the parent's DDL mentions `COLLATE`, because a
245
- * `NOCASE` parent key lets the child values 'a' and 'A' both reference the
246
- * parent 'a'.
247
- */
248
- export declare function sqliteToOneForeignKey(columnsByTable: Map<string, ColumnMetadata[]>, relationUniqueByTable: Map<string, string[][]>, tableDefinitions: Map<string, string>, tableFlags: Map<string, {
390
+ * and refuses on any `COLLATE` it finds. The child's unique keys (the
391
+ * introspector's `uniqueKeysByTable`) already leave out every key of a table
392
+ * or index that mentions one. On the parent side a key that is the rowid
393
+ * alias needs no such check: it holds only integers, which compare as numbers
394
+ * whatever the collation. Any other parent key is refused when the parent's
395
+ * DDL mentions `COLLATE`, because a `NOCASE` parent key lets the child values
396
+ * 'a' and 'A' both reference the parent 'a'.
397
+ */
398
+ export declare function sqliteKeyComparison(columnsByTable: Map<string, ColumnMetadata[]>, tableDefinitions: Map<string, string>, tableFlags: Map<string, {
249
399
  strict: number;
250
400
  }>): (fk: ForeignKeyEntry) => boolean;
@@ -375,11 +375,11 @@ function resolveRelationNameCollision(candidate, taken, table, source, logger) {
375
375
  * from {@link detectUniqueForeignKeySets}). A reverse relation whose FK column
376
376
  * set EXACTLY matches one of the child's unique sets is emitted as `hasOne`
377
377
  * (to-one) instead of `hasMany`, and named with the SINGULAR of the child
378
- * table (falling back to the legacy plural name on collision). The engine
379
- * introspectors pass a function instead, deciding each foreign key on its own
380
- * (a unique key alone is not enough there: the key must also compare the way
381
- * the join does, which depends on the parent column too). Omit it to keep
382
- * every reverse relation `hasMany`.
378
+ * table (falling back to the legacy plural name on collision).
379
+ * {@link deriveRelations} passes a function instead, deciding each foreign
380
+ * key on its own (on most engines a unique key alone is not enough: the key
381
+ * must also compare the way the join does, which depends on the parent column
382
+ * too). Omit it to keep every reverse relation `hasMany`.
383
383
  */
384
384
  export function buildRelationsFromForeignKeys(foreignKeys, columnFieldsByTable, fkActions, unknownTypedFieldsByTable, uniqueSetsByTable, logger = consoleLogger) {
385
385
  // Count FKs per (source, target) pair for disambiguation.
@@ -454,24 +454,12 @@ export function buildRelationsFromForeignKeys(foreignKeys, columnFieldsByTable,
454
454
  takenFor(fk.sourceTable).add(belongsToName);
455
455
  assignedFor(fk.sourceTable).add(belongsToName);
456
456
  // Referential actions (omit the 'no action' default to keep metadata lean).
457
- // A constraint NAME is only unique per table in Postgres, so the catalog
458
- // introspector keys this map "<table>::<constraint>". Callers that
459
- // synthesize names from a code-first schema key it by bare name, so both
460
- // spellings resolve.
461
- //
462
- // The bare-name fallback is LIVE, not defensive: `schemaDefToMetadata` keys
463
- // its map by the synthesized `<table>_<column>_fkey` alone, so the qualified
464
- // lookup always misses there and this second lookup is the ONLY thing that
465
- // carries a `defineSchema` relation's onDelete/onUpdate into the metadata.
466
- // Deleting it would silently drop referential actions from every code-first
467
- // schema (verified: a `references: { onDelete: 'cascade' }` resolves through
468
- // this branch and through no other). It is safe for that producer precisely
469
- // because the name it synthesizes already embeds the source table, so a bare
470
- // hit cannot belong to a different table's constraint. A future producer
471
- // emitting TABLE-AGNOSTIC constraint names would break that property and
472
- // could mis-attribute one table's ON DELETE to another's relation; such a
473
- // producer must key the map "<table>::<constraint>" like the catalog reader.
474
- const actions = fkActions?.get(`${fk.sourceTable}::${fk.constraintName}`) ?? fkActions?.get(fk.constraintName) ?? undefined;
457
+ // Every reader but PostgreSQL's hands them over on the key itself, because
458
+ // a name does not identify a key there: SQLite accepts one name twice, and
459
+ // two tables can synthesize one (`box_items.item_id`, `box.items_item_id`),
460
+ // so a map keyed by name gave one key's ON DELETE to another. PostgreSQL's
461
+ // reader keys its map "<table>::<constraint>", which is unique there.
462
+ const actions = fk.actions ?? fkActions?.get(`${fk.sourceTable}::${fk.constraintName}`);
475
463
  const actionFields = {};
476
464
  if (actions?.onDelete && actions.onDelete !== 'no action')
477
465
  actionFields.onDelete = actions.onDelete;
@@ -550,6 +538,10 @@ export function buildRelationsFromForeignKeys(foreignKeys, columnFieldsByTable,
550
538
  * 3. Each FK's source column is one of J's two key columns.
551
539
  * 4. The two FKs target two DISTINCT tables (A and B).
552
540
  * 5. J has no payload columns beyond the two FK/key columns.
541
+ * 6. Each FK references exactly its target's primary key. The query joins
542
+ * the junction to the target's primary key, so any other referenced
543
+ * column would return rows the junction does not reference. An explicit
544
+ * `manyToMany` declaration is not affected.
553
545
  *
554
546
  * For such a J linking A and B this ADDS a `manyToMany` on A → B and B → A
555
547
  * routed `through` J. It never removes or renames an existing relation:
@@ -592,6 +584,16 @@ export function addAutoManyToManyRelations(tableNames, foreignKeys, pkByTable, c
592
584
  const [fkA, fkB] = tableFks;
593
585
  if (fkA.targetTable === fkB.targetTable)
594
586
  continue;
587
+ // Each key references its target's primary key. The many-to-many query
588
+ // joins the junction to the target's PRIMARY KEY, so through a key to
589
+ // another unique column (`tag_code REFERENCES tags (code)`) it returned
590
+ // tags the junction does not reference.
591
+ const referencesPrimaryKey = (fk) => {
592
+ const pk = pkByTable.get(fk.targetTable) ?? [];
593
+ return pk.length === fk.targetColumns.length && pk.every((c, i) => c === fk.targetColumns[i]);
594
+ };
595
+ if (!referencesPrimaryKey(fkA) || !referencesPrimaryKey(fkB))
596
+ continue;
595
597
  // No payload columns: J's columns are exactly the two FK/key columns.
596
598
  const jCols = columnNamesByTable.get(tableName) ?? [];
597
599
  if (jCols.length !== 2)
@@ -645,33 +647,207 @@ export function addAutoManyToManyRelations(tableNames, foreignKeys, pkByTable, c
645
647
  addM2M(fkB, fkA); // B → A
646
648
  }
647
649
  }
650
+ /** PostgreSQL's identifier limit, NAMEDATALEN - 1 bytes. */
651
+ const PG_NAME_BYTES = 63;
652
+ const utf8Bytes = (s) => {
653
+ let n = 0;
654
+ for (const ch of s) {
655
+ const code = ch.codePointAt(0);
656
+ n += code < 0x80 ? 1 : code < 0x800 ? 2 : code < 0x10000 ? 3 : 4;
657
+ }
658
+ return n;
659
+ };
660
+ /** The longest prefix of `s` that fits in `bytes` bytes of UTF-8, never ending inside a character. */
661
+ const clipUtf8 = (s, bytes) => {
662
+ let out = '';
663
+ let used = 0;
664
+ for (const ch of s) {
665
+ used += utf8Bytes(ch);
666
+ if (used > bytes)
667
+ break;
668
+ out += ch;
669
+ }
670
+ return out;
671
+ };
672
+ /**
673
+ * An identifier as PostgreSQL stores it: cut to 63 bytes of UTF-8, never
674
+ * inside a character (`truncate_identifier`). Other engines keep longer names
675
+ * (MySQL 64 characters, SQL Server 128), so a name read from their catalogs or
676
+ * DDL is cut the same way before a relation is named from it.
677
+ */
678
+ export function postgresIdentifier(name) {
679
+ return clipUtf8(name, PG_NAME_BYTES);
680
+ }
681
+ /**
682
+ * The constraint name PostgreSQL gives a foreign key nobody named:
683
+ * `<table>_<column>[_<column>...]_fkey`, truncated the way PostgreSQL truncates
684
+ * an identifier to 63 bytes (the longer of the two parts first, never inside a
685
+ * character), with a counter after `fkey` while the name is in `taken`.
686
+ *
687
+ * A relation name reads the constraint name in exactly one shape, a COMPOSITE
688
+ * foreign key that shares its target with another foreign key from the same
689
+ * table. Engines disagree about what an unnamed constraint is called (MySQL
690
+ * `orders_ibfk_1`, SQL Server `FK__orders__tenan__1A2B3C4D` with a random
691
+ * suffix, SQLite nothing at all), so an engine introspector names its keys with
692
+ * {@link foreignKeyConstraintNames}, which calls this for each unnamed one, and
693
+ * that shape derives the same relation names as on PostgreSQL.
694
+ */
695
+ export function defaultForeignKeyConstraintName(table, columns, taken) {
696
+ // ChooseForeignKeyConstraintNameAddition: columns joined by `_`, stopping
697
+ // once the addition reaches NAMEDATALEN.
698
+ let addition = '';
699
+ for (const column of columns) {
700
+ if (addition.length > 0)
701
+ addition += '_';
702
+ addition += column;
703
+ if (utf8Bytes(addition) >= PG_NAME_BYTES + 1)
704
+ break;
705
+ }
706
+ // makeObjectName + ChooseConstraintName.
707
+ for (let pass = 0;; pass++) {
708
+ const label = pass === 0 ? 'fkey' : `fkey${pass}`;
709
+ let tableBytes = utf8Bytes(table);
710
+ let additionBytes = utf8Bytes(addition);
711
+ const available = PG_NAME_BYTES - (label.length + 2);
712
+ while (tableBytes + additionBytes > available) {
713
+ if (tableBytes > additionBytes)
714
+ tableBytes--;
715
+ else
716
+ additionBytes--;
717
+ }
718
+ const name = `${clipUtf8(table, tableBytes)}_${clipUtf8(addition, additionBytes)}_${label}`;
719
+ if (!taken?.has(name)) {
720
+ taken?.add(name);
721
+ return name;
722
+ }
723
+ }
724
+ }
725
+ /**
726
+ * One table's foreign-key constraint names, as PostgreSQL names the same
727
+ * declarations: an explicit name is the key's own (cut to 63 bytes, see
728
+ * {@link postgresIdentifier}), and each unnamed key, in declaration order, takes
729
+ * {@link defaultForeignKeyConstraintName}, counting up while the name is taken.
730
+ * On PostgreSQL these are catalog facts, so declaring the same two unnamed keys
731
+ * the other way round gives the `1` suffix to the other one; every engine
732
+ * follows the same rule.
733
+ *
734
+ * What a default must avoid: every other constraint the table carries
735
+ * (`reserved`: PRIMARY KEY, UNIQUE, CHECK and NOT NULL, which PostgreSQL creates
736
+ * before any foreign key, but not a plain index, which it does not consult), and
737
+ * every explicit foreign-key name. All of them are reserved before any default
738
+ * is chosen. PostgreSQL itself names foreign keys one at a time and refuses a
739
+ * statement whose explicit name an earlier unnamed key already took, so for
740
+ * every statement PostgreSQL accepts, reserving first gives its answer; for one
741
+ * it refuses, the explicit key still keeps its name.
742
+ *
743
+ * `taken` holds the foreign-key names of the tables named so far: one set for
744
+ * the whole schema, because PostgreSQL checks a default against every
745
+ * constraint name in it, and it gives the counter to the table created second
746
+ * where two tables' names coincide (the catalog readers name tables in name
747
+ * order, `schemaDefToMetadata` in declaration order). The table's other
748
+ * constraint names are this table's alone and never enter `taken`: on
749
+ * PostgreSQL another table's CHECK counts only if that table was created
750
+ * first, which no other catalog records, and a set shared in name order let a
751
+ * table created later move an earlier table's names. This table's foreign-key
752
+ * names, explicit and chosen, are added to `taken`.
753
+ *
754
+ * @param keys the table's foreign keys in declaration order, `name` undefined
755
+ * for an unnamed one
756
+ * @param reserved the table's other constraint names
757
+ */
758
+ export function foreignKeyConstraintNames(table, keys, taken, reserved = []) {
759
+ const names = keys.map((key) => (key.name === undefined ? undefined : postgresIdentifier(key.name)));
760
+ for (const name of names)
761
+ if (name !== undefined)
762
+ taken.add(name);
763
+ const own = new Set(Array.from(reserved, postgresIdentifier));
764
+ const avoid = { has: (name) => taken.has(name) || own.has(name), add: (name) => taken.add(name) };
765
+ return keys.map((key, i) => names[i] ?? defaultForeignKeyConstraintName(table, key.columns, avoid));
766
+ }
767
+ /**
768
+ * A catalog's ON DELETE / ON UPDATE rule (`CASCADE`, `SET NULL`, SQL Server's
769
+ * `NO_ACTION`, ...) as a {@link ReferentialAction}. Anything else is
770
+ * `no action`, the SQL default.
771
+ */
772
+ export function referentialActionFromCatalog(rule) {
773
+ const action = typeof rule === 'string' ? rule.trim().toLowerCase().replace(/_/g, ' ') : '';
774
+ return action === 'cascade' || action === 'restrict' || action === 'set null' || action === 'set default'
775
+ ? action
776
+ : 'no action';
777
+ }
778
+ /**
779
+ * PostgreSQL's order for `name`, which compares bytes: for UTF-8 that is code
780
+ * point order. JavaScript's `<` compares UTF-16 code units instead, which puts a
781
+ * character above U+FFFF (a surrogate pair) BEFORE one in U+E000..U+FFFF, so two
782
+ * differing units at or above U+D800 are compared as the code points they
783
+ * encode.
784
+ */
785
+ export function compareCatalogNames(a, b) {
786
+ const length = Math.min(a.length, b.length);
787
+ for (let i = 0; i < length; i++) {
788
+ let x = a.charCodeAt(i);
789
+ let y = b.charCodeAt(i);
790
+ if (x === y)
791
+ continue;
792
+ if (x >= 0xd800 && y >= 0xd800) {
793
+ // Surrogates (U+D800..U+DFFF) move above U+E000..U+FFFF.
794
+ x += x >= 0xe000 ? -0x800 : 0x2000;
795
+ y += y >= 0xe000 ? -0x800 : 0x2000;
796
+ }
797
+ return x - y;
798
+ }
799
+ return a.length - b.length;
800
+ }
648
801
  /**
649
- * One-stop relation derivation for the engine introspectors (SQLite / MySQL /
650
- * MSSQL): filters the FK list to the introspected table set, seeds the
651
- * taken-name / json-shadow maps from the engine's column metadata, and runs
652
- * the SAME `buildRelationsFromForeignKeys` + `addAutoManyToManyRelations`
653
- * pipeline as the Postgres introspector, so every engine derives identical
654
- * relation names for the same logical schema (the engines previously carried
655
- * stale copies of a retired naming scheme).
802
+ * THE relation derivation. Every surface that turns a schema into relations
803
+ * calls it with its own catalog facts: the PostgreSQL introspector and the MCP
804
+ * server (via `deriveCatalogRelations`), the SQLite, MySQL, SQL Server, libSQL
805
+ * and D1 introspectors, and `schemaDefToMetadata` for a `defineSchema` schema.
806
+ * The same schema therefore derives the same relations on every engine:
807
+ * `src/test/relation-derivation-parity.test.ts` creates one schema natively on
808
+ * each and holds them all to PostgreSQL's answer.
656
809
  *
657
- * `isToOne` decides, per foreign key, whether the reverse relation is a to-one.
658
- * It must be decided HERE, before naming, and not by flipping the type of a
659
- * relation already named: a to-one is named with the singular of the child
660
- * table (`users.profile`), as PostgreSQL names it, and a flip afterwards kept
661
- * the to-many's plural (`users.profiles`). Omit it (the `legacyToManyUniques`
662
- * opt-out does) to keep every reverse relation `hasMany`.
810
+ * Two things live here rather than in each caller, because each is where the
811
+ * engines used to drift:
812
+ *
813
+ * - CARDINALITY IS DECIDED BEFORE NAMING, one foreign key at a time. A to-one
814
+ * reverse relation is named with the singular of its table
815
+ * (`users.profile`), so the engines that flipped `hasMany` to `hasOne` after
816
+ * naming kept the plural (`profiles`) and accepted a different `with` key
817
+ * than PostgreSQL for the same schema. Each engine states what a unique key
818
+ * is and how its columns compare
819
+ * ({@link RelationCatalogFacts.uniqueKeysByTable},
820
+ * {@link RelationCatalogFacts.sameKeyComparison}) and the decision is made
821
+ * once, here.
822
+ * - FOREIGN KEYS ARE TAKEN IN ONE ORDER, source table then constraint name.
823
+ * The first foreign key to claim a contested name keeps it, and the
824
+ * catalogs return them in different orders (PostgreSQL by table and
825
+ * constraint, MySQL by constraint name, SQLite by PRAGMA id).
663
826
  */
664
- export function deriveEngineRelations(tableNames, foreignKeys, pkByTable, columnsByTable, logger = consoleLogger, isToOne) {
665
- const tableSet = new Set(tableNames);
666
- const fks = foreignKeys.filter((fk) => tableSet.has(fk.sourceTable) && tableSet.has(fk.targetTable));
827
+ export function deriveRelations(facts) {
828
+ const tableSet = new Set(facts.tableNames);
829
+ const foreignKeys = facts.foreignKeys.filter((fk) => tableSet.has(fk.sourceTable) && tableSet.has(fk.targetTable));
830
+ if (!facts.inCatalogOrder) {
831
+ foreignKeys.sort((a, b) => compareCatalogNames(a.sourceTable, b.sourceTable) || compareCatalogNames(a.constraintName, b.constraintName));
832
+ }
833
+ const enums = facts.enums ?? {};
667
834
  const columnFieldsByTable = new Map();
668
835
  const unknownTypedFieldsByTable = new Map();
669
- for (const [tbl, cols] of columnsByTable) {
836
+ for (const [tbl, cols] of facts.columnsByTable) {
670
837
  columnFieldsByTable.set(tbl, new Set(cols.map((c) => c.field)));
671
- unknownTypedFieldsByTable.set(tbl, new Set(cols.filter((c) => isUnknownTsType(c.tsType)).map((c) => c.field)));
838
+ // Enum-typed columns also report tsType 'unknown' here, but generate.ts
839
+ // gives them a concrete union type, so a shadow of one is type-broken and
840
+ // must NOT be preserved as a historical json/jsonb shadow.
841
+ unknownTypedFieldsByTable.set(tbl, new Set(cols.filter((c) => isUnknownTsType(c.tsType) && !Object.hasOwn(enums, c.pgType)).map((c) => c.field)));
672
842
  }
673
- const relationsByTable = buildRelationsFromForeignKeys(fks, columnFieldsByTable, undefined, unknownTypedFieldsByTable, isToOne, logger);
674
- addAutoManyToManyRelations(tableNames, fks, pkByTable, new Map(Array.from(columnsByTable, ([tbl, cols]) => [tbl, cols.map((c) => c.name)])), relationsByTable, columnFieldsByTable, unknownTypedFieldsByTable, undefined, logger);
843
+ const { uniqueKeysByTable, sameKeyComparison } = facts;
844
+ const isToOne = facts.legacyToManyUniques
845
+ ? undefined
846
+ : (fk) => (uniqueKeysByTable?.get(fk.sourceTable) ?? []).some((key) => columnSetsEqual(key, fk.sourceColumns)) &&
847
+ (sameKeyComparison === undefined || sameKeyComparison(fk));
848
+ const logger = facts.logger ?? consoleLogger;
849
+ const relationsByTable = buildRelationsFromForeignKeys(foreignKeys, columnFieldsByTable, facts.fkActions, unknownTypedFieldsByTable, isToOne, logger);
850
+ addAutoManyToManyRelations(facts.inCatalogOrder ? facts.tableNames : [...facts.tableNames].sort(compareCatalogNames), foreignKeys, facts.pkByTable, new Map(Array.from(facts.columnsByTable, ([tbl, cols]) => [tbl, cols.map((c) => c.name)])), relationsByTable, columnFieldsByTable, unknownTypedFieldsByTable, facts.junctionKeysByTable, logger);
675
851
  return relationsByTable;
676
852
  }
677
853
  /** SQLite's declared-type affinity rules, in their required precedence order. */
@@ -691,25 +867,25 @@ function sqliteComparisonAffinity(declared, strict) {
691
867
  return 'numeric';
692
868
  }
693
869
  /**
694
- * The SQLite to-one test, one foreign key at a time, shared by every SQLite
695
- * introspector (node:sqlite, better-sqlite3, libSQL, D1) so they cannot
696
- * disagree. The child's columns must be exactly a unique key that compares the
697
- * way the join does:
870
+ * SQLite's {@link RelationCatalogFacts.sameKeyComparison}, shared by every
871
+ * SQLite introspector (node:sqlite, better-sqlite3, libSQL, D1) so they cannot
872
+ * disagree. A child's unique key proves a to-one only when the foreign key
873
+ * compares the way the join does:
698
874
  *
699
875
  * - The same comparison affinity on both sides. A TEXT unique FK can store both
700
876
  * '1' and '01', and both match the INTEGER parent 1 after affinity is applied,
701
877
  * so index uniqueness alone cannot justify a to-one.
702
878
  * - No collation that could make two distinct child values match one parent.
703
879
  * Column collations are absent from the catalog, so the test reads the DDL
704
- * and refuses on any `COLLATE` it finds. `relationUniqueByTable` already
705
- * leaves out every child key of a table or index that mentions one. On the
706
- * parent side a key that is the rowid alias needs no such check: it holds
707
- * only integers, which compare as numbers whatever the collation. Any other
708
- * parent key is refused when the parent's DDL mentions `COLLATE`, because a
709
- * `NOCASE` parent key lets the child values 'a' and 'A' both reference the
710
- * parent 'a'.
880
+ * and refuses on any `COLLATE` it finds. The child's unique keys (the
881
+ * introspector's `uniqueKeysByTable`) already leave out every key of a table
882
+ * or index that mentions one. On the parent side a key that is the rowid
883
+ * alias needs no such check: it holds only integers, which compare as numbers
884
+ * whatever the collation. Any other parent key is refused when the parent's
885
+ * DDL mentions `COLLATE`, because a `NOCASE` parent key lets the child values
886
+ * 'a' and 'A' both reference the parent 'a'.
711
887
  */
712
- export function sqliteToOneForeignKey(columnsByTable, relationUniqueByTable, tableDefinitions, tableFlags) {
888
+ export function sqliteKeyComparison(columnsByTable, tableDefinitions, tableFlags) {
713
889
  return (fk) => {
714
890
  const child = columnsByTable.get(fk.sourceTable);
715
891
  const parent = columnsByTable.get(fk.targetTable);
@@ -724,7 +900,6 @@ export function sqliteToOneForeignKey(columnsByTable, relationUniqueByTable, tab
724
900
  to !== undefined &&
725
901
  sqliteComparisonAffinity(from.pgType, tableFlags.get(fk.sourceTable)?.strict === 1) ===
726
902
  sqliteComparisonAffinity(to.pgType, tableFlags.get(fk.targetTable)?.strict === 1));
727
- }) &&
728
- (relationUniqueByTable.get(fk.sourceTable) ?? []).some((key) => columnSetsEqual(key, fk.sourceColumns)));
903
+ }));
729
904
  };
730
905
  }