uql-orm 0.91.1 → 0.93.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/dist/browser/http/bus.js +3 -4
  2. package/dist/browser/http/http.d.ts +1 -2
  3. package/dist/browser/http/http.js +8 -7
  4. package/dist/browser/index.d.ts +0 -1
  5. package/dist/browser/index.js +0 -1
  6. package/dist/browser/querier/httpQuerier.d.ts +18 -20
  7. package/dist/browser/querier/httpQuerier.js +20 -56
  8. package/dist/browser/type/index.d.ts +0 -1
  9. package/dist/browser/type/index.js +0 -1
  10. package/dist/browser/uql-browser.min.js +2 -2
  11. package/dist/browser/uql-browser.min.js.map +11 -12
  12. package/dist/cockroachdb/cockroachDialect.d.ts +4 -1
  13. package/dist/cockroachdb/cockroachDialect.js +6 -2
  14. package/dist/dialect/abstractDialect.d.ts +1 -1
  15. package/dist/dialect/abstractDialect.js +4 -1
  16. package/dist/dialect/abstractSqlDialect.d.ts +68 -37
  17. package/dist/dialect/abstractSqlDialect.js +185 -107
  18. package/dist/dialect/aliases.d.ts +4 -1
  19. package/dist/dialect/aliases.js +5 -2
  20. package/dist/dialect/hydrateColumn.js +3 -10
  21. package/dist/dialect/jsonSql.d.ts +4 -1
  22. package/dist/dialect/jsonSql.js +4 -1
  23. package/dist/dialect/mergeSqlDialect.d.ts +14 -4
  24. package/dist/dialect/mergeSqlDialect.js +32 -15
  25. package/dist/dialect/mysqlLikeSqlDialect.d.ts +16 -24
  26. package/dist/dialect/mysqlLikeSqlDialect.js +38 -52
  27. package/dist/dialect/pgLikeSqlDialect.d.ts +8 -8
  28. package/dist/dialect/pgLikeSqlDialect.js +19 -22
  29. package/dist/http/contract.d.ts +4 -0
  30. package/dist/http/contract.js +1 -0
  31. package/dist/http/handler.d.ts +2 -2
  32. package/dist/http/handler.js +17 -19
  33. package/dist/http/query.d.ts +5 -3
  34. package/dist/http/query.js +42 -42
  35. package/dist/index.d.ts +2 -2
  36. package/dist/index.js +2 -2
  37. package/dist/maria/mariaDialect.d.ts +4 -3
  38. package/dist/maria/mariaDialect.js +4 -6
  39. package/dist/migrate/builder/columnBuilder.d.ts +5 -15
  40. package/dist/migrate/builder/columnBuilder.js +50 -86
  41. package/dist/migrate/builder/index.d.ts +0 -1
  42. package/dist/migrate/builder/index.js +0 -1
  43. package/dist/migrate/builder/migrationBuilder.d.ts +3 -11
  44. package/dist/migrate/builder/migrationBuilder.js +41 -81
  45. package/dist/migrate/builder/tableBuilder.d.ts +0 -7
  46. package/dist/migrate/builder/tableBuilder.js +19 -30
  47. package/dist/migrate/builder/types.d.ts +2 -2
  48. package/dist/migrate/codegen/entityCodeGenerator.js +3 -3
  49. package/dist/migrate/codegen/entityTypes.js +2 -2
  50. package/dist/migrate/codegen/fieldOptionsSource.d.ts +2 -2
  51. package/dist/migrate/codegen/fieldOptionsSource.js +22 -14
  52. package/dist/migrate/codegen/indexDecoratorSource.js +64 -41
  53. package/dist/migrate/ddl/defaultSql.d.ts +31 -0
  54. package/dist/migrate/ddl/defaultSql.js +109 -0
  55. package/dist/migrate/ddl/index.d.ts +2 -4
  56. package/dist/migrate/ddl/index.js +14 -5
  57. package/dist/migrate/ddl/mssqlTableDdl.d.ts +1 -0
  58. package/dist/migrate/ddl/mssqlTableDdl.js +4 -1
  59. package/dist/migrate/ddl/mysqlTableDdl.d.ts +17 -0
  60. package/dist/migrate/ddl/mysqlTableDdl.js +33 -0
  61. package/dist/migrate/ddl/pgTableDdl.d.ts +7 -0
  62. package/dist/migrate/ddl/pgTableDdl.js +17 -0
  63. package/dist/migrate/ddl/tableDdl.d.ts +15 -10
  64. package/dist/migrate/ddl/tableDdl.js +31 -32
  65. package/dist/migrate/drift/driftDetector.js +46 -59
  66. package/dist/migrate/generator/definitionToNode.d.ts +11 -7
  67. package/dist/migrate/generator/definitionToNode.js +27 -34
  68. package/dist/migrate/generator/indexNodeToSchema.d.ts +3 -3
  69. package/dist/migrate/generator/indexNodeToSchema.js +5 -4
  70. package/dist/migrate/index.js +1 -1
  71. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +10 -5
  72. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +9 -0
  73. package/dist/migrate/introspection/baseSqlIntrospector.d.ts +0 -1
  74. package/dist/migrate/introspection/baseSqlIntrospector.js +6 -8
  75. package/dist/migrate/introspection/mssqlIntrospector.js +3 -8
  76. package/dist/migrate/introspection/mysqlIntrospector.d.ts +11 -4
  77. package/dist/migrate/introspection/mysqlIntrospector.js +27 -11
  78. package/dist/migrate/introspection/postgresIntrospector.d.ts +2 -2
  79. package/dist/migrate/introspection/postgresIntrospector.js +3 -3
  80. package/dist/migrate/introspection/sqliteIntrospector.d.ts +1 -1
  81. package/dist/migrate/introspection/sqliteIntrospector.js +7 -10
  82. package/dist/migrate/migrationTarget.js +3 -3
  83. package/dist/migrate/schemaGenerator.d.ts +8 -12
  84. package/dist/migrate/schemaGenerator.js +36 -62
  85. package/dist/migrate/storage/databaseStorage.js +2 -2
  86. package/dist/migrate/triggerSql.d.ts +1 -1
  87. package/dist/migrate/triggerSql.js +17 -8
  88. package/dist/mongo/mongoDialect.d.ts +4 -3
  89. package/dist/mongo/mongoDialect.js +52 -38
  90. package/dist/mongo/mongoIntrospector.js +1 -1
  91. package/dist/mongo/mongoSchemaGenerator.d.ts +7 -4
  92. package/dist/mongo/mongoSchemaGenerator.js +18 -21
  93. package/dist/mongo/mongodbQuerier.d.ts +15 -8
  94. package/dist/mongo/mongodbQuerier.js +48 -33
  95. package/dist/mssql/mssqlDialect.d.ts +9 -5
  96. package/dist/mssql/mssqlDialect.js +23 -8
  97. package/dist/postgres/postgresDialect.d.ts +5 -2
  98. package/dist/postgres/postgresDialect.js +6 -6
  99. package/dist/querier/abstractQuerier.d.ts +20 -15
  100. package/dist/querier/abstractQuerier.js +93 -41
  101. package/dist/querier/abstractQuerierPool.d.ts +26 -24
  102. package/dist/querier/abstractQuerierPool.js +26 -64
  103. package/dist/querier/abstractSqlQuerier.d.ts +5 -6
  104. package/dist/querier/abstractSqlQuerier.js +15 -33
  105. package/dist/querier/cursor.d.ts +10 -0
  106. package/dist/querier/cursor.js +81 -0
  107. package/dist/querier/keyset.d.ts +19 -0
  108. package/dist/querier/keyset.js +198 -0
  109. package/dist/schema/canonicalType.d.ts +3 -3
  110. package/dist/schema/canonicalType.js +13 -12
  111. package/dist/schema/indexDifferences.d.ts +14 -7
  112. package/dist/schema/indexDifferences.js +7 -5
  113. package/dist/schema/schemaAST.d.ts +0 -1
  114. package/dist/schema/schemaAST.js +0 -2
  115. package/dist/schema/schemaASTBuilder.js +14 -20
  116. package/dist/schema/schemaASTDiffer.d.ts +7 -9
  117. package/dist/schema/schemaASTDiffer.js +54 -107
  118. package/dist/schema/sqlExpression.d.ts +28 -0
  119. package/dist/schema/sqlExpression.js +42 -0
  120. package/dist/schema/types.d.ts +48 -105
  121. package/dist/sqlite/sqliteDialect.d.ts +10 -13
  122. package/dist/sqlite/sqliteDialect.js +19 -30
  123. package/dist/type/dialect.d.ts +46 -11
  124. package/dist/type/dialect.js +2 -0
  125. package/dist/type/entity.d.ts +18 -3
  126. package/dist/type/migration.d.ts +7 -7
  127. package/dist/type/querier.d.ts +19 -26
  128. package/dist/type/query.d.ts +116 -25
  129. package/dist/type/query.js +21 -28
  130. package/dist/type/universalQuerier.d.ts +33 -7
  131. package/dist/type/utility.d.ts +10 -0
  132. package/dist/util/bytes.d.ts +7 -0
  133. package/dist/util/bytes.js +22 -0
  134. package/dist/util/date.d.ts +5 -0
  135. package/dist/util/date.js +5 -0
  136. package/dist/util/dialect.util.d.ts +1 -25
  137. package/dist/util/dialect.util.js +4 -50
  138. package/dist/util/field.util.d.ts +9 -0
  139. package/dist/util/field.util.js +15 -0
  140. package/dist/util/fieldOption.util.js +2 -2
  141. package/dist/util/index.d.ts +2 -1
  142. package/dist/util/index.js +2 -1
  143. package/dist/util/object.util.d.ts +0 -2
  144. package/dist/util/object.util.js +0 -7
  145. package/dist/util/query.util.d.ts +40 -0
  146. package/dist/util/query.util.js +76 -0
  147. package/dist/util/raw.d.ts +16 -1
  148. package/dist/util/raw.js +31 -0
  149. package/dist/util/relationQuery.util.js +18 -16
  150. package/dist/util/rowKey.util.js +2 -3
  151. package/dist/util/sql.util.d.ts +8 -2
  152. package/dist/util/sql.util.js +16 -17
  153. package/dist/util/sqlLiteral.js +2 -12
  154. package/dist/util/string.util.d.ts +5 -0
  155. package/dist/util/string.util.js +12 -0
  156. package/dist/util/triggerWrite.d.ts +11 -1
  157. package/dist/util/triggerWrite.js +14 -0
  158. package/package.json +1 -1
  159. package/skills/uql-orm/SKILL.md +22 -10
  160. package/dist/browser/options.d.ts +0 -4
  161. package/dist/browser/options.js +0 -13
  162. package/dist/browser/type/clientQuerierPool.d.ts +0 -4
  163. package/dist/browser/type/clientQuerierPool.js +0 -1
  164. package/dist/migrate/builder/expressions.d.ts +0 -69
  165. package/dist/migrate/builder/expressions.js +0 -145
@@ -1,6 +1,6 @@
1
1
  import type { Document, MongoClient } from 'mongodb';
2
2
  import { AbstractQuerier } from '../querier/index.js';
3
- import type { EntityData, ExtraOptions, PrimaryKey, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryPage, QueryGroupMap, QueryOptions, QuerySearch, TransactionOptions, Type, UpdatePayload } from '../type/index.js';
3
+ import type { EntityData, ExtraOptions, PrimaryKey, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryPage, QueryGroupMap, QueryOptions, QuerySearch, TransactionOptions, Type, UpdatePayload, UpsertOptions } from '../type/index.js';
4
4
  import type { MongoDialect } from './mongoDialect.js';
5
5
  import type { MongoQuerier } from './mongoQuerier.js';
6
6
  export declare class MongodbQuerier extends AbstractQuerier implements MongoQuerier {
@@ -53,29 +53,36 @@ export declare class MongodbQuerier extends AbstractQuerier implements MongoQuer
53
53
  */
54
54
  private upsertUpdate;
55
55
  private buildConflictFilter;
56
- protected internalUpsertOne<E extends Document>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: EntityData<E>): Promise<{
56
+ /**
57
+ * An upsert whose conflicting document takes `update`, which no single call pairs with inserting the payload:
58
+ * `$setOnInsert` and `$inc` on one field conflict. So the row inserts if absent, and a document it found,
59
+ * a concurrent one included, then takes `update`.
60
+ */
61
+ private upsertWithUpdate;
62
+ /** The id and whether it was created, read off the document a `findOneAndUpdate` upsert wrote. */
63
+ private upserted;
64
+ protected internalUpsertOne<E extends Document>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E, { update }: UpsertOptions<E>): Promise<{
57
65
  ids: (PrimaryKey | undefined)[];
58
66
  changes: number;
59
67
  created: boolean;
60
68
  }>;
61
- protected internalUpsertMany<E extends Document>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: EntityData<E>[]): Promise<{
69
+ protected internalUpsertMany<E extends Document>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E[], { update }: UpsertOptions<E>): Promise<{
70
+ ids: (PrimaryKey | undefined)[];
62
71
  changes: number;
63
- ids?: undefined;
64
72
  } | {
65
73
  changes: number;
66
- ids: (PrimaryKey | undefined)[];
74
+ ids?: undefined;
67
75
  }>;
68
76
  protected internalDeleteMany<E extends Document>(entity: Type<E>, qm: QuerySearch<E>, opts?: QueryOptions): Promise<number>;
69
77
  get hasOpenTransaction(): boolean;
70
78
  /** Every read and write goes through here, which makes it where a released querier is caught. */
71
79
  collection<E extends Document>(entity: Type<E>): import("mongodb").Collection<E>;
72
80
  get db(): import("mongodb").Db;
73
- beginTransaction(_opts?: TransactionOptions): Promise<void>;
81
+ protected openTransaction(_opts?: TransactionOptions): Promise<void>;
74
82
  /**
75
83
  * The driver owns the transaction state here and settles it in its own `finally`, so a failed commit
76
84
  * or abort still leaves `inTransaction()` false and the querier releasable.
77
85
  */
78
- commitTransaction(): Promise<void>;
79
- rollbackTransaction(): Promise<void>;
86
+ protected endTransaction(commit: boolean): Promise<void>;
80
87
  internalRelease(): Promise<void>;
81
88
  }
@@ -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)`
@@ -226,8 +226,34 @@ export class MongodbQuerier extends AbstractQuerier {
226
226
  buildConflictFilter(entity, conflictPaths, item) {
227
227
  return this.dialect.where(entity, whereEach(getKeys(conflictPaths), (key) => item[key]));
228
228
  }
229
- async internalUpsertOne(entity, conflictPaths, payload) {
229
+ /**
230
+ * An upsert whose conflicting document takes `update`, which no single call pairs with inserting the payload:
231
+ * `$setOnInsert` and `$inc` on one field conflict. So the row inserts if absent, and a document it found,
232
+ * a concurrent one included, then takes `update`.
233
+ */
234
+ async upsertWithUpdate(entity, conflictPaths, row, update) {
235
+ const persistable = this.dialect.getPersistable(getMeta(entity), clone(row), 'onInsert');
236
+ const res = await this.execute((session) => this.collection(entity).findOneAndUpdate(this.buildConflictFilter(entity, conflictPaths, row), { $setOnInsert: persistable }, { upsert: true, returnDocument: 'after', includeResultMetadata: true, session }));
237
+ const { id, created } = this.upserted(res);
238
+ // An empty `update` leaves a found document as it is, as `DO NOTHING` does.
239
+ const updates = !created && hasKeys(update);
240
+ if (updates) {
241
+ await this.internalUpdateMany(entity, { $where: whereEach(getKeys(conflictPaths), (key) => row[key]) }, update);
242
+ }
243
+ return { id, created, changes: created || updates ? 1 : 0 };
244
+ }
245
+ /** The id and whether it was created, read off the document a `findOneAndUpdate` upsert wrote. */
246
+ upserted(res) {
247
+ const id = this.dialect.fromWireId(res.value?._id);
248
+ // `updatedExisting` is false when a new document was inserted (upserted).
249
+ return { id, created: res.lastErrorObject?.['updatedExisting'] === false };
250
+ }
251
+ async internalUpsertOne(entity, conflictPaths, payload, { update }) {
230
252
  refuseTriggers(entity);
253
+ if (update) {
254
+ const { id, created, changes } = await this.upsertWithUpdate(entity, conflictPaths, payload, update);
255
+ return { ids: [id], changes, created };
256
+ }
231
257
  return this.timed('upsertOne', undefined, async () => {
232
258
  payload = clone(payload);
233
259
  const meta = getMeta(entity);
@@ -241,14 +267,22 @@ export class MongodbQuerier extends AbstractQuerier {
241
267
  session,
242
268
  }));
243
269
  // Read off the document as written, which carries its `_id` on either branch.
244
- const id = this.dialect.fromWireId(res?.value?._id);
245
- // `updatedExisting` is false when a new document was inserted (upserted).
246
- const created = res?.lastErrorObject?.['updatedExisting'] === false;
270
+ const { id, created } = this.upserted(res);
247
271
  return { ids: [id], changes: id === undefined ? 0 : 1, created };
248
272
  });
249
273
  }
250
- async internalUpsertMany(entity, conflictPaths, payload) {
274
+ async internalUpsertMany(entity, conflictPaths, payload, { update }) {
251
275
  refuseTriggers(entity);
276
+ if (update) {
277
+ const ids = [];
278
+ let changes = 0;
279
+ for (const row of payload) {
280
+ const written = await this.upsertWithUpdate(entity, conflictPaths, row, update);
281
+ ids.push(written.id);
282
+ changes += written.changes;
283
+ }
284
+ return { ids, changes };
285
+ }
252
286
  return this.timed('upsertMany', undefined, async () => {
253
287
  if (!payload?.length) {
254
288
  return { changes: 0 };
@@ -319,38 +353,19 @@ export class MongodbQuerier extends AbstractQuerier {
319
353
  get db() {
320
354
  return this.conn.db();
321
355
  }
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
- });
356
+ async openTransaction(_opts) {
357
+ this.logger.logInfo('beginTransaction');
358
+ await this.session?.endSession();
359
+ this.session = this.conn.startSession();
360
+ this.session.startTransaction();
332
361
  }
333
362
  /**
334
363
  * The driver owns the transaction state here and settles it in its own `finally`, so a failed commit
335
364
  * or abort still leaves `inTransaction()` false and the querier releasable.
336
365
  */
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
- });
366
+ async endTransaction(commit) {
367
+ this.logger.logInfo(commit ? 'commitTransaction' : 'rollbackTransaction');
368
+ await (commit ? this.session?.commitTransaction() : this.session?.abortTransaction());
354
369
  }
355
370
  async internalRelease() {
356
371
  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, SqlValues, TriggerRows, Type, UpsertOptions, 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,20 @@ 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
+ /**
21
+ * The clock in UTC, since `CURRENT_TIMESTAMP` is local time in the server's zone. No v7: `NEWSEQUENTIALID()` is
22
+ * an ordered v4 with no readable timestamp, so it is refused rather than served as one.
23
+ */
24
+ readonly sqlValues: SqlValues;
25
+ /** Only where the statement touched a row the trigger selects, since it fires once per statement, even for none. */
26
+ protected refusal(message: string, rows?: TriggerRows): string;
22
27
  /** [The hard server limit](https://github.com/yiisoft/yii2/issues/10371), not a driver preference. */
23
28
  readonly maxBindValues = 2100;
24
29
  /** `OUTPUT` has no trailing form: it sits between the column list and `VALUES`. */
25
30
  readonly returningPosition = "after-target";
26
31
  /** `OUTPUT` reads the written row off the `INSERTED` pseudo-table. */
27
32
  protected readonly returnedRowPrefix = "INSERTED.";
28
- readonly insertIdSource: InsertIdSource;
29
33
  /** Holds the update key lock across the insert; without it two concurrent upserts of one key race. */
30
34
  protected readonly mergeTargetHint = " WITH (HOLDLOCK)";
31
35
  protected readonly statementTerminator = ";";
@@ -69,7 +73,7 @@ export declare class MsSqlDialect extends MergeSqlDialect {
69
73
  * carrying a trigger, and through a table it works whether one is there or not.
70
74
  */
71
75
  returningId<E>(meta: EntityMeta<E>): string;
72
- upsert<E>(ctx: QueryContext, entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[], extraReturning?: string): void;
76
+ upsert<E>(ctx: QueryContext, entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[], opts?: UpsertOptions<E>): void;
73
77
  /**
74
78
  * A statement writing rows, `write`, wrapped in what SQL Server needs around one. The table variable its
75
79
  * `OUTPUT` fills, typed as the id column is, and the read handing that back, uncounted so the batch
@@ -1,4 +1,4 @@
1
- import { relationTermKey } from '../dialect/abstractSqlDialect.js';
1
+ import { ANSI_SQL_VALUES, fromRows, relationTermKey, } from '../dialect/abstractSqlDialect.js';
2
2
  import { AGGREGATE_VALUE_ALIAS, JSON_PULL_ALIAS } from '../dialect/aliases.js';
3
3
  import { BYTES_PREFIX } from '../dialect/hydrateColumn.js';
4
4
  import { jsonArraySlotArgs, jsonPath, jsonSlotArgs } from '../dialect/jsonSql.js';
@@ -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,12 +40,14 @@ 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',
44
47
  layout: 'tableFirst',
45
48
  scope: 'schema',
46
49
  before: false,
50
+ deferrable: false,
47
51
  },
48
52
  };
49
53
  /** The `type` `OPENJSON` reports for the JSON scalar an element is compared with; anything else binds as a string. */
@@ -72,7 +76,6 @@ export class MsSqlDialect extends MergeSqlDialect {
72
76
  type: this.escapeId('type'),
73
77
  };
74
78
  autoIncrementSuffix = 'IDENTITY(1,1)';
75
- tableOptions = '';
76
79
  beginTransactionCommand = 'BEGIN TRANSACTION';
77
80
  commitTransactionCommand = 'COMMIT TRANSACTION';
78
81
  rollbackTransactionCommand = 'ROLLBACK TRANSACTION';
@@ -81,15 +84,27 @@ export class MsSqlDialect extends MergeSqlDialect {
81
84
  * as statements would run; `MsSqlQuerier` opens its transactions through the driver instead.
82
85
  */
83
86
  isolationLevelStrategy = 'set-before';
84
- dropIndexSyntax = 'on-table';
85
87
  booleanLiteral = 'integer';
88
+ /**
89
+ * The clock in UTC, since `CURRENT_TIMESTAMP` is local time in the server's zone. No v7: `NEWSEQUENTIALID()` is
90
+ * an ordered v4 with no readable timestamp, so it is refused rather than served as one.
91
+ */
92
+ sqlValues = {
93
+ ...ANSI_SQL_VALUES,
94
+ currentTimestamp: 'SYSUTCDATETIME()',
95
+ uuid: 'NEWID()',
96
+ };
97
+ /** Only where the statement touched a row the trigger selects, since it fires once per statement, even for none. */
98
+ refusal(message, rows) {
99
+ const touched = rows ? `IF EXISTS (SELECT 1${fromRows(rows)}) ` : '';
100
+ return `${touched}THROW 50000, ${message}, 1;`;
101
+ }
86
102
  /** [The hard server limit](https://github.com/yiisoft/yii2/issues/10371), not a driver preference. */
87
103
  maxBindValues = 2100;
88
104
  /** `OUTPUT` has no trailing form: it sits between the column list and `VALUES`. */
89
105
  returningPosition = 'after-target';
90
106
  /** `OUTPUT` reads the written row off the `INSERTED` pseudo-table. */
91
107
  returnedRowPrefix = 'INSERTED.';
92
- insertIdSource = 'returning';
93
108
  /** Holds the update key lock across the insert; without it two concurrent upserts of one key race. */
94
109
  mergeTargetHint = ' WITH (HOLDLOCK)';
95
110
  statementTerminator = ';';
@@ -163,10 +178,10 @@ export class MsSqlDialect extends MergeSqlDialect {
163
178
  */
164
179
  returningId(meta) {
165
180
  const expression = this.returningIdExpression(meta);
166
- return expression ? `OUTPUT ${expression} INTO ${OUTPUT_TABLE}` : '';
181
+ return expression ? this.mergeReturning(expression) : '';
167
182
  }
168
- upsert(ctx, entity, conflictPaths, payload, extraReturning = '') {
169
- this.writeRows(ctx, getMeta(entity), payload, () => super.upsert(ctx, entity, conflictPaths, payload, extraReturning));
183
+ upsert(ctx, entity, conflictPaths, payload, opts) {
184
+ this.writeRows(ctx, getMeta(entity), payload, () => super.upsert(ctx, entity, conflictPaths, payload, opts));
170
185
  }
171
186
  /**
172
187
  * A statement writing rows, `write`, wrapped in what SQL Server needs around one. The table variable its
@@ -216,7 +231,7 @@ export class MsSqlDialect extends MergeSqlDialect {
216
231
  return `N'${escapeSingleQuotes(value)}'`;
217
232
  }
218
233
  if (value instanceof Uint8Array) {
219
- return `0x${Array.from(value, (byte) => byte.toString(16).padStart(2, '0')).join('')}`;
234
+ return `0x${bytesToHex(value)}`;
220
235
  }
221
236
  return super.escape(value);
222
237
  }
@@ -1,12 +1,15 @@
1
1
  import { PgLikeSqlDialect } from '../dialect/pgLikeSqlDialect.js';
2
- import type { QueryConflictPaths, QueryContext, SqlDialectFeatures, SqlDialectName, Type } from '../type/index.js';
2
+ import type { QueryContext, SqlDialectFeatures, SqlDialectName, SqlValues, Type } from '../type/index.js';
3
3
  /** PostgreSQL, under every driver: `pg`, Neon, PGlite, `bun:sql`. Adds pgvector and the `xmax` upsert `created`. */
4
4
  export declare class PostgresDialect extends PgLikeSqlDialect {
5
5
  readonly dialectName: SqlDialectName;
6
6
  readonly vectorExtension: string | undefined;
7
7
  /** pgvector is the only engine with `halfvec` and `sparsevec`. */
8
8
  readonly features: SqlDialectFeatures;
9
- upsert<E>(ctx: QueryContext, entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[]): void;
9
+ /** `uuidv7()` is Postgres 18+; an older server refuses it itself. */
10
+ readonly sqlValues: SqlValues;
11
+ /** The xmax system column is 0 for a newly inserted row and non-zero for an updated one (MVCC). */
12
+ protected readonly upsertCreatedReturning: string;
10
13
  /**
11
14
  * `to_regclass` rather than a `::regclass` cast: it answers `NULL` for a table that does not exist
12
15
  * (mid-migration, say) where the cast throws. `GREATEST` because a table nothing has analyzed yet
@@ -1,5 +1,5 @@
1
- import { AGGREGATE_VALUE_ALIAS } from '../dialect/aliases.js';
2
- import { PG_FEATURES, PgLikeSqlDialect } from '../dialect/pgLikeSqlDialect.js';
1
+ import { AGGREGATE_VALUE_ALIAS, UPSERT_CREATED_ALIAS } from '../dialect/aliases.js';
2
+ import { PG_FEATURES, PG_SQL_VALUES, 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`. */
5
5
  export class PostgresDialect extends PgLikeSqlDialect {
@@ -7,10 +7,10 @@ export class PostgresDialect extends PgLikeSqlDialect {
7
7
  vectorExtension = 'vector';
8
8
  /** pgvector is the only engine with `halfvec` and `sparsevec`. */
9
9
  features = { ...PG_FEATURES, narrowVectorTypes: true };
10
- upsert(ctx, entity, conflictPaths, payload) {
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')}`);
13
- }
10
+ /** `uuidv7()` is Postgres 18+; an older server refuses it itself. */
11
+ sqlValues = { ...PG_SQL_VALUES, uuidv7: 'uuidv7()' };
12
+ /** The xmax system column is 0 for a newly inserted row and non-zero for an updated one (MVCC). */
13
+ upsertCreatedReturning = `(xmax = 0) AS ${this.escapeId(UPSERT_CREATED_ALIAS)}`;
14
14
  /**
15
15
  * `to_regclass` rather than a `::regclass` cast: it answers `NULL` for a table that does not exist
16
16
  * (mid-migration, say) where the cast throws. `GREATEST` because a table nothing has analyzed yet
@@ -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, UpsertOptions, 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
  */
@@ -126,22 +127,22 @@ export declare abstract class AbstractQuerier implements Querier {
126
127
  */
127
128
  private unversionedUpdate;
128
129
  /** Fires `beforeUpsert`/`afterUpsert`: which branch a row takes is the database's to decide, so neither the insert's nor the update's pair fits. */
129
- upsertOne<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: EntityWrite<E>): Promise<QueryUpsertOneResult<E>>;
130
- upsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: readonly EntityWrite<E>[]): Promise<QueryUpsertManyResult<E>>;
130
+ upsertOne<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: EntityWrite<E>, opts?: UpsertOptions<E>): Promise<QueryUpsertOneResult<E>>;
131
+ upsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: readonly EntityWrite<E>[], opts?: UpsertOptions<E>): Promise<QueryUpsertManyResult<E>>;
131
132
  /**
132
133
  * An upsert on an entity a `security` filter guards. `ON CONFLICT` updates the conflicting row whoever
133
134
  * it belongs to, so the rows the conflict names are read through the filter: those found update, the
134
135
  * rest insert, where another tenant's row fails on its key. See architecture/security-filter-writes.md.
135
136
  */
136
137
  private guardedUpsert;
137
- protected abstract internalUpsertOne<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: EntityData<E>): Promise<QueryUpdateResult>;
138
- protected abstract internalUpsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: EntityData<E>[]): Promise<QueryUpdateResult>;
138
+ protected abstract internalUpsertOne<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E, opts: UpsertOptions<E>): Promise<QueryUpdateResult>;
139
+ protected abstract internalUpsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E[], opts: UpsertOptions<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.