uql-orm 0.97.0 → 0.98.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 +4 -21
  66. package/dist/migrate/migrator.js +47 -71
  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
@@ -16,6 +16,7 @@ export class DatabaseMigrationStorage {
16
16
  this.pool = pool;
17
17
  this.tableName = options.tableName ?? DEFAULT_MIGRATIONS_TABLE;
18
18
  }
19
+ /** Creates the table on first use, once. */
19
20
  async ensureStorage() {
20
21
  if (this.storageInitialized) {
21
22
  return;
@@ -43,8 +44,8 @@ export class DatabaseMigrationStorage {
43
44
  return withSqlQuerierForMigrations(this.pool, 'DatabaseMigrationStorage', async (querier) => {
44
45
  const { dialect } = querier;
45
46
  const sql = /*sql*/ `SELECT ${dialect.escapeId('name')} FROM ${dialect.escapeId(this.tableName)} ORDER BY ${dialect.escapeId('name')} ASC`;
46
- const results = await querier.all(sql);
47
- return results.map((r) => r.name);
47
+ const rows = await querier.all(sql);
48
+ return rows.map((row) => row.name);
48
49
  });
49
50
  }
50
51
  /**
@@ -4,10 +4,9 @@ import type { MigrationStorage, Querier } from '../../type/index.js';
4
4
  * Useful for development or environments without a database.
5
5
  */
6
6
  export declare class JsonMigrationStorage implements MigrationStorage {
7
- private executedMigrations;
8
7
  private readonly filePath;
9
8
  constructor(filePath?: string);
10
- ensureStorage(): Promise<void>;
9
+ /** The names the file records, a missing file read as none run yet; any other read failure is the caller's. */
11
10
  executed(): Promise<string[]>;
12
11
  logWithQuerier(_querier: Querier, migrationName: string): Promise<void>;
13
12
  unlogWithQuerier(_querier: Querier, migrationName: string): Promise<void>;
@@ -4,39 +4,30 @@ import * as fs from 'node:fs/promises';
4
4
  * Useful for development or environments without a database.
5
5
  */
6
6
  export class JsonMigrationStorage {
7
- executedMigrations = [];
8
7
  filePath;
9
8
  constructor(filePath = './migrations/.uql-migrations.json') {
10
9
  this.filePath = filePath;
11
10
  }
12
- async ensureStorage() {
13
- const content = await fs.readFile(this.filePath, 'utf-8').catch(async (error) => {
11
+ /** The names the file records, a missing file read as none run yet; any other read failure is the caller's. */
12
+ async executed() {
13
+ const content = await fs.readFile(this.filePath, 'utf-8').catch((error) => {
14
14
  if (error.code === 'ENOENT') {
15
- const initial = '[]';
16
- await fs.writeFile(this.filePath, initial, 'utf-8');
17
- return initial;
15
+ return '[]';
18
16
  }
19
17
  throw error;
20
18
  });
21
- this.executedMigrations = JSON.parse(content);
22
- }
23
- async executed() {
24
- await this.ensureStorage();
25
- return this.executedMigrations;
19
+ return JSON.parse(content);
26
20
  }
27
21
  async logWithQuerier(_querier, migrationName) {
28
- await this.ensureStorage();
29
- if (!this.executedMigrations.includes(migrationName)) {
30
- this.executedMigrations.push(migrationName);
31
- await this.save();
22
+ const executed = await this.executed();
23
+ if (!executed.includes(migrationName)) {
24
+ await this.save([...executed, migrationName]);
32
25
  }
33
26
  }
34
27
  async unlogWithQuerier(_querier, migrationName) {
35
- await this.ensureStorage();
36
- this.executedMigrations = this.executedMigrations.filter((m) => m !== migrationName);
37
- await this.save();
28
+ await this.save((await this.executed()).filter((name) => name !== migrationName));
38
29
  }
39
- async save() {
40
- await fs.writeFile(this.filePath, JSON.stringify(this.executedMigrations, null, 2), 'utf-8');
30
+ save(names) {
31
+ return fs.writeFile(this.filePath, JSON.stringify(names, null, 2), 'utf-8');
41
32
  }
42
33
  }
@@ -8,10 +8,10 @@ import type { EntityMeta, EntityTriggerMeta } from '../type/index.js';
8
8
  */
9
9
  export declare function renderTrigger<E>(dialect: AbstractSqlDialect, meta: EntityMeta<E>, trigger: EntityTriggerMeta<E>, position: number): TriggerSchema;
10
10
  /**
11
- * What removes one trigger: the trigger, named with its table only where the engine scopes the name to
12
- * one, then {@link dropTriggerBody}.
11
+ * What removes one trigger of `table`, a name qualified where its schema is: the trigger, in that schema and
12
+ * named with its table only where the engine scopes the name to one, then {@link dropTriggerBody}.
13
13
  */
14
- export declare function dropTrigger(dialect: AbstractSqlDialect, table: string, schema: string | undefined, name: string): string[];
14
+ export declare function dropTrigger(dialect: AbstractSqlDialect, table: string, name: string): string[];
15
15
  /** What dropping a trigger or its table leaves behind: on the Postgres family, the function holding its body. */
16
16
  export declare function dropTriggerBody(dialect: AbstractSqlDialect, schema: string | undefined, name: string): string[];
17
17
  /**
@@ -2,7 +2,7 @@ import { TriggerWriteRaw } from '../type/index.js';
2
2
  import { stampEvents } from '../util/field.util.js';
3
3
  import { definedEntries } from '../util/object.util.js';
4
4
  import { raw, refs, rowRefs } from '../util/raw.js';
5
- import { ownedName } from '../util/sql.util.js';
5
+ import { ownedName, splitQualifiedName } from '../util/sql.util.js';
6
6
  import { written } from '../util/triggerWrite.js';
7
7
  import { UqlUsageError } from '../util/uqlError.js';
8
8
  /**
@@ -18,10 +18,11 @@ export function renderTrigger(dialect, meta, trigger, position) {
18
18
  return { name, statements: triggerStatements(dialect, meta, trigger, name) };
19
19
  }
20
20
  /**
21
- * What removes one trigger: the trigger, named with its table only where the engine scopes the name to
22
- * one, then {@link dropTriggerBody}.
21
+ * What removes one trigger of `table`, a name qualified where its schema is: the trigger, in that schema and
22
+ * named with its table only where the engine scopes the name to one, then {@link dropTriggerBody}.
23
23
  */
24
- export function dropTrigger(dialect, table, schema, name) {
24
+ export function dropTrigger(dialect, table, name) {
25
+ const { schema } = splitQualifiedName(table);
25
26
  const on = dialect.features.triggers.scope === 'table' ? ` ON ${dialect.escapeId(table)}` : '';
26
27
  return [`DROP TRIGGER IF EXISTS ${triggerId(dialect, schema, name)}${on}`, ...dropTriggerBody(dialect, schema, name)];
27
28
  }
@@ -5,4 +5,3 @@ export * from './mongoIntrospector.js';
5
5
  export * from './mongoMigrationStorage.js';
6
6
  export { isMongoQuerier, type MongoQuerier } from './mongoQuerier.js';
7
7
  export * from './mongoSchemaGenerator.js';
8
- export * from './textLanguage.js';
@@ -5,4 +5,3 @@ export * from './mongoIntrospector.js';
5
5
  export * from './mongoMigrationStorage.js';
6
6
  export { isMongoQuerier } from './mongoQuerier.js';
7
7
  export * from './mongoSchemaGenerator.js';
8
- export * from './textLanguage.js';
@@ -19,7 +19,6 @@ export const mongoDialectFeatures = {
19
19
  schemas: false, // the connection picks the database, and a collection name takes no dot
20
20
  dropTableCascade: false,
21
21
  rebuildsTables: false,
22
- commentSyntax: 'none',
23
22
  vectorIndexRequiresNotNull: false,
24
23
  vectorSupportsLength: false,
25
24
  vectorBytes: false,
@@ -1,4 +1,3 @@
1
- import type { IndexFacet } from '../schema/indexDifferences.js';
2
1
  import { SchemaAST } from '../schema/schemaAST.js';
3
2
  import type { QuerierPool, SchemaIntrospector, TableSchema } from '../type/index.js';
4
3
  /**
@@ -7,8 +6,6 @@ import type { QuerierPool, SchemaIntrospector, TableSchema } from '../type/index
7
6
  */
8
7
  export declare class MongoSchemaIntrospector implements SchemaIntrospector {
9
8
  private readonly pool;
10
- /** `listIndexes` reports keys, uniqueness and text weights; a `partialFilterExpression` is no SQL predicate. */
11
- readonly indexFacets: ReadonlySet<IndexFacet>;
12
9
  constructor(pool: QuerierPool);
13
10
  introspect(tables?: readonly string[]): Promise<SchemaAST>;
14
11
  getTableSchema(tableName: string): Promise<TableSchema | undefined>;
@@ -1,6 +1,5 @@
1
1
  import { createTableNode, SchemaAST } from '../schema/schemaAST.js';
2
- import { UqlUsageError } from '../util/uqlError.js';
3
- import { isMongoQuerier } from './mongoQuerier.js';
2
+ import { withMongoQuerierForMigrations } from './mongoQuerier.js';
4
3
  import { textConfigOf } from './textLanguage.js';
5
4
  /** What a server without Atlas Search answers a search index command with. */
6
5
  const SEARCH_NOT_ENABLED = 31082;
@@ -10,8 +9,6 @@ const SEARCH_NOT_ENABLED = 31082;
10
9
  */
11
10
  export class MongoSchemaIntrospector {
12
11
  pool;
13
- /** `listIndexes` reports keys, uniqueness and text weights; a `partialFilterExpression` is no SQL predicate. */
14
- indexFacets = new Set(['textIndex']);
15
12
  constructor(pool) {
16
13
  this.pool = pool;
17
14
  }
@@ -21,7 +18,7 @@ export class MongoSchemaIntrospector {
21
18
  for (const name of tableNames) {
22
19
  const schema = await this.getTableSchema(name);
23
20
  if (schema) {
24
- ast.addTable(buildTable(schema, this.indexFacets));
21
+ ast.addTable(buildTable(schema));
25
22
  }
26
23
  }
27
24
  return ast;
@@ -74,12 +71,7 @@ export class MongoSchemaIntrospector {
74
71
  return this.withDb((db) => hasCollection(db, tableName));
75
72
  }
76
73
  withDb(task) {
77
- return this.pool.withQuerier((querier) => {
78
- if (!isMongoQuerier(querier)) {
79
- throw new UqlUsageError('MongoSchemaIntrospector requires a MongoDB querier');
80
- }
81
- return task(querier.db);
82
- });
74
+ return withMongoQuerierForMigrations(this.pool, 'MongoSchemaIntrospector', (querier) => task(querier.db));
83
75
  }
84
76
  }
85
77
  /** A text index field as an entity declares it: its weight stated only where it is not the default 1. */
@@ -103,8 +95,10 @@ async function hasCollection(db, name) {
103
95
  return collections.length > 0;
104
96
  }
105
97
  /** Mongo has no columns to read, so a table's are the fields its indexes name, one node per field. */
106
- function buildTable({ name, indexes = [] }, indexFacets) {
107
- const table = createTableNode(name, undefined, indexFacets);
98
+ /** `listIndexes` reports keys, uniqueness and text weights; a `partialFilterExpression` is no SQL predicate. */
99
+ const INDEX_FACETS = new Set(['textIndex']);
100
+ function buildTable({ name, indexes = [] }) {
101
+ const table = createTableNode(name, undefined, INDEX_FACETS);
108
102
  for (const index of indexes) {
109
103
  for (const { column } of index.entries) {
110
104
  if (!table.columns.has(column)) {
@@ -116,7 +110,6 @@ function buildTable({ name, indexes = [] }, indexFacets) {
116
110
  isAutoIncrement: false,
117
111
  isUnique: false,
118
112
  table,
119
- referencedBy: [],
120
113
  });
121
114
  }
122
115
  }
@@ -1,47 +1,34 @@
1
1
  import type { AnyMigrationOperation } from '../migrate/builder/types.js';
2
2
  import type { TableNode } from '../schema/types.js';
3
- import { type CreateSchemaOptions, type EntityWhereMeta, type IndexSchema, type NamingStrategy, type SchemaDiff, type SchemaGenerator, type Type } from '../type/index.js';
3
+ import { type CreateSchemaOptions, 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
6
  /** Takes no default foreign key action, since a document store has no foreign keys. */
7
7
  constructor(namingStrategy?: NamingStrategy);
8
- /** A collection has no SQL to render a check, a computed column or an index expression into. */
9
- compileDdl(): string;
10
8
  /**
11
9
  * A document store has no cross-collection constraint, so unlike the SQL generator there is nothing to
12
- * defer and no order to respect: this is each collection and nothing more. `foreignKeys` is accepted
13
- * and ignored for the same reason.
10
+ * defer and no order to respect: this is each collection and nothing more.
14
11
  */
15
12
  generateCreateSchema(entities: readonly Type<object>[], options?: CreateSchemaOptions): string[];
16
13
  generateDropSchema(entities: readonly Type<object>[]): string[];
17
- private selected;
14
+ /** A collection, and one `createIndex` command for each of its indexes, as SQL's `[CREATE TABLE, ...CREATE INDEX]`. */
15
+ private createCollection;
18
16
  /**
19
- * The indexes an entity declares, as the collection would hold them. One owner because two paths need
20
- * it: creating a collection, and working out which of its indexes are missing.
17
+ * The indexes an entity declares, as the collection would hold them: members resolved to document paths, a
18
+ * `where` to a filter document, and every other option spread through, so a new one cannot be lost.
21
19
  */
22
20
  private indexesOf;
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
- */
27
- private indexSchema;
28
21
  /**
29
22
  * The JSON of the document `partialFilterExpression` takes, refused where the predicate reaches past
30
23
  * what that holds or what a migration carries as JSON.
31
24
  */
32
- compileIndexPredicate(where: EntityWhereMeta<object>, entity: Type<object>, indexName: string): string;
33
- generateCreateTable<E extends object>(entity: Type<E>, _options?: {
34
- ifNotExists?: boolean;
35
- }): string[];
36
- generateDropTable(tableName: string): string;
25
+ private indexFilter;
37
26
  /** A collection's indexes: each dropped, then each created, an alter as both. */
38
27
  generateAlterTable(diff: SchemaDiff): string[];
39
- private dropIndexCommand;
40
28
  /** An index as MongoDB's key spec (`-1` descending, `'text'` full-text), refusing the SQL-only options. */
41
29
  generateCreateIndex(tableName: string, index: IndexSchema): string;
42
30
  /** An Atlas vector search index: its vector field first, then each field a `$vectorSearch` pre-filters on. */
43
31
  private generateCreateSearchIndex;
44
- generateDropIndex(tableName: string, indexName: string): string;
45
32
  /** A collection and its indexes, which is all a document store has: a column, a constraint or SQL throws. */
46
33
  generateOperation(operation: AnyMigrationOperation): string[];
47
34
  diffSchema(entity: Type<object>, currentTable: TableNode | undefined): SchemaDiff | undefined;
@@ -28,63 +28,60 @@ export class MongoSchemaGenerator extends MongoDialect {
28
28
  constructor(namingStrategy) {
29
29
  super({ namingStrategy });
30
30
  }
31
- /** A collection has no SQL to render a check, a computed column or an index expression into. */
32
- compileDdl() {
33
- throw new UqlUsageError('mongodb has no SQL to render a check, a computed column or an index expression into');
34
- }
35
31
  /**
36
32
  * A document store has no cross-collection constraint, so unlike the SQL generator there is nothing to
37
- * defer and no order to respect: this is each collection and nothing more. `foreignKeys` is accepted
38
- * and ignored for the same reason.
33
+ * defer and no order to respect: this is each collection and nothing more.
39
34
  */
40
35
  generateCreateSchema(entities, options) {
41
- return this.selected(entities, options?.only).flatMap((entity) => this.generateCreateTable(entity, options));
36
+ const wanted = options?.only && new Set(options.only);
37
+ return entities
38
+ .map((entity) => getMeta(entity))
39
+ .filter((meta) => !wanted || wanted.has(this.resolveTableName(meta)))
40
+ .flatMap((meta) => {
41
+ const name = this.resolveTableName(meta);
42
+ return this.createCollection(name, this.indexesOf(meta, name));
43
+ });
42
44
  }
43
45
  generateDropSchema(entities) {
44
- return this.selected(entities).map((entity) => this.generateDropTable(this.resolveTableName(getMeta(entity))));
46
+ return entities.map((entity) => serializeMongoCommand({ action: 'dropCollection', name: this.resolveTableName(getMeta(entity)) }));
45
47
  }
46
- selected(entities, only) {
47
- if (!only) {
48
- return entities;
49
- }
50
- const wanted = new Set(only);
51
- return entities.filter((entity) => wanted.has(this.resolveTableName(getMeta(entity))));
48
+ /** A collection, and one `createIndex` command for each of its indexes, as SQL's `[CREATE TABLE, ...CREATE INDEX]`. */
49
+ createCollection(name, indexes) {
50
+ return [
51
+ serializeMongoCommand({ action: 'createCollection', name }),
52
+ ...indexes.map((index) => this.generateCreateIndex(name, index)),
53
+ ];
52
54
  }
53
55
  /**
54
- * The indexes an entity declares, as the collection would hold them. One owner because two paths need
55
- * it: creating a collection, and working out which of its indexes are missing.
56
+ * The indexes an entity declares, as the collection would hold them: members resolved to document paths, a
57
+ * `where` to a filter document, and every other option spread through, so a new one cannot be lost.
56
58
  */
57
59
  indexesOf(meta, collectionName) {
58
- return declaredIndexes(meta).map((index) => this.indexSchema(meta, collectionName, index));
59
- }
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
66
- .map((entry) => renderIndexColumn(entry, () => this.compileDdl()))
67
- .map((entry) => ({ ...entry, column: this.columnOf(meta, entry.column) }));
68
- const [first] = columns;
69
- const vector = options.type === 'vectorSearch' && typeof first?.column === 'string' ? meta.fields[first.column] : undefined;
70
- const name = vector
71
- ? this.vectorSearchIndexName(options.name, entries[0].column)
72
- : declaredIndexName(options.name, collectionName, entries);
73
- return {
74
- ...options,
75
- name,
76
- entries,
77
- unique: options.unique ?? false,
78
- where: where && this.compileIndexPredicate(where, meta.entity, name),
79
- distance: options.distance ?? vector?.distance,
80
- dimensions: vector?.dimensions,
81
- };
60
+ return declaredIndexes(meta).map(({ columns, where, ...options }) => {
61
+ const entries = columns
62
+ .map((entry) => renderIndexColumn(entry, refuseSql))
63
+ .map((entry) => ({ ...entry, column: this.columnOf(meta, entry.column) }));
64
+ const [first] = columns;
65
+ const vector = options.type === 'vectorSearch' && typeof first?.column === 'string' ? meta.fields[first.column] : undefined;
66
+ const name = vector
67
+ ? this.vectorSearchIndexName(options.name, entries[0].column)
68
+ : declaredIndexName(options.name, collectionName, entries);
69
+ return {
70
+ ...options,
71
+ name,
72
+ entries,
73
+ unique: options.unique ?? false,
74
+ where: where && this.indexFilter(where, meta.entity, name),
75
+ distance: options.distance ?? vector?.distance,
76
+ dimensions: vector?.dimensions,
77
+ };
78
+ });
82
79
  }
83
80
  /**
84
81
  * The JSON of the document `partialFilterExpression` takes, refused where the predicate reaches past
85
82
  * what that holds or what a migration carries as JSON.
86
83
  */
87
- compileIndexPredicate(where, entity, indexName) {
84
+ indexFilter(where, entity, indexName) {
88
85
  if (where instanceof QueryRaw) {
89
86
  throw new UqlUsageError(`mongodb does not support partial indexes from a SQL predicate (index "${indexName}")`);
90
87
  }
@@ -96,31 +93,13 @@ export class MongoSchemaGenerator extends MongoDialect {
96
93
  }
97
94
  return JSON.stringify(filter);
98
95
  }
99
- generateCreateTable(entity, _options) {
100
- const meta = getMeta(entity);
101
- const collectionName = this.resolveTableName(meta);
102
- // One `createIndex` command each, mirroring the SQL generator's `[CREATE TABLE, ...CREATE INDEX]`,
103
- // so the key spec is built here and the migrator only executes it.
104
- return [
105
- serializeMongoCommand({ action: 'createCollection', name: collectionName }),
106
- ...this.indexesOf(meta, collectionName).map((index) => this.generateCreateIndex(collectionName, index)),
107
- ];
108
- }
109
- generateDropTable(tableName) {
110
- return serializeMongoCommand({ action: 'dropCollection', name: tableName });
111
- }
112
96
  /** A collection's indexes: each dropped, then each created, an alter as both. */
113
97
  generateAlterTable(diff) {
114
98
  return [
115
- ...sides(diff.indexes, 'from').map((index) => this.dropIndexCommand(diff.tableName, index)),
99
+ ...sides(diff.indexes, 'from').map((index) => dropIndex(diff.tableName, index.name, index.type)),
116
100
  ...sides(diff.indexes, 'to').map((index) => this.generateCreateIndex(diff.tableName, index)),
117
101
  ];
118
102
  }
119
- dropIndexCommand(tableName, index) {
120
- return index.type === 'vectorSearch'
121
- ? serializeMongoCommand({ action: 'dropSearchIndex', collection: tableName, name: index.name })
122
- : this.generateDropIndex(tableName, index.name);
123
- }
124
103
  /** An index as MongoDB's key spec (`-1` descending, `'text'` full-text), refusing the SQL-only options. */
125
104
  generateCreateIndex(tableName, index) {
126
105
  assertIndexType(index, MONGO_INDEX_TYPES, this.dialectName);
@@ -174,31 +153,25 @@ export class MongoSchemaGenerator extends MongoDialect {
174
153
  },
175
154
  });
176
155
  }
177
- generateDropIndex(tableName, indexName) {
178
- return serializeMongoCommand({ action: 'dropIndex', collection: tableName, name: indexName });
179
- }
180
156
  /** A collection and its indexes, which is all a document store has: a column, a constraint or SQL throws. */
181
157
  generateOperation(operation) {
182
- const render = (index) => renderIndexDefinition(index, () => this.compileDdl());
158
+ const render = (index) => renderIndexDefinition(index, refuseSql);
183
159
  switch (operation.type) {
184
160
  case 'createTable': {
185
161
  const { name, columns, indexes } = operation.table;
186
162
  if (columns.length) {
187
163
  throw new UqlUsageError(`mongodb does not support columns in a migration (collection "${name}")`);
188
164
  }
189
- return [
190
- serializeMongoCommand({ action: 'createCollection', name }),
191
- ...indexes.map((index) => this.generateCreateIndex(name, render(index))),
192
- ];
165
+ return this.createCollection(name, indexes.map(render));
193
166
  }
194
167
  case 'dropTable':
195
- return [this.generateDropTable(operation.tableName)];
168
+ return [serializeMongoCommand({ action: 'dropCollection', name: operation.tableName })];
196
169
  case 'renameTable':
197
170
  return [serializeMongoCommand({ action: 'renameCollection', from: operation.oldName, to: operation.newName })];
198
171
  case 'createIndex':
199
172
  return [this.generateCreateIndex(operation.tableName, render(operation.index))];
200
173
  case 'dropIndex':
201
- return [this.generateDropIndex(operation.tableName, operation.indexName)];
174
+ return [dropIndex(operation.tableName, operation.indexName)];
202
175
  default:
203
176
  throw new UqlUsageError(`mongodb does not support ${operation.type} in a migration`);
204
177
  }
@@ -214,6 +187,14 @@ export class MongoSchemaGenerator extends MongoDialect {
214
187
  return indexes.length ? { tableName: collectionName, type: 'alter', indexes } : undefined;
215
188
  }
216
189
  }
190
+ /** A collection has no SQL to render a check, a computed column or an index expression into. */
191
+ function refuseSql() {
192
+ throw new UqlUsageError('mongodb has no SQL to render a check, a computed column or an index expression into');
193
+ }
194
+ /** The command dropping an index, a search index by its own. */
195
+ function dropIndex(collection, name, type) {
196
+ return serializeMongoCommand({ action: type === 'vectorSearch' ? 'dropSearchIndex' : 'dropIndex', collection, name });
197
+ }
217
198
  /** The first value `partialFilterExpression` refuses, `null`, or a migration cannot carry as JSON, such as a `Date`. */
218
199
  function refusedFilterValue(value) {
219
200
  if (value === null) {
@@ -20,7 +20,6 @@ const MSSQL_FEATURES = {
20
20
  dropTableCascade: false,
21
21
  rebuildsTables: false,
22
22
  // Extended properties are out-of-band metadata with their own procedures, not comments.
23
- commentSyntax: 'none',
24
23
  vectorIndexRequiresNotNull: false,
25
24
  vectorSupportsLength: true,
26
25
  vectorBytes: false,
@@ -5,23 +5,20 @@ import { type DialectName } from '../type/index.js';
5
5
  import type { CanonicalType, TypeCategory } from './types.js';
6
6
  /** Whether a category is one of the vector types, narrowing it to the cast pgvector names use. */
7
7
  export declare function isVectorCategory(category: TypeCategory | undefined): category is VectorCast;
8
+ /** The bounds an engine reports beside a type's name, or a field declares beside its SQL type. */
9
+ type TypeBounds = {
10
+ readonly length?: number;
11
+ readonly precision?: number;
12
+ readonly scale?: number;
13
+ readonly dimensions?: number;
14
+ };
8
15
  /**
9
- * Parse a SQL type string into a canonical type.
10
- * Handles complex types like VARCHAR(255), DECIMAL(10,2), etc.
16
+ * The canonical type of a SQL type string, and of the bounds an engine reports beside it
17
+ * (`character_maximum_length` and friends), which win over the name's own. The one place a SQL type is
18
+ * read: everything downstream compares and renders canonical types, so no consumer has to know that
19
+ * `TINYINT(1)` means boolean on MySQL.
11
20
  */
12
- export declare function sqlToCanonical(sqlType: string): CanonicalType;
13
- /**
14
- * The canonical type for a column an engine reported, merging the metadata columns it reports beside
15
- * the type name (`character_maximum_length` and friends) over whatever the name itself carried. This is
16
- * the one place a SQL type string is parsed: everything downstream compares and renders canonical
17
- * types, so no consumer has to know that `TINYINT(1)` means boolean on MySQL.
18
- */
19
- export declare function canonicalColumnType(sqlType: string, reported?: {
20
- length?: number;
21
- precision?: number;
22
- scale?: number;
23
- dimensions?: number;
24
- }): CanonicalType;
21
+ export declare function sqlToCanonical(sqlType: string, reported?: TypeBounds): CanonicalType;
25
22
  /**
26
23
  * Convert a canonical type to a SQL type string for a specific dialect instance.
27
24
  */
@@ -30,10 +27,8 @@ export declare function canonicalToSql(type: CanonicalType, dialect: AbstractDia
30
27
  * Convert a canonical type to a TypeScript type string.
31
28
  */
32
29
  export declare function canonicalToTypeScript(type: CanonicalType): string;
33
- /** The fractional-second digits an engine's timestamp holds when its type states none; `undefined` where it counts none. */
34
- export declare function defaultTimestampPrecision(dialectName: DialectName): number | undefined;
35
- /** Gives a timestamp type that states no precision `digits` fractional seconds; other types pass through. */
36
- export declare function withTimestampPrecision(type: CanonicalType, digits: number | undefined): CanonicalType;
30
+ /** A SQL type as `dialectName` stores it: a timestamp stating no precision holds the engine's default digits. */
31
+ export declare function storedType(dialectName: DialectName, sqlType: string, reported?: TypeBounds): CanonicalType;
37
32
  /**
38
33
  * A type as `dialect` stores it, rendered and read back: several types share one storage type, and only
39
34
  * the engine settles an unstated bound. Migrations and drift both compare through it.
@@ -59,3 +54,4 @@ export declare function canonicalToColumnType(type: CanonicalType): ColumnType;
59
54
  * `type` (`typeFromReference`), so a foreign key matches the key it points at; `columnType` always wins.
60
55
  */
61
56
  export declare function resolveColumnCanonicalType(field: FieldMeta, seen?: Set<EntityGetter>): CanonicalType;
57
+ export {};