uql-orm 0.91.1 → 0.92.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 (156) hide show
  1. package/dist/browser/http/bus.js +3 -4
  2. package/dist/browser/http/http.d.ts +1 -2
  3. package/dist/browser/http/http.js +8 -7
  4. package/dist/browser/index.d.ts +0 -1
  5. package/dist/browser/index.js +0 -1
  6. package/dist/browser/querier/httpQuerier.d.ts +18 -20
  7. package/dist/browser/querier/httpQuerier.js +20 -56
  8. package/dist/browser/type/index.d.ts +0 -1
  9. package/dist/browser/type/index.js +0 -1
  10. package/dist/browser/uql-browser.min.js +2 -2
  11. package/dist/browser/uql-browser.min.js.map +11 -12
  12. package/dist/cockroachdb/cockroachDialect.d.ts +4 -1
  13. package/dist/cockroachdb/cockroachDialect.js +5 -1
  14. package/dist/dialect/abstractDialect.d.ts +1 -1
  15. package/dist/dialect/abstractDialect.js +4 -1
  16. package/dist/dialect/abstractSqlDialect.d.ts +24 -28
  17. package/dist/dialect/abstractSqlDialect.js +47 -45
  18. package/dist/dialect/aliases.d.ts +4 -1
  19. package/dist/dialect/aliases.js +5 -2
  20. package/dist/dialect/hydrateColumn.js +3 -10
  21. package/dist/dialect/jsonSql.d.ts +4 -1
  22. package/dist/dialect/jsonSql.js +4 -1
  23. package/dist/dialect/mergeSqlDialect.d.ts +4 -3
  24. package/dist/dialect/mergeSqlDialect.js +5 -4
  25. package/dist/dialect/mysqlLikeSqlDialect.d.ts +7 -21
  26. package/dist/dialect/mysqlLikeSqlDialect.js +9 -36
  27. package/dist/dialect/pgLikeSqlDialect.d.ts +3 -7
  28. package/dist/dialect/pgLikeSqlDialect.js +11 -21
  29. package/dist/http/contract.d.ts +4 -0
  30. package/dist/http/contract.js +1 -0
  31. package/dist/http/handler.d.ts +2 -2
  32. package/dist/http/handler.js +17 -19
  33. package/dist/http/query.d.ts +5 -3
  34. package/dist/http/query.js +42 -42
  35. package/dist/index.d.ts +1 -1
  36. package/dist/index.js +1 -1
  37. package/dist/maria/mariaDialect.d.ts +2 -3
  38. package/dist/maria/mariaDialect.js +1 -5
  39. package/dist/migrate/builder/columnBuilder.d.ts +5 -15
  40. package/dist/migrate/builder/columnBuilder.js +50 -86
  41. package/dist/migrate/builder/expressions.d.ts +12 -18
  42. package/dist/migrate/builder/expressions.js +39 -42
  43. package/dist/migrate/builder/migrationBuilder.d.ts +3 -11
  44. package/dist/migrate/builder/migrationBuilder.js +41 -81
  45. package/dist/migrate/builder/tableBuilder.d.ts +0 -7
  46. package/dist/migrate/builder/tableBuilder.js +17 -28
  47. package/dist/migrate/builder/types.d.ts +2 -2
  48. package/dist/migrate/codegen/entityCodeGenerator.js +3 -3
  49. package/dist/migrate/codegen/entityTypes.js +2 -2
  50. package/dist/migrate/codegen/fieldOptionsSource.d.ts +2 -2
  51. package/dist/migrate/codegen/fieldOptionsSource.js +27 -12
  52. package/dist/migrate/codegen/indexDecoratorSource.js +64 -41
  53. package/dist/migrate/ddl/index.d.ts +2 -4
  54. package/dist/migrate/ddl/index.js +14 -5
  55. package/dist/migrate/ddl/mssqlTableDdl.d.ts +1 -0
  56. package/dist/migrate/ddl/mssqlTableDdl.js +4 -1
  57. package/dist/migrate/ddl/mysqlTableDdl.d.ts +17 -0
  58. package/dist/migrate/ddl/mysqlTableDdl.js +33 -0
  59. package/dist/migrate/ddl/pgTableDdl.d.ts +7 -0
  60. package/dist/migrate/ddl/pgTableDdl.js +17 -0
  61. package/dist/migrate/ddl/tableDdl.d.ts +15 -10
  62. package/dist/migrate/ddl/tableDdl.js +31 -32
  63. package/dist/migrate/drift/driftDetector.js +46 -59
  64. package/dist/migrate/generator/definitionToNode.d.ts +11 -7
  65. package/dist/migrate/generator/definitionToNode.js +27 -34
  66. package/dist/migrate/generator/indexNodeToSchema.d.ts +3 -3
  67. package/dist/migrate/generator/indexNodeToSchema.js +5 -4
  68. package/dist/migrate/index.js +1 -1
  69. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +10 -5
  70. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +10 -0
  71. package/dist/migrate/introspection/baseSqlIntrospector.d.ts +0 -1
  72. package/dist/migrate/introspection/baseSqlIntrospector.js +6 -8
  73. package/dist/migrate/introspection/mssqlIntrospector.js +3 -8
  74. package/dist/migrate/introspection/mysqlIntrospector.d.ts +11 -4
  75. package/dist/migrate/introspection/mysqlIntrospector.js +25 -11
  76. package/dist/migrate/introspection/postgresIntrospector.d.ts +2 -2
  77. package/dist/migrate/introspection/postgresIntrospector.js +3 -3
  78. package/dist/migrate/introspection/sqliteIntrospector.d.ts +1 -1
  79. package/dist/migrate/introspection/sqliteIntrospector.js +7 -10
  80. package/dist/migrate/migrationTarget.js +3 -3
  81. package/dist/migrate/schemaGenerator.d.ts +8 -12
  82. package/dist/migrate/schemaGenerator.js +35 -61
  83. package/dist/migrate/triggerSql.d.ts +1 -1
  84. package/dist/migrate/triggerSql.js +8 -6
  85. package/dist/mongo/mongoDialect.d.ts +4 -3
  86. package/dist/mongo/mongoDialect.js +52 -38
  87. package/dist/mongo/mongoIntrospector.js +1 -1
  88. package/dist/mongo/mongoSchemaGenerator.d.ts +7 -4
  89. package/dist/mongo/mongoSchemaGenerator.js +18 -21
  90. package/dist/mongo/mongodbQuerier.d.ts +2 -3
  91. package/dist/mongo/mongodbQuerier.js +9 -28
  92. package/dist/mssql/mssqlDialect.d.ts +4 -5
  93. package/dist/mssql/mssqlDialect.js +9 -7
  94. package/dist/postgres/postgresDialect.js +2 -2
  95. package/dist/querier/abstractQuerier.d.ts +16 -11
  96. package/dist/querier/abstractQuerier.js +74 -26
  97. package/dist/querier/abstractQuerierPool.d.ts +26 -24
  98. package/dist/querier/abstractQuerierPool.js +26 -64
  99. package/dist/querier/abstractSqlQuerier.d.ts +2 -3
  100. package/dist/querier/abstractSqlQuerier.js +8 -26
  101. package/dist/querier/cursor.d.ts +10 -0
  102. package/dist/querier/cursor.js +81 -0
  103. package/dist/querier/keyset.d.ts +19 -0
  104. package/dist/querier/keyset.js +198 -0
  105. package/dist/schema/canonicalType.d.ts +3 -3
  106. package/dist/schema/canonicalType.js +13 -12
  107. package/dist/schema/indexDifferences.d.ts +14 -7
  108. package/dist/schema/indexDifferences.js +7 -5
  109. package/dist/schema/schemaAST.d.ts +0 -1
  110. package/dist/schema/schemaAST.js +0 -2
  111. package/dist/schema/schemaASTBuilder.js +28 -20
  112. package/dist/schema/schemaASTDiffer.d.ts +7 -9
  113. package/dist/schema/schemaASTDiffer.js +54 -107
  114. package/dist/schema/sqlExpression.d.ts +22 -0
  115. package/dist/schema/sqlExpression.js +28 -0
  116. package/dist/schema/types.d.ts +48 -105
  117. package/dist/sqlite/sqliteDialect.d.ts +9 -13
  118. package/dist/sqlite/sqliteDialect.js +10 -29
  119. package/dist/type/dialect.d.ts +20 -3
  120. package/dist/type/entity.d.ts +3 -3
  121. package/dist/type/migration.d.ts +7 -7
  122. package/dist/type/querier.d.ts +19 -26
  123. package/dist/type/query.d.ts +104 -24
  124. package/dist/type/query.js +21 -28
  125. package/dist/type/universalQuerier.d.ts +31 -5
  126. package/dist/type/utility.d.ts +10 -0
  127. package/dist/util/bytes.d.ts +7 -0
  128. package/dist/util/bytes.js +22 -0
  129. package/dist/util/date.d.ts +5 -0
  130. package/dist/util/date.js +5 -0
  131. package/dist/util/dialect.util.d.ts +1 -25
  132. package/dist/util/dialect.util.js +4 -50
  133. package/dist/util/field.util.d.ts +9 -0
  134. package/dist/util/field.util.js +15 -0
  135. package/dist/util/fieldOption.util.js +2 -2
  136. package/dist/util/index.d.ts +1 -0
  137. package/dist/util/index.js +1 -0
  138. package/dist/util/object.util.d.ts +0 -2
  139. package/dist/util/object.util.js +0 -7
  140. package/dist/util/query.util.d.ts +40 -0
  141. package/dist/util/query.util.js +76 -0
  142. package/dist/util/raw.d.ts +5 -0
  143. package/dist/util/raw.js +5 -0
  144. package/dist/util/relationQuery.util.js +18 -16
  145. package/dist/util/rowKey.util.js +2 -3
  146. package/dist/util/sql.util.d.ts +8 -2
  147. package/dist/util/sql.util.js +16 -17
  148. package/dist/util/sqlLiteral.js +2 -12
  149. package/dist/util/string.util.d.ts +5 -0
  150. package/dist/util/string.util.js +12 -0
  151. package/package.json +1 -1
  152. package/skills/uql-orm/SKILL.md +21 -10
  153. package/dist/browser/options.d.ts +0 -4
  154. package/dist/browser/options.js +0 -13
  155. package/dist/browser/type/clientQuerierPool.d.ts +0 -4
  156. package/dist/browser/type/clientQuerierPool.js +0 -1
@@ -1,5 +1,5 @@
1
- import { formatDefaultValue, sameDefault } from '../builder/expressions.js';
2
- import { lacksValue } from '../schemaChange.js';
1
+ import { UqlUsageError } from '../../util/uqlError.js';
2
+ import { formatDefaultValue } from '../builder/expressions.js';
3
3
  /**
4
4
  * A column's type with the size it was read back with, unless its spelling already carries one:
5
5
  * introspection reports `VARCHAR` and `255` apart, where a type from an entity is already whole.
@@ -15,14 +15,16 @@ export function sizedType(column) {
15
15
  return column.length === undefined ? column.type : `${column.type}(${column.length})`;
16
16
  }
17
17
  /**
18
- * The `ALTER TABLE` statements an engine spells its own way: the migrator's, for the reason
19
- * {@link IndexDdl} is. The form here is the portable one; SQL Server's is {@link MsSqlTableDdl}.
18
+ * Table DDL that engines spell differently. Like {@link IndexDdl}, it belongs to the migrator, so no runtime
19
+ * entry carries it. This class holds the portable form, which SQLite takes; other families override what differs.
20
20
  */
21
21
  export class TableDdl {
22
22
  dialect;
23
23
  constructor(dialect) {
24
24
  this.dialect = dialect;
25
25
  }
26
+ /** Options appended to `CREATE TABLE`, such as MySQL's engine; empty by default. */
27
+ tableOptions = '';
26
28
  /** A `CREATE TABLE` up to its column list, a no-op where `ifNotExists` and the table is already there. */
27
29
  createTable(target, ifNotExists) {
28
30
  return `CREATE TABLE ${ifNotExists ? 'IF NOT EXISTS ' : ''}${target}`;
@@ -30,41 +32,19 @@ export class TableDdl {
30
32
  addColumn(table, definition) {
31
33
  return `ALTER TABLE ${this.dialect.escapeId(table)} ADD COLUMN ${definition};`;
32
34
  }
33
- /**
34
- * `column` added, spelled by `render`. MySQL fills a zero into the rows already there for a required
35
- * column with no default, so there it is added nullable and required after, failing on them as elsewhere.
36
- */
35
+ /** The statements that add `column`, whose definition `render` writes. */
37
36
  addColumnStatements(table, column, render) {
38
- if (this.dialect.alterColumnSyntax !== 'MODIFY COLUMN' || !lacksValue(column)) {
39
- return [this.addColumn(table, render(column))];
40
- }
41
- return [
42
- this.addColumn(table, render({ ...column, nullable: true })),
43
- ...this.alterColumn(table, column, render(column)),
44
- ];
37
+ return [this.addColumn(table, render(column))];
45
38
  }
46
39
  dropColumn(table, column) {
47
40
  return [`ALTER TABLE ${this.dialect.escapeId(table)} DROP COLUMN ${this.dialect.escapeId(column)};`];
48
41
  }
49
42
  /**
50
- * What changes `column` to what it now declares. `definition` is the whole column, which MySQL's
51
- * `MODIFY COLUMN` restates; Postgres takes each change as a clause of its own, so given what the
52
- * column was (`from`), only the clauses that changed.
43
+ * The statements that change a column from `from`, what it was, to `column`, what it now declares.
44
+ * `definition` is the complete new column definition.
53
45
  */
54
- alterColumn(table, column, definition, from) {
55
- const target = this.dialect.escapeId(table);
56
- if (this.dialect.alterColumnStrategy !== 'separate-clauses') {
57
- return [`ALTER TABLE ${target} ${this.dialect.alterColumnSyntax} ${definition};`];
58
- }
59
- const name = this.dialect.escapeId(column.name);
60
- const alter = `ALTER TABLE ${target} ALTER COLUMN ${name}`;
61
- return [
62
- // Cast, since the engine converts only between types it deems compatible: text to integer needs saying.
63
- (!from || from.type !== column.type) && `${alter} TYPE ${column.type} USING ${name}::${column.type};`,
64
- (!from || from.nullable !== column.nullable) && `${alter} ${column.nullable ? 'DROP NOT NULL' : 'SET NOT NULL'};`,
65
- (!from || !sameDefault(column.defaultValue, from.defaultValue, this.dialect)) &&
66
- (column.defaultValue === undefined ? `${alter} DROP DEFAULT;` : `${alter} SET${this.defaultClause(column)};`),
67
- ].filter((statement) => statement !== false);
46
+ alterColumn(table, _column, definition, _from) {
47
+ return [`ALTER TABLE ${this.dialect.escapeId(table)} ALTER COLUMN ${definition};`];
68
48
  }
69
49
  renameColumn(table, oldName, newName) {
70
50
  const [target, from, to] = [table, oldName, newName].map((name) => this.dialect.escapeId(name));
@@ -73,6 +53,21 @@ export class TableDdl {
73
53
  renameTable(oldName, newName) {
74
54
  return `ALTER TABLE ${this.dialect.escapeId(oldName)} RENAME TO ${this.dialect.escapeId(newName)};`;
75
55
  }
56
+ /** `schema` is the table's schema, which also holds its indexes. */
57
+ dropIndex(table, index, schema) {
58
+ return `DROP INDEX IF EXISTS ${this.dialect.escapeQualifiedId(index, schema)};`;
59
+ }
60
+ dropForeignKey(table, constraint) {
61
+ return `ALTER TABLE ${this.dialect.escapeId(table)} DROP CONSTRAINT ${this.dialect.escapeId(constraint)};`;
62
+ }
63
+ /** Drops the primary key by its real constraint name: the introspected one, or the one uql derived when adding it. */
64
+ dropPrimaryKey(table, constraint) {
65
+ if (!constraint) {
66
+ throw new UqlUsageError(`Cannot drop the primary key of "${table}": ${this.dialect.dialectName} names the constraint, and ` +
67
+ 'introspection did not report a name for it.');
68
+ }
69
+ return `ALTER TABLE ${this.dialect.escapeId(table)} DROP CONSTRAINT ${this.dialect.escapeId(constraint)};`;
70
+ }
76
71
  /** A stored generated column's type, with the clause computing it. */
77
72
  storedGeneratedColumn(type, expression) {
78
73
  return `${type} GENERATED ALWAYS AS (${expression}) STORED`;
@@ -87,3 +82,7 @@ export class TableDdl {
87
82
  : ` DEFAULT ${formatDefaultValue(column.defaultValue, this.dialect, column.type)}`;
88
83
  }
89
84
  }
85
+ /** `DROP INDEX <index> ON <table>`, for engines that scope index names per table: MySQL and SQL Server. */
86
+ export function dropIndexOnTable(dialect, table, index) {
87
+ return `DROP INDEX ${dialect.escapeId(index)} ON ${dialect.escapeId(table)};`;
88
+ }
@@ -30,8 +30,7 @@ export function detectDrift(expectedAST, actualAST, options = {}) {
30
30
  compareRelationships: opts.checkForeignKeys,
31
31
  excludeTables: opts.excludeTables,
32
32
  defaultsEqual: opts.defaultsEqual,
33
- // Without a dialect there is no engine to compare through, and `formatType` below then reports no
34
- // type drift at all.
33
+ // Types are normalized through the dialect's engine; without a dialect, no type drift is reported.
35
34
  ...(dialect && { normalizeType: engineType(dialect) }),
36
35
  });
37
36
  const drifts = [
@@ -55,11 +54,11 @@ export function detectDrift(expectedAST, actualAST, options = {}) {
55
54
  * are not the rows the ORM believes are unique, so it addresses by a key nothing enforces.
56
55
  */
57
56
  function detectPrimaryKeyDrifts(diff) {
58
- return diff.primaryKeyDiffs.map((pkDiff) => ({
57
+ return diff.primaryKeys.map((pkDiff) => ({
59
58
  type: 'constraint_mismatch',
60
59
  severity: 'critical',
61
60
  table: pkDiff.table,
62
- details: `Primary key of "${pkDiff.table}" is (${keyColumns(pkDiff.actual)}) in the database but (${keyColumns(pkDiff.expected)}) in the entity`,
61
+ details: `Primary key of "${pkDiff.table}" is (${keyColumns(pkDiff.from)}) in the database but (${keyColumns(pkDiff.to)}) in the entity`,
63
62
  suggestion: 'Generate a migration to change the primary key',
64
63
  }));
65
64
  }
@@ -71,34 +70,29 @@ function keyColumns(key) {
71
70
  * Detect table-level drifts (missing/unexpected tables).
72
71
  */
73
72
  function detectTableDrifts(diff) {
74
- const drifts = [];
75
- for (const table of diff.tablesToCreate) {
76
- drifts.push({
73
+ return diff.tables.map((change) => change.from === undefined
74
+ ? {
77
75
  type: 'missing_table',
78
76
  severity: 'critical',
79
- table: table.name,
80
- details: `Entity "${table.name}" exists but table not in database`,
77
+ table: change.to.name,
78
+ details: `Entity "${change.to.name}" exists but table not in database`,
81
79
  suggestion: 'Run migrations to create table',
82
- });
83
- }
84
- for (const table of diff.tablesToDrop) {
85
- drifts.push({
80
+ }
81
+ : {
86
82
  type: 'unexpected_table',
87
83
  severity: 'warning',
88
- table: table.name,
89
- details: `Table "${table.name}" exists in database but no matching entity`,
84
+ table: change.from.name,
85
+ details: `Table "${change.from.name}" exists in database but no matching entity`,
90
86
  suggestion: 'Create entity or drop table',
91
87
  });
92
- }
93
- return drifts;
94
88
  }
95
89
  /**
96
90
  * Detect column-level drifts.
97
91
  */
98
92
  function detectColumnDrifts(diff, opts) {
99
93
  const drifts = [];
100
- for (const colDiff of diff.columnDiffs) {
101
- if (colDiff.type === 'add') {
94
+ for (const colDiff of diff.columns) {
95
+ if (colDiff.from === undefined) {
102
96
  drifts.push({
103
97
  type: 'missing_column',
104
98
  severity: 'critical',
@@ -108,7 +102,7 @@ function detectColumnDrifts(diff, opts) {
108
102
  suggestion: 'Run migration to add column',
109
103
  });
110
104
  }
111
- else if (colDiff.type === 'drop') {
105
+ else if (colDiff.to === undefined) {
112
106
  drifts.push({
113
107
  type: 'unexpected_column',
114
108
  severity: 'warning',
@@ -124,53 +118,46 @@ function detectColumnDrifts(diff, opts) {
124
118
  }
125
119
  return drifts;
126
120
  }
127
- /**
128
- * Add drifts for column alterations: type, nullability and default.
129
- */
121
+ /** The drifts for each part of a column the differ found changed: type, nullability and default. */
130
122
  function addAlterColumnDrifts(colDiff, drifts, opts) {
131
- // An auto-increment key is created through the dialect's `serialPrimaryKey`, whose spelling the
132
- // entity never states - `BIGINT UNSIGNED AUTO_INCREMENT` on the MySQL family, where the column then
133
- // reads back as `BIGINT UNSIGNED` against an entity that can only say `BIGINT`. Comparing the two
134
- // reported every table uql created itself as drifting on its own id.
135
- const dialectOwnsType = colDiff.expected.isPrimaryKey && colDiff.expected.isAutoIncrement;
136
- if (opts.checkTypes && !dialectOwnsType) {
137
- const expectedType = formatType(colDiff.expected.type, opts.dialect);
138
- const actualType = formatType(colDiff.actual.type, opts.dialect);
139
- if (expectedType !== actualType) {
140
- drifts.push({
141
- type: 'type_mismatch',
142
- severity: colDiff.isBreaking ? 'critical' : 'warning',
143
- table: colDiff.table,
144
- column: colDiff.column,
145
- expected: expectedType,
146
- actual: actualType,
147
- details: `Type mismatch for "${colDiff.column}": expected ${expectedType}, got ${actualType}`,
148
- suggestion: colDiff.isBreaking
149
- ? 'Data truncation risk! Create migration to fix.'
150
- : 'Create migration to align types',
151
- });
152
- }
123
+ const { changed } = colDiff;
124
+ // Type drift needs a dialect to render both types.
125
+ if (opts.checkTypes && opts.dialect && changed.includes('type')) {
126
+ const expectedType = formatType(colDiff.to.type, opts.dialect);
127
+ const actualType = formatType(colDiff.from.type, opts.dialect);
128
+ drifts.push({
129
+ type: 'type_mismatch',
130
+ severity: colDiff.isBreaking ? 'critical' : 'warning',
131
+ table: colDiff.table,
132
+ column: colDiff.column,
133
+ expected: expectedType,
134
+ actual: actualType,
135
+ details: `Type mismatch for "${colDiff.column}": expected ${expectedType}, got ${actualType}`,
136
+ suggestion: colDiff.isBreaking
137
+ ? 'Data truncation risk! Create migration to fix.'
138
+ : 'Create migration to align types',
139
+ });
153
140
  }
154
- if (opts.checkNullable && colDiff.expected.nullable !== colDiff.actual.nullable) {
141
+ if (opts.checkNullable && changed.includes('nullable')) {
155
142
  drifts.push({
156
143
  type: 'constraint_mismatch',
157
144
  severity: 'warning',
158
145
  table: colDiff.table,
159
146
  column: colDiff.column,
160
- expected: colDiff.expected.nullable ? 'NULLABLE' : 'NOT NULL',
161
- actual: colDiff.actual.nullable ? 'NULLABLE' : 'NOT NULL',
147
+ expected: colDiff.to.nullable ? 'NULLABLE' : 'NOT NULL',
148
+ actual: colDiff.from.nullable ? 'NULLABLE' : 'NOT NULL',
162
149
  details: `Nullable mismatch for "${colDiff.column}"`,
163
150
  suggestion: 'Align nullable setting in entity or database',
164
151
  });
165
152
  }
166
- if (opts.checkDefaults && !opts.defaultsEqual(colDiff.expected.defaultValue, colDiff.actual.defaultValue)) {
153
+ if (opts.checkDefaults && changed.includes('default')) {
167
154
  drifts.push({
168
155
  type: 'constraint_mismatch',
169
156
  severity: 'info',
170
157
  table: colDiff.table,
171
158
  column: colDiff.column,
172
- expected: String(colDiff.expected.defaultValue ?? 'NULL'),
173
- actual: String(colDiff.actual.defaultValue ?? 'NULL'),
159
+ expected: String(colDiff.to.defaultValue ?? 'NULL'),
160
+ actual: String(colDiff.from.defaultValue ?? 'NULL'),
174
161
  details: `Default mismatch for "${colDiff.column}"`,
175
162
  suggestion: 'Align the default in the entity or the database',
176
163
  });
@@ -181,8 +168,8 @@ function addAlterColumnDrifts(colDiff, drifts, opts) {
181
168
  */
182
169
  function detectIndexDrifts(diff) {
183
170
  const drifts = [];
184
- for (const idxDiff of diff.indexDiffs) {
185
- if (idxDiff.type === 'create') {
171
+ for (const idxDiff of diff.indexes) {
172
+ if (idxDiff.from === undefined) {
186
173
  drifts.push({
187
174
  type: 'missing_index',
188
175
  severity: 'warning',
@@ -192,7 +179,7 @@ function detectIndexDrifts(diff) {
192
179
  suggestion: 'Create index via migration',
193
180
  });
194
181
  }
195
- else if (idxDiff.type === 'drop') {
182
+ else if (idxDiff.to === undefined) {
196
183
  drifts.push({
197
184
  type: 'unexpected_index',
198
185
  severity: 'info',
@@ -222,8 +209,8 @@ function detectIndexDrifts(diff) {
222
209
  */
223
210
  function detectRelationshipDrifts(diff) {
224
211
  const drifts = [];
225
- for (const relDiff of diff.relationshipDiffs) {
226
- if (relDiff.type === 'create') {
212
+ for (const relDiff of diff.relationships) {
213
+ if (relDiff.from === undefined) {
227
214
  drifts.push({
228
215
  type: 'missing_relationship',
229
216
  severity: 'warning',
@@ -233,7 +220,7 @@ function detectRelationshipDrifts(diff) {
233
220
  suggestion: 'Add FK constraint or remove relation from entity',
234
221
  });
235
222
  }
236
- else if (relDiff.type === 'drop') {
223
+ else if (relDiff.to === undefined) {
237
224
  drifts.push({
238
225
  type: 'unexpected_relationship',
239
226
  severity: 'info',
@@ -249,8 +236,8 @@ function detectRelationshipDrifts(diff) {
249
236
  severity: 'warning',
250
237
  table: relDiff.fromTable,
251
238
  relationship: relDiff.name,
252
- expected: formatActions(relDiff.expected),
253
- actual: formatActions(relDiff.actual),
239
+ expected: formatActions(relDiff.to),
240
+ actual: formatActions(relDiff.from),
254
241
  details: `FK "${relDiff.name}" has other referential actions in the database than in the entity`,
255
242
  suggestion: 'Generate a migration, which drops and re-adds the constraint',
256
243
  });
@@ -1,18 +1,16 @@
1
- import type { ColumnNode, TableNode } from '../../schema/types.js';
1
+ import type { TableNode } from '../../schema/types.js';
2
+ import type { IndexColumnInput, IndexOptions } from '../../type/entity.js';
2
3
  import type { ForeignKeySchema, IndexSchema } from '../../type/migration.js';
3
4
  import type { QueryRaw } from '../../type/queryRaw.js';
4
- import type { FullColumnDefinition, IndexDefinition, TableDefinition } from '../builder/types.js';
5
+ import type { ColumnDefinition, FullColumnDefinition, IndexDefinition, TableDefinition } from '../builder/types.js';
5
6
  /**
6
7
  * A migration builder's table definition as the AST nodes the generators render from, so a hand-written
7
8
  * `createTable` and an entity reach `generateCreateTableFromNode` in the same shape, its SQL rendered by
8
9
  * `render`. Free functions and not generator methods: the dialect reaches them only through `render`.
9
10
  */
10
11
  export declare function tableDefinitionToNode(def: TableDefinition, render: (sql: QueryRaw) => string): TableNode;
11
- /**
12
- * A builder's column as the node the generators render, spread so a field the node gains carries over.
13
- * `index` and `foreignKey` are lifted onto the table elsewhere; `addRelationship` sets `references`.
14
- */
15
- export declare function fullColumnDefinitionToNode(col: FullColumnDefinition, tableName: string): ColumnNode;
12
+ /** A builder's column without its `index` and `foreignKey`, which are lifted onto the table. */
13
+ export declare function bareColumn({ index: _index, foreignKey: _foreignKey, ...column }: FullColumnDefinition): ColumnDefinition;
16
14
  /**
17
15
  * The index a column-level `index` or `unique` declares, or nothing: a unique column is a unique index.
18
16
  *
@@ -20,6 +18,12 @@ export declare function fullColumnDefinitionToNode(col: FullColumnDefinition, ta
20
18
  * `addColumn` had no lift at all and silently emitted a column with no index.
21
19
  */
22
20
  export declare function columnIndex(tableName: string, col: FullColumnDefinition): Pick<IndexSchema, 'name' | 'entries' | 'unique'> | undefined;
21
+ /**
22
+ * The index that `table.index`, `table.unique` and `createIndex` record. Its entries are normalized, since
23
+ * an entry left as written reaches the generator as a column named `[object Object]`. An unnamed index is
24
+ * named after its entries, with `_uk` only for `table.unique`, so names earlier migrations installed stay.
25
+ */
26
+ export declare function indexDefinition(tableName: string, columns: readonly IndexColumnInput[], { name, unique, ...options }?: IndexOptions, uniqueName?: boolean): IndexDefinition;
23
27
  /** An index the builder recorded, its SQL rendered by `render` into the text the schema holds. */
24
28
  export declare function renderIndexDefinition(index: IndexDefinition, render: (sql: QueryRaw) => string): IndexSchema;
25
29
  /** The foreign key a column-level `references` declares, or nothing. Shared for the same reason. */
@@ -1,22 +1,22 @@
1
1
  import { createTableNode, keyOfColumns } from '../../schema/schemaAST.js';
2
- import { renderIndexColumn } from '../../util/ddlExpression.util.js';
3
- import { derivedForeignKeyName, derivedIndexName } from '../../util/sql.util.js';
4
- /** A table the builder names but has not seen, which the generator reads only the name of. */
5
- function unresolvedTable(name) {
6
- return { name };
7
- }
2
+ import { indexNameParts, normalizeIndexColumn, renderIndexColumn } from '../../util/ddlExpression.util.js';
3
+ import { derivedIndexName, splitQualifiedName } from '../../util/sql.util.js';
8
4
  /**
9
5
  * A migration builder's table definition as the AST nodes the generators render from, so a hand-written
10
6
  * `createTable` and an entity reach `generateCreateTableFromNode` in the same shape, its SQL rendered by
11
7
  * `render`. Free functions and not generator methods: the dialect reaches them only through `render`.
12
8
  */
13
9
  export function tableDefinitionToNode(def, render) {
14
- const table = { ...createTableNode(def.name), comment: def.comment };
10
+ const { name, schema } = splitQualifiedName(def.name);
11
+ // Foreign keys stay external: each names its target table, which has no node in this build.
12
+ const table = {
13
+ ...createTableNode(name, schema),
14
+ comment: def.comment,
15
+ externalForeignKeys: [...def.foreignKeys],
16
+ };
15
17
  const { columns } = table;
16
18
  for (const colDef of def.columns) {
17
- const node = fullColumnDefinitionToNode(colDef, def.name);
18
- node.table = table;
19
- columns.set(node.name, node);
19
+ columns.set(colDef.name, { ...bareColumn(colDef), table, referencedBy: [] });
20
20
  }
21
21
  // A declared key keeps only the columns the table has, in its own order.
22
22
  table.primaryKey = def.primaryKey
@@ -25,32 +25,11 @@ export function tableDefinitionToNode(def, render) {
25
25
  for (const idxDef of def.indexes) {
26
26
  table.indexes.push({ ...renderIndexDefinition(idxDef, render), table });
27
27
  }
28
- for (const fkDef of def.foreignKeys) {
29
- const relNode = {
30
- name: fkDef.name ?? derivedForeignKeyName(def.name, fkDef.columns),
31
- type: 'ManyToOne', // Builder default
32
- from: {
33
- table,
34
- columns: fkDef.columns.map((name) => columns.get(name)).filter((c) => c !== undefined),
35
- },
36
- to: {
37
- table: unresolvedTable(fkDef.references.table),
38
- columns: fkDef.references.columns.map((name) => ({ name })),
39
- },
40
- onDelete: fkDef.onDelete,
41
- onUpdate: fkDef.onUpdate,
42
- };
43
- table.outgoingRelations.push(relNode);
44
- }
45
28
  return table;
46
29
  }
47
- /**
48
- * A builder's column as the node the generators render, spread so a field the node gains carries over.
49
- * `index` and `foreignKey` are lifted onto the table elsewhere; `addRelationship` sets `references`.
50
- */
51
- export function fullColumnDefinitionToNode(col, tableName) {
52
- const { index: _index, foreignKey: _foreignKey, ...column } = col;
53
- return { ...column, table: unresolvedTable(tableName), referencedBy: [] };
30
+ /** A builder's column without its `index` and `foreignKey`, which are lifted onto the table. */
31
+ export function bareColumn({ index: _index, foreignKey: _foreignKey, ...column }) {
32
+ return column;
54
33
  }
55
34
  /**
56
35
  * The index a column-level `index` or `unique` declares, or nothing: a unique column is a unique index.
@@ -68,6 +47,20 @@ export function columnIndex(tableName, col) {
68
47
  unique: col.isUnique,
69
48
  };
70
49
  }
50
+ /**
51
+ * The index that `table.index`, `table.unique` and `createIndex` record. Its entries are normalized, since
52
+ * an entry left as written reaches the generator as a column named `[object Object]`. An unnamed index is
53
+ * named after its entries, with `_uk` only for `table.unique`, so names earlier migrations installed stay.
54
+ */
55
+ export function indexDefinition(tableName, columns, { name, unique = false, ...options } = {}, uniqueName = false) {
56
+ const entries = columns.map(normalizeIndexColumn);
57
+ return {
58
+ ...options,
59
+ name: name ?? derivedIndexName(tableName, indexNameParts(entries), uniqueName),
60
+ entries,
61
+ unique,
62
+ };
63
+ }
71
64
  /** An index the builder recorded, its SQL rendered by `render` into the text the schema holds. */
72
65
  export function renderIndexDefinition(index, render) {
73
66
  return {
@@ -1,8 +1,8 @@
1
1
  import type { IndexNode } from '../../schema/types.js';
2
2
  import type { IndexSchema } from '../../type/index.js';
3
3
  /**
4
- * An AST index as the generators and dialects want it. Spread rather than copied field by field:
5
- * rebuilding it by hand is how the partial-index `where` once vanished without a trace. Its `table` is
6
- * ignored downstream, and the vector type travels along because pgvector's operator-class names are built from it.
4
+ * An AST index in the form generators and dialects take. It is spread rather than copied field by field, so
5
+ * no field (such as a partial index's `where`) is lost. It drops `table`, a link back into the graph that a
6
+ * plan cannot carry as JSON, and adds the vector type, from which pgvector's operator-class names are built.
7
7
  */
8
8
  export declare function indexNodeToSchema(index: IndexNode): IndexSchema;
@@ -1,13 +1,14 @@
1
1
  import { isVectorCategory } from '../../schema/canonicalType.js';
2
2
  import { indexColumns } from '../../schema/indexColumns.js';
3
3
  /**
4
- * An AST index as the generators and dialects want it. Spread rather than copied field by field:
5
- * rebuilding it by hand is how the partial-index `where` once vanished without a trace. Its `table` is
6
- * ignored downstream, and the vector type travels along because pgvector's operator-class names are built from it.
4
+ * An AST index in the form generators and dialects take. It is spread rather than copied field by field, so
5
+ * no field (such as a partial index's `where`) is lost. It drops `table`, a link back into the graph that a
6
+ * plan cannot carry as JSON, and adds the vector type, from which pgvector's operator-class names are built.
7
7
  */
8
8
  export function indexNodeToSchema(index) {
9
+ const { table: _table, ...schema } = index;
9
10
  return {
10
- ...index,
11
+ ...schema,
11
12
  vectorType: indexColumns(index)
12
13
  .map((col) => col.type?.category)
13
14
  .find(isVectorCategory),
@@ -6,7 +6,7 @@ export * from './builder/index.js';
6
6
  export { loadConfig } from './cli-config.js';
7
7
  // Entity code generation
8
8
  export * from './codegen/index.js';
9
- // `CREATE INDEX`, per dialect family
9
+ // Index and table DDL, per dialect family
10
10
  export * from './ddl/index.js';
11
11
  // Drift detection
12
12
  export * from './drift/index.js';
@@ -1,3 +1,4 @@
1
+ import { SqlExpression } from '../../schema/sqlExpression.js';
1
2
  import { type ForeignKeyAction } from '../../schema/types.js';
2
3
  import type { ColumnSchema, InstalledTriggers, ForeignKeySchema, IndexSchema, PrimaryKeySchema, QuerierPool, RawRow, SchemaIntrospector, SqlQuerier, StoredDefinition, TableSchema } from '../../type/index.js';
3
4
  import { BaseSqlIntrospector } from './baseSqlIntrospector.js';
@@ -85,11 +86,10 @@ export declare abstract class AbstractSqlSchemaIntrospector extends BaseSqlIntro
85
86
  /** SQL query to get primary key columns. Parameter: tableName (for PRAGMA-style). */
86
87
  protected abstract getPrimaryKeyQuery(tableName: string): string;
87
88
  /**
88
- * SQL listing every trigger in the schema as a `table`, a `name`, the engine's reprint of it as a
89
- * `definition`, and where the body lives apart, the `requires` recreated first: what is installed, not
90
- * what uql wrote, which is exactly what a rollback puts back.
89
+ * SQL listing the triggers on the table named by its single parameter: each one's `name`, its `definition`
90
+ * as the engine reprints it, and what it `requires` to be recreated first. It reads what is installed, not
91
+ * what uql wrote, which is exactly what a rollback restores.
91
92
  */
92
- /** The triggers on the table its one parameter names: each one's `name`, `definition`, and what it `requires`. */
93
93
  protected abstract triggersQuery(): string;
94
94
  /**
95
95
  * Extract table name from a row returned by getTableNamesQuery.
@@ -116,6 +116,11 @@ export declare abstract class AbstractSqlSchemaIntrospector extends BaseSqlIntro
116
116
  * and only the reported name will do - see {@link PrimaryKeySchema.name}.
117
117
  */
118
118
  protected mapPrimaryKeyName(results: RawRow[]): string | undefined;
119
- /** Parse default value string to appropriate type. */
119
+ /** Parses a default as the catalogue reports it: to its literal value, or through {@link sqlDefault} if SQL. */
120
120
  protected abstract parseDefaultValue(defaultValue: string | null): unknown;
121
+ /**
122
+ * A SQL default, wrapped in parentheses. The current timestamp uql declares reads back as `expr.now()`, so
123
+ * it compares equal on every engine and `generate:from-db` writes it as `currentTimestamp`.
124
+ */
125
+ protected sqlDefault(sql: string): SqlExpression;
121
126
  }
@@ -1,7 +1,9 @@
1
+ import { SqlExpression } from '../../schema/sqlExpression.js';
1
2
  import { FOREIGN_KEY_ACTIONS } from '../../schema/types.js';
2
3
  import { isSqlQuerier } from '../../type/index.js';
3
4
  import { isOwnedName } from '../../util/sql.util.js';
4
5
  import { UqlUsageError } from '../../util/uqlError.js';
6
+ import { expr, sameDefault } from '../builder/expressions.js';
5
7
  import { BaseSqlIntrospector } from './baseSqlIntrospector.js';
6
8
  /** A SQL introspector: an engine states its catalogue queries (`get*Query`) and how their rows map (`map*Result`). */
7
9
  export class AbstractSqlSchemaIntrospector extends BaseSqlIntrospector {
@@ -172,6 +174,14 @@ export class AbstractSqlSchemaIntrospector extends BaseSqlIntrospector {
172
174
  const name = results[0]?.['constraint_name'];
173
175
  return name === undefined || name === null ? undefined : String(name);
174
176
  }
177
+ /**
178
+ * A SQL default, wrapped in parentheses. The current timestamp uql declares reads back as `expr.now()`, so
179
+ * it compares equal on every engine and `generate:from-db` writes it as `currentTimestamp`.
180
+ */
181
+ sqlDefault(sql) {
182
+ const expression = SqlExpression.parenthesized(sql);
183
+ return sameDefault(expr.now(), expression, this.dialect) ? expr.now() : expression;
184
+ }
175
185
  }
176
186
  /** A {@link TableRowReader} over one querier: the same statement is only ever sent once. */
177
187
  function createTableRowReader(querier) {
@@ -16,7 +16,6 @@ export declare abstract class BaseSqlIntrospector {
16
16
  * `undefined` for "wherever the connection points", and name a schema only when one was asked for.
17
17
  */
18
18
  constructor(dialect: AbstractSqlDialect, schema?: string | undefined);
19
- protected escapeId(identifier: string): string;
20
19
  /**
21
20
  * The database as a {@link SchemaAST}, or just the tables named. A name nothing matches is left out
22
21
  * rather than raised: the point of naming them is to read a database other things are still
@@ -1,6 +1,6 @@
1
- import { canonicalColumnType } from '../../schema/canonicalType.js';
1
+ import { canonicalColumnType, defaultTimestampPrecision, withTimestampPrecision } from '../../schema/canonicalType.js';
2
2
  import { createTableNode, keyOfColumns, SchemaAST } from '../../schema/schemaAST.js';
3
- import { escapeSqlId } from '../../util/index.js';
3
+ import { DEFAULT_FOREIGN_KEY_ACTION, } from '../../schema/types.js';
4
4
  import { derivedForeignKeyName, qualifyName } from '../../util/sql.util.js';
5
5
  /**
6
6
  * Base class for SQL introspectors with shared AST building logic.
@@ -19,9 +19,6 @@ export class BaseSqlIntrospector {
19
19
  this.dialect = dialect;
20
20
  this.schema = schema;
21
21
  }
22
- escapeId(identifier) {
23
- return escapeSqlId(identifier, this.dialect.escapeIdChar);
24
- }
25
22
  /**
26
23
  * The database as a {@link SchemaAST}, or just the tables named. A name nothing matches is left out
27
24
  * rather than raised: the point of naming them is to read a database other things are still
@@ -87,7 +84,8 @@ export class BaseSqlIntrospector {
87
84
  const { type, length: _length, precision: _precision, scale: _scale, ...rest } = col;
88
85
  const column = {
89
86
  ...rest,
90
- type: canonicalColumnType(type, col),
87
+ // A timestamp with no stated precision has the engine's default; otherwise an entity would assume 3.
88
+ type: withTimestampPrecision(canonicalColumnType(type, col), defaultTimestampPrecision(this.dialect.dialectName)),
91
89
  table,
92
90
  referencedBy: [],
93
91
  };
@@ -115,8 +113,8 @@ export class BaseSqlIntrospector {
115
113
  type: fromColumns[0].isUnique ? 'OneToOne' : 'ManyToOne',
116
114
  from: { table: fromTable, columns: fromColumns },
117
115
  to: { table: toTable, columns: toColumns },
118
- onDelete: fk.onDelete || 'NO ACTION',
119
- onUpdate: fk.onUpdate || 'NO ACTION',
116
+ onDelete: fk.onDelete || DEFAULT_FOREIGN_KEY_ACTION,
117
+ onUpdate: fk.onUpdate || DEFAULT_FOREIGN_KEY_ACTION,
120
118
  };
121
119
  ast.addRelationship(rel);
122
120
  }
@@ -1,4 +1,3 @@
1
- import { defaultTimestampPrecision } from '../../schema/canonicalType.js';
2
1
  import { AbstractSqlSchemaIntrospector, } from './abstractSqlSchemaIntrospector.js';
3
2
  /**
4
3
  * SQL Server schema introspector.
@@ -178,22 +177,18 @@ export class MsSqlSchemaIntrospector extends AbstractSqlSchemaIntrospector {
178
177
  if (quoted) {
179
178
  return quoted[1].replaceAll("''", "'");
180
179
  }
181
- return text === 'NULL' ? null : text;
180
+ return text === 'NULL' ? null : this.sqlDefault(text);
182
181
  }
183
182
  }
184
183
  /** The types whose `max_length` is a width rather than a fixed storage size. */
185
184
  const CHARACTER_TYPES = new Set(['CHAR', 'NCHAR', 'VARCHAR', 'NVARCHAR', 'BINARY', 'VARBINARY']);
186
185
  const NUMERIC_TYPES = new Set(['DECIMAL', 'NUMERIC']);
187
- /** `(MAX)` on an unbounded character type, and a timestamp's fractional digits where not the engine's default. */
186
+ /** The type as DDL spells it: `(MAX)` on an unbounded character type, or a timestamp's fractional digits. */
188
187
  function spelledType(type, bytes, scale) {
189
188
  if (bytes === -1 && CHARACTER_TYPES.has(type)) {
190
189
  return `${type}(MAX)`;
191
190
  }
192
- return (type === 'DATETIME2' || type === 'DATETIMEOFFSET') &&
193
- scale !== undefined &&
194
- scale !== defaultTimestampPrecision('mssql')
195
- ? `${type}(${scale})`
196
- : type;
191
+ return (type === 'DATETIME2' || type === 'DATETIMEOFFSET') && scale !== undefined ? `${type}(${scale})` : type;
197
192
  }
198
193
  /**
199
194
  * A column's declared width from `max_length`, which is bytes: an `N` type holds two a character, a