uql-orm 0.96.1 → 0.98.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/dist/dialect/abstractSqlDialect.d.ts +1 -7
- package/dist/dialect/abstractSqlDialect.js +1 -9
- package/dist/dialect/mysqlLikeSqlDialect.d.ts +2 -0
- package/dist/dialect/mysqlLikeSqlDialect.js +4 -1
- package/dist/dialect/pgLikeSqlDialect.js +0 -1
- package/dist/migrate/acquireQuerierForMigrations.d.ts +4 -8
- package/dist/migrate/acquireQuerierForMigrations.js +10 -18
- package/dist/migrate/builder/columnBuilder.d.ts +1 -2
- package/dist/migrate/builder/columnBuilder.js +3 -10
- package/dist/migrate/builder/migrationBuilder.d.ts +6 -26
- package/dist/migrate/builder/migrationBuilder.js +21 -78
- package/dist/migrate/builder/tableBuilder.js +2 -3
- package/dist/migrate/builder/types.d.ts +59 -120
- package/dist/migrate/cli-config.d.ts +1 -0
- package/dist/migrate/cli-config.js +11 -26
- package/dist/migrate/cli.d.ts +0 -13
- package/dist/migrate/cli.js +55 -118
- package/dist/migrate/codegen/entityCodeGenerator.d.ts +7 -61
- package/dist/migrate/codegen/entityCodeGenerator.js +53 -174
- package/dist/migrate/codegen/fieldOptionsSource.d.ts +1 -3
- package/dist/migrate/codegen/fieldOptionsSource.js +3 -11
- package/dist/migrate/codegen/index.d.ts +2 -7
- package/dist/migrate/codegen/index.js +2 -8
- package/dist/migrate/codegen/migrationFile.d.ts +1 -8
- package/dist/migrate/codegen/migrationFile.js +9 -13
- package/dist/migrate/ddl/defaultSql.d.ts +2 -1
- package/dist/migrate/ddl/defaultSql.js +1 -3
- package/dist/migrate/ddl/indexCapabilities.d.ts +18 -0
- package/dist/migrate/ddl/indexCapabilities.js +60 -0
- package/dist/migrate/ddl/indexDdl.d.ts +11 -24
- package/dist/migrate/ddl/indexDdl.js +22 -28
- package/dist/migrate/ddl/mssqlIndexDdl.d.ts +1 -7
- package/dist/migrate/ddl/mssqlIndexDdl.js +1 -7
- package/dist/migrate/ddl/mssqlTableDdl.d.ts +6 -9
- package/dist/migrate/ddl/mssqlTableDdl.js +14 -17
- package/dist/migrate/ddl/mysqlIndexDdl.d.ts +0 -21
- package/dist/migrate/ddl/mysqlIndexDdl.js +4 -48
- package/dist/migrate/ddl/mysqlTableDdl.d.ts +6 -5
- package/dist/migrate/ddl/mysqlTableDdl.js +15 -10
- package/dist/migrate/ddl/pgIndexDdl.d.ts +0 -10
- package/dist/migrate/ddl/pgIndexDdl.js +5 -44
- package/dist/migrate/ddl/pgTableDdl.d.ts +6 -2
- package/dist/migrate/ddl/pgTableDdl.js +17 -1
- package/dist/migrate/ddl/sqliteIndexDdl.js +2 -7
- package/dist/migrate/ddl/tableDdl.d.ts +43 -24
- package/dist/migrate/ddl/tableDdl.js +56 -37
- package/dist/migrate/ddl/tableRebuild.d.ts +2 -1
- package/dist/migrate/drift/driftDetector.d.ts +29 -32
- package/dist/migrate/drift/driftDetector.js +155 -205
- package/dist/migrate/drift/index.d.ts +1 -6
- package/dist/migrate/drift/index.js +1 -6
- package/dist/migrate/generator/definitionToNode.d.ts +2 -2
- package/dist/migrate/generator/definitionToNode.js +6 -5
- package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +56 -77
- package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +75 -98
- package/dist/migrate/introspection/mssqlIntrospector.d.ts +10 -43
- package/dist/migrate/introspection/mssqlIntrospector.js +52 -77
- package/dist/migrate/introspection/mysqlIntrospector.d.ts +21 -37
- package/dist/migrate/introspection/mysqlIntrospector.js +75 -56
- package/dist/migrate/introspection/postgresIntrospector.d.ts +15 -60
- package/dist/migrate/introspection/postgresIntrospector.js +74 -77
- package/dist/migrate/introspection/sqliteIntrospector.d.ts +19 -53
- package/dist/migrate/introspection/sqliteIntrospector.js +73 -119
- package/dist/migrate/introspection/tableSchemaAST.d.ts +13 -0
- package/dist/migrate/introspection/tableSchemaAST.js +85 -0
- package/dist/migrate/migrationTarget.js +10 -2
- package/dist/migrate/migrator.d.ts +9 -44
- package/dist/migrate/migrator.js +72 -150
- package/dist/migrate/schemaChange.d.ts +8 -5
- package/dist/migrate/schemaChange.js +25 -8
- package/dist/migrate/schemaGenerator.d.ts +35 -109
- package/dist/migrate/schemaGenerator.js +179 -353
- package/dist/migrate/storage/databaseStorage.d.ts +2 -1
- package/dist/migrate/storage/databaseStorage.js +3 -2
- package/dist/migrate/storage/jsonStorage.d.ts +1 -2
- package/dist/migrate/storage/jsonStorage.js +11 -20
- package/dist/migrate/triggerSql.d.ts +7 -9
- package/dist/migrate/triggerSql.js +17 -18
- package/dist/mongo/index.d.ts +0 -1
- package/dist/mongo/index.js +0 -1
- package/dist/mongo/mongoDialect.js +0 -1
- package/dist/mongo/mongoIntrospector.d.ts +1 -6
- package/dist/mongo/mongoIntrospector.js +7 -18
- package/dist/mongo/mongoSchemaGenerator.d.ts +7 -26
- package/dist/mongo/mongoSchemaGenerator.js +51 -75
- package/dist/mssql/mssqlDialect.js +0 -1
- package/dist/schema/canonicalType.d.ts +15 -19
- package/dist/schema/canonicalType.js +20 -43
- package/dist/schema/dependencyGraph.d.ts +2 -3
- package/dist/schema/dependencyGraph.js +0 -4
- package/dist/schema/indexDifferences.js +2 -2
- package/dist/schema/schemaAST.d.ts +1 -1
- package/dist/schema/schemaAST.js +5 -12
- package/dist/schema/schemaASTBuilder.d.ts +5 -6
- package/dist/schema/schemaASTBuilder.js +17 -18
- package/dist/schema/schemaASTDiffer.d.ts +4 -5
- package/dist/schema/schemaASTDiffer.js +40 -73
- package/dist/schema/types.d.ts +24 -54
- package/dist/sqlite/localSqliteQuerierPool.d.ts +16 -2
- package/dist/sqlite/localSqliteQuerierPool.js +20 -4
- package/dist/sqlite/nodeSqliteQuerierPool.js +2 -2
- package/dist/sqlite/sqliteDialect.js +0 -1
- package/dist/sqlite/sqliteQuerierPool.js +3 -3
- package/dist/type/dialect.d.ts +0 -2
- package/dist/type/migration.d.ts +13 -73
- package/dist/util/ddlExpression.util.d.ts +13 -2
- package/dist/util/ddlExpression.util.js +27 -4
- package/dist/util/sql.util.d.ts +2 -12
- package/dist/util/sql.util.js +9 -18
- package/package.json +1 -1
- package/skills/uql-orm/SKILL.md +1 -1
- package/dist/migrate/introspection/baseSqlIntrospector.d.ts +0 -36
- package/dist/migrate/introspection/baseSqlIntrospector.js +0 -133
- package/dist/schema/index.d.ts +0 -2
- package/dist/schema/index.js +0 -1
- package/dist/sqlite/sqlitePragmas.d.ts +0 -3
- package/dist/sqlite/sqlitePragmas.js +0 -15
|
@@ -13,7 +13,6 @@ export function isVectorCategory(category) {
|
|
|
13
13
|
* Handles variations across dialects (PostgreSQL, MySQL, SQLite).
|
|
14
14
|
*/
|
|
15
15
|
const SQL_TO_CANONICAL = {
|
|
16
|
-
// === Integers ===
|
|
17
16
|
int: { category: 'integer' },
|
|
18
17
|
int4: { category: 'integer' },
|
|
19
18
|
integer: { category: 'integer' },
|
|
@@ -26,18 +25,15 @@ const SQL_TO_CANONICAL = {
|
|
|
26
25
|
serial: { category: 'integer' },
|
|
27
26
|
bigserial: { category: 'integer', size: 'big' },
|
|
28
27
|
smallserial: { category: 'integer', size: 'small' },
|
|
29
|
-
// === Floats ===
|
|
30
28
|
float: { category: 'float' },
|
|
31
29
|
float4: { category: 'float' },
|
|
32
30
|
real: { category: 'float' },
|
|
33
31
|
float8: { category: 'float', size: 'big' },
|
|
34
32
|
double: { category: 'float', size: 'big' },
|
|
35
33
|
'double precision': { category: 'float', size: 'big' },
|
|
36
|
-
// === Decimals ===
|
|
37
34
|
decimal: { category: 'decimal' },
|
|
38
35
|
numeric: { category: 'decimal' },
|
|
39
36
|
money: { category: 'decimal' },
|
|
40
|
-
// === Strings ===
|
|
41
37
|
char: { category: 'string' },
|
|
42
38
|
character: { category: 'string' },
|
|
43
39
|
varchar: { category: 'string' },
|
|
@@ -49,11 +45,9 @@ const SQL_TO_CANONICAL = {
|
|
|
49
45
|
tinytext: { category: 'string', size: 'tiny' },
|
|
50
46
|
mediumtext: { category: 'string', size: 'medium' },
|
|
51
47
|
longtext: { category: 'string', size: 'big' },
|
|
52
|
-
// === Boolean ===
|
|
53
48
|
bool: { category: 'boolean' },
|
|
54
49
|
boolean: { category: 'boolean' },
|
|
55
50
|
bit: { category: 'boolean' },
|
|
56
|
-
// === Date/Time ===
|
|
57
51
|
date: { category: 'date' },
|
|
58
52
|
time: { category: 'time' },
|
|
59
53
|
'time without time zone': { category: 'time' },
|
|
@@ -67,13 +61,10 @@ const SQL_TO_CANONICAL = {
|
|
|
67
61
|
datetime2: { category: 'timestamp' },
|
|
68
62
|
smalldatetime: { category: 'timestamp' },
|
|
69
63
|
datetimeoffset: { category: 'timestamp', withTimezone: true },
|
|
70
|
-
// === JSON ===
|
|
71
64
|
json: { category: 'json' },
|
|
72
65
|
jsonb: { category: 'json' },
|
|
73
|
-
// === UUID ===
|
|
74
66
|
uuid: { category: 'uuid' },
|
|
75
67
|
uniqueidentifier: { category: 'uuid' },
|
|
76
|
-
// === Binary ===
|
|
77
68
|
blob: { category: 'blob' },
|
|
78
69
|
bytea: { category: 'blob' },
|
|
79
70
|
binary: { category: 'blob' },
|
|
@@ -82,7 +73,6 @@ const SQL_TO_CANONICAL = {
|
|
|
82
73
|
mediumblob: { category: 'blob', size: 'medium' },
|
|
83
74
|
longblob: { category: 'blob', size: 'big' },
|
|
84
75
|
image: { category: 'blob', size: 'big' },
|
|
85
|
-
// === Vector (for AI/embeddings) ===
|
|
86
76
|
vector: { category: 'vector' },
|
|
87
77
|
f32_blob: { category: 'vector' },
|
|
88
78
|
halfvec: { category: 'halfvec' },
|
|
@@ -238,10 +228,12 @@ const CANONICAL_TO_TS = {
|
|
|
238
228
|
sparsevec: 'number[]',
|
|
239
229
|
};
|
|
240
230
|
/**
|
|
241
|
-
*
|
|
242
|
-
*
|
|
231
|
+
* The canonical type of a SQL type string, and of the bounds an engine reports beside it
|
|
232
|
+
* (`character_maximum_length` and friends), which win over the name's own. The one place a SQL type is
|
|
233
|
+
* read: everything downstream compares and renders canonical types, so no consumer has to know that
|
|
234
|
+
* `TINYINT(1)` means boolean on MySQL.
|
|
243
235
|
*/
|
|
244
|
-
export function sqlToCanonical(sqlType) {
|
|
236
|
+
export function sqlToCanonical(sqlType, reported = {}) {
|
|
245
237
|
const normalized = sqlType.toLowerCase().trim();
|
|
246
238
|
const unsigned = normalized.includes('unsigned');
|
|
247
239
|
const withoutUnsigned = normalized.replace(/\s*unsigned\s*/i, ' ').trim();
|
|
@@ -251,14 +243,16 @@ export function sqlToCanonical(sqlType) {
|
|
|
251
243
|
.replace(/^(\w+)\((\d+)\)\s+(.+)$/, '$1 $3($2)')
|
|
252
244
|
.match(/^([a-z][a-z0-9_ ]*?)(?:\(([^)]+)\))?$/);
|
|
253
245
|
const base = match ? SQL_TO_CANONICAL[match[1]] : undefined;
|
|
246
|
+
const length = reported.dimensions ?? reported.length;
|
|
254
247
|
if (!match || !base) {
|
|
255
|
-
return { category: 'string', raw: sqlType };
|
|
248
|
+
return { category: 'string', raw: sqlType, length };
|
|
256
249
|
}
|
|
257
250
|
const params = match[2]?.split(',').map((param) => param.trim()) ?? [];
|
|
258
251
|
const [first, second] = params
|
|
259
252
|
.map((param) => Number.parseInt(param, 10))
|
|
260
253
|
.map((n) => (Number.isNaN(n) ? undefined : n));
|
|
261
|
-
// A length for a string or a
|
|
254
|
+
// A length for a string, a blob or a vector (its dimensions), a precision for a decimal or a timestamp,
|
|
255
|
+
// a scale for a decimal: catalogues also report an integer's digits or a float's bits, which no type states.
|
|
262
256
|
const measured = base.category === 'string' || base.category === 'blob' || isVectorCategory(base.category);
|
|
263
257
|
const decimal = base.category === 'decimal';
|
|
264
258
|
return {
|
|
@@ -266,28 +260,12 @@ export function sqlToCanonical(sqlType) {
|
|
|
266
260
|
// SQL Server's unbounded `(MAX)` is what it creates for a `TEXT`.
|
|
267
261
|
size: measured && params[0] === 'max' ? 'small' : base.size,
|
|
268
262
|
withTimezone: base.withTimezone,
|
|
269
|
-
length: measured ? first : undefined,
|
|
270
|
-
precision: decimal || base.category === 'timestamp' ? first : undefined,
|
|
271
|
-
scale: decimal ? second : undefined,
|
|
263
|
+
length: measured ? (length ?? first) : undefined,
|
|
264
|
+
precision: decimal || base.category === 'timestamp' ? (reported.precision ?? first) : undefined,
|
|
265
|
+
scale: decimal ? (reported.scale ?? second) : undefined,
|
|
272
266
|
unsigned: unsigned || undefined,
|
|
273
267
|
};
|
|
274
268
|
}
|
|
275
|
-
/**
|
|
276
|
-
* The canonical type for a column an engine reported, merging the metadata columns it reports beside
|
|
277
|
-
* the type name (`character_maximum_length` and friends) over whatever the name itself carried. This is
|
|
278
|
-
* the one place a SQL type string is parsed: everything downstream compares and renders canonical
|
|
279
|
-
* types, so no consumer has to know that `TINYINT(1)` means boolean on MySQL.
|
|
280
|
-
*/
|
|
281
|
-
export function canonicalColumnType(sqlType, reported = {}) {
|
|
282
|
-
const base = sqlToCanonical(sqlType);
|
|
283
|
-
return {
|
|
284
|
-
...base,
|
|
285
|
-
// A vector states its length as `dimensions`, and only a vector may: one bound, named from either side.
|
|
286
|
-
length: reported.dimensions ?? reported.length ?? base.length,
|
|
287
|
-
precision: reported.precision ?? base.precision,
|
|
288
|
-
scale: reported.scale ?? base.scale,
|
|
289
|
-
};
|
|
290
|
-
}
|
|
291
269
|
/**
|
|
292
270
|
* The SQL type a field declares, however it named one: `columnType`, the engine's own as a `raw`
|
|
293
271
|
* constant, or a `type` that is a SQL string rather than a constructor.
|
|
@@ -310,7 +288,7 @@ export function canonicalToSql(type, dialect) {
|
|
|
310
288
|
// A `size` the engine spells out wins outright; anything else falls through to the rules below.
|
|
311
289
|
// `TEXT` canonicalizes to `size: 'small'`, so a string counts as unsized only where the engine
|
|
312
290
|
// declares no variant for it, which is how Postgres reaches `TEXT` rather than its base `VARCHAR`.
|
|
313
|
-
const sized = engine.sizes?.[type.category]?.[type.size];
|
|
291
|
+
const sized = type.size && engine.sizes?.[type.category]?.[type.size];
|
|
314
292
|
let sqlType = sized ?? engine.scalars[type.category];
|
|
315
293
|
if (type.category === 'string' && !sized) {
|
|
316
294
|
sqlType = formatStringSqlType(type, engine.scalars.string, features.stringSizing);
|
|
@@ -353,21 +331,20 @@ function formatDecimalSqlType(type, fallback, baseType) {
|
|
|
353
331
|
export function canonicalToTypeScript(type) {
|
|
354
332
|
return CANONICAL_TO_TS[type.category];
|
|
355
333
|
}
|
|
356
|
-
/** The fractional-second digits an engine's timestamp holds when its type states none; `undefined` where it counts none. */
|
|
357
|
-
export function defaultTimestampPrecision(dialectName) {
|
|
358
|
-
return ENGINE_TYPES[dialectName].timestampPrecision;
|
|
359
|
-
}
|
|
360
334
|
/** Gives a timestamp type that states no precision `digits` fractional seconds; other types pass through. */
|
|
361
|
-
|
|
335
|
+
function withTimestampPrecision(type, digits) {
|
|
362
336
|
return type.category === 'timestamp' && type.precision === undefined ? { ...type, precision: digits } : type;
|
|
363
337
|
}
|
|
338
|
+
/** A SQL type as `dialectName` stores it: a timestamp stating no precision holds the engine's default digits. */
|
|
339
|
+
export function storedType(dialectName, sqlType, reported) {
|
|
340
|
+
return withTimestampPrecision(sqlToCanonical(sqlType, reported), ENGINE_TYPES[dialectName].timestampPrecision);
|
|
341
|
+
}
|
|
364
342
|
/**
|
|
365
343
|
* A type as `dialect` stores it, rendered and read back: several types share one storage type, and only
|
|
366
344
|
* the engine settles an unstated bound. Migrations and drift both compare through it.
|
|
367
345
|
*/
|
|
368
346
|
export function engineType(dialect) {
|
|
369
|
-
|
|
370
|
-
return (type) => withTimestampPrecision(sqlToCanonical(canonicalToSql(type, dialect)), timestampPrecision);
|
|
347
|
+
return (type) => storedType(dialect.dialectName, canonicalToSql(type, dialect));
|
|
371
348
|
}
|
|
372
349
|
/** A field's canonical type; a timestamp without precision gets a `Date`'s milliseconds, unless it is `raw` SQL. */
|
|
373
350
|
export function fieldOptionsToCanonical(options) {
|
|
@@ -379,7 +356,7 @@ function fieldType(options) {
|
|
|
379
356
|
// beside it is read the same way either way.
|
|
380
357
|
const declared = declaredSqlType(options);
|
|
381
358
|
if (declared !== undefined) {
|
|
382
|
-
return
|
|
359
|
+
return sqlToCanonical(declared, options);
|
|
383
360
|
}
|
|
384
361
|
switch (columnFamily(options.type)) {
|
|
385
362
|
case 'numeric':
|
|
@@ -2,11 +2,10 @@
|
|
|
2
2
|
* Dependency ordering over any schema object, not just tables: a new kind joins the ordering by
|
|
3
3
|
* describing its edges rather than by adding a branch here.
|
|
4
4
|
*/
|
|
5
|
-
|
|
5
|
+
type DependenciesOf<N> = (node: N) => Iterable<N>;
|
|
6
6
|
/**
|
|
7
7
|
* Nodes in creation order, dependencies first. Cycle-tolerant: a cyclic foreign key is legal SQL,
|
|
8
8
|
* handled by deferring the constraint, so a cycle orders arbitrarily rather than throwing.
|
|
9
9
|
*/
|
|
10
10
|
export declare function createOrder<N>(nodes: Iterable<N>, dependenciesOf: DependenciesOf<N>): N[];
|
|
11
|
-
|
|
12
|
-
export declare function dropOrder<N>(nodes: Iterable<N>, dependenciesOf: DependenciesOf<N>): N[];
|
|
11
|
+
export {};
|
|
@@ -52,7 +52,7 @@ export function indexChanges(table, declared, current, facets) {
|
|
|
52
52
|
}
|
|
53
53
|
/**
|
|
54
54
|
* Whether uql named the index itself, from its own columns: `Order__total_idx`, its unique `_uk`, or
|
|
55
|
-
*
|
|
55
|
+
* `idx_Order_total`, which a database an older uql created holds.
|
|
56
56
|
*/
|
|
57
57
|
function hasDerivedName(table, index) {
|
|
58
58
|
const parts = index.entries.map((entry, at) => (isColumnEntry(entry) ? entry.column : `expr${at}`));
|
|
@@ -66,7 +66,7 @@ function hasDerivedName(table, index) {
|
|
|
66
66
|
/** What this version emits. */
|
|
67
67
|
const KIND_SUFFIX = /_(?:idx|fk|ck|pk|uk|uq)$/i;
|
|
68
68
|
/**
|
|
69
|
-
* What it only ever *reads*: uql
|
|
69
|
+
* What it only ever *reads*: a database an older uql created holds `idx_User_email`, and one it did not
|
|
70
70
|
* create at all - the one `generate:from-db` points at - most often spells it that way too. Tried
|
|
71
71
|
* second, so a name already marked at the end keeps a leading `pk_` that is part of its table.
|
|
72
72
|
*/
|
|
@@ -18,6 +18,6 @@ export declare class SchemaAST {
|
|
|
18
18
|
/** Tables in `DROP` order, each before the tables it references. */
|
|
19
19
|
getDropOrder(): TableNode[];
|
|
20
20
|
addIndex(index: IndexNode): void;
|
|
21
|
-
/** Adds a foreign key, linking it from both tables
|
|
21
|
+
/** Adds a foreign key, linking it from both tables. */
|
|
22
22
|
addRelationship(rel: RelationshipNode): void;
|
|
23
23
|
}
|
package/dist/schema/schemaAST.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { qualifyName } from '../util/sql.util.js';
|
|
2
|
-
import { createOrder
|
|
2
|
+
import { createOrder } from './dependencyGraph.js';
|
|
3
3
|
/** A table node with its collections empty, ready to be filled. */
|
|
4
4
|
export function createTableNode(name, schema, indexFacets = new Set()) {
|
|
5
5
|
return {
|
|
@@ -9,6 +9,7 @@ export function createTableNode(name, schema, indexFacets = new Set()) {
|
|
|
9
9
|
columns: new Map(),
|
|
10
10
|
indexes: [],
|
|
11
11
|
checks: [],
|
|
12
|
+
triggers: [],
|
|
12
13
|
externalForeignKeys: [],
|
|
13
14
|
incomingRelations: [],
|
|
14
15
|
outgoingRelations: [],
|
|
@@ -39,24 +40,16 @@ export class SchemaAST {
|
|
|
39
40
|
}
|
|
40
41
|
/** Tables in `DROP` order, each before the tables it references. */
|
|
41
42
|
getDropOrder() {
|
|
42
|
-
return
|
|
43
|
+
return this.getCreateOrder().reverse();
|
|
43
44
|
}
|
|
44
45
|
addIndex(index) {
|
|
45
|
-
|
|
46
|
-
index.table.indexes.push(index);
|
|
47
|
-
}
|
|
46
|
+
index.table.indexes.push(index);
|
|
48
47
|
}
|
|
49
|
-
/** Adds a foreign key, linking it from both tables
|
|
48
|
+
/** Adds a foreign key, linking it from both tables. */
|
|
50
49
|
addRelationship(rel) {
|
|
51
50
|
this.relationships.push(rel);
|
|
52
51
|
rel.from.table.outgoingRelations.push(rel);
|
|
53
52
|
rel.to.table.incomingRelations.push(rel);
|
|
54
|
-
for (const col of rel.from.columns) {
|
|
55
|
-
col.references = rel;
|
|
56
|
-
}
|
|
57
|
-
for (const col of rel.to.columns) {
|
|
58
|
-
col.referencedBy.push(rel);
|
|
59
|
-
}
|
|
60
53
|
}
|
|
61
54
|
}
|
|
62
55
|
function referencedTables(table) {
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import type { EntityMeta, EntityWhereMeta, FieldOptions, Type } from '../type/index.js';
|
|
2
|
-
import type { NamingStrategy } from '../type/namingStrategy.js';
|
|
3
2
|
import { SchemaAST } from './schemaAST.js';
|
|
4
|
-
import { type ForeignKeyAction } from './types.js';
|
|
3
|
+
import { type ForeignKeyAction, type TriggerSchema } from './types.js';
|
|
5
4
|
/**
|
|
6
5
|
* Options for building SchemaAST from entities.
|
|
7
6
|
*/
|
|
@@ -12,21 +11,21 @@ export interface BuildSchemaASTOptions {
|
|
|
12
11
|
resolveSchema?: (meta: EntityMeta<object>) => string | undefined;
|
|
13
12
|
/** Custom column name resolver */
|
|
14
13
|
resolveColumnName?: (key: string, field: FieldOptions) => string;
|
|
15
|
-
/** Naming strategy to use */
|
|
16
|
-
namingStrategy?: NamingStrategy;
|
|
17
14
|
/** Default action for foreign key ON DELETE and ON UPDATE clauses */
|
|
18
15
|
defaultForeignKeyAction?: ForeignKeyAction;
|
|
19
16
|
/**
|
|
20
17
|
* The text of SQL an entity declares - a check, a stored computed column, an index expression or
|
|
21
|
-
* predicate - which only a dialect can render. `
|
|
18
|
+
* predicate - which only a dialect can render. `SqlSchemaGenerator.buildAST` supplies it.
|
|
22
19
|
*/
|
|
23
20
|
compileDdl?: (sql: EntityWhereMeta<object>, entity: Type<object>) => string;
|
|
24
|
-
/** A partial index's predicate as the engine writes it, `compileDdl` where none is given.
|
|
21
|
+
/** A partial index's predicate as the engine writes it, `compileDdl` where none is given. */
|
|
25
22
|
compileIndexPredicate?: (where: EntityWhereMeta<object>, entity: Type<object>, indexName: string) => string;
|
|
26
23
|
/** Whether a weighted fulltext index declares one of its own for each heavier column, as MySQL scores through one. */
|
|
27
24
|
textScoreIndexes?: boolean;
|
|
28
25
|
/** Whether a column a vector index covers is `NOT NULL` whatever the entity declares, as MariaDB demands. */
|
|
29
26
|
vectorIndexRequiresNotNull?: boolean;
|
|
27
|
+
/** The triggers an entity's table carries, as its dialect renders them; none where no dialect renders any. */
|
|
28
|
+
renderTriggers?: (meta: EntityMeta<object>) => TriggerSchema[];
|
|
30
29
|
}
|
|
31
30
|
/**
|
|
32
31
|
* Build a SchemaAST from entity classes (decorated with `@Entity`, `@Field`, etc.).
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { fieldOf, foreignKeysOf, getMeta } from '../entity/metadata/definition.js';
|
|
2
|
-
import { declaredIndexes, declaredIndexName, renderIndexColumn } from '../util/ddlExpression.util.js';
|
|
2
|
+
import { declaredIndexes, declaredIndexName, enumCheck, ownedCheck, renderIndexColumn, } from '../util/ddlExpression.util.js';
|
|
3
3
|
import { fulltextWeights, textWeightSteps } from '../util/dialect.util.js';
|
|
4
4
|
import { declaresNotNull, isAutoIncrement, isInlinedExpression, isSoleIdField } from '../util/field.util.js';
|
|
5
5
|
import { definedEntries, entityName } from '../util/object.util.js';
|
|
@@ -9,7 +9,7 @@ import { resolveColumnCanonicalType } from './canonicalType.js';
|
|
|
9
9
|
import { lookupColumns } from './indexColumns.js';
|
|
10
10
|
import { createTableNode, keyOfColumns, SchemaAST } from './schemaAST.js';
|
|
11
11
|
import { schemaDefault } from './sqlExpression.js';
|
|
12
|
-
import { DEFAULT_FOREIGN_KEY_ACTION } from './types.js';
|
|
12
|
+
import { DEFAULT_FOREIGN_KEY_ACTION, } from './types.js';
|
|
13
13
|
/**
|
|
14
14
|
* Build a SchemaAST from entity classes (decorated with `@Entity`, `@Field`, etc.).
|
|
15
15
|
*
|
|
@@ -17,19 +17,19 @@ import { DEFAULT_FOREIGN_KEY_ACTION } from './types.js';
|
|
|
17
17
|
* resolves against a table another entity declares, and an index against the columns of its own.
|
|
18
18
|
*/
|
|
19
19
|
export function buildSchemaAST(entities, options = {}) {
|
|
20
|
-
const { namingStrategy } = options;
|
|
21
20
|
const compileDdl = options.compileDdl ?? refuseDdl;
|
|
22
21
|
const ctx = {
|
|
23
22
|
ast: new SchemaAST(),
|
|
24
23
|
tables: new Map(),
|
|
25
|
-
resolveTableName: options.resolveTableName ??
|
|
24
|
+
resolveTableName: options.resolveTableName ?? entityName,
|
|
26
25
|
resolveSchema: options.resolveSchema ?? ((m) => m.schema),
|
|
27
|
-
resolveColumnName: options.resolveColumnName ?? ((
|
|
26
|
+
resolveColumnName: options.resolveColumnName ?? ((key, field) => field.name ?? key),
|
|
28
27
|
defaultForeignKeyAction: options.defaultForeignKeyAction ?? DEFAULT_FOREIGN_KEY_ACTION,
|
|
29
28
|
compileDdl,
|
|
30
29
|
compileIndexPredicate: options.compileIndexPredicate ?? compileDdl,
|
|
31
30
|
textScoreIndexes: options.textScoreIndexes ?? false,
|
|
32
31
|
vectorIndexRequiresNotNull: options.vectorIndexRequiresNotNull ?? false,
|
|
32
|
+
renderTriggers: options.renderTriggers ?? (() => []),
|
|
33
33
|
};
|
|
34
34
|
for (const entity of entities) {
|
|
35
35
|
const meta = getMeta(entity);
|
|
@@ -44,7 +44,7 @@ export function buildSchemaAST(entities, options = {}) {
|
|
|
44
44
|
}
|
|
45
45
|
/** The `compileDdl` of a build given no dialect, which has nothing to render an entity's SQL with. */
|
|
46
46
|
function refuseDdl() {
|
|
47
|
-
throw new UqlUsageError('building the schema of an entity that declares SQL (a check, a stored computed column, an index expression or predicate) needs a dialect to render it: pass `compileDdl`, as `
|
|
47
|
+
throw new UqlUsageError('building the schema of an entity that declares SQL (a check, a stored computed column, an index expression or predicate) needs a dialect to render it: pass `compileDdl`, as `SqlSchemaGenerator.buildAST` does');
|
|
48
48
|
}
|
|
49
49
|
/** The entries a vector index of `meta` covers: the members it names, and any expression. */
|
|
50
50
|
function vectorIndexedEntries(meta) {
|
|
@@ -59,7 +59,7 @@ function addTableFromEntity(ctx, meta) {
|
|
|
59
59
|
const tableName = ctx.resolveTableName(meta);
|
|
60
60
|
const table = createTableNode(tableName, ctx.resolveSchema(meta));
|
|
61
61
|
const { columns } = table;
|
|
62
|
-
table.checks.push(...(meta.checks ?? []).map(({ name, where }) => (
|
|
62
|
+
table.checks.push(...(meta.checks ?? []).map(({ name, where }) => ownedCheck(tableName, name, ctx.compileDdl(where, meta.entity))));
|
|
63
63
|
const notNull = ctx.vectorIndexRequiresNotNull ? vectorIndexedEntries(meta) : new Set();
|
|
64
64
|
// Add columns from fields
|
|
65
65
|
for (const [key, field] of definedEntries(meta.fields)) {
|
|
@@ -81,14 +81,13 @@ function addTableFromEntity(ctx, meta) {
|
|
|
81
81
|
// A stamp is filled by a trigger, so it is a column like any other; only `stored: true` generates.
|
|
82
82
|
generatedAs: field.stored === true && field.computed ? ctx.compileDdl(field.computed, meta.entity) : undefined,
|
|
83
83
|
comment: field.comment,
|
|
84
|
-
enum: field.enum,
|
|
85
84
|
table,
|
|
86
|
-
referencedBy: [],
|
|
87
|
-
references: undefined,
|
|
88
85
|
};
|
|
89
86
|
columns.set(columnName, column);
|
|
87
|
+
table.checks.push(...enumCheck(tableName, { name: columnName, enum: field.enum }, (sql) => ctx.compileDdl(sql, meta.entity)));
|
|
90
88
|
}
|
|
91
89
|
table.primaryKey = keyOfColumns(columns.values());
|
|
90
|
+
table.triggers.push(...ctx.renderTriggers(meta));
|
|
92
91
|
ctx.ast.addTable(table);
|
|
93
92
|
return table;
|
|
94
93
|
}
|
|
@@ -164,10 +163,10 @@ function isIndexedBy(table, columns) {
|
|
|
164
163
|
const leads = (indexed) => columns.every((column, at) => indexed[at] === column);
|
|
165
164
|
return leads(table.primaryKey?.columns ?? []) || table.indexes.some((index) => leads(lookupColumns(index)));
|
|
166
165
|
}
|
|
167
|
-
/**
|
|
168
|
-
function
|
|
169
|
-
const field = meta.fields[
|
|
170
|
-
return field
|
|
166
|
+
/** The column the member `key` of `meta` maps to, or `undefined` where the entity has no such member. */
|
|
167
|
+
function fieldColumn(ctx, meta, key) {
|
|
168
|
+
const field = meta.fields[key];
|
|
169
|
+
return field && ctx.resolveColumnName(key, field);
|
|
171
170
|
}
|
|
172
171
|
/**
|
|
173
172
|
* One index the entity declares. Its entries keep the authored form (expression, prefix length, order) with
|
|
@@ -176,12 +175,11 @@ function resolveIncludeColumn(ctx, meta, column) {
|
|
|
176
175
|
*/
|
|
177
176
|
function addCompositeIndex(ctx, table, meta, { columns, include, where, ...options }) {
|
|
178
177
|
// An entry survives if it is an expression (nothing to resolve) or names a column that exists;
|
|
179
|
-
// an index left with none is dropped,
|
|
178
|
+
// an index left with none is dropped, as one naming only unknown columns is.
|
|
180
179
|
const resolved = columns.flatMap((entry) => {
|
|
181
180
|
if (typeof entry.column !== 'string')
|
|
182
181
|
return [entry];
|
|
183
|
-
const
|
|
184
|
-
const column = field && ctx.resolveColumnName(entry.column, field);
|
|
182
|
+
const column = fieldColumn(ctx, meta, entry.column);
|
|
185
183
|
return column && table.columns.has(column) ? [{ ...entry, column }] : [];
|
|
186
184
|
});
|
|
187
185
|
if (!resolved.length)
|
|
@@ -192,7 +190,8 @@ function addCompositeIndex(ctx, table, meta, { columns, include, where, ...optio
|
|
|
192
190
|
name,
|
|
193
191
|
table,
|
|
194
192
|
entries: resolved.map((entry) => renderIndexColumn(entry, (sql) => ctx.compileDdl(sql, meta.entity))),
|
|
195
|
-
include
|
|
193
|
+
// An `include` column is named like any other, so a custom naming has to reach it too.
|
|
194
|
+
include: include?.map((column) => fieldColumn(ctx, meta, column) ?? column),
|
|
196
195
|
unique: options.unique ?? false,
|
|
197
196
|
where: where && ctx.compileIndexPredicate(where, meta.entity, name),
|
|
198
197
|
});
|
|
@@ -6,10 +6,6 @@ import type { ForeignKeyAction, RelationshipDiff, RelationshipNode, SchemaDiffRe
|
|
|
6
6
|
* Options for schema diffing.
|
|
7
7
|
*/
|
|
8
8
|
export interface DiffOptions {
|
|
9
|
-
/** Compare indexes */
|
|
10
|
-
compareIndexes?: boolean;
|
|
11
|
-
/** Compare foreign keys/relationships */
|
|
12
|
-
compareRelationships?: boolean;
|
|
13
9
|
/** Tables to exclude from comparison */
|
|
14
10
|
excludeTables?: string[];
|
|
15
11
|
/**
|
|
@@ -22,7 +18,10 @@ export interface DiffOptions {
|
|
|
22
18
|
}
|
|
23
19
|
/** The differences between the expected schema (the entities) and the actual one (the database). */
|
|
24
20
|
export declare function diffSchemas(source: SchemaAST, target: SchemaAST, options?: DiffOptions): SchemaDiffResult;
|
|
25
|
-
/**
|
|
21
|
+
/**
|
|
22
|
+
* The differences between two tables but their indexes, which a migration pairs on its own; shared by
|
|
23
|
+
* migrations and drift detection so they cannot disagree.
|
|
24
|
+
*/
|
|
26
25
|
export declare function diffTable(source: TableNode, target: TableNode, options?: DiffOptions): TableDiff | undefined;
|
|
27
26
|
/**
|
|
28
27
|
* The columns renamed in the tables both sides name, by qualified table:
|
|
@@ -1,15 +1,10 @@
|
|
|
1
|
-
import { qualifyName } from '../util/sql.util.js';
|
|
1
|
+
import { isOwnedName, qualifyName } from '../util/sql.util.js';
|
|
2
2
|
import { areTypesEqual, isBreakingTypeChange } from './canonicalType.js';
|
|
3
3
|
import { indexChanges } from './indexDifferences.js';
|
|
4
4
|
import { matchByKey, pairUnique } from './matchByKey.js';
|
|
5
5
|
import { writtenDefault } from './sqlExpression.js';
|
|
6
6
|
import { DEFAULT_FOREIGN_KEY_ACTION } from './types.js';
|
|
7
|
-
/**
|
|
8
|
-
* Default diff options.
|
|
9
|
-
*/
|
|
10
7
|
const DEFAULT_OPTIONS = {
|
|
11
|
-
compareIndexes: true,
|
|
12
|
-
compareRelationships: true,
|
|
13
8
|
normalizeType: (type) => type,
|
|
14
9
|
defaultsEqual: defaultsEqualAsWritten,
|
|
15
10
|
excludeTables: [],
|
|
@@ -28,19 +23,36 @@ export function diffSchemas(source, target, options = {}) {
|
|
|
28
23
|
return {
|
|
29
24
|
tables: [...created.map((to) => ({ to })), ...dropped.map((from) => ({ from }))],
|
|
30
25
|
columns: altered.flatMap((tableDiff) => tableDiff.columns),
|
|
31
|
-
indexes:
|
|
26
|
+
indexes: matched.flatMap(([sourceTable, targetTable]) => diffTableIndexes(sourceTable, targetTable)),
|
|
27
|
+
checks: altered.flatMap((tableDiff) => tableDiff.checks),
|
|
28
|
+
triggers: altered.flatMap((tableDiff) => tableDiff.triggers),
|
|
32
29
|
primaryKeys: altered.flatMap((tableDiff) => tableDiff.primaryKey ?? []),
|
|
33
30
|
// Relationships span tables, so they are compared over the whole schema rather than per table.
|
|
34
|
-
relationships:
|
|
31
|
+
relationships: diffRelationshipNodes(source.relationships, target.relationships),
|
|
35
32
|
};
|
|
36
33
|
}
|
|
37
|
-
/**
|
|
34
|
+
/**
|
|
35
|
+
* The differences between two tables but their indexes, which a migration pairs on its own; shared by
|
|
36
|
+
* migrations and drift detection so they cannot disagree.
|
|
37
|
+
*/
|
|
38
38
|
export function diffTable(source, target, options = {}) {
|
|
39
39
|
const opts = { ...DEFAULT_OPTIONS, ...options };
|
|
40
40
|
const columns = diffTableColumns(source, target, opts);
|
|
41
|
-
const
|
|
41
|
+
const checks = diffOwned(source.name, source.checks, target.checks);
|
|
42
|
+
const triggers = diffOwned(source.name, source.triggers, target.triggers);
|
|
42
43
|
const primaryKey = diffPrimaryKey(source, target);
|
|
43
|
-
return columns.length ||
|
|
44
|
+
return columns.length || checks.length || triggers.length || primaryKey
|
|
45
|
+
? { columns, checks, triggers, primaryKey }
|
|
46
|
+
: undefined;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* What one side declares and the other has not installed, by name, for an object named after a hash of its
|
|
50
|
+
* SQL. Only uql's own are ever dropped: the rest are a second writer's.
|
|
51
|
+
*/
|
|
52
|
+
function diffOwned(table, declared, installed) {
|
|
53
|
+
const owned = installed.filter((it) => isOwnedName(it.name));
|
|
54
|
+
const { created, dropped } = matchByKey(declared, owned, (it) => it.name);
|
|
55
|
+
return [...created.map((to) => ({ table, to })), ...dropped.map((from) => ({ table, from }))];
|
|
44
56
|
}
|
|
45
57
|
/** The two keys where they hold different columns, compared in order and never by the name the engine gave them. */
|
|
46
58
|
function diffPrimaryKey(source, target) {
|
|
@@ -51,9 +63,6 @@ function diffPrimaryKey(source, target) {
|
|
|
51
63
|
}
|
|
52
64
|
return { table: source.name, from: target.primaryKey, to: source.primaryKey };
|
|
53
65
|
}
|
|
54
|
-
/**
|
|
55
|
-
* Compare columns between two tables.
|
|
56
|
-
*/
|
|
57
66
|
function diffTableColumns(source, target, opts) {
|
|
58
67
|
const { created, dropped, matched } = matchByKey(source.columns.values(), target.columns.values(), (column) => column.name);
|
|
59
68
|
return [
|
|
@@ -61,14 +70,12 @@ function diffTableColumns(source, target, opts) {
|
|
|
61
70
|
table: source.name,
|
|
62
71
|
column: column.name,
|
|
63
72
|
to: column,
|
|
64
|
-
description: `Add column "${column.name}"`,
|
|
65
73
|
})),
|
|
66
74
|
...dropped.map((column) => ({
|
|
67
75
|
table: target.name,
|
|
68
76
|
column: column.name,
|
|
69
77
|
from: column,
|
|
70
78
|
isBreaking: true,
|
|
71
|
-
description: `Drop column "${column.name}"`,
|
|
72
79
|
})),
|
|
73
80
|
...matched
|
|
74
81
|
.map(([sourceColumn, targetColumn]) => diffColumn(source.name, sourceColumn, targetColumn, opts))
|
|
@@ -97,7 +104,8 @@ export function columnRenames(desired, actual, options = {}) {
|
|
|
97
104
|
export function tableRenameCandidates(desired, actual, options = {}) {
|
|
98
105
|
const opts = { ...DEFAULT_OPTIONS, ...options };
|
|
99
106
|
const { created, dropped } = matchTables(desired, actual, opts);
|
|
100
|
-
|
|
107
|
+
// Columns and key alone: a check or trigger is named for its table, so a renamed one differs by them.
|
|
108
|
+
const same = (to, from) => to.schema === from.schema && !diffTableColumns(to, from, opts).length && !diffPrimaryKey(to, from);
|
|
101
109
|
return pairUnique(created, dropped, same).matched.map(([to, from]) => ({ from: from.name, to: to.name }));
|
|
102
110
|
}
|
|
103
111
|
/** The two sides' tables paired by name, those `excludeTables` names left out of both. */
|
|
@@ -119,11 +127,8 @@ function diffTableIndexes(source, target) {
|
|
|
119
127
|
name: change.to === undefined ? change.from.name : change.to.name,
|
|
120
128
|
}));
|
|
121
129
|
}
|
|
122
|
-
/**
|
|
123
|
-
* Compare two columns and return the difference.
|
|
124
|
-
*/
|
|
130
|
+
/** How `target`, the database's column, differs from `source`, the entity's, or `undefined` where they agree. */
|
|
125
131
|
function diffColumn(tableName, source, target, opts) {
|
|
126
|
-
const differences = [];
|
|
127
132
|
const changed = [];
|
|
128
133
|
// A key column's type and nullability are implied, not stated, and catalogues report them
|
|
129
134
|
// inconsistently (`BIGINT(20)`, SQLite's `notnull: 0` rowid), so neither is compared.
|
|
@@ -131,33 +136,23 @@ function diffColumn(tableName, source, target, opts) {
|
|
|
131
136
|
const impliedNotNull = source.isPrimaryKey && target.isPrimaryKey;
|
|
132
137
|
const expectedType = opts.normalizeType(source.type);
|
|
133
138
|
const actualType = opts.normalizeType(target.type);
|
|
134
|
-
|
|
139
|
+
// A generated key's signedness alone: the one part of its serial spelling that round trips, and an unsigned
|
|
140
|
+
// key refuses every foreign key, which takes the canonical, signed type.
|
|
141
|
+
const typeChanged = generatedType
|
|
142
|
+
? !!source.type.unsigned !== !!target.type.unsigned
|
|
143
|
+
: !areTypesEqual(expectedType, actualType);
|
|
135
144
|
if (typeChanged) {
|
|
136
|
-
differences.push(`type: ${formatType(source.type)} -> ${formatType(target.type)}`);
|
|
137
|
-
changed.push('type');
|
|
138
|
-
}
|
|
139
|
-
// Signedness is the one thing compared on a generated key, because it is the one part of the serial
|
|
140
|
-
// spelling that does round trip - and a key left unsigned refuses every foreign key pointing at it,
|
|
141
|
-
// since the referencing column takes its type from the canonical one, which is signed. Without this
|
|
142
|
-
// a database created before the serial became signed could never gain a foreign key.
|
|
143
|
-
const signednessChanged = generatedType && !!source.type.unsigned !== !!target.type.unsigned;
|
|
144
|
-
if (signednessChanged) {
|
|
145
|
-
differences.push(`type: ${formatType(source.type)} -> ${formatType(target.type)}`);
|
|
146
145
|
changed.push('type');
|
|
147
146
|
}
|
|
148
147
|
if (!impliedNotNull && source.nullable !== target.nullable) {
|
|
149
|
-
differences.push(`nullable: ${target.nullable} -> ${source.nullable}`);
|
|
150
148
|
changed.push('nullable');
|
|
151
149
|
}
|
|
152
150
|
// Not compared, since no statement this generator emits could settle a difference: `isAutoIncrement`,
|
|
153
|
-
// `
|
|
154
|
-
// column is a unique index, compared with the indexes.
|
|
155
|
-
// Compare default values (if both defined)
|
|
151
|
+
// `generatedAs`, and `comment`. Nor `isUnique`: a unique column is a unique index, compared with the indexes.
|
|
156
152
|
if (!opts.defaultsEqual(source.defaultValue, target.defaultValue)) {
|
|
157
|
-
differences.push(`default: ${target.defaultValue ?? 'NULL'} -> ${source.defaultValue ?? 'NULL'}`);
|
|
158
153
|
changed.push('default');
|
|
159
154
|
}
|
|
160
|
-
if (
|
|
155
|
+
if (!changed.length) {
|
|
161
156
|
return undefined;
|
|
162
157
|
}
|
|
163
158
|
return {
|
|
@@ -166,16 +161,13 @@ function diffColumn(tableName, source, target, opts) {
|
|
|
166
161
|
from: target,
|
|
167
162
|
to: source,
|
|
168
163
|
changed,
|
|
169
|
-
// Only the type this diff
|
|
170
|
-
|
|
171
|
-
// cannot say so.
|
|
172
|
-
isBreaking: (typeChanged || signednessChanged) && isBreakingTypeChange(actualType, expectedType),
|
|
173
|
-
description: differences.join(', '),
|
|
164
|
+
// Only by the type this diff reports: a column altered for its default loses nothing.
|
|
165
|
+
isBreaking: typeChanged && isBreakingTypeChange(actualType, expectedType),
|
|
174
166
|
};
|
|
175
167
|
}
|
|
176
168
|
/** The differences between two lists of foreign keys, matched by their columns and never by the name the engine gave them. */
|
|
177
169
|
export function diffRelationshipNodes(source, target) {
|
|
178
|
-
const { created, dropped, matched } = matchByKey(source, target,
|
|
170
|
+
const { created, dropped, matched } = matchByKey(source, target, relationshipKey);
|
|
179
171
|
return [
|
|
180
172
|
...created.map((relation) => ({ ...relationEnds(relation), to: relation })),
|
|
181
173
|
...dropped.map((relation) => ({ ...relationEnds(relation), from: relation })),
|
|
@@ -199,35 +191,10 @@ function diffRelationship(source, target) {
|
|
|
199
191
|
}
|
|
200
192
|
return undefined;
|
|
201
193
|
}
|
|
202
|
-
/**
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
const fromCols = rel.from.columns
|
|
207
|
-
.map((c) => c.name)
|
|
208
|
-
.sort()
|
|
209
|
-
.join(',');
|
|
210
|
-
const toCols = rel.to.columns
|
|
211
|
-
.map((c) => c.name)
|
|
212
|
-
.sort()
|
|
213
|
-
.join(',');
|
|
214
|
-
return `${rel.from.table.name}.${fromCols}->${rel.to.table.name}.${toCols}`;
|
|
215
|
-
}
|
|
216
|
-
/**
|
|
217
|
-
* Format a canonical type for display.
|
|
218
|
-
*/
|
|
219
|
-
function formatType(type) {
|
|
220
|
-
let result = type.category;
|
|
221
|
-
if (type.size)
|
|
222
|
-
result += `(${type.size})`;
|
|
223
|
-
if (type.length)
|
|
224
|
-
result += `(${type.length})`;
|
|
225
|
-
if (type.precision) {
|
|
226
|
-
result += type.scale !== undefined ? `(${type.precision},${type.scale})` : `(${type.precision})`;
|
|
227
|
-
}
|
|
228
|
-
if (type.unsigned)
|
|
229
|
-
result += ' unsigned';
|
|
230
|
-
return result;
|
|
194
|
+
/** What a foreign key is: its two tables, and each of its columns with the one it points at, in any order. */
|
|
195
|
+
function relationshipKey(rel) {
|
|
196
|
+
const pairs = rel.from.columns.map((column, at) => `${column.name}>${rel.to.columns[at].name}`).sort();
|
|
197
|
+
return `${rel.from.table.name}->${rel.to.table.name}:${pairs.join(',')}`;
|
|
231
198
|
}
|
|
232
199
|
/**
|
|
233
200
|
* Compares two defaults exactly as written, for when no dialect renders them: SQL must match to the letter.
|