uql-orm 0.102.6 → 0.103.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 (109) hide show
  1. package/README.md +1 -1
  2. package/dist/browser/uql-browser.min.js +2 -2
  3. package/dist/browser/uql-browser.min.js.map +3 -3
  4. package/dist/bunSql/bunSqlQuerier.d.ts +9 -3
  5. package/dist/bunSql/bunSqlQuerier.js +7 -15
  6. package/dist/cockroachdb/crdbQuerierPool.d.ts +2 -2
  7. package/dist/context/context.d.ts +0 -6
  8. package/dist/context/context.js +1 -7
  9. package/dist/d1/d1Querier.d.ts +18 -14
  10. package/dist/d1/d1Querier.js +21 -8
  11. package/dist/d1/d1QuerierPool.d.ts +0 -1
  12. package/dist/d1/d1QuerierPool.js +0 -1
  13. package/dist/d1/d1SqliteDialect.d.ts +2 -0
  14. package/dist/d1/d1SqliteDialect.js +3 -0
  15. package/dist/dialect/abstractDialect.d.ts +3 -0
  16. package/dist/dialect/abstractDialect.js +6 -2
  17. package/dist/dialect/abstractSqlDialect.d.ts +26 -7
  18. package/dist/dialect/abstractSqlDialect.js +89 -60
  19. package/dist/dialect/mysqlLikeSqlDialect.js +6 -1
  20. package/dist/dialect/operators.d.ts +9 -3
  21. package/dist/dialect/operators.js +32 -9
  22. package/dist/dialect/vectorSqlDialect.js +2 -2
  23. package/dist/entity/metadata/definition.d.ts +11 -1
  24. package/dist/entity/metadata/definition.js +18 -0
  25. package/dist/mariadb/mariadbQuerier.d.ts +5 -2
  26. package/dist/mariadb/mariadbQuerier.js +5 -10
  27. package/dist/migrate/ddl/defaultSql.js +1 -1
  28. package/dist/migrate/ddl/indexDdl.d.ts +3 -3
  29. package/dist/migrate/ddl/indexDdl.js +7 -7
  30. package/dist/migrate/ddl/mysqlIndexDdl.js +2 -2
  31. package/dist/migrate/ddl/tableDdl.js +2 -2
  32. package/dist/migrate/indexPredicate.d.ts +4 -3
  33. package/dist/migrate/indexPredicate.js +5 -5
  34. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +2 -6
  35. package/dist/migrate/schemaGenerator.js +1 -1
  36. package/dist/migrate/triggerSql.js +7 -5
  37. package/dist/mongodb/mongoDialect.js +17 -41
  38. package/dist/mongodb/mongoSchemaGenerator.js +12 -12
  39. package/dist/mongodb/mongodbQuerier.d.ts +4 -3
  40. package/dist/mongodb/mongodbQuerier.js +75 -102
  41. package/dist/mssql/mssqlDialect.js +4 -9
  42. package/dist/mssql/mssqlQuerier.d.ts +9 -3
  43. package/dist/mssql/mssqlQuerier.js +9 -11
  44. package/dist/mysql/mysql2Querier.d.ts +11 -2
  45. package/dist/mysql/mysql2Querier.js +4 -7
  46. package/dist/neon/index.d.ts +2 -0
  47. package/dist/neon/index.js +2 -0
  48. package/dist/neon/neonDialect.d.ts +7 -0
  49. package/dist/neon/neonDialect.js +8 -0
  50. package/dist/neon/neonQuerier.d.ts +26 -0
  51. package/dist/neon/neonQuerier.js +42 -0
  52. package/dist/neon/neonQuerierPool.d.ts +16 -6
  53. package/dist/neon/neonQuerierPool.js +48 -5
  54. package/dist/pglite/pgliteQuerier.d.ts +9 -5
  55. package/dist/pglite/pgliteQuerier.js +7 -11
  56. package/dist/postgres/abstractPgQuerierPool.d.ts +6 -6
  57. package/dist/postgres/pgExecution.d.ts +8 -0
  58. package/dist/postgres/pgExecution.js +3 -0
  59. package/dist/postgres/pgQuerier.d.ts +8 -11
  60. package/dist/postgres/pgQuerier.js +5 -9
  61. package/dist/postgres/pgQuerierPool.d.ts +2 -2
  62. package/dist/querier/abstractQuerier.d.ts +24 -20
  63. package/dist/querier/abstractQuerier.js +79 -58
  64. package/dist/querier/abstractQuerierPool.d.ts +2 -4
  65. package/dist/querier/abstractQuerierPool.js +2 -0
  66. package/dist/querier/abstractSqlQuerier.d.ts +46 -30
  67. package/dist/querier/abstractSqlQuerier.js +141 -119
  68. package/dist/querier/queryError.d.ts +2 -0
  69. package/dist/querier/queryError.js +9 -0
  70. package/dist/querier/transaction.js +3 -7
  71. package/dist/schema/canonicalType.d.ts +3 -3
  72. package/dist/schema/canonicalType.js +4 -10
  73. package/dist/sqlite/bindValues.d.ts +10 -0
  74. package/dist/sqlite/bindValues.js +8 -0
  75. package/dist/sqlite/hranaQuerier.d.ts +17 -11
  76. package/dist/sqlite/hranaQuerier.js +16 -5
  77. package/dist/sqlite/index.d.ts +1 -1
  78. package/dist/sqlite/index.js +0 -1
  79. package/dist/sqlite/localSqliteQuerierPool.js +19 -9
  80. package/dist/sqlite/sqliteQuerier.d.ts +9 -4
  81. package/dist/sqlite/sqliteQuerier.js +14 -8
  82. package/dist/turso/tursoQuerierPool.d.ts +0 -2
  83. package/dist/turso/tursoQuerierPool.js +0 -2
  84. package/dist/turso/tursoSessionQuerier.d.ts +19 -7
  85. package/dist/turso/tursoSessionQuerier.js +31 -20
  86. package/dist/type/dialect.d.ts +3 -0
  87. package/dist/type/querier.d.ts +12 -0
  88. package/dist/type/querier.js +10 -0
  89. package/dist/type/vector.d.ts +2 -1
  90. package/dist/type/vector.js +2 -2
  91. package/dist/util/asyncScope.d.ts +11 -0
  92. package/dist/util/asyncScope.js +29 -0
  93. package/dist/util/dialect.util.d.ts +21 -6
  94. package/dist/util/dialect.util.js +34 -9
  95. package/dist/util/filters.util.d.ts +5 -4
  96. package/dist/util/filters.util.js +4 -7
  97. package/dist/util/logger.js +2 -6
  98. package/dist/util/object.util.d.ts +7 -0
  99. package/dist/util/object.util.js +17 -0
  100. package/dist/util/query.util.d.ts +3 -2
  101. package/dist/util/sql.js +1 -1
  102. package/dist/util/sql.util.d.ts +18 -16
  103. package/dist/util/sql.util.js +8 -6
  104. package/package.json +5 -8
  105. package/skills/uql-orm/SKILL.md +4 -2
  106. package/dist/context/context.browser.d.ts +0 -12
  107. package/dist/context/context.browser.js +0 -33
  108. package/dist/sqlite/abstractSqliteQuerier.d.ts +0 -28
  109. package/dist/sqlite/abstractSqliteQuerier.js +0 -36
@@ -2,7 +2,7 @@ import { getMeta, idOf, namesKey, relationOf } from '../entity/index.js';
2
2
  import { SAVEPOINT_PREFIX } from '../dialect/aliases.js';
3
3
  import { namesRows } from '../dialect/operators.js';
4
4
  import { parseQueryLock } from '../type/index.js';
5
- import { childrenExcept, childrenOf, chunk, clone, entityName, fillOnFields, filterFieldKeys, forEachRequestedRelation, getKeys, hasKeys, getRelationRequestSummary, guardWrite, idOnlyQuery, keyJoins, keySet, isPagedQuery, isScalarId, LoggerWrapper, normalizeScalarFieldSelection, parentJoins, pointAt, queryLoggerFor, parseRelationAtKey, parseRelationQueryValue, rowKey, runHooks, securityConditions, someKey, targetJoins, whereEach, whereIds, whereKeysIn, whereWith, withoutSoftDeleteFilter, cascadingRelations, holdsForeignKey, } from '../util/index.js';
5
+ import { childrenExcept, childrenOf, chunk, clone, entityName, fillOnFields, filterFieldKeys, forEachRequestedRelation, getKeys, omitKeys, deletionOf, hasKeys, getRelationRequestSummary, guardWrite, idOnlyQuery, keyJoins, keySet, isPagedQuery, isScalarId, LoggerWrapper, normalizeScalarFieldSelection, parentJoins, pointAt, queryLoggerFor, parseRelationAtKey, parseRelationQueryValue, rowKey, runHooks, securityConditions, someKey, targetJoins, whereEach, whereIds, whereKeysIn, whereWith, withDeleted, cascadingRelations, holdsForeignKey, } from '../util/index.js';
6
6
  import { UqlOptimisticLockError, UqlUsageError } from '../util/uqlError.js';
7
7
  import { keysetRead } from './keyset.js';
8
8
  import { enrichError } from './queryError.js';
@@ -92,26 +92,23 @@ function writtenIds(meta, rows) {
92
92
  function upsertsByReading(meta, rows, update) {
93
93
  return securityConditions(meta).length > 0 || writesRelations(meta, update ? [...rows, update] : rows);
94
94
  }
95
- /** What `ON CONFLICT` assigns a row it finds by default: the payload, less the columns it matched on. */
96
- function conflictAssignments(row, conflictPaths) {
97
- const assigned = { ...row };
98
- for (const key of getKeys(conflictPaths)) {
99
- delete assigned[key];
100
- }
101
- return assigned;
102
- }
95
+ /**
96
+ * Writes the key an upsert reported onto each row, over the one it named: a found row keeps its own, and a row
97
+ * reported none keeps what it has. Only the key, since an `onInsert` value was never written to a row the upsert
98
+ * updated.
99
+ */
103
100
  function adoptReportedIds(meta, rows, reported) {
104
- if (reported?.length !== rows.length) {
105
- return;
106
- }
107
101
  const [idKey] = meta.ids;
108
102
  rows.forEach((row, index) => {
109
103
  const id = reported[index];
104
+ if (id === undefined) {
105
+ return;
106
+ }
110
107
  if (meta.ids.length > 1) {
111
108
  Object.assign(row, id);
112
109
  }
113
110
  else {
114
- row[idKey] ??= id;
111
+ row[idKey] = id;
115
112
  }
116
113
  });
117
114
  }
@@ -136,10 +133,6 @@ function isEntityFirst(args) {
136
133
  function returnedKeys(meta, returning) {
137
134
  return hasKeys(returning) ? normalizeScalarFieldSelection(meta, returning) : undefined;
138
135
  }
139
- /** How a delete reads the rows it removes: a hard one takes already-soft-deleted rows too, so it has to see them. */
140
- function deletableRows(opts) {
141
- return opts?.hardDelete ? { ...opts, filters: withoutSoftDeleteFilter(opts.filters) } : opts;
142
- }
143
136
  /** Whether an update of `row` writes a column, its `onUpdate` fills included: one that writes none sends nothing. */
144
137
  function writesColumns(meta, row) {
145
138
  return filterFieldKeys(meta, row, 'onUpdate').length > 0;
@@ -179,11 +172,8 @@ export class AbstractQuerier {
179
172
  taskQueue = Promise.resolve();
180
173
  /** The stream reading on the connection, from its first row asked for until its loop ends. */
181
174
  #stream;
182
- /**
183
- * A querier is one unit of work, so releasing ends it. Checked where each backend reaches for its
184
- * connection, on every driver and not just the pooled ones.
185
- */
186
- released = false;
175
+ /** A querier is one unit of work, so releasing ends it. */
176
+ #released = false;
187
177
  logger;
188
178
  /**
189
179
  * The connection is in a state nothing here can name, so `release` discards it rather than hand it back: a
@@ -194,6 +184,12 @@ export class AbstractQuerier {
194
184
  this.extra = extra;
195
185
  this.logger = queryLoggerFor(extra);
196
186
  }
187
+ /** Refuses a call on a released querier: each backend calls it where it reaches for its connection. */
188
+ assertActive() {
189
+ if (this.#released) {
190
+ throw new UqlUsageError('querier already released');
191
+ }
192
+ }
197
193
  /**
198
194
  * What the transaction this querier opens belongs to: the querier itself, its own connection, unless every
199
195
  * querier of its pool is one session (SQLite, PGlite), whose queriers then name that handle and share it.
@@ -377,28 +373,29 @@ export class AbstractQuerier {
377
373
  */
378
374
  writeReturning(entity, write, opts) {
379
375
  const keys = returnedKeys(getMeta(entity), opts?.returning);
380
- return keys ? this.atomically(async () => this.readWritten(entity, await write(), keys)) : write();
376
+ return keys ? this.atomically(async () => this.readBack(entity, await write(), keys)) : write();
381
377
  }
382
- /** The rows `ids` names, in their order, each with only the fields `keys` names. */
383
- async readWritten(entity, ids, keys, opts) {
378
+ /**
379
+ * The rows `ids` names, in their order, each with only the fields `keys` names: as written, whatever a filter
380
+ * says of them, since a soft-deleted row inserted is still written.
381
+ */
382
+ async readBack(entity, ids, keys, opts) {
384
383
  const meta = getMeta(entity);
385
384
  const known = ids.filter((id) => id !== undefined);
386
385
  if (known.length < ids.length) {
387
- 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`);
386
+ throw new UqlUsageError(`'returning' reads each written '${entity.name}' back by its key, which ${this.dialect.engineName} did not report for every row: give the rows their own keys`);
388
387
  }
389
388
  if (!known.length) {
390
389
  return [];
391
390
  }
392
- // The rows this write wrote, whatever a filter says of them: a soft-deleted one inserted is still written.
393
- const read = { ...opts, filters: withoutSoftDeleteFilter(opts?.filters) };
394
- const $select = keySet([...keys, ...meta.ids]);
391
+ const named = known.map((id) => whereIds(meta, id));
392
+ const read = withDeleted(opts);
395
393
  const rows = [];
396
- for (const batch of chunk(known, this.dialect.keyListCapacity(meta.ids.length))) {
397
- rows.push(...(await this.internalFindMany(entity, { $select, $where: whereIds(meta, batch) }, read)));
394
+ for (const q of this.keyedReads(meta.ids, named, [...keys, ...meta.ids])) {
395
+ rows.push(...(await this.internalFindMany(entity, q, read)));
398
396
  }
399
397
  const byKey = new Map(rows.map((row) => [rowKey(row, meta.ids), row]));
400
- const ordered = known.flatMap((id) => byKey.get(rowKey(whereIds(meta, id), meta.ids)) ?? []);
401
- return this.returned(entity, ordered, keys);
398
+ return this.returned(entity, named.flatMap((id) => byKey.get(rowKey(id, meta.ids)) ?? []), keys);
402
399
  }
403
400
  /** What `returning` reports of `rows`: each through `afterLoad`, as a read's are, then only the fields `keys` names. */
404
401
  async returned(entity, rows, keys) {
@@ -445,7 +442,7 @@ export class AbstractQuerier {
445
442
  return this.atomically(async () => {
446
443
  const ids = await this.settleIds(entity, q, rest);
447
444
  await this.updateMatching(entity, q, payload, rest, ids);
448
- return this.readWritten(entity, ids, keys, rest);
445
+ return this.readBack(entity, ids, keys, rest);
449
446
  });
450
447
  }
451
448
  /**
@@ -587,7 +584,7 @@ export class AbstractQuerier {
587
584
  const $where = whereWith(meta.softDelete, { $ne: null }, q.$where);
588
585
  // No version: a restore only undoes the stamp a delete left, which takes none either, and two of
589
586
  // them racing agree on the result anyway. A lock is for content, and a restore writes none.
590
- return this.unversionedUpdate(entity, { ...q, $where }, { [meta.softDelete]: null }, { filters: { softDelete: false } });
587
+ return this.unversionedUpdate(entity, { ...q, $where }, { [meta.softDelete]: null }, withDeleted());
591
588
  }
592
589
  /**
593
590
  * An update the library writes of its own, hooked as a caller's is but carrying no version: a restore's
@@ -633,9 +630,10 @@ export class AbstractQuerier {
633
630
  // An empty `update` leaves a found row as it is, as `DO NOTHING` does.
634
631
  if (ids[index] !== undefined && (update === undefined || hasKeys(update))) {
635
632
  const q = { $where: whereEach(keys, (key) => row[key]) };
636
- // A copy each: the update fills its `onUpdate` fields into what it is handed.
637
- const assigned = update ? { ...update } : conflictAssignments(row, conflictPaths);
638
- await this.updateRows(entity, q, assigned, { filters: withoutSoftDeleteFilter(undefined) }, undefined);
633
+ // A copy each, as the update fills its `onUpdate` fields into it; by default, the payload less the found
634
+ // row's key and the columns it matched on.
635
+ const assigned = update ? { ...update } : omitKeys(row, [...meta.ids, ...keys]);
636
+ await this.updateRows(entity, q, assigned, withDeleted(), undefined);
639
637
  }
640
638
  }
641
639
  const inserts = rows.filter((_, index) => ids[index] === undefined);
@@ -667,13 +665,14 @@ export class AbstractQuerier {
667
665
  const read = [...keys, ...meta.ids];
668
666
  // A soft delete stamps the rows, which a `RETURNING` would report stamped rather than as they were.
669
667
  const { writesReturning } = this;
670
- if (writesReturning && (rest.hardDelete || !meta.softDelete) && this.deletesByFilter(entity, q)) {
668
+ const deletion = deletionOf(meta, rest);
669
+ if (writesReturning && !deletion.stamp && this.deletesByFilter(entity, q)) {
671
670
  return this.returned(entity, await writesReturning.delete(entity, q, rest, read), keys);
672
671
  }
673
672
  // A delete hook receives whole rows; without one, only the keys `returning` names and the ids are read.
674
673
  const $select = this.watchesDelete(entity) ? undefined : keySet(read);
675
674
  return this.atomically(async () => {
676
- const rows = await this.readForWrite(entity, { ...q, $select }, deletableRows(rest));
675
+ const rows = await this.readForWrite(entity, { ...q, $select }, deletion.opts);
677
676
  // `afterLoad` sees copies, as a read's rows, so a delete hook still gets each row as it was read.
678
677
  const reported = await this.returned(entity, clone(rows), keys);
679
678
  await this.deleteRows(entity, q, rest, rows);
@@ -702,9 +701,10 @@ export class AbstractQuerier {
702
701
  }
703
702
  const cascades = cascadingRelations(meta, 'delete').length > 0;
704
703
  const watched = this.watchesDelete(entity);
704
+ const deleting = opts ?? {};
705
705
  return this.atomically(async () => {
706
706
  // A hook receives the rows themselves; the ids read off them name the same rows a second read might not.
707
- const doomed = read ?? (await this.readForWrite(entity, watched ? q : idOnlyQuery(meta, q), deletableRows(opts)));
707
+ const doomed = read ?? (await this.readForWrite(entity, watched ? q : idOnlyQuery(meta, q), deletionOf(meta, deleting).opts));
708
708
  if (!doomed.length) {
709
709
  return 0;
710
710
  }
@@ -713,7 +713,7 @@ export class AbstractQuerier {
713
713
  const changes = await this.writeBatches(ids, meta.ids.length, async (batch) => {
714
714
  // Children first: they hold the foreign key, which a schema without `ON DELETE CASCADE` enforces.
715
715
  if (cascades) {
716
- await this.deleteChildren(entity, batch, opts);
716
+ await this.deleteChildren(entity, batch, deleting);
717
717
  }
718
718
  return this.internalDeleteMany(entity, { $where: whereIds(meta, batch) }, opts);
719
719
  });
@@ -894,7 +894,7 @@ export class AbstractQuerier {
894
894
  */
895
895
  async deleteChildren(entity, ids, opts) {
896
896
  const meta = getMeta(entity);
897
- const soft = !!meta.softDelete && !opts?.hardDelete;
897
+ const soft = deletionOf(meta, opts).stamp !== undefined;
898
898
  for (const relKey of cascadingRelations(meta, 'delete')) {
899
899
  const relOpts = relationOf(meta, relKey);
900
900
  const target = relOpts.through ? relOpts.through() : relOpts.entity();
@@ -975,7 +975,7 @@ export class AbstractQuerier {
975
975
  * none, so a transaction inside another is refused: it could not undo its own writes apart.
976
976
  */
977
977
  savepoint(_kind, _name) {
978
- return Promise.reject(new UqlUsageError(`${this.dialect.dialectName} has no savepoint to nest a transaction in another: run it on its own`));
978
+ return Promise.reject(new UqlUsageError(`${this.dialect.engineName} has no savepoint to nest a transaction in another: run it on its own`));
979
979
  }
980
980
  /**
981
981
  * Runs `callback` once the outermost transaction this flow is in commits, and dropped if it rolls back:
@@ -1070,29 +1070,45 @@ export class AbstractQuerier {
1070
1070
  await this.emitHook(entity, 'afterLoad', rows);
1071
1071
  }
1072
1072
  /**
1073
- * The ids of `rows`, read through the filters by the columns an upsert matches them on, and held as
1074
- * {@link readForWrite} holds them: after a statement that could not report them in payload order, or before a
1075
- * guarded upsert. A row that no read row matches, or that two do, keeps `undefined`: a missing id is honest
1076
- * where a guessed one is not.
1073
+ * The ids of `rows`, read by the columns an upsert matches them on, soft-deleted rows included since a unique key
1074
+ * holds across both, each read held as {@link readForWrite} holds its rows. A row no found row matches, or two do,
1075
+ * reads none, since a missing id is honest where a guessed one is not; a null key never conflicts, so is not read.
1077
1076
  */
1078
1077
  async idsByConflict(entity, conflictPaths, rows) {
1079
1078
  const meta = getMeta(entity);
1080
1079
  const keys = getKeys(conflictPaths);
1081
- // A null key never conflicts, so no row is read back for it, whether one key names the row or several.
1082
1080
  const named = rows.filter((row) => keys.every((key) => row[key] != null));
1083
1081
  const distinct = [...new Map(named.map((row) => [rowKey(row, keys), row])).values()];
1084
- const found = [];
1085
- for (const batch of chunk(distinct, this.dialect.keyListCapacity(keys.length))) {
1086
- const q = { $select: keySet([...meta.ids, ...keys]), $where: whereKeysIn(keys, batch) };
1087
- found.push(await this.readForWrite(entity, q, { filters: withoutSoftDeleteFilter(undefined) }));
1088
- }
1089
1082
  const byConflict = new Map();
1090
- for (const row of found.flat()) {
1091
- const key = rowKey(row, keys);
1092
- byConflict.set(key, byConflict.has(key) ? undefined : idOf(meta, row));
1083
+ for (const q of this.keyedReads(keys, distinct, [...meta.ids, ...keys])) {
1084
+ for (const row of await this.readForWrite(entity, q, withDeleted())) {
1085
+ const key = rowKey(row, keys);
1086
+ byConflict.set(key, byConflict.has(key) ? undefined : idOf(meta, row));
1087
+ }
1093
1088
  }
1094
1089
  return rows.map((row) => byConflict.get(rowKey(row, keys)));
1095
1090
  }
1091
+ /**
1092
+ * `ids` completed where an upsert reported no id for a row whose key it does not keep (`kept`, asked before the
1093
+ * write fills one in): read back by the conflict columns.
1094
+ */
1095
+ async withUnreportedIds(entity, conflictPaths, payload, ids, kept) {
1096
+ const unplaced = payload.flatMap((_, index) => (ids[index] === undefined && !kept[index] ? [index] : []));
1097
+ if (unplaced.length) {
1098
+ const found = await this.idsByConflict(entity, conflictPaths, unplaced.map((index) => payload[index]));
1099
+ unplaced.forEach((index, position) => {
1100
+ ids[index] = found[position];
1101
+ });
1102
+ }
1103
+ return ids;
1104
+ }
1105
+ /** Reads of the rows matching one of `rows` on `keys`, as many per statement as a key list takes, selecting `select`. */
1106
+ keyedReads(keys, rows, select) {
1107
+ return chunk(rows, this.dialect.keyListCapacity(keys.length)).map((batch) => ({
1108
+ $select: keySet(select),
1109
+ $where: whereKeysIn(keys, batch),
1110
+ }));
1111
+ }
1096
1112
  /**
1097
1113
  * Runs `write` between the event's `before`/`after` pair. The before hooks get the caller's rows, so
1098
1114
  * what they assign is written; `write` and the after hooks get a copy, which by then carries what
@@ -1215,10 +1231,15 @@ export class AbstractQuerier {
1215
1231
  }).catch((err) => {
1216
1232
  this.logger.logError('rollback failed; discarding the connection', err);
1217
1233
  });
1218
- this.released = true;
1234
+ this.#released = true;
1219
1235
  return this.enqueue(() => this.internalRelease(this.#unusable));
1220
1236
  }
1221
1237
  async [Symbol.asyncDispose]() {
1222
1238
  return this.release();
1223
1239
  }
1240
+ /**
1241
+ * Hands back what the querier holds, nothing where it holds no connection of its own. `discard` means the
1242
+ * connection must not be reused; backends with a pool evict it instead.
1243
+ */
1244
+ async internalRelease(_discard) { }
1224
1245
  }
@@ -50,8 +50,6 @@ export declare abstract class AbstractQuerierPool<Q extends Querier, D extends A
50
50
  readonly deleteMany: UniversalQuerier['deleteMany'];
51
51
  readonly restoreOneById: UniversalQuerier['restoreOneById'];
52
52
  readonly restoreMany: UniversalQuerier['restoreMany'];
53
- /**
54
- * end the pool.
55
- */
56
- abstract end(): Promise<void>;
53
+ /** Closes what the pool holds: nothing where each querier closes its own connection, or there is none to close. */
54
+ end(): Promise<void>;
57
55
  }
@@ -142,4 +142,6 @@ export class AbstractQuerierPool {
142
142
  deleteMany = (...args) => this.withQuerier((querier) => querier.deleteMany(...args));
143
143
  restoreOneById = (...args) => this.withQuerier((querier) => querier.restoreOneById(...args));
144
144
  restoreMany = (...args) => this.withQuerier((querier) => querier.restoreMany(...args));
145
+ /** Closes what the pool holds: nothing where each querier closes its own connection, or there is none to close. */
146
+ async end() { }
145
147
  }
@@ -1,25 +1,22 @@
1
1
  import type { AbstractSqlDialect } from '../dialect/index.js';
2
2
  import type { EntityData, ExtraOptions, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryPage, QueryGroupMap, QueryOptions, QuerySearch, QueryUpdateResult, RawRow, SavepointCommand, SqlQuerier, SqlStatement, TransactionOptions, Type, UpdatePayload } from '../type/index.js';
3
- import type { BuildUpdateResultPayload } from '../util/sql.util.js';
3
+ import type { SqlExecution } from '../util/sql.util.js';
4
4
  import { AbstractQuerier, type UpsertedId, type WritesReturning } from './abstractQuerier.js';
5
+ /** A statement as it is sent: its SQL and the values it binds. */
6
+ export type BoundStatement = {
7
+ readonly sql: string;
8
+ readonly values: unknown[];
9
+ };
5
10
  export declare abstract class AbstractSqlQuerier extends AbstractQuerier implements SqlQuerier {
6
11
  #private;
7
12
  readonly dialect: AbstractSqlDialect;
8
13
  readonly extra?: ExtraOptions | undefined;
9
14
  hasOpenTransaction: boolean;
10
15
  constructor(dialect: AbstractSqlDialect, extra?: ExtraOptions | undefined);
11
- /**
12
- * internal read query.
13
- */
14
- protected abstract internalAll<T>(query: string, values?: unknown[]): Promise<T[]>;
15
- /**
16
- * internal insert/update/delete/ddl query.
17
- */
18
- protected abstract internalRun(query: string, values?: unknown[]): Promise<QueryUpdateResult>;
19
- /**
20
- * Build a QueryUpdateResult with affected changes and calculated IDs.
21
- */
22
- protected buildUpdateResult(payload: BuildUpdateResultPayload): QueryUpdateResult;
16
+ /** Runs one statement on the driver: what it read, how many rows it changed, and any id its header reports. */
17
+ protected abstract execute(sql: string, values?: unknown[]): Promise<SqlExecution>;
18
+ /** What a write reports: the rows it changed, and their ids, inferred from a header's first id where the dialect reads them so. */
19
+ private updateResultOf;
23
20
  /**
24
21
  * The `auto_increment_increment` stride used to infer the ids of a multi-row insert from the
25
22
  * single id the driver reports (MySQL, which has no `RETURNING`). It is 1 on a standalone server
@@ -35,19 +32,33 @@ export declare abstract class AbstractSqlQuerier extends AbstractQuerier impleme
35
32
  protected lazyConnect(): Promise<void>;
36
33
  all<T extends object = RawRow>(...statement: SqlStatement): Promise<T[]>;
37
34
  run(...statement: SqlStatement): Promise<QueryUpdateResult>;
38
- /** Refused before the driver fails it, or PGlite answers it and every read after it wrong. */
39
- private assertBindBudget;
40
- /** The rows of a statement the dialect builds. */
41
- private query;
42
- /** Runs a statement the dialect builds. */
43
- private exec;
44
- /** Builds a statement and sends it on the connection, in turn, timed and its failure tagged with it. */
45
- private send;
46
35
  /**
47
- * Runs the `SET`s tuning an ANN index for the query on its connection, refusing where they would apply to
48
- * nothing: a `SET LOCAL` outside a transaction.
36
+ * Runs `statements` as one request, all or none, joining an open transaction: what a driver taking a list as one
37
+ * declares. Called for two or more.
38
+ */
39
+ protected executeBatch?(statements: readonly BoundStatement[]): Promise<SqlExecution[]>;
40
+ /**
41
+ * The one path every statement takes, alone or as a list answering a result each, all or none: one request where
42
+ * the driver has {@link executeBatch}, a failure tagged with the statement it names; else in turn, in a transaction
43
+ * where `atomic` (a split write) asks for one, opened before the queue is taken, which its `BEGIN` waits on.
49
44
  */
50
- private applyVectorTuning;
45
+ protected runStatements(statements: readonly BoundStatement[], atomic?: boolean): Promise<readonly SqlExecution[]>;
46
+ /** Runs `statements` one after another on the connection, each timed. */
47
+ private inTurn;
48
+ /** Runs `task` on the connection, connected, after everything queued before it. */
49
+ private onConnection;
50
+ /** The statement `build` writes, refused past the bind budget before the driver fails it. */
51
+ private bound;
52
+ /** Refused before the driver fails it, or PGlite answers it and every read after it wrong. */
53
+ private assertBindBudget;
54
+ /** The rows of the statement `build` writes, as the caller types them. */
55
+ private rowsOf;
56
+ /** What the write `build` writes reports. */
57
+ private changesOf;
58
+ /** The `SET`s tuning an ANN index for the query, leading its read: none without a vector search or an ANN index. */
59
+ private vectorTuning;
60
+ /** Whether `tuning` applies only inside a transaction, as a `SET LOCAL` does: a read opens one, or joins the open one. */
61
+ private tunedInTransaction;
51
62
  protected internalFindMany<E extends object>(entity: Type<E>, q: Query<E>, opts?: QueryOptions): Promise<E[]>;
52
63
  /** Every row `q` matches past its page, deduplicated where it reads `$distinct`. */
53
64
  private countUnpaged;
@@ -57,13 +68,17 @@ export declare abstract class AbstractSqlQuerier extends AbstractQuerier impleme
57
68
  * so those count apart.
58
69
  */
59
70
  protected internalFindManyAndCount<E extends object>(entity: Type<E>, q: Query<E>, opts?: QueryOptions): Promise<[E[], number]>;
60
- /** The rows a read of `entity` matches, each as its statement reads it. */
71
+ /**
72
+ * The rows a read of `entity` matches, each as its statement reads it, the vector search's tuning leading it, in a
73
+ * transaction of its own where the tuning needs one and none is open.
74
+ */
61
75
  private selectRows;
62
- /** The rows of a read the dialect builds, each as the terms it returns say. */
76
+ /** The rows of a statement the dialect builds, each as the terms it returns say, after the `leading` ones. */
63
77
  private readRows;
64
78
  /**
65
- * The one read not going through `all`, so it checks its budget and connects on its own; its values go as
66
- * the context holds them, each normalized as it was bound. The tuning is guarded as `selectRows` says.
79
+ * The one read not going through `runStatements`: it holds the connection for its loop, so it checks its budget
80
+ * and connects on its own, its values going as the context holds them, each normalized as it was bound. Tuning
81
+ * that needs a transaction is refused outside one, which would otherwise stay open for the whole loop.
67
82
  */
68
83
  protected internalFindManyStream<E extends object>(entity: Type<E>, q: Query<E>, opts?: QueryOptions): AsyncGenerator<Awaited<E>, void, unknown>;
69
84
  /**
@@ -87,8 +102,9 @@ export declare abstract class AbstractSqlQuerier extends AbstractQuerier impleme
87
102
  protected get writesReturning(): WritesReturning | undefined;
88
103
  /** The rows the write `build` renders reports, `RETURNING` the fields `keys` names. */
89
104
  private reportedRows;
90
- protected internalUpsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E[], update?: UpdatePayload<E>): Promise<(UpsertedId<E> | undefined)[] | undefined>;
91
- private runUpsert;
105
+ protected internalUpsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E[], update?: UpdatePayload<E>): Promise<(UpsertedId<E> | undefined)[]>;
106
+ /** The ids an upsert reports of its rows: its `RETURNING` rows' in order, or its one row's in the header. */
107
+ private reportedIds;
92
108
  protected internalDeleteMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, opts?: QueryOptions): Promise<number>;
93
109
  protected openTransaction(opts?: TransactionOptions): Promise<void>;
94
110
  /**