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,7 +1,8 @@
1
1
  import { qualifyName } from '../util/sql.util.js';
2
2
  import { areTypesEqual, isBreakingTypeChange } from './canonicalType.js';
3
- import { describeIndexDifferences, pairIndexes } from './indexDifferences.js';
3
+ import { indexChanges } from './indexDifferences.js';
4
4
  import { matchByKey, pairUnique } from './matchByKey.js';
5
+ import { writtenDefault } from './sqlExpression.js';
5
6
  import { DEFAULT_FOREIGN_KEY_ACTION } from './types.js';
6
7
  /**
7
8
  * Default diff options.
@@ -11,61 +12,35 @@ const DEFAULT_OPTIONS = {
11
12
  compareRelationships: true,
12
13
  normalizeType: (type) => type,
13
14
  defaultsEqual: defaultsEqualAsWritten,
14
- ignoreCase: false,
15
15
  excludeTables: [],
16
16
  };
17
- function nameNormalizer(opts) {
18
- return opts.ignoreCase ? (name) => name.toLowerCase() : (name) => name;
19
- }
20
17
  /** How a relationship diff names the pair it is about, whichever way it differs. */
21
18
  function relationEnds(relation) {
22
- return { name: relation.name, fromTable: relation.from.table.name, toTable: relation.to.table.name };
19
+ return { name: relation.name, fromTable: relation.from.table.name };
23
20
  }
24
21
  /** The differences between the expected schema (the entities) and the actual one (the database). */
25
22
  export function diffSchemas(source, target, options = {}) {
26
23
  const opts = { ...DEFAULT_OPTIONS, ...options };
27
- const { created: tablesToCreate, dropped: tablesToDrop, matched } = matchTables(source, target, opts);
28
- const tablesToAlter = matched
24
+ const { created, dropped, matched } = matchTables(source, target, opts);
25
+ const altered = matched
29
26
  .map(([sourceTable, targetTable]) => diffTable(sourceTable, targetTable, opts))
30
27
  .filter((tableDiff) => tableDiff !== undefined);
31
- const columnDiffs = tablesToAlter.flatMap((tableDiff) => tableDiff.columnDiffs);
32
- const indexDiffs = tablesToAlter.flatMap((tableDiff) => tableDiff.indexDiffs);
33
- const primaryKeyDiffs = tablesToAlter.flatMap((tableDiff) => tableDiff.primaryKeyDiff ?? []);
34
- // Relationships span tables, so they are compared over the whole schema rather than per table.
35
- const relationshipDiffs = opts.compareRelationships
36
- ? diffRelationshipNodes(source.relationships, target.relationships, opts)
37
- : [];
38
- const hasDifferences = tablesToCreate.length > 0 ||
39
- tablesToDrop.length > 0 ||
40
- tablesToAlter.length > 0 ||
41
- relationshipDiffs.length > 0 ||
42
- indexDiffs.length > 0 ||
43
- primaryKeyDiffs.length > 0;
44
- // Rewriting a key drops a constraint and rebuilds an index over the whole table, and fails outright
45
- // where its new columns are null on rows that already exist. Breaking by any measure.
46
- const hasBreakingChanges = tablesToDrop.length > 0 || primaryKeyDiffs.length > 0 || columnDiffs.some((d) => d.isBreaking);
47
28
  return {
48
- tablesToCreate,
49
- tablesToDrop,
50
- tablesToAlter,
51
- columnDiffs,
52
- indexDiffs,
53
- primaryKeyDiffs,
54
- relationshipDiffs,
55
- hasDifferences,
56
- hasBreakingChanges,
29
+ tables: [...created.map((to) => ({ to })), ...dropped.map((from) => ({ from }))],
30
+ columns: altered.flatMap((tableDiff) => tableDiff.columns),
31
+ indexes: altered.flatMap((tableDiff) => tableDiff.indexes),
32
+ primaryKeys: altered.flatMap((tableDiff) => tableDiff.primaryKey ?? []),
33
+ // Relationships span tables, so they are compared over the whole schema rather than per table.
34
+ relationships: opts.compareRelationships ? diffRelationshipNodes(source.relationships, target.relationships) : [],
57
35
  };
58
36
  }
59
37
  /** The differences between two tables, shared by migrations and drift detection so they cannot disagree. */
60
38
  export function diffTable(source, target, options = {}) {
61
39
  const opts = { ...DEFAULT_OPTIONS, ...options };
62
- const columnDiffs = diffTableColumns(source, target, opts);
63
- const indexDiffs = opts.compareIndexes ? diffTableIndexes(source, target, opts) : [];
64
- const primaryKeyDiff = diffPrimaryKey(source, target);
65
- if (columnDiffs.length === 0 && indexDiffs.length === 0 && !primaryKeyDiff) {
66
- return undefined;
67
- }
68
- return { name: source.name, type: 'alter', columnDiffs, indexDiffs, primaryKeyDiff };
40
+ const columns = diffTableColumns(source, target, opts);
41
+ const indexes = opts.compareIndexes ? diffTableIndexes(source, target) : [];
42
+ const primaryKey = diffPrimaryKey(source, target);
43
+ return columns.length || indexes.length || primaryKey ? { columns, indexes, primaryKey } : undefined;
69
44
  }
70
45
  /** The two keys where they hold different columns, compared in order and never by the name the engine gave them. */
71
46
  function diffPrimaryKey(source, target) {
@@ -74,27 +49,24 @@ function diffPrimaryKey(source, target) {
74
49
  if (expected.length === actual.length && expected.every((column, i) => column === actual[i])) {
75
50
  return undefined;
76
51
  }
77
- return { table: source.name, expected: source.primaryKey, actual: target.primaryKey };
52
+ return { table: source.name, from: target.primaryKey, to: source.primaryKey };
78
53
  }
79
54
  /**
80
55
  * Compare columns between two tables.
81
56
  */
82
57
  function diffTableColumns(source, target, opts) {
83
- const normalizeName = nameNormalizer(opts);
84
- const { created, dropped, matched } = matchByKey(source.columns.values(), target.columns.values(), (column) => normalizeName(column.name));
58
+ const { created, dropped, matched } = matchByKey(source.columns.values(), target.columns.values(), (column) => column.name);
85
59
  return [
86
60
  ...created.map((column) => ({
87
61
  table: source.name,
88
62
  column: column.name,
89
- type: 'add',
90
- expected: column,
63
+ to: column,
91
64
  description: `Add column "${column.name}"`,
92
65
  })),
93
66
  ...dropped.map((column) => ({
94
67
  table: target.name,
95
68
  column: column.name,
96
- type: 'drop',
97
- actual: column,
69
+ from: column,
98
70
  isBreaking: true,
99
71
  description: `Drop column "${column.name}"`,
100
72
  })),
@@ -110,9 +82,8 @@ function diffTableColumns(source, target, opts) {
110
82
  */
111
83
  export function columnRenames(desired, actual, options = {}) {
112
84
  const opts = { ...DEFAULT_OPTIONS, ...options };
113
- const normalizeName = nameNormalizer(opts);
114
85
  return new Map(matchTables(desired, actual, opts).matched.flatMap(([expected, current]) => {
115
- const { created, dropped } = matchByKey(expected.columns.values(), current.columns.values(), (column) => normalizeName(column.name));
86
+ const { created, dropped } = matchByKey(expected.columns.values(), current.columns.values(), (column) => column.name);
116
87
  const { matched } = pairUnique(created, dropped, (to, from) => !diffColumn(expected.name, to, from, opts));
117
88
  const table = qualifyName(current.name, current.schema);
118
89
  return matched.length ? [[table, matched.map(([to, from]) => ({ from: from.name, to: to.name }))]] : [];
@@ -131,26 +102,29 @@ export function tableRenameCandidates(desired, actual, options = {}) {
131
102
  }
132
103
  /** The two sides' tables paired by name, those `excludeTables` names left out of both. */
133
104
  function matchTables(desired, actual, opts) {
134
- const normalizeName = nameNormalizer(opts);
135
105
  const included = (tables) => [...tables].filter((table) => !opts.excludeTables.includes(table.name));
136
- return matchByKey(included(desired.tables.values()), included(actual.tables.values()), (table) => normalizeName(table.name));
106
+ return matchByKey(included(desired.tables.values()), included(actual.tables.values()), (table) => table.name);
137
107
  }
138
- /** Compare indexes between two tables, paired by {@link pairIndexes}, in what the target's reader reports. */
139
- function diffTableIndexes(source, target, opts) {
140
- const { created, dropped, matched } = pairIndexes(source.indexes, target.indexes, nameNormalizer(opts));
141
- return [
142
- ...created.map((index) => ({ name: index.name, table: source.name, type: 'create', expected: index })),
143
- ...dropped.map((index) => ({ name: index.name, table: target.name, type: 'drop', actual: index })),
144
- ...matched
145
- .map(([sourceIndex, targetIndex]) => diffIndex(source.name, sourceIndex, targetIndex, target.indexFacets))
146
- .filter((diff) => diff !== undefined),
147
- ];
108
+ /**
109
+ * The index changes between two tables, paired the way a migration pairs them. Every unpaired database
110
+ * index is reported as a drop, even one a migration would keep, and each change takes the entity's index
111
+ * name when there is one.
112
+ */
113
+ function diffTableIndexes(source, target) {
114
+ const { changes, kept } = indexChanges(source.name, source.indexes, target.indexes, target.indexFacets);
115
+ const drops = kept.map((from) => ({ from }));
116
+ return [...changes, ...drops].map((change) => ({
117
+ ...change,
118
+ table: source.name,
119
+ name: change.to === undefined ? change.from.name : change.to.name,
120
+ }));
148
121
  }
149
122
  /**
150
123
  * Compare two columns and return the difference.
151
124
  */
152
125
  function diffColumn(tableName, source, target, opts) {
153
126
  const differences = [];
127
+ const changed = [];
154
128
  // A key column's type and nullability are implied, not stated, and catalogues report them
155
129
  // inconsistently (`BIGINT(20)`, SQLite's `notnull: 0` rowid), so neither is compared.
156
130
  const generatedType = source.isAutoIncrement && target.isAutoIncrement;
@@ -160,6 +134,7 @@ function diffColumn(tableName, source, target, opts) {
160
134
  const typeChanged = !generatedType && !areTypesEqual(expectedType, actualType);
161
135
  if (typeChanged) {
162
136
  differences.push(`type: ${formatType(source.type)} -> ${formatType(target.type)}`);
137
+ changed.push('type');
163
138
  }
164
139
  // Signedness is the one thing compared on a generated key, because it is the one part of the serial
165
140
  // spelling that does round trip - and a key left unsigned refuses every foreign key pointing at it,
@@ -168,9 +143,11 @@ function diffColumn(tableName, source, target, opts) {
168
143
  const signednessChanged = generatedType && !!source.type.unsigned !== !!target.type.unsigned;
169
144
  if (signednessChanged) {
170
145
  differences.push(`type: ${formatType(source.type)} -> ${formatType(target.type)}`);
146
+ changed.push('type');
171
147
  }
172
148
  if (!impliedNotNull && source.nullable !== target.nullable) {
173
149
  differences.push(`nullable: ${target.nullable} -> ${source.nullable}`);
150
+ changed.push('nullable');
174
151
  }
175
152
  // Not compared, since no statement this generator emits could settle a difference: `isAutoIncrement`,
176
153
  // `enum` (a check the database reprints), `generatedAs`, and `comment`. Nor `isUnique`: a unique
@@ -178,6 +155,7 @@ function diffColumn(tableName, source, target, opts) {
178
155
  // Compare default values (if both defined)
179
156
  if (!opts.defaultsEqual(source.defaultValue, target.defaultValue)) {
180
157
  differences.push(`default: ${target.defaultValue ?? 'NULL'} -> ${source.defaultValue ?? 'NULL'}`);
158
+ changed.push('default');
181
159
  }
182
160
  if (differences.length === 0) {
183
161
  return undefined;
@@ -185,9 +163,9 @@ function diffColumn(tableName, source, target, opts) {
185
163
  return {
186
164
  table: tableName,
187
165
  column: source.name,
188
- type: 'alter',
189
- expected: source,
190
- actual: target,
166
+ from: target,
167
+ to: source,
168
+ changed,
191
169
  // Only the type this diff actually reports: a column altered for its default carries no data loss,
192
170
  // and a generated key's type - never compared above - reads as unsigned against an entity that
193
171
  // cannot say so.
@@ -195,34 +173,12 @@ function diffColumn(tableName, source, target, opts) {
195
173
  description: differences.join(', '),
196
174
  };
197
175
  }
198
- /**
199
- * Compare two indexes and return the difference.
200
- */
201
- function diffIndex(tableName, source, target, facets) {
202
- const differences = describeIndexDifferences(source, target, facets);
203
- if (differences.length === 0) {
204
- return undefined;
205
- }
206
- return {
207
- name: source.name,
208
- table: tableName,
209
- type: 'alter',
210
- expected: source,
211
- actual: target,
212
- description: differences.join(', '),
213
- };
214
- }
215
176
  /** The differences between two lists of foreign keys, matched by their columns and never by the name the engine gave them. */
216
- export function diffRelationshipNodes(source, target, opts = {}) {
217
- const normalizeName = nameNormalizer({ ...DEFAULT_OPTIONS, ...opts });
218
- const { created, dropped, matched } = matchByKey(source, target, (relation) => getRelationshipKey(relation, normalizeName));
177
+ export function diffRelationshipNodes(source, target) {
178
+ const { created, dropped, matched } = matchByKey(source, target, getRelationshipKey);
219
179
  return [
220
- ...created.map((relation) => ({
221
- ...relationEnds(relation),
222
- type: 'create',
223
- expected: relation,
224
- })),
225
- ...dropped.map((relation) => ({ ...relationEnds(relation), type: 'drop', actual: relation })),
180
+ ...created.map((relation) => ({ ...relationEnds(relation), to: relation })),
181
+ ...dropped.map((relation) => ({ ...relationEnds(relation), from: relation })),
226
182
  ...matched
227
183
  .map(([sourceRelation, targetRelation]) => diffRelationship(sourceRelation, targetRelation))
228
184
  .filter((diff) => diff !== undefined),
@@ -239,14 +195,14 @@ export function referentialActions(rel) {
239
195
  function diffRelationship(source, target) {
240
196
  const [expected, actual] = [referentialActions(source), referentialActions(target)];
241
197
  if (expected.onDelete !== actual.onDelete || expected.onUpdate !== actual.onUpdate) {
242
- return { ...relationEnds(source), type: 'alter', expected: source, actual: target };
198
+ return { ...relationEnds(source), from: target, to: source };
243
199
  }
244
200
  return undefined;
245
201
  }
246
202
  /**
247
203
  * Generate a unique key for a relationship based on its structure.
248
204
  */
249
- function getRelationshipKey(rel, normalizeName) {
205
+ function getRelationshipKey(rel) {
250
206
  const fromCols = rel.from.columns
251
207
  .map((c) => c.name)
252
208
  .sort()
@@ -255,7 +211,7 @@ function getRelationshipKey(rel, normalizeName) {
255
211
  .map((c) => c.name)
256
212
  .sort()
257
213
  .join(',');
258
- return `${normalizeName(rel.from.table.name)}.${fromCols}->${normalizeName(rel.to.table.name)}.${toCols}`;
214
+ return `${rel.from.table.name}.${fromCols}->${rel.to.table.name}.${toCols}`;
259
215
  }
260
216
  /**
261
217
  * Format a canonical type for display.
@@ -273,19 +229,10 @@ function formatType(type) {
273
229
  result += ' unsigned';
274
230
  return result;
275
231
  }
276
- /** Two defaults compared as written, where no dialect reprints them: `now()` and `CURRENT_TIMESTAMP` are one. */
232
+ /**
233
+ * Compares two defaults exactly as written, for when no dialect renders them: SQL must match to the letter.
234
+ * Migrations and drift use the generator's equality instead, which knows how its engine reprints SQL.
235
+ */
277
236
  export function defaultsEqualAsWritten(expected, actual) {
278
- return normalizeDefault(expected) === normalizeDefault(actual);
279
- }
280
- function normalizeDefault(value) {
281
- if (value === undefined || value === null)
282
- return '';
283
- if (typeof value === 'string') {
284
- // Normalize function calls
285
- const upper = value.toUpperCase();
286
- if (upper.includes('NOW()') || upper.includes('CURRENT_TIMESTAMP')) {
287
- return 'CURRENT_TIMESTAMP';
288
- }
289
- }
290
- return String(value);
237
+ return writtenDefault(expected ?? '') === writtenDefault(actual ?? '');
291
238
  }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The kind of a {@link SqlExpression}. Kinds are symbolic: `formatDefaultValue` renders each in the
3
+ * dialect's spelling at DDL time, while `raw` carries its own SQL.
4
+ */
5
+ export type SqlExpressionKind = 'now' | 'currentDate' | 'currentTime' | 'uuid' | 'uuidv7' | 'onUpdateNow' | 'raw';
6
+ /**
7
+ * A column default that is SQL rather than a literal, whether an entity or a migration declares it or
8
+ * introspection reads it back. It is a class, not a plain object, so a JSON default cannot pass for one.
9
+ */
10
+ export declare class SqlExpression {
11
+ readonly kind: SqlExpressionKind;
12
+ readonly sql?: string | undefined;
13
+ /** `sql` is set only for the `raw` kind, which carries its own text verbatim. */
14
+ constructor(kind: SqlExpressionKind, sql?: string | undefined);
15
+ static isExpression(value: unknown): value is SqlExpression;
16
+ /** Wraps `sql` in parentheses, which every engine accepts for a default expression and SQLite and MySQL require. */
17
+ static parenthesized(sql: string): SqlExpression;
18
+ /** Its SQL, or its kind, as diffs and drift reports show it. */
19
+ toString(): string;
20
+ }
21
+ /** A default as text for an exact comparison: objects (SQL included) as JSON, numbers as their digits. */
22
+ export declare function writtenDefault(value: unknown): string;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * A column default that is SQL rather than a literal, whether an entity or a migration declares it or
3
+ * introspection reads it back. It is a class, not a plain object, so a JSON default cannot pass for one.
4
+ */
5
+ export class SqlExpression {
6
+ kind;
7
+ sql;
8
+ /** `sql` is set only for the `raw` kind, which carries its own text verbatim. */
9
+ constructor(kind, sql) {
10
+ this.kind = kind;
11
+ this.sql = sql;
12
+ }
13
+ static isExpression(value) {
14
+ return value instanceof SqlExpression;
15
+ }
16
+ /** Wraps `sql` in parentheses, which every engine accepts for a default expression and SQLite and MySQL require. */
17
+ static parenthesized(sql) {
18
+ return new SqlExpression('raw', `(${sql})`);
19
+ }
20
+ /** Its SQL, or its kind, as diffs and drift reports show it. */
21
+ toString() {
22
+ return this.sql ?? this.kind;
23
+ }
24
+ }
25
+ /** A default as text for an exact comparison: objects (SQL included) as JSON, numbers as their digits. */
26
+ export function writtenDefault(value) {
27
+ return typeof value === 'object' ? JSON.stringify(value) : String(value);
28
+ }
@@ -1,4 +1,4 @@
1
- import type { ForeignKeySchema, IndexSchema, PrimaryKeySchema, StoredDefinition } from '../type/migration.js';
1
+ import type { Change, ForeignKeySchema, IndexSchema, PrimaryKeySchema, StoredDefinition } from '../type/migration.js';
2
2
  import type { IndexFacet } from './indexDifferences.js';
3
3
  /**
4
4
  * Type categories universal across SQL dialects.
@@ -71,7 +71,7 @@ export interface ColumnNode {
71
71
  readonly type: CanonicalType;
72
72
  /** Whether the column allows NULL values */
73
73
  readonly nullable: boolean;
74
- /** Default value expression or literal */
74
+ /** The column's default: a literal value, or an `SqlExpression` for SQL. */
75
75
  readonly defaultValue?: unknown;
76
76
  /** Whether this column is part of the primary key */
77
77
  readonly isPrimaryKey: boolean;
@@ -151,8 +151,6 @@ export interface RelationshipNode {
151
151
  readonly table: TableNode;
152
152
  readonly columns: ColumnNode[];
153
153
  };
154
- /** Junction table for ManyToMany relationships */
155
- readonly through?: TableNode;
156
154
  /** Action on delete of referenced row */
157
155
  readonly onDelete?: ForeignKeyAction;
158
156
  /** Action on update of referenced row */
@@ -167,120 +165,66 @@ export type IndexNode = IndexSchema & {
167
165
  readonly table: TableNode;
168
166
  };
169
167
  /**
170
- * Root of the schema graph.
171
- * Contains all tables, relationships, and provides graph operations.
168
+ * One node's difference, shaped like a migration's `Change`: `to` is the entities' side and `from` the
169
+ * database's. `to` alone means create, `from` alone means drop, and both mean alter. Being a union, testing
170
+ * one end narrows which ends are present; `Altered` holds the extra fields an alter carries.
172
171
  */
173
- export interface SchemaAST {
174
- /** Map of table name to table node */
175
- readonly tables: Map<string, TableNode>;
176
- /** All relationships in the schema */
177
- readonly relationships: RelationshipNode[];
178
- /** All indexes (also accessible via TableNode.indexes) */
179
- readonly indexes: IndexNode[];
180
- }
181
- /** How two columns differ, a union so which side is present follows from the kind of difference. */
182
- export type ColumnDiff = ColumnDiffBase & ({
183
- readonly type: 'add';
184
- readonly expected: ColumnNode;
185
- readonly actual?: undefined;
172
+ export type NodeChange<T, Altered = unknown> = {
173
+ readonly from?: undefined;
174
+ readonly to: T;
186
175
  } | {
187
- readonly type: 'drop';
188
- readonly expected?: undefined;
189
- readonly actual: ColumnNode;
190
- } | {
191
- readonly type: 'alter';
192
- readonly expected: ColumnNode;
193
- readonly actual: ColumnNode;
194
- });
195
- interface ColumnDiffBase {
176
+ readonly from: T;
177
+ readonly to?: undefined;
178
+ } | ({
179
+ readonly from: T;
180
+ readonly to: T;
181
+ } & Altered);
182
+ /** A column to create, drop or alter; an alter lists in `changed` which parts of the column differ. */
183
+ export type ColumnDiff = NodeChange<ColumnNode, {
184
+ readonly changed: readonly ColumnFacet[];
185
+ }> & {
196
186
  readonly table: string;
197
187
  readonly column: string;
198
- /** Whether this change could cause data loss */
188
+ /** Whether the change can lose data: a drop, or a type change that narrows the column. */
199
189
  readonly isBreaking?: boolean;
200
190
  readonly description?: string;
201
- }
202
- /**
203
- * Difference between two table definitions.
204
- */
205
- export interface TableDiff {
206
- readonly name: string;
207
- readonly type: 'create' | 'drop' | 'alter';
208
- readonly columnDiffs?: ColumnDiff[];
209
- readonly indexDiffs?: IndexDiff[];
210
- /** Set only where the two keys hold different columns. See {@link PrimaryKeyDiff}. */
211
- readonly primaryKeyDiff?: PrimaryKeyDiff;
212
- }
213
- /**
214
- * Two primary keys that hold different columns.
215
- *
216
- * By columns and in order, never by name: `(a, b)` is a different key from `(b, a)`, while the same
217
- * key called `Member_pkey` on one side and `Member__userId_pk` on the other is one key, not two.
218
- */
219
- export interface PrimaryKeyDiff {
191
+ };
192
+ /** A part of a column the differ compares. */
193
+ export type ColumnFacet = 'type' | 'nullable' | 'default';
194
+ /** An index to create, drop or alter; an alter's `description` says what differs. */
195
+ export type IndexDiff = NodeChange<IndexNode> & {
220
196
  readonly table: string;
221
- readonly expected?: PrimaryKeySchema;
222
- /** Named as the database reported it, which is the only name a `DROP` can use. */
223
- readonly actual?: PrimaryKeySchema;
224
- }
225
- /**
226
- * Difference between two index definitions.
227
- */
228
- export interface IndexDiff {
229
197
  readonly name: string;
230
- readonly table: string;
231
- readonly type: 'create' | 'drop' | 'alter';
232
- readonly expected?: IndexNode;
233
- readonly actual?: IndexNode;
234
198
  readonly description?: string;
235
- }
236
- /**
237
- * Difference between two relationship definitions.
238
- */
239
- interface RelationshipDiffBase {
199
+ };
200
+ /** A foreign key to create, drop or alter, matched by its tables and columns, never by name. */
201
+ export type RelationshipDiff = NodeChange<RelationshipNode> & {
240
202
  readonly name: string;
241
203
  readonly fromTable: string;
242
- readonly toTable: string;
243
- }
244
- /**
245
- * Difference between two relationships, shaped like {@link ColumnDiff} and for the same reason: which
246
- * node is present follows from the kind of difference, so a reader never asserts its way past an
247
- * `undefined` the kind had already ruled out.
248
- */
249
- export type RelationshipDiff = RelationshipDiffBase & ({
250
- readonly type: 'create';
251
- readonly expected: RelationshipNode;
252
- readonly actual?: undefined;
253
- } | {
254
- readonly type: 'drop';
255
- readonly expected?: undefined;
256
- readonly actual: RelationshipNode;
257
- } | {
258
- readonly type: 'alter';
259
- readonly expected: RelationshipNode;
260
- readonly actual: RelationshipNode;
261
- });
204
+ };
262
205
  /**
263
- * Complete diff between two schemas.
206
+ * Two primary keys with different columns. Keys are compared by their columns in order, never by name:
207
+ * `(a, b)` differs from `(b, a)`, while `Member_pkey` and `Member__userId_pk` over the same columns are equal.
208
+ * `from` keeps the name the database reported, the only name a `DROP` can use.
264
209
  */
210
+ export type PrimaryKeyDiff = Change<PrimaryKeySchema> & {
211
+ readonly table: string;
212
+ };
213
+ /** The differences within a table that exists on both sides. */
214
+ export interface TableDiff {
215
+ readonly columns: ColumnDiff[];
216
+ readonly indexes: IndexDiff[];
217
+ /** Set only when the two primary keys have different columns. */
218
+ readonly primaryKey?: PrimaryKeyDiff;
219
+ }
220
+ /** How two schemas differ, as the changes a migration would make, grouped by kind. */
265
221
  export interface SchemaDiffResult {
266
- /** Tables that need to be created */
267
- readonly tablesToCreate: TableNode[];
268
- /** Tables that need to be dropped */
269
- readonly tablesToDrop: TableNode[];
270
- /** Tables that need alterations */
271
- readonly tablesToAlter: TableDiff[];
272
- /** All column-level diffs */
273
- readonly columnDiffs: ColumnDiff[];
274
- /** All index diffs */
275
- readonly indexDiffs: IndexDiff[];
276
- /** Every table whose primary key holds different columns than the entity declares. */
277
- readonly primaryKeyDiffs: PrimaryKeyDiff[];
278
- /** All relationship/FK diffs */
279
- readonly relationshipDiffs: RelationshipDiff[];
280
- /** Whether there are any differences */
281
- readonly hasDifferences: boolean;
282
- /** Whether any changes are breaking (could cause data loss) */
283
- readonly hasBreakingChanges: boolean;
222
+ /** Tables only one side has: `to` for a table the database lacks, `from` for one no entity declares. */
223
+ readonly tables: NodeChange<TableNode>[];
224
+ readonly columns: ColumnDiff[];
225
+ readonly indexes: IndexDiff[];
226
+ readonly primaryKeys: PrimaryKeyDiff[];
227
+ readonly relationships: RelationshipDiff[];
284
228
  }
285
229
  /**
286
230
  * Severity level for schema drift issues.
@@ -323,4 +267,3 @@ export interface DriftReport {
323
267
  readonly info: number;
324
268
  };
325
269
  }
326
- export {};
@@ -1,6 +1,6 @@
1
1
  import { AbstractSqlDialect, type DerivedRelation, type RelationRows } from '../dialect/abstractSqlDialect.js';
2
2
  import { type JsonAccessMode, type JsonSlot } from '../dialect/jsonSql.js';
3
- import { type EntityMeta, type FieldOptions, type Query, type QueryContext, type QueryPager, type QueryTextSearchOptions, type QueryWhere, type SqlDialectFeatures, type VectorDistance, type VectorMetric } from '../type/index.js';
3
+ import { type EntityMeta, type FieldOptions, type Query, type QueryContext, type QueryTextSearchOptions, type QueryWhere, type SqlDialectFeatures, type VectorDistance, type VectorMetric } from '../type/index.js';
4
4
  /** What SQLite and the engines derived from it have. */
5
5
  export declare const SQLITE_FEATURES: SqlDialectFeatures;
6
6
  export declare class SqliteDialect extends AbstractSqlDialect {
@@ -8,15 +8,16 @@ export declare class SqliteDialect extends AbstractSqlDialect {
8
8
  readonly dialectName = "sqlite";
9
9
  readonly escapeIdChar = "`";
10
10
  readonly autoIncrementSuffix = "PRIMARY KEY AUTOINCREMENT";
11
- readonly tableOptions = "";
12
11
  readonly beginTransactionCommand = "BEGIN TRANSACTION";
13
- readonly commitTransactionCommand = "COMMIT";
14
- readonly rollbackTransactionCommand = "ROLLBACK";
15
12
  readonly isolationLevelStrategy = "none";
16
13
  readonly booleanLiteral = "integer";
14
+ /**
15
+ * Writes the same text as a bound `Date`. `CURRENT_TIMESTAMP` writes whole seconds with no fraction, so the
16
+ * two would not compare correctly. The parentheses also let SQLite take it as a column default.
17
+ */
18
+ readonly currentTimestamp = "(strftime('%Y-%m-%d %H:%M:%f', 'now'))";
17
19
  /** SQLite's own cap on a function call before 3.48, which libSQL and `bun:sqlite`'s build still have. */
18
20
  readonly maxFunctionArgs: number;
19
- readonly insertIdSource = "returning";
20
21
  /**
21
22
  * The [sqlite-vec](https://github.com/asg017/sqlite-vec) functions, which need that extension
22
23
  * loaded on the connection (see `Sqlite3QuerierPool`'s `extensions` option). libSQL and Turso ship
@@ -36,12 +37,9 @@ export declare class SqliteDialect extends AbstractSqlDialect {
36
37
  protected appendDefaultInsertValue(ctx: QueryContext, field: FieldOptions | undefined): void;
37
38
  protected readonly caseInsensitiveMatch = "native";
38
39
  neExpr(field: string, ph: string): string;
39
- normalizeValue(value: unknown): unknown;
40
- /**
41
- * `OFFSET` is only legal after a `LIMIT` here too, so a bare `$skip` needs one - `-1` being
42
- * SQLite's own spelling of "no limit", where the MySQL family uses its largest `BIGINT`.
43
- */
44
- pager(ctx: QueryContext, opts: QueryPager): void;
40
+ protected readonly dateZone = "";
41
+ /** SQLite's own spelling of no limit. */
42
+ protected readonly unboundedLimit = "-1";
45
43
  /** `json_group_array` of each row's object, ordered by the sort terms carried out beside them. */
46
44
  protected appendRelationArray(ctx: QueryContext, rows: RelationRows): void;
47
45
  /**
@@ -85,8 +83,6 @@ export declare class SqliteDialect extends AbstractSqlDialect {
85
83
  protected jsonCast(operand: string): string;
86
84
  /** `JSON` keeps each element's JSON type in the array, which answers `[]` for no rows. */
87
85
  protected jsonArrayOf(elem: string): string;
88
- protected jsonSet(ctx: QueryContext, expr: string, set: Record<string, unknown>, field?: FieldOptions): string;
89
86
  /** `[#]` appends, creating the array where it is absent: `JSON_SET`, since Turso's `JSON_INSERT` will not touch an existing array. */
90
87
  protected jsonPush(ctx: QueryContext, expr: string, push: Record<string, unknown>): string;
91
- protected jsonUnset(_ctx: QueryContext, expr: string, unset: readonly string[]): string;
92
88
  }