uql-orm 0.91.0 → 0.92.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 (156) 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 +5 -1
  14. package/dist/dialect/abstractDialect.d.ts +1 -1
  15. package/dist/dialect/abstractDialect.js +4 -1
  16. package/dist/dialect/abstractSqlDialect.d.ts +24 -28
  17. package/dist/dialect/abstractSqlDialect.js +47 -45
  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 +4 -3
  24. package/dist/dialect/mergeSqlDialect.js +5 -4
  25. package/dist/dialect/mysqlLikeSqlDialect.d.ts +7 -21
  26. package/dist/dialect/mysqlLikeSqlDialect.js +9 -36
  27. package/dist/dialect/pgLikeSqlDialect.d.ts +3 -7
  28. package/dist/dialect/pgLikeSqlDialect.js +11 -21
  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 +1 -1
  36. package/dist/index.js +1 -1
  37. package/dist/maria/mariaDialect.d.ts +2 -3
  38. package/dist/maria/mariaDialect.js +1 -5
  39. package/dist/migrate/builder/columnBuilder.d.ts +5 -15
  40. package/dist/migrate/builder/columnBuilder.js +50 -86
  41. package/dist/migrate/builder/expressions.d.ts +12 -18
  42. package/dist/migrate/builder/expressions.js +39 -42
  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 +17 -28
  47. package/dist/migrate/builder/types.d.ts +2 -2
  48. package/dist/migrate/codegen/entityCodeGenerator.js +7 -13
  49. package/dist/migrate/codegen/entityTypes.js +6 -20
  50. package/dist/migrate/codegen/fieldOptionsSource.d.ts +2 -2
  51. package/dist/migrate/codegen/fieldOptionsSource.js +27 -12
  52. package/dist/migrate/codegen/indexDecoratorSource.js +64 -41
  53. package/dist/migrate/ddl/index.d.ts +2 -4
  54. package/dist/migrate/ddl/index.js +14 -5
  55. package/dist/migrate/ddl/mssqlTableDdl.d.ts +1 -0
  56. package/dist/migrate/ddl/mssqlTableDdl.js +4 -1
  57. package/dist/migrate/ddl/mysqlTableDdl.d.ts +17 -0
  58. package/dist/migrate/ddl/mysqlTableDdl.js +33 -0
  59. package/dist/migrate/ddl/pgTableDdl.d.ts +7 -0
  60. package/dist/migrate/ddl/pgTableDdl.js +17 -0
  61. package/dist/migrate/ddl/tableDdl.d.ts +15 -10
  62. package/dist/migrate/ddl/tableDdl.js +31 -32
  63. package/dist/migrate/drift/driftDetector.js +46 -59
  64. package/dist/migrate/generator/definitionToNode.d.ts +11 -7
  65. package/dist/migrate/generator/definitionToNode.js +27 -34
  66. package/dist/migrate/generator/indexNodeToSchema.d.ts +3 -3
  67. package/dist/migrate/generator/indexNodeToSchema.js +5 -4
  68. package/dist/migrate/index.js +1 -1
  69. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +10 -5
  70. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +10 -0
  71. package/dist/migrate/introspection/baseSqlIntrospector.d.ts +0 -1
  72. package/dist/migrate/introspection/baseSqlIntrospector.js +6 -8
  73. package/dist/migrate/introspection/mssqlIntrospector.js +3 -8
  74. package/dist/migrate/introspection/mysqlIntrospector.d.ts +11 -4
  75. package/dist/migrate/introspection/mysqlIntrospector.js +25 -11
  76. package/dist/migrate/introspection/postgresIntrospector.d.ts +2 -2
  77. package/dist/migrate/introspection/postgresIntrospector.js +3 -3
  78. package/dist/migrate/introspection/sqliteIntrospector.d.ts +1 -1
  79. package/dist/migrate/introspection/sqliteIntrospector.js +7 -10
  80. package/dist/migrate/migrationTarget.js +3 -3
  81. package/dist/migrate/schemaGenerator.d.ts +8 -12
  82. package/dist/migrate/schemaGenerator.js +35 -61
  83. package/dist/migrate/triggerSql.d.ts +1 -1
  84. package/dist/migrate/triggerSql.js +8 -6
  85. package/dist/mongo/mongoDialect.d.ts +4 -3
  86. package/dist/mongo/mongoDialect.js +52 -38
  87. package/dist/mongo/mongoIntrospector.js +1 -1
  88. package/dist/mongo/mongoSchemaGenerator.d.ts +7 -4
  89. package/dist/mongo/mongoSchemaGenerator.js +18 -21
  90. package/dist/mongo/mongodbQuerier.d.ts +2 -3
  91. package/dist/mongo/mongodbQuerier.js +9 -28
  92. package/dist/mssql/mssqlDialect.d.ts +4 -5
  93. package/dist/mssql/mssqlDialect.js +9 -7
  94. package/dist/postgres/postgresDialect.js +2 -2
  95. package/dist/querier/abstractQuerier.d.ts +16 -11
  96. package/dist/querier/abstractQuerier.js +74 -26
  97. package/dist/querier/abstractQuerierPool.d.ts +26 -24
  98. package/dist/querier/abstractQuerierPool.js +26 -64
  99. package/dist/querier/abstractSqlQuerier.d.ts +2 -3
  100. package/dist/querier/abstractSqlQuerier.js +8 -26
  101. package/dist/querier/cursor.d.ts +10 -0
  102. package/dist/querier/cursor.js +81 -0
  103. package/dist/querier/keyset.d.ts +19 -0
  104. package/dist/querier/keyset.js +198 -0
  105. package/dist/schema/canonicalType.d.ts +3 -3
  106. package/dist/schema/canonicalType.js +13 -12
  107. package/dist/schema/indexDifferences.d.ts +14 -7
  108. package/dist/schema/indexDifferences.js +7 -5
  109. package/dist/schema/schemaAST.d.ts +0 -1
  110. package/dist/schema/schemaAST.js +0 -2
  111. package/dist/schema/schemaASTBuilder.js +28 -20
  112. package/dist/schema/schemaASTDiffer.d.ts +7 -9
  113. package/dist/schema/schemaASTDiffer.js +54 -107
  114. package/dist/schema/sqlExpression.d.ts +22 -0
  115. package/dist/schema/sqlExpression.js +28 -0
  116. package/dist/schema/types.d.ts +48 -105
  117. package/dist/sqlite/sqliteDialect.d.ts +9 -13
  118. package/dist/sqlite/sqliteDialect.js +10 -29
  119. package/dist/type/dialect.d.ts +20 -3
  120. package/dist/type/entity.d.ts +7 -20
  121. package/dist/type/migration.d.ts +7 -7
  122. package/dist/type/querier.d.ts +19 -26
  123. package/dist/type/query.d.ts +104 -24
  124. package/dist/type/query.js +21 -28
  125. package/dist/type/universalQuerier.d.ts +31 -5
  126. package/dist/type/utility.d.ts +10 -0
  127. package/dist/util/bytes.d.ts +7 -0
  128. package/dist/util/bytes.js +22 -0
  129. package/dist/util/date.d.ts +5 -0
  130. package/dist/util/date.js +5 -0
  131. package/dist/util/dialect.util.d.ts +1 -25
  132. package/dist/util/dialect.util.js +4 -50
  133. package/dist/util/field.util.d.ts +9 -0
  134. package/dist/util/field.util.js +15 -0
  135. package/dist/util/fieldOption.util.js +2 -2
  136. package/dist/util/index.d.ts +1 -0
  137. package/dist/util/index.js +1 -0
  138. package/dist/util/object.util.d.ts +0 -2
  139. package/dist/util/object.util.js +0 -7
  140. package/dist/util/query.util.d.ts +40 -0
  141. package/dist/util/query.util.js +76 -0
  142. package/dist/util/raw.d.ts +5 -0
  143. package/dist/util/raw.js +5 -0
  144. package/dist/util/relationQuery.util.js +18 -16
  145. package/dist/util/rowKey.util.js +2 -3
  146. package/dist/util/sql.util.d.ts +8 -2
  147. package/dist/util/sql.util.js +16 -17
  148. package/dist/util/sqlLiteral.js +2 -12
  149. package/dist/util/string.util.d.ts +5 -0
  150. package/dist/util/string.util.js +12 -0
  151. package/package.json +1 -1
  152. package/skills/uql-orm/SKILL.md +22 -11
  153. package/dist/browser/options.d.ts +0 -4
  154. package/dist/browser/options.js +0 -13
  155. package/dist/browser/type/clientQuerierPool.d.ts +0 -4
  156. package/dist/browser/type/clientQuerierPool.js +0 -1
@@ -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
  }
@@ -70,12 +70,11 @@ export declare class MongodbQuerier extends AbstractQuerier implements MongoQuer
70
70
  /** Every read and write goes through here, which makes it where a released querier is caught. */
71
71
  collection<E extends Document>(entity: Type<E>): import("mongodb").Collection<E>;
72
72
  get db(): import("mongodb").Db;
73
- beginTransaction(_opts?: TransactionOptions): Promise<void>;
73
+ protected openTransaction(_opts?: TransactionOptions): Promise<void>;
74
74
  /**
75
75
  * The driver owns the transaction state here and settles it in its own `finally`, so a failed commit
76
76
  * or abort still leaves `inTransaction()` false and the querier releasable.
77
77
  */
78
- commitTransaction(): Promise<void>;
79
- rollbackTransaction(): Promise<void>;
78
+ protected endTransaction(commit: boolean): Promise<void>;
80
79
  internalRelease(): Promise<void>;
81
80
  }
@@ -2,7 +2,7 @@ import { AGGREGATE_VALUE_ALIAS } from '../dialect/aliases.js';
2
2
  import { hasRequiredJoin } from '../dialect/queryJoins.js';
3
3
  import { fieldOf, getMeta, namesKey, soleIdOf } from '../entity/index.js';
4
4
  import { AbstractQuerier, enrichError } from '../querier/index.js';
5
- import { clone, getKeys, getSoftDeleteValue, hasKeys, hasTriggers, populatesRelations, textSortOf, throwNoPendingTransaction, throwPendingTransaction, vectorCandidates, withoutSoftDeleteFilter, whereEach, } from '../util/index.js';
5
+ import { clone, getKeys, getSoftDeleteValue, hasKeys, hasTriggers, populatesRelations, textSortOf, vectorCandidates, withoutSoftDeleteFilter, whereEach, } from '../util/index.js';
6
6
  import { UqlUsageError } from '../util/uqlError.js';
7
7
  /**
8
8
  * `$limit: 0` asks for no rows, the way it does on every SQL dialect - but MongoDB reads `limit(0)`
@@ -319,38 +319,19 @@ export class MongodbQuerier extends AbstractQuerier {
319
319
  get db() {
320
320
  return this.conn.db();
321
321
  }
322
- async beginTransaction(_opts) {
323
- return this.serialize(async () => {
324
- if (this.hasOpenTransaction) {
325
- throwPendingTransaction();
326
- }
327
- this.logger.logInfo('beginTransaction');
328
- await this.session?.endSession();
329
- this.session = this.conn.startSession();
330
- this.session.startTransaction();
331
- });
322
+ async openTransaction(_opts) {
323
+ this.logger.logInfo('beginTransaction');
324
+ await this.session?.endSession();
325
+ this.session = this.conn.startSession();
326
+ this.session.startTransaction();
332
327
  }
333
328
  /**
334
329
  * The driver owns the transaction state here and settles it in its own `finally`, so a failed commit
335
330
  * or abort still leaves `inTransaction()` false and the querier releasable.
336
331
  */
337
- async commitTransaction() {
338
- return this.serialize(async () => {
339
- if (!this.hasOpenTransaction) {
340
- throwNoPendingTransaction();
341
- }
342
- this.logger.logInfo('commitTransaction');
343
- await this.session?.commitTransaction();
344
- });
345
- }
346
- async rollbackTransaction() {
347
- return this.serialize(async () => {
348
- if (!this.hasOpenTransaction) {
349
- return;
350
- }
351
- this.logger.logInfo('rollbackTransaction');
352
- await this.session?.abortTransaction();
353
- });
332
+ async endTransaction(commit) {
333
+ this.logger.logInfo(commit ? 'commitTransaction' : 'rollbackTransaction');
334
+ await (commit ? this.session?.commitTransaction() : this.session?.abortTransaction());
354
335
  }
355
336
  async internalRelease() {
356
337
  const session = this.session;
@@ -1,14 +1,13 @@
1
1
  import { type RelationRows } from '../dialect/abstractSqlDialect.js';
2
2
  import { type JsonAccessMode, type JsonSlot } from '../dialect/jsonSql.js';
3
3
  import { MergeSqlDialect } from '../dialect/mergeSqlDialect.js';
4
- import type { EntityMeta, FieldOptions, InsertIdSource, Query, QueryConflictPaths, QueryContext, QueryOptions, QueryPager, SqlDialectFeatures, Type, VectorDistance, VectorMetric } from '../type/index.js';
4
+ import type { EntityMeta, FieldOptions, Query, QueryConflictPaths, QueryContext, QueryOptions, QueryPager, SqlDialectFeatures, Type, VectorDistance, VectorMetric } from '../type/index.js';
5
5
  /** Microsoft SQL Server 2017 and up. Identifiers are `"`-quoted, the ANSI spelling `tedious` enables. */
6
6
  export declare class MsSqlDialect extends MergeSqlDialect {
7
7
  #private;
8
8
  readonly features: SqlDialectFeatures;
9
9
  readonly dialectName = "mssql";
10
10
  readonly autoIncrementSuffix = "IDENTITY(1,1)";
11
- readonly tableOptions = "";
12
11
  readonly beginTransactionCommand = "BEGIN TRANSACTION";
13
12
  readonly commitTransactionCommand = "COMMIT TRANSACTION";
14
13
  readonly rollbackTransactionCommand = "ROLLBACK TRANSACTION";
@@ -17,15 +16,15 @@ export declare class MsSqlDialect extends MergeSqlDialect {
17
16
  * as statements would run; `MsSqlQuerier` opens its transactions through the driver instead.
18
17
  */
19
18
  readonly isolationLevelStrategy = "set-before";
20
- readonly dropIndexSyntax = "on-table";
21
19
  readonly booleanLiteral = "integer";
20
+ /** UTC, since `CURRENT_TIMESTAMP` is local time in the server's zone. */
21
+ readonly currentTimestamp = "SYSUTCDATETIME()";
22
22
  /** [The hard server limit](https://github.com/yiisoft/yii2/issues/10371), not a driver preference. */
23
23
  readonly maxBindValues = 2100;
24
24
  /** `OUTPUT` has no trailing form: it sits between the column list and `VALUES`. */
25
25
  readonly returningPosition = "after-target";
26
26
  /** `OUTPUT` reads the written row off the `INSERTED` pseudo-table. */
27
27
  protected readonly returnedRowPrefix = "INSERTED.";
28
- readonly insertIdSource: InsertIdSource;
29
28
  /** Holds the update key lock across the insert; without it two concurrent upserts of one key race. */
30
29
  protected readonly mergeTargetHint = " WITH (HOLDLOCK)";
31
30
  protected readonly statementTerminator = ";";
@@ -69,7 +68,7 @@ export declare class MsSqlDialect extends MergeSqlDialect {
69
68
  * carrying a trigger, and through a table it works whether one is there or not.
70
69
  */
71
70
  returningId<E>(meta: EntityMeta<E>): string;
72
- upsert<E>(ctx: QueryContext, entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[], extraReturning?: string): void;
71
+ upsert<E>(ctx: QueryContext, entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[]): void;
73
72
  /**
74
73
  * A statement writing rows, `write`, wrapped in what SQL Server needs around one. The table variable its
75
74
  * `OUTPUT` fills, typed as the id column is, and the read handing that back, uncounted so the batch
@@ -7,6 +7,7 @@ import { getMeta } from '../entity/index.js';
7
7
  import { canonicalToSql, fieldOptionsToCanonical, resolveColumnCanonicalType } from '../schema/canonicalType.js';
8
8
  import { QueryRaw } from '../type/index.js';
9
9
  import { parseQueryLock } from '../type/index.js';
10
+ import { bytesToHex } from '../util/bytes.js';
10
11
  import { isAutoIncrement } from '../util/field.util.js';
11
12
  import { assertNonNegativeInteger } from '../util/index.js';
12
13
  import { escapeSingleQuotes } from '../util/sqlLiteral.js';
@@ -29,6 +30,7 @@ const MSSQL_FEATURES = {
29
30
  serverSideCursors: false,
30
31
  correlatedWrites: true,
31
32
  rowLocks: { of: true, withWindow: true, placement: 'tableHint' },
33
+ nullsSortLowest: true,
32
34
  nullsOrdering: 'case',
33
35
  textScoreIndexes: false,
34
36
  orderedUpsertReturning: false,
@@ -38,6 +40,7 @@ const MSSQL_FEATURES = {
38
40
  serialDeclaresPrimaryKey: false,
39
41
  triggers: {
40
42
  preamble: 'SET NOCOUNT ON;',
43
+ reentryGuard: 'IF TRIGGER_NESTLEVEL(@@PROCID) > 1 RETURN;',
41
44
  assignsRow: false,
42
45
  body: 'inline',
43
46
  fires: 'eachStatement',
@@ -72,7 +75,6 @@ export class MsSqlDialect extends MergeSqlDialect {
72
75
  type: this.escapeId('type'),
73
76
  };
74
77
  autoIncrementSuffix = 'IDENTITY(1,1)';
75
- tableOptions = '';
76
78
  beginTransactionCommand = 'BEGIN TRANSACTION';
77
79
  commitTransactionCommand = 'COMMIT TRANSACTION';
78
80
  rollbackTransactionCommand = 'ROLLBACK TRANSACTION';
@@ -81,15 +83,15 @@ export class MsSqlDialect extends MergeSqlDialect {
81
83
  * as statements would run; `MsSqlQuerier` opens its transactions through the driver instead.
82
84
  */
83
85
  isolationLevelStrategy = 'set-before';
84
- dropIndexSyntax = 'on-table';
85
86
  booleanLiteral = 'integer';
87
+ /** UTC, since `CURRENT_TIMESTAMP` is local time in the server's zone. */
88
+ currentTimestamp = 'SYSUTCDATETIME()';
86
89
  /** [The hard server limit](https://github.com/yiisoft/yii2/issues/10371), not a driver preference. */
87
90
  maxBindValues = 2100;
88
91
  /** `OUTPUT` has no trailing form: it sits between the column list and `VALUES`. */
89
92
  returningPosition = 'after-target';
90
93
  /** `OUTPUT` reads the written row off the `INSERTED` pseudo-table. */
91
94
  returnedRowPrefix = 'INSERTED.';
92
- insertIdSource = 'returning';
93
95
  /** Holds the update key lock across the insert; without it two concurrent upserts of one key race. */
94
96
  mergeTargetHint = ' WITH (HOLDLOCK)';
95
97
  statementTerminator = ';';
@@ -163,10 +165,10 @@ export class MsSqlDialect extends MergeSqlDialect {
163
165
  */
164
166
  returningId(meta) {
165
167
  const expression = this.returningIdExpression(meta);
166
- return expression ? `OUTPUT ${expression} INTO ${OUTPUT_TABLE}` : '';
168
+ return expression ? this.mergeReturning(expression) : '';
167
169
  }
168
- upsert(ctx, entity, conflictPaths, payload, extraReturning = '') {
169
- this.writeRows(ctx, getMeta(entity), payload, () => super.upsert(ctx, entity, conflictPaths, payload, extraReturning));
170
+ upsert(ctx, entity, conflictPaths, payload) {
171
+ this.writeRows(ctx, getMeta(entity), payload, () => super.upsert(ctx, entity, conflictPaths, payload));
170
172
  }
171
173
  /**
172
174
  * A statement writing rows, `write`, wrapped in what SQL Server needs around one. The table variable its
@@ -216,7 +218,7 @@ export class MsSqlDialect extends MergeSqlDialect {
216
218
  return `N'${escapeSingleQuotes(value)}'`;
217
219
  }
218
220
  if (value instanceof Uint8Array) {
219
- return `0x${Array.from(value, (byte) => byte.toString(16).padStart(2, '0')).join('')}`;
221
+ return `0x${bytesToHex(value)}`;
220
222
  }
221
223
  return super.escape(value);
222
224
  }
@@ -1,4 +1,4 @@
1
- import { AGGREGATE_VALUE_ALIAS } from '../dialect/aliases.js';
1
+ import { AGGREGATE_VALUE_ALIAS, UPSERT_CREATED_ALIAS } from '../dialect/aliases.js';
2
2
  import { PG_FEATURES, PgLikeSqlDialect } from '../dialect/pgLikeSqlDialect.js';
3
3
  import { getMeta } from '../entity/index.js';
4
4
  /** PostgreSQL, under every driver: `pg`, Neon, PGlite, `bun:sql`. Adds pgvector and the `xmax` upsert `created`. */
@@ -9,7 +9,7 @@ export class PostgresDialect extends PgLikeSqlDialect {
9
9
  features = { ...PG_FEATURES, narrowVectorTypes: true };
10
10
  upsert(ctx, entity, conflictPaths, payload) {
11
11
  // The xmax system column is 0 for a newly inserted row and non-zero for an updated one (MVCC).
12
- super.upsert(ctx, entity, conflictPaths, payload, `(xmax = 0) AS ${this.escapeId('_created')}`);
12
+ super.upsert(ctx, entity, conflictPaths, payload, `(xmax = 0) AS ${this.escapeId(UPSERT_CREATED_ALIAS)}`);
13
13
  }
14
14
  /**
15
15
  * `to_regclass` rather than a `::regclass` cast: it answers `NULL` for a table that does not exist
@@ -1,5 +1,5 @@
1
1
  import type { AbstractDialect } from '../dialect/abstractDialect.js';
2
- import type { EntityData, EntityId, EntityWrite, ExtraOptions, FieldKey, Querier, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryFilter, QueryFindResult, QueryGroupMap, QueryOneProjected, QueryOptions, QueryPage, QueryProjected, QuerySearch, PrimaryKey, QueryUpdateResult, QueryUpsertOneResult, QueryUpsertManyResult, RelationKey, TransactionOptions, Type, UpdatePayload, UpdateWrite, WrittenId } from '../type/index.js';
2
+ import type { CursorPage, EntityData, EntityId, EntityWrite, ExtraOptions, FieldKey, Querier, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryFilter, QueryFindResult, QueryGroupMap, QueryKeysetProjected, QueryOneProjected, QueryOptions, QueryPage, QueryProjected, QuerySearch, PrimaryKey, QueryUpdateResult, QueryUpsertOneResult, QueryUpsertManyResult, RelationKey, TransactionOptions, Type, UpdatePayload, UpdateWrite, WrittenId } from '../type/index.js';
3
3
  import { LoggerWrapper } from '../util/index.js';
4
4
  /** Base class for all database queriers. */
5
5
  export declare abstract class AbstractQuerier implements Querier {
@@ -27,10 +27,6 @@ export declare abstract class AbstractQuerier implements Querier {
27
27
  */
28
28
  private assertLockable;
29
29
  private validateProjectionQueryRecursive;
30
- /** `[entity, query, opts]` from either call form, `(entity, q, opts)` or `({ $entity, ...q }, opts)`. */
31
- protected resolveEntityQuery<E extends object, Q extends object>(entityOrQuery: Type<E> | (Q & {
32
- $entity: Type<E>;
33
- }), maybeQueryOrOpts?: Q | QueryOptions, maybeOpts?: QueryOptions): [Type<E>, Q, QueryOptions | undefined];
34
30
  findOneById<E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(entity: Type<E>, id: EntityId<E>, q?: QueryOneProjected<E, S, V, X, P, C>, opts?: QueryOptions): Promise<QueryFindResult<E, S, V, X, P, C> | undefined>;
35
31
  /** Find one record, the entity passed first or as the query's `$entity`. */
36
32
  findOne<E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(q: QueryOneProjected<E, S, V, X, P, C> & {
@@ -63,18 +59,23 @@ export declare abstract class AbstractQuerier implements Querier {
63
59
  * backend with no way to answer both at once is left with; SQL overrides it to answer from one.
64
60
  */
65
61
  protected internalFindManyAndCount<E extends object>(entity: Type<E>, q: Query<E>, opts?: QueryOptions): Promise<[E[], number]>;
62
+ /** Read a page of records from a cursor, the entity passed first or as the query's `$entity`. */
63
+ findManyPage<E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(q: QueryKeysetProjected<E, S, V, X, P, C> & {
64
+ $entity: Type<E>;
65
+ }, opts?: QueryOptions): Promise<CursorPage<QueryFindResult<E, S, V, X, P, C>>>;
66
+ findManyPage<E extends object, const S extends FieldKey<E> = never, const V = true, const X extends FieldKey<E> = never, const P extends RelationKey<E> = never, const C extends RelationKey<E> = never>(entity: Type<E>, q: QueryKeysetProjected<E, S, V, X, P, C>, opts?: QueryOptions): Promise<CursorPage<QueryFindResult<E, S, V, X, P, C>>>;
66
67
  /** Count records matching the query, the entity passed first or as the query's `$entity`. */
67
- count<E extends object>(entity: Type<E>, q?: QueryPage<E>, opts?: QueryOptions): Promise<number>;
68
68
  count<E extends object>(q: QueryPage<E> & {
69
69
  $entity: Type<E>;
70
70
  }, opts?: QueryOptions): Promise<number>;
71
+ count<E extends object>(entity: Type<E>, q?: QueryPage<E>, opts?: QueryOptions): Promise<number>;
71
72
  /** How many rows match, or how many of them a page takes: counted where they are, never read. */
72
73
  protected abstract internalCount<E extends object>(entity: Type<E>, q: QueryPage<E>, opts?: QueryOptions): Promise<number>;
73
74
  /** Whether anything matches, the entity passed first or as `$entity`: a count capped at one row. */
74
- exists<E extends object>(entity: Type<E>, q?: QueryFilter<E>, opts?: QueryOptions): Promise<boolean>;
75
75
  exists<E extends object>(q: QueryFilter<E> & {
76
76
  $entity: Type<E>;
77
77
  }, opts?: QueryOptions): Promise<boolean>;
78
+ exists<E extends object>(entity: Type<E>, q?: QueryFilter<E>, opts?: QueryOptions): Promise<boolean>;
78
79
  /**
79
80
  * Run an aggregate query.
80
81
  */
@@ -138,10 +139,10 @@ export declare abstract class AbstractQuerier implements Querier {
138
139
  protected abstract internalUpsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: EntityData<E>[]): Promise<QueryUpdateResult>;
139
140
  deleteOneById<E extends object>(entity: Type<E>, id: EntityId<E>, opts?: QueryOptions): Promise<number>;
140
141
  /** Delete records matching the query, the entity passed first or as `$entity`; soft-deletes unless `opts.hardDelete`. */
141
- deleteMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, opts?: QueryOptions): Promise<number>;
142
142
  deleteMany<E extends object>(q: QuerySearch<E> & {
143
143
  $entity: Type<E>;
144
144
  }, opts?: QueryOptions): Promise<number>;
145
+ deleteMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, opts?: QueryOptions): Promise<number>;
145
146
  /** Runs one DELETE (or soft-delete stamp) over `q`, which names its rows by id wherever {@link deleteMany} settled them. */
146
147
  protected abstract internalDeleteMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, opts?: QueryOptions): Promise<number>;
147
148
  saveOne<E extends object>(entity: Type<E>, payload: EntityWrite<E>): Promise<WrittenId<E> | undefined>;
@@ -196,14 +197,18 @@ export declare abstract class AbstractQuerier implements Querier {
196
197
  protected serialize<T>(task: () => Promise<T>): Promise<T>;
197
198
  /** Runs `task`, logs `query` with its duration, and tags a failure with it: a method, since a decorator would lose the generics. */
198
199
  protected timed<T>(query: string, values: readonly unknown[] | undefined, task: () => Promise<T>): Promise<T>;
199
- abstract beginTransaction(opts?: TransactionOptions): Promise<void>;
200
+ beginTransaction(opts?: TransactionOptions): Promise<void>;
200
201
  /** Strict: this is the check that catches a forgotten `beginTransaction`. */
201
- abstract commitTransaction(): Promise<void>;
202
+ commitTransaction(): Promise<void>;
202
203
  /**
203
204
  * Rolls the open transaction back, or does nothing when there is none: it is called from `catch` and
204
205
  * `finally`, where the caller cannot know whether `beginTransaction` got far enough to open one.
205
206
  */
206
- abstract rollbackTransaction(): Promise<void>;
207
+ rollbackTransaction(): Promise<void>;
208
+ /** Opens a transaction on the engine, after `beginTransaction` has queued the call and checked none is open. */
209
+ protected abstract openTransaction(opts?: TransactionOptions): Promise<void>;
210
+ /** Commits the open transaction on the engine, or rolls it back when `commit` is false. */
211
+ protected abstract endTransaction(commit: boolean): Promise<void>;
207
212
  /**
208
213
  * Rolls back an unfinished transaction, then hands the connection back, discarding it if the rollback
209
214
  * failed. Never throws first, since `await using` has no other way to release.