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,8 +1,9 @@
1
1
  import { assertSoleId, getMeta, idOf, namesKey, relationOf } from '../entity/index.js';
2
2
  import { namesRows } from '../dialect/operators.js';
3
3
  import { parseQueryLock } from '../type/index.js';
4
- import { cascadesOnDelete, childrenOf, clone, entityName, fillOnFields, filterFieldKeys, filterPersistableRelationKeys, forEachRequestedRelation, getKeys, getRelationRequestSummary, guardWrite, idOnlyQuery, keySet, isPagedQuery, isScalarId, LoggerWrapper, parentJoins, queryLoggerFor, parseRelationAtKey, parseRelationQueryValue, rowKey, runHooks, securityConditions, someKey, targetKeyColumns, whereAnyOf, whereEach, whereIds, whereWith, withoutSoftDeleteFilter, } from '../util/index.js';
4
+ import { cascadesOnDelete, childrenOf, clone, entityName, fillOnFields, filterFieldKeys, filterPersistableRelationKeys, forEachRequestedRelation, getKeys, hasKeys, getRelationRequestSummary, guardWrite, idOnlyQuery, keySet, isPagedQuery, isScalarId, LoggerWrapper, parentJoins, queryLoggerFor, parseRelationAtKey, parseRelationQueryValue, rowKey, runHooks, securityConditions, someKey, targetKeyColumns, whereAnyOf, whereEach, whereIds, whereWith, withoutSoftDeleteFilter, } from '../util/index.js';
5
5
  import { UqlOptimisticLockError, UqlUsageError } from '../util/uqlError.js';
6
+ import { keysetRead } from './keyset.js';
6
7
  import { enrichError } from './queryError.js';
7
8
  /**
8
9
  * Refuses a nullish id, which would reduce to no filter at all, and a composite id missing a column,
@@ -86,6 +87,14 @@ function assertLockableUpdate(meta, q, settles) {
86
87
  function writtenIds(meta, rows) {
87
88
  return rows.map((row) => (namesKey(meta, row) ? idOf(meta, row) : undefined));
88
89
  }
90
+ /** What `ON CONFLICT` assigns a row it finds by default: the payload, less the columns it matched on. */
91
+ function conflictAssignments(row, conflictPaths) {
92
+ const assigned = { ...row };
93
+ for (const key of getKeys(conflictPaths)) {
94
+ delete assigned[key];
95
+ }
96
+ return assigned;
97
+ }
89
98
  /**
90
99
  * Writes the key an upsert reported onto each row that named none - only the key, since an `onInsert`
91
100
  * value was never written to a row the upsert updated. A report aligns with the rows only when it
@@ -100,6 +109,23 @@ function adoptReportedIds(meta, rows, reported) {
100
109
  rows[index][idKey] ??= reported[index];
101
110
  }
102
111
  }
112
+ /** Normalizes either call form to `[entity, query, opts]`, throwing when a query object has no `$entity`. */
113
+ function entityArgs(args) {
114
+ if (isEntityFirst(args)) {
115
+ const [entity, q, opts] = args;
116
+ return [entity, q ?? {}, opts];
117
+ }
118
+ const [{ $entity, ...q }, opts] = args;
119
+ if (!$entity) {
120
+ throw new UqlUsageError('$entity is required when using query-object syntax');
121
+ }
122
+ return [$entity, q, opts];
123
+ }
124
+ /** Whether the entity is passed first, i.e. the first argument is a class rather than a query object. */
125
+ function isEntityFirst(args) {
126
+ const [first] = args;
127
+ return typeof first === 'function' && first.prototype !== undefined;
128
+ }
103
129
  /** Base class for all database queriers. */
104
130
  export class AbstractQuerier {
105
131
  extra;
@@ -156,29 +182,17 @@ export class AbstractQuerier {
156
182
  }
157
183
  });
158
184
  }
159
- /** `[entity, query, opts]` from either call form, `(entity, q, opts)` or `({ $entity, ...q }, opts)`. */
160
- resolveEntityQuery(entityOrQuery, maybeQueryOrOpts, maybeOpts) {
161
- if (typeof entityOrQuery === 'function' && entityOrQuery.prototype) {
162
- return [entityOrQuery, maybeQueryOrOpts ?? {}, maybeOpts];
163
- }
164
- const q = entityOrQuery;
165
- if (!q.$entity) {
166
- throw new UqlUsageError('$entity is required when using query-object syntax');
167
- }
168
- const { $entity, ...query } = q;
169
- return [$entity, query, maybeQueryOrOpts];
170
- }
171
185
  async findOneById(entity, id, q = {}, opts) {
172
186
  assertIdValue(entity, id);
173
187
  return this.findOne(entity, { ...q, $where: { ...q.$where, ...whereIds(getMeta(entity), id) } }, opts);
174
188
  }
175
- async findOne(entityOrQuery, maybeQueryOrOpts, maybeOpts) {
176
- const [entity, q, opts] = this.resolveEntityQuery(entityOrQuery, maybeQueryOrOpts, maybeOpts);
189
+ async findOne(...args) {
190
+ const [entity, q, opts] = entityArgs(args);
177
191
  const rows = await this.findMany(entity, { ...q, $limit: 1 }, opts);
178
192
  return rows[0];
179
193
  }
180
- async findMany(entityOrQuery, maybeQueryOrOpts, maybeOpts) {
181
- const [entity, q, opts] = this.resolveEntityQuery(entityOrQuery, maybeQueryOrOpts, maybeOpts);
194
+ async findMany(...args) {
195
+ const [entity, q, opts] = entityArgs(args);
182
196
  this.validateReadQuery(entity, q);
183
197
  const founds = await this.internalFindMany(entity, q, opts);
184
198
  // Guarded here rather than only inside: awaiting a call that returns at once still costs every read
@@ -188,13 +202,13 @@ export class AbstractQuerier {
188
202
  }
189
203
  return founds;
190
204
  }
191
- findManyStream(entityOrQuery, maybeQueryOrOpts, maybeOpts) {
192
- const [entity, q, opts] = this.resolveEntityQuery(entityOrQuery, maybeQueryOrOpts, maybeOpts);
205
+ findManyStream(...args) {
206
+ const [entity, q, opts] = entityArgs(args);
193
207
  this.validateReadQuery(entity, q);
194
208
  return this.internalFindManyStream(entity, q, opts);
195
209
  }
196
- async findManyAndCount(entityOrQuery, maybeQueryOrOpts, maybeOpts) {
197
- const [entity, q, opts] = this.resolveEntityQuery(entityOrQuery, maybeQueryOrOpts, maybeOpts);
210
+ async findManyAndCount(...args) {
211
+ const [entity, q, opts] = entityArgs(args);
198
212
  this.validateReadQuery(entity, q);
199
213
  const [founds, count] = await this.internalFindManyAndCount(entity, q, opts);
200
214
  if (this.listensForLoad(entity, q.$populate)) {
@@ -212,12 +226,26 @@ export class AbstractQuerier {
212
226
  this.internalCount(entity, { $where: q.$where }, opts),
213
227
  ]);
214
228
  }
215
- async count(entityOrQuery, maybeQueryOrOpts, maybeOpts) {
216
- const [entity, q, opts] = this.resolveEntityQuery(entityOrQuery, maybeQueryOrOpts, maybeOpts);
229
+ /**
230
+ * Shared by every backend: the keyset condition is an ordinary `$where`, so each engine renders it with the
231
+ * operators it already has, and the page holds the rows `findMany` would return.
232
+ */
233
+ async findManyPage(...args) {
234
+ const [entity, q, opts] = entityArgs(args);
235
+ this.validateReadQuery(entity, q);
236
+ const read = keysetRead(getMeta(entity), q, this.dialect.features.nullsSortLowest);
237
+ const page = read.page(await this.internalFindMany(entity, read.query, opts));
238
+ if (this.listensForLoad(entity, q.$populate)) {
239
+ await this.emitLoaded(entity, page.items, q.$populate);
240
+ }
241
+ return page;
242
+ }
243
+ async count(...args) {
244
+ const [entity, q, opts] = entityArgs(args);
217
245
  return this.internalCount(entity, q, opts);
218
246
  }
219
- async exists(entityOrQuery, maybeQueryOrOpts, maybeOpts) {
220
- const [entity, q, opts] = this.resolveEntityQuery(entityOrQuery, maybeQueryOrOpts, maybeOpts);
247
+ async exists(...args) {
248
+ const [entity, q, opts] = entityArgs(args);
221
249
  return (await this.internalCount(entity, { $where: q.$where, $limit: 1 }, opts)) > 0;
222
250
  }
223
251
  /**
@@ -348,25 +376,25 @@ export class AbstractQuerier {
348
376
  return this.hooked(entity, 'Update', [payload], ([row]) => this.updateRows(entity, q, row, opts, undefined));
349
377
  }
350
378
  /** 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. */
351
- async upsertOne(entity, conflictPaths, payload) {
379
+ async upsertOne(entity, conflictPaths, payload, opts = {}) {
352
380
  const meta = getMeta(entity);
353
381
  assertUnversioned(meta, "'upsertOne'");
354
382
  return this.hooked(entity, 'Upsert', [payload], async (rows) => {
355
383
  const { ids, changes, created } = securityConditions(meta).length
356
- ? await this.guardedUpsert(entity, conflictPaths, rows)
357
- : await this.internalUpsertOne(entity, conflictPaths, rows[0]);
384
+ ? await this.guardedUpsert(entity, conflictPaths, rows, opts)
385
+ : await this.internalUpsertOne(entity, conflictPaths, rows[0], opts);
358
386
  adoptReportedIds(meta, rows, ids);
359
387
  const [id] = writtenIds(meta, rows);
360
388
  return { id, changes, created };
361
389
  });
362
390
  }
363
- async upsertMany(entity, conflictPaths, payload) {
391
+ async upsertMany(entity, conflictPaths, payload, opts = {}) {
364
392
  const meta = getMeta(entity);
365
393
  assertUnversioned(meta, "'upsertMany'");
366
394
  return this.hooked(entity, 'Upsert', payload, async (rows) => {
367
395
  const { ids, changes } = securityConditions(meta).length
368
- ? await this.guardedUpsert(entity, conflictPaths, rows)
369
- : await this.internalUpsertMany(entity, conflictPaths, rows);
396
+ ? await this.guardedUpsert(entity, conflictPaths, rows, opts)
397
+ : await this.internalUpsertMany(entity, conflictPaths, rows, opts);
370
398
  adoptReportedIds(meta, rows, ids);
371
399
  return { ids: writtenIds(meta, rows), changes };
372
400
  });
@@ -376,7 +404,7 @@ export class AbstractQuerier {
376
404
  * it belongs to, so the rows the conflict names are read through the filter: those found update, the
377
405
  * rest insert, where another tenant's row fails on its key. See architecture/security-filter-writes.md.
378
406
  */
379
- async guardedUpsert(entity, conflictPaths, rows) {
407
+ async guardedUpsert(entity, conflictPaths, rows, { update }) {
380
408
  guardWrite(getMeta(entity), rows, 'insert');
381
409
  if (!rows.length) {
382
410
  return { changes: 0 };
@@ -386,13 +414,9 @@ export class AbstractQuerier {
386
414
  const ids = await this.idsByConflict(entity, conflictPaths, rows);
387
415
  let changes = 0;
388
416
  for (const [index, row] of rows.entries()) {
389
- if (ids[index] !== undefined) {
390
- // What `ON CONFLICT` would assign: the row, less the columns it matched on.
391
- const payload = { ...row };
392
- for (const key of keys) {
393
- delete payload[key];
394
- }
395
- changes += await this.updateColumns(entity, { $where: whereEach(keys, (key) => row[key]) }, payload, undefined, 0);
417
+ // An empty `update` leaves a found row as it is, as `DO NOTHING` does.
418
+ if (ids[index] !== undefined && (update === undefined || hasKeys(update))) {
419
+ changes += await this.updateColumns(entity, { $where: whereEach(keys, (key) => row[key]) }, update ?? conflictAssignments(row, conflictPaths), undefined, 0);
396
420
  }
397
421
  }
398
422
  const inserts = rows.filter((_, index) => ids[index] === undefined);
@@ -411,8 +435,8 @@ export class AbstractQuerier {
411
435
  assertIdValue(entity, id);
412
436
  return this.deleteMany(entity, { $where: whereIds(getMeta(entity), id) }, opts);
413
437
  }
414
- async deleteMany(entityOrQuery, qOrOpts, maybeOpts) {
415
- const [entity, q, opts] = this.resolveEntityQuery(entityOrQuery, qOrOpts, maybeOpts);
438
+ async deleteMany(...args) {
439
+ const [entity, q, opts] = entityArgs(args);
416
440
  assertNamesRows(entity, 'deleteMany', q, opts);
417
441
  const meta = getMeta(entity);
418
442
  const cascades = cascadesOnDelete(meta);
@@ -687,6 +711,34 @@ export class AbstractQuerier {
687
711
  this.logger.logQuery(query, values, Math.round(performance.now() - startTime));
688
712
  }
689
713
  }
714
+ beginTransaction(opts) {
715
+ return this.serialize(async () => {
716
+ if (this.hasOpenTransaction) {
717
+ throw new UqlUsageError('pending transaction');
718
+ }
719
+ await this.openTransaction(opts);
720
+ });
721
+ }
722
+ /** Strict: this is the check that catches a forgotten `beginTransaction`. */
723
+ commitTransaction() {
724
+ return this.serialize(async () => {
725
+ if (!this.hasOpenTransaction) {
726
+ throw new UqlUsageError('not a pending transaction');
727
+ }
728
+ await this.endTransaction(true);
729
+ });
730
+ }
731
+ /**
732
+ * Rolls the open transaction back, or does nothing when there is none: it is called from `catch` and
733
+ * `finally`, where the caller cannot know whether `beginTransaction` got far enough to open one.
734
+ */
735
+ rollbackTransaction() {
736
+ return this.serialize(async () => {
737
+ if (this.hasOpenTransaction) {
738
+ await this.endTransaction(false);
739
+ }
740
+ });
741
+ }
690
742
  /**
691
743
  * Rolls back an unfinished transaction, then hands the connection back, discarding it if the rollback
692
744
  * failed. Never throws first, since `await using` has no other way to release.
@@ -1,5 +1,5 @@
1
1
  import type { AbstractDialect } from '../dialect/index.js';
2
- import type { EntityWrite, EntityId, ExtraOptions, FieldKey, PoolRunOptions, Querier, QuerierPool, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryFilter, QueryFindResult, QueryGroupMap, QueryOneProjected, QueryOptions, QueryPage, QueryProjected, QuerySearch, QueryUpsertOneResult, QueryUpsertManyResult, RelationKey, TransactionOptions, Type, UpdateWrite, WrittenId } from '../type/index.js';
2
+ import type { ExtraOptions, PoolRunOptions, Querier, QuerierPool, TransactionOptions, UniversalQuerier } from '../type/index.js';
3
3
  /**
4
4
  * Base pool: dialect id and behavior come only from the `dialect` instance (see {@link QuerierPool}).
5
5
  */
@@ -24,31 +24,33 @@ export declare abstract class AbstractQuerierPool<Q extends Querier, D extends A
24
24
  withQuerier<T>(callback: (querier: Q) => Promise<T>, opts?: PoolRunOptions): Promise<T>;
25
25
  /** Run `fn` under `context` (an enclosing {@link withContext}) when provided, else run it as-is. */
26
26
  private runScoped;
27
- 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>;
28
- 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>(entity: Type<E>, q: QueryOneProjected<E, S, V, X, P, C>, opts?: QueryOptions): Promise<QueryFindResult<E, S, V, X, P, C> | undefined>;
29
- findMany<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: QueryProjected<E, S, V, X, P, C>, opts?: QueryOptions): Promise<QueryFindResult<E, S, V, X, P, C>[]>;
27
+ readonly findOneById: UniversalQuerier['findOneById'];
28
+ readonly findOne: UniversalQuerier['findOne'];
29
+ readonly findMany: UniversalQuerier['findMany'];
30
30
  /**
31
- * The connection outlives the call here: it is held until the iterator is drained or closed by a
32
- * `break`/`throw`. Abandoning the iterator instead leaks it until GC, so consume it in a `for await`.
31
+ * The connection outlives the call: it is held until the iterator is drained or closed by a `break` or
32
+ * `throw`. Abandoning the iterator leaks it until GC, so consume it in a `for await`.
33
33
  */
34
- findManyStream<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: QueryProjected<E, S, V, X, P, C>, opts?: QueryOptions): AsyncGenerator<QueryFindResult<E, S, V, X, P, C>>;
35
- findManyAndCount<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: QueryProjected<E, S, V, X, P, C>, opts?: QueryOptions): Promise<[QueryFindResult<E, S, V, X, P, C>[], number]>;
36
- count<E extends object>(entity: Type<E>, q?: QueryPage<E>, opts?: QueryOptions): Promise<number>;
37
- exists<E extends object>(entity: Type<E>, q?: QueryFilter<E>, opts?: QueryOptions): Promise<boolean>;
38
- aggregate<E extends object, const G extends QueryGroupMap<E>, const A extends QueryAggMap<E>>(entity: Type<E>, q: QueryAggregate<E, G, A>, opts?: QueryOptions): Promise<QueryAggregateResult<E, G, A>[]>;
39
- estimatedCount<E extends object>(entity: Type<E>): Promise<number>;
40
- insertOne<E extends object>(entity: Type<E>, payload: EntityWrite<E>): Promise<WrittenId<E> | undefined>;
41
- insertMany<E extends object>(entity: Type<E>, payload: readonly EntityWrite<E>[]): Promise<(WrittenId<E> | undefined)[]>;
42
- updateOneById<E extends object>(entity: Type<E>, id: EntityId<E>, payload: UpdateWrite<E>, opts?: QueryOptions): Promise<number>;
43
- updateMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, payload: UpdateWrite<E>, opts?: QueryOptions): Promise<number>;
44
- upsertOne<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: EntityWrite<E>): Promise<QueryUpsertOneResult<E>>;
45
- upsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: readonly EntityWrite<E>[]): Promise<QueryUpsertManyResult<E>>;
46
- saveOne<E extends object>(entity: Type<E>, payload: EntityWrite<E>): Promise<WrittenId<E> | undefined>;
47
- saveMany<E extends object>(entity: Type<E>, payload: readonly EntityWrite<E>[]): Promise<(WrittenId<E> | undefined)[]>;
48
- deleteOneById<E extends object>(entity: Type<E>, id: EntityId<E>, opts?: QueryOptions): Promise<number>;
49
- deleteMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, opts?: QueryOptions): Promise<number>;
50
- restoreOneById<E extends object>(entity: Type<E>, id: EntityId<E>): Promise<number>;
51
- restoreMany<E extends object>(entity: Type<E>, q: QuerySearch<E>): Promise<number>;
34
+ readonly findManyStream: UniversalQuerier['findManyStream'];
35
+ private streamWithQuerier;
36
+ readonly findManyAndCount: UniversalQuerier['findManyAndCount'];
37
+ readonly findManyPage: UniversalQuerier['findManyPage'];
38
+ readonly count: UniversalQuerier['count'];
39
+ readonly exists: UniversalQuerier['exists'];
40
+ readonly aggregate: UniversalQuerier['aggregate'];
41
+ readonly estimatedCount: UniversalQuerier['estimatedCount'];
42
+ readonly insertOne: UniversalQuerier['insertOne'];
43
+ readonly insertMany: UniversalQuerier['insertMany'];
44
+ readonly updateOneById: UniversalQuerier['updateOneById'];
45
+ readonly updateMany: UniversalQuerier['updateMany'];
46
+ readonly upsertOne: UniversalQuerier['upsertOne'];
47
+ readonly upsertMany: UniversalQuerier['upsertMany'];
48
+ readonly saveOne: UniversalQuerier['saveOne'];
49
+ readonly saveMany: UniversalQuerier['saveMany'];
50
+ readonly deleteOneById: UniversalQuerier['deleteOneById'];
51
+ readonly deleteMany: UniversalQuerier['deleteMany'];
52
+ readonly restoreOneById: UniversalQuerier['restoreOneById'];
53
+ readonly restoreMany: UniversalQuerier['restoreMany'];
52
54
  /**
53
55
  * end the pool.
54
56
  */
@@ -86,24 +86,19 @@ export class AbstractQuerierPool {
86
86
  runScoped(context, fn) {
87
87
  return context ? withContext(context, fn) : fn();
88
88
  }
89
- findOneById(entity, id, q, opts) {
90
- return this.withQuerier((querier) => querier.findOneById(entity, id, q, opts));
91
- }
92
- findOne(entity, q, opts) {
93
- return this.withQuerier((querier) => querier.findOne(entity, q, opts));
94
- }
95
- findMany(entity, q, opts) {
96
- return this.withQuerier((querier) => querier.findMany(entity, q, opts));
97
- }
89
+ findOneById = (entity, id, q, opts) => this.withQuerier((querier) => querier.findOneById(entity, id, q, opts));
90
+ findOne = (entity, q, opts) => this.withQuerier((querier) => querier.findOne(entity, q, opts));
91
+ findMany = (entity, q, opts) => this.withQuerier((querier) => querier.findMany(entity, q, opts));
98
92
  /**
99
- * The connection outlives the call here: it is held until the iterator is drained or closed by a
100
- * `break`/`throw`. Abandoning the iterator instead leaks it until GC, so consume it in a `for await`.
93
+ * The connection outlives the call: it is held until the iterator is drained or closed by a `break` or
94
+ * `throw`. Abandoning the iterator leaks it until GC, so consume it in a `for await`.
101
95
  */
102
- async *findManyStream(entity, q, opts) {
96
+ findManyStream = (entity, q, opts) => this.streamWithQuerier((querier) => querier.findManyStream(entity, q, opts));
97
+ async *streamWithQuerier(read) {
103
98
  const env_1 = { stack: [], error: void 0, hasError: false };
104
99
  try {
105
100
  const querier = __addDisposableResource(env_1, await this.getQuerier(), true);
106
- yield* querier.findManyStream(entity, q, opts);
101
+ yield* read(querier);
107
102
  }
108
103
  catch (e_1) {
109
104
  env_1.error = e_1;
@@ -115,55 +110,22 @@ export class AbstractQuerierPool {
115
110
  await result_1;
116
111
  }
117
112
  }
118
- findManyAndCount(entity, q, opts) {
119
- return this.withQuerier((querier) => querier.findManyAndCount(entity, q, opts));
120
- }
121
- count(entity, q, opts) {
122
- return this.withQuerier((querier) => querier.count(entity, q, opts));
123
- }
124
- exists(entity, q, opts) {
125
- return this.withQuerier((querier) => querier.exists(entity, q, opts));
126
- }
127
- aggregate(entity, q, opts) {
128
- return this.withQuerier((querier) => querier.aggregate(entity, q, opts));
129
- }
130
- estimatedCount(entity) {
131
- return this.withQuerier((querier) => querier.estimatedCount(entity));
132
- }
133
- insertOne(entity, payload) {
134
- return this.withQuerier((querier) => querier.insertOne(entity, payload));
135
- }
136
- insertMany(entity, payload) {
137
- return this.withQuerier((querier) => querier.insertMany(entity, payload));
138
- }
139
- updateOneById(entity, id, payload, opts) {
140
- return this.withQuerier((querier) => querier.updateOneById(entity, id, payload, opts));
141
- }
142
- updateMany(entity, q, payload, opts) {
143
- return this.withQuerier((querier) => querier.updateMany(entity, q, payload, opts));
144
- }
145
- upsertOne(entity, conflictPaths, payload) {
146
- return this.withQuerier((querier) => querier.upsertOne(entity, conflictPaths, payload));
147
- }
148
- upsertMany(entity, conflictPaths, payload) {
149
- return this.withQuerier((querier) => querier.upsertMany(entity, conflictPaths, payload));
150
- }
151
- saveOne(entity, payload) {
152
- return this.withQuerier((querier) => querier.saveOne(entity, payload));
153
- }
154
- saveMany(entity, payload) {
155
- return this.withQuerier((querier) => querier.saveMany(entity, payload));
156
- }
157
- deleteOneById(entity, id, opts) {
158
- return this.withQuerier((querier) => querier.deleteOneById(entity, id, opts));
159
- }
160
- deleteMany(entity, q, opts) {
161
- return this.withQuerier((querier) => querier.deleteMany(entity, q, opts));
162
- }
163
- restoreOneById(entity, id) {
164
- return this.withQuerier((querier) => querier.restoreOneById(entity, id));
165
- }
166
- restoreMany(entity, q) {
167
- return this.withQuerier((querier) => querier.restoreMany(entity, q));
168
- }
113
+ findManyAndCount = (entity, q, opts) => this.withQuerier((querier) => querier.findManyAndCount(entity, q, opts));
114
+ findManyPage = (entity, q, opts) => this.withQuerier((querier) => querier.findManyPage(entity, q, opts));
115
+ count = (entity, q, opts) => this.withQuerier((querier) => querier.count(entity, q, opts));
116
+ exists = (entity, q, opts) => this.withQuerier((querier) => querier.exists(entity, q, opts));
117
+ aggregate = (entity, q, opts) => this.withQuerier((querier) => querier.aggregate(entity, q, opts));
118
+ estimatedCount = (entity) => this.withQuerier((querier) => querier.estimatedCount(entity));
119
+ insertOne = (entity, payload) => this.withQuerier((querier) => querier.insertOne(entity, payload));
120
+ insertMany = (entity, payload) => this.withQuerier((querier) => querier.insertMany(entity, payload));
121
+ updateOneById = (entity, id, payload, opts) => this.withQuerier((querier) => querier.updateOneById(entity, id, payload, opts));
122
+ updateMany = (entity, q, payload, opts) => this.withQuerier((querier) => querier.updateMany(entity, q, payload, opts));
123
+ upsertOne = (entity, conflictPaths, payload) => this.withQuerier((querier) => querier.upsertOne(entity, conflictPaths, payload));
124
+ upsertMany = (entity, conflictPaths, payload) => this.withQuerier((querier) => querier.upsertMany(entity, conflictPaths, payload));
125
+ saveOne = (entity, payload) => this.withQuerier((querier) => querier.saveOne(entity, payload));
126
+ saveMany = (entity, payload) => this.withQuerier((querier) => querier.saveMany(entity, payload));
127
+ deleteOneById = (entity, id, opts) => this.withQuerier((querier) => querier.deleteOneById(entity, id, opts));
128
+ deleteMany = (entity, q, opts) => this.withQuerier((querier) => querier.deleteMany(entity, q, opts));
129
+ restoreOneById = (entity, id) => this.withQuerier((querier) => querier.restoreOneById(entity, id));
130
+ restoreMany = (entity, q) => this.withQuerier((querier) => querier.restoreMany(entity, q));
169
131
  }
@@ -1,5 +1,5 @@
1
1
  import type { AbstractSqlDialect } from '../dialect/index.js';
2
- import type { EntityData, ExtraOptions, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryPage, QueryGroupMap, QueryOptions, QuerySearch, QueryUpdateResult, SqlQuerier, TransactionOptions, Type, UpdatePayload } from '../type/index.js';
2
+ import type { EntityData, ExtraOptions, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryPage, QueryGroupMap, QueryOptions, QuerySearch, QueryUpdateResult, SqlQuerier, TransactionOptions, Type, UpdatePayload, UpsertOptions } from '../type/index.js';
3
3
  import type { BuildUpdateResultPayload } from '../util/sql.util.js';
4
4
  import { AbstractQuerier } from './abstractQuerier.js';
5
5
  export declare abstract class AbstractSqlQuerier extends AbstractQuerier implements SqlQuerier {
@@ -85,19 +85,18 @@ export declare abstract class AbstractSqlQuerier extends AbstractQuerier impleme
85
85
  protected internalAggregate<E extends object, G extends QueryGroupMap<E>, A extends QueryAggMap<E>>(entity: Type<E>, q: QueryAggregate<E, G, A>, opts?: QueryOptions): Promise<QueryAggregateResult<E, G, A>[]>;
86
86
  internalInsertMany<E extends object>(entity: Type<E>, rows: EntityData<E>[]): Promise<void>;
87
87
  internalUpdateMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, payload: UpdatePayload<E>, opts?: QueryOptions): Promise<number>;
88
- protected internalUpsertOne<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: EntityData<E>): Promise<QueryUpdateResult>;
89
- protected internalUpsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: EntityData<E>[]): Promise<QueryUpdateResult>;
88
+ protected internalUpsertOne<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E, opts: UpsertOptions<E>): Promise<QueryUpdateResult>;
89
+ protected internalUpsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E[], opts: UpsertOptions<E>): Promise<QueryUpdateResult>;
90
90
  private runUpsert;
91
91
  protected internalDeleteMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, opts?: QueryOptions): Promise<number>;
92
92
  get hasOpenTransaction(): boolean;
93
- beginTransaction(opts?: TransactionOptions): Promise<void>;
93
+ protected openTransaction(opts?: TransactionOptions): Promise<void>;
94
94
  /**
95
95
  * Only an end that succeeded ends the transaction. A `COMMIT` that fails can leave it open (SQLite
96
96
  * answers `SQLITE_BUSY` and keeps it), so the flag has to stay set for the `catch` in
97
97
  * {@link AbstractQuerier.transaction} or {@link AbstractQuerier.release} to roll it back.
98
98
  */
99
- commitTransaction(): Promise<void>;
100
- rollbackTransaction(): Promise<void>;
99
+ protected endTransaction(commit: boolean): Promise<void>;
101
100
  /**
102
101
  * How this driver opens, commits and rolls back: the dialect's statements, unless its transactions
103
102
  * are objects rather than statements - Hrana's session handle, `mssql`'s `Transaction` - in which
@@ -2,7 +2,7 @@ import { AGGREGATE_VALUE_ALIAS, TOTAL_ALIAS } from '../dialect/aliases.js';
2
2
  import { decodeColumn } from '../dialect/hydrateColumn.js';
3
3
  import { getMeta, namesKey } from '../entity/index.js';
4
4
  import { COUNT_RESULT_KEY } from '../type/index.js';
5
- import { buildUpdateResult, clone, getInsertFieldKeys, insertShapeOf, isAutoIncrement, isRecord, obtainAttrsPaths, throwNoPendingTransaction, throwPendingTransaction, unflatObject, unflatObjects, } from '../util/index.js';
5
+ import { buildUpdateResult, clone, getInsertFieldKeys, insertShapeOf, isAutoIncrement, isRecord, obtainAttrsPaths, unflatObject, unflatObjects, } from '../util/index.js';
6
6
  import { UqlUsageError } from '../util/uqlError.js';
7
7
  import { AbstractQuerier } from './abstractQuerier.js';
8
8
  import { streamViaCursor } from './cursorStream.js';
@@ -341,10 +341,10 @@ export class AbstractSqlQuerier extends AbstractQuerier {
341
341
  const { changes = 0 } = await this.exec((ctx) => this.dialect.update(ctx, entity, q, payload, opts));
342
342
  return changes;
343
343
  }
344
- async internalUpsertOne(entity, conflictPaths, payload) {
345
- return this.internalUpsertMany(entity, conflictPaths, [payload]);
344
+ async internalUpsertOne(entity, conflictPaths, payload, opts) {
345
+ return this.internalUpsertMany(entity, conflictPaths, [payload], opts);
346
346
  }
347
- async internalUpsertMany(entity, conflictPaths, payload) {
347
+ async internalUpsertMany(entity, conflictPaths, payload, opts) {
348
348
  if (!payload?.length) {
349
349
  return { changes: 0 };
350
350
  }
@@ -355,7 +355,7 @@ export class AbstractSqlQuerier extends AbstractQuerier {
355
355
  // `DO UPDATE SET` resolves to non-binding `EXCLUDED` references rather than inlined values.
356
356
  const statements = groupByInsertShape(meta, payload).flatMap((group) => chunkByBindBudget(meta, payload, group, this.dialect.maxBindValues));
357
357
  if (statements.length === 1) {
358
- return this.runUpsert(entity, conflictPaths, payload);
358
+ return this.runUpsert(entity, conflictPaths, payload, opts);
359
359
  }
360
360
  // An upsert's assignment list is the statement's, so rows of different shapes go in statements
361
361
  // of their own, together in a transaction (`transaction` is re-entrant).
@@ -365,7 +365,7 @@ export class AbstractSqlQuerier extends AbstractQuerier {
365
365
  // than it wrote places none.
366
366
  const ids = new Array(payload.length);
367
367
  for (const indexes of statements) {
368
- const { changes: written = 0, ids: reported } = await this.runUpsert(entity, conflictPaths, indexes.map((index) => payload[index]));
368
+ const { changes: written = 0, ids: reported } = await this.runUpsert(entity, conflictPaths, indexes.map((index) => payload[index]), opts);
369
369
  changes += written;
370
370
  if (reported?.length === indexes.length) {
371
371
  for (let position = 0; position < indexes.length; position++) {
@@ -377,11 +377,11 @@ export class AbstractSqlQuerier extends AbstractQuerier {
377
377
  return { changes, ids };
378
378
  });
379
379
  }
380
- async runUpsert(entity, conflictPaths, payload) {
380
+ async runUpsert(entity, conflictPaths, payload, opts) {
381
381
  const meta = getMeta(entity);
382
382
  // Asked first: the statement fills an `onInsert` key into these rows whether it inserts them or not.
383
383
  const unnamed = meta.ids.length === 1 && payload.some((row) => !namesKey(meta, row));
384
- const result = await this.exec((ctx) => this.dialect.upsert(ctx, entity, conflictPaths, payload));
384
+ const result = await this.exec((ctx) => this.dialect.upsert(ctx, entity, conflictPaths, payload, opts));
385
385
  const ordered = payload.length === 1 ||
386
386
  (this.dialect.insertIdSource === 'returning' && this.dialect.features.orderedUpsertReturning);
387
387
  if (ordered && result.ids?.length === payload.length) {
@@ -403,37 +403,19 @@ export class AbstractSqlQuerier extends AbstractQuerier {
403
403
  get hasOpenTransaction() {
404
404
  return !!this.hasPendingTransaction;
405
405
  }
406
- async beginTransaction(opts) {
407
- return this.serialize(async () => {
408
- if (this.hasPendingTransaction) {
409
- throwPendingTransaction();
410
- }
411
- await this.lazyConnect();
412
- await this.internalBegin(opts);
413
- this.hasPendingTransaction = true;
414
- });
406
+ async openTransaction(opts) {
407
+ await this.lazyConnect();
408
+ await this.internalBegin(opts);
409
+ this.hasPendingTransaction = true;
415
410
  }
416
411
  /**
417
412
  * Only an end that succeeded ends the transaction. A `COMMIT` that fails can leave it open (SQLite
418
413
  * answers `SQLITE_BUSY` and keeps it), so the flag has to stay set for the `catch` in
419
414
  * {@link AbstractQuerier.transaction} or {@link AbstractQuerier.release} to roll it back.
420
415
  */
421
- async commitTransaction() {
422
- return this.serialize(async () => {
423
- if (!this.hasPendingTransaction) {
424
- throwNoPendingTransaction();
425
- }
426
- await this.internalCommit();
427
- this.hasPendingTransaction = false;
428
- });
429
- }
430
- async rollbackTransaction() {
431
- return this.serialize(async () => {
432
- if (this.hasPendingTransaction) {
433
- await this.internalRollback();
434
- this.hasPendingTransaction = false;
435
- }
436
- });
416
+ async endTransaction(commit) {
417
+ await (commit ? this.internalCommit() : this.internalRollback());
418
+ this.hasPendingTransaction = false;
437
419
  }
438
420
  /**
439
421
  * How this driver opens, commits and rolls back: the dialect's statements, unless its transactions
@@ -0,0 +1,10 @@
1
+ import type { EntityMeta, FieldKey } from '../type/index.js';
2
+ /** A sort key whose value a cursor carries, and whether that value may be null. */
3
+ export type CursorKey<E> = {
4
+ readonly key: FieldKey<E>;
5
+ readonly nullable: boolean;
6
+ };
7
+ /** Encodes the cursor for `row` as base64url JSON: the page's `fingerprint`, then each key's value. */
8
+ export declare function mintCursor<E>(meta: EntityMeta<E>, fingerprint: string, keys: readonly CursorKey<E>[], row: object): string;
9
+ /** Decodes the key values in `cursor`, refusing a cursor that no page with this sort minted. */
10
+ export declare function readCursor<E>(meta: EntityMeta<E>, fingerprint: string, keys: readonly CursorKey<E>[], cursor: string): unknown[];
@@ -0,0 +1,81 @@
1
+ import { entityName, getKeys, isRecord } from '../util/object.util.js';
2
+ import { UqlUsageError } from '../util/uqlError.js';
3
+ /** Encodes the cursor for `row` as base64url JSON: the page's `fingerprint`, then each key's value. */
4
+ export function mintCursor(meta, fingerprint, keys, row) {
5
+ const values = keys.map(({ key }) => encodeValue(meta, key, Reflect.get(row, key)));
6
+ return toBase64Url(JSON.stringify([fingerprint, ...values]));
7
+ }
8
+ /** Decodes the key values in `cursor`, refusing a cursor that no page with this sort minted. */
9
+ export function readCursor(meta, fingerprint, keys, cursor) {
10
+ const invalid = () => new UqlUsageError("not a cursor: pass a page's startCursor or endCursor as it came");
11
+ let parsed;
12
+ try {
13
+ parsed = JSON.parse(fromBase64Url(cursor));
14
+ }
15
+ catch {
16
+ throw invalid();
17
+ }
18
+ if (!Array.isArray(parsed) || parsed.length !== keys.length + 1) {
19
+ throw invalid();
20
+ }
21
+ const [minted, ...values] = parsed;
22
+ if (minted !== fingerprint) {
23
+ throw new UqlUsageError(`the cursor was not minted by a page of '${entityName(meta)}' sorted this way`);
24
+ }
25
+ return keys.map((key, at) => {
26
+ const value = decodeValue(values[at]);
27
+ if (value === undefined || (value === null && !key.nullable)) {
28
+ throw invalid();
29
+ }
30
+ return value;
31
+ });
32
+ }
33
+ /**
34
+ * Encodes a row's value so JSON round-trips it exactly. A `Date` is tagged because JSON turns it into text,
35
+ * which MongoDB and SQLite would compare as text; a `bigint` is tagged because JSON cannot represent it.
36
+ */
37
+ function encodeValue(meta, key, value) {
38
+ if (value === undefined || value === null) {
39
+ return null;
40
+ }
41
+ if (value instanceof Date) {
42
+ return { d: value.toISOString() };
43
+ }
44
+ if (typeof value === 'bigint') {
45
+ return { n: String(value) };
46
+ }
47
+ if (typeof value === 'object') {
48
+ throw new UqlUsageError(`cannot page '${entityName(meta)}' by '${key}': a cursor carries scalars, and it holds an object`);
49
+ }
50
+ return value;
51
+ }
52
+ /** Reverses {@link encodeValue}, returning `undefined` for anything it never writes. */
53
+ function decodeValue(value) {
54
+ if (!isRecord(value)) {
55
+ return value === null || ['string', 'number', 'boolean'].includes(typeof value) ? value : undefined;
56
+ }
57
+ const [tag, ...others] = getKeys(value);
58
+ const text = value[tag];
59
+ if (others.length || typeof text !== 'string') {
60
+ return undefined;
61
+ }
62
+ if (tag === 'd') {
63
+ const date = new Date(text);
64
+ return Number.isNaN(date.getTime()) ? undefined : date;
65
+ }
66
+ return tag === 'n' && WHOLE.test(text) ? BigInt(text) : undefined;
67
+ }
68
+ const WHOLE = /^-?\d+$/;
69
+ /** Encodes text as UTF-8 base64url with `btoa`, since `Buffer` is missing on browser and edge runtimes. */
70
+ function toBase64Url(text) {
71
+ let binary = '';
72
+ for (const byte of new TextEncoder().encode(text)) {
73
+ binary += String.fromCharCode(byte);
74
+ }
75
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
76
+ }
77
+ /** Reverses {@link toBase64Url}, throwing on input it never produces. */
78
+ function fromBase64Url(cursor) {
79
+ const binary = atob(cursor.replace(/-/g, '+').replace(/_/g, '/'));
80
+ return new TextDecoder('utf-8', { fatal: true }).decode(Uint8Array.from(binary, (char) => char.charCodeAt(0)));
81
+ }