uql-orm 0.91.1 → 0.93.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 (165) 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 +6 -2
  14. package/dist/dialect/abstractDialect.d.ts +1 -1
  15. package/dist/dialect/abstractDialect.js +4 -1
  16. package/dist/dialect/abstractSqlDialect.d.ts +68 -37
  17. package/dist/dialect/abstractSqlDialect.js +185 -107
  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 +14 -4
  24. package/dist/dialect/mergeSqlDialect.js +32 -15
  25. package/dist/dialect/mysqlLikeSqlDialect.d.ts +16 -24
  26. package/dist/dialect/mysqlLikeSqlDialect.js +38 -52
  27. package/dist/dialect/pgLikeSqlDialect.d.ts +8 -8
  28. package/dist/dialect/pgLikeSqlDialect.js +19 -22
  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 +2 -2
  36. package/dist/index.js +2 -2
  37. package/dist/maria/mariaDialect.d.ts +4 -3
  38. package/dist/maria/mariaDialect.js +4 -6
  39. package/dist/migrate/builder/columnBuilder.d.ts +5 -15
  40. package/dist/migrate/builder/columnBuilder.js +50 -86
  41. package/dist/migrate/builder/index.d.ts +0 -1
  42. package/dist/migrate/builder/index.js +0 -1
  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 +19 -30
  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 +22 -14
  52. package/dist/migrate/codegen/indexDecoratorSource.js +64 -41
  53. package/dist/migrate/ddl/defaultSql.d.ts +31 -0
  54. package/dist/migrate/ddl/defaultSql.js +109 -0
  55. package/dist/migrate/ddl/index.d.ts +2 -4
  56. package/dist/migrate/ddl/index.js +14 -5
  57. package/dist/migrate/ddl/mssqlTableDdl.d.ts +1 -0
  58. package/dist/migrate/ddl/mssqlTableDdl.js +4 -1
  59. package/dist/migrate/ddl/mysqlTableDdl.d.ts +17 -0
  60. package/dist/migrate/ddl/mysqlTableDdl.js +33 -0
  61. package/dist/migrate/ddl/pgTableDdl.d.ts +7 -0
  62. package/dist/migrate/ddl/pgTableDdl.js +17 -0
  63. package/dist/migrate/ddl/tableDdl.d.ts +15 -10
  64. package/dist/migrate/ddl/tableDdl.js +31 -32
  65. package/dist/migrate/drift/driftDetector.js +46 -59
  66. package/dist/migrate/generator/definitionToNode.d.ts +11 -7
  67. package/dist/migrate/generator/definitionToNode.js +27 -34
  68. package/dist/migrate/generator/indexNodeToSchema.d.ts +3 -3
  69. package/dist/migrate/generator/indexNodeToSchema.js +5 -4
  70. package/dist/migrate/index.js +1 -1
  71. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +10 -5
  72. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +9 -0
  73. package/dist/migrate/introspection/baseSqlIntrospector.d.ts +0 -1
  74. package/dist/migrate/introspection/baseSqlIntrospector.js +6 -8
  75. package/dist/migrate/introspection/mssqlIntrospector.js +3 -8
  76. package/dist/migrate/introspection/mysqlIntrospector.d.ts +11 -4
  77. package/dist/migrate/introspection/mysqlIntrospector.js +27 -11
  78. package/dist/migrate/introspection/postgresIntrospector.d.ts +2 -2
  79. package/dist/migrate/introspection/postgresIntrospector.js +3 -3
  80. package/dist/migrate/introspection/sqliteIntrospector.d.ts +1 -1
  81. package/dist/migrate/introspection/sqliteIntrospector.js +7 -10
  82. package/dist/migrate/migrationTarget.js +3 -3
  83. package/dist/migrate/schemaGenerator.d.ts +8 -12
  84. package/dist/migrate/schemaGenerator.js +36 -62
  85. package/dist/migrate/storage/databaseStorage.js +2 -2
  86. package/dist/migrate/triggerSql.d.ts +1 -1
  87. package/dist/migrate/triggerSql.js +17 -8
  88. package/dist/mongo/mongoDialect.d.ts +4 -3
  89. package/dist/mongo/mongoDialect.js +52 -38
  90. package/dist/mongo/mongoIntrospector.js +1 -1
  91. package/dist/mongo/mongoSchemaGenerator.d.ts +7 -4
  92. package/dist/mongo/mongoSchemaGenerator.js +18 -21
  93. package/dist/mongo/mongodbQuerier.d.ts +15 -8
  94. package/dist/mongo/mongodbQuerier.js +48 -33
  95. package/dist/mssql/mssqlDialect.d.ts +9 -5
  96. package/dist/mssql/mssqlDialect.js +23 -8
  97. package/dist/postgres/postgresDialect.d.ts +5 -2
  98. package/dist/postgres/postgresDialect.js +6 -6
  99. package/dist/querier/abstractQuerier.d.ts +20 -15
  100. package/dist/querier/abstractQuerier.js +93 -41
  101. package/dist/querier/abstractQuerierPool.d.ts +26 -24
  102. package/dist/querier/abstractQuerierPool.js +26 -64
  103. package/dist/querier/abstractSqlQuerier.d.ts +5 -6
  104. package/dist/querier/abstractSqlQuerier.js +15 -33
  105. package/dist/querier/cursor.d.ts +10 -0
  106. package/dist/querier/cursor.js +81 -0
  107. package/dist/querier/keyset.d.ts +19 -0
  108. package/dist/querier/keyset.js +198 -0
  109. package/dist/schema/canonicalType.d.ts +3 -3
  110. package/dist/schema/canonicalType.js +13 -12
  111. package/dist/schema/indexDifferences.d.ts +14 -7
  112. package/dist/schema/indexDifferences.js +7 -5
  113. package/dist/schema/schemaAST.d.ts +0 -1
  114. package/dist/schema/schemaAST.js +0 -2
  115. package/dist/schema/schemaASTBuilder.js +14 -20
  116. package/dist/schema/schemaASTDiffer.d.ts +7 -9
  117. package/dist/schema/schemaASTDiffer.js +54 -107
  118. package/dist/schema/sqlExpression.d.ts +28 -0
  119. package/dist/schema/sqlExpression.js +42 -0
  120. package/dist/schema/types.d.ts +48 -105
  121. package/dist/sqlite/sqliteDialect.d.ts +10 -13
  122. package/dist/sqlite/sqliteDialect.js +19 -30
  123. package/dist/type/dialect.d.ts +46 -11
  124. package/dist/type/dialect.js +2 -0
  125. package/dist/type/entity.d.ts +18 -3
  126. package/dist/type/migration.d.ts +7 -7
  127. package/dist/type/querier.d.ts +19 -26
  128. package/dist/type/query.d.ts +116 -25
  129. package/dist/type/query.js +21 -28
  130. package/dist/type/universalQuerier.d.ts +33 -7
  131. package/dist/type/utility.d.ts +10 -0
  132. package/dist/util/bytes.d.ts +7 -0
  133. package/dist/util/bytes.js +22 -0
  134. package/dist/util/date.d.ts +5 -0
  135. package/dist/util/date.js +5 -0
  136. package/dist/util/dialect.util.d.ts +1 -25
  137. package/dist/util/dialect.util.js +4 -50
  138. package/dist/util/field.util.d.ts +9 -0
  139. package/dist/util/field.util.js +15 -0
  140. package/dist/util/fieldOption.util.js +2 -2
  141. package/dist/util/index.d.ts +2 -1
  142. package/dist/util/index.js +2 -1
  143. package/dist/util/object.util.d.ts +0 -2
  144. package/dist/util/object.util.js +0 -7
  145. package/dist/util/query.util.d.ts +40 -0
  146. package/dist/util/query.util.js +76 -0
  147. package/dist/util/raw.d.ts +16 -1
  148. package/dist/util/raw.js +31 -0
  149. package/dist/util/relationQuery.util.js +18 -16
  150. package/dist/util/rowKey.util.js +2 -3
  151. package/dist/util/sql.util.d.ts +8 -2
  152. package/dist/util/sql.util.js +16 -17
  153. package/dist/util/sqlLiteral.js +2 -12
  154. package/dist/util/string.util.d.ts +5 -0
  155. package/dist/util/string.util.js +12 -0
  156. package/dist/util/triggerWrite.d.ts +11 -1
  157. package/dist/util/triggerWrite.js +14 -0
  158. package/package.json +1 -1
  159. package/skills/uql-orm/SKILL.md +22 -10
  160. package/dist/browser/options.d.ts +0 -4
  161. package/dist/browser/options.js +0 -13
  162. package/dist/browser/type/clientQuerierPool.d.ts +0 -4
  163. package/dist/browser/type/clientQuerierPool.js +0 -1
  164. package/dist/migrate/builder/expressions.d.ts +0 -69
  165. package/dist/migrate/builder/expressions.js +0 -145
@@ -1,17 +1,18 @@
1
1
  import { getMeta } from '../entity/index.js';
2
- import { canonicalToSql, engineType, isVectorCategory, resolveColumnCanonicalType } from '../schema/canonicalType.js';
2
+ import { canonicalToSql, engineType, isVectorCategory } from '../schema/canonicalType.js';
3
3
  import { indexChanges } from '../schema/indexDifferences.js';
4
4
  import { buildSchemaAST } from '../schema/schemaASTBuilder.js';
5
5
  import { diffRelationshipNodes, diffTable } from '../schema/schemaASTDiffer.js';
6
- import { isAutoIncrement, qualifyName } from '../util/index.js';
6
+ import { DEFAULT_FOREIGN_KEY_ACTION, } from '../schema/types.js';
7
+ import { qualifyName } from '../util/index.js';
7
8
  import { derivedCheckName, derivedForeignKeyName, derivedPrimaryKeyName, isOwnedName } from '../util/sql.util.js';
8
9
  import { UqlUsageError } from '../util/uqlError.js';
9
- import { formatDefaultValue, sameDefault } from './builder/expressions.js';
10
10
  import { splitSqlStatements } from './builder/splitSqlStatements.js';
11
+ import { formatDefaultValue, sameDefault } from './ddl/defaultSql.js';
11
12
  import { indexDdlFor, tableDdlFor } from './ddl/index.js';
12
13
  import { sizedType } from './ddl/tableDdl.js';
13
14
  import { rebuildTable } from './ddl/tableRebuild.js';
14
- import { columnForeignKey, columnIndex, fullColumnDefinitionToNode, renderIndexDefinition, tableDefinitionToNode, } from './generator/definitionToNode.js';
15
+ import { columnForeignKey, columnIndex, bareColumn, renderIndexDefinition, tableDefinitionToNode, } from './generator/definitionToNode.js';
15
16
  import { indexNodeToSchema } from './generator/indexNodeToSchema.js';
16
17
  import { assertIndexPredicate } from './indexPredicate.js';
17
18
  import { added, alterations, dropped, needsRebuild, newlyRequired, nonEmpty, sides } from './schemaChange.js';
@@ -27,7 +28,7 @@ export class SqlSchemaGenerator {
27
28
  indexDdl;
28
29
  /** The `ALTER TABLE` statements this dialect spells its own way, the migrator's for the same reason. */
29
30
  tableDdl;
30
- constructor(dialect, defaultForeignKeyAction = 'NO ACTION') {
31
+ constructor(dialect, defaultForeignKeyAction = DEFAULT_FOREIGN_KEY_ACTION) {
31
32
  this.dialect = dialect;
32
33
  this.defaultForeignKeyAction = defaultForeignKeyAction;
33
34
  this.indexDdl = indexDdlFor(dialect);
@@ -242,10 +243,7 @@ export class SqlSchemaGenerator {
242
243
  * operand instead, which is already qualified.
243
244
  */
244
245
  generateDropIndex(tableName, indexName, schema) {
245
- if (this.dialect.dropIndexSyntax === 'on-table') {
246
- return `DROP INDEX ${this.escapeId(indexName)} ON ${this.escapeId(tableName)};`;
247
- }
248
- return `DROP INDEX IF EXISTS ${this.dialect.escapeQualifiedId(indexName, schema)};`;
246
+ return this.tableDdl.dropIndex(tableName, indexName, schema);
249
247
  }
250
248
  /**
251
249
  * A column definition from a {@link ColumnSchema}, whose type is already the engine's spelling. Apart from
@@ -278,16 +276,6 @@ export class SqlSchemaGenerator {
278
276
  }
279
277
  return def;
280
278
  }
281
- /**
282
- * The column type a field gets, resolved as its table resolves it. A field alone cannot tell that it is
283
- * one column of a composite key, which its table never makes serial.
284
- */
285
- getSqlType(field) {
286
- const canonical = resolveColumnCanonicalType(field);
287
- return isAutoIncrement(field, field.isId === true)
288
- ? this.serialType(canonical)
289
- : this.canonicalTypeToSql(canonical);
290
- }
291
279
  /** The inline ` COMMENT '...'` a column declaration carries, where the engine takes one there. */
292
280
  generateColumnComment(comment) {
293
281
  return this.features.commentSyntax === 'inline' ? ` COMMENT ${this.dialect.escape(comment)}` : '';
@@ -335,44 +323,36 @@ export class SqlSchemaGenerator {
335
323
  // restated `CHECK` by adding a *second* constraint rather than replacing the first, so the column
336
324
  // would accumulate one per alter. An enum's values reach the database with the column and are never
337
325
  // restated - which is also why changing them is a hand-written migration. See architecture/roadmap.md.
338
- const columns = (tableDiff?.columnDiffs ?? []).map((it) => {
339
- if (it.type === 'add') {
340
- return { to: this.columnNodeToSchema(it.expected) };
326
+ const columns = (tableDiff?.columns ?? []).map((it) => {
327
+ if (it.from === undefined) {
328
+ return { to: this.columnNodeToSchema(it.to) };
341
329
  }
342
- if (it.type === 'drop') {
343
- return { from: this.columnNodeToSchema(it.actual), isBreaking: true };
330
+ if (it.to === undefined) {
331
+ return { from: this.columnNodeToSchema(it.from), isBreaking: true };
344
332
  }
345
333
  return {
346
- from: this.columnNodeToSchema(it.actual),
347
- to: { ...this.columnNodeToSchema(it.expected), enum: undefined },
334
+ from: this.columnNodeToSchema(it.from),
335
+ to: { ...this.columnNodeToSchema(it.to), enum: undefined },
348
336
  isBreaking: it.isBreaking,
349
337
  };
350
338
  });
351
- const keyDiff = tableDiff?.primaryKeyDiff;
339
+ const keyDiff = tableDiff?.primaryKey;
352
340
  // The key added named as this generator names it, so the rollback can drop it by that name.
353
341
  const primaryKey = keyDiff && {
354
- from: keyDiff.actual,
355
- to: keyDiff.expected && {
356
- columns: keyDiff.expected.columns,
357
- name: derivedPrimaryKeyName(tableName, keyDiff.expected.columns),
358
- },
342
+ from: keyDiff.from,
343
+ to: keyDiff.to && { columns: keyDiff.to.columns, name: derivedPrimaryKeyName(tableName, keyDiff.to.columns) },
359
344
  };
360
- const relationDiffs = diffRelationshipNodes(desired.outgoingRelations, currentTable.outgoingRelations, this.diffOptions());
361
- const foreignKeys = relationDiffs.map(({ actual, expected }) => ({
362
- from: actual && foreignKeyOf(actual),
363
- to: expected && foreignKeyOf(expected),
364
- }));
345
+ const foreignKeys = diffRelationshipNodes(desired.outgoingRelations, currentTable.outgoingRelations).map(({ from, to }) => ({ from: from && foreignKeyOf(from), to: to && foreignKeyOf(to) }));
365
346
  const alter = {
366
347
  tableName,
367
348
  schema,
368
349
  type: 'alter',
369
350
  primaryKey,
370
351
  columns: nonEmpty(columns),
371
- indexes: nonEmpty([
372
- ...indexes.toAdd.map((to) => ({ to: indexNodeToSchema(to) })),
373
- ...indexes.toDrop.map((from) => ({ from: indexNodeToSchema(from) })),
374
- ...indexes.toAlter.map(({ from, to }) => ({ from: indexNodeToSchema(from), to: indexNodeToSchema(to) })),
375
- ]),
352
+ indexes: nonEmpty(indexes.changes.map(({ from, to }) => ({
353
+ from: from && indexNodeToSchema(from),
354
+ to: to && indexNodeToSchema(to),
355
+ }))),
376
356
  foreignKeys: nonEmpty(foreignKeys),
377
357
  renamedColumns: nonEmpty(renamedColumns ?? []),
378
358
  };
@@ -415,6 +395,11 @@ export class SqlSchemaGenerator {
415
395
  defaultsEqual: this.defaultsEqual,
416
396
  };
417
397
  }
398
+ /** Converts a builder's column to the `ColumnSchema` its DDL is rendered from. */
399
+ definitionColumn(col) {
400
+ const column = bareColumn(col);
401
+ return { ...column, type: this.columnSqlType(column) };
402
+ }
418
403
  /** Spread, not copied field by field, so a field the node gains cannot go missing here. */
419
404
  columnNodeToSchema(col) {
420
405
  const { table: _table, referencedBy: _referencedBy, references: _references, ...column } = col;
@@ -460,8 +445,8 @@ export class SqlSchemaGenerator {
460
445
  createSql += constraints.map((c) => ` ${c}`).join(',\n');
461
446
  }
462
447
  createSql += '\n)';
463
- if (this.dialect.tableOptions) {
464
- createSql += ` ${this.dialect.tableOptions}`;
448
+ if (this.tableDdl.tableOptions) {
449
+ createSql += ` ${this.tableDdl.tableOptions}`;
465
450
  }
466
451
  if (table.comment && this.features.commentSyntax === 'inline') {
467
452
  createSql += ` COMMENT=${this.dialect.escape(table.comment)}`;
@@ -484,8 +469,8 @@ export class SqlSchemaGenerator {
484
469
  return statements;
485
470
  }
486
471
  /**
487
- * Generate a column definition from a ColumnNode. A composite key is declared as a table constraint,
488
- * so only a lone primary key column carries `PRIMARY KEY` inline.
472
+ * Generate a column definition from a ColumnNode. The primary key is never inline: it is always a table
473
+ * constraint, so a later `DROP` can name it.
489
474
  */
490
475
  generateColumnFromNode(col) {
491
476
  return this.renderColumn({ ...col, type: this.columnSqlType(col) });
@@ -502,9 +487,6 @@ export class SqlSchemaGenerator {
502
487
  const tableNode = tableDefinitionToNode(table, (sql) => this.dialect.compileDdl(sql));
503
488
  return this.generateCreateTableFromNode(tableNode, options);
504
489
  }
505
- generateCreateIndexFromDefinition(tableName, index) {
506
- return this.generateCreateIndex(tableName, renderIndexDefinition(index, (sql) => this.dialect.compileDdl(sql)));
507
- }
508
490
  generateRenameTableSql(oldName, newName) {
509
491
  return this.tableDdl.renameTable(oldName, newName);
510
492
  }
@@ -543,7 +525,7 @@ export class SqlSchemaGenerator {
543
525
  }
544
526
  /** `ADD COLUMN`, plus the foreign key and index the column declares, as `CREATE TABLE` lifts them. */
545
527
  generateAddColumnSql(tableName, column) {
546
- const statements = this.addColumnStatements(tableName, this.columnNodeToSchema(fullColumnDefinitionToNode(column, tableName)));
528
+ const statements = this.addColumnStatements(tableName, this.definitionColumn(column));
547
529
  const foreignKey = columnForeignKey(column);
548
530
  if (foreignKey) {
549
531
  statements.push(...this.addForeignKeyStatements(tableName, [foreignKey]));
@@ -556,8 +538,8 @@ export class SqlSchemaGenerator {
556
538
  }
557
539
  generateAlterColumnSql(tableName, columnName, column) {
558
540
  this.assertAlterable(`Altering the column "${columnName}" of "${tableName}"`);
559
- const node = fullColumnDefinitionToNode(column, tableName);
560
- return this.tableDdl.alterColumn(tableName, { ...this.columnNodeToSchema(node), name: columnName }, this.generateColumnFromNode(node));
541
+ const schema = this.definitionColumn(column);
542
+ return this.tableDdl.alterColumn(tableName, { ...schema, name: columnName }, this.renderColumn(schema));
561
543
  }
562
544
  generateDropColumnSql(tableName, columnName) {
563
545
  return this.tableDdl.dropColumn(tableName, columnName);
@@ -585,7 +567,7 @@ export class SqlSchemaGenerator {
585
567
  return `ALTER TABLE ${this.escapeId(tableName)} ADD ${constraint};`;
586
568
  }
587
569
  generateDropForeignKeySql(tableName, constraintName) {
588
- return `ALTER TABLE ${this.escapeId(tableName)} ${this.dialect.dropForeignKeySyntax} ${this.escapeId(constraintName)};`;
570
+ return this.tableDdl.dropForeignKey(tableName, constraintName);
589
571
  }
590
572
  /**
591
573
  * `ALTER TABLE ... ADD CONSTRAINT <name> PRIMARY KEY (...)`, the other half of
@@ -604,15 +586,7 @@ export class SqlSchemaGenerator {
604
586
  */
605
587
  generateDropPrimaryKeySql(tableName, constraintName) {
606
588
  this.assertAlterable(`Changing the primary key of "${tableName}"`);
607
- const table = this.escapeId(tableName);
608
- if (this.dialect.dropPrimaryKeySyntax === 'DROP PRIMARY KEY') {
609
- return `ALTER TABLE ${table} DROP PRIMARY KEY;`;
610
- }
611
- if (!constraintName) {
612
- throw new UqlUsageError(`Cannot drop the primary key of "${tableName}": ${this.dialect} names the constraint, and ` +
613
- 'introspection did not report a name for it.');
614
- }
615
- return `ALTER TABLE ${table} DROP CONSTRAINT ${this.escapeId(constraintName)};`;
589
+ return this.tableDdl.dropPrimaryKey(tableName, constraintName);
616
590
  }
617
591
  /** A stored generated column, which an engine that rebuilds tables takes only in a `CREATE TABLE`. */
618
592
  assertColumnAddable(tableName, column) {
@@ -1,5 +1,5 @@
1
+ import { currentTimestamp } from '../../util/raw.js';
1
2
  import { withSqlQuerierForMigrations } from '../acquireQuerierForMigrations.js';
2
- import { expr } from '../builder/expressions.js';
3
3
  import { TableBuilder } from '../builder/tableBuilder.js';
4
4
  import { SqlSchemaGenerator } from '../schemaGenerator.js';
5
5
  /** Where executed migrations are recorded when the config does not name a table. */
@@ -32,7 +32,7 @@ export class DatabaseMigrationStorage {
32
32
  async createTableIfNotExists(querier) {
33
33
  const table = new TableBuilder(this.tableName);
34
34
  table.string('name', { length: 255, primaryKey: true });
35
- table.timestamptz('executed_at', { defaultValue: expr.now() });
35
+ table.timestamptz('executed_at', { defaultValue: currentTimestamp });
36
36
  const generator = new SqlSchemaGenerator(querier.dialect);
37
37
  for (const sql of generator.generateCreateTableFromDefinition(table.build(), { ifNotExists: true })) {
38
38
  await querier.run(sql);
@@ -19,6 +19,6 @@ export declare function dropTrigger<E>(dialect: AbstractSqlDialect, meta: Entity
19
19
  /**
20
20
  * The triggers a stamp needs: one per event it names, each assigning the field's expression to its
21
21
  * column. Generated rather than authored, so unlike an authored body it renders on every engine from
22
- * one declaration - and not at all on the MySQL family, whose columns stamp themselves.
22
+ * one declaration.
23
23
  */
24
24
  export declare function stampTriggers<E extends object>(dialect: AbstractSqlDialect, meta: EntityMeta<E>): EntityTriggerMeta<E>[];
@@ -50,6 +50,9 @@ function triggerStatements(dialect, meta, trigger, name) {
50
50
  const features = dialect.features.triggers;
51
51
  const [timing, operation] = EVENT_PARTS[trigger.on];
52
52
  const before = timing === 'BEFORE';
53
+ if (trigger.deferred && !features.deferrable) {
54
+ throw new UqlUsageError(`${dialect.dialectName} cannot defer a trigger to commit, which ${meta.entity.name} asks for; only Postgres can`);
55
+ }
53
56
  const { fires } = features;
54
57
  const perStatement = fires === 'eachStatement';
55
58
  const names = rowNames(dialect);
@@ -76,9 +79,13 @@ function triggerStatements(dialect, meta, trigger, name) {
76
79
  const each = perStatement ? '' : '\nFOR EACH ROW';
77
80
  const whenClause = filter && byWhen ? `\nWHEN (${filter})` : '';
78
81
  const event = `${timing} ${operation}${of}`;
82
+ // Deferred, it is a constraint trigger, which is what Postgres lets wait for the commit.
83
+ const [kind, deferral] = trigger.deferred
84
+ ? ['CONSTRAINT TRIGGER', '\nDEFERRABLE INITIALLY DEFERRED']
85
+ : ['TRIGGER', ''];
79
86
  const header = features.layout === 'tableFirst'
80
- ? `CREATE TRIGGER ${id}\nON ${table} ${event}${each}${whenClause}\nAS`
81
- : `CREATE TRIGGER ${id}\n${event} ON ${table}${each}${whenClause}`;
87
+ ? `CREATE ${kind} ${id}\nON ${table} ${event}${each}${whenClause}\nAS`
88
+ : `CREATE ${kind} ${id}\n${event} ON ${table}${deferral}${each}${whenClause}`;
82
89
  if (features.body !== 'function') {
83
90
  return [`${header}\nBEGIN\n${opened}\nEND`];
84
91
  }
@@ -156,7 +163,7 @@ function condition(dialect, meta, where, rows, names, operand) {
156
163
  /**
157
164
  * The triggers a stamp needs: one per event it names, each assigning the field's expression to its
158
165
  * column. Generated rather than authored, so unlike an authored body it renders on every engine from
159
- * one declaration - and not at all on the MySQL family, whose columns stamp themselves.
166
+ * one declaration.
160
167
  */
161
168
  export function stampTriggers(dialect, meta) {
162
169
  const features = dialect.features.triggers;
@@ -184,10 +191,10 @@ const STAMP_EVENTS = {
184
191
  after: { insert: 'afterInsert', update: 'afterUpdate' },
185
192
  };
186
193
  /**
187
- * The one statement a stamp runs, in whichever of the two shapes the engine leaves open: an assignment
188
- * to the incoming row, or where it may not be written, the row restated after the write, as any write in
189
- * a trigger's body is, keyed on its whole key and only where the stamp still differs: that `UPDATE` fires
190
- * the trigger again, and with recursive triggers on it then finds nothing left to change.
194
+ * The statement a stamp runs: an assignment to the incoming row where the engine allows one, else an
195
+ * `UPDATE` of the written row after the write, by its whole key and only where the stamp still differs.
196
+ * That `UPDATE` fires the table's triggers again; where a running trigger can fire again, `reentryGuard`
197
+ * makes the nested run return.
191
198
  */
192
199
  function stampBody(dialect, meta, key, value, newRow) {
193
200
  const { entity } = meta;
@@ -201,7 +208,9 @@ function stampBody(dialect, meta, key, value, newRow) {
201
208
  const stamped = dialect.compileDdl(value, entity);
202
209
  const differs = raw(({ ctx, escapedPrefix }) => ctx.append(dialect.neExpr(`${escapedPrefix}${dialect.escapedColumnName(meta, key)}`, stamped)));
203
210
  const where = { $and: [...keyed, differs] };
204
- return written({ kind: 'update', entity, set: { [key]: value }, where });
211
+ const restated = written({ kind: 'update', entity, set: { [key]: value }, where });
212
+ const { reentryGuard } = dialect.features.triggers;
213
+ return reentryGuard ? raw `${raw(() => reentryGuard)}\n${restated}` : restated;
205
214
  }
206
215
  /** A dollar quote the body does not contain, so no `$$` in it - a literal, a comment - ends the function early. */
207
216
  function dollarQuote(body) {
@@ -35,7 +35,6 @@ export declare class MongoDialect extends AbstractDialect {
35
35
  #private;
36
36
  readonly features: DialectFeatures;
37
37
  readonly dialectName = "mongodb";
38
- readonly insertIdSource = "returning";
39
38
  /**
40
39
  * MongoDB stores the primary key as `_id`; everything else resolves as usual. Projections, sorts,
41
40
  * `$group` refs and `$where` keys all map through here, so no read path can address a property name
@@ -80,8 +79,6 @@ export declare class MongoDialect extends AbstractDialect {
80
79
  * Each end is one field matched against one `_id`, so both sides must be sole-keyed.
81
80
  */
82
81
  private junctionOf;
83
- /** Whether a query subtracts `key` from the projection, via `$exclude` or a negative `$select`. */
84
- private subtractsKey;
85
82
  /** `raw()` renders SQL, so it has no MongoDB equivalent - say so instead of emitting `{}`. */
86
83
  private assertNoRaw;
87
84
  /**
@@ -222,6 +219,10 @@ export declare class MongoDialect extends AbstractDialect {
222
219
  * it, and anything else as given. Only 24-hex, not any 12-byte string. Arrays convert element-wise.
223
220
  */
224
221
  toWireId(value: unknown): unknown;
222
+ /** Whether `key` holds ids the driver stores as `ObjectId`s: the entity's own `_id`, or a reference to one. */
223
+ private holdsKeys;
224
+ /** Converts every operand `ops` compares a key against with {@link toWireId}, including inside a `$not`. */
225
+ private toWireOperands;
225
226
  /** The seam out of the driver: an `ObjectId` becomes its hex string, the type the code declares. */
226
227
  fromWireId(value: unknown): unknown;
227
228
  getPersistable<E extends Document>(meta: EntityMeta<E>, payload: EntityData<E>, callbackKey: CallbackKey): Partial<E>;
@@ -6,7 +6,7 @@ import { aggregateColumnField, groupPathField, resolveGroupJoins, relationSortTe
6
6
  import { assertSoleId, fieldOf, getMeta, relationOf, soleIdOf } from '../entity/index.js';
7
7
  import { COUNT_RESULT_KEY } from '../type/query.js';
8
8
  import { QueryRaw } from '../type/queryRaw.js';
9
- import { aggregateOf, isSelectList, assertAggregateColumns, assertNonNegativeInteger, columnFamily, countedRelations, entityName, fieldUpdateOf, fillOnFields, filterFieldKeys, findVectorIndex, findVectorSort, getKeys, getRelationRequestSummary, hasKeys, isFieldUpdateOp, isJsonObject, isJsonUpdateOp, isOperatorMap, isOperatorObject, isRecord, isVectorSearch, normalizeScalarFieldSelection, parentJoins, parseGroupMap, parseRelationAtKey, parseRelationSize, rankedTextSearch, someKey, targetKeyColumns, textSortOf, vectorDistanceOf, } from '../util/index.js';
9
+ import { aggregateOf, isSelectList, assertAggregateColumns, assertNonNegativeInteger, columnFamily, countedRelations, entityName, fieldUpdateOf, fillOnFields, filterFieldKeys, findVectorIndex, findVectorSort, getKeys, getRelationRequestSummary, hasKeys, isFieldUpdateOp, isJsonObject, isJsonUpdateOp, isOperatorMap, isOperatorObject, isRecord, isVectorSearch, normalizeScalarFieldSelection, parentJoins, parseGroupMap, parseRelationAtKey, parseRelationSize, parseSortDirection, rankedTextSearch, someKey, targetKeyColumns, textSortOf, vectorDistanceOf, } from '../util/index.js';
10
10
  import { UqlUsageError } from '../util/uqlError.js';
11
11
  import { decodeBigIntsExcept } from '../util/wideNumber.js';
12
12
  import { textLanguage } from './textLanguage.js';
@@ -30,6 +30,7 @@ export const mongoDialectFeatures = {
30
30
  serverSideCursors: false,
31
31
  correlatedWrites: false,
32
32
  rowLocks: false, // its concurrency control is the transaction plus atomic document updates
33
+ nullsSortLowest: true,
33
34
  };
34
35
  /** What `toWireId` converts: the hex spelling of an `ObjectId`, and nothing looser. */
35
36
  const HEX_24 = /^[0-9a-f]{24}$/i;
@@ -38,6 +39,17 @@ function declaredTypeName(type) {
38
39
  return typeof type === 'function' ? type.name : String(type);
39
40
  }
40
41
  const ID_KEY = '_id';
42
+ /** Native operators that compare a field against values. On a key field, those values are sent as `ObjectId`s. */
43
+ const KEY_OPERATORS = new Set([
44
+ '$eq',
45
+ '$ne',
46
+ '$lt',
47
+ '$lte',
48
+ '$gt',
49
+ '$gte',
50
+ '$in',
51
+ '$nin',
52
+ ]);
41
53
  /** Atlas rejects a `$vectorSearch` asking for more candidates than this. */
42
54
  const MAX_NUM_CANDIDATES = 10_000;
43
55
  /** Adds `expr` to `filter`'s `$expr`, `AND`ed with any already there. */
@@ -96,8 +108,6 @@ function isNullExpr(ref) {
96
108
  export class MongoDialect extends AbstractDialect {
97
109
  features = mongoDialectFeatures;
98
110
  dialectName = 'mongodb';
99
- // The MongoDB driver reports the exact `_id` of every inserted document (`insertedIds`).
100
- insertIdSource = 'returning';
101
111
  /**
102
112
  * MongoDB stores the primary key as `_id`; everything else resolves as usual. Projections, sorts,
103
113
  * `$group` refs and `$where` keys all map through here, so no read path can address a property name
@@ -175,24 +185,26 @@ export class MongoDialect extends AbstractDialect {
175
185
  }
176
186
  this.appendAggregateField(meta, key, lookups);
177
187
  }
178
- const isReference = !!meta.fields[key]?.references;
188
+ const keyed = this.holdsKeys(meta, key);
179
189
  key = this.pathOf(meta, key);
180
- if ((key === ID_KEY || isReference) && !isOperatorObject(val)) {
181
- val = this.toWireId(val);
182
- }
183
190
  if (!isOperatorObject(val)) {
184
- filter[key] = Array.isArray(val) ? { $in: val } : val;
191
+ const wire = keyed ? this.toWireId(val) : val;
192
+ filter[key] = Array.isArray(wire) ? { $in: wire } : wire;
185
193
  continue;
186
194
  }
195
+ const operators = (ops) => {
196
+ const native = this.transformOperators(ops);
197
+ return keyed ? this.toWireOperands(native) : native;
198
+ };
187
199
  // MongoDB's `$size` takes only a number, so bounds become an `$expr` beside the other operators.
188
200
  const { $size: size, ...ops } = val;
189
201
  if (!isRecord(size)) {
190
- filter[key] = this.transformOperators(val);
202
+ filter[key] = operators(val);
191
203
  }
192
204
  else {
193
205
  andExpr(filter, arraySize(key, size));
194
206
  if (hasKeys(ops)) {
195
- filter[key] = this.transformOperators(ops);
207
+ filter[key] = operators(ops);
196
208
  }
197
209
  }
198
210
  }
@@ -298,11 +310,6 @@ export class MongoDialect extends AbstractDialect {
298
310
  target: this.columnOf(throughMeta, targetColumn),
299
311
  };
300
312
  }
301
- /** Whether a query subtracts `key` from the projection, via `$exclude` or a negative `$select`. */
302
- subtractsKey(key, select, exclude) {
303
- const at = (map) => map?.[key];
304
- return at(exclude) === true || at(select) === false;
305
- }
306
313
  /** `raw()` renders SQL, so it has no MongoDB equivalent - say so instead of emitting `{}`. */
307
314
  assertNoRaw(value) {
308
315
  if (value instanceof QueryRaw) {
@@ -419,10 +426,11 @@ export class MongoDialect extends AbstractDialect {
419
426
  if (isSelectList(select)) {
420
427
  throw new UqlUsageError('raw $select is not supported on MongoDB');
421
428
  }
429
+ const fields = normalizeScalarFieldSelection(meta, select, exclude);
422
430
  // Projected by column, not by field key; `normalizeId` maps them back on the way out.
423
- const projection = normalizeScalarFieldSelection(meta, select, exclude).reduce((acc, key) => {
424
- // A computed field writing SQL leaves the document nothing to project: refused asked for by
425
- // name, skipped swept in with the rest. A relation aggregate is on it by now, like any column.
431
+ const projection = fields.reduce((acc, key) => {
432
+ // A computed field that writes SQL has nothing in the document to project: refused when `$select`
433
+ // names it, skipped otherwise. A relation aggregate is already on the document, like any column.
426
434
  const field = meta.fields[key];
427
435
  if (field?.computed && !aggregateOf(field)) {
428
436
  if (select && key in select) {
@@ -433,10 +441,10 @@ export class MongoDialect extends AbstractDialect {
433
441
  acc[this.columnOf(meta, key)] = 1;
434
442
  return acc;
435
443
  }, {});
436
- // MongoDB returns `_id` unless it is explicitly excluded, so subtracting the primary key needs
437
- // `_id: 0` - the one inclusion/exclusion mix MongoDB allows - or `$exclude: { id: true }` would
438
- // have no effect at all.
439
- if (this.subtractsKey(soleIdOf(meta, 'MongoDB'), select, exclude)) {
444
+ // MongoDB returns `_id` unless it is explicitly excluded, so a projection without the key sets `_id: 0`,
445
+ // the one inclusion/exclusion mix MongoDB allows. This returns the same fields a SQL engine would, and is
446
+ // what makes `$exclude: { id: true }` work at all.
447
+ if (!fields.includes(soleIdOf(meta, 'MongoDB'))) {
440
448
  projection[ID_KEY] = 0;
441
449
  }
442
450
  return projection;
@@ -491,19 +499,18 @@ export class MongoDialect extends AbstractDialect {
491
499
  }
492
500
  if (!relation) {
493
501
  // The queried entity's first vector search is lifted out into `$vectorSearch` before this walk,
494
- // so one reaching it is a second. `sortDirection` would read the operator object as "ascending"
495
- // and order by the raw vector column instead, a silent answer where the caller asked for a rank.
502
+ // so one found here is a second one. It is refused as such, not as an unknown direction.
496
503
  if (isVectorSearch(value)) {
497
504
  throw new UqlUsageError(`cannot $sort by a second vector '${key}' on MongoDB: $vectorSearch ranks by one`);
498
505
  }
499
506
  const docPath = path + this.pathOf(meta, key);
500
- const nulls = sortNulls(value);
507
+ const { desc, nulls } = parseSortDirection(value);
501
508
  if (nulls) {
502
509
  placed.push(docPath);
503
510
  // The flag holds 1 for a null, so ordering by it descending brings the null block to the front.
504
511
  out[nullsSortField(docPath)] = nulls === 'first' ? -1 : 1;
505
512
  }
506
- out[docPath] = sortDirection(value);
513
+ out[docPath] = desc ? -1 : 1;
507
514
  continue;
508
515
  }
509
516
  // A `$lookup` is what puts the relation's fields on the document, and only `$populate` asks for
@@ -965,6 +972,21 @@ export class MongoDialect extends AbstractDialect {
965
972
  }
966
973
  return typeof value === 'string' && HEX_24.test(value) ? new ObjectId(value) : value;
967
974
  }
975
+ /** Whether `key` holds ids the driver stores as `ObjectId`s: the entity's own `_id`, or a reference to one. */
976
+ holdsKeys(meta, key) {
977
+ return this.pathOf(meta, key) === ID_KEY || !!meta.fields[key]?.references;
978
+ }
979
+ /** Converts every operand `ops` compares a key against with {@link toWireId}, including inside a `$not`. */
980
+ toWireOperands(ops) {
981
+ return Object.fromEntries(Object.entries(ops).map(([op, operand]) => [
982
+ op,
983
+ op === '$not' && isRecord(operand)
984
+ ? this.toWireOperands(operand)
985
+ : KEY_OPERATORS.has(op)
986
+ ? this.toWireId(operand)
987
+ : operand,
988
+ ]));
989
+ }
968
990
  /** The seam out of the driver: an `ObjectId` becomes its hex string, the type the code declares. */
969
991
  fromWireId(value) {
970
992
  return value instanceof ObjectId ? value.toHexString() : value;
@@ -1210,9 +1232,8 @@ export class MongoDialect extends AbstractDialect {
1210
1232
  }
1211
1233
  const val = where[key];
1212
1234
  named.push(key);
1213
- const path = this.pathOf(meta, key);
1214
- const wire = (value) => path === ID_KEY || meta.fields[key]?.references ? this.toWireId(value) : value;
1215
- return this.fieldExpression(`$${path}`, val, wire);
1235
+ const wire = this.holdsKeys(meta, key) ? (value) => this.toWireId(value) : (value) => value;
1236
+ return this.fieldExpression(`$${this.pathOf(meta, key)}`, val, wire);
1216
1237
  });
1217
1238
  return terms.length === 1 ? terms[0] : { $and: terms };
1218
1239
  }
@@ -1330,16 +1351,9 @@ export class MongoDialect extends AbstractDialect {
1330
1351
  return { $vectorSearch: stage };
1331
1352
  }
1332
1353
  }
1333
- /** `-1` for every descending spelling, `1` for everything else - MongoDB knows no other value. */
1354
+ /** A sort direction in MongoDB's form: `-1` for descending, else `1`. MongoDB accepts no other values. */
1334
1355
  function sortDirection(value) {
1335
- return value === -1 || (typeof value === 'string' && value.startsWith('desc')) ? -1 : 1;
1336
- }
1337
- /** Where a direction asks nulls to land, where it asks at all. */
1338
- function sortNulls(value) {
1339
- if (typeof value !== 'string') {
1340
- return undefined;
1341
- }
1342
- return value.endsWith('NullsFirst') ? 'first' : value.endsWith('NullsLast') ? 'last' : undefined;
1356
+ return parseSortDirection(value).desc ? -1 : 1;
1343
1357
  }
1344
1358
  /**
1345
1359
  * A `computed` field writing SQL is refused wherever a query names it, since no document engine
@@ -125,7 +125,7 @@ function buildTable({ name, indexes = [] }, indexFacets) {
125
125
  });
126
126
  }
127
127
  }
128
- table.indexes.push({ name: index.name, table, entries: index.entries, unique: index.unique, type: index.type });
128
+ table.indexes.push({ ...index, table });
129
129
  }
130
130
  return table;
131
131
  }
@@ -1,10 +1,10 @@
1
1
  import type { AnyMigrationOperation } from '../migrate/builder/types.js';
2
- import type { ForeignKeyAction, TableNode } from '../schema/types.js';
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
5
  export declare class MongoSchemaGenerator extends MongoDialect implements SchemaGenerator {
6
- protected readonly defaultForeignKeyAction?: ForeignKeyAction | undefined;
7
- constructor(namingStrategy?: NamingStrategy, defaultForeignKeyAction?: ForeignKeyAction | undefined);
6
+ /** Takes no default foreign key action, since a document store has no foreign keys. */
7
+ constructor(namingStrategy?: NamingStrategy);
8
8
  /** A collection has no SQL to render a check, a computed column or an index expression into. */
9
9
  compileDdl(): string;
10
10
  /**
@@ -20,7 +20,10 @@ export declare class MongoSchemaGenerator extends MongoDialect implements Schema
20
20
  * it: creating a collection, and working out which of its indexes are missing.
21
21
  */
22
22
  private indexesOf;
23
- /** One declared index, its members resolved to document paths and its `where` to a filter document. */
23
+ /**
24
+ * A declared index, with its members resolved to document paths and its `where` to a filter document.
25
+ * Every other option is spread through, so a newly added one, such as the text `config`, cannot be lost.
26
+ */
24
27
  private indexSchema;
25
28
  /**
26
29
  * The JSON of the document `partialFilterExpression` takes, refused where the predicate reaches past
@@ -24,10 +24,9 @@ const ATLAS_SIMILARITY = {
24
24
  inner: 'dotProduct',
25
25
  };
26
26
  export class MongoSchemaGenerator extends MongoDialect {
27
- defaultForeignKeyAction;
28
- constructor(namingStrategy, defaultForeignKeyAction) {
27
+ /** Takes no default foreign key action, since a document store has no foreign keys. */
28
+ constructor(namingStrategy) {
29
29
  super({ namingStrategy });
30
- this.defaultForeignKeyAction = defaultForeignKeyAction;
31
30
  }
32
31
  /** A collection has no SQL to render a check, a computed column or an index expression into. */
33
32
  compileDdl() {
@@ -58,24 +57,26 @@ export class MongoSchemaGenerator extends MongoDialect {
58
57
  indexesOf(meta, collectionName) {
59
58
  return declaredIndexes(meta).map((index) => this.indexSchema(meta, collectionName, index));
60
59
  }
61
- /** One declared index, its members resolved to document paths and its `where` to a filter document. */
62
- indexSchema(meta, collectionName, index) {
63
- const entries = index.columns
60
+ /**
61
+ * A declared index, with its members resolved to document paths and its `where` to a filter document.
62
+ * Every other option is spread through, so a newly added one, such as the text `config`, cannot be lost.
63
+ */
64
+ indexSchema(meta, collectionName, { columns, where, ...options }) {
65
+ const entries = columns
64
66
  .map((entry) => renderIndexColumn(entry, () => this.compileDdl()))
65
67
  .map((entry) => ({ ...entry, column: this.columnOf(meta, entry.column) }));
66
- const [first] = index.columns;
67
- const vector = index.type === 'vectorSearch' && typeof first?.column === 'string' ? meta.fields[first.column] : undefined;
68
+ const [first] = columns;
69
+ const vector = options.type === 'vectorSearch' && typeof first?.column === 'string' ? meta.fields[first.column] : undefined;
68
70
  const name = vector
69
- ? this.vectorSearchIndexName(index.name, entries[0].column)
70
- : declaredIndexName(index.name, collectionName, entries);
71
+ ? this.vectorSearchIndexName(options.name, entries[0].column)
72
+ : declaredIndexName(options.name, collectionName, entries);
71
73
  return {
74
+ ...options,
72
75
  name,
73
76
  entries,
74
- unique: index.unique ?? false,
75
- type: index.type,
76
- include: index.include,
77
- where: index.where && this.compileIndexPredicate(index.where, meta.entity, name),
78
- distance: index.distance ?? vector?.distance,
77
+ unique: options.unique ?? false,
78
+ where: where && this.compileIndexPredicate(where, meta.entity, name),
79
+ distance: options.distance ?? vector?.distance,
79
80
  dimensions: vector?.dimensions,
80
81
  };
81
82
  }
@@ -218,12 +219,8 @@ export class MongoSchemaGenerator extends MongoDialect {
218
219
  if (!currentTable) {
219
220
  return { tableName: collectionName, type: 'create' };
220
221
  }
221
- const { toAdd, toDrop, toAlter } = indexChanges(collectionName, this.indexesOf(meta, collectionName), currentTable.indexes, currentTable.indexFacets);
222
- const indexes = [
223
- ...toAdd.map((to) => ({ to })),
224
- ...toDrop.map((from) => ({ from: indexNodeToSchema(from) })),
225
- ...toAlter.map(({ from, to }) => ({ from: indexNodeToSchema(from), to })),
226
- ];
222
+ const { changes } = indexChanges(collectionName, this.indexesOf(meta, collectionName), currentTable.indexes, currentTable.indexFacets);
223
+ const indexes = changes.map(({ from, to }) => ({ from: from && indexNodeToSchema(from), to }));
227
224
  return indexes.length ? { tableName: collectionName, type: 'alter', indexes } : undefined;
228
225
  }
229
226
  }