uql-orm 0.97.0 → 0.99.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.
Files changed (114) hide show
  1. package/dist/dialect/abstractSqlDialect.d.ts +1 -7
  2. package/dist/dialect/abstractSqlDialect.js +1 -9
  3. package/dist/dialect/mysqlLikeSqlDialect.d.ts +2 -0
  4. package/dist/dialect/mysqlLikeSqlDialect.js +4 -1
  5. package/dist/dialect/pgLikeSqlDialect.js +0 -1
  6. package/dist/migrate/acquireQuerierForMigrations.d.ts +4 -8
  7. package/dist/migrate/acquireQuerierForMigrations.js +10 -18
  8. package/dist/migrate/builder/columnBuilder.d.ts +1 -2
  9. package/dist/migrate/builder/columnBuilder.js +3 -10
  10. package/dist/migrate/builder/migrationBuilder.d.ts +6 -26
  11. package/dist/migrate/builder/migrationBuilder.js +21 -78
  12. package/dist/migrate/builder/tableBuilder.js +2 -3
  13. package/dist/migrate/builder/types.d.ts +57 -120
  14. package/dist/migrate/cli-config.d.ts +1 -0
  15. package/dist/migrate/cli-config.js +11 -26
  16. package/dist/migrate/cli.d.ts +0 -13
  17. package/dist/migrate/cli.js +55 -118
  18. package/dist/migrate/codegen/entityCodeGenerator.d.ts +7 -61
  19. package/dist/migrate/codegen/entityCodeGenerator.js +51 -168
  20. package/dist/migrate/codegen/fieldOptionsSource.js +3 -6
  21. package/dist/migrate/codegen/index.d.ts +2 -7
  22. package/dist/migrate/codegen/index.js +2 -8
  23. package/dist/migrate/codegen/migrationFile.d.ts +1 -8
  24. package/dist/migrate/codegen/migrationFile.js +9 -13
  25. package/dist/migrate/ddl/defaultSql.d.ts +2 -1
  26. package/dist/migrate/ddl/defaultSql.js +1 -3
  27. package/dist/migrate/ddl/indexCapabilities.d.ts +18 -0
  28. package/dist/migrate/ddl/indexCapabilities.js +60 -0
  29. package/dist/migrate/ddl/indexDdl.d.ts +11 -24
  30. package/dist/migrate/ddl/indexDdl.js +22 -28
  31. package/dist/migrate/ddl/mssqlIndexDdl.d.ts +1 -7
  32. package/dist/migrate/ddl/mssqlIndexDdl.js +1 -7
  33. package/dist/migrate/ddl/mssqlTableDdl.d.ts +6 -9
  34. package/dist/migrate/ddl/mssqlTableDdl.js +14 -17
  35. package/dist/migrate/ddl/mysqlIndexDdl.d.ts +0 -21
  36. package/dist/migrate/ddl/mysqlIndexDdl.js +4 -48
  37. package/dist/migrate/ddl/mysqlTableDdl.d.ts +6 -5
  38. package/dist/migrate/ddl/mysqlTableDdl.js +15 -10
  39. package/dist/migrate/ddl/pgIndexDdl.d.ts +0 -10
  40. package/dist/migrate/ddl/pgIndexDdl.js +5 -44
  41. package/dist/migrate/ddl/pgTableDdl.d.ts +6 -2
  42. package/dist/migrate/ddl/pgTableDdl.js +17 -1
  43. package/dist/migrate/ddl/sqliteIndexDdl.js +2 -7
  44. package/dist/migrate/ddl/tableDdl.d.ts +43 -24
  45. package/dist/migrate/ddl/tableDdl.js +56 -37
  46. package/dist/migrate/ddl/tableRebuild.d.ts +2 -1
  47. package/dist/migrate/drift/driftDetector.d.ts +29 -32
  48. package/dist/migrate/drift/driftDetector.js +139 -205
  49. package/dist/migrate/drift/index.d.ts +1 -6
  50. package/dist/migrate/drift/index.js +1 -6
  51. package/dist/migrate/generator/definitionToNode.js +3 -3
  52. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +53 -76
  53. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +68 -90
  54. package/dist/migrate/introspection/mssqlIntrospector.d.ts +8 -43
  55. package/dist/migrate/introspection/mssqlIntrospector.js +44 -77
  56. package/dist/migrate/introspection/mysqlIntrospector.d.ts +11 -38
  57. package/dist/migrate/introspection/mysqlIntrospector.js +48 -57
  58. package/dist/migrate/introspection/postgresIntrospector.d.ts +12 -60
  59. package/dist/migrate/introspection/postgresIntrospector.js +62 -77
  60. package/dist/migrate/introspection/sqliteIntrospector.d.ts +14 -53
  61. package/dist/migrate/introspection/sqliteIntrospector.js +59 -119
  62. package/dist/migrate/introspection/tableSchemaAST.d.ts +13 -0
  63. package/dist/migrate/introspection/tableSchemaAST.js +85 -0
  64. package/dist/migrate/migrationTarget.js +10 -2
  65. package/dist/migrate/migrator.d.ts +14 -37
  66. package/dist/migrate/migrator.js +89 -126
  67. package/dist/migrate/schemaChange.d.ts +0 -2
  68. package/dist/migrate/schemaChange.js +1 -1
  69. package/dist/migrate/schemaGenerator.d.ts +22 -97
  70. package/dist/migrate/schemaGenerator.js +113 -298
  71. package/dist/migrate/storage/databaseStorage.d.ts +2 -1
  72. package/dist/migrate/storage/databaseStorage.js +3 -2
  73. package/dist/migrate/storage/jsonStorage.d.ts +1 -2
  74. package/dist/migrate/storage/jsonStorage.js +11 -20
  75. package/dist/migrate/triggerSql.d.ts +3 -3
  76. package/dist/migrate/triggerSql.js +5 -4
  77. package/dist/mongo/index.d.ts +0 -1
  78. package/dist/mongo/index.js +0 -1
  79. package/dist/mongo/mongoDialect.js +0 -1
  80. package/dist/mongo/mongoIntrospector.d.ts +0 -3
  81. package/dist/mongo/mongoIntrospector.js +7 -14
  82. package/dist/mongo/mongoSchemaGenerator.d.ts +7 -20
  83. package/dist/mongo/mongoSchemaGenerator.js +51 -70
  84. package/dist/mssql/mssqlDialect.js +0 -1
  85. package/dist/schema/canonicalType.d.ts +15 -19
  86. package/dist/schema/canonicalType.js +20 -43
  87. package/dist/schema/dependencyGraph.d.ts +2 -3
  88. package/dist/schema/dependencyGraph.js +0 -4
  89. package/dist/schema/indexDifferences.js +2 -2
  90. package/dist/schema/schemaAST.d.ts +1 -1
  91. package/dist/schema/schemaAST.js +4 -12
  92. package/dist/schema/schemaASTBuilder.d.ts +2 -5
  93. package/dist/schema/schemaASTBuilder.js +11 -14
  94. package/dist/schema/schemaASTDiffer.d.ts +4 -5
  95. package/dist/schema/schemaASTDiffer.js +22 -70
  96. package/dist/schema/types.d.ts +1 -48
  97. package/dist/sqlite/localSqliteQuerierPool.d.ts +16 -2
  98. package/dist/sqlite/localSqliteQuerierPool.js +20 -4
  99. package/dist/sqlite/nodeSqliteQuerierPool.js +2 -2
  100. package/dist/sqlite/sqliteDialect.js +0 -1
  101. package/dist/sqlite/sqliteQuerierPool.js +3 -3
  102. package/dist/type/dialect.d.ts +0 -2
  103. package/dist/type/migration.d.ts +3 -54
  104. package/dist/util/ddlExpression.util.d.ts +2 -2
  105. package/dist/util/ddlExpression.util.js +3 -3
  106. package/dist/util/sql.util.d.ts +0 -8
  107. package/dist/util/sql.util.js +7 -12
  108. package/package.json +1 -1
  109. package/dist/migrate/introspection/baseSqlIntrospector.d.ts +0 -36
  110. package/dist/migrate/introspection/baseSqlIntrospector.js +0 -133
  111. package/dist/schema/index.d.ts +0 -2
  112. package/dist/schema/index.js +0 -1
  113. package/dist/sqlite/sqlitePragmas.d.ts +0 -3
  114. 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
- * Parse a SQL type string into a canonical type.
242
- * Handles complex types like VARCHAR(255), DECIMAL(10,2), etc.
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 blob, the dimensions for a vector: `VARCHAR(255)`, `VECTOR(1536)`.
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
- export function withTimestampPrecision(type, digits) {
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
- const timestampPrecision = defaultTimestampPrecision(dialect.dialectName);
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 canonicalColumnType(declared, options);
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
- export type DependenciesOf<N> = (node: N) => Iterable<N>;
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
- /** Nodes in drop order, dependents first. */
12
- export declare function dropOrder<N>(nodes: Iterable<N>, dependenciesOf: DependenciesOf<N>): N[];
11
+ export {};
@@ -24,7 +24,3 @@ export function createOrder(nodes, dependenciesOf) {
24
24
  }
25
25
  return ordered;
26
26
  }
27
- /** Nodes in drop order, dependents first. */
28
- export function dropOrder(nodes, dependenciesOf) {
29
- return createOrder(nodes, dependenciesOf).reverse();
30
- }
@@ -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
- * the `idx_Order_total` it wrote until 0.42.1.
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 wrote `idx_User_email` until 0.42.1, and a database it did not
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 and both column sets. */
21
+ /** Adds a foreign key, linking it from both tables. */
22
22
  addRelationship(rel: RelationshipNode): void;
23
23
  }
@@ -1,5 +1,5 @@
1
1
  import { qualifyName } from '../util/sql.util.js';
2
- import { createOrder, dropOrder } from './dependencyGraph.js';
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 {
@@ -40,24 +40,16 @@ export class SchemaAST {
40
40
  }
41
41
  /** Tables in `DROP` order, each before the tables it references. */
42
42
  getDropOrder() {
43
- return dropOrder(this.tables.values(), referencedTables);
43
+ return this.getCreateOrder().reverse();
44
44
  }
45
45
  addIndex(index) {
46
- if (!index.table.indexes.includes(index)) {
47
- index.table.indexes.push(index);
48
- }
46
+ index.table.indexes.push(index);
49
47
  }
50
- /** Adds a foreign key, linking it from both tables and both column sets. */
48
+ /** Adds a foreign key, linking it from both tables. */
51
49
  addRelationship(rel) {
52
50
  this.relationships.push(rel);
53
51
  rel.from.table.outgoingRelations.push(rel);
54
52
  rel.to.table.incomingRelations.push(rel);
55
- for (const col of rel.from.columns) {
56
- col.references = rel;
57
- }
58
- for (const col of rel.to.columns) {
59
- col.referencedBy.push(rel);
60
- }
61
53
  }
62
54
  }
63
55
  function referencedTables(table) {
@@ -1,5 +1,4 @@
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
3
  import { type ForeignKeyAction, type TriggerSchema } from './types.js';
5
4
  /**
@@ -12,16 +11,14 @@ 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. `buildEntityAST` supplies it from the generator.
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. `buildEntityAST` supplies it. */
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;
@@ -17,14 +17,13 @@ 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 ?? ((m) => namingStrategy?.tableName(entityName(m)) ?? entityName(m)),
24
+ resolveTableName: options.resolveTableName ?? entityName,
26
25
  resolveSchema: options.resolveSchema ?? ((m) => m.schema),
27
- resolveColumnName: options.resolveColumnName ?? ((k, f) => namingStrategy?.columnName(f.name ?? k) ?? f.name ?? k),
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,
@@ -45,7 +44,7 @@ export function buildSchemaAST(entities, options = {}) {
45
44
  }
46
45
  /** The `compileDdl` of a build given no dialect, which has nothing to render an entity's SQL with. */
47
46
  function refuseDdl() {
48
- 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 `buildEntityAST` does');
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');
49
48
  }
50
49
  /** The entries a vector index of `meta` covers: the members it names, and any expression. */
51
50
  function vectorIndexedEntries(meta) {
@@ -83,8 +82,6 @@ function addTableFromEntity(ctx, meta) {
83
82
  generatedAs: field.stored === true && field.computed ? ctx.compileDdl(field.computed, meta.entity) : undefined,
84
83
  comment: field.comment,
85
84
  table,
86
- referencedBy: [],
87
- references: undefined,
88
85
  };
89
86
  columns.set(columnName, column);
90
87
  table.checks.push(...enumCheck(tableName, { name: columnName, enum: field.enum }, (sql) => ctx.compileDdl(sql, meta.entity)));
@@ -166,10 +163,10 @@ function isIndexedBy(table, columns) {
166
163
  const leads = (indexed) => columns.every((column, at) => indexed[at] === column);
167
164
  return leads(table.primaryKey?.columns ?? []) || table.indexes.some((index) => leads(lookupColumns(index)));
168
165
  }
169
- /** An `include` column is named like any other, so a naming strategy has to reach it too. */
170
- function resolveIncludeColumn(ctx, meta, column) {
171
- const field = meta.fields[column];
172
- return field ? ctx.resolveColumnName(column, field) : column;
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);
173
170
  }
174
171
  /**
175
172
  * One index the entity declares. Its entries keep the authored form (expression, prefix length, order) with
@@ -178,12 +175,11 @@ function resolveIncludeColumn(ctx, meta, column) {
178
175
  */
179
176
  function addCompositeIndex(ctx, table, meta, { columns, include, where, ...options }) {
180
177
  // An entry survives if it is an expression (nothing to resolve) or names a column that exists;
181
- // an index left with none is dropped, the same as one naming only unknown columns always was.
178
+ // an index left with none is dropped, as one naming only unknown columns is.
182
179
  const resolved = columns.flatMap((entry) => {
183
180
  if (typeof entry.column !== 'string')
184
181
  return [entry];
185
- const field = meta.fields[entry.column];
186
- const column = field && ctx.resolveColumnName(entry.column, field);
182
+ const column = fieldColumn(ctx, meta, entry.column);
187
183
  return column && table.columns.has(column) ? [{ ...entry, column }] : [];
188
184
  });
189
185
  if (!resolved.length)
@@ -194,7 +190,8 @@ function addCompositeIndex(ctx, table, meta, { columns, include, where, ...optio
194
190
  name,
195
191
  table,
196
192
  entries: resolved.map((entry) => renderIndexColumn(entry, (sql) => ctx.compileDdl(sql, meta.entity))),
197
- include: include?.map((column) => resolveIncludeColumn(ctx, meta, column)),
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),
198
195
  unique: options.unique ?? false,
199
196
  where: where && ctx.compileIndexPredicate(where, meta.entity, name),
200
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
- /** The differences between two tables, shared by migrations and drift detection so they cannot disagree. */
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:
@@ -4,12 +4,7 @@ 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,24 +23,26 @@ 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: altered.flatMap((tableDiff) => tableDiff.indexes),
26
+ indexes: matched.flatMap(([sourceTable, targetTable]) => diffTableIndexes(sourceTable, targetTable)),
32
27
  checks: altered.flatMap((tableDiff) => tableDiff.checks),
33
28
  triggers: altered.flatMap((tableDiff) => tableDiff.triggers),
34
29
  primaryKeys: altered.flatMap((tableDiff) => tableDiff.primaryKey ?? []),
35
30
  // Relationships span tables, so they are compared over the whole schema rather than per table.
36
- relationships: opts.compareRelationships ? diffRelationshipNodes(source.relationships, target.relationships) : [],
31
+ relationships: diffRelationshipNodes(source.relationships, target.relationships),
37
32
  };
38
33
  }
39
- /** The differences between two tables, shared by migrations and drift detection so they cannot disagree. */
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
+ */
40
38
  export function diffTable(source, target, options = {}) {
41
39
  const opts = { ...DEFAULT_OPTIONS, ...options };
42
40
  const columns = diffTableColumns(source, target, opts);
43
- const indexes = opts.compareIndexes ? diffTableIndexes(source, target) : [];
44
41
  const checks = diffOwned(source.name, source.checks, target.checks);
45
42
  const triggers = diffOwned(source.name, source.triggers, target.triggers);
46
43
  const primaryKey = diffPrimaryKey(source, target);
47
- return columns.length || indexes.length || checks.length || triggers.length || primaryKey
48
- ? { columns, indexes, checks, triggers, primaryKey }
44
+ return columns.length || checks.length || triggers.length || primaryKey
45
+ ? { columns, checks, triggers, primaryKey }
49
46
  : undefined;
50
47
  }
51
48
  /**
@@ -66,9 +63,6 @@ function diffPrimaryKey(source, target) {
66
63
  }
67
64
  return { table: source.name, from: target.primaryKey, to: source.primaryKey };
68
65
  }
69
- /**
70
- * Compare columns between two tables.
71
- */
72
66
  function diffTableColumns(source, target, opts) {
73
67
  const { created, dropped, matched } = matchByKey(source.columns.values(), target.columns.values(), (column) => column.name);
74
68
  return [
@@ -76,14 +70,12 @@ function diffTableColumns(source, target, opts) {
76
70
  table: source.name,
77
71
  column: column.name,
78
72
  to: column,
79
- description: `Add column "${column.name}"`,
80
73
  })),
81
74
  ...dropped.map((column) => ({
82
75
  table: target.name,
83
76
  column: column.name,
84
77
  from: column,
85
78
  isBreaking: true,
86
- description: `Drop column "${column.name}"`,
87
79
  })),
88
80
  ...matched
89
81
  .map(([sourceColumn, targetColumn]) => diffColumn(source.name, sourceColumn, targetColumn, opts))
@@ -135,11 +127,8 @@ function diffTableIndexes(source, target) {
135
127
  name: change.to === undefined ? change.from.name : change.to.name,
136
128
  }));
137
129
  }
138
- /**
139
- * Compare two columns and return the difference.
140
- */
130
+ /** How `target`, the database's column, differs from `source`, the entity's, or `undefined` where they agree. */
141
131
  function diffColumn(tableName, source, target, opts) {
142
- const differences = [];
143
132
  const changed = [];
144
133
  // A key column's type and nullability are implied, not stated, and catalogues report them
145
134
  // inconsistently (`BIGINT(20)`, SQLite's `notnull: 0` rowid), so neither is compared.
@@ -147,32 +136,23 @@ function diffColumn(tableName, source, target, opts) {
147
136
  const impliedNotNull = source.isPrimaryKey && target.isPrimaryKey;
148
137
  const expectedType = opts.normalizeType(source.type);
149
138
  const actualType = opts.normalizeType(target.type);
150
- const typeChanged = !generatedType && !areTypesEqual(expectedType, actualType);
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);
151
144
  if (typeChanged) {
152
- differences.push(`type: ${formatType(source.type)} -> ${formatType(target.type)}`);
153
- changed.push('type');
154
- }
155
- // Signedness is the one thing compared on a generated key, because it is the one part of the serial
156
- // spelling that does round trip - and a key left unsigned refuses every foreign key pointing at it,
157
- // since the referencing column takes its type from the canonical one, which is signed. Without this
158
- // a database created before the serial became signed could never gain a foreign key.
159
- const signednessChanged = generatedType && !!source.type.unsigned !== !!target.type.unsigned;
160
- if (signednessChanged) {
161
- differences.push(`type: ${formatType(source.type)} -> ${formatType(target.type)}`);
162
145
  changed.push('type');
163
146
  }
164
147
  if (!impliedNotNull && source.nullable !== target.nullable) {
165
- differences.push(`nullable: ${target.nullable} -> ${source.nullable}`);
166
148
  changed.push('nullable');
167
149
  }
168
150
  // Not compared, since no statement this generator emits could settle a difference: `isAutoIncrement`,
169
151
  // `generatedAs`, and `comment`. Nor `isUnique`: a unique column is a unique index, compared with the indexes.
170
- // Compare default values (if both defined)
171
152
  if (!opts.defaultsEqual(source.defaultValue, target.defaultValue)) {
172
- differences.push(`default: ${target.defaultValue ?? 'NULL'} -> ${source.defaultValue ?? 'NULL'}`);
173
153
  changed.push('default');
174
154
  }
175
- if (differences.length === 0) {
155
+ if (!changed.length) {
176
156
  return undefined;
177
157
  }
178
158
  return {
@@ -181,16 +161,13 @@ function diffColumn(tableName, source, target, opts) {
181
161
  from: target,
182
162
  to: source,
183
163
  changed,
184
- // Only the type this diff actually reports: a column altered for its default carries no data loss,
185
- // and a generated key's type - never compared above - reads as unsigned against an entity that
186
- // cannot say so.
187
- isBreaking: (typeChanged || signednessChanged) && isBreakingTypeChange(actualType, expectedType),
188
- 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),
189
166
  };
190
167
  }
191
168
  /** The differences between two lists of foreign keys, matched by their columns and never by the name the engine gave them. */
192
169
  export function diffRelationshipNodes(source, target) {
193
- const { created, dropped, matched } = matchByKey(source, target, getRelationshipKey);
170
+ const { created, dropped, matched } = matchByKey(source, target, relationshipKey);
194
171
  return [
195
172
  ...created.map((relation) => ({ ...relationEnds(relation), to: relation })),
196
173
  ...dropped.map((relation) => ({ ...relationEnds(relation), from: relation })),
@@ -214,35 +191,10 @@ function diffRelationship(source, target) {
214
191
  }
215
192
  return undefined;
216
193
  }
217
- /**
218
- * Generate a unique key for a relationship based on its structure.
219
- */
220
- function getRelationshipKey(rel) {
221
- const fromCols = rel.from.columns
222
- .map((c) => c.name)
223
- .sort()
224
- .join(',');
225
- const toCols = rel.to.columns
226
- .map((c) => c.name)
227
- .sort()
228
- .join(',');
229
- return `${rel.from.table.name}.${fromCols}->${rel.to.table.name}.${toCols}`;
230
- }
231
- /**
232
- * Format a canonical type for display.
233
- */
234
- function formatType(type) {
235
- let result = type.category;
236
- if (type.size)
237
- result += `(${type.size})`;
238
- if (type.length)
239
- result += `(${type.length})`;
240
- if (type.precision) {
241
- result += type.scale !== undefined ? `(${type.precision},${type.scale})` : `(${type.precision})`;
242
- }
243
- if (type.unsigned)
244
- result += ' unsigned';
245
- 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(',')}`;
246
198
  }
247
199
  /**
248
200
  * Compares two defaults exactly as written, for when no dialect renders them: SQL must match to the letter.
@@ -93,12 +93,8 @@ export interface ColumnNode {
93
93
  readonly generatedAs?: string;
94
94
  /** Column comment/description */
95
95
  readonly comment?: string;
96
- /** Reference to the parent table */
96
+ /** The table the column is in. */
97
97
  table: TableNode;
98
- /** Relationships where this column is referenced (FKs pointing TO this column) */
99
- referencedBy: RelationshipNode[];
100
- /** Relationship where this column is the foreign key (FK this column points FROM) */
101
- references?: RelationshipNode;
102
98
  }
103
99
  /**
104
100
  * Table node in the schema graph.
@@ -194,7 +190,6 @@ export type ColumnDiff = NodeChange<ColumnNode, {
194
190
  readonly column: string;
195
191
  /** Whether the change can lose data: a drop, or a type change that narrows the column. */
196
192
  readonly isBreaking?: boolean;
197
- readonly description?: string;
198
193
  };
199
194
  /** A part of a column the differ compares. */
200
195
  export type ColumnFacet = 'type' | 'nullable' | 'default';
@@ -222,7 +217,6 @@ export type TableChange<T> = Change<T> & {
222
217
  /** The differences within a table that exists on both sides. */
223
218
  export interface TableDiff {
224
219
  readonly columns: ColumnDiff[];
225
- readonly indexes: IndexDiff[];
226
220
  /** A check or trigger only one side has. Never both: a changed one is a new name, one dropped and one added. */
227
221
  readonly checks: TableChange<CheckSchema>[];
228
222
  readonly triggers: TableChange<TriggerSchema>[];
@@ -240,44 +234,3 @@ export interface SchemaDiffResult {
240
234
  readonly primaryKeys: PrimaryKeyDiff[];
241
235
  readonly relationships: RelationshipDiff[];
242
236
  }
243
- /**
244
- * Severity level for schema drift issues.
245
- */
246
- export type DriftSeverity = 'critical' | 'warning' | 'info';
247
- /**
248
- * Type of schema drift.
249
- */
250
- export type DriftType = 'missing_table' | 'unexpected_table' | 'missing_column' | 'unexpected_column' | 'type_mismatch' | 'constraint_mismatch' | 'missing_index' | 'unexpected_index' | 'index_mismatch' | 'missing_relationship' | 'unexpected_relationship' | 'relationship_mismatch';
251
- /**
252
- * A single schema drift issue.
253
- */
254
- export interface Drift {
255
- readonly type: DriftType;
256
- readonly severity: DriftSeverity;
257
- readonly table?: string;
258
- readonly column?: string;
259
- readonly index?: string;
260
- readonly relationship?: string;
261
- readonly expected?: unknown;
262
- readonly actual?: unknown;
263
- readonly details: string;
264
- readonly suggestion: string;
265
- }
266
- /**
267
- * Overall drift status.
268
- */
269
- export type DriftStatus = 'in_sync' | 'drifted' | 'critical';
270
- /**
271
- * Complete drift detection report.
272
- */
273
- export interface DriftReport {
274
- readonly status: DriftStatus;
275
- readonly drifts: Drift[];
276
- readonly generatedAt: Date;
277
- /** Count by severity */
278
- readonly summary: {
279
- readonly critical: number;
280
- readonly warning: number;
281
- readonly info: number;
282
- };
283
- }