uql-orm 0.99.0 → 0.100.1

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 (174) hide show
  1. package/LICENSE.md +22 -0
  2. package/README.md +1 -1
  3. package/dist/browser/uql-browser.min.js +2 -2
  4. package/dist/browser/uql-browser.min.js.map +5 -5
  5. package/dist/bunSql/bunSql.util.js +2 -2
  6. package/dist/bunSql/bunSqlQuerier.js +0 -1
  7. package/dist/bunSql/bunSqlQuerierPool.js +1 -1
  8. package/dist/cockroachdb/cockroachDialect.js +1 -0
  9. package/dist/context/context.browser.d.ts +5 -0
  10. package/dist/context/context.browser.js +21 -11
  11. package/dist/context/context.d.ts +5 -0
  12. package/dist/context/context.js +8 -3
  13. package/dist/dialect/abstractDialect.js +4 -2
  14. package/dist/dialect/abstractSqlDialect.d.ts +5 -5
  15. package/dist/dialect/abstractSqlDialect.js +26 -18
  16. package/dist/dialect/aliases.d.ts +0 -2
  17. package/dist/dialect/aliases.js +0 -2
  18. package/dist/dialect/hydrateColumn.d.ts +3 -3
  19. package/dist/dialect/hydrateColumn.js +1 -0
  20. package/dist/dialect/index.js +0 -2
  21. package/dist/dialect/jsonSql.d.ts +2 -3
  22. package/dist/dialect/jsonSql.js +4 -6
  23. package/dist/dialect/mysqlLikeSqlDialect.d.ts +1 -1
  24. package/dist/dialect/mysqlLikeSqlDialect.js +5 -3
  25. package/dist/dialect/operators.d.ts +2 -3
  26. package/dist/dialect/operators.js +3 -4
  27. package/dist/dialect/pgLikeSqlDialect.js +12 -12
  28. package/dist/entity/decorator/members.d.ts +4 -12
  29. package/dist/entity/metadata/definition.js +8 -5
  30. package/dist/http/handler.d.ts +6 -6
  31. package/dist/http/handler.js +20 -5
  32. package/dist/index.d.ts +6 -5
  33. package/dist/index.js +6 -5
  34. package/dist/{maria → mariadb}/mariadbQuerier.js +1 -1
  35. package/dist/migrate/builder/columnBuilder.d.ts +3 -3
  36. package/dist/migrate/builder/columnBuilder.js +1 -1
  37. package/dist/migrate/builder/index.d.ts +0 -3
  38. package/dist/migrate/builder/index.js +0 -3
  39. package/dist/migrate/builder/migrationBuilder.d.ts +6 -6
  40. package/dist/migrate/builder/migrationBuilder.js +7 -7
  41. package/dist/migrate/builder/tableBuilder.d.ts +25 -25
  42. package/dist/migrate/builder/tableBuilder.js +5 -5
  43. package/dist/migrate/builder/types.d.ts +37 -37
  44. package/dist/migrate/cli-config.d.ts +11 -1
  45. package/dist/migrate/cli-config.js +20 -6
  46. package/dist/migrate/cli.js +9 -18
  47. package/dist/migrate/codegen/entityCodeGenerator.js +1 -1
  48. package/dist/migrate/codegen/migrationFile.d.ts +7 -7
  49. package/dist/migrate/codegen/migrationFile.js +11 -12
  50. package/dist/migrate/ddl/indexCapabilities.d.ts +2 -0
  51. package/dist/migrate/ddl/indexCapabilities.js +6 -0
  52. package/dist/migrate/ddl/indexDdl.d.ts +8 -0
  53. package/dist/migrate/ddl/indexDdl.js +22 -6
  54. package/dist/migrate/generator/definitionToNode.d.ts +1 -1
  55. package/dist/migrate/generator/definitionToNode.js +1 -1
  56. package/dist/migrate/index.d.ts +1 -3
  57. package/dist/migrate/index.js +0 -3
  58. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +11 -15
  59. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +13 -15
  60. package/dist/migrate/introspection/mssqlIntrospector.d.ts +5 -5
  61. package/dist/migrate/introspection/mssqlIntrospector.js +24 -28
  62. package/dist/migrate/introspection/mysqlIntrospector.d.ts +5 -5
  63. package/dist/migrate/introspection/mysqlIntrospector.js +31 -37
  64. package/dist/migrate/introspection/postgresIntrospector.d.ts +13 -13
  65. package/dist/migrate/introspection/postgresIntrospector.js +35 -39
  66. package/dist/migrate/introspection/registry.js +1 -1
  67. package/dist/migrate/introspection/sqliteIntrospector.d.ts +6 -4
  68. package/dist/migrate/introspection/sqliteIntrospector.js +15 -12
  69. package/dist/migrate/migrationLock.d.ts +38 -0
  70. package/dist/migrate/migrationLock.js +103 -0
  71. package/dist/migrate/migrationTarget.d.ts +6 -2
  72. package/dist/migrate/migrationTarget.js +30 -14
  73. package/dist/migrate/migrator.d.ts +39 -23
  74. package/dist/migrate/migrator.js +110 -74
  75. package/dist/migrate/schemaGenerator.d.ts +3 -1
  76. package/dist/migrate/schemaGenerator.js +14 -5
  77. package/dist/migrate/storage/databaseStorage.d.ts +28 -20
  78. package/dist/migrate/storage/databaseStorage.js +36 -54
  79. package/dist/migrate/storage/index.d.ts +0 -1
  80. package/dist/migrate/storage/index.js +0 -1
  81. package/dist/{mongo → mongodb}/index.d.ts +0 -1
  82. package/dist/{mongo → mongodb}/index.js +0 -1
  83. package/dist/{mongo → mongodb}/mongoCommand.d.ts +17 -1
  84. package/dist/{mongo → mongodb}/mongoCommand.js +15 -2
  85. package/dist/{mongo → mongodb}/mongoDialect.js +8 -12
  86. package/dist/{mongo → mongodb}/mongoIntrospector.js +12 -3
  87. package/dist/{mongo → mongodb}/mongoMigrationStorage.d.ts +5 -5
  88. package/dist/{mongo → mongodb}/mongoMigrationStorage.js +8 -12
  89. package/dist/{mongo → mongodb}/mongoQuerier.d.ts +3 -1
  90. package/dist/{mongo → mongodb}/mongoSchemaGenerator.d.ts +11 -1
  91. package/dist/{mongo → mongodb}/mongoSchemaGenerator.js +56 -11
  92. package/dist/{mongo → mongodb}/mongodbQuerier.d.ts +7 -18
  93. package/dist/{mongo → mongodb}/mongodbQuerier.js +44 -78
  94. package/dist/mssql/mssqlDialect.d.ts +6 -4
  95. package/dist/mssql/mssqlDialect.js +20 -10
  96. package/dist/mssql/mssqlQuerier.d.ts +2 -2
  97. package/dist/mssql/mssqlQuerier.js +3 -3
  98. package/dist/mssql/mssqlQuerierPool.d.ts +1 -1
  99. package/dist/mssql/mssqlQuerierPool.js +2 -2
  100. package/dist/mysql/mysql2Querier.js +1 -5
  101. package/dist/namingStrategy/defaultNamingStrategy.d.ts +0 -1
  102. package/dist/namingStrategy/defaultNamingStrategy.js +0 -3
  103. package/dist/pglite/pgliteDialect.d.ts +3 -0
  104. package/dist/pglite/pgliteDialect.js +3 -1
  105. package/dist/pglite/pgliteQuerier.d.ts +2 -0
  106. package/dist/pglite/pgliteQuerier.js +4 -0
  107. package/dist/postgres/postgresDialect.d.ts +3 -4
  108. package/dist/postgres/postgresDialect.js +5 -6
  109. package/dist/querier/abstractQuerier.d.ts +119 -36
  110. package/dist/querier/abstractQuerier.js +465 -161
  111. package/dist/querier/abstractQuerierPool.d.ts +5 -6
  112. package/dist/querier/abstractQuerierPool.js +20 -6
  113. package/dist/querier/abstractSqlQuerier.d.ts +15 -10
  114. package/dist/querier/abstractSqlQuerier.js +54 -47
  115. package/dist/querier/abstractSqlQuerierPool.d.ts +5 -3
  116. package/dist/querier/abstractSqlQuerierPool.js +7 -4
  117. package/dist/querier/transaction.d.ts +46 -0
  118. package/dist/querier/transaction.js +56 -0
  119. package/dist/schema/canonicalType.js +2 -2
  120. package/dist/schema/schemaASTDiffer.d.ts +11 -3
  121. package/dist/schema/schemaASTDiffer.js +20 -8
  122. package/dist/sqlite/nodeSqliteQuerierPool.d.ts +1 -1
  123. package/dist/sqlite/nodeSqliteQuerierPool.js +1 -1
  124. package/dist/sqlite/sqliteDialect.d.ts +1 -1
  125. package/dist/sqlite/sqliteDialect.js +3 -1
  126. package/dist/sqlite/sqliteQuerier.d.ts +2 -0
  127. package/dist/sqlite/sqliteQuerier.js +4 -0
  128. package/dist/sqlite/sqliteQuerierPool.d.ts +4 -4
  129. package/dist/sqlite/sqliteQuerierPool.js +1 -1
  130. package/dist/type/dialect.d.ts +16 -2
  131. package/dist/type/entity.d.ts +32 -32
  132. package/dist/type/migration.d.ts +10 -27
  133. package/dist/type/namingStrategy.d.ts +0 -4
  134. package/dist/type/querier.d.ts +18 -10
  135. package/dist/type/query.d.ts +7 -22
  136. package/dist/type/queryRaw.d.ts +11 -6
  137. package/dist/type/queryRaw.js +2 -3
  138. package/dist/type/universalQuerier.d.ts +26 -28
  139. package/dist/type/utility.d.ts +7 -2
  140. package/dist/util/dialect.util.d.ts +2 -2
  141. package/dist/util/dialect.util.js +4 -1
  142. package/dist/util/field.util.d.ts +12 -0
  143. package/dist/util/field.util.js +24 -0
  144. package/dist/util/hook.util.d.ts +3 -2
  145. package/dist/util/query.util.d.ts +5 -0
  146. package/dist/util/query.util.js +34 -1
  147. package/dist/util/raw.d.ts +8 -2
  148. package/dist/util/raw.js +22 -0
  149. package/dist/util/relationQuery.util.d.ts +2 -0
  150. package/dist/util/relationQuery.util.js +4 -0
  151. package/dist/util/sql.util.d.ts +0 -5
  152. package/dist/util/sql.util.js +3 -9
  153. package/dist/util/uqlError.d.ts +0 -6
  154. package/dist/util/uqlError.js +0 -5
  155. package/package.json +20 -26
  156. package/skills/uql-orm/SKILL.md +13 -10
  157. package/dist/migrate/storage/jsonStorage.d.ts +0 -14
  158. package/dist/migrate/storage/jsonStorage.js +0 -33
  159. /package/dist/{maria → mariadb}/index.d.ts +0 -0
  160. /package/dist/{maria → mariadb}/index.js +0 -0
  161. /package/dist/{maria → mariadb}/mariaDialect.d.ts +0 -0
  162. /package/dist/{maria → mariadb}/mariaDialect.js +0 -0
  163. /package/dist/{maria → mariadb}/mariadbQuerier.d.ts +0 -0
  164. /package/dist/{maria → mariadb}/mariadbQuerierPool.d.ts +0 -0
  165. /package/dist/{maria → mariadb}/mariadbQuerierPool.js +0 -0
  166. /package/dist/{mongo → mongodb}/mongoDialect.d.ts +0 -0
  167. /package/dist/{mongo → mongodb}/mongoIntrospector.d.ts +0 -0
  168. /package/dist/{mongo → mongodb}/mongoQuerier.js +0 -0
  169. /package/dist/{mongo → mongodb}/mongodbQuerierPool.d.ts +0 -0
  170. /package/dist/{mongo → mongodb}/mongodbQuerierPool.js +0 -0
  171. /package/dist/{mongo → mongodb}/textLanguage.d.ts +0 -0
  172. /package/dist/{mongo → mongodb}/textLanguage.js +0 -0
  173. /package/dist/{mongo → mongodb}/vectorDistance.d.ts +0 -0
  174. /package/dist/{mongo → mongodb}/vectorDistance.js +0 -0
@@ -1,10 +1,11 @@
1
- import { assertSoleId, getMeta, idOf, namesKey, relationOf } from '../entity/index.js';
1
+ import { assertSoleId, getMeta, idOf, namesKey, relationOf, soleIdOf } from '../entity/index.js';
2
2
  import { namesRows } from '../dialect/operators.js';
3
3
  import { parseQueryLock } from '../type/index.js';
4
- import { cascadesOnDelete, childrenOf, chunk, clone, entityName, fillOnFields, filterFieldKeys, filterPersistableRelationKeys, forEachRequestedRelation, getKeys, hasKeys, getRelationRequestSummary, guardWrite, idOnlyQuery, keySet, isPagedQuery, isScalarId, LoggerWrapper, parentJoins, queryLoggerFor, parseRelationAtKey, parseRelationQueryValue, rowKey, runHooks, securityConditions, someKey, targetKeyColumns, whereEach, whereIds, whereKeysIn, whereWith, withoutSoftDeleteFilter, } from '../util/index.js';
4
+ import { cascadesOnDelete, childrenOf, chunk, clone, entityName, fillOnFields, filterFieldKeys, filterPersistableRelationKeys, forEachRequestedRelation, getKeys, hasKeys, holdsForeignKey, getRelationRequestSummary, guardWrite, idOnlyQuery, keySet, isPagedQuery, isScalarId, LoggerWrapper, normalizeScalarFieldSelection, parentJoins, queryLoggerFor, parseRelationAtKey, parseRelationQueryValue, rowKey, runHooks, securityConditions, someKey, targetKeyColumns, whereEach, whereIds, whereKeysIn, whereWith, withoutSoftDeleteFilter, } from '../util/index.js';
5
5
  import { UqlOptimisticLockError, UqlUsageError } from '../util/uqlError.js';
6
6
  import { keysetRead } from './keyset.js';
7
7
  import { enrichError } from './queryError.js';
8
+ import { awaitTurn, claim, currentTransaction, depthOf, free, inTransaction, newScope, slotOf, } from './transaction.js';
8
9
  /**
9
10
  * Refuses a nullish id, which would reduce to no filter at all, and a composite id missing a column,
10
11
  * which would address every row agreeing on the rest. Callers are `async`, so it always rejects.
@@ -92,9 +93,7 @@ function writtenIds(meta, rows) {
92
93
  * to, and writes no relation.
93
94
  */
94
95
  function upsertsByReading(meta, rows, update) {
95
- const relates = (payload) => filterPersistableRelationKeys(meta, payload, 'persist').length > 0;
96
- return (securityConditions(meta).length > 0 ||
97
- (relates(meta.relations) && (rows.some(relates) || (update !== undefined && relates(update)))));
96
+ return securityConditions(meta).length > 0 || writesRelations(meta, update ? [...rows, update] : rows);
98
97
  }
99
98
  /** What `ON CONFLICT` assigns a row it finds by default: the payload, less the columns it matched on. */
100
99
  function conflictAssignments(row, conflictPaths) {
@@ -135,6 +134,42 @@ function isEntityFirst(args) {
135
134
  const [first] = args;
136
135
  return typeof first === 'function' && first.prototype !== undefined;
137
136
  }
137
+ /** The fields `returning` projects, read as `$select` is, or `undefined` where it names none: the write reads nothing back. */
138
+ function returnedKeys(meta, returning) {
139
+ return hasKeys(returning) ? normalizeScalarFieldSelection(meta, returning) : undefined;
140
+ }
141
+ /** How a delete reads the rows it removes: a hard one takes already-soft-deleted rows too, so it has to see them. */
142
+ function deletableRows(opts) {
143
+ return opts?.hardDelete ? { ...opts, filters: withoutSoftDeleteFilter(opts.filters) } : opts;
144
+ }
145
+ /** `row` with only the fields `keys` names. */
146
+ function pickFields(row, keys) {
147
+ const picked = {};
148
+ for (const key of keys) {
149
+ picked[key] = row[key];
150
+ }
151
+ return picked;
152
+ }
153
+ /** Whether any payload writes a relation it cascades to, which makes the write several statements. */
154
+ function writesRelations(meta, payloads) {
155
+ return payloads.some((payload) => filterPersistableRelationKeys(meta, payload, 'persist').length > 0);
156
+ }
157
+ /** The relations a payload writes whose rows hold the parent's key: written after the parent, by its id. */
158
+ function childRelationKeys(meta, payload) {
159
+ return filterPersistableRelationKeys(meta, payload, 'persist').filter((relKey) => !holdsForeignKey(relationOf(meta, relKey)));
160
+ }
161
+ /** A relation's value as the rows it lists: a to-many's list, a to-one's row, none for `null`. */
162
+ function listedRows(value) {
163
+ return value == null ? [] : Array.isArray(value) ? value : [value];
164
+ }
165
+ /** What a savepoint the querier names is called, its depth appended. */
166
+ const SAVEPOINT_PREFIX = '_uql_sp';
167
+ /** Runs the callbacks a transaction gathered for its commit, in the order they were registered. */
168
+ async function runCallbacks(callbacks) {
169
+ for (const callback of callbacks) {
170
+ await callback();
171
+ }
172
+ }
138
173
  const STREAM_HOLDS_QUERIER = 'a stream is reading on this querier: run the statement after its loop, or on another querier';
139
174
  /** Base class for all database queriers. */
140
175
  export class AbstractQuerier {
@@ -153,10 +188,26 @@ export class AbstractQuerier {
153
188
  */
154
189
  released = false;
155
190
  logger;
191
+ /**
192
+ * The connection is in a state nothing here can name, so `release` discards it rather than hand it back: a
193
+ * rollback or a stream's close failed. The one place that decision is kept, whichever failure made it.
194
+ */
195
+ #unusable = false;
156
196
  constructor(extra) {
157
197
  this.extra = extra;
158
198
  this.logger = queryLoggerFor(extra);
159
199
  }
200
+ /**
201
+ * What the transaction this querier opens belongs to: the querier itself, its own connection, unless every
202
+ * querier of its pool is one session (SQLite, PGlite), whose queriers then name that handle and share it.
203
+ */
204
+ get connection() {
205
+ return this;
206
+ }
207
+ /** The transaction the connection holds, which every querier on it reads. */
208
+ get #slot() {
209
+ return slotOf(this.connection);
210
+ }
160
211
  /** What every read is checked for before it runs, whichever backend runs it. */
161
212
  validateReadQuery(entity, q) {
162
213
  this.assertLockable(entity, q);
@@ -172,7 +223,7 @@ export class AbstractQuerier {
172
223
  return;
173
224
  }
174
225
  this.dialect.assertLockSupported(entity, q);
175
- if (!this.hasOpenTransaction) {
226
+ if (!this.scopeHere()) {
176
227
  throw new UqlUsageError('$lock requires an open transaction');
177
228
  }
178
229
  }
@@ -235,6 +286,7 @@ export class AbstractQuerier {
235
286
  querier.#stream = stream;
236
287
  try {
237
288
  await querier.taskQueue;
289
+ await querier.#turn();
238
290
  for await (const row of rows) {
239
291
  if (loaded) {
240
292
  await loaded(row);
@@ -296,40 +348,111 @@ export class AbstractQuerier {
296
348
  aggregate(entity, q, opts) {
297
349
  return this.internalAggregate(entity, q, opts);
298
350
  }
299
- async insertOne(entity, payload) {
300
- const [id] = await this.insertMany(entity, [payload]);
301
- return id;
351
+ async insertOne(entity, payload, opts) {
352
+ const [written] = await this.writeReturning(entity, () => this.insertIds(entity, [payload]), opts);
353
+ return written;
354
+ }
355
+ async insertMany(entity, payload, opts) {
356
+ return this.writeReturning(entity, () => this.insertIds(entity, payload), opts);
302
357
  }
303
358
  /**
304
- * The `onInsert` values are filled here, before the write, so the after hooks and the ids read the
305
- * same rows the statement wrote.
359
+ * The ids of the rows inserted, in payload order. The `onInsert` values are filled before the write, so
360
+ * the after hooks and the ids read the same rows the statement wrote.
306
361
  */
307
- async insertMany(entity, payload) {
308
- if (!payload?.length) {
362
+ async insertIds(entity, payload) {
363
+ if (!payload.length) {
309
364
  return [];
310
365
  }
311
366
  const meta = getMeta(entity);
312
- return this.hooked(entity, 'Insert', payload, async (rows) => {
367
+ const insert = () => this.hooked(entity, 'Insert', payload, async (rows) => {
313
368
  await this.insertRows(entity, rows);
314
369
  return writtenIds(meta, rows);
315
370
  });
371
+ return writesRelations(meta, payload) ? this.atomically(insert) : insert();
372
+ }
373
+ /**
374
+ * The ids `write` reports, or, where `opts` asks for `returning`, the rows they name, read back in the same
375
+ * transaction with only the fields it lists.
376
+ */
377
+ writeReturning(entity, write, opts) {
378
+ const keys = returnedKeys(getMeta(entity), opts?.returning);
379
+ return keys ? this.atomically(async () => this.readWritten(entity, await write(), keys)) : write();
380
+ }
381
+ /** The rows `q` matches with the fields `keys` names and their keys, through `afterLoad` as a read's are. */
382
+ async readReturning(entity, q, keys, opts) {
383
+ const $select = keySet([...keys, ...getMeta(entity).ids]);
384
+ const rows = await this.internalFindMany(entity, { ...q, $select }, opts);
385
+ if (this.hasHook(entity, 'afterLoad')) {
386
+ await this.emitHook(entity, 'afterLoad', rows);
387
+ }
388
+ return rows;
389
+ }
390
+ /** The rows `ids` names, in their order, each with only the fields `keys` names. */
391
+ async readWritten(entity, ids, keys, opts) {
392
+ const meta = getMeta(entity);
393
+ const known = ids.filter((id) => id !== undefined);
394
+ if (known.length < ids.length) {
395
+ throw new UqlUsageError(`'returning' reads each written '${entity.name}' back by its key, which ${this.dialect.dialectName} did not report for every row: give the rows their own keys`);
396
+ }
397
+ if (!known.length) {
398
+ return [];
399
+ }
400
+ // The rows this write wrote, whatever a filter says of them: a soft-deleted one inserted is still written.
401
+ const read = { ...opts, filters: withoutSoftDeleteFilter(opts?.filters) };
402
+ const rows = [];
403
+ for (const batch of chunk(known, this.dialect.keyListCapacity(meta.ids.length))) {
404
+ rows.push(...(await this.readReturning(entity, { $where: whereIds(meta, batch) }, keys, read)));
405
+ }
406
+ const byKey = new Map(rows.map((row) => [rowKey(row, meta.ids), row]));
407
+ return known.flatMap((id) => {
408
+ const row = byKey.get(rowKey(whereIds(meta, id), meta.ids));
409
+ return row ? [pickFields(row, keys)] : [];
410
+ });
316
411
  }
317
- /** Fills and guards `rows`, then writes them and their relations: an insert, and the insert half of a read upsert. */
412
+ /**
413
+ * Writes `rows` and their relations: the to-ones they hold the keys of first, so each row inserts
414
+ * pointing at its own, then the rows, then their children by the keys the rows got. An insert, and the
415
+ * insert half of a read upsert.
416
+ */
318
417
  async insertRows(entity, rows) {
319
418
  const meta = getMeta(entity);
419
+ await this.writeHeldReferences(entity, rows);
320
420
  fillOnFields(meta, rows, 'onInsert');
321
421
  guardWrite(meta, rows, 'insert');
322
422
  await this.internalInsertMany(entity, rows);
323
- await this.insertRelations(entity, rows);
423
+ await this.insertChildren(entity, rows);
324
424
  }
325
425
  async updateOneById(entity, id, payload, opts) {
326
426
  assertIdValue(entity, id);
327
- return this.updateMany(entity, { $where: whereIds(getMeta(entity), id) }, payload, opts);
427
+ const updated = await this.updateWhere(entity, { $where: whereIds(getMeta(entity), id) }, payload, opts);
428
+ return typeof updated === 'number' ? updated : updated[0];
328
429
  }
329
- /** Settles the rows first where the update cascades, so a payload changing what `$where` reads still names them. */
330
430
  async updateMany(entity, q, payload, opts) {
431
+ return this.updateWhere(entity, q, payload, opts);
432
+ }
433
+ /**
434
+ * The number of rows the update changed, or the rows `returning` reads back: their ids settled first, so a
435
+ * payload changing what `$where` reads still names them, and read back by those ids in the same transaction.
436
+ */
437
+ async updateWhere(entity, q, payload, opts) {
331
438
  assertNamesRows(entity, 'updateMany', q, opts);
332
- return this.hooked(entity, 'Update', [payload], ([row]) => this.updateRows(entity, q, row, opts, getMeta(entity).version));
439
+ const meta = getMeta(entity);
440
+ const { returning, ...rest } = opts ?? {};
441
+ const keys = returnedKeys(meta, returning);
442
+ if (!keys) {
443
+ return this.updateMatching(entity, q, payload, opts);
444
+ }
445
+ return this.atomically(async () => {
446
+ const ids = await this.settleIds(entity, q, rest);
447
+ await this.updateMatching(entity, q, payload, rest);
448
+ return this.readWritten(entity, ids, keys, rest);
449
+ });
450
+ }
451
+ /** Updates the rows `q` matches between the update hooks, atomically where the payload writes relations too. */
452
+ updateMatching(entity, q, payload, opts) {
453
+ const meta = getMeta(entity);
454
+ const update = () => this.hooked(entity, 'Update', [payload], ([row]) => this.updateRows(entity, q, row, opts, meta.version));
455
+ return writesRelations(meta, [payload]) ? this.atomically(update) : update();
333
456
  }
334
457
  /**
335
458
  * The write every update runs, matching the version `lockKey` names where one is being held. Only a
@@ -337,9 +460,10 @@ export class AbstractQuerier {
337
460
  */
338
461
  async updateRows(entity, q, row, opts, lockKey) {
339
462
  const meta = getMeta(entity);
463
+ await this.writeHeldReferences(entity, [row]);
340
464
  fillOnFields(meta, [row], 'onUpdate');
341
465
  guardWrite(meta, [row], 'update');
342
- const relKeys = filterPersistableRelationKeys(meta, row, 'persist');
466
+ const relKeys = childRelationKeys(meta, row);
343
467
  const settles = !!relKeys.length || this.settlesWrite(entity, q);
344
468
  if (lockKey) {
345
469
  assertLockableUpdate(meta, q, settles);
@@ -357,7 +481,7 @@ export class AbstractQuerier {
357
481
  }
358
482
  const changes = await this.writeBatches(ids, meta.ids.length, (batch) => this.updateColumns(entity, { $where: whereIds(meta, batch) }, row, opts, batch.length));
359
483
  for (const relKey of relKeys) {
360
- await this.saveRelation(entity, relKey, ids.map((id) => ({ id, value: row[relKey] })), true);
484
+ await this.replaceChildren(entity, relKey, ids, row[relKey]);
361
485
  }
362
486
  return changes;
363
487
  }
@@ -406,9 +530,9 @@ export class AbstractQuerier {
406
530
  };
407
531
  return batches.length > 1 ? this.atomically(each) : each();
408
532
  }
409
- /** Runs a write split into several statements as one, in a transaction that joins an open one. */
533
+ /** Runs a write of several statements as one: in a transaction of its own, or the one already open. */
410
534
  atomically(write) {
411
- return this.transaction(write);
535
+ return this.scopeHere() ? write() : this.transaction(write);
412
536
  }
413
537
  /** The ids `q` matches, in its own order and page. */
414
538
  async settleIds(entity, q, opts) {
@@ -437,29 +561,23 @@ export class AbstractQuerier {
437
561
  unversionedUpdate(entity, q, payload, opts) {
438
562
  return this.hooked(entity, 'Update', [payload], ([row]) => this.updateRows(entity, q, row, opts, undefined));
439
563
  }
440
- /** 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. */
441
- async upsertOne(entity, conflictPaths, payload, update) {
442
- const meta = getMeta(entity);
443
- assertUnversioned(meta, "'upsertOne'");
444
- return this.hooked(entity, 'Upsert', [payload], async (rows) => {
445
- const { ids, changes, created } = upsertsByReading(meta, rows, update)
446
- ? await this.readThenUpsert(entity, conflictPaths, rows, update)
447
- : await this.internalUpsertOne(entity, conflictPaths, rows[0], update);
448
- adoptReportedIds(meta, rows, ids);
449
- const [id] = writtenIds(meta, rows);
450
- return { id, changes, created };
451
- });
564
+ async upsertOne(entity, conflictPaths, payload, update, opts) {
565
+ const [written] = await this.upsertMany(entity, conflictPaths, [payload], update, opts);
566
+ return written;
452
567
  }
453
- async upsertMany(entity, conflictPaths, payload, update) {
568
+ async upsertMany(entity, conflictPaths, payload, update, opts) {
454
569
  const meta = getMeta(entity);
455
- assertUnversioned(meta, "'upsertMany'");
456
- return this.hooked(entity, 'Upsert', payload, async (rows) => {
457
- const { ids, changes } = upsertsByReading(meta, rows, update)
570
+ assertUnversioned(meta, "'upsert'");
571
+ // Fires `beforeUpsert`/`afterUpsert`: which branch a row takes is the database's to decide, so neither
572
+ // the insert's nor the update's pair fits.
573
+ const upsert = () => this.hooked(entity, 'Upsert', payload, async (rows) => {
574
+ const ids = upsertsByReading(meta, rows, update)
458
575
  ? await this.readThenUpsert(entity, conflictPaths, rows, update)
459
576
  : await this.internalUpsertMany(entity, conflictPaths, rows, update);
460
577
  adoptReportedIds(meta, rows, ids);
461
- return { ids: writtenIds(meta, rows), changes };
578
+ return writtenIds(meta, rows);
462
579
  });
580
+ return this.writeReturning(entity, upsert, opts);
463
581
  }
464
582
  /**
465
583
  * An upsert as a read, then writes: the rows the conflict names are read through the filters, those found update
@@ -470,74 +588,96 @@ export class AbstractQuerier {
470
588
  const meta = getMeta(entity);
471
589
  guardWrite(meta, rows, 'insert');
472
590
  if (!rows.length) {
473
- return { changes: 0 };
591
+ return [];
474
592
  }
475
593
  const keys = getKeys(conflictPaths);
476
594
  const write = async () => {
477
595
  const ids = await this.idsByConflict(entity, conflictPaths, rows);
478
- let changes = 0;
479
596
  for (const [index, row] of rows.entries()) {
480
597
  // An empty `update` leaves a found row as it is, as `DO NOTHING` does.
481
598
  if (ids[index] !== undefined && (update === undefined || hasKeys(update))) {
482
599
  const q = { $where: whereEach(keys, (key) => row[key]) };
483
600
  // A copy each: the update fills its `onUpdate` fields into what it is handed.
484
601
  const assigned = update ? { ...update } : conflictAssignments(row, conflictPaths);
485
- changes += await this.updateRows(entity, q, assigned, undefined, undefined);
602
+ await this.updateRows(entity, q, assigned, { filters: withoutSoftDeleteFilter(undefined) }, undefined);
486
603
  }
487
604
  }
488
605
  const inserts = rows.filter((_, index) => ids[index] === undefined);
489
606
  if (inserts.length) {
490
607
  await this.insertRows(entity, inserts);
491
- changes += inserts.length;
492
608
  }
493
- const created = rows.length === 1 ? ids[0] === undefined : undefined;
494
609
  // A found row's key is adopted by the caller; an inserted one carries the key its insert wrote.
495
- return { changes, created, ids };
610
+ return ids;
496
611
  };
497
- return rows.length === 1 ? write() : this.atomically(write);
612
+ return rows.length > 1 || writesRelations(meta, [...rows, ...(update ? [update] : [])])
613
+ ? this.atomically(write)
614
+ : write();
498
615
  }
499
616
  async deleteOneById(entity, id, opts) {
500
617
  assertIdValue(entity, id);
501
- return this.deleteMany(entity, { $where: whereIds(getMeta(entity), id) }, opts);
618
+ const deleted = await this.deleteWhere(entity, { $where: whereIds(getMeta(entity), id) }, opts);
619
+ return typeof deleted === 'number' ? deleted : deleted[0];
502
620
  }
503
621
  async deleteMany(...args) {
504
622
  const [entity, q, opts] = entityArgs(args);
623
+ return this.deleteWhere(entity, q, opts);
624
+ }
625
+ /** The number of rows deleted, or the rows `returning` reads as they were, before the delete and in its transaction. */
626
+ async deleteWhere(entity, q, opts) {
505
627
  assertNamesRows(entity, 'deleteMany', q, opts);
628
+ const meta = getMeta(entity);
629
+ const { returning, ...rest } = opts ?? {};
630
+ const keys = returnedKeys(meta, returning);
631
+ if (!keys) {
632
+ return this.deleteRows(entity, q, opts);
633
+ }
634
+ return this.atomically(async () => {
635
+ const rows = await this.readReturning(entity, q, keys, deletableRows(rest));
636
+ await this.deleteRows(entity, q, rest);
637
+ return rows.map((row) => pickFields(row, keys));
638
+ });
639
+ }
640
+ async deleteRows(entity, q, opts) {
506
641
  const meta = getMeta(entity);
507
642
  const cascades = cascadesOnDelete(meta);
508
643
  const watched = this.hasHook(entity, 'beforeDelete') || this.hasHook(entity, 'afterDelete');
509
644
  if (!watched && !cascades && !this.settlesWrite(entity, q)) {
510
645
  return this.internalDeleteMany(entity, q, opts);
511
646
  }
512
- // A hard delete takes already-soft-deleted rows too, so reading them back has to see them.
513
- const readOpts = opts?.hardDelete ? { ...opts, filters: withoutSoftDeleteFilter(opts.filters) } : opts;
647
+ const readOpts = deletableRows(opts);
514
648
  // A hook receives the rows themselves; the ids read off them name the same rows a second read might not.
515
649
  const doomed = watched ? await this.internalFindMany(entity, q, readOpts) : [];
516
650
  const ids = watched ? doomed.map((row) => idOf(meta, row)) : await this.settleIds(entity, q, readOpts);
517
651
  if (!ids.length) {
518
652
  return 0;
519
653
  }
520
- await this.emitHook(entity, 'beforeDelete', doomed);
521
- const changes = await this.writeBatches(ids, meta.ids.length, async (batch) => {
522
- // Children first: they hold the foreign key, which a schema without `ON DELETE CASCADE` enforces.
523
- if (cascades) {
524
- await this.deleteRelations(entity, batch, opts);
525
- }
526
- return this.internalDeleteMany(entity, { $where: whereIds(meta, batch) }, opts);
527
- });
528
- await this.emitHook(entity, 'afterDelete', doomed);
529
- return changes;
654
+ const remove = async () => {
655
+ await this.emitHook(entity, 'beforeDelete', doomed);
656
+ const changes = await this.writeBatches(ids, meta.ids.length, async (batch) => {
657
+ // Children first: they hold the foreign key, which a schema without `ON DELETE CASCADE` enforces.
658
+ if (cascades) {
659
+ await this.deleteChildren(entity, batch, opts);
660
+ }
661
+ return this.internalDeleteMany(entity, { $where: whereIds(meta, batch) }, opts);
662
+ });
663
+ await this.emitHook(entity, 'afterDelete', doomed);
664
+ return changes;
665
+ };
666
+ return cascades ? this.atomically(remove) : remove();
667
+ }
668
+ async saveOne(entity, payload, opts) {
669
+ const [written] = await this.writeReturning(entity, () => this.saveIds(entity, [payload]), opts);
670
+ return written;
530
671
  }
531
- async saveOne(entity, payload) {
532
- const [id] = await this.saveMany(entity, [payload]);
533
- return id;
672
+ async saveMany(entity, payload, opts) {
673
+ return this.writeReturning(entity, () => this.saveIds(entity, payload), opts);
534
674
  }
535
675
  /**
536
676
  * Whether a row names its key decides its statement, never whether the row exists: a named row
537
677
  * upserts on that key, so a stale id is written rather than silently missed, and an unnamed one
538
678
  * inserts. A composite is always named. The hooks follow the statement: a named row fires the upsert pair.
539
679
  */
540
- async saveMany(entity, payload) {
680
+ async saveIds(entity, payload) {
541
681
  const meta = getMeta(entity);
542
682
  assertUnversioned(meta, "'save'");
543
683
  // Indexes, not rows: the result is reported in payload order so it can be zipped with what was
@@ -564,14 +704,14 @@ export class AbstractQuerier {
564
704
  }
565
705
  const write = async () => {
566
706
  if (toInsert.length) {
567
- const inserted = await this.insertMany(entity, toInsert.map((index) => payload[index]));
707
+ const inserted = await this.insertIds(entity, toInsert.map((index) => payload[index]));
568
708
  for (let position = 0; position < toInsert.length; position++) {
569
709
  ids[toInsert[position]] = inserted[position];
570
710
  }
571
711
  }
572
712
  if (toUpsert.length) {
573
713
  const conflictPaths = keySet(meta.ids);
574
- const { ids: upserted } = await this.upsertMany(entity, conflictPaths, toUpsert.map((index) => payload[index]));
714
+ const upserted = await this.upsertMany(entity, conflictPaths, toUpsert.map((index) => payload[index]));
575
715
  for (let position = 0; position < toUpsert.length; position++) {
576
716
  ids[toUpsert[position]] = upserted[position];
577
717
  }
@@ -580,101 +720,259 @@ export class AbstractQuerier {
580
720
  await (toInsert.length && toUpsert.length ? this.atomically(write) : write());
581
721
  return ids;
582
722
  }
583
- /** Writes each inserted row's relations, one set of statements per relation whatever the number of rows. */
584
- async insertRelations(entity, rows) {
723
+ /**
724
+ * Writes the target of each to-one `rows` hold the key of, and points each row at its own: a row naming
725
+ * only its key is a link and writes nothing, any other saves as `saveMany` does, and `null` clears the key.
726
+ */
727
+ async writeHeldReferences(entity, rows) {
585
728
  const meta = getMeta(entity);
586
- const [idKey] = meta.ids;
587
729
  for (const relKey of filterPersistableRelationKeys(meta, meta.relations, 'persist')) {
588
- const writes = rows.flatMap((row) => (row[relKey] == null ? [] : [{ id: row[idKey], value: row[relKey] }]));
589
- if (writes.length) {
590
- await this.saveRelation(entity, relKey, writes, false);
730
+ const relOpts = relationOf(meta, relKey);
731
+ const holding = rows.filter((row) => row[relKey] !== undefined);
732
+ if (!holdsForeignKey(relOpts) || !holding.length) {
733
+ continue;
734
+ }
735
+ const relMeta = getMeta(relOpts.entity());
736
+ const pointing = holding.flatMap((row) => listedRows(row[relKey]).map((target) => ({ row, target })));
737
+ const ids = await this.saveTargets(entity, relKey, pointing.map(({ target }) => target));
738
+ const columns = (target) => Object.fromEntries(relOpts.references.map(({ local, foreign }) => [local, target[foreign] ?? null]));
739
+ for (const row of holding) {
740
+ Object.assign(row, columns({}));
591
741
  }
742
+ pointing.forEach(({ row, target }, index) => {
743
+ Object.assign(row, columns({ ...target, ...whereIds(relMeta, ids[index]) }));
744
+ });
592
745
  }
593
746
  }
594
- /** `EntityId` because a settled composite row is an object, which {@link childrenOf} reads each foreign key column out of. */
595
- async deleteRelations(entity, ids, opts) {
747
+ /** Writes each inserted row's children, one set of statements per relation whatever the number of rows. */
748
+ async insertChildren(entity, rows) {
596
749
  const meta = getMeta(entity);
597
- const relKeys = filterPersistableRelationKeys(meta, meta.relations, 'delete');
598
- // Cascade forwards `opts` (including `hardDelete`); each child soft-deletes only if it can.
599
- for (const relKey of relKeys) {
600
- const relOpts = relationOf(meta, relKey);
601
- const relEntity = relOpts.entity();
602
- const target = relOpts.through ? relOpts.through() : relEntity;
603
- await this.deleteMany(target, { $where: childrenOf(parentJoins(relOpts, meta.ids.length), ids) }, opts);
750
+ const [idKey] = meta.ids;
751
+ for (const relKey of childRelationKeys(meta, meta.relations)) {
752
+ const writes = rows.flatMap((row) => (row[relKey] == null ? [] : [{ id: row[idKey], value: row[relKey] }]));
753
+ if (writes.length) {
754
+ assertSoleId(meta, 'saving a relation');
755
+ await this.saveChildren(entity, relKey, writes);
756
+ }
604
757
  }
605
758
  }
606
759
  /**
607
- * Writes each parent's value into one relation. The parent owns what it points at: an update replaces
608
- * it, and a `null` only clears it.
760
+ * Makes `value` the children of each parent `ids` names, which it owns: the rows it lists are saved,
761
+ * keeping what each does not write, and the parent's other children (a junction's other links) go.
609
762
  */
610
- async saveRelation(entity, relKey, writes, isUpdate) {
763
+ async replaceChildren(entity, relKey, ids, value) {
611
764
  const meta = getMeta(entity);
612
- // Writing the parent's key into a child is one column per key, and the helpers below read the first pair.
613
765
  assertSoleId(meta, 'saving a relation');
614
766
  const relOpts = relationOf(meta, relKey);
615
767
  const relEntity = relOpts.entity();
616
- if (relOpts.cardinality === 'm1') {
617
- return this.saveManyToOne(entity, relEntity, relOpts.references[0].local, writes);
618
- }
619
- const holder = relOpts.through ? relOpts.through() : relEntity;
768
+ const relMeta = getMeta(relEntity);
620
769
  const parentColumn = soleParentColumn(relOpts);
621
- if (isUpdate) {
622
- await this.writeBatches(writes, 1, (batch) => this.deleteMany(holder, { $where: { [parentColumn]: batch.map(({ id }) => id) } }));
770
+ const listed = listedRows(value);
771
+ if (relOpts.through) {
772
+ const holder = relOpts.through();
773
+ const [targetColumn] = targetKeyColumns(relOpts, 1);
774
+ const targetIds = await this.saveTargets(entity, relKey, listed);
775
+ await this.writeBatches(ids, 1, (batch) => this.deleteMany(holder, { $where: { [parentColumn]: batch, ...(targetIds.length && { [targetColumn]: { $nin: targetIds } }) } }, { hardDelete: true }));
776
+ const linked = await this.internalFindMany(holder, {
777
+ $where: { [parentColumn]: ids, [targetColumn]: targetIds },
778
+ });
779
+ const has = new Set(linked.map((link) => rowKey(link, [parentColumn, targetColumn])));
780
+ const links = ids.flatMap((id) => targetIds.map((targetId) => ({ [parentColumn]: id, [targetColumn]: targetId })));
781
+ const missing = links.filter((link) => !has.has(rowKey(link, [parentColumn, targetColumn])));
782
+ await this.insertMany(holder, missing);
783
+ return;
623
784
  }
785
+ const keptIds = listed.filter((row) => namesKey(relMeta, row)).map((row) => idOf(relMeta, row));
786
+ await this.writeBatches(ids, 1, (batch) => this.deleteMany(relEntity, {
787
+ $where: {
788
+ [parentColumn]: batch,
789
+ ...(keptIds.length && { [soleIdOf(relMeta, 'replacing the rows of a relation')]: { $nin: keptIds } }),
790
+ },
791
+ }));
792
+ await this.saveChildren(entity, relKey, ids.map((id) => ({ id, value })));
793
+ }
794
+ /** Writes each parent's children: rows pointed at their parent, or targets linked through the junction. */
795
+ async saveChildren(entity, relKey, writes) {
796
+ const relOpts = relationOf(getMeta(entity), relKey);
797
+ const parentColumn = soleParentColumn(relOpts);
624
798
  // Each parent gets its own copies, so a row listed for two parents is written twice.
625
- const children = writes.flatMap(({ id, value }) => [value ?? []].flat().map((row) => ({ id, row })));
799
+ const children = writes.flatMap(({ id, value }) => listedRows(value).map((row) => ({ id, row })));
626
800
  if (!children.length) {
627
801
  return;
628
802
  }
629
803
  if (!relOpts.through) {
630
- await this.saveMany(relEntity, children.map(({ id, row }) => ({ ...row, [parentColumn]: id })));
804
+ await this.saveMany(relOpts.entity(), children.map(({ id, row }) => ({ ...row, [parentColumn]: id })));
631
805
  return;
632
806
  }
633
- const savedIds = await this.saveMany(relEntity, children.map(({ row }) => row));
634
- // A link needs the target's id, which a MySQL batch mixing supplied and generated keys cannot report.
635
- if (savedIds.includes(undefined)) {
636
- throw new UqlUsageError(`'${relEntity.name}' rows saved through '${holder.name}' reported no id, so they cannot be linked. ` +
807
+ const targetIds = await this.saveTargets(entity, relKey, children.map(({ row }) => row));
808
+ const [targetColumn] = targetKeyColumns(relOpts, 1);
809
+ await this.insertMany(relOpts.through(), children.map(({ id }, index) => ({ [parentColumn]: id, [targetColumn]: targetIds[index] })));
810
+ }
811
+ /**
812
+ * Saves the rows a relation points at, each one's id what the pointer needs: a MySQL batch mixing supplied and
813
+ * generated keys cannot report it, so one it could not is refused rather than left pointing nowhere.
814
+ */
815
+ async saveTargets(entity, relKey, rows) {
816
+ const relEntity = relationOf(getMeta(entity), relKey).entity();
817
+ const ids = await this.saveMany(relEntity, rows);
818
+ if (ids.includes(undefined)) {
819
+ throw new UqlUsageError(`'${relEntity.name}' rows saved through '${entity.name}.${relKey}' reported no id, so they cannot be pointed at. ` +
637
820
  'Insert them with their own ids, or save the relation in its own statement.');
638
821
  }
639
- const [targetColumn] = targetKeyColumns(relOpts, 1);
640
- await this.insertMany(holder, children.map(({ id }, index) => ({ [parentColumn]: id, [targetColumn]: savedIds[index] })));
822
+ return ids.filter((id) => id !== undefined);
823
+ }
824
+ /**
825
+ * Deletes the children of the parents `ids` names, as the parents go: a hard delete takes them all, a soft
826
+ * delete stamps those that can be stamped and keeps the rest, junction links included, for a restore.
827
+ * `EntityId` because a settled composite row is an object, which {@link childrenOf} reads each foreign key column out of.
828
+ */
829
+ async deleteChildren(entity, ids, opts) {
830
+ const meta = getMeta(entity);
831
+ const soft = !!meta.softDelete && !opts?.hardDelete;
832
+ for (const relKey of filterPersistableRelationKeys(meta, meta.relations, 'delete')) {
833
+ const relOpts = relationOf(meta, relKey);
834
+ const target = relOpts.through ? relOpts.through() : relOpts.entity();
835
+ if (soft && !getMeta(target).softDelete) {
836
+ continue;
837
+ }
838
+ const $where = childrenOf(parentJoins(relOpts, meta.ids.length), ids);
839
+ await this.deleteMany(target, { $where }, { ...opts, hardDelete: !soft });
840
+ }
641
841
  }
642
- /** Each parent gets its own referenced row, and its own column pointing at it. */
643
- async saveManyToOne(entity, relEntity, localColumn, writes) {
644
- // Before anything is written: the follow-up that points each row at its new relation carries no
645
- // version, and half an insert is worse than a refusal.
646
- assertUnversioned(getMeta(entity), 'save a to-one relation of');
647
- const pointing = writes.filter(({ value }) => value);
648
- const referenceIds = await this.insertMany(relEntity, pointing.map(({ value }) => value));
649
- for (const [index, { id }] of pointing.entries()) {
650
- assertIdValue(entity, id);
651
- await this.unversionedUpdate(entity, { $where: whereIds(getMeta(entity), id) }, { [localColumn]: referenceIds[index] });
842
+ /**
843
+ * The transaction this flow runs in on this connection, the innermost where they nest: the callback's,
844
+ * or a `beginTransaction` of this querier's. `undefined` outside one, or inside another flow's.
845
+ */
846
+ scopeHere() {
847
+ const held = this.#slot.held;
848
+ if (!held) {
849
+ return undefined;
850
+ }
851
+ const current = currentTransaction();
852
+ if (current?.slot === this.#slot) {
853
+ return current;
652
854
  }
855
+ return held.manual && held.scope.querier === this ? held.scope : undefined;
653
856
  }
654
857
  /**
655
- * Runs `callback` in a transaction, joining one already open. A rollback that fails is logged, never
656
- * thrown over the original error, and the connection stays with whoever acquired it.
858
+ * Runs `callback` in a transaction. Inside one this flow already runs, it is a savepoint: its failure undoes
859
+ * its own writes alone. A transaction another flow holds on this connection is waited for, never joined.
657
860
  */
658
861
  async transaction(callback, opts) {
659
- if (this.hasOpenTransaction) {
660
- return callback();
862
+ const here = this.scopeHere();
863
+ if (here) {
864
+ return this.nested(here, callback);
661
865
  }
866
+ const scope = newScope(this, this.#slot);
867
+ const result = await inTransaction(scope, async () => {
868
+ await this.open(scope, false, opts);
869
+ try {
870
+ const value = await callback();
871
+ await this.close(true);
872
+ return value;
873
+ }
874
+ catch (err) {
875
+ // Reported rather than thrown: the error being unwound is the useful one.
876
+ await this.rollbackTransaction().catch((rollbackErr) => {
877
+ this.logger.logError('rollback failed', rollbackErr);
878
+ });
879
+ throw err;
880
+ }
881
+ });
882
+ await runCallbacks(scope.onCommit);
883
+ return result;
884
+ }
885
+ /** A transaction inside `parent`, after any other it runs: a savepoint where the engine has them. */
886
+ nested(parent, callback) {
887
+ const scope = newScope(this, this.#slot, parent);
888
+ const run = parent.nested.then(() => inTransaction(scope, () => this.savepointed(scope, parent, callback)));
889
+ parent.nested = run.catch(() => undefined);
890
+ return run;
891
+ }
892
+ /** `callback` between a savepoint and its release, rolled back to it on failure, its `onCommit` callbacks kept only where it succeeds. */
893
+ async savepointed(scope, parent, callback) {
894
+ const name = `${SAVEPOINT_PREFIX}${depthOf(scope)}`;
895
+ await this.serialize(() => this.savepoint('open', name));
662
896
  try {
663
- await this.beginTransaction(opts);
664
- const res = await callback();
665
- await this.commitTransaction();
666
- return res;
897
+ const value = await callback();
898
+ await this.serialize(() => this.savepoint('release', name));
899
+ parent.onCommit.push(...scope.onCommit);
900
+ return value;
667
901
  }
668
902
  catch (err) {
669
- // Reported rather than thrown: the error being unwound is the useful one. Inline rather than
670
- // shared with `release` below, because this method is grafted onto plain objects in tests and
671
- // every `this.x` it reaches for has to exist there too.
672
- await this.rollbackTransaction().catch((rollbackErr) => {
673
- this.logger.logError('rollback failed', rollbackErr);
674
- });
903
+ await this.serialize(() => this.savepoint('rollback', name));
675
904
  throw err;
676
905
  }
677
906
  }
907
+ /**
908
+ * Opens, releases or rolls back to a savepoint, which a SQL engine overrides. Elsewhere (MongoDB) there is
909
+ * none, so a transaction inside another is refused: it could not undo its own writes apart.
910
+ */
911
+ savepoint(_kind, _name) {
912
+ return Promise.reject(new UqlUsageError(`${this.dialect.dialectName} has no savepoint to nest a transaction in another: run it on its own`));
913
+ }
914
+ /**
915
+ * Runs `callback` once the outermost transaction this flow is in commits, and dropped if it rolls back:
916
+ * a mail sent for a row that never landed is not sent. With no transaction open it runs now.
917
+ */
918
+ async onCommit(callback) {
919
+ const scope = this.scopeHere();
920
+ if (scope) {
921
+ scope.onCommit.push(callback);
922
+ return;
923
+ }
924
+ await callback();
925
+ }
926
+ /** Waits for the connection's transaction, if another flow holds one, then opens `scope`'s on it. */
927
+ async open(scope, manual, opts) {
928
+ await claim(this.#slot, scope, manual);
929
+ try {
930
+ await this.serialize(() => this.openTransaction(opts));
931
+ }
932
+ catch (err) {
933
+ free(this.#slot);
934
+ throw err;
935
+ }
936
+ }
937
+ /** Whether the transaction its connection holds is this querier's. */
938
+ holds() {
939
+ return this.#slot.held?.scope.querier === this;
940
+ }
941
+ /**
942
+ * Commits, or rolls back, the transaction this querier holds, in turn on its connection. With none held a
943
+ * rollback has nothing to do, and a commit refuses: a `release` inside the callback rolled it back.
944
+ */
945
+ close(commit) {
946
+ return this.serialize(async () => {
947
+ if (this.holds()) {
948
+ return this.end(commit);
949
+ }
950
+ if (commit) {
951
+ throw new UqlUsageError('the querier was released inside its transaction, which rolled back');
952
+ }
953
+ });
954
+ }
955
+ /**
956
+ * Commits, or rolls back, the transaction this querier holds. A commit that fails can leave it open (SQLite
957
+ * answers `SQLITE_BUSY` and keeps it) for the rollback after it; a failed rollback ends it, leaving the
958
+ * connection unusable.
959
+ */
960
+ async end(commit) {
961
+ try {
962
+ if (this.hasOpenTransaction) {
963
+ await this.endTransaction(commit);
964
+ }
965
+ }
966
+ catch (err) {
967
+ this.#unusable ||= !commit;
968
+ throw err;
969
+ }
970
+ finally {
971
+ if (!this.hasOpenTransaction) {
972
+ free(this.#slot);
973
+ }
974
+ }
975
+ }
678
976
  /** Whether anything at all - a global listener or the entity itself - handles `event`. */
679
977
  hasHook(entity, event) {
680
978
  return (this.extra?.listeners?.some((listener) => listener[event]) || (getMeta(entity).hooks?.[event]?.length ?? 0) > 0);
@@ -752,13 +1050,26 @@ export class AbstractQuerier {
752
1050
  for (const listener of this.extra?.listeners ?? []) {
753
1051
  await listener[event]?.({ entity, querier: this, payloads, event });
754
1052
  }
755
- await runHooks(entity, event, payloads, { querier: this });
1053
+ await runHooks(entity, event, payloads, { querier: this, onCommit: (callback) => this.onCommit(callback) });
756
1054
  }
757
- /** Runs `task` after everything already queued, one at a time. Not re-entrant: never nest `serialize` calls. */
1055
+ /**
1056
+ * Runs `task` after everything already queued, one at a time, once no transaction of another flow holds the
1057
+ * connection: a statement from outside one never lands in it. Not re-entrant: never nest `serialize` calls.
1058
+ */
758
1059
  serialize(task) {
1060
+ if (this.#slot.held && !this.scopeHere()) {
1061
+ return this.#turn().then(() => this.serialize(task));
1062
+ }
759
1063
  if (this.#stream) {
760
1064
  return Promise.reject(new UqlUsageError(STREAM_HOLDS_QUERIER));
761
1065
  }
1066
+ return this.enqueue(task);
1067
+ }
1068
+ /** Waits for a transaction another flow holds on the connection to end. */
1069
+ #turn() {
1070
+ return awaitTurn(this.#slot, () => !!this.scopeHere());
1071
+ }
1072
+ enqueue(task) {
762
1073
  const res = this.taskQueue.then(task);
763
1074
  this.taskQueue = res.catch(() => { });
764
1075
  return res;
@@ -796,57 +1107,50 @@ export class AbstractQuerier {
796
1107
  this.logger.logQuery(query, values, Math.round((answeredAt ?? performance.now()) - startTime));
797
1108
  }
798
1109
  }
799
- beginTransaction(opts) {
800
- return this.serialize(async () => {
801
- if (this.hasOpenTransaction) {
802
- throw new UqlUsageError('pending transaction');
803
- }
804
- await this.openTransaction(opts);
805
- });
1110
+ /** Opens a transaction that holds this querier until `commitTransaction` or `rollbackTransaction`, whatever flow calls them. */
1111
+ async beginTransaction(opts) {
1112
+ if (this.scopeHere()) {
1113
+ throw new UqlUsageError('pending transaction');
1114
+ }
1115
+ await this.open(newScope(this, this.#slot), true, opts);
806
1116
  }
807
1117
  /** Strict: this is the check that catches a forgotten `beginTransaction`. */
808
- commitTransaction() {
809
- return this.serialize(async () => {
810
- if (!this.hasOpenTransaction) {
811
- throw new UqlUsageError('not a pending transaction');
812
- }
813
- await this.endTransaction(true);
814
- });
1118
+ async commitTransaction() {
1119
+ const held = this.#slot.held;
1120
+ if (!held?.manual || held.scope.querier !== this) {
1121
+ throw new UqlUsageError('not a pending transaction');
1122
+ }
1123
+ await this.close(true);
1124
+ await runCallbacks(held.scope.onCommit);
815
1125
  }
816
1126
  /**
817
- * Rolls the open transaction back, or does nothing when there is none: it is called from `catch` and
818
- * `finally`, where the caller cannot know whether `beginTransaction` got far enough to open one.
1127
+ * Rolls back the transaction this querier holds, or does nothing when there is none: it is called from `catch`
1128
+ * and `finally`, where the caller cannot know whether `beginTransaction` got far enough to open one. A
1129
+ * transaction another flow's callback holds is waited for, and so has ended by then.
819
1130
  */
820
1131
  rollbackTransaction() {
821
- return this.serialize(async () => {
822
- if (this.hasOpenTransaction) {
823
- await this.endTransaction(false);
824
- }
825
- });
1132
+ return this.close(false);
826
1133
  }
827
1134
  /**
828
1135
  * Closes a stream left open and rolls back an unfinished transaction, then hands the connection back,
829
- * discarding it if either failed: the pool would otherwise take one still reading. Never throws first,
830
- * since `await using` has no other way to release.
1136
+ * discarding it where it is unusable: the pool would otherwise take one still reading, or in a state the
1137
+ * next borrower inherits. Never throws first, since `await using` has no other way to release.
831
1138
  */
832
1139
  async release() {
833
- let discard = false;
834
1140
  await this.#stream?.return(undefined).catch((err) => {
835
1141
  this.logger.logError('closing an open stream failed; discarding the connection', err);
836
- discard = true;
1142
+ this.#unusable = true;
1143
+ });
1144
+ await this.serialize(async () => {
1145
+ if (this.holds()) {
1146
+ this.logger.logWarn('rolling back a transaction left open at release');
1147
+ await this.end(false);
1148
+ }
1149
+ }).catch((err) => {
1150
+ this.logger.logError('rollback failed; discarding the connection', err);
837
1151
  });
838
- if (this.hasOpenTransaction) {
839
- this.logger.logWarn('rolling back a transaction left open at release');
840
- // The rollback doubles as a health check. One that succeeds proves the connection round-trips and
841
- // left no transaction behind, so it is safe to reuse. One that fails leaves a session state
842
- // nothing here can name, and the next borrower would inherit it.
843
- await this.rollbackTransaction().catch((err) => {
844
- this.logger.logError('rollback failed; discarding the connection', err);
845
- discard = true;
846
- });
847
- }
848
1152
  this.released = true;
849
- return this.serialize(() => this.internalRelease(discard));
1153
+ return this.enqueue(() => this.internalRelease(this.#unusable));
850
1154
  }
851
1155
  async [Symbol.asyncDispose]() {
852
1156
  return this.release();