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.
- package/dist/browser/http/bus.js +3 -4
- package/dist/browser/http/http.d.ts +1 -2
- package/dist/browser/http/http.js +8 -7
- package/dist/browser/index.d.ts +0 -1
- package/dist/browser/index.js +0 -1
- package/dist/browser/querier/httpQuerier.d.ts +18 -20
- package/dist/browser/querier/httpQuerier.js +20 -56
- package/dist/browser/type/index.d.ts +0 -1
- package/dist/browser/type/index.js +0 -1
- package/dist/browser/uql-browser.min.js +2 -2
- package/dist/browser/uql-browser.min.js.map +11 -12
- package/dist/cockroachdb/cockroachDialect.d.ts +4 -1
- package/dist/cockroachdb/cockroachDialect.js +6 -2
- package/dist/dialect/abstractDialect.d.ts +1 -1
- package/dist/dialect/abstractDialect.js +4 -1
- package/dist/dialect/abstractSqlDialect.d.ts +68 -37
- package/dist/dialect/abstractSqlDialect.js +185 -107
- package/dist/dialect/aliases.d.ts +4 -1
- package/dist/dialect/aliases.js +5 -2
- package/dist/dialect/hydrateColumn.js +3 -10
- package/dist/dialect/jsonSql.d.ts +4 -1
- package/dist/dialect/jsonSql.js +4 -1
- package/dist/dialect/mergeSqlDialect.d.ts +14 -4
- package/dist/dialect/mergeSqlDialect.js +32 -15
- package/dist/dialect/mysqlLikeSqlDialect.d.ts +16 -24
- package/dist/dialect/mysqlLikeSqlDialect.js +38 -52
- package/dist/dialect/pgLikeSqlDialect.d.ts +8 -8
- package/dist/dialect/pgLikeSqlDialect.js +19 -22
- package/dist/http/contract.d.ts +4 -0
- package/dist/http/contract.js +1 -0
- package/dist/http/handler.d.ts +2 -2
- package/dist/http/handler.js +17 -19
- package/dist/http/query.d.ts +5 -3
- package/dist/http/query.js +42 -42
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/maria/mariaDialect.d.ts +4 -3
- package/dist/maria/mariaDialect.js +4 -6
- package/dist/migrate/builder/columnBuilder.d.ts +5 -15
- package/dist/migrate/builder/columnBuilder.js +50 -86
- package/dist/migrate/builder/index.d.ts +0 -1
- package/dist/migrate/builder/index.js +0 -1
- package/dist/migrate/builder/migrationBuilder.d.ts +3 -11
- package/dist/migrate/builder/migrationBuilder.js +41 -81
- package/dist/migrate/builder/tableBuilder.d.ts +0 -7
- package/dist/migrate/builder/tableBuilder.js +19 -30
- package/dist/migrate/builder/types.d.ts +2 -2
- package/dist/migrate/codegen/entityCodeGenerator.js +3 -3
- package/dist/migrate/codegen/entityTypes.js +2 -2
- package/dist/migrate/codegen/fieldOptionsSource.d.ts +2 -2
- package/dist/migrate/codegen/fieldOptionsSource.js +22 -14
- package/dist/migrate/codegen/indexDecoratorSource.js +64 -41
- package/dist/migrate/ddl/defaultSql.d.ts +31 -0
- package/dist/migrate/ddl/defaultSql.js +109 -0
- package/dist/migrate/ddl/index.d.ts +2 -4
- package/dist/migrate/ddl/index.js +14 -5
- package/dist/migrate/ddl/mssqlTableDdl.d.ts +1 -0
- package/dist/migrate/ddl/mssqlTableDdl.js +4 -1
- package/dist/migrate/ddl/mysqlTableDdl.d.ts +17 -0
- package/dist/migrate/ddl/mysqlTableDdl.js +33 -0
- package/dist/migrate/ddl/pgTableDdl.d.ts +7 -0
- package/dist/migrate/ddl/pgTableDdl.js +17 -0
- package/dist/migrate/ddl/tableDdl.d.ts +15 -10
- package/dist/migrate/ddl/tableDdl.js +31 -32
- package/dist/migrate/drift/driftDetector.js +46 -59
- package/dist/migrate/generator/definitionToNode.d.ts +11 -7
- package/dist/migrate/generator/definitionToNode.js +27 -34
- package/dist/migrate/generator/indexNodeToSchema.d.ts +3 -3
- package/dist/migrate/generator/indexNodeToSchema.js +5 -4
- package/dist/migrate/index.js +1 -1
- package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +10 -5
- package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +9 -0
- package/dist/migrate/introspection/baseSqlIntrospector.d.ts +0 -1
- package/dist/migrate/introspection/baseSqlIntrospector.js +6 -8
- package/dist/migrate/introspection/mssqlIntrospector.js +3 -8
- package/dist/migrate/introspection/mysqlIntrospector.d.ts +11 -4
- package/dist/migrate/introspection/mysqlIntrospector.js +27 -11
- package/dist/migrate/introspection/postgresIntrospector.d.ts +2 -2
- package/dist/migrate/introspection/postgresIntrospector.js +3 -3
- package/dist/migrate/introspection/sqliteIntrospector.d.ts +1 -1
- package/dist/migrate/introspection/sqliteIntrospector.js +7 -10
- package/dist/migrate/migrationTarget.js +3 -3
- package/dist/migrate/schemaGenerator.d.ts +8 -12
- package/dist/migrate/schemaGenerator.js +36 -62
- package/dist/migrate/storage/databaseStorage.js +2 -2
- package/dist/migrate/triggerSql.d.ts +1 -1
- package/dist/migrate/triggerSql.js +17 -8
- package/dist/mongo/mongoDialect.d.ts +4 -3
- package/dist/mongo/mongoDialect.js +52 -38
- package/dist/mongo/mongoIntrospector.js +1 -1
- package/dist/mongo/mongoSchemaGenerator.d.ts +7 -4
- package/dist/mongo/mongoSchemaGenerator.js +18 -21
- package/dist/mongo/mongodbQuerier.d.ts +15 -8
- package/dist/mongo/mongodbQuerier.js +48 -33
- package/dist/mssql/mssqlDialect.d.ts +9 -5
- package/dist/mssql/mssqlDialect.js +23 -8
- package/dist/postgres/postgresDialect.d.ts +5 -2
- package/dist/postgres/postgresDialect.js +6 -6
- package/dist/querier/abstractQuerier.d.ts +20 -15
- package/dist/querier/abstractQuerier.js +93 -41
- package/dist/querier/abstractQuerierPool.d.ts +26 -24
- package/dist/querier/abstractQuerierPool.js +26 -64
- package/dist/querier/abstractSqlQuerier.d.ts +5 -6
- package/dist/querier/abstractSqlQuerier.js +15 -33
- package/dist/querier/cursor.d.ts +10 -0
- package/dist/querier/cursor.js +81 -0
- package/dist/querier/keyset.d.ts +19 -0
- package/dist/querier/keyset.js +198 -0
- package/dist/schema/canonicalType.d.ts +3 -3
- package/dist/schema/canonicalType.js +13 -12
- package/dist/schema/indexDifferences.d.ts +14 -7
- package/dist/schema/indexDifferences.js +7 -5
- package/dist/schema/schemaAST.d.ts +0 -1
- package/dist/schema/schemaAST.js +0 -2
- package/dist/schema/schemaASTBuilder.js +14 -20
- package/dist/schema/schemaASTDiffer.d.ts +7 -9
- package/dist/schema/schemaASTDiffer.js +54 -107
- package/dist/schema/sqlExpression.d.ts +28 -0
- package/dist/schema/sqlExpression.js +42 -0
- package/dist/schema/types.d.ts +48 -105
- package/dist/sqlite/sqliteDialect.d.ts +10 -13
- package/dist/sqlite/sqliteDialect.js +19 -30
- package/dist/type/dialect.d.ts +46 -11
- package/dist/type/dialect.js +2 -0
- package/dist/type/entity.d.ts +18 -3
- package/dist/type/migration.d.ts +7 -7
- package/dist/type/querier.d.ts +19 -26
- package/dist/type/query.d.ts +116 -25
- package/dist/type/query.js +21 -28
- package/dist/type/universalQuerier.d.ts +33 -7
- package/dist/type/utility.d.ts +10 -0
- package/dist/util/bytes.d.ts +7 -0
- package/dist/util/bytes.js +22 -0
- package/dist/util/date.d.ts +5 -0
- package/dist/util/date.js +5 -0
- package/dist/util/dialect.util.d.ts +1 -25
- package/dist/util/dialect.util.js +4 -50
- package/dist/util/field.util.d.ts +9 -0
- package/dist/util/field.util.js +15 -0
- package/dist/util/fieldOption.util.js +2 -2
- package/dist/util/index.d.ts +2 -1
- package/dist/util/index.js +2 -1
- package/dist/util/object.util.d.ts +0 -2
- package/dist/util/object.util.js +0 -7
- package/dist/util/query.util.d.ts +40 -0
- package/dist/util/query.util.js +76 -0
- package/dist/util/raw.d.ts +16 -1
- package/dist/util/raw.js +31 -0
- package/dist/util/relationQuery.util.js +18 -16
- package/dist/util/rowKey.util.js +2 -3
- package/dist/util/sql.util.d.ts +8 -2
- package/dist/util/sql.util.js +16 -17
- package/dist/util/sqlLiteral.js +2 -12
- package/dist/util/string.util.d.ts +5 -0
- package/dist/util/string.util.js +12 -0
- package/dist/util/triggerWrite.d.ts +11 -1
- package/dist/util/triggerWrite.js +14 -0
- package/package.json +1 -1
- package/skills/uql-orm/SKILL.md +22 -10
- package/dist/browser/options.d.ts +0 -4
- package/dist/browser/options.js +0 -13
- package/dist/browser/type/clientQuerierPool.d.ts +0 -4
- package/dist/browser/type/clientQuerierPool.js +0 -1
- package/dist/migrate/builder/expressions.d.ts +0 -69
- 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
|
|
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 {
|
|
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,
|
|
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 =
|
|
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
|
-
|
|
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?.
|
|
339
|
-
if (it.
|
|
340
|
-
return { to: this.columnNodeToSchema(it.
|
|
326
|
+
const columns = (tableDiff?.columns ?? []).map((it) => {
|
|
327
|
+
if (it.from === undefined) {
|
|
328
|
+
return { to: this.columnNodeToSchema(it.to) };
|
|
341
329
|
}
|
|
342
|
-
if (it.
|
|
343
|
-
return { from: this.columnNodeToSchema(it.
|
|
330
|
+
if (it.to === undefined) {
|
|
331
|
+
return { from: this.columnNodeToSchema(it.from), isBreaking: true };
|
|
344
332
|
}
|
|
345
333
|
return {
|
|
346
|
-
from: this.columnNodeToSchema(it.
|
|
347
|
-
to: { ...this.columnNodeToSchema(it.
|
|
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?.
|
|
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.
|
|
355
|
-
to: keyDiff.
|
|
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
|
|
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
|
-
|
|
373
|
-
|
|
374
|
-
|
|
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.
|
|
464
|
-
createSql += ` ${this.
|
|
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.
|
|
488
|
-
* so
|
|
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.
|
|
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
|
|
560
|
-
return this.tableDdl.alterColumn(tableName, { ...
|
|
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
|
|
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
|
-
|
|
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:
|
|
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
|
|
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
|
|
81
|
-
: `CREATE
|
|
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
|
|
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
|
|
188
|
-
*
|
|
189
|
-
*
|
|
190
|
-
* the
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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] =
|
|
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] =
|
|
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 =
|
|
424
|
-
// A computed field
|
|
425
|
-
//
|
|
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
|
|
437
|
-
//
|
|
438
|
-
//
|
|
439
|
-
if (
|
|
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
|
|
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 =
|
|
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] =
|
|
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
|
|
1214
|
-
|
|
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
|
-
/**
|
|
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
|
|
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({
|
|
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 {
|
|
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
|
-
|
|
7
|
-
constructor(namingStrategy?: NamingStrategy
|
|
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
|
-
/**
|
|
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
|
-
|
|
28
|
-
constructor(namingStrategy
|
|
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
|
-
/**
|
|
62
|
-
|
|
63
|
-
|
|
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] =
|
|
67
|
-
const vector =
|
|
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(
|
|
70
|
-
: declaredIndexName(
|
|
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:
|
|
75
|
-
|
|
76
|
-
|
|
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 {
|
|
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
|
}
|