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.
@@ -15,10 +15,11 @@
15
15
  * names, constraint names, view flags).
16
16
  *
17
17
  * Parity notes (ground truth = introspect.ts + generate.ts):
18
- * - Relations are derived from `references:` exactly like introspection
19
- * derives them from foreign keys: a `belongsTo` on the child table and
20
- * a `hasMany` on the parent, with the same disambiguation rules when
21
- * multiple FKs point at the same target.
18
+ * - Relations are derived from `references:` by the same derivation every
19
+ * introspector calls: a `belongsTo` on the child table and a `hasMany` on
20
+ * the parent (a singular-named `hasOne` when the column is unique, the
21
+ * primary key, or a declared unique index), with the same disambiguation
22
+ * rules when multiple FKs point at the same target.
22
23
  * - Pure junction tables (2-column composite PK that IS the two
23
24
  * single-column FKs to two distinct tables, no payload columns) get
24
25
  * the same conservative auto-`manyToMany` treatment as introspection.
@@ -16,10 +16,11 @@
16
16
  * names, constraint names, view flags).
17
17
  *
18
18
  * Parity notes (ground truth = introspect.ts + generate.ts):
19
- * - Relations are derived from `references:` exactly like introspection
20
- * derives them from foreign keys: a `belongsTo` on the child table and
21
- * a `hasMany` on the parent, with the same disambiguation rules when
22
- * multiple FKs point at the same target.
19
+ * - Relations are derived from `references:` by the same derivation every
20
+ * introspector calls: a `belongsTo` on the child table and a `hasMany` on
21
+ * the parent (a singular-named `hasOne` when the column is unique, the
22
+ * primary key, or a declared unique index), with the same disambiguation
23
+ * rules when multiple FKs point at the same target.
23
24
  * - Pure junction tables (2-column composite PK that IS the two
24
25
  * single-column FKs to two distinct tables, no payload columns) get
25
26
  * the same conservative auto-`manyToMany` treatment as introspection.
@@ -266,8 +267,8 @@ function schemaDefToMetadata(def, options = {}) {
266
267
  }
267
268
  // ----- Pass 3: derive belongsTo / hasMany / hasOne relations (SHARED with introspect)
268
269
  //
269
- // Delegates to the exact same builder introspection uses
270
- // (`buildRelationsFromForeignKeys`), so the same logical schema yields
270
+ // Delegates to the exact same derivation introspection uses
271
+ // (`deriveRelations`, Pass 4), so the same logical schema yields
271
272
  // IDENTICAL relation names whether it arrives via `defineSchema()` or a live
272
273
  // catalog: legacy-first naming, per-column disambiguation for several FKs to
273
274
  // the same target, and collision resolution against scalar column fields
@@ -277,78 +278,93 @@ function schemaDefToMetadata(def, options = {}) {
277
278
  // scalar, and two FKs deriving the same name silently clobbered each other
278
279
  //.
279
280
  //
280
- // Constraint names are synthesized in pg's default `<table>_<column>_fkey`
281
- // form; they only feed the referential-action lookup and composite-FK
282
- // naming (never hit here, `references:` is single-column by design).
281
+ // Constraint names follow PostgreSQL's rule for the unnamed keys
282
+ // `schemaToSQL` emits; they only order the derivation (and name a composite
283
+ // FK, never declared here: `references:` is single-column by design). The
284
+ // actions travel on each key, because two tables can produce one name
285
+ // (`box_items.item_id` and `box.items_item_id`).
283
286
  const fkEntries = [];
284
- const fkActions = new Map();
287
+ const constraintNames = new Set();
285
288
  for (const fk of foreignKeys) {
286
- const constraintName = `${fk.sourceTable}_${fk.sourceColumn}_fkey`;
287
289
  fkEntries.push({
288
290
  sourceTable: fk.sourceTable,
289
291
  sourceColumns: [fk.sourceColumn],
290
292
  targetTable: fk.targetTable,
291
293
  targetColumns: [fk.targetColumn],
292
- constraintName,
293
- });
294
- fkActions.set(constraintName, {
295
- onDelete: fk.onDelete ?? 'no action',
296
- onUpdate: fk.onUpdate ?? 'no action',
294
+ constraintName: (0, introspect_js_1.defaultForeignKeyConstraintName)(fk.sourceTable, [fk.sourceColumn], constraintNames),
295
+ actions: { onDelete: fk.onDelete ?? 'no action', onUpdate: fk.onUpdate ?? 'no action' },
297
296
  });
298
297
  }
299
298
  // Taken-name seeds: every table's camelCase column fields (the SchemaDef
300
- // keys ARE the fields) + which of them are json/jsonb (`unknown`-typed).
301
- const columnFieldsByTable = new Map();
302
- const unknownTypedFieldsByTable = new Map();
303
- for (const tableDef of Object.values(def.tables)) {
304
- const fields = Object.keys(tableDef.columns);
305
- columnFieldsByTable.set(tableDef.name, new Set(fields));
306
- // ENUM columns map to concrete union types in the generated layer, so
307
- // only genuine json/jsonb (`unknown`-typed) columns qualify as shadows.
308
- unknownTypedFieldsByTable.set(tableDef.name, new Set(fields.filter((f) => {
309
- const config = tableDef.columns[f];
310
- if (config.type === 'ENUM')
311
- return false;
312
- const wire = config.isArray ? `_${udtName(config)}` : udtName(config);
313
- return (0, introspect_js_1.isUnknownTsType)((0, schema_js_1.pgTypeToTs)(wire, false));
314
- })));
315
- }
316
- // The column sets that hold at most one row per value, the same sets
317
- // PostgreSQL introspection reads from the pushed schema's catalog: the
318
- // primary key, every `unique: true` column and every declared unique index.
319
- // A foreign key over exactly one of them has a to-one reverse relation.
320
- const uniqueSetsByTable = new Map();
321
- for (const tableDef of Object.values(def.tables)) {
322
- const sets = [];
323
- if (tableDef.primaryKey && tableDef.primaryKey.length > 0)
324
- sets.push(tableDef.primaryKey.map(schema_js_1.camelToSnake));
325
- for (const [field, config] of Object.entries(tableDef.columns)) {
326
- if (config.isPrimaryKey || config.isUnique)
327
- sets.push([(0, schema_js_1.camelToSnake)(field)]);
328
- }
329
- for (const idx of tableDef.indexes ?? []) {
330
- if (idx.unique && !(0, schema_builder_js_1.isDocFieldIndexDef)(idx))
331
- sets.push(idx.columns.map(schema_js_1.camelToSnake));
332
- }
333
- uniqueSetsByTable.set(tableDef.name, sets);
334
- }
335
- const relationsByTable = (0, introspect_js_1.buildRelationsFromForeignKeys)(fkEntries, columnFieldsByTable, fkActions, unknownTypedFieldsByTable, options.legacyToManyUniques ? undefined : uniqueSetsByTable);
336
- // ----- Pass 4: conservative junction auto-m2m (SHARED with introspect) ---
337
- // Same shared detector + naming/collision rules as introspection: a table J
338
- // is a PURE junction only when its PK is exactly the two single-column FKs
339
- // to two DISTINCT tables and it has no payload columns.
299
+ // keys ARE the fields) with the type each maps to, so a json/jsonb
300
+ // (`unknown`-typed) column can be told apart. ENUM columns map to concrete
301
+ // union types in the generated layer, so their types are passed as enums and
302
+ // are never json shadows.
303
+ const columnsByTable = new Map();
304
+ const enumTypes = { ...def.enums };
340
305
  const pkByTable = new Map();
341
- const columnNamesByTable = new Map();
306
+ // Every column set that holds at most one row, the facts introspection reads
307
+ // from the database this schema creates: the primary key, each `unique`
308
+ // column and each declared unique index.
309
+ const uniqueKeysByTable = new Map();
310
+ const junctionKeysByTable = new Map();
342
311
  for (const tableDef of Object.values(def.tables)) {
312
+ columnsByTable.set(tableDef.name, Object.entries(tableDef.columns).map(([field, config]) => {
313
+ const wire = config.isArray ? `_${udtName(config)}` : udtName(config);
314
+ if (config.type === 'ENUM')
315
+ enumTypes[wire] ??= [];
316
+ return { name: (0, schema_js_1.camelToSnake)(field), field, tsType: (0, schema_js_1.pgTypeToTs)(wire, false), pgType: wire };
317
+ }));
343
318
  const pkFields = tableDef.primaryKey && tableDef.primaryKey.length > 0
344
319
  ? [...tableDef.primaryKey]
345
320
  : Object.entries(tableDef.columns)
346
321
  .filter(([, c]) => c.isPrimaryKey)
347
322
  .map(([f]) => f);
348
- pkByTable.set(tableDef.name, pkFields.map(schema_js_1.camelToSnake));
349
- columnNamesByTable.set(tableDef.name, Object.keys(tableDef.columns).map(schema_js_1.camelToSnake));
323
+ const pk = pkFields.map(schema_js_1.camelToSnake);
324
+ pkByTable.set(tableDef.name, pk);
325
+ const uniqueIndexes = (tableDef.indexes ?? [])
326
+ .filter((idx) => !(0, schema_builder_js_1.isDocFieldIndexDef)(idx) && idx.unique)
327
+ .map((idx) => idx.columns.map(schema_js_1.camelToSnake));
328
+ uniqueKeysByTable.set(tableDef.name, [
329
+ pk,
330
+ ...Object.entries(tableDef.columns)
331
+ .filter(([, c]) => c.isUnique)
332
+ .map(([f]) => [(0, schema_js_1.camelToSnake)(f)]),
333
+ ...uniqueIndexes,
334
+ ]);
335
+ junctionKeysByTable.set(tableDef.name, uniqueIndexes.filter((key) => key.length === 2));
336
+ }
337
+ // ----- Pass 4: the ONE relation derivation every engine's introspector
338
+ // also calls, so this schema derives the relations introspection derives
339
+ // from the database it creates: legacy-first naming, per-column
340
+ // disambiguation, collision resolution against scalar column fields, a
341
+ // unique foreign key's to-one reverse relation, and the conservative
342
+ // pure-junction manyToMany.
343
+ const facts = {
344
+ tableNames: Object.values(def.tables).map((t) => t.name),
345
+ foreignKeys: fkEntries,
346
+ pkByTable,
347
+ columnsByTable,
348
+ enums: enumTypes,
349
+ uniqueKeysByTable,
350
+ junctionKeysByTable,
351
+ ...(options.legacyToManyUniques ? { legacyToManyUniques: true } : {}),
352
+ };
353
+ const relationsByTable = (0, introspect_js_1.deriveRelations)(facts);
354
+ // The names above are the sorted derivation's, so they match introspection.
355
+ // The ORDER each table lists them in stays declaration order, as it was
356
+ // before the derivation was shared, so a schema whose relation names did not
357
+ // change keeps generating the same files. A second, silent derivation that
358
+ // takes the declarations as given supplies that order; a name it does not
359
+ // produce (one a contested name moved) follows in the sorted order.
360
+ const declared = (0, introspect_js_1.deriveRelations)({ ...facts, inCatalogOrder: true, logger: {} });
361
+ for (const [table, relations] of relationsByTable) {
362
+ const order = Object.keys(declared.get(table) ?? {}).filter((name) => Object.hasOwn(relations, name));
363
+ for (const name of Object.keys(relations))
364
+ if (!order.includes(name))
365
+ order.push(name);
366
+ relationsByTable.set(table, Object.fromEntries(order.map((name) => [name, relations[name]])));
350
367
  }
351
- (0, introspect_js_1.addAutoManyToManyRelations)(Object.values(def.tables).map((t) => t.name), fkEntries, pkByTable, columnNamesByTable, relationsByTable, columnFieldsByTable, unknownTypedFieldsByTable);
352
368
  // ----- Pass 5: assemble TableMetadata -----
353
369
  const tables = {};
354
370
  for (const tableDef of Object.values(def.tables)) {
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Foreign-key constraint names, and the spelling of foreign-key identifiers,
3
+ * for SQLite tables.
4
+ *
5
+ * SQLite keeps no constraint name in its catalog (`PRAGMA foreign_key_list` has
6
+ * no name column), only in the statement text `sqlite_master.sql` stores. A
7
+ * relation name reads the constraint name in one shape, a composite foreign key
8
+ * that shares its target with another, so without this a SQLite schema derived
9
+ * different names than the same schema on PostgreSQL and MySQL. The SQLite,
10
+ * libSQL and D1 introspectors share it.
11
+ *
12
+ * Deliberately a reader of the one clause it needs, not a SQL parser. A key it
13
+ * cannot read is named as an unnamed key, with the name PostgreSQL would have
14
+ * given it.
15
+ */
16
+ import { type ForeignKeyEntry } from './catalog-metadata.js';
17
+ /** One foreign key a `CREATE TABLE` statement declares, table- or column-level. */
18
+ export interface DeclaredForeignKey {
19
+ /** The `CONSTRAINT` name, absent for an unnamed key. */
20
+ name?: string;
21
+ columns: string[];
22
+ table: string;
23
+ /** The referenced columns, empty when the clause names none (the target's primary key). */
24
+ references: string[];
25
+ }
26
+ /** Every foreign key a `CREATE TABLE` statement declares, in statement order. */
27
+ export declare function declaredForeignKeys(createTable: string): DeclaredForeignKey[];
28
+ /**
29
+ * Names every foreign key of one SQLite table as PostgreSQL names the same
30
+ * declarations, setting each key's `constraintName`: its declared `CONSTRAINT`
31
+ * name, else (see {@link foreignKeyConstraintNames}) PostgreSQL's default in
32
+ * declaration order, with every constraint name the statement declares
33
+ * reserved first.
34
+ *
35
+ * A key is matched to its declaration by its whole identity, child columns,
36
+ * target table and referenced columns, compared as SQLite compares
37
+ * identifiers. Keys that are identical in all three are matched in declaration
38
+ * order. When the statement holds a different number of declarations of one
39
+ * identity than the catalog holds keys (a clause this reader cannot read), no
40
+ * key of that identity takes a declared name.
41
+ *
42
+ * @param keys the table's foreign keys in `PRAGMA foreign_key_list` id order,
43
+ * with `targetColumns` still empty where the clause names none. SQLite
44
+ * numbers the LAST declared key 0, so reversed they are in declaration order.
45
+ * @param taken constraint names already taken in the schema, see
46
+ * {@link foreignKeyConstraintNames}
47
+ */
48
+ export declare function nameSqliteForeignKeys(table: string, createTable: string, keys: readonly ForeignKeyEntry[], taken: Set<string>): void;
49
+ /** `name` as `names` spell it, compared as SQLite compares identifiers; undefined when none matches. */
50
+ export declare const sqliteCatalogName: (names: readonly string[], name: string) => string | undefined;
51
+ /**
52
+ * Rewrites every key's child and referenced columns to the spelling their
53
+ * table's catalog gives them, and returns the keys that name a column a known
54
+ * table does not have. `PRAGMA foreign_key_list` keeps the spelling the
55
+ * REFERENCES clause used (`REFERENCES posts (ID)` for the column `id`), and
56
+ * SQLite compares identifiers ignoring ASCII case, so without this a junction
57
+ * key to the primary key did not read as one, nor a unique key's parent column
58
+ * as that column. Each introspector also looks a key's target table up with
59
+ * {@link sqliteCatalogName}.
60
+ *
61
+ * @param columnsOf a table's columns, undefined for a table that was not read
62
+ */
63
+ export declare function canonicalSqliteForeignKeyColumns(keys: readonly ForeignKeyEntry[], columnsOf: (table: string) => readonly {
64
+ name: string;
65
+ }[] | undefined): ForeignKeyEntry[];
@@ -0,0 +1,264 @@
1
+ "use strict";
2
+ /**
3
+ * Foreign-key constraint names, and the spelling of foreign-key identifiers,
4
+ * for SQLite tables.
5
+ *
6
+ * SQLite keeps no constraint name in its catalog (`PRAGMA foreign_key_list` has
7
+ * no name column), only in the statement text `sqlite_master.sql` stores. A
8
+ * relation name reads the constraint name in one shape, a composite foreign key
9
+ * that shares its target with another, so without this a SQLite schema derived
10
+ * different names than the same schema on PostgreSQL and MySQL. The SQLite,
11
+ * libSQL and D1 introspectors share it.
12
+ *
13
+ * Deliberately a reader of the one clause it needs, not a SQL parser. A key it
14
+ * cannot read is named as an unnamed key, with the name PostgreSQL would have
15
+ * given it.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.sqliteCatalogName = void 0;
19
+ exports.declaredForeignKeys = declaredForeignKeys;
20
+ exports.nameSqliteForeignKeys = nameSqliteForeignKeys;
21
+ exports.canonicalSqliteForeignKeyColumns = canonicalSqliteForeignKeyColumns;
22
+ const catalog_metadata_js_1 = require("./catalog-metadata.js");
23
+ function tokenize(sql) {
24
+ const out = [];
25
+ let i = 0;
26
+ while (i < sql.length) {
27
+ const c = sql[i];
28
+ if (/\s/.test(c)) {
29
+ i++;
30
+ }
31
+ else if (c === '-' && sql[i + 1] === '-') {
32
+ const end = sql.indexOf('\n', i);
33
+ i = end === -1 ? sql.length : end + 1;
34
+ }
35
+ else if (c === '/' && sql[i + 1] === '*') {
36
+ const end = sql.indexOf('*/', i + 2);
37
+ i = end === -1 ? sql.length : end + 2;
38
+ }
39
+ else if (c === "'" || c === '"' || c === '`' || c === '[') {
40
+ // A doubled closing quote is an escaped one, except inside [ ].
41
+ const close = c === '[' ? ']' : c;
42
+ let j = i + 1;
43
+ let value = '';
44
+ while (j < sql.length) {
45
+ if (sql[j] === close) {
46
+ if (close !== ']' && sql[j + 1] === close) {
47
+ value += close;
48
+ j += 2;
49
+ continue;
50
+ }
51
+ break;
52
+ }
53
+ value += sql[j];
54
+ j++;
55
+ }
56
+ // SQLite reads a single-quoted string as an identifier where one is expected.
57
+ out.push({ kind: c === "'" ? 'string' : 'ident', value });
58
+ i = j + 1;
59
+ }
60
+ else if (/[A-Za-z_\u0080-￿]/.test(c)) {
61
+ let j = i + 1;
62
+ while (j < sql.length && /[A-Za-z0-9_$\u0080-￿]/.test(sql[j]))
63
+ j++;
64
+ out.push({ kind: 'word', value: sql.slice(i, j) });
65
+ i = j;
66
+ }
67
+ else {
68
+ out.push({ kind: c === '(' || c === ')' || c === ',' ? 'punct' : 'other', value: c });
69
+ i++;
70
+ }
71
+ }
72
+ return out;
73
+ }
74
+ /** ASCII case folding, the only folding SQLite applies to identifiers and PostgreSQL to a bare word in UTF-8. */
75
+ const fold = (s) => s.replace(/[A-Z]/g, (c) => c.toLowerCase());
76
+ const keyword = (t) => (t?.kind === 'word' ? t.value.toUpperCase() : undefined);
77
+ /**
78
+ * An identifier as PostgreSQL would store it: a bare word folds to lower case,
79
+ * a quoted one keeps its case.
80
+ */
81
+ const identifier = (t) => t?.kind === 'word' ? fold(t.value) : t?.kind === 'ident' || t?.kind === 'string' ? t.value : undefined;
82
+ const punct = (t, value) => t?.kind === 'punct' && t.value === value;
83
+ /** The parenthesized identifier list at `def[at]`, and the index after it. Undefined when there is none. */
84
+ function identifierList(def, at) {
85
+ if (!punct(def[at], '('))
86
+ return undefined;
87
+ const names = [];
88
+ for (let k = at + 1; k < def.length; k += 2) {
89
+ const name = identifier(def[k]);
90
+ if (name === undefined)
91
+ return undefined;
92
+ names.push(name);
93
+ if (punct(def[k + 1], ')'))
94
+ return [names, k + 2];
95
+ if (!punct(def[k + 1], ','))
96
+ return undefined;
97
+ }
98
+ return undefined;
99
+ }
100
+ const TABLE_CONSTRAINTS = new Set(['CONSTRAINT', 'PRIMARY', 'UNIQUE', 'CHECK', 'FOREIGN']);
101
+ /**
102
+ * The column constraints a `CONSTRAINT <name>` names in PostgreSQL's catalog.
103
+ * A name on DEFAULT, COLLATE or GENERATED creates no constraint there.
104
+ */
105
+ const NAMED_COLUMN_CONSTRAINTS = new Set(['PRIMARY', 'UNIQUE', 'CHECK', 'REFERENCES', 'NOT']);
106
+ /** Every foreign key a `CREATE TABLE` statement declares, in statement order. */
107
+ function declaredForeignKeys(createTable) {
108
+ return readCreateTable(createTable).foreignKeys;
109
+ }
110
+ /**
111
+ * The statement's foreign keys, and the names of every constraint it names
112
+ * (PRIMARY KEY, UNIQUE, CHECK, NOT NULL and foreign keys, table- or
113
+ * column-level): PostgreSQL creates all of them before it names an unnamed
114
+ * foreign key, so a default must avoid them.
115
+ */
116
+ function readCreateTable(createTable) {
117
+ const tokens = tokenize(createTable);
118
+ const open = tokens.findIndex((t) => punct(t, '('));
119
+ if (open === -1)
120
+ return { foreignKeys: [], constraintNames: [] };
121
+ // Split the body into its comma-separated definitions, marking the tokens
122
+ // inside a definition's own parentheses (a type's, a CHECK's, a column list).
123
+ const definitions = [];
124
+ let current = [];
125
+ let depth = 0;
126
+ for (let k = open + 1; k < tokens.length; k++) {
127
+ const t = tokens[k];
128
+ if (punct(t, '('))
129
+ depth++;
130
+ else if (punct(t, ')')) {
131
+ if (depth === 0) {
132
+ definitions.push(current);
133
+ break;
134
+ }
135
+ depth--;
136
+ }
137
+ else if (punct(t, ',') && depth === 0) {
138
+ definitions.push(current);
139
+ current = [];
140
+ continue;
141
+ }
142
+ current.push(depth > 0 ? { ...t, nested: true } : t);
143
+ }
144
+ const found = [];
145
+ const constraintNames = [];
146
+ // REFERENCES <table> [(<columns>)] at `def[at]`.
147
+ const reference = (def, at, columns, name) => {
148
+ const table = keyword(def[at]) === 'REFERENCES' ? identifier(def[at + 1]) : undefined;
149
+ if (table === undefined)
150
+ return;
151
+ const references = punct(def[at + 2], '(') ? identifierList(def, at + 2)?.[0] : [];
152
+ if (references !== undefined)
153
+ found.push({ ...(name === undefined ? {} : { name }), columns, table, references });
154
+ };
155
+ for (const def of definitions) {
156
+ const first = keyword(def[0]);
157
+ if (first !== undefined && TABLE_CONSTRAINTS.has(first)) {
158
+ const name = first === 'CONSTRAINT' ? identifier(def[1]) : undefined;
159
+ if (name !== undefined && TABLE_CONSTRAINTS.has(keyword(def[2]) ?? ''))
160
+ constraintNames.push(name);
161
+ // [CONSTRAINT <name>] FOREIGN KEY (<columns>) REFERENCES <table> [(<columns>)]
162
+ const at = first === 'CONSTRAINT' ? 2 : 0;
163
+ if (keyword(def[at]) !== 'FOREIGN' || keyword(def[at + 1]) !== 'KEY')
164
+ continue;
165
+ const list = identifierList(def, at + 2);
166
+ if (list)
167
+ reference(def, list[1], list[0], at === 2 ? identifier(def[1]) : undefined);
168
+ continue;
169
+ }
170
+ // <column> <type> ... [CONSTRAINT <name>] REFERENCES <table> [(<column>)], any number of times
171
+ const column = identifier(def[0]);
172
+ if (column === undefined)
173
+ continue;
174
+ const top = def.flatMap((t, k) => (t.nested ? [] : [k]));
175
+ for (let k = 1; k < top.length; k++) {
176
+ // CONSTRAINT <name> NOT NULL / UNIQUE / CHECK / PRIMARY KEY / REFERENCES
177
+ if (keyword(def[top[k]]) === 'CONSTRAINT') {
178
+ const name = identifier(def[top[k + 1]]);
179
+ if (name !== undefined && NAMED_COLUMN_CONSTRAINTS.has(keyword(def[top[k + 2]]) ?? ''))
180
+ constraintNames.push(name);
181
+ }
182
+ if (keyword(def[top[k]]) !== 'REFERENCES')
183
+ continue;
184
+ const named = k >= 3 && keyword(def[top[k - 2]]) === 'CONSTRAINT';
185
+ reference(def, top[k], [column], named ? identifier(def[top[k - 1]]) : undefined);
186
+ }
187
+ }
188
+ return { foreignKeys: found, constraintNames };
189
+ }
190
+ /**
191
+ * Names every foreign key of one SQLite table as PostgreSQL names the same
192
+ * declarations, setting each key's `constraintName`: its declared `CONSTRAINT`
193
+ * name, else (see {@link foreignKeyConstraintNames}) PostgreSQL's default in
194
+ * declaration order, with every constraint name the statement declares
195
+ * reserved first.
196
+ *
197
+ * A key is matched to its declaration by its whole identity, child columns,
198
+ * target table and referenced columns, compared as SQLite compares
199
+ * identifiers. Keys that are identical in all three are matched in declaration
200
+ * order. When the statement holds a different number of declarations of one
201
+ * identity than the catalog holds keys (a clause this reader cannot read), no
202
+ * key of that identity takes a declared name.
203
+ *
204
+ * @param keys the table's foreign keys in `PRAGMA foreign_key_list` id order,
205
+ * with `targetColumns` still empty where the clause names none. SQLite
206
+ * numbers the LAST declared key 0, so reversed they are in declaration order.
207
+ * @param taken constraint names already taken in the schema, see
208
+ * {@link foreignKeyConstraintNames}
209
+ */
210
+ function nameSqliteForeignKeys(table, createTable, keys, taken) {
211
+ const identity = (columns, target, references) => fold(JSON.stringify([columns, target, references]));
212
+ const declared = new Map();
213
+ const statement = readCreateTable(createTable);
214
+ for (const d of statement.foreignKeys) {
215
+ const id = identity(d.columns, d.table, d.references);
216
+ declared.set(id, [...(declared.get(id) ?? []), d.name]);
217
+ }
218
+ const ordered = [...keys].reverse();
219
+ const ids = ordered.map((k) => identity(k.sourceColumns, k.targetTable, k.targetColumns));
220
+ const seen = new Map();
221
+ const names = (0, catalog_metadata_js_1.foreignKeyConstraintNames)(table, ordered.map((k, i) => {
222
+ const id = ids[i];
223
+ const rank = seen.get(id) ?? 0;
224
+ seen.set(id, rank + 1);
225
+ const names = declared.get(id);
226
+ // Every key of this identity has a declaration, so the rank pairs them.
227
+ const matched = names?.length === ids.filter((other) => other === id).length;
228
+ return { columns: k.sourceColumns, name: matched ? names[rank] : undefined };
229
+ }), taken, statement.constraintNames);
230
+ ordered.forEach((k, i) => {
231
+ k.constraintName = names[i];
232
+ });
233
+ }
234
+ /** `name` as `names` spell it, compared as SQLite compares identifiers; undefined when none matches. */
235
+ const sqliteCatalogName = (names, name) => names.find((candidate) => fold(candidate) === fold(name));
236
+ exports.sqliteCatalogName = sqliteCatalogName;
237
+ /**
238
+ * Rewrites every key's child and referenced columns to the spelling their
239
+ * table's catalog gives them, and returns the keys that name a column a known
240
+ * table does not have. `PRAGMA foreign_key_list` keeps the spelling the
241
+ * REFERENCES clause used (`REFERENCES posts (ID)` for the column `id`), and
242
+ * SQLite compares identifiers ignoring ASCII case, so without this a junction
243
+ * key to the primary key did not read as one, nor a unique key's parent column
244
+ * as that column. Each introspector also looks a key's target table up with
245
+ * {@link sqliteCatalogName}.
246
+ *
247
+ * @param columnsOf a table's columns, undefined for a table that was not read
248
+ */
249
+ function canonicalSqliteForeignKeyColumns(keys, columnsOf) {
250
+ const unresolved = new Set();
251
+ for (const fk of keys) {
252
+ const spell = (table, name) => {
253
+ const columns = columnsOf(table);
254
+ const found = columns &&
255
+ (0, exports.sqliteCatalogName)(columns.map((c) => c.name), name);
256
+ if (columns && found === undefined)
257
+ unresolved.add(fk);
258
+ return found ?? name;
259
+ };
260
+ fk.sourceColumns = fk.sourceColumns.map((name) => spell(fk.sourceTable, name));
261
+ fk.targetColumns = fk.targetColumns.map((name) => spell(fk.targetTable, name));
262
+ }
263
+ return [...unresolved];
264
+ }
@@ -93,7 +93,6 @@ exports.turbineSqlite = turbineSqlite;
93
93
  exports.createSqliteBindingClient = createSqliteBindingClient;
94
94
  const node_async_hooks_1 = require("node:async_hooks");
95
95
  const node_module_1 = require("node:module");
96
- const catalog_metadata_js_1 = require("./catalog-metadata.js");
97
96
  const client_js_1 = require("./client.js");
98
97
  const sqlite_dialect_js_1 = require("./d1/sqlite-dialect.js");
99
98
  const errors_js_1 = require("./errors.js");
@@ -101,6 +100,7 @@ const introspect_js_1 = require("./introspect.js");
101
100
  const sql_comment_js_1 = require("./query/sql-comment.js");
102
101
  const schema_js_1 = require("./schema.js");
103
102
  const sql_placeholders_js_1 = require("./sql-placeholders.js");
103
+ const sqlite_constraint_names_js_1 = require("./sqlite-constraint-names.js");
104
104
  var sqlite_dialect_js_2 = require("./d1/sqlite-dialect.js");
105
105
  Object.defineProperty(exports, "sqliteTypeToTs", { enumerable: true, get: function () { return sqlite_dialect_js_2.sqliteTypeToTs; } });
106
106
  let cachedDatabaseSync;
@@ -1475,6 +1475,7 @@ function introspectSqliteDatabase(db, options = {}) {
1475
1475
  const relationUniqueByTable = new Map();
1476
1476
  const indexesByTable = new Map();
1477
1477
  const foreignKeys = [];
1478
+ const constraintNames = new Set();
1478
1479
  for (const tableName of tableNames) {
1479
1480
  const q = (name) => `"${name.replace(/"/g, '""')}"`;
1480
1481
  // ----- Columns + primary key -----
@@ -1529,9 +1530,14 @@ function introspectSqliteDatabase(db, options = {}) {
1529
1530
  entry = {
1530
1531
  sourceTable: tableName,
1531
1532
  sourceColumns: [],
1532
- targetTable: fk.table,
1533
+ // The catalog keeps the spelling the REFERENCES clause used.
1534
+ targetTable: (0, sqlite_constraint_names_js_1.sqliteCatalogName)(tableNames, fk.table) ?? fk.table,
1533
1535
  targetColumns: [],
1534
- constraintName: `fk_${tableName}_${fk.id}`,
1536
+ constraintName: '',
1537
+ actions: {
1538
+ onDelete: (0, introspect_js_1.referentialActionFromCatalog)(fk.on_delete),
1539
+ onUpdate: (0, introspect_js_1.referentialActionFromCatalog)(fk.on_update),
1540
+ },
1535
1541
  };
1536
1542
  fkById.set(fk.id, entry);
1537
1543
  }
@@ -1540,6 +1546,10 @@ function introspectSqliteDatabase(db, options = {}) {
1540
1546
  if (fk.to)
1541
1547
  entry.targetColumns.push(fk.to);
1542
1548
  }
1549
+ // SQLite's catalog names no constraint, and relation naming reads the
1550
+ // name for a composite FK: take it from the CREATE TABLE text, else the
1551
+ // name PostgreSQL would give it.
1552
+ (0, sqlite_constraint_names_js_1.nameSqliteForeignKeys)(tableName, tableDefinitions.get(tableName) ?? '', [...fkById.values()], constraintNames);
1543
1553
  for (const entry of fkById.values()) {
1544
1554
  if (entry.targetColumns.length === 0) {
1545
1555
  // Implicit reference → the target table's primary key.
@@ -1592,21 +1602,31 @@ function introspectSqliteDatabase(db, options = {}) {
1592
1602
  uniqueByTable.set(tableName, uniques);
1593
1603
  relationUniqueByTable.set(tableName, relationUniques);
1594
1604
  }
1605
+ // The referenced columns as the catalog spells them, so the relations, the
1606
+ // junction test and the comparison test all read one spelling.
1607
+ (0, sqlite_constraint_names_js_1.canonicalSqliteForeignKeyColumns)(foreignKeys, (table) => columnsByTable.get(table));
1595
1608
  // ----- Build relations from foreign keys (belongsTo + hasMany + m2m) -----
1596
- // Delegated to the SHARED introspection pipeline (introspect.ts) so SQLite
1597
- // derives IDENTICAL relation names to the Postgres introspector for the
1598
- // same logical schema, legacy-first naming, per-column disambiguation,
1599
- // collision resolution against scalar column fields, and the conservative
1600
- // pure-junction manyToMany auto-detection included.
1609
+ // Delegated to the ONE relation derivation every engine calls, so SQLite
1610
+ // derives the relations PostgreSQL derives for the same schema. What SQLite
1611
+ // contributes is its own facts: which column sets are unique keys, and when a
1612
+ // foreign key compares the way its key does (affinity), which together decide
1613
+ // a to-one before it is named.
1601
1614
  // One field per column, as the PostgreSQL introspector requires.
1602
1615
  for (const [tableName, cols] of columnsByTable)
1603
1616
  (0, introspect_js_1.assertDistinctColumnFields)(tableName, cols);
1604
- // A to-one is decided per foreign key BEFORE naming, so it is named as
1605
- // PostgreSQL names it (`users.profile`); the shared test is the libSQL and D1
1606
- // one, so every SQLite introspector gives the same answer.
1607
- const relationsByTable = (0, introspect_js_1.deriveEngineRelations)(tableNames, foreignKeys, pkByTable, columnsByTable, options.logger, options.legacyToManyUniques
1608
- ? undefined
1609
- : (0, catalog_metadata_js_1.sqliteToOneForeignKey)(columnsByTable, relationUniqueByTable, tableDefinitions, tableFlags));
1617
+ // The comparison test is the one every SQLite introspector shares (libSQL
1618
+ // and D1 included), so they all give the same answer.
1619
+ const relationsByTable = (0, introspect_js_1.deriveRelations)({
1620
+ tableNames,
1621
+ foreignKeys,
1622
+ pkByTable,
1623
+ columnsByTable,
1624
+ uniqueKeysByTable: relationUniqueByTable,
1625
+ sameKeyComparison: (0, introspect_js_1.sqliteKeyComparison)(columnsByTable, tableDefinitions, tableFlags),
1626
+ junctionKeysByTable: new Map(Array.from(uniqueByTable, ([table, keys]) => [table, keys.filter((key) => key.length === 2)])),
1627
+ ...(options.legacyToManyUniques ? { legacyToManyUniques: true } : {}),
1628
+ ...(options.logger ? { logger: options.logger } : {}),
1629
+ });
1610
1630
  // ----- Assemble TableMetadata -----
1611
1631
  const tables = (0, introspect_js_1.nullRecord)();
1612
1632
  for (const tableName of tableNames) {