turbine-orm 0.94.0 → 0.95.0-next.c2a12c6

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.
Files changed (52) hide show
  1. package/README.md +3 -3
  2. package/dist/catalog-metadata.d.ts +182 -32
  3. package/dist/catalog-metadata.js +232 -57
  4. package/dist/cjs/catalog-metadata.d.ts +182 -32
  5. package/dist/cjs/catalog-metadata.js +239 -59
  6. package/dist/cjs/cli/prisma-resolve.js +14 -9
  7. package/dist/cjs/client.js +49 -0
  8. package/dist/cjs/connection-url.d.ts +44 -1
  9. package/dist/cjs/connection-url.js +57 -2
  10. package/dist/cjs/d1/catalog-metadata.js +30 -19
  11. package/dist/cjs/introspect.d.ts +4 -5
  12. package/dist/cjs/introspect.js +34 -33
  13. package/dist/cjs/libsql/introspect.js +30 -19
  14. package/dist/cjs/mssql.js +83 -29
  15. package/dist/cjs/mysql.js +69 -23
  16. package/dist/cjs/nested-write.js +79 -17
  17. package/dist/cjs/prisma-compat.d.ts +107 -15
  18. package/dist/cjs/prisma-compat.js +654 -113
  19. package/dist/cjs/query/aggregates.js +13 -1
  20. package/dist/cjs/query/types.d.ts +15 -1
  21. package/dist/cjs/schema-metadata.d.ts +5 -4
  22. package/dist/cjs/schema-metadata.js +76 -60
  23. package/dist/cjs/schema.d.ts +8 -7
  24. package/dist/cjs/sqlite-constraint-names.d.ts +65 -0
  25. package/dist/cjs/sqlite-constraint-names.js +264 -0
  26. package/dist/cjs/sqlite.js +34 -14
  27. package/dist/cjs/transaction-state.d.ts +14 -1
  28. package/dist/cjs/transaction-state.js +61 -6
  29. package/dist/cli/prisma-resolve.js +14 -9
  30. package/dist/client.js +50 -1
  31. package/dist/connection-url.d.ts +44 -1
  32. package/dist/connection-url.js +55 -2
  33. package/dist/d1/catalog-metadata.js +31 -20
  34. package/dist/introspect.d.ts +4 -5
  35. package/dist/introspect.js +29 -33
  36. package/dist/libsql/introspect.js +31 -20
  37. package/dist/mssql.js +84 -30
  38. package/dist/mysql.js +70 -24
  39. package/dist/nested-write.js +79 -17
  40. package/dist/prisma-compat.d.ts +107 -15
  41. package/dist/prisma-compat.js +652 -113
  42. package/dist/query/aggregates.js +14 -2
  43. package/dist/query/types.d.ts +15 -1
  44. package/dist/schema-metadata.d.ts +5 -4
  45. package/dist/schema-metadata.js +77 -61
  46. package/dist/schema.d.ts +8 -7
  47. package/dist/sqlite-constraint-names.d.ts +65 -0
  48. package/dist/sqlite-constraint-names.js +257 -0
  49. package/dist/sqlite.js +35 -15
  50. package/dist/transaction-state.d.ts +14 -1
  51. package/dist/transaction-state.js +61 -6
  52. package/package.json +1 -1
@@ -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;
@@ -13,8 +13,13 @@ exports.relationNameFromColumn = relationNameFromColumn;
13
13
  exports.isUnknownTsType = isUnknownTsType;
14
14
  exports.buildRelationsFromForeignKeys = buildRelationsFromForeignKeys;
15
15
  exports.addAutoManyToManyRelations = addAutoManyToManyRelations;
16
- exports.deriveEngineRelations = deriveEngineRelations;
17
- exports.sqliteToOneForeignKey = sqliteToOneForeignKey;
16
+ exports.postgresIdentifier = postgresIdentifier;
17
+ exports.defaultForeignKeyConstraintName = defaultForeignKeyConstraintName;
18
+ exports.foreignKeyConstraintNames = foreignKeyConstraintNames;
19
+ exports.referentialActionFromCatalog = referentialActionFromCatalog;
20
+ exports.compareCatalogNames = compareCatalogNames;
21
+ exports.deriveRelations = deriveRelations;
22
+ exports.sqliteKeyComparison = sqliteKeyComparison;
18
23
  /** Portable catalog policy extracted verbatim from introspect.ts. No driver imports. */
19
24
  const errors_js_1 = require("./errors.js");
20
25
  const logger_js_1 = require("./logger.js");
@@ -392,11 +397,11 @@ function resolveRelationNameCollision(candidate, taken, table, source, logger) {
392
397
  * from {@link detectUniqueForeignKeySets}). A reverse relation whose FK column
393
398
  * set EXACTLY matches one of the child's unique sets is emitted as `hasOne`
394
399
  * (to-one) instead of `hasMany`, and named with the SINGULAR of the child
395
- * table (falling back to the legacy plural name on collision). The engine
396
- * introspectors pass a function instead, deciding each foreign key on its own
397
- * (a unique key alone is not enough there: the key must also compare the way
398
- * the join does, which depends on the parent column too). Omit it to keep
399
- * every reverse relation `hasMany`.
400
+ * table (falling back to the legacy plural name on collision).
401
+ * {@link deriveRelations} passes a function instead, deciding each foreign
402
+ * key on its own (on most engines a unique key alone is not enough: the key
403
+ * must also compare the way the join does, which depends on the parent column
404
+ * too). Omit it to keep every reverse relation `hasMany`.
400
405
  */
401
406
  function buildRelationsFromForeignKeys(foreignKeys, columnFieldsByTable, fkActions, unknownTypedFieldsByTable, uniqueSetsByTable, logger = logger_js_1.consoleLogger) {
402
407
  // Count FKs per (source, target) pair for disambiguation.
@@ -471,24 +476,12 @@ function buildRelationsFromForeignKeys(foreignKeys, columnFieldsByTable, fkActio
471
476
  takenFor(fk.sourceTable).add(belongsToName);
472
477
  assignedFor(fk.sourceTable).add(belongsToName);
473
478
  // Referential actions (omit the 'no action' default to keep metadata lean).
474
- // A constraint NAME is only unique per table in Postgres, so the catalog
475
- // introspector keys this map "<table>::<constraint>". Callers that
476
- // synthesize names from a code-first schema key it by bare name, so both
477
- // spellings resolve.
478
- //
479
- // The bare-name fallback is LIVE, not defensive: `schemaDefToMetadata` keys
480
- // its map by the synthesized `<table>_<column>_fkey` alone, so the qualified
481
- // lookup always misses there and this second lookup is the ONLY thing that
482
- // carries a `defineSchema` relation's onDelete/onUpdate into the metadata.
483
- // Deleting it would silently drop referential actions from every code-first
484
- // schema (verified: a `references: { onDelete: 'cascade' }` resolves through
485
- // this branch and through no other). It is safe for that producer precisely
486
- // because the name it synthesizes already embeds the source table, so a bare
487
- // hit cannot belong to a different table's constraint. A future producer
488
- // emitting TABLE-AGNOSTIC constraint names would break that property and
489
- // could mis-attribute one table's ON DELETE to another's relation; such a
490
- // producer must key the map "<table>::<constraint>" like the catalog reader.
491
- const actions = fkActions?.get(`${fk.sourceTable}::${fk.constraintName}`) ?? fkActions?.get(fk.constraintName) ?? undefined;
479
+ // Every reader but PostgreSQL's hands them over on the key itself, because
480
+ // a name does not identify a key there: SQLite accepts one name twice, and
481
+ // two tables can synthesize one (`box_items.item_id`, `box.items_item_id`),
482
+ // so a map keyed by name gave one key's ON DELETE to another. PostgreSQL's
483
+ // reader keys its map "<table>::<constraint>", which is unique there.
484
+ const actions = fk.actions ?? fkActions?.get(`${fk.sourceTable}::${fk.constraintName}`);
492
485
  const actionFields = {};
493
486
  if (actions?.onDelete && actions.onDelete !== 'no action')
494
487
  actionFields.onDelete = actions.onDelete;
@@ -567,6 +560,10 @@ function buildRelationsFromForeignKeys(foreignKeys, columnFieldsByTable, fkActio
567
560
  * 3. Each FK's source column is one of J's two key columns.
568
561
  * 4. The two FKs target two DISTINCT tables (A and B).
569
562
  * 5. J has no payload columns beyond the two FK/key columns.
563
+ * 6. Each FK references exactly its target's primary key. The query joins
564
+ * the junction to the target's primary key, so any other referenced
565
+ * column would return rows the junction does not reference. An explicit
566
+ * `manyToMany` declaration is not affected.
570
567
  *
571
568
  * For such a J linking A and B this ADDS a `manyToMany` on A → B and B → A
572
569
  * routed `through` J. It never removes or renames an existing relation:
@@ -609,6 +606,16 @@ function addAutoManyToManyRelations(tableNames, foreignKeys, pkByTable, columnNa
609
606
  const [fkA, fkB] = tableFks;
610
607
  if (fkA.targetTable === fkB.targetTable)
611
608
  continue;
609
+ // Each key references its target's primary key. The many-to-many query
610
+ // joins the junction to the target's PRIMARY KEY, so through a key to
611
+ // another unique column (`tag_code REFERENCES tags (code)`) it returned
612
+ // tags the junction does not reference.
613
+ const referencesPrimaryKey = (fk) => {
614
+ const pk = pkByTable.get(fk.targetTable) ?? [];
615
+ return pk.length === fk.targetColumns.length && pk.every((c, i) => c === fk.targetColumns[i]);
616
+ };
617
+ if (!referencesPrimaryKey(fkA) || !referencesPrimaryKey(fkB))
618
+ continue;
612
619
  // No payload columns: J's columns are exactly the two FK/key columns.
613
620
  const jCols = columnNamesByTable.get(tableName) ?? [];
614
621
  if (jCols.length !== 2)
@@ -662,33 +669,207 @@ function addAutoManyToManyRelations(tableNames, foreignKeys, pkByTable, columnNa
662
669
  addM2M(fkB, fkA); // B → A
663
670
  }
664
671
  }
672
+ /** PostgreSQL's identifier limit, NAMEDATALEN - 1 bytes. */
673
+ const PG_NAME_BYTES = 63;
674
+ const utf8Bytes = (s) => {
675
+ let n = 0;
676
+ for (const ch of s) {
677
+ const code = ch.codePointAt(0);
678
+ n += code < 0x80 ? 1 : code < 0x800 ? 2 : code < 0x10000 ? 3 : 4;
679
+ }
680
+ return n;
681
+ };
682
+ /** The longest prefix of `s` that fits in `bytes` bytes of UTF-8, never ending inside a character. */
683
+ const clipUtf8 = (s, bytes) => {
684
+ let out = '';
685
+ let used = 0;
686
+ for (const ch of s) {
687
+ used += utf8Bytes(ch);
688
+ if (used > bytes)
689
+ break;
690
+ out += ch;
691
+ }
692
+ return out;
693
+ };
694
+ /**
695
+ * An identifier as PostgreSQL stores it: cut to 63 bytes of UTF-8, never
696
+ * inside a character (`truncate_identifier`). Other engines keep longer names
697
+ * (MySQL 64 characters, SQL Server 128), so a name read from their catalogs or
698
+ * DDL is cut the same way before a relation is named from it.
699
+ */
700
+ function postgresIdentifier(name) {
701
+ return clipUtf8(name, PG_NAME_BYTES);
702
+ }
703
+ /**
704
+ * The constraint name PostgreSQL gives a foreign key nobody named:
705
+ * `<table>_<column>[_<column>...]_fkey`, truncated the way PostgreSQL truncates
706
+ * an identifier to 63 bytes (the longer of the two parts first, never inside a
707
+ * character), with a counter after `fkey` while the name is in `taken`.
708
+ *
709
+ * A relation name reads the constraint name in exactly one shape, a COMPOSITE
710
+ * foreign key that shares its target with another foreign key from the same
711
+ * table. Engines disagree about what an unnamed constraint is called (MySQL
712
+ * `orders_ibfk_1`, SQL Server `FK__orders__tenan__1A2B3C4D` with a random
713
+ * suffix, SQLite nothing at all), so an engine introspector names its keys with
714
+ * {@link foreignKeyConstraintNames}, which calls this for each unnamed one, and
715
+ * that shape derives the same relation names as on PostgreSQL.
716
+ */
717
+ function defaultForeignKeyConstraintName(table, columns, taken) {
718
+ // ChooseForeignKeyConstraintNameAddition: columns joined by `_`, stopping
719
+ // once the addition reaches NAMEDATALEN.
720
+ let addition = '';
721
+ for (const column of columns) {
722
+ if (addition.length > 0)
723
+ addition += '_';
724
+ addition += column;
725
+ if (utf8Bytes(addition) >= PG_NAME_BYTES + 1)
726
+ break;
727
+ }
728
+ // makeObjectName + ChooseConstraintName.
729
+ for (let pass = 0;; pass++) {
730
+ const label = pass === 0 ? 'fkey' : `fkey${pass}`;
731
+ let tableBytes = utf8Bytes(table);
732
+ let additionBytes = utf8Bytes(addition);
733
+ const available = PG_NAME_BYTES - (label.length + 2);
734
+ while (tableBytes + additionBytes > available) {
735
+ if (tableBytes > additionBytes)
736
+ tableBytes--;
737
+ else
738
+ additionBytes--;
739
+ }
740
+ const name = `${clipUtf8(table, tableBytes)}_${clipUtf8(addition, additionBytes)}_${label}`;
741
+ if (!taken?.has(name)) {
742
+ taken?.add(name);
743
+ return name;
744
+ }
745
+ }
746
+ }
747
+ /**
748
+ * One table's foreign-key constraint names, as PostgreSQL names the same
749
+ * declarations: an explicit name is the key's own (cut to 63 bytes, see
750
+ * {@link postgresIdentifier}), and each unnamed key, in declaration order, takes
751
+ * {@link defaultForeignKeyConstraintName}, counting up while the name is taken.
752
+ * On PostgreSQL these are catalog facts, so declaring the same two unnamed keys
753
+ * the other way round gives the `1` suffix to the other one; every engine
754
+ * follows the same rule.
755
+ *
756
+ * What a default must avoid: every other constraint the table carries
757
+ * (`reserved`: PRIMARY KEY, UNIQUE, CHECK and NOT NULL, which PostgreSQL creates
758
+ * before any foreign key, but not a plain index, which it does not consult), and
759
+ * every explicit foreign-key name. All of them are reserved before any default
760
+ * is chosen. PostgreSQL itself names foreign keys one at a time and refuses a
761
+ * statement whose explicit name an earlier unnamed key already took, so for
762
+ * every statement PostgreSQL accepts, reserving first gives its answer; for one
763
+ * it refuses, the explicit key still keeps its name.
764
+ *
765
+ * `taken` holds the foreign-key names of the tables named so far: one set for
766
+ * the whole schema, because PostgreSQL checks a default against every
767
+ * constraint name in it, and it gives the counter to the table created second
768
+ * where two tables' names coincide (the catalog readers name tables in name
769
+ * order, `schemaDefToMetadata` in declaration order). The table's other
770
+ * constraint names are this table's alone and never enter `taken`: on
771
+ * PostgreSQL another table's CHECK counts only if that table was created
772
+ * first, which no other catalog records, and a set shared in name order let a
773
+ * table created later move an earlier table's names. This table's foreign-key
774
+ * names, explicit and chosen, are added to `taken`.
775
+ *
776
+ * @param keys the table's foreign keys in declaration order, `name` undefined
777
+ * for an unnamed one
778
+ * @param reserved the table's other constraint names
779
+ */
780
+ function foreignKeyConstraintNames(table, keys, taken, reserved = []) {
781
+ const names = keys.map((key) => (key.name === undefined ? undefined : postgresIdentifier(key.name)));
782
+ for (const name of names)
783
+ if (name !== undefined)
784
+ taken.add(name);
785
+ const own = new Set(Array.from(reserved, postgresIdentifier));
786
+ const avoid = { has: (name) => taken.has(name) || own.has(name), add: (name) => taken.add(name) };
787
+ return keys.map((key, i) => names[i] ?? defaultForeignKeyConstraintName(table, key.columns, avoid));
788
+ }
789
+ /**
790
+ * A catalog's ON DELETE / ON UPDATE rule (`CASCADE`, `SET NULL`, SQL Server's
791
+ * `NO_ACTION`, ...) as a {@link ReferentialAction}. Anything else is
792
+ * `no action`, the SQL default.
793
+ */
794
+ function referentialActionFromCatalog(rule) {
795
+ const action = typeof rule === 'string' ? rule.trim().toLowerCase().replace(/_/g, ' ') : '';
796
+ return action === 'cascade' || action === 'restrict' || action === 'set null' || action === 'set default'
797
+ ? action
798
+ : 'no action';
799
+ }
800
+ /**
801
+ * PostgreSQL's order for `name`, which compares bytes: for UTF-8 that is code
802
+ * point order. JavaScript's `<` compares UTF-16 code units instead, which puts a
803
+ * character above U+FFFF (a surrogate pair) BEFORE one in U+E000..U+FFFF, so two
804
+ * differing units at or above U+D800 are compared as the code points they
805
+ * encode.
806
+ */
807
+ function compareCatalogNames(a, b) {
808
+ const length = Math.min(a.length, b.length);
809
+ for (let i = 0; i < length; i++) {
810
+ let x = a.charCodeAt(i);
811
+ let y = b.charCodeAt(i);
812
+ if (x === y)
813
+ continue;
814
+ if (x >= 0xd800 && y >= 0xd800) {
815
+ // Surrogates (U+D800..U+DFFF) move above U+E000..U+FFFF.
816
+ x += x >= 0xe000 ? -0x800 : 0x2000;
817
+ y += y >= 0xe000 ? -0x800 : 0x2000;
818
+ }
819
+ return x - y;
820
+ }
821
+ return a.length - b.length;
822
+ }
665
823
  /**
666
- * One-stop relation derivation for the engine introspectors (SQLite / MySQL /
667
- * MSSQL): filters the FK list to the introspected table set, seeds the
668
- * taken-name / json-shadow maps from the engine's column metadata, and runs
669
- * the SAME `buildRelationsFromForeignKeys` + `addAutoManyToManyRelations`
670
- * pipeline as the Postgres introspector, so every engine derives identical
671
- * relation names for the same logical schema (the engines previously carried
672
- * stale copies of a retired naming scheme).
824
+ * THE relation derivation. Every surface that turns a schema into relations
825
+ * calls it with its own catalog facts: the PostgreSQL introspector and the MCP
826
+ * server (via `deriveCatalogRelations`), the SQLite, MySQL, SQL Server, libSQL
827
+ * and D1 introspectors, and `schemaDefToMetadata` for a `defineSchema` schema.
828
+ * The same schema therefore derives the same relations on every engine:
829
+ * `src/test/relation-derivation-parity.test.ts` creates one schema natively on
830
+ * each and holds them all to PostgreSQL's answer.
673
831
  *
674
- * `isToOne` decides, per foreign key, whether the reverse relation is a to-one.
675
- * It must be decided HERE, before naming, and not by flipping the type of a
676
- * relation already named: a to-one is named with the singular of the child
677
- * table (`users.profile`), as PostgreSQL names it, and a flip afterwards kept
678
- * the to-many's plural (`users.profiles`). Omit it (the `legacyToManyUniques`
679
- * opt-out does) to keep every reverse relation `hasMany`.
832
+ * Two things live here rather than in each caller, because each is where the
833
+ * engines used to drift:
834
+ *
835
+ * - CARDINALITY IS DECIDED BEFORE NAMING, one foreign key at a time. A to-one
836
+ * reverse relation is named with the singular of its table
837
+ * (`users.profile`), so the engines that flipped `hasMany` to `hasOne` after
838
+ * naming kept the plural (`profiles`) and accepted a different `with` key
839
+ * than PostgreSQL for the same schema. Each engine states what a unique key
840
+ * is and how its columns compare
841
+ * ({@link RelationCatalogFacts.uniqueKeysByTable},
842
+ * {@link RelationCatalogFacts.sameKeyComparison}) and the decision is made
843
+ * once, here.
844
+ * - FOREIGN KEYS ARE TAKEN IN ONE ORDER, source table then constraint name.
845
+ * The first foreign key to claim a contested name keeps it, and the
846
+ * catalogs return them in different orders (PostgreSQL by table and
847
+ * constraint, MySQL by constraint name, SQLite by PRAGMA id).
680
848
  */
681
- function deriveEngineRelations(tableNames, foreignKeys, pkByTable, columnsByTable, logger = logger_js_1.consoleLogger, isToOne) {
682
- const tableSet = new Set(tableNames);
683
- const fks = foreignKeys.filter((fk) => tableSet.has(fk.sourceTable) && tableSet.has(fk.targetTable));
849
+ function deriveRelations(facts) {
850
+ const tableSet = new Set(facts.tableNames);
851
+ const foreignKeys = facts.foreignKeys.filter((fk) => tableSet.has(fk.sourceTable) && tableSet.has(fk.targetTable));
852
+ if (!facts.inCatalogOrder) {
853
+ foreignKeys.sort((a, b) => compareCatalogNames(a.sourceTable, b.sourceTable) || compareCatalogNames(a.constraintName, b.constraintName));
854
+ }
855
+ const enums = facts.enums ?? {};
684
856
  const columnFieldsByTable = new Map();
685
857
  const unknownTypedFieldsByTable = new Map();
686
- for (const [tbl, cols] of columnsByTable) {
858
+ for (const [tbl, cols] of facts.columnsByTable) {
687
859
  columnFieldsByTable.set(tbl, new Set(cols.map((c) => c.field)));
688
- unknownTypedFieldsByTable.set(tbl, new Set(cols.filter((c) => isUnknownTsType(c.tsType)).map((c) => c.field)));
860
+ // Enum-typed columns also report tsType 'unknown' here, but generate.ts
861
+ // gives them a concrete union type, so a shadow of one is type-broken and
862
+ // must NOT be preserved as a historical json/jsonb shadow.
863
+ unknownTypedFieldsByTable.set(tbl, new Set(cols.filter((c) => isUnknownTsType(c.tsType) && !Object.hasOwn(enums, c.pgType)).map((c) => c.field)));
689
864
  }
690
- const relationsByTable = buildRelationsFromForeignKeys(fks, columnFieldsByTable, undefined, unknownTypedFieldsByTable, isToOne, logger);
691
- addAutoManyToManyRelations(tableNames, fks, pkByTable, new Map(Array.from(columnsByTable, ([tbl, cols]) => [tbl, cols.map((c) => c.name)])), relationsByTable, columnFieldsByTable, unknownTypedFieldsByTable, undefined, logger);
865
+ const { uniqueKeysByTable, sameKeyComparison } = facts;
866
+ const isToOne = facts.legacyToManyUniques
867
+ ? undefined
868
+ : (fk) => (uniqueKeysByTable?.get(fk.sourceTable) ?? []).some((key) => columnSetsEqual(key, fk.sourceColumns)) &&
869
+ (sameKeyComparison === undefined || sameKeyComparison(fk));
870
+ const logger = facts.logger ?? logger_js_1.consoleLogger;
871
+ const relationsByTable = buildRelationsFromForeignKeys(foreignKeys, columnFieldsByTable, facts.fkActions, unknownTypedFieldsByTable, isToOne, logger);
872
+ 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);
692
873
  return relationsByTable;
693
874
  }
694
875
  /** SQLite's declared-type affinity rules, in their required precedence order. */
@@ -708,25 +889,25 @@ function sqliteComparisonAffinity(declared, strict) {
708
889
  return 'numeric';
709
890
  }
710
891
  /**
711
- * The SQLite to-one test, one foreign key at a time, shared by every SQLite
712
- * introspector (node:sqlite, better-sqlite3, libSQL, D1) so they cannot
713
- * disagree. The child's columns must be exactly a unique key that compares the
714
- * way the join does:
892
+ * SQLite's {@link RelationCatalogFacts.sameKeyComparison}, shared by every
893
+ * SQLite introspector (node:sqlite, better-sqlite3, libSQL, D1) so they cannot
894
+ * disagree. A child's unique key proves a to-one only when the foreign key
895
+ * compares the way the join does:
715
896
  *
716
897
  * - The same comparison affinity on both sides. A TEXT unique FK can store both
717
898
  * '1' and '01', and both match the INTEGER parent 1 after affinity is applied,
718
899
  * so index uniqueness alone cannot justify a to-one.
719
900
  * - No collation that could make two distinct child values match one parent.
720
901
  * Column collations are absent from the catalog, so the test reads the DDL
721
- * and refuses on any `COLLATE` it finds. `relationUniqueByTable` already
722
- * leaves out every child key of a table or index that mentions one. On the
723
- * parent side a key that is the rowid alias needs no such check: it holds
724
- * only integers, which compare as numbers whatever the collation. Any other
725
- * parent key is refused when the parent's DDL mentions `COLLATE`, because a
726
- * `NOCASE` parent key lets the child values 'a' and 'A' both reference the
727
- * parent 'a'.
902
+ * and refuses on any `COLLATE` it finds. The child's unique keys (the
903
+ * introspector's `uniqueKeysByTable`) already leave out every key of a table
904
+ * or index that mentions one. On the parent side a key that is the rowid
905
+ * alias needs no such check: it holds only integers, which compare as numbers
906
+ * whatever the collation. Any other parent key is refused when the parent's
907
+ * DDL mentions `COLLATE`, because a `NOCASE` parent key lets the child values
908
+ * 'a' and 'A' both reference the parent 'a'.
728
909
  */
729
- function sqliteToOneForeignKey(columnsByTable, relationUniqueByTable, tableDefinitions, tableFlags) {
910
+ function sqliteKeyComparison(columnsByTable, tableDefinitions, tableFlags) {
730
911
  return (fk) => {
731
912
  const child = columnsByTable.get(fk.sourceTable);
732
913
  const parent = columnsByTable.get(fk.targetTable);
@@ -741,7 +922,6 @@ function sqliteToOneForeignKey(columnsByTable, relationUniqueByTable, tableDefin
741
922
  to !== undefined &&
742
923
  sqliteComparisonAffinity(from.pgType, tableFlags.get(fk.sourceTable)?.strict === 1) ===
743
924
  sqliteComparisonAffinity(to.pgType, tableFlags.get(fk.targetTable)?.strict === 1));
744
- }) &&
745
- (relationUniqueByTable.get(fk.sourceTable) ?? []).some((key) => columnSetsEqual(key, fk.sourceColumns)));
925
+ }));
746
926
  };
747
927
  }