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