uql-orm 0.96.1 → 0.97.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 (42) hide show
  1. package/dist/migrate/builder/types.d.ts +2 -0
  2. package/dist/migrate/codegen/entityCodeGenerator.js +2 -6
  3. package/dist/migrate/codegen/fieldOptionsSource.d.ts +1 -3
  4. package/dist/migrate/codegen/fieldOptionsSource.js +0 -5
  5. package/dist/migrate/drift/driftDetector.js +16 -0
  6. package/dist/migrate/generator/definitionToNode.d.ts +2 -2
  7. package/dist/migrate/generator/definitionToNode.js +4 -3
  8. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +7 -5
  9. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +10 -11
  10. package/dist/migrate/introspection/baseSqlIntrospector.js +4 -4
  11. package/dist/migrate/introspection/mssqlIntrospector.d.ts +2 -0
  12. package/dist/migrate/introspection/mssqlIntrospector.js +8 -0
  13. package/dist/migrate/introspection/mysqlIntrospector.d.ts +11 -0
  14. package/dist/migrate/introspection/mysqlIntrospector.js +28 -0
  15. package/dist/migrate/introspection/postgresIntrospector.d.ts +3 -0
  16. package/dist/migrate/introspection/postgresIntrospector.js +12 -0
  17. package/dist/migrate/introspection/sqliteIntrospector.d.ts +5 -0
  18. package/dist/migrate/introspection/sqliteIntrospector.js +14 -0
  19. package/dist/migrate/migrator.d.ts +5 -23
  20. package/dist/migrate/migrator.js +26 -80
  21. package/dist/migrate/schemaChange.d.ts +8 -3
  22. package/dist/migrate/schemaChange.js +24 -7
  23. package/dist/migrate/schemaGenerator.d.ts +20 -19
  24. package/dist/migrate/schemaGenerator.js +87 -76
  25. package/dist/migrate/triggerSql.d.ts +6 -8
  26. package/dist/migrate/triggerSql.js +14 -16
  27. package/dist/mongo/mongoIntrospector.d.ts +1 -3
  28. package/dist/mongo/mongoIntrospector.js +0 -4
  29. package/dist/mongo/mongoSchemaGenerator.d.ts +0 -6
  30. package/dist/mongo/mongoSchemaGenerator.js +0 -5
  31. package/dist/schema/schemaAST.js +1 -0
  32. package/dist/schema/schemaASTBuilder.d.ts +3 -1
  33. package/dist/schema/schemaASTBuilder.js +6 -4
  34. package/dist/schema/schemaASTDiffer.js +20 -5
  35. package/dist/schema/types.d.ts +23 -6
  36. package/dist/type/migration.d.ts +10 -19
  37. package/dist/util/ddlExpression.util.d.ts +11 -0
  38. package/dist/util/ddlExpression.util.js +24 -1
  39. package/dist/util/sql.util.d.ts +4 -6
  40. package/dist/util/sql.util.js +2 -6
  41. package/package.json +1 -1
  42. package/skills/uql-orm/SKILL.md +1 -1
@@ -1,11 +1,13 @@
1
1
  import { getMeta } from '../entity/index.js';
2
2
  import { canonicalToSql, engineType, isVectorCategory } from '../schema/canonicalType.js';
3
3
  import { indexChanges } from '../schema/indexDifferences.js';
4
+ import { matchByKey } from '../schema/matchByKey.js';
4
5
  import { buildSchemaAST } from '../schema/schemaASTBuilder.js';
5
6
  import { diffRelationshipNodes, diffTable } from '../schema/schemaASTDiffer.js';
6
7
  import { DEFAULT_FOREIGN_KEY_ACTION, } from '../schema/types.js';
8
+ import { enumCheck } from '../util/ddlExpression.util.js';
7
9
  import { qualifyName } from '../util/index.js';
8
- import { derivedCheckName, derivedForeignKeyName, derivedPrimaryKeyName, isOwnedName } from '../util/sql.util.js';
10
+ import { derivedForeignKeyName, derivedPrimaryKeyName, isOwnedName, splitQualifiedName } from '../util/sql.util.js';
9
11
  import { splitSqlStatements } from './builder/splitSqlStatements.js';
10
12
  import { formatDefaultValue, sameDefault } from './ddl/defaultSql.js';
11
13
  import { indexDdlFor, tableDdlFor } from './ddl/index.js';
@@ -15,7 +17,7 @@ import { columnForeignKey, columnIndex, bareColumn, renderIndexDefinition, table
15
17
  import { indexNodeToSchema } from './generator/indexNodeToSchema.js';
16
18
  import { assertIndexPredicate } from './indexPredicate.js';
17
19
  import { added, alterations, dropped, needsRebuild, newlyRequired, nonEmpty, sides } from './schemaChange.js';
18
- import { dropTrigger, renderTrigger, stampTriggers } from './triggerSql.js';
20
+ import { dropTrigger, dropTriggerBody, renderTrigger, stampTriggers } from './triggerSql.js';
19
21
  /**
20
22
  * Unified SQL schema generator.
21
23
  * Parameterized by dialect to handle Postgres, MySQL, MariaDB, and SQLite.
@@ -80,6 +82,7 @@ export class SqlSchemaGenerator {
80
82
  buildAST(entities) {
81
83
  return buildEntityAST(this, entities, {
82
84
  defaultForeignKeyAction: this.defaultForeignKeyAction,
85
+ renderTriggers: (meta) => [...(meta.triggers ?? []), ...stampTriggers(this.dialect, meta)].map((trigger, i) => renderTrigger(this.dialect, meta, trigger, i)),
83
86
  textScoreIndexes: this.dialect.features.textScoreIndexes,
84
87
  vectorIndexRequiresNotNull: this.features.vectorIndexRequiresNotNull,
85
88
  });
@@ -103,48 +106,9 @@ export class SqlSchemaGenerator {
103
106
  }
104
107
  }
105
108
  // Triggers last: each needs its own table, and a body may read any other the same schema just made.
106
- const made = new Set(tables.map((table) => qualifyName(table.name, table.schema)));
107
- statements.push(...entities
108
- .filter((entity) => made.has(this.resolveTableName(getMeta(entity))))
109
- .flatMap((entity) => this.generateTriggers(entity)));
109
+ statements.push(...terminated(tables.flatMap((table) => table.triggers.flatMap((trigger) => trigger.statements))));
110
110
  return statements;
111
111
  }
112
- /**
113
- * The installed triggers on `entity`'s table it does not declare, and the declared ones not installed,
114
- * compared by name alone: a name carries a hash of the trigger's SQL, so an edited one is a new name.
115
- * Every trigger counts - the ones it authored, and one per event each stamp names.
116
- */
117
- triggerChanges(entity, installed) {
118
- const meta = getMeta(entity);
119
- const triggers = [...(meta.triggers ?? []), ...stampTriggers(this.dialect, meta)];
120
- const rendered = triggers.map((trigger, i) => renderTrigger(this.dialect, meta, trigger, i));
121
- const declared = new Set(rendered.map((trigger) => trigger.name));
122
- return {
123
- stale: [...installed]
124
- .filter(([name]) => isOwnedName(name) && !declared.has(name))
125
- .map(([name, statements]) => ({ name, statements })),
126
- missing: rendered.filter((trigger) => !installed.has(trigger.name)),
127
- };
128
- }
129
- generateTriggers(entity, installed = new Map()) {
130
- const { stale, missing } = this.triggerChanges(entity, installed);
131
- return this.swapTriggers(entity, stale, missing);
132
- }
133
- generateTriggersDown(entity, installed = new Map()) {
134
- const { stale, missing } = this.triggerChanges(entity, installed);
135
- return this.swapTriggers(entity, missing, stale);
136
- }
137
- /** `dropped` taken off `entity`'s table and `created` put on, which is a reconcile read either way. */
138
- swapTriggers(entity, dropped, created) {
139
- return [
140
- ...this.generateTriggerDrops(entity, dropped.map((trigger) => trigger.name)),
141
- ...created.flatMap((trigger) => trigger.statements.map((sql) => `${sql};`)),
142
- ];
143
- }
144
- generateTriggerDrops(entity, names) {
145
- const meta = getMeta(entity);
146
- return names.filter(isOwnedName).flatMap((name) => dropTrigger(this.dialect, meta, name).map((sql) => `${sql};`));
147
- }
148
112
  /**
149
113
  * One statement per distinct schema the tables being created live in, in first-seen order. Only
150
114
  * the tables actually being created, so a narrowed `only` does not declare namespaces it is not
@@ -154,8 +118,12 @@ export class SqlSchemaGenerator {
154
118
  const named = tables.map((table) => table.schema).filter((it) => it !== undefined);
155
119
  return [...new Set(named)].map((schema) => this.dialect.createSchemaSql(schema));
156
120
  }
121
+ /**
122
+ * The inverse of {@link generateCreateSchema}: a table's drop takes its triggers along, so only what they
123
+ * leave behind follows it.
124
+ */
157
125
  generateDropSchema(entities, options = {}) {
158
- const tables = this.orderedTables(entities, 'drop').map((table) => qualifyName(table.name, table.schema));
126
+ const tables = this.orderedTables(entities, 'drop');
159
127
  // A `CASCADE` drop takes the foreign keys with it, and SQLite drops with its constraints off.
160
128
  const cascades = options.cascade && this.features.dropTableCascade;
161
129
  const existing = cascades || this.features.rebuildsTables ? [] : (options.existing?.getTables() ?? []);
@@ -167,7 +135,13 @@ export class SqlSchemaGenerator {
167
135
  ];
168
136
  return names.map((name) => this.generateDropForeignKeySql(tableName, name));
169
137
  });
170
- return [...foreignKeyDrops, ...tables.map((tableName) => this.generateDropTable(tableName, options))];
138
+ return [
139
+ ...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
+ ]),
144
+ ];
171
145
  }
172
146
  /**
173
147
  * The tables of `entities` in dependency order, optionally narrowed to `only`. The AST always spans
@@ -192,19 +166,31 @@ export class SqlSchemaGenerator {
192
166
  * The statements taking a table through `diff`, in the one order both directions need: whatever holds
193
167
  * something down goes before it and comes back after it. A foreign key holds its columns and the key it
194
168
  * points at, so it goes first and comes back last; the key holds its columns; and some engines drop an
195
- * index along with its column, which would leave nothing to name. An alter is its drop, then its add.
169
+ * index along with its column, which would leave nothing to name. A check holds the columns it names, which
170
+ * MySQL refuses to rename or drop under one. An alter is its drop, then its add.
196
171
  */
197
172
  generateAlterTable(diff) {
198
173
  const { tableName, schema, primaryKey, columns, rebuild } = diff;
199
174
  const fills = this.defaultFills(columns);
175
+ const moved = Boolean(rebuild || diff.renamedColumns?.length || sides(columns, 'from').length);
176
+ 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)));
178
+ const triggerCreates = terminated(sides(triggers, 'to').flatMap((trigger) => trigger.statements));
200
179
  if (rebuild) {
201
- return rebuildTable(this.dialect, tableName, rebuild, { renames: diff.renamedColumns ?? [], fills });
180
+ return [
181
+ ...triggerDrops,
182
+ ...rebuildTable(this.dialect, tableName, rebuild, { renames: diff.renamedColumns ?? [], fills }),
183
+ ...triggerCreates,
184
+ ];
202
185
  }
203
186
  const target = this.escapeId(tableName);
204
187
  return [
188
+ ...triggerDrops,
205
189
  ...sides(diff.foreignKeys, 'from').map((foreignKey) => this.generateDropForeignKeySql(tableName, constraintNameOf(tableName, foreignKey))),
206
190
  ...(primaryKey?.from ? [this.generateDropPrimaryKeySql(tableName, primaryKey.from.name)] : []),
207
191
  ...sides(diff.indexes, 'from').map((index) => this.generateDropIndex(tableName, index.name, schema)),
192
+ ...sides(diff.checks, 'from').map((check) => this.dropCheckSql(tableName, check)),
193
+ ...(diff.renamedColumns ?? []).map(({ from, to }) => this.generateRenameColumnSql(tableName, from, to)),
208
194
  ...added(columns).flatMap((column) => this.addColumnStatements(tableName, column, schema)),
209
195
  ...[...fills].map(([column, value]) => {
210
196
  const name = this.escapeId(column);
@@ -215,8 +201,20 @@ export class SqlSchemaGenerator {
215
201
  ...this.addIndexStatements(tableName, sides(diff.indexes, 'to')),
216
202
  ...(primaryKey?.to ? [this.generateAddPrimaryKeySql(tableName, primaryKey.to.columns, primaryKey.to.name)] : []),
217
203
  ...this.addForeignKeyStatements(tableName, sides(diff.foreignKeys, 'to')),
204
+ ...sides(diff.checks, 'to').map((check) => this.addCheckSql(tableName, check)),
205
+ ...triggerCreates,
218
206
  ];
219
207
  }
208
+ /** `CONSTRAINT <name> CHECK (...)`, in a `CREATE TABLE`, after `ADD`, or inline where a column brings it. */
209
+ checkConstraint(check) {
210
+ return `CONSTRAINT ${this.escapeId(check.name)} CHECK (${check.expression})`;
211
+ }
212
+ addCheckSql(tableName, check) {
213
+ return `ALTER TABLE ${this.escapeId(tableName)} ADD ${this.checkConstraint(check)};`;
214
+ }
215
+ dropCheckSql(tableName, check) {
216
+ return `ALTER TABLE ${this.escapeId(tableName)} DROP CONSTRAINT ${this.escapeId(check.name)};`;
217
+ }
220
218
  /**
221
219
  * Each column the changes make required while declaring a default, and that default as SQL: the rows
222
220
  * already there hold a null it has to replace, and it is the only value the entity says it may take.
@@ -237,11 +235,15 @@ export class SqlSchemaGenerator {
237
235
  ...this.indexDdl.settleStatements(tableName, index),
238
236
  ]);
239
237
  }
240
- /** A column added to a table that exists, and its comment where the engine keeps one apart. */
241
- addColumnStatements(tableName, column, schema) {
238
+ /**
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 = []) {
242
243
  this.assertColumnAddable(tableName, column);
244
+ const inline = checks.map((check) => ` ${this.checkConstraint(check)}`).join('');
243
245
  return [
244
- ...this.tableDdl.addColumnStatements(tableName, column, (it) => this.generateColumnDefinitionFromSchema(it)),
246
+ ...this.tableDdl.addColumnStatements(tableName, column, (it) => this.generateColumnDefinitionFromSchema(it) + inline),
245
247
  ...this.generateColumnCommentStatement(tableName, column, schema),
246
248
  ];
247
249
  }
@@ -257,7 +259,7 @@ export class SqlSchemaGenerator {
257
259
  }
258
260
  /**
259
261
  * A column definition from a {@link ColumnSchema}, whose type is already the engine's spelling. Apart from
260
- * {@link generateColumnFromNode}, which alone knows an `enum`; both render through {@link renderColumn}.
262
+ * {@link generateColumnFromNode}, which sizes a canonical type; both render through {@link renderColumn}.
261
263
  */
262
264
  generateColumnDefinitionFromSchema(column) {
263
265
  return this.renderColumn({ ...column, type: sizedType(column) });
@@ -266,7 +268,7 @@ export class SqlSchemaGenerator {
266
268
  * The one place a column definition is spelled, so the `ColumnSchema` and `ColumnNode` paths cannot
267
269
  * drift. A key column states `NOT NULL` rather than leave it to the key: SQLite lets a key column hold
268
270
  * NULL otherwise, and SQL Server adds no key over a nullable column. Never `UNIQUE`: a unique column is
269
- * a unique index, which the table creates beside it. An enum's `CHECK` comes last, the only place MariaDB takes it.
271
+ * a unique index, which the table creates beside it. Nor an enum's `CHECK`, which is the table's, named.
270
272
  */
271
273
  renderColumn(column) {
272
274
  const type = column.generatedAs
@@ -280,10 +282,6 @@ export class SqlSchemaGenerator {
280
282
  if (column.comment) {
281
283
  def += this.generateColumnComment(column.comment);
282
284
  }
283
- if (column.enum?.length) {
284
- const values = column.enum.map((value) => this.dialect.escape(value)).join(', ');
285
- def += ` CHECK (${this.escapeId(column.name)} IN (${values}))`;
286
- }
287
285
  return def;
288
286
  }
289
287
  /** The inline ` COMMENT '...'` a column declaration carries, where the engine takes one there. */
@@ -329,10 +327,6 @@ export class SqlSchemaGenerator {
329
327
  }
330
328
  const tableDiff = diffTable(desired, currentTable, { ...this.diffOptions(), compareIndexes: false });
331
329
  const indexes = indexChanges(currentTable.name, desired.indexes, currentTable.indexes, currentTable.indexFacets);
332
- // An alter's `to` without its values: an alter restates the whole column, and MySQL answers a
333
- // restated `CHECK` by adding a *second* constraint rather than replacing the first, so the column
334
- // would accumulate one per alter. An enum's values reach the database with the column and are never
335
- // restated - which is also why changing them is a hand-written migration. See architecture/roadmap.md.
336
330
  const columns = (tableDiff?.columns ?? []).map((it) => {
337
331
  if (it.from === undefined) {
338
332
  return { to: this.columnNodeToSchema(it.to) };
@@ -340,11 +334,7 @@ export class SqlSchemaGenerator {
340
334
  if (it.to === undefined) {
341
335
  return { from: this.columnNodeToSchema(it.from), isBreaking: true };
342
336
  }
343
- return {
344
- from: this.columnNodeToSchema(it.from),
345
- to: { ...this.columnNodeToSchema(it.to), enum: undefined },
346
- isBreaking: it.isBreaking,
347
- };
337
+ return { from: this.columnNodeToSchema(it.from), to: this.columnNodeToSchema(it.to), isBreaking: it.isBreaking };
348
338
  });
349
339
  const keyDiff = tableDiff?.primaryKey;
350
340
  // The key added named as this generator names it, so the rollback can drop it by that name.
@@ -364,9 +354,18 @@ export class SqlSchemaGenerator {
364
354
  to: to && indexNodeToSchema(to),
365
355
  }))),
366
356
  foreignKeys: nonEmpty(foreignKeys),
357
+ checks: nonEmpty(tableDiff?.checks ?? []),
358
+ // A kept trigger as both sides, which the alter cycles only where a column moves under it.
359
+ triggers: nonEmpty([
360
+ ...(tableDiff?.triggers ?? []),
361
+ ...matchByKey(desired.triggers, currentTable.triggers, (it) => it.name).matched.map(([to, from]) => ({
362
+ from,
363
+ to,
364
+ })),
365
+ ]),
367
366
  renamedColumns: nonEmpty(renamedColumns ?? []),
368
367
  };
369
- if (!(alter.primaryKey || alter.columns || alter.indexes || alter.foreignKeys || alter.renamedColumns)) {
368
+ if (!(tableDiff || alter.indexes || alter.foreignKeys || alter.renamedColumns)) {
370
369
  return undefined;
371
370
  }
372
371
  return this.features.rebuildsTables && needsRebuild(alter)
@@ -375,25 +374,30 @@ export class SqlSchemaGenerator {
375
374
  }
376
375
  /**
377
376
  * Both ends of rebuilding `actual` as `desired`. The new table is the entity's, keeping what it cannot
378
- * know of: the indexes and triggers uql did not make, and foreign keys to tables no entity names. The
379
- * old one is the engine's own statements, so a rollback restores it exactly, checks included.
377
+ * know of: the indexes, checks and triggers uql did not make, and foreign keys to tables no entity names.
378
+ * The old one is the engine's own statements, so a rollback restores it exactly.
380
379
  */
381
380
  rebuildOf(desired, actual, kept, renames) {
382
381
  const definition = actual.definition ?? [];
383
382
  const read = new Set(actual.indexes.map((index) => index.name));
384
383
  const own = (entry) => entry.kind === 'trigger' && isOwnedName(entry.name);
385
- const verbatim = (entries) => entries.map((entry) => `${entry.sql};`);
386
384
  const stored = (table) => [...table.columns.values()].filter((column) => !column.generatedAs).map((column) => column.name);
387
385
  return {
388
386
  from: {
389
- statements: verbatim(definition.filter((entry) => !own(entry))),
387
+ statements: terminated(definition.filter((entry) => !own(entry)).map((entry) => entry.sql)),
390
388
  columns: stored(actual).map((name) => renames.find((rename) => rename.to === name)?.from ?? name),
391
389
  },
392
390
  to: {
393
391
  statements: [
394
- ...this.generateCreateTableFromNode({ ...desired, externalForeignKeys: actual.externalForeignKeys }),
392
+ ...this.generateCreateTableFromNode({
393
+ ...desired,
394
+ checks: [...desired.checks, ...actual.checks.filter((check) => !isOwnedName(check.name))],
395
+ externalForeignKeys: actual.externalForeignKeys,
396
+ }),
395
397
  ...kept.map((index) => this.generateCreateIndexFromNode(index)),
396
- ...verbatim(definition.filter((entry) => (entry.kind === 'index' && !read.has(entry.name)) || (entry.kind === 'trigger' && !own(entry)))),
398
+ ...terminated(definition
399
+ .filter((entry) => (entry.kind === 'index' && !read.has(entry.name)) || (entry.kind === 'trigger' && !own(entry)))
400
+ .map((entry) => entry.sql)),
397
401
  ],
398
402
  columns: stored(desired),
399
403
  },
@@ -436,10 +440,7 @@ export class SqlSchemaGenerator {
436
440
  const columns = key.columns.map((column) => this.escapeId(column)).join(', ');
437
441
  constraints.push(`CONSTRAINT ${this.escapeId(name)} PRIMARY KEY (${columns})`);
438
442
  }
439
- table.checks.forEach((check, i) => {
440
- const name = check.name ?? derivedCheckName(table.name, i + 1);
441
- constraints.push(`CONSTRAINT ${this.escapeId(name)} CHECK (${check.expression})`);
442
- });
443
+ constraints.push(...table.checks.map((check) => this.checkConstraint(check)));
443
444
  for (const rel of table.outgoingRelations) {
444
445
  const refTable = this.dialect.escapeQualifiedId(rel.to.table.name, rel.to.table.schema);
445
446
  constraints.push(this.foreignKeyConstraint(table.name, foreignKeyOf(rel), refTable));
@@ -535,7 +536,13 @@ export class SqlSchemaGenerator {
535
536
  }
536
537
  /** `ADD COLUMN`, plus the foreign key and index the column declares, as `CREATE TABLE` lifts them. */
537
538
  generateAddColumnSql(tableName, column) {
538
- const statements = this.addColumnStatements(tableName, this.definitionColumn(column));
539
+ const checks = enumCheck(splitQualifiedName(tableName).name, column, (sql) => this.dialect.compileDdl(sql));
540
+ const statements = this.features.rebuildsTables
541
+ ? this.addColumnStatements(tableName, this.definitionColumn(column), undefined, checks)
542
+ : [
543
+ ...this.addColumnStatements(tableName, this.definitionColumn(column)),
544
+ ...checks.map((check) => this.addCheckSql(tableName, check)),
545
+ ];
539
546
  const foreignKey = columnForeignKey(column);
540
547
  if (foreignKey) {
541
548
  statements.push(...this.addForeignKeyStatements(tableName, [foreignKey]));
@@ -614,6 +621,10 @@ export class SqlSchemaGenerator {
614
621
  }
615
622
  }
616
623
  }
624
+ /** Statements as a migration runs them, each ended. */
625
+ function terminated(statements) {
626
+ return statements.map((sql) => `${sql};`);
627
+ }
617
628
  /**
618
629
  * What a constraint is called: its own name, or one derived from its columns where nothing named it.
619
630
  * Shared by the add and the drop so a `DROP CONSTRAINT` names exactly what an `ADD CONSTRAINT` made.
@@ -1,21 +1,19 @@
1
1
  import type { AbstractSqlDialect } from '../dialect/index.js';
2
+ import type { TriggerSchema } from '../schema/types.js';
2
3
  import type { EntityMeta, EntityTriggerMeta } from '../type/index.js';
3
- /** A trigger as uql installs it: the identifier, and the statements creating it under that identifier. */
4
- export type RenderedTrigger = {
5
- readonly name: string;
6
- readonly statements: readonly string[];
7
- };
8
4
  /**
9
5
  * One trigger for `dialect`, named for its table and label and ending in a hash of its own SQL. That hash
10
6
  * is the whole of change detection: a trigger is in place exactly when its name is installed, and an
11
7
  * edited one is a new name, created while the old one drops as no longer declared.
12
8
  */
13
- export declare function renderTrigger<E>(dialect: AbstractSqlDialect, meta: EntityMeta<E>, trigger: EntityTriggerMeta<E>, position: number): RenderedTrigger;
9
+ export declare function renderTrigger<E>(dialect: AbstractSqlDialect, meta: EntityMeta<E>, trigger: EntityTriggerMeta<E>, position: number): TriggerSchema;
14
10
  /**
15
11
  * What removes one trigger: the trigger, named with its table only where the engine scopes the name to
16
- * one, and on the Postgres family the function holding its body, which dropping a trigger leaves behind.
12
+ * one, then {@link dropTriggerBody}.
17
13
  */
18
- export declare function dropTrigger<E>(dialect: AbstractSqlDialect, meta: EntityMeta<E>, name: string): string[];
14
+ export declare function dropTrigger(dialect: AbstractSqlDialect, table: string, schema: string | undefined, name: string): string[];
15
+ /** What dropping a trigger or its table leaves behind: on the Postgres family, the function holding its body. */
16
+ export declare function dropTriggerBody(dialect: AbstractSqlDialect, schema: string | undefined, name: string): string[];
19
17
  /**
20
18
  * The triggers a stamp needs: one per event it names, each assigning the field's expression to its
21
19
  * column. Generated rather than authored, so unlike an authored body it renders on every engine from
@@ -19,27 +19,25 @@ export function renderTrigger(dialect, meta, trigger, position) {
19
19
  }
20
20
  /**
21
21
  * What removes one trigger: the trigger, named with its table only where the engine scopes the name to
22
- * one, and on the Postgres family the function holding its body, which dropping a trigger leaves behind.
22
+ * one, then {@link dropTriggerBody}.
23
23
  */
24
- export function dropTrigger(dialect, meta, name) {
25
- const { scope, body } = dialect.features.triggers;
26
- const table = dialect.escapedTableName(meta);
27
- return [
28
- `DROP TRIGGER IF EXISTS ${triggerId(dialect, meta, name)}${scope === 'table' ? ` ON ${table}` : ''}`,
29
- ...(body === 'function' ? [`DROP FUNCTION IF EXISTS ${schemaObjectId(dialect, meta, name)}()`] : []),
30
- ];
24
+ export function dropTrigger(dialect, table, schema, name) {
25
+ const on = dialect.features.triggers.scope === 'table' ? ` ON ${dialect.escapeId(table)}` : '';
26
+ return [`DROP TRIGGER IF EXISTS ${triggerId(dialect, schema, name)}${on}`, ...dropTriggerBody(dialect, schema, name)];
27
+ }
28
+ /** What dropping a trigger or its table leaves behind: on the Postgres family, the function holding its body. */
29
+ export function dropTriggerBody(dialect, schema, name) {
30
+ return dialect.features.triggers.body === 'function'
31
+ ? [`DROP FUNCTION IF EXISTS ${dialect.escapeQualifiedId(name, schema)}()`]
32
+ : [];
31
33
  }
32
34
  /**
33
35
  * A trigger's name as its statements spell it: bare where the engine keeps the name under its table,
34
36
  * since Postgres refuses a schema there, and in the table's schema where the engine keeps names per
35
37
  * schema, or MySQL would look for it in the connection's database and SQL Server in its default schema.
36
38
  */
37
- function triggerId(dialect, meta, name) {
38
- return dialect.features.triggers.scope === 'table' ? dialect.escapeId(name) : schemaObjectId(dialect, meta, name);
39
- }
40
- /** A name in the schema of `meta`'s table, where uql keeps whatever it installs beside it. */
41
- function schemaObjectId(dialect, meta, name) {
42
- return dialect.escapeQualifiedId(name, dialect.resolveSchema(meta));
39
+ function triggerId(dialect, schema, name) {
40
+ return dialect.features.triggers.scope === 'table' ? dialect.escapeId(name) : dialect.escapeQualifiedId(name, schema);
43
41
  }
44
42
  /**
45
43
  * The statements creating one trigger under `name`. Every difference between engines is read off
@@ -70,7 +68,7 @@ function triggerStatements(dialect, meta, trigger, name) {
70
68
  // A per-row engine keeps to the selected rows by a guard; a per-statement one narrowed what the body reads.
71
69
  const guarded = filter && fires === 'eachRowIf' ? `IF ${filter} THEN\n${sql}\nEND IF;` : sql;
72
70
  const opened = features.preamble ? `${features.preamble}\n${guarded}` : guarded;
73
- const id = triggerId(dialect, meta, name);
71
+ const id = triggerId(dialect, dialect.resolveSchema(meta), name);
74
72
  const table = dialect.escapedTableName(meta);
75
73
  const byWhen = fires === 'eachRowWhen';
76
74
  const of = byWhen && operation === 'UPDATE' && trigger.of?.length
@@ -92,7 +90,7 @@ function triggerStatements(dialect, meta, trigger, name) {
92
90
  // A `BEFORE` trigger returning NULL discards the write, so it hands back the row it leaves behind;
93
91
  // after the write the value is ignored.
94
92
  const returned = before ? (operation === 'DELETE' ? names.$old : names.$new) : 'NULL';
95
- const fn = schemaObjectId(dialect, meta, name);
93
+ const fn = dialect.escapeQualifiedId(name, dialect.resolveSchema(meta));
96
94
  return [plpgsqlFunction(fn, `BEGIN\n${opened}\nRETURN ${returned};\nEND`), `${header}\nEXECUTE FUNCTION ${fn}()`];
97
95
  }
98
96
  /** Each event read apart: `beforeUpdate` is `BEFORE` and `UPDATE`. */
@@ -1,6 +1,6 @@
1
1
  import type { IndexFacet } from '../schema/indexDifferences.js';
2
2
  import { SchemaAST } from '../schema/schemaAST.js';
3
- import type { InstalledTriggers, QuerierPool, SchemaIntrospector, TableSchema } from '../type/index.js';
3
+ import type { QuerierPool, SchemaIntrospector, TableSchema } from '../type/index.js';
4
4
  /**
5
5
  * MongoDB schema introspector.
6
6
  * MongoDB doesn't have a fixed schema, so this primarily focuses on collections and indexes.
@@ -10,8 +10,6 @@ export declare class MongoSchemaIntrospector implements SchemaIntrospector {
10
10
  /** `listIndexes` reports keys, uniqueness and text weights; a `partialFilterExpression` is no SQL predicate. */
11
11
  readonly indexFacets: ReadonlySet<IndexFacet>;
12
12
  constructor(pool: QuerierPool);
13
- /** MongoDB runs no trigger within a write, so uql installs none. */
14
- ownedTriggers(): Promise<InstalledTriggers>;
15
13
  introspect(tables?: readonly string[]): Promise<SchemaAST>;
16
14
  getTableSchema(tableName: string): Promise<TableSchema | undefined>;
17
15
  /** Collections only, the way a SQL engine lists its base tables: no view, nor the `system.views` behind one. */
@@ -15,10 +15,6 @@ export class MongoSchemaIntrospector {
15
15
  constructor(pool) {
16
16
  this.pool = pool;
17
17
  }
18
- /** MongoDB runs no trigger within a write, so uql installs none. */
19
- async ownedTriggers() {
20
- return new Map();
21
- }
22
18
  async introspect(tables) {
23
19
  const tableNames = tables ?? (await this.getTableNames());
24
20
  const ast = new SchemaAST();
@@ -2,8 +2,6 @@ import type { AnyMigrationOperation } from '../migrate/builder/types.js';
2
2
  import type { TableNode } from '../schema/types.js';
3
3
  import { type CreateSchemaOptions, type EntityWhereMeta, type IndexSchema, type NamingStrategy, type SchemaDiff, type SchemaGenerator, type Type } from '../type/index.js';
4
4
  import { MongoDialect } from './mongoDialect.js';
5
- /** MongoDB runs no trigger within a write, and a write to an entity declaring one is refused, so there is none to reconcile. */
6
- declare const noTriggers: () => string[];
7
5
  export declare class MongoSchemaGenerator extends MongoDialect implements SchemaGenerator {
8
6
  /** Takes no default foreign key action, since a document store has no foreign keys. */
9
7
  constructor(namingStrategy?: NamingStrategy);
@@ -38,9 +36,6 @@ export declare class MongoSchemaGenerator extends MongoDialect implements Schema
38
36
  generateDropTable(tableName: string): string;
39
37
  /** A collection's indexes: each dropped, then each created, an alter as both. */
40
38
  generateAlterTable(diff: SchemaDiff): string[];
41
- readonly generateTriggers: typeof noTriggers;
42
- readonly generateTriggersDown: typeof noTriggers;
43
- readonly generateTriggerDrops: typeof noTriggers;
44
39
  private dropIndexCommand;
45
40
  /** An index as MongoDB's key spec (`-1` descending, `'text'` full-text), refusing the SQL-only options. */
46
41
  generateCreateIndex(tableName: string, index: IndexSchema): string;
@@ -51,4 +46,3 @@ export declare class MongoSchemaGenerator extends MongoDialect implements Schema
51
46
  generateOperation(operation: AnyMigrationOperation): string[];
52
47
  diffSchema(entity: Type<object>, currentTable: TableNode | undefined): SchemaDiff | undefined;
53
48
  }
54
- export {};
@@ -23,8 +23,6 @@ const ATLAS_SIMILARITY = {
23
23
  l2: 'euclidean',
24
24
  inner: 'dotProduct',
25
25
  };
26
- /** MongoDB runs no trigger within a write, and a write to an entity declaring one is refused, so there is none to reconcile. */
27
- const noTriggers = () => [];
28
26
  export class MongoSchemaGenerator extends MongoDialect {
29
27
  /** Takes no default foreign key action, since a document store has no foreign keys. */
30
28
  constructor(namingStrategy) {
@@ -118,9 +116,6 @@ export class MongoSchemaGenerator extends MongoDialect {
118
116
  ...sides(diff.indexes, 'to').map((index) => this.generateCreateIndex(diff.tableName, index)),
119
117
  ];
120
118
  }
121
- generateTriggers = noTriggers;
122
- generateTriggersDown = noTriggers;
123
- generateTriggerDrops = noTriggers;
124
119
  dropIndexCommand(tableName, index) {
125
120
  return index.type === 'vectorSearch'
126
121
  ? serializeMongoCommand({ action: 'dropSearchIndex', collection: tableName, name: index.name })
@@ -9,6 +9,7 @@ export function createTableNode(name, schema, indexFacets = new Set()) {
9
9
  columns: new Map(),
10
10
  indexes: [],
11
11
  checks: [],
12
+ triggers: [],
12
13
  externalForeignKeys: [],
13
14
  incomingRelations: [],
14
15
  outgoingRelations: [],
@@ -1,7 +1,7 @@
1
1
  import type { EntityMeta, EntityWhereMeta, FieldOptions, Type } from '../type/index.js';
2
2
  import type { NamingStrategy } from '../type/namingStrategy.js';
3
3
  import { SchemaAST } from './schemaAST.js';
4
- import { type ForeignKeyAction } from './types.js';
4
+ import { type ForeignKeyAction, type TriggerSchema } from './types.js';
5
5
  /**
6
6
  * Options for building SchemaAST from entities.
7
7
  */
@@ -27,6 +27,8 @@ export interface BuildSchemaASTOptions {
27
27
  textScoreIndexes?: boolean;
28
28
  /** Whether a column a vector index covers is `NOT NULL` whatever the entity declares, as MariaDB demands. */
29
29
  vectorIndexRequiresNotNull?: boolean;
30
+ /** The triggers an entity's table carries, as its dialect renders them; none where no dialect renders any. */
31
+ renderTriggers?: (meta: EntityMeta<object>) => TriggerSchema[];
30
32
  }
31
33
  /**
32
34
  * Build a SchemaAST from entity classes (decorated with `@Entity`, `@Field`, etc.).
@@ -1,5 +1,5 @@
1
1
  import { fieldOf, foreignKeysOf, getMeta } from '../entity/metadata/definition.js';
2
- import { declaredIndexes, declaredIndexName, renderIndexColumn } from '../util/ddlExpression.util.js';
2
+ import { declaredIndexes, declaredIndexName, enumCheck, ownedCheck, renderIndexColumn, } from '../util/ddlExpression.util.js';
3
3
  import { fulltextWeights, textWeightSteps } from '../util/dialect.util.js';
4
4
  import { declaresNotNull, isAutoIncrement, isInlinedExpression, isSoleIdField } from '../util/field.util.js';
5
5
  import { definedEntries, entityName } from '../util/object.util.js';
@@ -9,7 +9,7 @@ import { resolveColumnCanonicalType } from './canonicalType.js';
9
9
  import { lookupColumns } from './indexColumns.js';
10
10
  import { createTableNode, keyOfColumns, SchemaAST } from './schemaAST.js';
11
11
  import { schemaDefault } from './sqlExpression.js';
12
- import { DEFAULT_FOREIGN_KEY_ACTION } from './types.js';
12
+ import { DEFAULT_FOREIGN_KEY_ACTION, } from './types.js';
13
13
  /**
14
14
  * Build a SchemaAST from entity classes (decorated with `@Entity`, `@Field`, etc.).
15
15
  *
@@ -30,6 +30,7 @@ export function buildSchemaAST(entities, options = {}) {
30
30
  compileIndexPredicate: options.compileIndexPredicate ?? compileDdl,
31
31
  textScoreIndexes: options.textScoreIndexes ?? false,
32
32
  vectorIndexRequiresNotNull: options.vectorIndexRequiresNotNull ?? false,
33
+ renderTriggers: options.renderTriggers ?? (() => []),
33
34
  };
34
35
  for (const entity of entities) {
35
36
  const meta = getMeta(entity);
@@ -59,7 +60,7 @@ function addTableFromEntity(ctx, meta) {
59
60
  const tableName = ctx.resolveTableName(meta);
60
61
  const table = createTableNode(tableName, ctx.resolveSchema(meta));
61
62
  const { columns } = table;
62
- table.checks.push(...(meta.checks ?? []).map(({ name, where }) => ({ name, expression: ctx.compileDdl(where, meta.entity) })));
63
+ table.checks.push(...(meta.checks ?? []).map(({ name, where }) => ownedCheck(tableName, name, ctx.compileDdl(where, meta.entity))));
63
64
  const notNull = ctx.vectorIndexRequiresNotNull ? vectorIndexedEntries(meta) : new Set();
64
65
  // Add columns from fields
65
66
  for (const [key, field] of definedEntries(meta.fields)) {
@@ -81,14 +82,15 @@ function addTableFromEntity(ctx, meta) {
81
82
  // A stamp is filled by a trigger, so it is a column like any other; only `stored: true` generates.
82
83
  generatedAs: field.stored === true && field.computed ? ctx.compileDdl(field.computed, meta.entity) : undefined,
83
84
  comment: field.comment,
84
- enum: field.enum,
85
85
  table,
86
86
  referencedBy: [],
87
87
  references: undefined,
88
88
  };
89
89
  columns.set(columnName, column);
90
+ table.checks.push(...enumCheck(tableName, { name: columnName, enum: field.enum }, (sql) => ctx.compileDdl(sql, meta.entity)));
90
91
  }
91
92
  table.primaryKey = keyOfColumns(columns.values());
93
+ table.triggers.push(...ctx.renderTriggers(meta));
92
94
  ctx.ast.addTable(table);
93
95
  return table;
94
96
  }
@@ -1,4 +1,4 @@
1
- import { qualifyName } from '../util/sql.util.js';
1
+ import { isOwnedName, qualifyName } from '../util/sql.util.js';
2
2
  import { areTypesEqual, isBreakingTypeChange } from './canonicalType.js';
3
3
  import { indexChanges } from './indexDifferences.js';
4
4
  import { matchByKey, pairUnique } from './matchByKey.js';
@@ -29,6 +29,8 @@ export function diffSchemas(source, target, options = {}) {
29
29
  tables: [...created.map((to) => ({ to })), ...dropped.map((from) => ({ from }))],
30
30
  columns: altered.flatMap((tableDiff) => tableDiff.columns),
31
31
  indexes: altered.flatMap((tableDiff) => tableDiff.indexes),
32
+ checks: altered.flatMap((tableDiff) => tableDiff.checks),
33
+ triggers: altered.flatMap((tableDiff) => tableDiff.triggers),
32
34
  primaryKeys: altered.flatMap((tableDiff) => tableDiff.primaryKey ?? []),
33
35
  // Relationships span tables, so they are compared over the whole schema rather than per table.
34
36
  relationships: opts.compareRelationships ? diffRelationshipNodes(source.relationships, target.relationships) : [],
@@ -39,8 +41,21 @@ export function diffTable(source, target, options = {}) {
39
41
  const opts = { ...DEFAULT_OPTIONS, ...options };
40
42
  const columns = diffTableColumns(source, target, opts);
41
43
  const indexes = opts.compareIndexes ? diffTableIndexes(source, target) : [];
44
+ const checks = diffOwned(source.name, source.checks, target.checks);
45
+ const triggers = diffOwned(source.name, source.triggers, target.triggers);
42
46
  const primaryKey = diffPrimaryKey(source, target);
43
- return columns.length || indexes.length || primaryKey ? { columns, indexes, primaryKey } : undefined;
47
+ return columns.length || indexes.length || checks.length || triggers.length || primaryKey
48
+ ? { columns, indexes, checks, triggers, primaryKey }
49
+ : undefined;
50
+ }
51
+ /**
52
+ * What one side declares and the other has not installed, by name, for an object named after a hash of its
53
+ * SQL. Only uql's own are ever dropped: the rest are a second writer's.
54
+ */
55
+ function diffOwned(table, declared, installed) {
56
+ const owned = installed.filter((it) => isOwnedName(it.name));
57
+ const { created, dropped } = matchByKey(declared, owned, (it) => it.name);
58
+ return [...created.map((to) => ({ table, to })), ...dropped.map((from) => ({ table, from }))];
44
59
  }
45
60
  /** The two keys where they hold different columns, compared in order and never by the name the engine gave them. */
46
61
  function diffPrimaryKey(source, target) {
@@ -97,7 +112,8 @@ export function columnRenames(desired, actual, options = {}) {
97
112
  export function tableRenameCandidates(desired, actual, options = {}) {
98
113
  const opts = { ...DEFAULT_OPTIONS, ...options };
99
114
  const { created, dropped } = matchTables(desired, actual, opts);
100
- const same = (to, from) => to.schema === from.schema && !diffTable(to, from, { ...opts, compareIndexes: false });
115
+ // Columns and key alone: a check or trigger is named for its table, so a renamed one differs by them.
116
+ const same = (to, from) => to.schema === from.schema && !diffTableColumns(to, from, opts).length && !diffPrimaryKey(to, from);
101
117
  return pairUnique(created, dropped, same).matched.map(([to, from]) => ({ from: from.name, to: to.name }));
102
118
  }
103
119
  /** The two sides' tables paired by name, those `excludeTables` names left out of both. */
@@ -150,8 +166,7 @@ function diffColumn(tableName, source, target, opts) {
150
166
  changed.push('nullable');
151
167
  }
152
168
  // Not compared, since no statement this generator emits could settle a difference: `isAutoIncrement`,
153
- // `enum` (a check the database reprints), `generatedAs`, and `comment`. Nor `isUnique`: a unique
154
- // column is a unique index, compared with the indexes.
169
+ // `generatedAs`, and `comment`. Nor `isUnique`: a unique column is a unique index, compared with the indexes.
155
170
  // Compare default values (if both defined)
156
171
  if (!opts.defaultsEqual(source.defaultValue, target.defaultValue)) {
157
172
  differences.push(`default: ${target.defaultValue ?? 'NULL'} -> ${source.defaultValue ?? 'NULL'}`);