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.
@@ -1,7 +1,8 @@
1
1
  /** SQLite catalog facts normalized for the D1 value contract, never a SQLite transport. */
2
- import { applyRelationRenames, applyTableFilters, assertDistinctColumnFields, assertSafeCatalogSchema, deriveEngineRelations, nullRecord, printableCatalogName, sqliteToOneForeignKey, } from '../catalog-metadata.js';
2
+ import { applyRelationRenames, applyTableFilters, assertDistinctColumnFields, assertSafeCatalogSchema, deriveRelations, nullRecord, printableCatalogName, referentialActionFromCatalog, sqliteKeyComparison, } from '../catalog-metadata.js';
3
3
  import { UnsupportedFeatureError, ValidationError } from '../errors.js';
4
4
  import { isDateType, snakeToCamel, } from '../schema.js';
5
+ import { canonicalSqliteForeignKeyColumns, nameSqliteForeignKeys, sqliteCatalogName, } from '../sqlite-constraint-names.js';
5
6
  import { CATALOG_TABLES, CATALOG_VIEWS, literal, q } from './catalog.js';
6
7
  import { sqliteTypeToTs } from './sqlite-dialect.js';
7
8
  /** Native D1 INTEGER results are numbers. Decimal affinity may retain nonnumeric TEXT. */
@@ -10,7 +11,6 @@ function d1ColumnType(declared, nullable) {
10
11
  return nullable ? 'number | string | null' : 'number | string';
11
12
  return sqliteTypeToTs(declared, nullable);
12
13
  }
13
- const sqliteName = (name) => name.replace(/[A-Z]/g, (letter) => letter.toLowerCase());
14
14
  function isSqliteDateType(type) {
15
15
  return isDateType(type.toLowerCase()) || /(timestamp|datetime|date)/i.test(type);
16
16
  }
@@ -39,6 +39,7 @@ export function d1CatalogMetadata(snapshot, options) {
39
39
  const relationUniqueByTable = new Map();
40
40
  const indexesByTable = new Map();
41
41
  const foreignKeys = [];
42
+ const constraintNames = new Set();
42
43
  for (const tableName of tableNames) {
43
44
  // ----- Columns + primary key -----
44
45
  // table_xinfo also exposes computed columns (hidden = 2/3). Virtual-table
@@ -91,9 +92,13 @@ export function d1CatalogMetadata(snapshot, options) {
91
92
  entry = {
92
93
  sourceTable: tableName,
93
94
  sourceColumns: [],
94
- targetTable: tableNames.find((name) => sqliteName(name) === sqliteName(fk.table)) ?? fk.table,
95
+ targetTable: sqliteCatalogName(tableNames, fk.table) ?? fk.table,
95
96
  targetColumns: [],
96
- constraintName: `fk_${tableName}_${fk.id}`,
97
+ constraintName: '',
98
+ actions: {
99
+ onDelete: referentialActionFromCatalog(fk.on_delete),
100
+ onUpdate: referentialActionFromCatalog(fk.on_update),
101
+ },
97
102
  };
98
103
  fkById.set(fk.id, entry);
99
104
  }
@@ -102,6 +107,10 @@ export function d1CatalogMetadata(snapshot, options) {
102
107
  if (fk.to !== null)
103
108
  entry.targetColumns.push(fk.to);
104
109
  }
110
+ // SQLite's catalog names no constraint, and relation naming reads the name
111
+ // for a composite FK: take it from the CREATE TABLE text, else the name
112
+ // PostgreSQL would give it.
113
+ nameSqliteForeignKeys(tableName, tableDefinitions.get(tableName) ?? '', [...fkById.values()], constraintNames);
105
114
  for (const entry of fkById.values()) {
106
115
  if (!tableSet.has(entry.targetTable))
107
116
  continue;
@@ -159,25 +168,27 @@ export function d1CatalogMetadata(snapshot, options) {
159
168
  }
160
169
  // SQLite resolves FK identifiers with ASCII case folding. Preserve the actual
161
170
  // catalog spelling in metadata and refuse unresolved in-scope references.
162
- for (const fk of foreignKeys) {
163
- const resolve = (table, name) => {
164
- const column = columnsByTable.get(table)?.find((c) => sqliteName(c.name) === sqliteName(name));
165
- if (!column)
166
- throw new ValidationError(`Unresolvable D1 foreign key: ${printableCatalogName(fk.constraintName)}.`);
167
- return column.name;
168
- };
169
- fk.sourceColumns = fk.sourceColumns.map((name) => resolve(fk.sourceTable, name));
170
- fk.targetColumns = fk.targetColumns.map((name) => resolve(fk.targetTable, name));
171
- }
171
+ const [unresolved] = canonicalSqliteForeignKeyColumns(foreignKeys, (table) => columnsByTable.get(table));
172
+ if (unresolved)
173
+ throw new ValidationError(`Unresolvable D1 foreign key: ${printableCatalogName(unresolved.constraintName)}.`);
172
174
  // ----- Build relations from foreign keys (belongsTo + hasMany + m2m) -----
173
- // Reuse the established engine naming, field-collision and conservative
174
- // junction policies. A to-one is decided per foreign key before naming, so
175
- // it is named as PostgreSQL names it (`users.profile`).
175
+ // The ONE relation derivation every engine calls, with SQLite's own facts:
176
+ // its unique keys, and when a foreign key compares the way its key does. A
177
+ // to-one is decided per foreign key before naming, so it is named as
178
+ // PostgreSQL names it (`users.profile`).
176
179
  for (const [tableName, cols] of columnsByTable)
177
180
  assertDistinctColumnFields(tableName, cols);
178
- const relationsByTable = deriveEngineRelations(tableNames, foreignKeys, pkByTable, columnsByTable, options.logger, options.legacyToManyUniques
179
- ? undefined
180
- : sqliteToOneForeignKey(columnsByTable, relationUniqueByTable, tableDefinitions, tableFlags));
181
+ const relationsByTable = deriveRelations({
182
+ tableNames,
183
+ foreignKeys,
184
+ pkByTable,
185
+ columnsByTable,
186
+ uniqueKeysByTable: relationUniqueByTable,
187
+ sameKeyComparison: sqliteKeyComparison(columnsByTable, tableDefinitions, tableFlags),
188
+ junctionKeysByTable: new Map(Array.from(uniqueByTable, ([table, keys]) => [table, keys.filter((key) => key.length === 2)])),
189
+ ...(options.legacyToManyUniques ? { legacyToManyUniques: true } : {}),
190
+ ...(options.logger ? { logger: options.logger } : {}),
191
+ });
181
192
  // ----- Assemble TableMetadata -----
182
193
  const tables = nullRecord();
183
194
  for (const tableName of tableNames) {
@@ -1,5 +1,5 @@
1
1
  import { type ForeignKeyEntry } from './catalog-metadata.js';
2
- export { addAutoManyToManyRelations, applyRelationRenames, applyTableFilters, assertDistinctColumnFields, assertSafeCatalogIdentifier, assertSafeCatalogSchema, buildRelationsFromForeignKeys, DEFAULT_EXCLUDED_TABLES, defaultExcludedTablesPresent, deriveEngineRelations, type ForeignKeyEntry, isUnknownTsType, nullRecord, printableCatalogName, relationNameFromColumn, type TableFilterOptions, } from './catalog-metadata.js';
2
+ export { addAutoManyToManyRelations, applyRelationRenames, applyTableFilters, assertDistinctColumnFields, assertSafeCatalogIdentifier, assertSafeCatalogSchema, buildRelationsFromForeignKeys, compareCatalogNames, DEFAULT_EXCLUDED_TABLES, defaultExcludedTablesPresent, defaultForeignKeyConstraintName, deriveRelations, type ForeignKeyEntry, foreignKeyConstraintNames, isUnknownTsType, nullRecord, printableCatalogName, type RelationCatalogFacts, referentialActionFromCatalog, relationNameFromColumn, sqliteKeyComparison, type TableFilterOptions, } from './catalog-metadata.js';
3
3
  import { type Dialect } from './dialect.js';
4
4
  import { type TurbineLogger } from './logger.js';
5
5
  import { type ColumnMetadata, type IndexMetadata, type ReferentialAction, type RelationDef, type SchemaMetadata } from './schema.js';
@@ -209,9 +209,8 @@ export interface CatalogRelationInputs {
209
209
  * losing every auto-m2m relation through a Prisma-style PK-less junction. Adding
210
210
  * an argument here reaches both surfaces or neither.
211
211
  *
212
- * The engine introspectors (SQLite / MySQL / MSSQL) keep their own
213
- * {@link deriveEngineRelations}. Since 0.94 it names a unique foreign key's
214
- * reverse relation as a to-one too, the way this function does; the remaining
215
- * differences between the two are listed in docs/relation-names.md.
212
+ * It is the PostgreSQL catalog's adapter onto {@link deriveRelations}, the one
213
+ * derivation every engine introspector and `schemaDefToMetadata` also call, so
214
+ * the same schema derives the same relations on every engine.
216
215
  */
217
216
  export declare function deriveCatalogRelations(inputs: CatalogRelationInputs): Map<string, Record<string, RelationDef>>;
@@ -1,5 +1,5 @@
1
- import { addAutoManyToManyRelations, applyRelationRenames, applyTableFilters, assertDistinctColumnFields, assertSafeCatalogSchema, buildRelationsFromForeignKeys, DEFAULT_EXCLUDED_TABLES, defaultExcludedTablesPresent, deriveEngineRelations, isUnknownTsType, nullRecord, printableCatalogName, } from './catalog-metadata.js';
2
- export { addAutoManyToManyRelations, applyRelationRenames, applyTableFilters, assertDistinctColumnFields, assertSafeCatalogIdentifier, assertSafeCatalogSchema, buildRelationsFromForeignKeys, DEFAULT_EXCLUDED_TABLES, defaultExcludedTablesPresent, deriveEngineRelations, isUnknownTsType, nullRecord, printableCatalogName, relationNameFromColumn, } from './catalog-metadata.js';
1
+ import { applyRelationRenames, applyTableFilters, assertDistinctColumnFields, assertSafeCatalogSchema, DEFAULT_EXCLUDED_TABLES, defaultExcludedTablesPresent, deriveRelations, nullRecord, printableCatalogName, } from './catalog-metadata.js';
2
+ export { addAutoManyToManyRelations, applyRelationRenames, applyTableFilters, assertDistinctColumnFields, assertSafeCatalogIdentifier, assertSafeCatalogSchema, buildRelationsFromForeignKeys, compareCatalogNames, DEFAULT_EXCLUDED_TABLES, defaultExcludedTablesPresent, defaultForeignKeyConstraintName, deriveRelations, foreignKeyConstraintNames, isUnknownTsType, nullRecord, printableCatalogName, referentialActionFromCatalog, relationNameFromColumn, sqliteKeyComparison, } from './catalog-metadata.js';
3
3
  /**
4
4
  * turbine-orm, Schema introspection
5
5
  *
@@ -512,10 +512,9 @@ export async function introspectPostgresCatalog(options) {
512
512
  `relation is emitted for these. Introspect the other schema separately, or add the target table to this one.`, { code: 'introspect-cross-schema-fk', schema, references: crossSchemaRefs.length });
513
513
  }
514
514
  // Referential actions (ON DELETE / ON UPDATE) per constraint. Keyed
515
- // "<table>::<constraint>" because the NAME alone is not unique (the same
516
- // collision SQL_FOREIGN_KEYS documents); buildRelationsFromForeignKeys
517
- // prefers that key and falls back to the bare name for callers that build
518
- // the map from a code-first schema, where names are synthesized per table.
515
+ // "<table>::<constraint>" because the NAME alone is not unique across
516
+ // tables (the same collision SQL_FOREIGN_KEYS documents); PostgreSQL keeps
517
+ // it unique within one table.
519
518
  const fkActions = new Map();
520
519
  for (const row of fkResult.rows) {
521
520
  fkActions.set(`${row.source_table}::${row.constraint_name}`, {
@@ -764,30 +763,11 @@ export function detectUniqueForeignKeySets(pkByTable, uniqueByTable, indexesByTa
764
763
  * losing every auto-m2m relation through a Prisma-style PK-less junction. Adding
765
764
  * an argument here reaches both surfaces or neither.
766
765
  *
767
- * The engine introspectors (SQLite / MySQL / MSSQL) keep their own
768
- * {@link deriveEngineRelations}. Since 0.94 it names a unique foreign key's
769
- * reverse relation as a to-one too, the way this function does; the remaining
770
- * differences between the two are listed in docs/relation-names.md.
766
+ * It is the PostgreSQL catalog's adapter onto {@link deriveRelations}, the one
767
+ * derivation every engine introspector and `schemaDefToMetadata` also call, so
768
+ * the same schema derives the same relations on every engine.
771
769
  */
772
770
  export function deriveCatalogRelations(inputs) {
773
- const { tableNames, foreignKeys, pkByTable, columnsByTable, uniqueByTable, indexesByTable, enums } = inputs;
774
- const columnFieldsByTable = new Map();
775
- const unknownTypedFieldsByTable = new Map();
776
- for (const [tbl, cols] of columnsByTable) {
777
- columnFieldsByTable.set(tbl, new Set(cols.map((c) => c.field)));
778
- // Enum-typed columns also report tsType 'unknown' here, but generate.ts
779
- // gives them a concrete union type, so a shadow of one is type-broken and
780
- // must NOT be preserved as a historical json/jsonb shadow.
781
- unknownTypedFieldsByTable.set(tbl, new Set(cols.filter((c) => isUnknownTsType(c.tsType) && !Object.hasOwn(enums, c.pgType)).map((c) => c.field)));
782
- }
783
- // Unless the caller opts out, detect child FK column sets that a unique
784
- // constraint / plain unique index exactly covers, so the reverse relation is
785
- // emitted as a one-to-one (`hasOne`) instead of `hasMany`.
786
- const uniqueSetsByTable = inputs.legacyToManyUniques
787
- ? undefined
788
- : detectUniqueForeignKeySets(pkByTable, uniqueByTable, indexesByTable);
789
- const logger = inputs.logger ?? consoleLogger;
790
- const relationsByTable = buildRelationsFromForeignKeys(foreignKeys, columnFieldsByTable, inputs.fkActions, unknownTypedFieldsByTable, uniqueSetsByTable, logger);
791
771
  // Prisma's implicit m2m junctions have no primary key (just a two-column
792
772
  // UNIQUE index over the FK columns), so pass the introspected two-column
793
773
  // unique indexes as the fallback junction-key source.
@@ -800,8 +780,8 @@ export function deriveCatalogRelations(inputs) {
800
780
  // soft-deleted junction, constrains only the rows matching its predicate. A
801
781
  // manyToMany derived from either returns duplicate rows. The metadata flags
802
782
  // are honoured too, so a caller-supplied `partial: true` still refuses.
803
- const uniqueIndexColsByTable = new Map();
804
- for (const [tbl, idxs] of indexesByTable) {
783
+ const junctionKeysByTable = new Map();
784
+ for (const [tbl, idxs] of inputs.indexesByTable) {
805
785
  const twoColUniques = idxs.flatMap((idx) => {
806
786
  const read = indexMetadataFromDefinition(idx.name, idx.definition);
807
787
  return idx.unique && !idx.partial && read.unique && !read.partial && read.columns.length === 2
@@ -809,8 +789,24 @@ export function deriveCatalogRelations(inputs) {
809
789
  : [];
810
790
  });
811
791
  if (twoColUniques.length > 0)
812
- uniqueIndexColsByTable.set(tbl, twoColUniques);
792
+ junctionKeysByTable.set(tbl, twoColUniques);
813
793
  }
814
- addAutoManyToManyRelations(tableNames, foreignKeys, pkByTable, new Map(Array.from(columnsByTable, ([tbl, cols]) => [tbl, cols.map((c) => c.name)])), relationsByTable, columnFieldsByTable, unknownTypedFieldsByTable, uniqueIndexColsByTable, logger);
815
- return relationsByTable;
794
+ return deriveRelations({
795
+ tableNames: inputs.tableNames,
796
+ foreignKeys: inputs.foreignKeys,
797
+ pkByTable: inputs.pkByTable,
798
+ columnsByTable: inputs.columnsByTable,
799
+ enums: inputs.enums,
800
+ // A child FK column set that a unique constraint / plain unique index
801
+ // exactly covers makes the reverse relation a one-to-one (`hasOne`).
802
+ uniqueKeysByTable: detectUniqueForeignKeySets(inputs.pkByTable, inputs.uniqueByTable, inputs.indexesByTable),
803
+ junctionKeysByTable,
804
+ // Both catalog readers (this module and the MCP server) already order
805
+ // tables and foreign keys (see SQL_FOREIGN_KEYS), and that order is the
806
+ // reference the other engines sort to.
807
+ inCatalogOrder: true,
808
+ ...(inputs.fkActions ? { fkActions: inputs.fkActions } : {}),
809
+ ...(inputs.legacyToManyUniques ? { legacyToManyUniques: true } : {}),
810
+ ...(inputs.logger ? { logger: inputs.logger } : {}),
811
+ });
816
812
  }
@@ -1,9 +1,10 @@
1
- import { applyRelationRenames, applyTableFilters, assertDistinctColumnFields, assertSafeCatalogSchema, deriveEngineRelations, nullRecord, printableCatalogName, sqliteToOneForeignKey, } from '../catalog-metadata.js';
1
+ import { applyRelationRenames, applyTableFilters, assertDistinctColumnFields, assertSafeCatalogSchema, deriveRelations, nullRecord, printableCatalogName, referentialActionFromCatalog, sqliteKeyComparison, } from '../catalog-metadata.js';
2
2
  /** Native local libSQL catalog reads only; no schema lifecycle or remote transport. */
3
3
  import { sqliteTypeToTs } from '../d1/sqlite-dialect.js';
4
4
  import { ConnectionError, UnsupportedFeatureError, ValidationError } from '../errors.js';
5
5
  import importOptionalPeer from '../optional-peer-import.cjs';
6
6
  import { isDateType, snakeToCamel, } from '../schema.js';
7
+ import { canonicalSqliteForeignKeyColumns, nameSqliteForeignKeys, sqliteCatalogName, } from '../sqlite-constraint-names.js';
7
8
  import { localUrl } from './pool.js';
8
9
  import { rows } from './values.js';
9
10
  const optionKeys = new Set([
@@ -76,7 +77,6 @@ async function catalog(client, sql, args) {
76
77
  // native row decoder. Identifiers are quoted; query values use native binds.
77
78
  return rows(await client.execute({ sql, args }));
78
79
  }
79
- const sqliteName = (name) => name.replace(/[A-Z]/g, (letter) => letter.toLowerCase());
80
80
  const q = (name) => `"${name.replace(/"/g, '""')}"`;
81
81
  function isSqliteDateType(type) {
82
82
  return isDateType(type.toLowerCase()) || /(timestamp|datetime|date)/i.test(type);
@@ -105,6 +105,7 @@ async function readCatalog(client, options) {
105
105
  const relationUniqueByTable = new Map();
106
106
  const indexesByTable = new Map();
107
107
  const foreignKeys = [];
108
+ const constraintNames = new Set();
108
109
  for (const tableName of tableNames) {
109
110
  // ----- Columns + primary key -----
110
111
  // table_xinfo also exposes computed columns (hidden = 2/3). Virtual-table
@@ -157,9 +158,13 @@ async function readCatalog(client, options) {
157
158
  entry = {
158
159
  sourceTable: tableName,
159
160
  sourceColumns: [],
160
- targetTable: tableNames.find((name) => sqliteName(name) === sqliteName(fk.table)) ?? fk.table,
161
+ targetTable: sqliteCatalogName(tableNames, fk.table) ?? fk.table,
161
162
  targetColumns: [],
162
- constraintName: `fk_${tableName}_${fk.id}`,
163
+ constraintName: '',
164
+ actions: {
165
+ onDelete: referentialActionFromCatalog(fk.on_delete),
166
+ onUpdate: referentialActionFromCatalog(fk.on_update),
167
+ },
163
168
  };
164
169
  fkById.set(fk.id, entry);
165
170
  }
@@ -168,6 +173,10 @@ async function readCatalog(client, options) {
168
173
  if (fk.to !== null)
169
174
  entry.targetColumns.push(fk.to);
170
175
  }
176
+ // SQLite's catalog names no constraint, and relation naming reads the name
177
+ // for a composite FK: take it from the CREATE TABLE text, else the name
178
+ // PostgreSQL would give it.
179
+ nameSqliteForeignKeys(tableName, tableDefinitions.get(tableName) ?? '', [...fkById.values()], constraintNames);
171
180
  for (const entry of fkById.values()) {
172
181
  if (entry.targetColumns.length === 0) {
173
182
  // Implicit reference → the target table's primary key.
@@ -223,25 +232,27 @@ async function readCatalog(client, options) {
223
232
  }
224
233
  // SQLite resolves FK identifiers with ASCII case folding. Preserve the actual
225
234
  // catalog spelling in metadata and refuse unresolved in-scope references.
226
- for (const fk of foreignKeys) {
227
- const resolve = (table, name) => {
228
- const column = columnsByTable.get(table)?.find((c) => sqliteName(c.name) === sqliteName(name));
229
- if (!column)
230
- throw new ValidationError(`Unresolvable local libSQL foreign key: ${printableCatalogName(fk.constraintName)}.`);
231
- return column.name;
232
- };
233
- fk.sourceColumns = fk.sourceColumns.map((name) => resolve(fk.sourceTable, name));
234
- fk.targetColumns = fk.targetColumns.map((name) => resolve(fk.targetTable, name));
235
- }
235
+ const [unresolved] = canonicalSqliteForeignKeyColumns(foreignKeys, (table) => columnsByTable.get(table));
236
+ if (unresolved)
237
+ throw new ValidationError(`Unresolvable local libSQL foreign key: ${printableCatalogName(unresolved.constraintName)}.`);
236
238
  // ----- Build relations from foreign keys (belongsTo + hasMany + m2m) -----
237
- // Reuse the established engine naming, field-collision and conservative
238
- // junction policies. A to-one is decided per foreign key before naming, so
239
- // it is named as PostgreSQL names it (`users.profile`).
239
+ // The ONE relation derivation every engine calls, with SQLite's own facts:
240
+ // its unique keys, and when a foreign key compares the way its key does. A
241
+ // to-one is decided per foreign key before naming, so it is named as
242
+ // PostgreSQL names it (`users.profile`).
240
243
  for (const [tableName, cols] of columnsByTable)
241
244
  assertDistinctColumnFields(tableName, cols);
242
- const relationsByTable = deriveEngineRelations(tableNames, foreignKeys, pkByTable, columnsByTable, options.logger, options.legacyToManyUniques
243
- ? undefined
244
- : sqliteToOneForeignKey(columnsByTable, relationUniqueByTable, tableDefinitions, tableFlags));
245
+ const relationsByTable = deriveRelations({
246
+ tableNames,
247
+ foreignKeys,
248
+ pkByTable,
249
+ columnsByTable,
250
+ uniqueKeysByTable: relationUniqueByTable,
251
+ sameKeyComparison: sqliteKeyComparison(columnsByTable, tableDefinitions, tableFlags),
252
+ junctionKeysByTable: new Map(Array.from(uniqueByTable, ([table, keys]) => [table, keys.filter((key) => key.length === 2)])),
253
+ ...(options.legacyToManyUniques ? { legacyToManyUniques: true } : {}),
254
+ ...(options.logger ? { logger: options.logger } : {}),
255
+ });
245
256
  // ----- Assemble TableMetadata -----
246
257
  const tables = nullRecord();
247
258
  for (const tableName of tableNames) {
package/dist/mssql.js CHANGED
@@ -90,7 +90,7 @@
90
90
  import { TurbineClient, } from './client.js';
91
91
  import { postgresDialect, } from './dialect.js';
92
92
  import { ConnectionError, malformedConnectionStringMessage, markValueBearingMessage, RelationError, UnsupportedFeatureError, ValidationError, } from './errors.js';
93
- import { applyTableFilters, assertDistinctColumnFields, deriveEngineRelations, nullRecord, } from './introspect.js';
93
+ import { applyTableFilters, assertDistinctColumnFields, compareCatalogNames, deriveRelations, foreignKeyConstraintNames, nullRecord, referentialActionFromCatalog, } from './introspect.js';
94
94
  import importOptionalPeer from './optional-peer-import.cjs';
95
95
  import { orderByEntries } from './query/filters.js';
96
96
  import { availableClause } from './query/utils.js';
@@ -1538,15 +1538,14 @@ const num = (v) => (typeof v === 'string' ? Number(v) : (v ?? 0));
1538
1538
  */
1539
1539
  const bitIsTrue = (v) => v === true || v === 1 || v === '1' || v === 'true';
1540
1540
  /**
1541
- * Derive relations from the FK list via the SHARED introspection pipeline
1542
- * (`deriveEngineRelations` → `buildRelationsFromForeignKeys` +
1543
- * `addAutoManyToManyRelations` in introspect.ts), so this engine derives
1544
- * IDENTICAL relation names to `turbine generate` against Postgres for the
1545
- * same logical schema, legacy-first naming, per-column disambiguation, and
1546
- * collision resolution against scalar column fields included.
1541
+ * Derive relations through the ONE relation derivation every engine calls
1542
+ * (`deriveRelations` in catalog-metadata.ts), so this engine derives the
1543
+ * relations `turbine generate` derives against PostgreSQL for the same schema.
1544
+ * SQL Server contributes its own facts: its unique keys, when a key's
1545
+ * comparison semantics match the join's, and its referential actions.
1547
1546
  */
1548
- function buildRelationsFromForeignKeys(tableNames, foreignKeys, pkByTable, columnsByTable, logger, isToOne) {
1549
- return deriveEngineRelations(tableNames, foreignKeys, pkByTable, columnsByTable, logger, isToOne);
1547
+ function buildRelationsFromForeignKeys(facts) {
1548
+ return deriveRelations(facts);
1550
1549
  }
1551
1550
  /**
1552
1551
  * Introspect a SQL Server database into the same {@link SchemaMetadata} shape the
@@ -1668,7 +1667,10 @@ export async function introspectMssqlWith(exec, schema = 'dbo', options = {}) {
1668
1667
  cpt.name AS REFERENCED_COLUMN_NAME,
1669
1668
  fkc.constraint_column_id AS ORDINAL_POSITION,
1670
1669
  s.name AS TABLE_SCHEMA,
1671
- rs.name AS REFERENCED_TABLE_SCHEMA
1670
+ rs.name AS REFERENCED_TABLE_SCHEMA,
1671
+ fk.delete_referential_action_desc AS DELETE_RULE,
1672
+ fk.update_referential_action_desc AS UPDATE_RULE,
1673
+ fk.is_system_named AS IS_SYSTEM_NAMED
1672
1674
  FROM sys.foreign_keys fk
1673
1675
  JOIN sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
1674
1676
  JOIN sys.columns cps ON cps.object_id = fkc.parent_object_id AND cps.column_id = fkc.parent_column_id
@@ -1678,7 +1680,7 @@ export async function introspectMssqlWith(exec, schema = 'dbo', options = {}) {
1678
1680
  JOIN sys.schemas rs ON rs.schema_id = rt.schema_id
1679
1681
  WHERE s.name = @p1 AND rs.name = @p1
1680
1682
  ORDER BY fk.name, fkc.constraint_column_id`, [schema]);
1681
- const fkByConstraint = new Map();
1683
+ const fkByTable = new Map();
1682
1684
  for (const r of fkRows.sort((a, b) => Number(a.ORDINAL_POSITION) - Number(b.ORDINAL_POSITION))) {
1683
1685
  const sourceTable = String(r.TABLE_NAME);
1684
1686
  const targetTable = String(r.REFERENCED_TABLE_NAME);
@@ -1688,16 +1690,64 @@ export async function introspectMssqlWith(exec, schema = 'dbo', options = {}) {
1688
1690
  (r.TABLE_SCHEMA != null && r.REFERENCED_TABLE_SCHEMA != null && r.REFERENCED_TABLE_SCHEMA !== r.TABLE_SCHEMA))
1689
1691
  continue;
1690
1692
  const constraintName = String(r.CONSTRAINT_NAME);
1691
- const key = JSON.stringify([sourceTable, constraintName]);
1692
- let entry = fkByConstraint.get(key);
1693
- if (!entry) {
1694
- entry = { sourceTable, sourceColumns: [], targetTable, targetColumns: [], constraintName };
1695
- fkByConstraint.set(key, entry);
1693
+ if (!fkByTable.has(sourceTable))
1694
+ fkByTable.set(sourceTable, new Map());
1695
+ const table = fkByTable.get(sourceTable);
1696
+ let key = table.get(constraintName);
1697
+ if (!key) {
1698
+ key = {
1699
+ fk: {
1700
+ sourceTable,
1701
+ sourceColumns: [],
1702
+ targetTable,
1703
+ targetColumns: [],
1704
+ constraintName,
1705
+ actions: {
1706
+ onDelete: referentialActionFromCatalog(r.DELETE_RULE),
1707
+ onUpdate: referentialActionFromCatalog(r.UPDATE_RULE),
1708
+ },
1709
+ },
1710
+ systemNamed: bitIsTrue(r.IS_SYSTEM_NAMED),
1711
+ };
1712
+ table.set(constraintName, key);
1696
1713
  }
1697
- entry.sourceColumns.push(String(r.COLUMN_NAME));
1698
- entry.targetColumns.push(String(r.REFERENCED_COLUMN_NAME));
1714
+ key.fk.sourceColumns.push(String(r.COLUMN_NAME));
1715
+ key.fk.targetColumns.push(String(r.REFERENCED_COLUMN_NAME));
1716
+ }
1717
+ // Relation naming reads a composite FK's constraint name. A system-named
1718
+ // constraint (`FK__orders__tenan__1A2B3C4D`, with a random suffix) takes the
1719
+ // name PostgreSQL would have given it, so that relation is named the same on
1720
+ // every database and on every engine; an explicit name is reserved first.
1721
+ // SQL Server records no declaration order, so system-named keys are named in
1722
+ // the order of their columns, what they reference and their actions, never
1723
+ // of the suffix. A default also avoids the table's explicit CHECK, PRIMARY
1724
+ // KEY and UNIQUE constraint names, which PostgreSQL creates first.
1725
+ const reserved = new Map();
1726
+ for (const r of await exec(`SELECT OBJECT_NAME(k.parent_object_id) AS TABLE_NAME, k.name AS CONSTRAINT_NAME
1727
+ FROM sys.key_constraints k JOIN sys.schemas s ON s.schema_id = k.schema_id
1728
+ WHERE s.name = @p1 AND k.is_system_named = 0
1729
+ UNION ALL
1730
+ SELECT OBJECT_NAME(c.parent_object_id), c.name
1731
+ FROM sys.check_constraints c JOIN sys.schemas s ON s.schema_id = c.schema_id
1732
+ WHERE s.name = @p1 AND c.is_system_named = 0`, [schema])) {
1733
+ const table = String(r.TABLE_NAME);
1734
+ reserved.set(table, [...(reserved.get(table) ?? []), String(r.CONSTRAINT_NAME)]);
1735
+ }
1736
+ const constraintNames = new Set();
1737
+ const foreignKeys = [];
1738
+ const identity = ({ fk }) => JSON.stringify([fk.sourceColumns, fk.targetTable, fk.targetColumns, fk.actions?.onDelete, fk.actions?.onUpdate]);
1739
+ for (const [table, entries] of [...fkByTable].sort(([a], [b]) => compareCatalogNames(a, b))) {
1740
+ const keys = [...entries.values()].sort((a, b) => Number(a.systemNamed) - Number(b.systemNamed) || compareCatalogNames(identity(a), identity(b)));
1741
+ const names = foreignKeyConstraintNames(table, keys.map(({ fk, systemNamed }) => ({
1742
+ columns: fk.sourceColumns,
1743
+ name: systemNamed ? undefined : fk.constraintName,
1744
+ })), constraintNames, reserved.get(table));
1745
+ keys.forEach(({ fk }, i) => {
1746
+ fk.constraintName = names[i];
1747
+ if (tableSet.has(fk.targetTable))
1748
+ foreignKeys.push(fk);
1749
+ });
1699
1750
  }
1700
- const foreignKeys = [...fkByConstraint.values()].filter((fk) => tableSet.has(fk.targetTable));
1701
1751
  // ----- Indexes + unique constraints -----
1702
1752
  const idxRows = await exec(`SELECT t.name AS TABLE_NAME, i.name AS INDEX_NAME, i.is_unique AS IS_UNIQUE,
1703
1753
  c.name AS COLUMN_NAME, ic.key_ordinal AS SEQ,
@@ -1801,17 +1851,21 @@ export async function introspectMssqlWith(exec, schema = 'dbo', options = {}) {
1801
1851
  return false;
1802
1852
  return ['CHARACTER_MAXIMUM_LENGTH', 'NUMERIC_PRECISION', 'NUMERIC_SCALE', 'DATETIME_PRECISION'].every((fact) => child[fact] === parent[fact]);
1803
1853
  };
1804
- const relationsByTable = buildRelationsFromForeignKeys(tableNames, foreignKeys, pkByTable, columnsByTable, options.logger, options.legacyToManyUniques
1805
- ? undefined
1806
- : (fk) => {
1807
- const columns = fk.sourceColumns;
1808
- if (columns.length !== fk.targetColumns.length ||
1809
- !columns.every((name, i) => sameComparison(fk.sourceTable, name, fk.targetTable, fk.targetColumns[i])))
1810
- return false;
1811
- const primary = inactivePrimaryTables.has(fk.sourceTable) ? [] : (pkByTable.get(fk.sourceTable) ?? []);
1812
- const keys = [primary, ...(uniqueByTable.get(fk.sourceTable) ?? [])];
1813
- return keys.some((key) => key.length > 0 && key.length === columns.length && key.every((name) => columns.includes(name)));
1814
- });
1854
+ const relationsByTable = buildRelationsFromForeignKeys({
1855
+ tableNames,
1856
+ foreignKeys,
1857
+ pkByTable,
1858
+ columnsByTable,
1859
+ uniqueKeysByTable: new Map(tableNames.map((table) => [
1860
+ table,
1861
+ [inactivePrimaryTables.has(table) ? [] : (pkByTable.get(table) ?? []), ...(uniqueByTable.get(table) ?? [])],
1862
+ ])),
1863
+ sameKeyComparison: (fk) => fk.sourceColumns.length === fk.targetColumns.length &&
1864
+ fk.sourceColumns.every((name, i) => sameComparison(fk.sourceTable, name, fk.targetTable, fk.targetColumns[i])),
1865
+ junctionKeysByTable: new Map(Array.from(uniqueByTable, ([table, keys]) => [table, keys.filter((key) => key.length === 2)])),
1866
+ ...(options.legacyToManyUniques ? { legacyToManyUniques: true } : {}),
1867
+ ...(options.logger ? { logger: options.logger } : {}),
1868
+ });
1815
1869
  // ----- Assemble TableMetadata -----
1816
1870
  const tables = nullRecord();
1817
1871
  for (const tableName of tableNames) {
package/dist/mysql.js CHANGED
@@ -64,7 +64,7 @@
64
64
  import { TurbineClient, } from './client.js';
65
65
  import { postgresDialect, } from './dialect.js';
66
66
  import { ConnectionError, malformedConnectionStringMessage, markValueBearingMessage, TimeoutError, TransactionOutcomeUnknownError, UnsupportedFeatureError, ValidationError, } from './errors.js';
67
- import { applyTableFilters, assertDistinctColumnFields, deriveEngineRelations, nullRecord } from './introspect.js';
67
+ import { applyTableFilters, assertDistinctColumnFields, compareCatalogNames, deriveRelations, foreignKeyConstraintNames, nullRecord, referentialActionFromCatalog, } from './introspect.js';
68
68
  import { consoleLogger, logTo } from './logger.js';
69
69
  import importOptionalPeer from './optional-peer-import.cjs';
70
70
  import { isDateType, snakeToCamel, } from './schema.js';
@@ -1530,15 +1530,15 @@ export const mysqlDialect = {
1530
1530
  };
1531
1531
  const num = (v) => (typeof v === 'string' ? Number(v) : (v ?? 0));
1532
1532
  /**
1533
- * Derive relations from the FK list via the SHARED introspection pipeline
1534
- * (`deriveEngineRelations` → `buildRelationsFromForeignKeys` +
1535
- * `addAutoManyToManyRelations` in introspect.ts), so this engine derives
1536
- * IDENTICAL relation names to `turbine generate` against Postgres for the
1537
- * same logical schema, legacy-first naming, per-column disambiguation, and
1538
- * collision resolution against scalar column fields included.
1533
+ * Derive relations through the ONE relation derivation every engine calls
1534
+ * (`deriveRelations` in catalog-metadata.ts), so this engine derives the
1535
+ * relations `turbine generate` derives against PostgreSQL for the same schema.
1536
+ * MySQL contributes its own facts: its unique keys, the column domains under
1537
+ * which a key also enforces the join (`mysqlSameKeyEquality`), and its
1538
+ * referential actions.
1539
1539
  */
1540
- function buildRelationsFromForeignKeys(tableNames, foreignKeys, pkByTable, columnsByTable, logger, isToOne) {
1541
- return deriveEngineRelations(tableNames, foreignKeys, pkByTable, columnsByTable, logger, isToOne);
1540
+ function buildRelationsFromForeignKeys(facts) {
1541
+ return deriveRelations(facts);
1542
1542
  }
1543
1543
  /** Only comparison domains whose native equality also enforces the unique key. */
1544
1544
  function mysqlSameKeyEquality(child, parent) {
@@ -1707,19 +1707,24 @@ export async function introspectMysqlWith(exec, schema, options = {}) {
1707
1707
  pkByTable.get(r.TABLE_NAME).push(r.COLUMN_NAME);
1708
1708
  }
1709
1709
  // ----- Foreign keys (grouped by constraint for composite FKs) -----
1710
- const fkRows = (await exec(`SELECT TABLE_NAME, COLUMN_NAME, REFERENCED_TABLE_SCHEMA, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME, CONSTRAINT_NAME, ORDINAL_POSITION
1711
- FROM information_schema.KEY_COLUMN_USAGE
1712
- WHERE TABLE_SCHEMA = :p1 AND REFERENCED_TABLE_NAME IS NOT NULL
1713
- AND REFERENCED_TABLE_SCHEMA = :p1
1714
- ORDER BY CONSTRAINT_NAME, ORDINAL_POSITION`, [schema]));
1715
- const fkByConstraint = new Map();
1710
+ const fkRows = (await exec(`SELECT k.TABLE_NAME, k.COLUMN_NAME, k.REFERENCED_TABLE_SCHEMA, k.REFERENCED_TABLE_NAME, k.REFERENCED_COLUMN_NAME,
1711
+ k.CONSTRAINT_NAME, k.ORDINAL_POSITION, r.UPDATE_RULE, r.DELETE_RULE
1712
+ FROM information_schema.KEY_COLUMN_USAGE k
1713
+ LEFT JOIN information_schema.REFERENTIAL_CONSTRAINTS r
1714
+ ON r.CONSTRAINT_SCHEMA = k.CONSTRAINT_SCHEMA AND r.CONSTRAINT_NAME = k.CONSTRAINT_NAME AND r.TABLE_NAME = k.TABLE_NAME
1715
+ WHERE k.TABLE_SCHEMA = :p1 AND k.REFERENCED_TABLE_NAME IS NOT NULL
1716
+ AND k.REFERENCED_TABLE_SCHEMA = :p1
1717
+ ORDER BY k.CONSTRAINT_NAME, k.ORDINAL_POSITION`, [schema]));
1718
+ const fkByTable = new Map();
1716
1719
  for (const r of fkRows) {
1717
1720
  if (!tableSet.has(r.TABLE_NAME))
1718
1721
  continue;
1719
1722
  if (r.REFERENCED_TABLE_SCHEMA !== undefined && r.REFERENCED_TABLE_SCHEMA !== schema)
1720
1723
  continue;
1721
- const key = JSON.stringify([r.TABLE_NAME, r.CONSTRAINT_NAME]);
1722
- let entry = fkByConstraint.get(key);
1724
+ if (!fkByTable.has(r.TABLE_NAME))
1725
+ fkByTable.set(r.TABLE_NAME, new Map());
1726
+ const table = fkByTable.get(r.TABLE_NAME);
1727
+ let entry = table.get(r.CONSTRAINT_NAME);
1723
1728
  if (!entry) {
1724
1729
  entry = {
1725
1730
  sourceTable: r.TABLE_NAME,
@@ -1727,13 +1732,46 @@ export async function introspectMysqlWith(exec, schema, options = {}) {
1727
1732
  targetTable: r.REFERENCED_TABLE_NAME,
1728
1733
  targetColumns: [],
1729
1734
  constraintName: r.CONSTRAINT_NAME,
1735
+ actions: {
1736
+ onDelete: referentialActionFromCatalog(r.DELETE_RULE),
1737
+ onUpdate: referentialActionFromCatalog(r.UPDATE_RULE),
1738
+ },
1730
1739
  };
1731
- fkByConstraint.set(key, entry);
1740
+ table.set(r.CONSTRAINT_NAME, entry);
1732
1741
  }
1733
1742
  entry.sourceColumns.push(r.COLUMN_NAME);
1734
1743
  entry.targetColumns.push(r.REFERENCED_COLUMN_NAME);
1735
1744
  }
1736
- const foreignKeys = [...fkByConstraint.values()].filter((fk) => tableSet.has(fk.targetTable));
1745
+ // Relation naming reads a composite FK's constraint name, so each key takes
1746
+ // the name PostgreSQL gives the same declarations. A name InnoDB generated,
1747
+ // `<table>_ibfk_<n>`, numbers the unnamed keys in declaration order (the
1748
+ // catalog lists `_ibfk_10` before `_ibfk_2`), and each takes PostgreSQL's
1749
+ // default in that order. The catalog cannot tell an explicit name in that
1750
+ // form from a generated one, so it reads as generated.
1751
+ //
1752
+ // A default also avoids the table's other constraint names. MySQL lists a
1753
+ // UNIQUE index here exactly as a UNIQUE constraint, so both are reserved
1754
+ // (PostgreSQL would not consult an index); a primary key is always `PRIMARY`.
1755
+ const reserved = new Map();
1756
+ for (const r of (await exec(`SELECT TABLE_NAME, CONSTRAINT_NAME FROM information_schema.TABLE_CONSTRAINTS
1757
+ WHERE TABLE_SCHEMA = :p1 AND CONSTRAINT_TYPE IN ('UNIQUE', 'CHECK')`, [schema]))) {
1758
+ reserved.set(r.TABLE_NAME, [...(reserved.get(r.TABLE_NAME) ?? []), r.CONSTRAINT_NAME]);
1759
+ }
1760
+ const constraintNames = new Set();
1761
+ const foreignKeys = [];
1762
+ for (const [table, entries] of [...fkByTable].sort(([a], [b]) => compareCatalogNames(a, b))) {
1763
+ const keys = [...entries.values()].map((fk) => {
1764
+ const n = fk.constraintName.slice(table.length + 6);
1765
+ return { fk, n: fk.constraintName.startsWith(`${table}_ibfk_`) && /^\d+$/.test(n) ? Number(n) : -1 };
1766
+ });
1767
+ keys.sort((a, b) => a.n - b.n);
1768
+ const names = foreignKeyConstraintNames(table, keys.map(({ fk, n }) => ({ columns: fk.sourceColumns, name: n < 0 ? fk.constraintName : undefined })), constraintNames, reserved.get(table));
1769
+ keys.forEach(({ fk }, i) => {
1770
+ fk.constraintName = names[i];
1771
+ if (tableSet.has(fk.targetTable))
1772
+ foreignKeys.push(fk);
1773
+ });
1774
+ }
1737
1775
  // ----- Indexes + unique constraints -----
1738
1776
  const idxRows = (await exec(`SELECT TABLE_NAME, INDEX_NAME, NON_UNIQUE, COLUMN_NAME, SEQ_IN_INDEX,
1739
1777
  SUB_PART, EXPRESSION, COLLATION, INDEX_TYPE, IS_VISIBLE, INDEX_COMMENT
@@ -1794,11 +1832,19 @@ export async function introspectMysqlWith(exec, schema, options = {}) {
1794
1832
  // PostgreSQL names it (`users.profile`): the child's columns are exactly its
1795
1833
  // primary key or a unique key, and each column pair compares the way the
1796
1834
  // enforced key does.
1797
- const relationsByTable = buildRelationsFromForeignKeys(tableNames, foreignKeys, pkByTable, columnsByTable, options.logger, options.legacyToManyUniques
1798
- ? undefined
1799
- : (fk) => fk.sourceColumns.length === fk.targetColumns.length &&
1800
- fk.sourceColumns.every((name, i) => mysqlSameKeyEquality(nativeColumns.get(JSON.stringify([fk.sourceTable, name])), nativeColumns.get(JSON.stringify([fk.targetTable, fk.targetColumns[i]])))) &&
1801
- [pkByTable.get(fk.sourceTable) ?? [], ...(uniqueByTable.get(fk.sourceTable) ?? [])].some((key) => key.length === fk.sourceColumns.length && key.every((name) => fk.sourceColumns.includes(name))));
1835
+ const relationsByTable = buildRelationsFromForeignKeys({
1836
+ tableNames,
1837
+ foreignKeys,
1838
+ pkByTable,
1839
+ columnsByTable,
1840
+ uniqueKeysByTable: new Map(tableNames.map((table) => [table, [pkByTable.get(table) ?? [], ...(uniqueByTable.get(table) ?? [])]])),
1841
+ // A unique key proves a to-one only when the join compares like the key.
1842
+ sameKeyComparison: (fk) => fk.sourceColumns.length === fk.targetColumns.length &&
1843
+ fk.sourceColumns.every((name, i) => mysqlSameKeyEquality(nativeColumns.get(JSON.stringify([fk.sourceTable, name])), nativeColumns.get(JSON.stringify([fk.targetTable, fk.targetColumns[i]])))),
1844
+ junctionKeysByTable: new Map(Array.from(uniqueByTable, ([table, keys]) => [table, keys.filter((key) => key.length === 2)])),
1845
+ ...(options.legacyToManyUniques ? { legacyToManyUniques: true } : {}),
1846
+ ...(options.logger ? { logger: options.logger } : {}),
1847
+ });
1802
1848
  // ----- Assemble TableMetadata -----
1803
1849
  const tables = nullRecord();
1804
1850
  for (const tableName of tableNames) {