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
@@ -11,17 +11,14 @@ import { derivedForeignKeyName, derivedPrimaryKeyName, isOwnedName, splitQualifi
11
11
  import { splitSqlStatements } from './builder/splitSqlStatements.js';
12
12
  import { formatDefaultValue, sameDefault } from './ddl/defaultSql.js';
13
13
  import { indexDdlFor, tableDdlFor } from './ddl/index.js';
14
- import { rebuildRefusal, sizedType } from './ddl/tableDdl.js';
14
+ import { rebuildRefusal } from './ddl/tableDdl.js';
15
15
  import { rebuildTable } from './ddl/tableRebuild.js';
16
16
  import { columnForeignKey, columnIndex, bareColumn, renderIndexDefinition, tableDefinitionToNode, } from './generator/definitionToNode.js';
17
17
  import { indexNodeToSchema } from './generator/indexNodeToSchema.js';
18
18
  import { assertIndexPredicate } from './indexPredicate.js';
19
19
  import { added, alterations, dropped, needsRebuild, newlyRequired, nonEmpty, sides } from './schemaChange.js';
20
20
  import { dropTrigger, dropTriggerBody, renderTrigger, stampTriggers } from './triggerSql.js';
21
- /**
22
- * Unified SQL schema generator.
23
- * Parameterized by dialect to handle Postgres, MySQL, MariaDB, and SQLite.
24
- */
21
+ /** The SQL schema generator, one for every SQL engine, its spellings taken from the dialect and its DDL classes. */
25
22
  export class SqlSchemaGenerator {
26
23
  dialect;
27
24
  defaultForeignKeyAction;
@@ -35,52 +32,37 @@ export class SqlSchemaGenerator {
35
32
  this.indexDdl = indexDdlFor(dialect);
36
33
  this.tableDdl = tableDdlFor(dialect);
37
34
  }
38
- get namingStrategy() {
39
- return this.dialect.namingStrategy;
40
- }
41
35
  get features() {
42
36
  return this.dialect.features;
43
37
  }
44
- resolveTableName(meta) {
45
- return this.dialect.resolveTableName(meta);
46
- }
47
- resolveTableAlias(meta) {
48
- return this.dialect.resolveTableAlias(meta);
49
- }
50
- resolveSchema(meta) {
51
- return this.dialect.resolveSchema(meta);
52
- }
53
- resolveColumnName(key, field) {
54
- return this.dialect.resolveColumnName(key, field);
55
- }
56
- compileDdl(sql, entity) {
57
- return this.dialect.compileDdl(sql, entity);
58
- }
59
- compileIndexPredicate(where, entity, indexName) {
60
- assertIndexPredicate(where, this.dialect.dialectName, indexName);
61
- return this.dialect.compileDdl(where, entity);
62
- }
63
38
  /** Escape an identifier (table name, column name, etc.) */
64
39
  escapeId(identifier) {
65
40
  return this.dialect.escapeId(identifier);
66
41
  }
67
42
  /**
68
- * An auto-increment key's type: its canonical type rendered like any column's, plus the engine's generated
69
- * suffix, so a foreign key taking its type from this key gets the same one.
43
+ * The SQL type a column is spelled with: its canonical type, plus the engine's generated suffix on an
44
+ * auto-increment key, so a foreign key taking its type from the key gets the same one.
70
45
  */
71
- serialType(type) {
72
- return `${this.canonicalTypeToSql(type)} ${this.dialect.autoIncrementSuffix}`;
73
- }
74
- /** The SQL type a column is spelled with: the generated-key form for an auto-increment key, the canonical type otherwise. */
75
46
  columnSqlType(col) {
76
- return col.isPrimaryKey && col.isAutoIncrement ? this.serialType(col.type) : this.canonicalTypeToSql(col.type);
77
- }
78
- canonicalTypeToSql(type) {
79
- return canonicalToSql(type, this.dialect);
47
+ const type = canonicalToSql(col.type, this.dialect);
48
+ return col.isPrimaryKey && col.isAutoIncrement ? `${type} ${this.dialect.autoIncrementSuffix}` : type;
80
49
  }
81
- /** The entity side as an AST, carrying this generator's default referential action. */
50
+ /**
51
+ * The entity side as an AST, carrying this generator's default referential action. Named by the dialect's
52
+ * resolvers rather than a naming strategy, which would also rename an explicit `@Entity({ name })`.
53
+ */
82
54
  buildAST(entities) {
83
- return buildEntityAST(this, entities, {
55
+ const { dialect } = this;
56
+ return buildSchemaAST(entities, {
57
+ // The alias, not `resolveTableName`: a node holds its schema apart, so a name derived from it is one identifier.
58
+ resolveTableName: (meta) => dialect.resolveTableAlias(meta),
59
+ resolveSchema: (meta) => dialect.resolveSchema(meta),
60
+ resolveColumnName: (key, field) => dialect.resolveColumnName(key, field),
61
+ compileDdl: (sql, entity) => dialect.compileDdl(sql, entity),
62
+ compileIndexPredicate: (where, entity, indexName) => {
63
+ assertIndexPredicate(where, dialect.dialectName, indexName);
64
+ return dialect.compileDdl(where, entity);
65
+ },
84
66
  defaultForeignKeyAction: this.defaultForeignKeyAction,
85
67
  renderTriggers: (meta) => [...(meta.triggers ?? []), ...stampTriggers(this.dialect, meta)].map((trigger, i) => renderTrigger(this.dialect, meta, trigger, i)),
86
68
  textScoreIndexes: this.dialect.features.textScoreIndexes,
@@ -93,28 +75,25 @@ export class SqlSchemaGenerator {
93
75
  */
94
76
  generateCreateSchema(entities, options = {}) {
95
77
  const tables = this.orderedTables(entities, 'create', options.only);
96
- // Inline only where a constraint cannot be added afterwards, which is what makes the cyclic case
97
- // work everywhere else.
78
+ // Inline only where a constraint cannot be added afterwards, which is what makes the cyclic case work elsewhere.
98
79
  const inline = this.features.rebuildsTables;
99
- // Namespaces first: a qualified `CREATE TABLE` fails against a schema nobody created, and the
100
- // schema is the one part of the layout a migration cannot infer from the table it is making.
101
- const statements = this.generateCreateSchemas(tables);
102
- statements.push(...tables.flatMap((table) => this.generateCreateTableFromNode(inline ? table : { ...table, outgoingRelations: [] }, options)));
103
- if (!inline) {
104
- for (const table of tables) {
105
- statements.push(...this.addForeignKeyStatements(qualifyName(table.name, table.schema), table.outgoingRelations.map(foreignKeyOf)));
106
- }
107
- }
108
- // Triggers last: each needs its own table, and a body may read any other the same schema just made.
109
- statements.push(...terminated(tables.flatMap((table) => table.triggers.flatMap((trigger) => trigger.statements))));
110
- return statements;
80
+ return [
81
+ // Namespaces first: a qualified `CREATE TABLE` fails against a schema nobody created.
82
+ ...this.createNamespaces(tables),
83
+ ...tables.flatMap((table) => this.generateCreateTableFromNode(inline ? table : { ...table, outgoingRelations: [] }, options)),
84
+ ...(inline
85
+ ? []
86
+ : tables.flatMap((table) => table.outgoingRelations.map((relation) => this.addForeignKeySql(qualifyName(table.name, table.schema), foreignKeyOf(relation))))),
87
+ // Triggers last: each needs its own table, and a body may read any other the same schema just made.
88
+ ...terminated(tables.flatMap((table) => table.triggers.flatMap((trigger) => trigger.statements))),
89
+ ];
111
90
  }
112
91
  /**
113
92
  * One statement per distinct schema the tables being created live in, in first-seen order. Only
114
93
  * the tables actually being created, so a narrowed `only` does not declare namespaces it is not
115
94
  * about to fill. Empty on an engine without schemas, whose tables are never qualified.
116
95
  */
117
- generateCreateSchemas(tables) {
96
+ createNamespaces(tables) {
118
97
  const named = tables.map((table) => table.schema).filter((it) => it !== undefined);
119
98
  return [...new Set(named)].map((schema) => this.dialect.createSchemaSql(schema));
120
99
  }
@@ -133,14 +112,19 @@ export class SqlSchemaGenerator {
133
112
  ...table.outgoingRelations.map((relation) => relation.name),
134
113
  ...table.externalForeignKeys.map((foreignKey) => constraintNameOf(tableName, foreignKey)),
135
114
  ];
136
- return names.map((name) => this.generateDropForeignKeySql(tableName, name));
115
+ return names.map((name) => this.tableDdl.dropForeignKey(tableName, name));
137
116
  });
138
117
  return [
139
118
  ...foreignKeyDrops,
140
- ...tables.flatMap((table) => [
141
- this.generateDropTable(qualifyName(table.name, table.schema), options),
142
- ...terminated(table.triggers.flatMap((trigger) => dropTriggerBody(this.dialect, table.schema, trigger.name))),
143
- ]),
119
+ ...tables.flatMap((table) => {
120
+ const name = qualifyName(table.name, table.schema);
121
+ // A table the database lacks left no function: CockroachDB refuses one named in a schema not made yet.
122
+ const triggers = options.existing && !options.existing.getTable(name) ? [] : table.triggers;
123
+ return [
124
+ this.dropTableSql(name, options),
125
+ ...terminated(triggers.flatMap((trigger) => dropTriggerBody(this.dialect, table.schema, trigger.name))),
126
+ ];
127
+ }),
144
128
  ];
145
129
  }
146
130
  /**
@@ -157,7 +141,7 @@ export class SqlSchemaGenerator {
157
141
  const wanted = new Set(only);
158
142
  return tables.filter((table) => wanted.has(qualifyName(table.name, table.schema)));
159
143
  }
160
- generateDropTable(tableName, options = {}) {
144
+ dropTableSql(tableName, options = {}) {
161
145
  const ifExists = options.ifExists ? 'IF EXISTS ' : '';
162
146
  const cascade = options.cascade && this.features.dropTableCascade ? ' CASCADE' : '';
163
147
  return `DROP TABLE ${ifExists}${this.escapeId(tableName)}${cascade};`;
@@ -170,11 +154,11 @@ export class SqlSchemaGenerator {
170
154
  * MySQL refuses to rename or drop under one. An alter is its drop, then its add.
171
155
  */
172
156
  generateAlterTable(diff) {
173
- const { tableName, schema, primaryKey, columns, rebuild } = diff;
157
+ const { tableName, primaryKey, columns, rebuild } = diff;
174
158
  const fills = this.defaultFills(columns);
175
159
  const moved = Boolean(rebuild || diff.renamedColumns?.length || sides(columns, 'from').length);
176
160
  const triggers = (diff.triggers ?? []).filter(({ from, to }) => moved || !from || !to);
177
- const triggerDrops = terminated(sides(triggers, 'from').flatMap((trigger) => dropTrigger(this.dialect, tableName, schema, trigger.name)));
161
+ const triggerDrops = terminated(sides(triggers, 'from').flatMap((trigger) => dropTrigger(this.dialect, tableName, trigger.name)));
178
162
  const triggerCreates = terminated(sides(triggers, 'to').flatMap((trigger) => trigger.statements));
179
163
  if (rebuild) {
180
164
  return [
@@ -184,23 +168,24 @@ export class SqlSchemaGenerator {
184
168
  ];
185
169
  }
186
170
  const target = this.escapeId(tableName);
171
+ const [dropKey, addKey] = this.tableDdl.replacePrimaryKey(tableName, primaryKey?.from, primaryKey?.to);
187
172
  return [
188
173
  ...triggerDrops,
189
- ...sides(diff.foreignKeys, 'from').map((foreignKey) => this.generateDropForeignKeySql(tableName, constraintNameOf(tableName, foreignKey))),
190
- ...(primaryKey?.from ? [this.generateDropPrimaryKeySql(tableName, primaryKey.from.name)] : []),
191
- ...sides(diff.indexes, 'from').map((index) => this.generateDropIndex(tableName, index.name, schema)),
174
+ ...sides(diff.foreignKeys, 'from').map((foreignKey) => this.tableDdl.dropForeignKey(tableName, constraintNameOf(tableName, foreignKey))),
175
+ ...dropKey,
176
+ ...sides(diff.indexes, 'from').map((index) => this.tableDdl.dropIndex(tableName, index.name)),
192
177
  ...sides(diff.checks, 'from').map((check) => this.dropCheckSql(tableName, check)),
193
- ...(diff.renamedColumns ?? []).map(({ from, to }) => this.generateRenameColumnSql(tableName, from, to)),
194
- ...added(columns).flatMap((column) => this.addColumnStatements(tableName, column, schema)),
178
+ ...(diff.renamedColumns ?? []).map(({ from, to }) => this.tableDdl.renameColumn(tableName, from, to)),
179
+ ...added(columns).flatMap((column) => this.addColumnStatements(tableName, column)),
195
180
  ...[...fills].map(([column, value]) => {
196
181
  const name = this.escapeId(column);
197
182
  return `UPDATE ${target} SET ${name} = ${value} WHERE ${name} IS NULL;`;
198
183
  }),
199
- ...this.tableDdl.alterColumns(tableName, alterations(columns), (column) => this.generateColumnDefinitionFromSchema(column)),
184
+ ...this.tableDdl.alterColumns(tableName, alterations(columns)),
185
+ ...addKey,
200
186
  ...dropped(columns).flatMap((column) => this.tableDdl.dropColumn(tableName, column.name)),
201
187
  ...this.addIndexStatements(tableName, sides(diff.indexes, 'to')),
202
- ...(primaryKey?.to ? [this.generateAddPrimaryKeySql(tableName, primaryKey.to.columns, primaryKey.to.name)] : []),
203
- ...this.addForeignKeyStatements(tableName, sides(diff.foreignKeys, 'to')),
188
+ ...sides(diff.foreignKeys, 'to').map((foreignKey) => this.addForeignKeySql(tableName, foreignKey)),
204
189
  ...sides(diff.checks, 'to').map((check) => this.addCheckSql(tableName, check)),
205
190
  ...triggerCreates,
206
191
  ];
@@ -224,89 +209,23 @@ export class SqlSchemaGenerator {
224
209
  .filter(({ from, to }) => from && to.defaultValue !== undefined)
225
210
  .map(({ to }) => [to.name, formatDefaultValue(to.defaultValue, this.dialect, to.type)]));
226
211
  }
227
- /** `ADD CONSTRAINT` for each of `foreignKeys`. */
228
- addForeignKeyStatements(tableName, foreignKeys) {
229
- return foreignKeys.map((foreignKey) => this.generateAddForeignKeySql(tableName, foreignKey));
230
- }
231
212
  /** An index added to a table that may already have rows: its `CREATE`, then what the engine needs after. */
232
213
  addIndexStatements(tableName, indexes) {
233
214
  return indexes.flatMap((index) => [
234
- this.generateCreateIndex(tableName, index),
215
+ this.indexDdl.getCreateIndexStatement(tableName, index),
235
216
  ...this.indexDdl.settleStatements(tableName, index),
236
217
  ]);
237
218
  }
238
219
  /**
239
- * A column added to a table that exists, and its comment where the engine keeps one apart. `checks` go
240
- * inline, which is the one way to constrain a table that is rebuilt to alter.
241
- */
242
- addColumnStatements(tableName, column, schema, checks = []) {
243
- this.assertColumnAddable(tableName, column);
244
- const inline = checks.map((check) => ` ${this.checkConstraint(check)}`).join('');
245
- return [
246
- ...this.tableDdl.addColumnStatements(tableName, column, (it) => this.generateColumnDefinitionFromSchema(it) + inline),
247
- ...this.generateColumnCommentStatement(tableName, column, schema),
248
- ];
249
- }
250
- generateCreateIndex(tableName, index, options = {}) {
251
- return this.indexDdl.getCreateIndexStatement(tableName, index, options);
252
- }
253
- /**
254
- * `schema` is the table's, because that is where its indexes live. MySQL takes it from the table
255
- * operand instead, which is already qualified.
256
- */
257
- generateDropIndex(tableName, indexName, schema) {
258
- return this.tableDdl.dropIndex(tableName, indexName, schema);
259
- }
260
- /**
261
- * A column definition from a {@link ColumnSchema}, whose type is already the engine's spelling. Apart from
262
- * {@link generateColumnFromNode}, which sizes a canonical type; both render through {@link renderColumn}.
220
+ * A column added to a table that exists. `checks` go inline, which is the one way to constrain a table that is
221
+ * rebuilt to alter; a stored generated column, an engine that rebuilds tables takes only in a `CREATE TABLE`.
263
222
  */
264
- generateColumnDefinitionFromSchema(column) {
265
- return this.renderColumn({ ...column, type: sizedType(column) });
266
- }
267
- /**
268
- * The one place a column definition is spelled, so the `ColumnSchema` and `ColumnNode` paths cannot
269
- * drift. A key column states `NOT NULL` rather than leave it to the key: SQLite lets a key column hold
270
- * NULL otherwise, and SQL Server adds no key over a nullable column. Never `UNIQUE`: a unique column is
271
- * a unique index, which the table creates beside it. Nor an enum's `CHECK`, which is the table's, named.
272
- */
273
- renderColumn(column) {
274
- const type = column.generatedAs
275
- ? this.tableDdl.storedGeneratedColumn(column.type, column.generatedAs)
276
- : column.type;
277
- let def = `${this.escapeId(column.name)} ${type}`;
278
- if (!column.nullable) {
279
- def += ' NOT NULL';
280
- }
281
- def += this.tableDdl.defaultClause(column);
282
- if (column.comment) {
283
- def += this.generateColumnComment(column.comment);
284
- }
285
- return def;
286
- }
287
- /** The inline ` COMMENT '...'` a column declaration carries, where the engine takes one there. */
288
- generateColumnComment(comment) {
289
- return this.features.commentSyntax === 'inline' ? ` COMMENT ${this.dialect.escape(comment)}` : '';
290
- }
291
- /** The `COMMENT ON` statements a table and its columns need, after the `CREATE TABLE`, where the engine uses them. */
292
- generateCommentStatements(table) {
293
- if (this.features.commentSyntax !== 'statement') {
294
- return [];
295
- }
296
- const tableRef = this.dialect.escapeQualifiedId(table.name, table.schema);
297
- const statements = table.comment ? [`COMMENT ON TABLE ${tableRef} IS ${this.dialect.escape(table.comment)};`] : [];
298
- for (const col of table.columns.values()) {
299
- statements.push(...this.generateColumnCommentStatement(table.name, col, table.schema));
300
- }
301
- return statements;
302
- }
303
- /** The `COMMENT ON COLUMN` a column needs where the engine uses one, for `CREATE TABLE` and every path adding a column. */
304
- generateColumnCommentStatement(tableName, column, schema) {
305
- if (!column.comment || this.features.commentSyntax !== 'statement') {
306
- return [];
223
+ addColumnStatements(tableName, column, checks = []) {
224
+ if (column.generatedAs) {
225
+ this.assertAlterable(`Adding the stored column "${column.name}" to "${tableName}"`);
307
226
  }
308
- const tableRef = this.dialect.escapeQualifiedId(tableName, schema);
309
- return [`COMMENT ON COLUMN ${tableRef}.${this.escapeId(column.name)} IS ${this.dialect.escape(column.comment)};`];
227
+ const inline = checks.map((check) => ` ${this.checkConstraint(check)}`).join('');
228
+ return this.tableDdl.addColumnStatements(tableName, column, inline);
310
229
  }
311
230
  /**
312
231
  * How the entity differs from the table the database reported, compared by {@link diffTable}, the one
@@ -314,10 +233,9 @@ export class SqlSchemaGenerator {
314
233
  */
315
234
  diffSchema(entity, currentTable, desiredAst, renamedColumns) {
316
235
  const meta = getMeta(entity);
317
- const tableName = this.resolveTableName(meta);
318
- const schema = this.resolveSchema(meta);
236
+ const tableName = this.dialect.resolveTableName(meta);
319
237
  if (!currentTable) {
320
- return { tableName, schema, type: 'create' };
238
+ return { tableName, type: 'create' };
321
239
  }
322
240
  // Keyed by the qualified name this generator resolves, which is the key the AST stores the table
323
241
  // under.
@@ -325,17 +243,13 @@ export class SqlSchemaGenerator {
325
243
  if (!desired) {
326
244
  return undefined;
327
245
  }
328
- const tableDiff = diffTable(desired, currentTable, { ...this.diffOptions(), compareIndexes: false });
246
+ const tableDiff = diffTable(desired, currentTable, this.diffOptions());
329
247
  const indexes = indexChanges(currentTable.name, desired.indexes, currentTable.indexes, currentTable.indexFacets);
330
- const columns = (tableDiff?.columns ?? []).map((it) => {
331
- if (it.from === undefined) {
332
- return { to: this.columnNodeToSchema(it.to) };
333
- }
334
- if (it.to === undefined) {
335
- return { from: this.columnNodeToSchema(it.from), isBreaking: true };
336
- }
337
- return { from: this.columnNodeToSchema(it.from), to: this.columnNodeToSchema(it.to), isBreaking: it.isBreaking };
338
- });
248
+ const columns = (tableDiff?.columns ?? []).map(({ from, to, isBreaking }) => ({
249
+ from: from && this.columnNodeToSchema(from),
250
+ to: to && this.columnNodeToSchema(to),
251
+ isBreaking,
252
+ }));
339
253
  const keyDiff = tableDiff?.primaryKey;
340
254
  // The key added named as this generator names it, so the rollback can drop it by that name.
341
255
  const primaryKey = keyDiff && {
@@ -345,7 +259,6 @@ export class SqlSchemaGenerator {
345
259
  const foreignKeys = diffRelationshipNodes(desired.outgoingRelations, currentTable.outgoingRelations).map(({ from, to }) => ({ from: from && foreignKeyOf(from), to: to && foreignKeyOf(to) }));
346
260
  const alter = {
347
261
  tableName,
348
- schema,
349
262
  type: 'alter',
350
263
  primaryKey,
351
264
  columns: nonEmpty(columns),
@@ -394,7 +307,7 @@ export class SqlSchemaGenerator {
394
307
  checks: [...desired.checks, ...actual.checks.filter((check) => !isOwnedName(check.name))],
395
308
  externalForeignKeys: actual.externalForeignKeys,
396
309
  }),
397
- ...kept.map((index) => this.generateCreateIndexFromNode(index)),
310
+ ...kept.map((index) => this.createIndexFromNode(index)),
398
311
  ...terminated(definition
399
312
  .filter((entry) => (entry.kind === 'index' && !read.has(entry.name)) || (entry.kind === 'trigger' && !own(entry)))
400
313
  .map((entry) => entry.sql)),
@@ -416,154 +329,100 @@ export class SqlSchemaGenerator {
416
329
  }
417
330
  /** Spread, not copied field by field, so a field the node gains cannot go missing here. */
418
331
  columnNodeToSchema(col) {
419
- const { table: _table, referencedBy: _referencedBy, references: _references, ...column } = col;
332
+ const { table: _table, ...column } = col;
420
333
  return { ...column, type: this.columnSqlType(col) };
421
334
  }
422
335
  /** Whether a column's stored default is the one the entity declares, as this engine reprints it. */
423
336
  defaultsEqual = (desired, current) => sameDefault(desired, current, this.dialect);
424
337
  generateCreateTableFromNode(table, options = {}) {
425
- const columns = [];
426
- const constraints = [];
427
- for (const col of table.columns.values()) {
428
- columns.push(this.generateColumnFromNode(col));
429
- }
430
- // Every key, of any width, as one named constraint beside the checks and foreign keys - so a
431
- // later `DROP` has something to name. The exception is a dialect whose serial type states the key
432
- // itself (SQLite's `INTEGER PRIMARY KEY AUTOINCREMENT`, which cannot be split): there the column
433
- // has already declared it, and saying it again is a second primary key.
338
+ // Every key, of any width, as one named constraint, so a later `DROP` has something to name. Except where
339
+ // the serial type states the key itself (SQLite's `INTEGER PRIMARY KEY AUTOINCREMENT`): a second one there.
434
340
  const key = table.primaryKey;
435
341
  const declaredByColumn = this.dialect.features.serialDeclaresPrimaryKey &&
436
342
  key?.columns.length === 1 &&
437
343
  table.columns.get(key.columns[0])?.isAutoIncrement;
438
- if (key && !declaredByColumn) {
439
- const name = key.name ?? derivedPrimaryKeyName(table.name, key.columns);
440
- const columns = key.columns.map((column) => this.escapeId(column)).join(', ');
441
- constraints.push(`CONSTRAINT ${this.escapeId(name)} PRIMARY KEY (${columns})`);
442
- }
443
- constraints.push(...table.checks.map((check) => this.checkConstraint(check)));
444
- for (const rel of table.outgoingRelations) {
445
- const refTable = this.dialect.escapeQualifiedId(rel.to.table.name, rel.to.table.schema);
446
- constraints.push(this.foreignKeyConstraint(table.name, foreignKeyOf(rel), refTable));
447
- }
448
- for (const foreignKey of table.externalForeignKeys) {
449
- constraints.push(this.foreignKeyConstraint(table.name, foreignKey, this.escapeId(foreignKey.references.table)));
450
- }
344
+ const definitions = [
345
+ ...[...table.columns.values()].map((column) => this.tableDdl.columnDefinition(this.columnNodeToSchema(column))),
346
+ ...(key && !declaredByColumn ? [this.tableDdl.primaryKeyConstraint(table.name, key)] : []),
347
+ ...table.checks.map((check) => this.checkConstraint(check)),
348
+ ...table.outgoingRelations.map((relation) => this.foreignKeyConstraint(table.name, foreignKeyOf(relation), this.dialect.escapeQualifiedId(relation.to.table.name, relation.to.table.schema))),
349
+ ...table.externalForeignKeys.map((foreignKey) => this.foreignKeyConstraint(table.name, foreignKey, this.escapeId(foreignKey.references.table))),
350
+ ];
451
351
  const target = this.dialect.escapeQualifiedId(table.name, table.schema);
452
- let createSql = `${this.tableDdl.createTable(target, !!options.ifNotExists)} (\n`;
453
- createSql += columns.map((col) => ` ${col}`).join(',\n');
454
- if (constraints.length > 0) {
455
- createSql += ',\n';
456
- createSql += constraints.map((c) => ` ${c}`).join(',\n');
457
- }
458
- createSql += '\n)';
459
- if (this.tableDdl.tableOptions) {
460
- createSql += ` ${this.tableDdl.tableOptions}`;
461
- }
462
- if (table.comment && this.features.commentSyntax === 'inline') {
463
- createSql += ` COMMENT=${this.dialect.escape(table.comment)}`;
464
- }
465
- createSql += ';';
466
- const statements = [];
467
- if (this.dialect.vectorExtension) {
468
- const hasVectorCol = [...table.columns.values()].some((c) => isVectorCategory(c.type.category));
469
- if (hasVectorCol) {
470
- statements.push(`CREATE EXTENSION IF NOT EXISTS ${this.dialect.vectorExtension};`);
471
- }
472
- }
473
- statements.push(createSql);
474
- statements.push(...this.generateCommentStatements(table));
352
+ const body = definitions.map((definition) => ` ${definition}`).join(',\n');
353
+ const vector = this.dialect.vectorExtension &&
354
+ [...table.columns.values()].some((column) => isVectorCategory(column.type.category));
475
355
  // A table created only if missing creates its indexes the same way, or re-creating a schema fails on the first.
476
356
  const indexOptions = { ifNotExists: !!options.ifNotExists && this.features.indexIfNotExists };
477
- for (const idx of table.indexes) {
478
- statements.push(this.generateCreateIndexFromNode(idx, indexOptions));
479
- }
480
- return statements;
481
- }
482
- /**
483
- * Generate a column definition from a ColumnNode. The primary key is never inline: it is always a table
484
- * constraint, so a later `DROP` can name it.
485
- */
486
- generateColumnFromNode(col) {
487
- return this.renderColumn({ ...col, type: this.columnSqlType(col) });
357
+ return [
358
+ ...(vector ? [`CREATE EXTENSION IF NOT EXISTS ${this.dialect.vectorExtension};`] : []),
359
+ `${this.tableDdl.createTable(target, !!options.ifNotExists)} (\n${body}\n)${this.tableDdl.tableSuffix(table.comment)};`,
360
+ ...this.tableDdl.commentStatements(qualifyName(table.name, table.schema), table.comment, [
361
+ ...table.columns.values(),
362
+ ]),
363
+ ...table.indexes.map((index) => this.createIndexFromNode(index, indexOptions)),
364
+ ];
488
365
  }
489
- /**
490
- * Generate CREATE INDEX SQL from an IndexNode.
491
- * Delegates to `generateCreateIndex` for unified SQL assembly.
492
- */
493
- generateCreateIndexFromNode(index, options = { ifNotExists: false }) {
366
+ /** The `CREATE INDEX` for an index of the AST. */
367
+ createIndexFromNode(index, options = { ifNotExists: false }) {
494
368
  // The index's own name stays unqualified: it is created in the schema of the table it is on.
495
- return this.generateCreateIndex(qualifyName(index.table.name, index.table.schema), indexNodeToSchema(index), options);
369
+ return this.indexDdl.getCreateIndexStatement(qualifyName(index.table.name, index.table.schema), indexNodeToSchema(index), options);
496
370
  }
497
371
  generateCreateTableFromDefinition(table, options = {}) {
498
372
  const tableNode = tableDefinitionToNode(table, (sql) => this.dialect.compileDdl(sql));
499
373
  return this.generateCreateTableFromNode(tableNode, options);
500
374
  }
501
- generateRenameTableSql(oldName, newName) {
502
- return this.tableDdl.renameTable(oldName, newName);
503
- }
504
375
  /** `raw` is split, being the one SQL no generator wrote. */
505
376
  generateOperation(operation) {
506
377
  switch (operation.type) {
507
378
  case 'createTable':
508
379
  return this.generateCreateTableFromDefinition(operation.table);
509
380
  case 'dropTable':
510
- return [
511
- this.generateDropTable(operation.tableName, { ifExists: operation.ifExists, cascade: operation.cascade }),
512
- ];
381
+ return [this.dropTableSql(operation.tableName, { ifExists: operation.ifExists, cascade: operation.cascade })];
513
382
  case 'renameTable':
514
- return [this.generateRenameTableSql(operation.oldName, operation.newName)];
383
+ return [this.tableDdl.renameTable(operation.oldName, operation.newName)];
515
384
  case 'addColumn':
516
- return this.generateAddColumnSql(operation.tableName, operation.column);
385
+ return this.addColumnSql(operation.tableName, operation.column);
517
386
  case 'dropColumn':
518
- return this.generateDropColumnSql(operation.tableName, operation.columnName);
387
+ return this.tableDdl.dropColumn(operation.tableName, operation.columnName);
519
388
  case 'renameColumn':
520
- return [this.generateRenameColumnSql(operation.tableName, operation.oldName, operation.newName)];
389
+ return [this.tableDdl.renameColumn(operation.tableName, operation.oldName, operation.newName)];
521
390
  case 'alterColumn':
522
- return this.generateAlterColumnSql(operation.tableName, operation.columnName, operation.changes);
391
+ this.assertAlterable(`Altering the column "${operation.changes.name}" of "${operation.tableName}"`);
392
+ return this.tableDdl.alterColumns(operation.tableName, [{ to: this.definitionColumn(operation.changes) }]);
523
393
  case 'createIndex':
524
394
  return this.addIndexStatements(operation.tableName, [
525
395
  renderIndexDefinition(operation.index, (sql) => this.dialect.compileDdl(sql)),
526
396
  ]);
527
397
  case 'dropIndex':
528
- return [this.generateDropIndex(operation.tableName, operation.indexName)];
398
+ return [this.tableDdl.dropIndex(operation.tableName, operation.indexName)];
529
399
  case 'addForeignKey':
530
- return [this.generateAddForeignKeySql(operation.tableName, operation.foreignKey)];
400
+ return [this.addForeignKeySql(operation.tableName, operation.foreignKey)];
531
401
  case 'dropForeignKey':
532
- return [this.generateDropForeignKeySql(operation.tableName, operation.constraintName)];
402
+ return [this.tableDdl.dropForeignKey(operation.tableName, operation.constraintName)];
533
403
  case 'raw':
534
404
  return splitSqlStatements(operation.sql);
535
405
  }
536
406
  }
537
407
  /** `ADD COLUMN`, plus the foreign key and index the column declares, as `CREATE TABLE` lifts them. */
538
- generateAddColumnSql(tableName, column) {
408
+ addColumnSql(tableName, column) {
539
409
  const checks = enumCheck(splitQualifiedName(tableName).name, column, (sql) => this.dialect.compileDdl(sql));
540
410
  const statements = this.features.rebuildsTables
541
- ? this.addColumnStatements(tableName, this.definitionColumn(column), undefined, checks)
411
+ ? this.addColumnStatements(tableName, this.definitionColumn(column), checks)
542
412
  : [
543
413
  ...this.addColumnStatements(tableName, this.definitionColumn(column)),
544
414
  ...checks.map((check) => this.addCheckSql(tableName, check)),
545
415
  ];
546
416
  const foreignKey = columnForeignKey(column);
547
417
  if (foreignKey) {
548
- statements.push(...this.addForeignKeyStatements(tableName, [foreignKey]));
418
+ statements.push(this.addForeignKeySql(tableName, foreignKey));
549
419
  }
550
420
  const index = columnIndex(tableName, column);
551
421
  if (index) {
552
- statements.push(this.generateCreateIndex(tableName, index));
422
+ statements.push(this.indexDdl.getCreateIndexStatement(tableName, index));
553
423
  }
554
424
  return statements;
555
425
  }
556
- generateAlterColumnSql(tableName, columnName, column) {
557
- this.assertAlterable(`Altering the column "${columnName}" of "${tableName}"`);
558
- const schema = this.definitionColumn(column);
559
- return this.tableDdl.alterColumn(tableName, { ...schema, name: columnName }, this.renderColumn(schema));
560
- }
561
- generateDropColumnSql(tableName, columnName) {
562
- return this.tableDdl.dropColumn(tableName, columnName);
563
- }
564
- generateRenameColumnSql(tableName, oldName, newName) {
565
- return this.tableDdl.renameColumn(tableName, oldName, newName);
566
- }
567
426
  /**
568
427
  * `CONSTRAINT <name> FOREIGN KEY (...) REFERENCES ... ON DELETE ... ON UPDATE ...`.
569
428
  *
@@ -578,39 +437,11 @@ export class SqlSchemaGenerator {
578
437
  `ON DELETE ${foreignKey.onDelete ?? this.defaultForeignKeyAction} ` +
579
438
  `ON UPDATE ${foreignKey.onUpdate ?? this.defaultForeignKeyAction}`);
580
439
  }
581
- generateAddForeignKeySql(tableName, foreignKey) {
440
+ addForeignKeySql(tableName, foreignKey) {
582
441
  this.assertAlterable(`Adding a foreign key to "${tableName}"`);
583
442
  const constraint = this.foreignKeyConstraint(tableName, foreignKey, this.escapeId(foreignKey.references.table));
584
443
  return `ALTER TABLE ${this.escapeId(tableName)} ADD ${constraint};`;
585
444
  }
586
- generateDropForeignKeySql(tableName, constraintName) {
587
- return this.tableDdl.dropForeignKey(tableName, constraintName);
588
- }
589
- /**
590
- * `ALTER TABLE ... ADD CONSTRAINT <name> PRIMARY KEY (...)`, the other half of
591
- * {@link generateDropPrimaryKeySql}. Refused where the engine cannot alter a key at all, by name,
592
- * rather than emitting DDL it will reject.
593
- */
594
- generateAddPrimaryKeySql(tableName, columns, name) {
595
- this.assertAlterable(`Changing the primary key of "${tableName}"`);
596
- const constraintName = this.escapeId(name ?? derivedPrimaryKeyName(tableName, columns));
597
- const pkCols = columns.map((c) => this.escapeId(c)).join(', ');
598
- return `ALTER TABLE ${this.escapeId(tableName)} ADD CONSTRAINT ${constraintName} PRIMARY KEY (${pkCols});`;
599
- }
600
- /**
601
- * Drops the table's key, by the name the constraint really has: introspected, or derived where this
602
- * generator added it. MySQL takes no name.
603
- */
604
- generateDropPrimaryKeySql(tableName, constraintName) {
605
- this.assertAlterable(`Changing the primary key of "${tableName}"`);
606
- return this.tableDdl.dropPrimaryKey(tableName, constraintName);
607
- }
608
- /** A stored generated column, which an engine that rebuilds tables takes only in a `CREATE TABLE`. */
609
- assertColumnAddable(tableName, column) {
610
- if (column.generatedAs) {
611
- this.assertAlterable(`Adding the stored column "${column.name}" to "${tableName}"`);
612
- }
613
- }
614
445
  /**
615
446
  * Refuses `what` where the engine makes it only by rebuilding the table, which a migration generated
616
447
  * from the entities does and a lone statement of the builder cannot.
@@ -635,8 +466,8 @@ export function constraintNameOf(tableName, foreignKey) {
635
466
  /**
636
467
  * A relationship node as the migration's own `ForeignKeySchema`. The node's `name` is kept rather
637
468
  * than derived: on the database's side it is the only name a `DROP` can use, and on the entity's it
638
- * is already the derived one. An unset action stays unset - the default belongs to the one place
639
- * that spends it, `addForeignKeyStatements`.
469
+ * is already the derived one. An unset action stays unset: the default belongs to the one place
470
+ * that spends it, `foreignKeyConstraint`.
640
471
  */
641
472
  function foreignKeyOf(relation) {
642
473
  return {
@@ -650,19 +481,3 @@ function foreignKeyOf(relation) {
650
481
  onUpdate: relation.onUpdate,
651
482
  };
652
483
  }
653
- /**
654
- * The entities as an AST, named by `generator`'s resolvers rather than a naming strategy, which would
655
- * also rename an explicit `@Entity({ name })` and so compare each table under another name.
656
- */
657
- export function buildEntityAST(generator, entities, options = {}) {
658
- return buildSchemaAST(entities, {
659
- // The alias, not `resolveTableName`: a node holds its schema separately, so that a name derived
660
- // from it stays a single identifier.
661
- resolveTableName: (meta) => generator.resolveTableAlias(meta),
662
- resolveSchema: (meta) => generator.resolveSchema(meta),
663
- resolveColumnName: (key, field) => generator.resolveColumnName(key, field),
664
- compileDdl: (sql, entity) => generator.compileDdl(sql, entity),
665
- compileIndexPredicate: (where, entity, indexName) => generator.compileIndexPredicate(where, entity, indexName),
666
- ...options,
667
- });
668
- }
@@ -12,7 +12,8 @@ export declare class DatabaseMigrationStorage implements MigrationStorage {
12
12
  constructor(pool: QuerierPool, options?: {
13
13
  tableName?: string;
14
14
  });
15
- ensureStorage(): Promise<void>;
15
+ /** Creates the table on first use, once. */
16
+ private ensureStorage;
16
17
  /**
17
18
  * Rendered by the schema generator rather than written out, so each engine gets its own spelling: SQL
18
19
  * Server has no `CREATE TABLE IF NOT EXISTS`, and its `TIMESTAMP` is a row version that takes no default.