turbine-orm 0.94.0 → 0.95.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/catalog-metadata.d.ts +182 -32
- package/dist/catalog-metadata.js +232 -57
- package/dist/cjs/catalog-metadata.d.ts +182 -32
- package/dist/cjs/catalog-metadata.js +239 -59
- package/dist/cjs/d1/catalog-metadata.js +30 -19
- package/dist/cjs/introspect.d.ts +4 -5
- package/dist/cjs/introspect.js +34 -33
- package/dist/cjs/libsql/introspect.js +30 -19
- package/dist/cjs/mssql.js +83 -29
- package/dist/cjs/mysql.js +69 -23
- package/dist/cjs/schema-metadata.d.ts +5 -4
- package/dist/cjs/schema-metadata.js +76 -60
- package/dist/cjs/sqlite-constraint-names.d.ts +65 -0
- package/dist/cjs/sqlite-constraint-names.js +264 -0
- package/dist/cjs/sqlite.js +34 -14
- package/dist/d1/catalog-metadata.js +31 -20
- package/dist/introspect.d.ts +4 -5
- package/dist/introspect.js +29 -33
- package/dist/libsql/introspect.js +31 -20
- package/dist/mssql.js +84 -30
- package/dist/mysql.js +70 -24
- package/dist/schema-metadata.d.ts +5 -4
- package/dist/schema-metadata.js +77 -61
- package/dist/sqlite-constraint-names.d.ts +65 -0
- package/dist/sqlite-constraint-names.js +257 -0
- package/dist/sqlite.js +35 -15
- package/package.json +1 -1
|
@@ -5,6 +5,7 @@ exports.d1CatalogMetadata = d1CatalogMetadata;
|
|
|
5
5
|
const catalog_metadata_js_1 = require("../catalog-metadata.js");
|
|
6
6
|
const errors_js_1 = require("../errors.js");
|
|
7
7
|
const schema_js_1 = require("../schema.js");
|
|
8
|
+
const sqlite_constraint_names_js_1 = require("../sqlite-constraint-names.js");
|
|
8
9
|
const catalog_js_1 = require("./catalog.js");
|
|
9
10
|
const sqlite_dialect_js_1 = require("./sqlite-dialect.js");
|
|
10
11
|
/** Native D1 INTEGER results are numbers. Decimal affinity may retain nonnumeric TEXT. */
|
|
@@ -13,7 +14,6 @@ function d1ColumnType(declared, nullable) {
|
|
|
13
14
|
return nullable ? 'number | string | null' : 'number | string';
|
|
14
15
|
return (0, sqlite_dialect_js_1.sqliteTypeToTs)(declared, nullable);
|
|
15
16
|
}
|
|
16
|
-
const sqliteName = (name) => name.replace(/[A-Z]/g, (letter) => letter.toLowerCase());
|
|
17
17
|
function isSqliteDateType(type) {
|
|
18
18
|
return (0, schema_js_1.isDateType)(type.toLowerCase()) || /(timestamp|datetime|date)/i.test(type);
|
|
19
19
|
}
|
|
@@ -42,6 +42,7 @@ function d1CatalogMetadata(snapshot, options) {
|
|
|
42
42
|
const relationUniqueByTable = new Map();
|
|
43
43
|
const indexesByTable = new Map();
|
|
44
44
|
const foreignKeys = [];
|
|
45
|
+
const constraintNames = new Set();
|
|
45
46
|
for (const tableName of tableNames) {
|
|
46
47
|
// ----- Columns + primary key -----
|
|
47
48
|
// table_xinfo also exposes computed columns (hidden = 2/3). Virtual-table
|
|
@@ -94,9 +95,13 @@ function d1CatalogMetadata(snapshot, options) {
|
|
|
94
95
|
entry = {
|
|
95
96
|
sourceTable: tableName,
|
|
96
97
|
sourceColumns: [],
|
|
97
|
-
targetTable:
|
|
98
|
+
targetTable: (0, sqlite_constraint_names_js_1.sqliteCatalogName)(tableNames, fk.table) ?? fk.table,
|
|
98
99
|
targetColumns: [],
|
|
99
|
-
constraintName:
|
|
100
|
+
constraintName: '',
|
|
101
|
+
actions: {
|
|
102
|
+
onDelete: (0, catalog_metadata_js_1.referentialActionFromCatalog)(fk.on_delete),
|
|
103
|
+
onUpdate: (0, catalog_metadata_js_1.referentialActionFromCatalog)(fk.on_update),
|
|
104
|
+
},
|
|
100
105
|
};
|
|
101
106
|
fkById.set(fk.id, entry);
|
|
102
107
|
}
|
|
@@ -105,6 +110,10 @@ function d1CatalogMetadata(snapshot, options) {
|
|
|
105
110
|
if (fk.to !== null)
|
|
106
111
|
entry.targetColumns.push(fk.to);
|
|
107
112
|
}
|
|
113
|
+
// SQLite's catalog names no constraint, and relation naming reads the name
|
|
114
|
+
// for a composite FK: take it from the CREATE TABLE text, else the name
|
|
115
|
+
// PostgreSQL would give it.
|
|
116
|
+
(0, sqlite_constraint_names_js_1.nameSqliteForeignKeys)(tableName, tableDefinitions.get(tableName) ?? '', [...fkById.values()], constraintNames);
|
|
108
117
|
for (const entry of fkById.values()) {
|
|
109
118
|
if (!tableSet.has(entry.targetTable))
|
|
110
119
|
continue;
|
|
@@ -162,25 +171,27 @@ function d1CatalogMetadata(snapshot, options) {
|
|
|
162
171
|
}
|
|
163
172
|
// SQLite resolves FK identifiers with ASCII case folding. Preserve the actual
|
|
164
173
|
// catalog spelling in metadata and refuse unresolved in-scope references.
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
if (!column)
|
|
169
|
-
throw new errors_js_1.ValidationError(`Unresolvable D1 foreign key: ${(0, catalog_metadata_js_1.printableCatalogName)(fk.constraintName)}.`);
|
|
170
|
-
return column.name;
|
|
171
|
-
};
|
|
172
|
-
fk.sourceColumns = fk.sourceColumns.map((name) => resolve(fk.sourceTable, name));
|
|
173
|
-
fk.targetColumns = fk.targetColumns.map((name) => resolve(fk.targetTable, name));
|
|
174
|
-
}
|
|
174
|
+
const [unresolved] = (0, sqlite_constraint_names_js_1.canonicalSqliteForeignKeyColumns)(foreignKeys, (table) => columnsByTable.get(table));
|
|
175
|
+
if (unresolved)
|
|
176
|
+
throw new errors_js_1.ValidationError(`Unresolvable D1 foreign key: ${(0, catalog_metadata_js_1.printableCatalogName)(unresolved.constraintName)}.`);
|
|
175
177
|
// ----- Build relations from foreign keys (belongsTo + hasMany + m2m) -----
|
|
176
|
-
//
|
|
177
|
-
//
|
|
178
|
-
//
|
|
178
|
+
// The ONE relation derivation every engine calls, with SQLite's own facts:
|
|
179
|
+
// its unique keys, and when a foreign key compares the way its key does. A
|
|
180
|
+
// to-one is decided per foreign key before naming, so it is named as
|
|
181
|
+
// PostgreSQL names it (`users.profile`).
|
|
179
182
|
for (const [tableName, cols] of columnsByTable)
|
|
180
183
|
(0, catalog_metadata_js_1.assertDistinctColumnFields)(tableName, cols);
|
|
181
|
-
const relationsByTable = (0, catalog_metadata_js_1.
|
|
182
|
-
|
|
183
|
-
|
|
184
|
+
const relationsByTable = (0, catalog_metadata_js_1.deriveRelations)({
|
|
185
|
+
tableNames,
|
|
186
|
+
foreignKeys,
|
|
187
|
+
pkByTable,
|
|
188
|
+
columnsByTable,
|
|
189
|
+
uniqueKeysByTable: relationUniqueByTable,
|
|
190
|
+
sameKeyComparison: (0, catalog_metadata_js_1.sqliteKeyComparison)(columnsByTable, tableDefinitions, tableFlags),
|
|
191
|
+
junctionKeysByTable: new Map(Array.from(uniqueByTable, ([table, keys]) => [table, keys.filter((key) => key.length === 2)])),
|
|
192
|
+
...(options.legacyToManyUniques ? { legacyToManyUniques: true } : {}),
|
|
193
|
+
...(options.logger ? { logger: options.logger } : {}),
|
|
194
|
+
});
|
|
184
195
|
// ----- Assemble TableMetadata -----
|
|
185
196
|
const tables = (0, catalog_metadata_js_1.nullRecord)();
|
|
186
197
|
for (const tableName of tableNames) {
|
package/dist/cjs/introspect.d.ts
CHANGED
|
@@ -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,
|
|
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
|
-
*
|
|
213
|
-
*
|
|
214
|
-
*
|
|
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>>;
|
package/dist/cjs/introspect.js
CHANGED
|
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.relationNameFromColumn = exports.printableCatalogName = exports.nullRecord = exports.isUnknownTsType = exports.
|
|
6
|
+
exports.sqliteKeyComparison = exports.relationNameFromColumn = exports.referentialActionFromCatalog = exports.printableCatalogName = exports.nullRecord = exports.isUnknownTsType = exports.foreignKeyConstraintNames = exports.deriveRelations = exports.defaultForeignKeyConstraintName = exports.defaultExcludedTablesPresent = exports.DEFAULT_EXCLUDED_TABLES = exports.compareCatalogNames = exports.buildRelationsFromForeignKeys = exports.assertSafeCatalogSchema = exports.assertSafeCatalogIdentifier = exports.assertDistinctColumnFields = exports.applyTableFilters = exports.applyRelationRenames = exports.addAutoManyToManyRelations = void 0;
|
|
7
7
|
exports.pgConfActionToReferential = pgConfActionToReferential;
|
|
8
8
|
exports.introspect = introspect;
|
|
9
9
|
exports.introspectPostgresCatalog = introspectPostgresCatalog;
|
|
@@ -24,13 +24,18 @@ Object.defineProperty(exports, "assertDistinctColumnFields", { enumerable: true,
|
|
|
24
24
|
Object.defineProperty(exports, "assertSafeCatalogIdentifier", { enumerable: true, get: function () { return catalog_metadata_js_2.assertSafeCatalogIdentifier; } });
|
|
25
25
|
Object.defineProperty(exports, "assertSafeCatalogSchema", { enumerable: true, get: function () { return catalog_metadata_js_2.assertSafeCatalogSchema; } });
|
|
26
26
|
Object.defineProperty(exports, "buildRelationsFromForeignKeys", { enumerable: true, get: function () { return catalog_metadata_js_2.buildRelationsFromForeignKeys; } });
|
|
27
|
+
Object.defineProperty(exports, "compareCatalogNames", { enumerable: true, get: function () { return catalog_metadata_js_2.compareCatalogNames; } });
|
|
27
28
|
Object.defineProperty(exports, "DEFAULT_EXCLUDED_TABLES", { enumerable: true, get: function () { return catalog_metadata_js_2.DEFAULT_EXCLUDED_TABLES; } });
|
|
28
29
|
Object.defineProperty(exports, "defaultExcludedTablesPresent", { enumerable: true, get: function () { return catalog_metadata_js_2.defaultExcludedTablesPresent; } });
|
|
29
|
-
Object.defineProperty(exports, "
|
|
30
|
+
Object.defineProperty(exports, "defaultForeignKeyConstraintName", { enumerable: true, get: function () { return catalog_metadata_js_2.defaultForeignKeyConstraintName; } });
|
|
31
|
+
Object.defineProperty(exports, "deriveRelations", { enumerable: true, get: function () { return catalog_metadata_js_2.deriveRelations; } });
|
|
32
|
+
Object.defineProperty(exports, "foreignKeyConstraintNames", { enumerable: true, get: function () { return catalog_metadata_js_2.foreignKeyConstraintNames; } });
|
|
30
33
|
Object.defineProperty(exports, "isUnknownTsType", { enumerable: true, get: function () { return catalog_metadata_js_2.isUnknownTsType; } });
|
|
31
34
|
Object.defineProperty(exports, "nullRecord", { enumerable: true, get: function () { return catalog_metadata_js_2.nullRecord; } });
|
|
32
35
|
Object.defineProperty(exports, "printableCatalogName", { enumerable: true, get: function () { return catalog_metadata_js_2.printableCatalogName; } });
|
|
36
|
+
Object.defineProperty(exports, "referentialActionFromCatalog", { enumerable: true, get: function () { return catalog_metadata_js_2.referentialActionFromCatalog; } });
|
|
33
37
|
Object.defineProperty(exports, "relationNameFromColumn", { enumerable: true, get: function () { return catalog_metadata_js_2.relationNameFromColumn; } });
|
|
38
|
+
Object.defineProperty(exports, "sqliteKeyComparison", { enumerable: true, get: function () { return catalog_metadata_js_2.sqliteKeyComparison; } });
|
|
34
39
|
/**
|
|
35
40
|
* turbine-orm, Schema introspection
|
|
36
41
|
*
|
|
@@ -543,10 +548,9 @@ async function introspectPostgresCatalog(options) {
|
|
|
543
548
|
`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 });
|
|
544
549
|
}
|
|
545
550
|
// Referential actions (ON DELETE / ON UPDATE) per constraint. Keyed
|
|
546
|
-
// "<table>::<constraint>" because the NAME alone is not unique
|
|
547
|
-
// collision SQL_FOREIGN_KEYS documents);
|
|
548
|
-
//
|
|
549
|
-
// the map from a code-first schema, where names are synthesized per table.
|
|
551
|
+
// "<table>::<constraint>" because the NAME alone is not unique across
|
|
552
|
+
// tables (the same collision SQL_FOREIGN_KEYS documents); PostgreSQL keeps
|
|
553
|
+
// it unique within one table.
|
|
550
554
|
const fkActions = new Map();
|
|
551
555
|
for (const row of fkResult.rows) {
|
|
552
556
|
fkActions.set(`${row.source_table}::${row.constraint_name}`, {
|
|
@@ -795,30 +799,11 @@ function detectUniqueForeignKeySets(pkByTable, uniqueByTable, indexesByTable) {
|
|
|
795
799
|
* losing every auto-m2m relation through a Prisma-style PK-less junction. Adding
|
|
796
800
|
* an argument here reaches both surfaces or neither.
|
|
797
801
|
*
|
|
798
|
-
*
|
|
799
|
-
*
|
|
800
|
-
*
|
|
801
|
-
* differences between the two are listed in docs/relation-names.md.
|
|
802
|
+
* It is the PostgreSQL catalog's adapter onto {@link deriveRelations}, the one
|
|
803
|
+
* derivation every engine introspector and `schemaDefToMetadata` also call, so
|
|
804
|
+
* the same schema derives the same relations on every engine.
|
|
802
805
|
*/
|
|
803
806
|
function deriveCatalogRelations(inputs) {
|
|
804
|
-
const { tableNames, foreignKeys, pkByTable, columnsByTable, uniqueByTable, indexesByTable, enums } = inputs;
|
|
805
|
-
const columnFieldsByTable = new Map();
|
|
806
|
-
const unknownTypedFieldsByTable = new Map();
|
|
807
|
-
for (const [tbl, cols] of columnsByTable) {
|
|
808
|
-
columnFieldsByTable.set(tbl, new Set(cols.map((c) => c.field)));
|
|
809
|
-
// Enum-typed columns also report tsType 'unknown' here, but generate.ts
|
|
810
|
-
// gives them a concrete union type, so a shadow of one is type-broken and
|
|
811
|
-
// must NOT be preserved as a historical json/jsonb shadow.
|
|
812
|
-
unknownTypedFieldsByTable.set(tbl, new Set(cols.filter((c) => (0, catalog_metadata_js_1.isUnknownTsType)(c.tsType) && !Object.hasOwn(enums, c.pgType)).map((c) => c.field)));
|
|
813
|
-
}
|
|
814
|
-
// Unless the caller opts out, detect child FK column sets that a unique
|
|
815
|
-
// constraint / plain unique index exactly covers, so the reverse relation is
|
|
816
|
-
// emitted as a one-to-one (`hasOne`) instead of `hasMany`.
|
|
817
|
-
const uniqueSetsByTable = inputs.legacyToManyUniques
|
|
818
|
-
? undefined
|
|
819
|
-
: detectUniqueForeignKeySets(pkByTable, uniqueByTable, indexesByTable);
|
|
820
|
-
const logger = inputs.logger ?? logger_js_1.consoleLogger;
|
|
821
|
-
const relationsByTable = (0, catalog_metadata_js_1.buildRelationsFromForeignKeys)(foreignKeys, columnFieldsByTable, inputs.fkActions, unknownTypedFieldsByTable, uniqueSetsByTable, logger);
|
|
822
807
|
// Prisma's implicit m2m junctions have no primary key (just a two-column
|
|
823
808
|
// UNIQUE index over the FK columns), so pass the introspected two-column
|
|
824
809
|
// unique indexes as the fallback junction-key source.
|
|
@@ -831,8 +816,8 @@ function deriveCatalogRelations(inputs) {
|
|
|
831
816
|
// soft-deleted junction, constrains only the rows matching its predicate. A
|
|
832
817
|
// manyToMany derived from either returns duplicate rows. The metadata flags
|
|
833
818
|
// are honoured too, so a caller-supplied `partial: true` still refuses.
|
|
834
|
-
const
|
|
835
|
-
for (const [tbl, idxs] of indexesByTable) {
|
|
819
|
+
const junctionKeysByTable = new Map();
|
|
820
|
+
for (const [tbl, idxs] of inputs.indexesByTable) {
|
|
836
821
|
const twoColUniques = idxs.flatMap((idx) => {
|
|
837
822
|
const read = indexMetadataFromDefinition(idx.name, idx.definition);
|
|
838
823
|
return idx.unique && !idx.partial && read.unique && !read.partial && read.columns.length === 2
|
|
@@ -840,8 +825,24 @@ function deriveCatalogRelations(inputs) {
|
|
|
840
825
|
: [];
|
|
841
826
|
});
|
|
842
827
|
if (twoColUniques.length > 0)
|
|
843
|
-
|
|
828
|
+
junctionKeysByTable.set(tbl, twoColUniques);
|
|
844
829
|
}
|
|
845
|
-
(0, catalog_metadata_js_1.
|
|
846
|
-
|
|
830
|
+
return (0, catalog_metadata_js_1.deriveRelations)({
|
|
831
|
+
tableNames: inputs.tableNames,
|
|
832
|
+
foreignKeys: inputs.foreignKeys,
|
|
833
|
+
pkByTable: inputs.pkByTable,
|
|
834
|
+
columnsByTable: inputs.columnsByTable,
|
|
835
|
+
enums: inputs.enums,
|
|
836
|
+
// A child FK column set that a unique constraint / plain unique index
|
|
837
|
+
// exactly covers makes the reverse relation a one-to-one (`hasOne`).
|
|
838
|
+
uniqueKeysByTable: detectUniqueForeignKeySets(inputs.pkByTable, inputs.uniqueByTable, inputs.indexesByTable),
|
|
839
|
+
junctionKeysByTable,
|
|
840
|
+
// Both catalog readers (this module and the MCP server) already order
|
|
841
|
+
// tables and foreign keys (see SQL_FOREIGN_KEYS), and that order is the
|
|
842
|
+
// reference the other engines sort to.
|
|
843
|
+
inCatalogOrder: true,
|
|
844
|
+
...(inputs.fkActions ? { fkActions: inputs.fkActions } : {}),
|
|
845
|
+
...(inputs.legacyToManyUniques ? { legacyToManyUniques: true } : {}),
|
|
846
|
+
...(inputs.logger ? { logger: inputs.logger } : {}),
|
|
847
|
+
});
|
|
847
848
|
}
|
|
@@ -10,6 +10,7 @@ const sqlite_dialect_js_1 = require("../d1/sqlite-dialect.js");
|
|
|
10
10
|
const errors_js_1 = require("../errors.js");
|
|
11
11
|
const optional_peer_import_cjs_1 = __importDefault(require("../optional-peer-import.cjs"));
|
|
12
12
|
const schema_js_1 = require("../schema.js");
|
|
13
|
+
const sqlite_constraint_names_js_1 = require("../sqlite-constraint-names.js");
|
|
13
14
|
const pool_js_1 = require("./pool.js");
|
|
14
15
|
const values_js_1 = require("./values.js");
|
|
15
16
|
const optionKeys = new Set([
|
|
@@ -82,7 +83,6 @@ async function catalog(client, sql, args) {
|
|
|
82
83
|
// native row decoder. Identifiers are quoted; query values use native binds.
|
|
83
84
|
return (0, values_js_1.rows)(await client.execute({ sql, args }));
|
|
84
85
|
}
|
|
85
|
-
const sqliteName = (name) => name.replace(/[A-Z]/g, (letter) => letter.toLowerCase());
|
|
86
86
|
const q = (name) => `"${name.replace(/"/g, '""')}"`;
|
|
87
87
|
function isSqliteDateType(type) {
|
|
88
88
|
return (0, schema_js_1.isDateType)(type.toLowerCase()) || /(timestamp|datetime|date)/i.test(type);
|
|
@@ -111,6 +111,7 @@ async function readCatalog(client, options) {
|
|
|
111
111
|
const relationUniqueByTable = new Map();
|
|
112
112
|
const indexesByTable = new Map();
|
|
113
113
|
const foreignKeys = [];
|
|
114
|
+
const constraintNames = new Set();
|
|
114
115
|
for (const tableName of tableNames) {
|
|
115
116
|
// ----- Columns + primary key -----
|
|
116
117
|
// table_xinfo also exposes computed columns (hidden = 2/3). Virtual-table
|
|
@@ -163,9 +164,13 @@ async function readCatalog(client, options) {
|
|
|
163
164
|
entry = {
|
|
164
165
|
sourceTable: tableName,
|
|
165
166
|
sourceColumns: [],
|
|
166
|
-
targetTable:
|
|
167
|
+
targetTable: (0, sqlite_constraint_names_js_1.sqliteCatalogName)(tableNames, fk.table) ?? fk.table,
|
|
167
168
|
targetColumns: [],
|
|
168
|
-
constraintName:
|
|
169
|
+
constraintName: '',
|
|
170
|
+
actions: {
|
|
171
|
+
onDelete: (0, catalog_metadata_js_1.referentialActionFromCatalog)(fk.on_delete),
|
|
172
|
+
onUpdate: (0, catalog_metadata_js_1.referentialActionFromCatalog)(fk.on_update),
|
|
173
|
+
},
|
|
169
174
|
};
|
|
170
175
|
fkById.set(fk.id, entry);
|
|
171
176
|
}
|
|
@@ -174,6 +179,10 @@ async function readCatalog(client, options) {
|
|
|
174
179
|
if (fk.to !== null)
|
|
175
180
|
entry.targetColumns.push(fk.to);
|
|
176
181
|
}
|
|
182
|
+
// SQLite's catalog names no constraint, and relation naming reads the name
|
|
183
|
+
// for a composite FK: take it from the CREATE TABLE text, else the name
|
|
184
|
+
// PostgreSQL would give it.
|
|
185
|
+
(0, sqlite_constraint_names_js_1.nameSqliteForeignKeys)(tableName, tableDefinitions.get(tableName) ?? '', [...fkById.values()], constraintNames);
|
|
177
186
|
for (const entry of fkById.values()) {
|
|
178
187
|
if (entry.targetColumns.length === 0) {
|
|
179
188
|
// Implicit reference → the target table's primary key.
|
|
@@ -229,25 +238,27 @@ async function readCatalog(client, options) {
|
|
|
229
238
|
}
|
|
230
239
|
// SQLite resolves FK identifiers with ASCII case folding. Preserve the actual
|
|
231
240
|
// catalog spelling in metadata and refuse unresolved in-scope references.
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
if (!column)
|
|
236
|
-
throw new errors_js_1.ValidationError(`Unresolvable local libSQL foreign key: ${(0, catalog_metadata_js_1.printableCatalogName)(fk.constraintName)}.`);
|
|
237
|
-
return column.name;
|
|
238
|
-
};
|
|
239
|
-
fk.sourceColumns = fk.sourceColumns.map((name) => resolve(fk.sourceTable, name));
|
|
240
|
-
fk.targetColumns = fk.targetColumns.map((name) => resolve(fk.targetTable, name));
|
|
241
|
-
}
|
|
241
|
+
const [unresolved] = (0, sqlite_constraint_names_js_1.canonicalSqliteForeignKeyColumns)(foreignKeys, (table) => columnsByTable.get(table));
|
|
242
|
+
if (unresolved)
|
|
243
|
+
throw new errors_js_1.ValidationError(`Unresolvable local libSQL foreign key: ${(0, catalog_metadata_js_1.printableCatalogName)(unresolved.constraintName)}.`);
|
|
242
244
|
// ----- Build relations from foreign keys (belongsTo + hasMany + m2m) -----
|
|
243
|
-
//
|
|
244
|
-
//
|
|
245
|
-
//
|
|
245
|
+
// The ONE relation derivation every engine calls, with SQLite's own facts:
|
|
246
|
+
// its unique keys, and when a foreign key compares the way its key does. A
|
|
247
|
+
// to-one is decided per foreign key before naming, so it is named as
|
|
248
|
+
// PostgreSQL names it (`users.profile`).
|
|
246
249
|
for (const [tableName, cols] of columnsByTable)
|
|
247
250
|
(0, catalog_metadata_js_1.assertDistinctColumnFields)(tableName, cols);
|
|
248
|
-
const relationsByTable = (0, catalog_metadata_js_1.
|
|
249
|
-
|
|
250
|
-
|
|
251
|
+
const relationsByTable = (0, catalog_metadata_js_1.deriveRelations)({
|
|
252
|
+
tableNames,
|
|
253
|
+
foreignKeys,
|
|
254
|
+
pkByTable,
|
|
255
|
+
columnsByTable,
|
|
256
|
+
uniqueKeysByTable: relationUniqueByTable,
|
|
257
|
+
sameKeyComparison: (0, catalog_metadata_js_1.sqliteKeyComparison)(columnsByTable, tableDefinitions, tableFlags),
|
|
258
|
+
junctionKeysByTable: new Map(Array.from(uniqueByTable, ([table, keys]) => [table, keys.filter((key) => key.length === 2)])),
|
|
259
|
+
...(options.legacyToManyUniques ? { legacyToManyUniques: true } : {}),
|
|
260
|
+
...(options.logger ? { logger: options.logger } : {}),
|
|
261
|
+
});
|
|
251
262
|
// ----- Assemble TableMetadata -----
|
|
252
263
|
const tables = (0, catalog_metadata_js_1.nullRecord)();
|
|
253
264
|
for (const tableName of tableNames) {
|
package/dist/cjs/mssql.js
CHANGED
|
@@ -1549,15 +1549,14 @@ const num = (v) => (typeof v === 'string' ? Number(v) : (v ?? 0));
|
|
|
1549
1549
|
*/
|
|
1550
1550
|
const bitIsTrue = (v) => v === true || v === 1 || v === '1' || v === 'true';
|
|
1551
1551
|
/**
|
|
1552
|
-
* Derive relations
|
|
1553
|
-
* (`
|
|
1554
|
-
* `
|
|
1555
|
-
*
|
|
1556
|
-
*
|
|
1557
|
-
* collision resolution against scalar column fields included.
|
|
1552
|
+
* Derive relations through the ONE relation derivation every engine calls
|
|
1553
|
+
* (`deriveRelations` in catalog-metadata.ts), so this engine derives the
|
|
1554
|
+
* relations `turbine generate` derives against PostgreSQL for the same schema.
|
|
1555
|
+
* SQL Server contributes its own facts: its unique keys, when a key's
|
|
1556
|
+
* comparison semantics match the join's, and its referential actions.
|
|
1558
1557
|
*/
|
|
1559
|
-
function buildRelationsFromForeignKeys(
|
|
1560
|
-
return (0, introspect_js_1.
|
|
1558
|
+
function buildRelationsFromForeignKeys(facts) {
|
|
1559
|
+
return (0, introspect_js_1.deriveRelations)(facts);
|
|
1561
1560
|
}
|
|
1562
1561
|
/**
|
|
1563
1562
|
* Introspect a SQL Server database into the same {@link SchemaMetadata} shape the
|
|
@@ -1679,7 +1678,10 @@ async function introspectMssqlWith(exec, schema = 'dbo', options = {}) {
|
|
|
1679
1678
|
cpt.name AS REFERENCED_COLUMN_NAME,
|
|
1680
1679
|
fkc.constraint_column_id AS ORDINAL_POSITION,
|
|
1681
1680
|
s.name AS TABLE_SCHEMA,
|
|
1682
|
-
rs.name AS REFERENCED_TABLE_SCHEMA
|
|
1681
|
+
rs.name AS REFERENCED_TABLE_SCHEMA,
|
|
1682
|
+
fk.delete_referential_action_desc AS DELETE_RULE,
|
|
1683
|
+
fk.update_referential_action_desc AS UPDATE_RULE,
|
|
1684
|
+
fk.is_system_named AS IS_SYSTEM_NAMED
|
|
1683
1685
|
FROM sys.foreign_keys fk
|
|
1684
1686
|
JOIN sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
|
|
1685
1687
|
JOIN sys.columns cps ON cps.object_id = fkc.parent_object_id AND cps.column_id = fkc.parent_column_id
|
|
@@ -1689,7 +1691,7 @@ async function introspectMssqlWith(exec, schema = 'dbo', options = {}) {
|
|
|
1689
1691
|
JOIN sys.schemas rs ON rs.schema_id = rt.schema_id
|
|
1690
1692
|
WHERE s.name = @p1 AND rs.name = @p1
|
|
1691
1693
|
ORDER BY fk.name, fkc.constraint_column_id`, [schema]);
|
|
1692
|
-
const
|
|
1694
|
+
const fkByTable = new Map();
|
|
1693
1695
|
for (const r of fkRows.sort((a, b) => Number(a.ORDINAL_POSITION) - Number(b.ORDINAL_POSITION))) {
|
|
1694
1696
|
const sourceTable = String(r.TABLE_NAME);
|
|
1695
1697
|
const targetTable = String(r.REFERENCED_TABLE_NAME);
|
|
@@ -1699,16 +1701,64 @@ async function introspectMssqlWith(exec, schema = 'dbo', options = {}) {
|
|
|
1699
1701
|
(r.TABLE_SCHEMA != null && r.REFERENCED_TABLE_SCHEMA != null && r.REFERENCED_TABLE_SCHEMA !== r.TABLE_SCHEMA))
|
|
1700
1702
|
continue;
|
|
1701
1703
|
const constraintName = String(r.CONSTRAINT_NAME);
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1704
|
+
if (!fkByTable.has(sourceTable))
|
|
1705
|
+
fkByTable.set(sourceTable, new Map());
|
|
1706
|
+
const table = fkByTable.get(sourceTable);
|
|
1707
|
+
let key = table.get(constraintName);
|
|
1708
|
+
if (!key) {
|
|
1709
|
+
key = {
|
|
1710
|
+
fk: {
|
|
1711
|
+
sourceTable,
|
|
1712
|
+
sourceColumns: [],
|
|
1713
|
+
targetTable,
|
|
1714
|
+
targetColumns: [],
|
|
1715
|
+
constraintName,
|
|
1716
|
+
actions: {
|
|
1717
|
+
onDelete: (0, introspect_js_1.referentialActionFromCatalog)(r.DELETE_RULE),
|
|
1718
|
+
onUpdate: (0, introspect_js_1.referentialActionFromCatalog)(r.UPDATE_RULE),
|
|
1719
|
+
},
|
|
1720
|
+
},
|
|
1721
|
+
systemNamed: bitIsTrue(r.IS_SYSTEM_NAMED),
|
|
1722
|
+
};
|
|
1723
|
+
table.set(constraintName, key);
|
|
1707
1724
|
}
|
|
1708
|
-
|
|
1709
|
-
|
|
1725
|
+
key.fk.sourceColumns.push(String(r.COLUMN_NAME));
|
|
1726
|
+
key.fk.targetColumns.push(String(r.REFERENCED_COLUMN_NAME));
|
|
1727
|
+
}
|
|
1728
|
+
// Relation naming reads a composite FK's constraint name. A system-named
|
|
1729
|
+
// constraint (`FK__orders__tenan__1A2B3C4D`, with a random suffix) takes the
|
|
1730
|
+
// name PostgreSQL would have given it, so that relation is named the same on
|
|
1731
|
+
// every database and on every engine; an explicit name is reserved first.
|
|
1732
|
+
// SQL Server records no declaration order, so system-named keys are named in
|
|
1733
|
+
// the order of their columns, what they reference and their actions, never
|
|
1734
|
+
// of the suffix. A default also avoids the table's explicit CHECK, PRIMARY
|
|
1735
|
+
// KEY and UNIQUE constraint names, which PostgreSQL creates first.
|
|
1736
|
+
const reserved = new Map();
|
|
1737
|
+
for (const r of await exec(`SELECT OBJECT_NAME(k.parent_object_id) AS TABLE_NAME, k.name AS CONSTRAINT_NAME
|
|
1738
|
+
FROM sys.key_constraints k JOIN sys.schemas s ON s.schema_id = k.schema_id
|
|
1739
|
+
WHERE s.name = @p1 AND k.is_system_named = 0
|
|
1740
|
+
UNION ALL
|
|
1741
|
+
SELECT OBJECT_NAME(c.parent_object_id), c.name
|
|
1742
|
+
FROM sys.check_constraints c JOIN sys.schemas s ON s.schema_id = c.schema_id
|
|
1743
|
+
WHERE s.name = @p1 AND c.is_system_named = 0`, [schema])) {
|
|
1744
|
+
const table = String(r.TABLE_NAME);
|
|
1745
|
+
reserved.set(table, [...(reserved.get(table) ?? []), String(r.CONSTRAINT_NAME)]);
|
|
1746
|
+
}
|
|
1747
|
+
const constraintNames = new Set();
|
|
1748
|
+
const foreignKeys = [];
|
|
1749
|
+
const identity = ({ fk }) => JSON.stringify([fk.sourceColumns, fk.targetTable, fk.targetColumns, fk.actions?.onDelete, fk.actions?.onUpdate]);
|
|
1750
|
+
for (const [table, entries] of [...fkByTable].sort(([a], [b]) => (0, introspect_js_1.compareCatalogNames)(a, b))) {
|
|
1751
|
+
const keys = [...entries.values()].sort((a, b) => Number(a.systemNamed) - Number(b.systemNamed) || (0, introspect_js_1.compareCatalogNames)(identity(a), identity(b)));
|
|
1752
|
+
const names = (0, introspect_js_1.foreignKeyConstraintNames)(table, keys.map(({ fk, systemNamed }) => ({
|
|
1753
|
+
columns: fk.sourceColumns,
|
|
1754
|
+
name: systemNamed ? undefined : fk.constraintName,
|
|
1755
|
+
})), constraintNames, reserved.get(table));
|
|
1756
|
+
keys.forEach(({ fk }, i) => {
|
|
1757
|
+
fk.constraintName = names[i];
|
|
1758
|
+
if (tableSet.has(fk.targetTable))
|
|
1759
|
+
foreignKeys.push(fk);
|
|
1760
|
+
});
|
|
1710
1761
|
}
|
|
1711
|
-
const foreignKeys = [...fkByConstraint.values()].filter((fk) => tableSet.has(fk.targetTable));
|
|
1712
1762
|
// ----- Indexes + unique constraints -----
|
|
1713
1763
|
const idxRows = await exec(`SELECT t.name AS TABLE_NAME, i.name AS INDEX_NAME, i.is_unique AS IS_UNIQUE,
|
|
1714
1764
|
c.name AS COLUMN_NAME, ic.key_ordinal AS SEQ,
|
|
@@ -1812,17 +1862,21 @@ async function introspectMssqlWith(exec, schema = 'dbo', options = {}) {
|
|
|
1812
1862
|
return false;
|
|
1813
1863
|
return ['CHARACTER_MAXIMUM_LENGTH', 'NUMERIC_PRECISION', 'NUMERIC_SCALE', 'DATETIME_PRECISION'].every((fact) => child[fact] === parent[fact]);
|
|
1814
1864
|
};
|
|
1815
|
-
const relationsByTable = buildRelationsFromForeignKeys(
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1865
|
+
const relationsByTable = buildRelationsFromForeignKeys({
|
|
1866
|
+
tableNames,
|
|
1867
|
+
foreignKeys,
|
|
1868
|
+
pkByTable,
|
|
1869
|
+
columnsByTable,
|
|
1870
|
+
uniqueKeysByTable: new Map(tableNames.map((table) => [
|
|
1871
|
+
table,
|
|
1872
|
+
[inactivePrimaryTables.has(table) ? [] : (pkByTable.get(table) ?? []), ...(uniqueByTable.get(table) ?? [])],
|
|
1873
|
+
])),
|
|
1874
|
+
sameKeyComparison: (fk) => fk.sourceColumns.length === fk.targetColumns.length &&
|
|
1875
|
+
fk.sourceColumns.every((name, i) => sameComparison(fk.sourceTable, name, fk.targetTable, fk.targetColumns[i])),
|
|
1876
|
+
junctionKeysByTable: new Map(Array.from(uniqueByTable, ([table, keys]) => [table, keys.filter((key) => key.length === 2)])),
|
|
1877
|
+
...(options.legacyToManyUniques ? { legacyToManyUniques: true } : {}),
|
|
1878
|
+
...(options.logger ? { logger: options.logger } : {}),
|
|
1879
|
+
});
|
|
1826
1880
|
// ----- Assemble TableMetadata -----
|
|
1827
1881
|
const tables = (0, introspect_js_1.nullRecord)();
|
|
1828
1882
|
for (const tableName of tableNames) {
|
package/dist/cjs/mysql.js
CHANGED
|
@@ -1541,15 +1541,15 @@ exports.mysqlDialect = {
|
|
|
1541
1541
|
};
|
|
1542
1542
|
const num = (v) => (typeof v === 'string' ? Number(v) : (v ?? 0));
|
|
1543
1543
|
/**
|
|
1544
|
-
* Derive relations
|
|
1545
|
-
* (`
|
|
1546
|
-
* `
|
|
1547
|
-
*
|
|
1548
|
-
*
|
|
1549
|
-
*
|
|
1544
|
+
* Derive relations through the ONE relation derivation every engine calls
|
|
1545
|
+
* (`deriveRelations` in catalog-metadata.ts), so this engine derives the
|
|
1546
|
+
* relations `turbine generate` derives against PostgreSQL for the same schema.
|
|
1547
|
+
* MySQL contributes its own facts: its unique keys, the column domains under
|
|
1548
|
+
* which a key also enforces the join (`mysqlSameKeyEquality`), and its
|
|
1549
|
+
* referential actions.
|
|
1550
1550
|
*/
|
|
1551
|
-
function buildRelationsFromForeignKeys(
|
|
1552
|
-
return (0, introspect_js_1.
|
|
1551
|
+
function buildRelationsFromForeignKeys(facts) {
|
|
1552
|
+
return (0, introspect_js_1.deriveRelations)(facts);
|
|
1553
1553
|
}
|
|
1554
1554
|
/** Only comparison domains whose native equality also enforces the unique key. */
|
|
1555
1555
|
function mysqlSameKeyEquality(child, parent) {
|
|
@@ -1718,19 +1718,24 @@ async function introspectMysqlWith(exec, schema, options = {}) {
|
|
|
1718
1718
|
pkByTable.get(r.TABLE_NAME).push(r.COLUMN_NAME);
|
|
1719
1719
|
}
|
|
1720
1720
|
// ----- Foreign keys (grouped by constraint for composite FKs) -----
|
|
1721
|
-
const fkRows = (await exec(`SELECT TABLE_NAME, COLUMN_NAME, REFERENCED_TABLE_SCHEMA, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME,
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1721
|
+
const fkRows = (await exec(`SELECT k.TABLE_NAME, k.COLUMN_NAME, k.REFERENCED_TABLE_SCHEMA, k.REFERENCED_TABLE_NAME, k.REFERENCED_COLUMN_NAME,
|
|
1722
|
+
k.CONSTRAINT_NAME, k.ORDINAL_POSITION, r.UPDATE_RULE, r.DELETE_RULE
|
|
1723
|
+
FROM information_schema.KEY_COLUMN_USAGE k
|
|
1724
|
+
LEFT JOIN information_schema.REFERENTIAL_CONSTRAINTS r
|
|
1725
|
+
ON r.CONSTRAINT_SCHEMA = k.CONSTRAINT_SCHEMA AND r.CONSTRAINT_NAME = k.CONSTRAINT_NAME AND r.TABLE_NAME = k.TABLE_NAME
|
|
1726
|
+
WHERE k.TABLE_SCHEMA = :p1 AND k.REFERENCED_TABLE_NAME IS NOT NULL
|
|
1727
|
+
AND k.REFERENCED_TABLE_SCHEMA = :p1
|
|
1728
|
+
ORDER BY k.CONSTRAINT_NAME, k.ORDINAL_POSITION`, [schema]));
|
|
1729
|
+
const fkByTable = new Map();
|
|
1727
1730
|
for (const r of fkRows) {
|
|
1728
1731
|
if (!tableSet.has(r.TABLE_NAME))
|
|
1729
1732
|
continue;
|
|
1730
1733
|
if (r.REFERENCED_TABLE_SCHEMA !== undefined && r.REFERENCED_TABLE_SCHEMA !== schema)
|
|
1731
1734
|
continue;
|
|
1732
|
-
|
|
1733
|
-
|
|
1735
|
+
if (!fkByTable.has(r.TABLE_NAME))
|
|
1736
|
+
fkByTable.set(r.TABLE_NAME, new Map());
|
|
1737
|
+
const table = fkByTable.get(r.TABLE_NAME);
|
|
1738
|
+
let entry = table.get(r.CONSTRAINT_NAME);
|
|
1734
1739
|
if (!entry) {
|
|
1735
1740
|
entry = {
|
|
1736
1741
|
sourceTable: r.TABLE_NAME,
|
|
@@ -1738,13 +1743,46 @@ async function introspectMysqlWith(exec, schema, options = {}) {
|
|
|
1738
1743
|
targetTable: r.REFERENCED_TABLE_NAME,
|
|
1739
1744
|
targetColumns: [],
|
|
1740
1745
|
constraintName: r.CONSTRAINT_NAME,
|
|
1746
|
+
actions: {
|
|
1747
|
+
onDelete: (0, introspect_js_1.referentialActionFromCatalog)(r.DELETE_RULE),
|
|
1748
|
+
onUpdate: (0, introspect_js_1.referentialActionFromCatalog)(r.UPDATE_RULE),
|
|
1749
|
+
},
|
|
1741
1750
|
};
|
|
1742
|
-
|
|
1751
|
+
table.set(r.CONSTRAINT_NAME, entry);
|
|
1743
1752
|
}
|
|
1744
1753
|
entry.sourceColumns.push(r.COLUMN_NAME);
|
|
1745
1754
|
entry.targetColumns.push(r.REFERENCED_COLUMN_NAME);
|
|
1746
1755
|
}
|
|
1747
|
-
|
|
1756
|
+
// Relation naming reads a composite FK's constraint name, so each key takes
|
|
1757
|
+
// the name PostgreSQL gives the same declarations. A name InnoDB generated,
|
|
1758
|
+
// `<table>_ibfk_<n>`, numbers the unnamed keys in declaration order (the
|
|
1759
|
+
// catalog lists `_ibfk_10` before `_ibfk_2`), and each takes PostgreSQL's
|
|
1760
|
+
// default in that order. The catalog cannot tell an explicit name in that
|
|
1761
|
+
// form from a generated one, so it reads as generated.
|
|
1762
|
+
//
|
|
1763
|
+
// A default also avoids the table's other constraint names. MySQL lists a
|
|
1764
|
+
// UNIQUE index here exactly as a UNIQUE constraint, so both are reserved
|
|
1765
|
+
// (PostgreSQL would not consult an index); a primary key is always `PRIMARY`.
|
|
1766
|
+
const reserved = new Map();
|
|
1767
|
+
for (const r of (await exec(`SELECT TABLE_NAME, CONSTRAINT_NAME FROM information_schema.TABLE_CONSTRAINTS
|
|
1768
|
+
WHERE TABLE_SCHEMA = :p1 AND CONSTRAINT_TYPE IN ('UNIQUE', 'CHECK')`, [schema]))) {
|
|
1769
|
+
reserved.set(r.TABLE_NAME, [...(reserved.get(r.TABLE_NAME) ?? []), r.CONSTRAINT_NAME]);
|
|
1770
|
+
}
|
|
1771
|
+
const constraintNames = new Set();
|
|
1772
|
+
const foreignKeys = [];
|
|
1773
|
+
for (const [table, entries] of [...fkByTable].sort(([a], [b]) => (0, introspect_js_1.compareCatalogNames)(a, b))) {
|
|
1774
|
+
const keys = [...entries.values()].map((fk) => {
|
|
1775
|
+
const n = fk.constraintName.slice(table.length + 6);
|
|
1776
|
+
return { fk, n: fk.constraintName.startsWith(`${table}_ibfk_`) && /^\d+$/.test(n) ? Number(n) : -1 };
|
|
1777
|
+
});
|
|
1778
|
+
keys.sort((a, b) => a.n - b.n);
|
|
1779
|
+
const names = (0, introspect_js_1.foreignKeyConstraintNames)(table, keys.map(({ fk, n }) => ({ columns: fk.sourceColumns, name: n < 0 ? fk.constraintName : undefined })), constraintNames, reserved.get(table));
|
|
1780
|
+
keys.forEach(({ fk }, i) => {
|
|
1781
|
+
fk.constraintName = names[i];
|
|
1782
|
+
if (tableSet.has(fk.targetTable))
|
|
1783
|
+
foreignKeys.push(fk);
|
|
1784
|
+
});
|
|
1785
|
+
}
|
|
1748
1786
|
// ----- Indexes + unique constraints -----
|
|
1749
1787
|
const idxRows = (await exec(`SELECT TABLE_NAME, INDEX_NAME, NON_UNIQUE, COLUMN_NAME, SEQ_IN_INDEX,
|
|
1750
1788
|
SUB_PART, EXPRESSION, COLLATION, INDEX_TYPE, IS_VISIBLE, INDEX_COMMENT
|
|
@@ -1805,11 +1843,19 @@ async function introspectMysqlWith(exec, schema, options = {}) {
|
|
|
1805
1843
|
// PostgreSQL names it (`users.profile`): the child's columns are exactly its
|
|
1806
1844
|
// primary key or a unique key, and each column pair compares the way the
|
|
1807
1845
|
// enforced key does.
|
|
1808
|
-
const relationsByTable = buildRelationsFromForeignKeys(
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1846
|
+
const relationsByTable = buildRelationsFromForeignKeys({
|
|
1847
|
+
tableNames,
|
|
1848
|
+
foreignKeys,
|
|
1849
|
+
pkByTable,
|
|
1850
|
+
columnsByTable,
|
|
1851
|
+
uniqueKeysByTable: new Map(tableNames.map((table) => [table, [pkByTable.get(table) ?? [], ...(uniqueByTable.get(table) ?? [])]])),
|
|
1852
|
+
// A unique key proves a to-one only when the join compares like the key.
|
|
1853
|
+
sameKeyComparison: (fk) => fk.sourceColumns.length === fk.targetColumns.length &&
|
|
1854
|
+
fk.sourceColumns.every((name, i) => mysqlSameKeyEquality(nativeColumns.get(JSON.stringify([fk.sourceTable, name])), nativeColumns.get(JSON.stringify([fk.targetTable, fk.targetColumns[i]])))),
|
|
1855
|
+
junctionKeysByTable: new Map(Array.from(uniqueByTable, ([table, keys]) => [table, keys.filter((key) => key.length === 2)])),
|
|
1856
|
+
...(options.legacyToManyUniques ? { legacyToManyUniques: true } : {}),
|
|
1857
|
+
...(options.logger ? { logger: options.logger } : {}),
|
|
1858
|
+
});
|
|
1813
1859
|
// ----- Assemble TableMetadata -----
|
|
1814
1860
|
const tables = (0, introspect_js_1.nullRecord)();
|
|
1815
1861
|
for (const tableName of tableNames) {
|