uql-orm 0.91.0 → 0.92.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/dist/browser/http/bus.js +3 -4
  2. package/dist/browser/http/http.d.ts +1 -2
  3. package/dist/browser/http/http.js +8 -7
  4. package/dist/browser/index.d.ts +0 -1
  5. package/dist/browser/index.js +0 -1
  6. package/dist/browser/querier/httpQuerier.d.ts +18 -20
  7. package/dist/browser/querier/httpQuerier.js +20 -56
  8. package/dist/browser/type/index.d.ts +0 -1
  9. package/dist/browser/type/index.js +0 -1
  10. package/dist/browser/uql-browser.min.js +2 -2
  11. package/dist/browser/uql-browser.min.js.map +11 -12
  12. package/dist/cockroachdb/cockroachDialect.d.ts +4 -1
  13. package/dist/cockroachdb/cockroachDialect.js +5 -1
  14. package/dist/dialect/abstractDialect.d.ts +1 -1
  15. package/dist/dialect/abstractDialect.js +4 -1
  16. package/dist/dialect/abstractSqlDialect.d.ts +24 -28
  17. package/dist/dialect/abstractSqlDialect.js +47 -45
  18. package/dist/dialect/aliases.d.ts +4 -1
  19. package/dist/dialect/aliases.js +5 -2
  20. package/dist/dialect/hydrateColumn.js +3 -10
  21. package/dist/dialect/jsonSql.d.ts +4 -1
  22. package/dist/dialect/jsonSql.js +4 -1
  23. package/dist/dialect/mergeSqlDialect.d.ts +4 -3
  24. package/dist/dialect/mergeSqlDialect.js +5 -4
  25. package/dist/dialect/mysqlLikeSqlDialect.d.ts +7 -21
  26. package/dist/dialect/mysqlLikeSqlDialect.js +9 -36
  27. package/dist/dialect/pgLikeSqlDialect.d.ts +3 -7
  28. package/dist/dialect/pgLikeSqlDialect.js +11 -21
  29. package/dist/http/contract.d.ts +4 -0
  30. package/dist/http/contract.js +1 -0
  31. package/dist/http/handler.d.ts +2 -2
  32. package/dist/http/handler.js +17 -19
  33. package/dist/http/query.d.ts +5 -3
  34. package/dist/http/query.js +42 -42
  35. package/dist/index.d.ts +1 -1
  36. package/dist/index.js +1 -1
  37. package/dist/maria/mariaDialect.d.ts +2 -3
  38. package/dist/maria/mariaDialect.js +1 -5
  39. package/dist/migrate/builder/columnBuilder.d.ts +5 -15
  40. package/dist/migrate/builder/columnBuilder.js +50 -86
  41. package/dist/migrate/builder/expressions.d.ts +12 -18
  42. package/dist/migrate/builder/expressions.js +39 -42
  43. package/dist/migrate/builder/migrationBuilder.d.ts +3 -11
  44. package/dist/migrate/builder/migrationBuilder.js +41 -81
  45. package/dist/migrate/builder/tableBuilder.d.ts +0 -7
  46. package/dist/migrate/builder/tableBuilder.js +17 -28
  47. package/dist/migrate/builder/types.d.ts +2 -2
  48. package/dist/migrate/codegen/entityCodeGenerator.js +7 -13
  49. package/dist/migrate/codegen/entityTypes.js +6 -20
  50. package/dist/migrate/codegen/fieldOptionsSource.d.ts +2 -2
  51. package/dist/migrate/codegen/fieldOptionsSource.js +27 -12
  52. package/dist/migrate/codegen/indexDecoratorSource.js +64 -41
  53. package/dist/migrate/ddl/index.d.ts +2 -4
  54. package/dist/migrate/ddl/index.js +14 -5
  55. package/dist/migrate/ddl/mssqlTableDdl.d.ts +1 -0
  56. package/dist/migrate/ddl/mssqlTableDdl.js +4 -1
  57. package/dist/migrate/ddl/mysqlTableDdl.d.ts +17 -0
  58. package/dist/migrate/ddl/mysqlTableDdl.js +33 -0
  59. package/dist/migrate/ddl/pgTableDdl.d.ts +7 -0
  60. package/dist/migrate/ddl/pgTableDdl.js +17 -0
  61. package/dist/migrate/ddl/tableDdl.d.ts +15 -10
  62. package/dist/migrate/ddl/tableDdl.js +31 -32
  63. package/dist/migrate/drift/driftDetector.js +46 -59
  64. package/dist/migrate/generator/definitionToNode.d.ts +11 -7
  65. package/dist/migrate/generator/definitionToNode.js +27 -34
  66. package/dist/migrate/generator/indexNodeToSchema.d.ts +3 -3
  67. package/dist/migrate/generator/indexNodeToSchema.js +5 -4
  68. package/dist/migrate/index.js +1 -1
  69. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +10 -5
  70. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +10 -0
  71. package/dist/migrate/introspection/baseSqlIntrospector.d.ts +0 -1
  72. package/dist/migrate/introspection/baseSqlIntrospector.js +6 -8
  73. package/dist/migrate/introspection/mssqlIntrospector.js +3 -8
  74. package/dist/migrate/introspection/mysqlIntrospector.d.ts +11 -4
  75. package/dist/migrate/introspection/mysqlIntrospector.js +25 -11
  76. package/dist/migrate/introspection/postgresIntrospector.d.ts +2 -2
  77. package/dist/migrate/introspection/postgresIntrospector.js +3 -3
  78. package/dist/migrate/introspection/sqliteIntrospector.d.ts +1 -1
  79. package/dist/migrate/introspection/sqliteIntrospector.js +7 -10
  80. package/dist/migrate/migrationTarget.js +3 -3
  81. package/dist/migrate/schemaGenerator.d.ts +8 -12
  82. package/dist/migrate/schemaGenerator.js +35 -61
  83. package/dist/migrate/triggerSql.d.ts +1 -1
  84. package/dist/migrate/triggerSql.js +8 -6
  85. package/dist/mongo/mongoDialect.d.ts +4 -3
  86. package/dist/mongo/mongoDialect.js +52 -38
  87. package/dist/mongo/mongoIntrospector.js +1 -1
  88. package/dist/mongo/mongoSchemaGenerator.d.ts +7 -4
  89. package/dist/mongo/mongoSchemaGenerator.js +18 -21
  90. package/dist/mongo/mongodbQuerier.d.ts +2 -3
  91. package/dist/mongo/mongodbQuerier.js +9 -28
  92. package/dist/mssql/mssqlDialect.d.ts +4 -5
  93. package/dist/mssql/mssqlDialect.js +9 -7
  94. package/dist/postgres/postgresDialect.js +2 -2
  95. package/dist/querier/abstractQuerier.d.ts +16 -11
  96. package/dist/querier/abstractQuerier.js +74 -26
  97. package/dist/querier/abstractQuerierPool.d.ts +26 -24
  98. package/dist/querier/abstractQuerierPool.js +26 -64
  99. package/dist/querier/abstractSqlQuerier.d.ts +2 -3
  100. package/dist/querier/abstractSqlQuerier.js +8 -26
  101. package/dist/querier/cursor.d.ts +10 -0
  102. package/dist/querier/cursor.js +81 -0
  103. package/dist/querier/keyset.d.ts +19 -0
  104. package/dist/querier/keyset.js +198 -0
  105. package/dist/schema/canonicalType.d.ts +3 -3
  106. package/dist/schema/canonicalType.js +13 -12
  107. package/dist/schema/indexDifferences.d.ts +14 -7
  108. package/dist/schema/indexDifferences.js +7 -5
  109. package/dist/schema/schemaAST.d.ts +0 -1
  110. package/dist/schema/schemaAST.js +0 -2
  111. package/dist/schema/schemaASTBuilder.js +28 -20
  112. package/dist/schema/schemaASTDiffer.d.ts +7 -9
  113. package/dist/schema/schemaASTDiffer.js +54 -107
  114. package/dist/schema/sqlExpression.d.ts +22 -0
  115. package/dist/schema/sqlExpression.js +28 -0
  116. package/dist/schema/types.d.ts +48 -105
  117. package/dist/sqlite/sqliteDialect.d.ts +9 -13
  118. package/dist/sqlite/sqliteDialect.js +10 -29
  119. package/dist/type/dialect.d.ts +20 -3
  120. package/dist/type/entity.d.ts +7 -20
  121. package/dist/type/migration.d.ts +7 -7
  122. package/dist/type/querier.d.ts +19 -26
  123. package/dist/type/query.d.ts +104 -24
  124. package/dist/type/query.js +21 -28
  125. package/dist/type/universalQuerier.d.ts +31 -5
  126. package/dist/type/utility.d.ts +10 -0
  127. package/dist/util/bytes.d.ts +7 -0
  128. package/dist/util/bytes.js +22 -0
  129. package/dist/util/date.d.ts +5 -0
  130. package/dist/util/date.js +5 -0
  131. package/dist/util/dialect.util.d.ts +1 -25
  132. package/dist/util/dialect.util.js +4 -50
  133. package/dist/util/field.util.d.ts +9 -0
  134. package/dist/util/field.util.js +15 -0
  135. package/dist/util/fieldOption.util.js +2 -2
  136. package/dist/util/index.d.ts +1 -0
  137. package/dist/util/index.js +1 -0
  138. package/dist/util/object.util.d.ts +0 -2
  139. package/dist/util/object.util.js +0 -7
  140. package/dist/util/query.util.d.ts +40 -0
  141. package/dist/util/query.util.js +76 -0
  142. package/dist/util/raw.d.ts +5 -0
  143. package/dist/util/raw.js +5 -0
  144. package/dist/util/relationQuery.util.js +18 -16
  145. package/dist/util/rowKey.util.js +2 -3
  146. package/dist/util/sql.util.d.ts +8 -2
  147. package/dist/util/sql.util.js +16 -17
  148. package/dist/util/sqlLiteral.js +2 -12
  149. package/dist/util/string.util.d.ts +5 -0
  150. package/dist/util/string.util.js +12 -0
  151. package/package.json +1 -1
  152. package/skills/uql-orm/SKILL.md +22 -11
  153. package/dist/browser/options.d.ts +0 -4
  154. package/dist/browser/options.js +0 -13
  155. package/dist/browser/type/clientQuerierPool.d.ts +0 -4
  156. package/dist/browser/type/clientQuerierPool.js +0 -1
@@ -3,6 +3,7 @@ import { namesRows } from '../dialect/operators.js';
3
3
  import { parseQueryLock } from '../type/index.js';
4
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';
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,
@@ -100,6 +101,23 @@ function adoptReportedIds(meta, rows, reported) {
100
101
  rows[index][idKey] ??= reported[index];
101
102
  }
102
103
  }
104
+ /** Normalizes either call form to `[entity, query, opts]`, throwing when a query object has no `$entity`. */
105
+ function entityArgs(args) {
106
+ if (isEntityFirst(args)) {
107
+ const [entity, q, opts] = args;
108
+ return [entity, q ?? {}, opts];
109
+ }
110
+ const [{ $entity, ...q }, opts] = args;
111
+ if (!$entity) {
112
+ throw new UqlUsageError('$entity is required when using query-object syntax');
113
+ }
114
+ return [$entity, q, opts];
115
+ }
116
+ /** Whether the entity is passed first, i.e. the first argument is a class rather than a query object. */
117
+ function isEntityFirst(args) {
118
+ const [first] = args;
119
+ return typeof first === 'function' && first.prototype !== undefined;
120
+ }
103
121
  /** Base class for all database queriers. */
104
122
  export class AbstractQuerier {
105
123
  extra;
@@ -156,29 +174,17 @@ export class AbstractQuerier {
156
174
  }
157
175
  });
158
176
  }
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
177
  async findOneById(entity, id, q = {}, opts) {
172
178
  assertIdValue(entity, id);
173
179
  return this.findOne(entity, { ...q, $where: { ...q.$where, ...whereIds(getMeta(entity), id) } }, opts);
174
180
  }
175
- async findOne(entityOrQuery, maybeQueryOrOpts, maybeOpts) {
176
- const [entity, q, opts] = this.resolveEntityQuery(entityOrQuery, maybeQueryOrOpts, maybeOpts);
181
+ async findOne(...args) {
182
+ const [entity, q, opts] = entityArgs(args);
177
183
  const rows = await this.findMany(entity, { ...q, $limit: 1 }, opts);
178
184
  return rows[0];
179
185
  }
180
- async findMany(entityOrQuery, maybeQueryOrOpts, maybeOpts) {
181
- const [entity, q, opts] = this.resolveEntityQuery(entityOrQuery, maybeQueryOrOpts, maybeOpts);
186
+ async findMany(...args) {
187
+ const [entity, q, opts] = entityArgs(args);
182
188
  this.validateReadQuery(entity, q);
183
189
  const founds = await this.internalFindMany(entity, q, opts);
184
190
  // Guarded here rather than only inside: awaiting a call that returns at once still costs every read
@@ -188,13 +194,13 @@ export class AbstractQuerier {
188
194
  }
189
195
  return founds;
190
196
  }
191
- findManyStream(entityOrQuery, maybeQueryOrOpts, maybeOpts) {
192
- const [entity, q, opts] = this.resolveEntityQuery(entityOrQuery, maybeQueryOrOpts, maybeOpts);
197
+ findManyStream(...args) {
198
+ const [entity, q, opts] = entityArgs(args);
193
199
  this.validateReadQuery(entity, q);
194
200
  return this.internalFindManyStream(entity, q, opts);
195
201
  }
196
- async findManyAndCount(entityOrQuery, maybeQueryOrOpts, maybeOpts) {
197
- const [entity, q, opts] = this.resolveEntityQuery(entityOrQuery, maybeQueryOrOpts, maybeOpts);
202
+ async findManyAndCount(...args) {
203
+ const [entity, q, opts] = entityArgs(args);
198
204
  this.validateReadQuery(entity, q);
199
205
  const [founds, count] = await this.internalFindManyAndCount(entity, q, opts);
200
206
  if (this.listensForLoad(entity, q.$populate)) {
@@ -212,12 +218,26 @@ export class AbstractQuerier {
212
218
  this.internalCount(entity, { $where: q.$where }, opts),
213
219
  ]);
214
220
  }
215
- async count(entityOrQuery, maybeQueryOrOpts, maybeOpts) {
216
- const [entity, q, opts] = this.resolveEntityQuery(entityOrQuery, maybeQueryOrOpts, maybeOpts);
221
+ /**
222
+ * Shared by every backend: the keyset condition is an ordinary `$where`, so each engine renders it with the
223
+ * operators it already has, and the page holds the rows `findMany` would return.
224
+ */
225
+ async findManyPage(...args) {
226
+ const [entity, q, opts] = entityArgs(args);
227
+ this.validateReadQuery(entity, q);
228
+ const read = keysetRead(getMeta(entity), q, this.dialect.features.nullsSortLowest);
229
+ const page = read.page(await this.internalFindMany(entity, read.query, opts));
230
+ if (this.listensForLoad(entity, q.$populate)) {
231
+ await this.emitLoaded(entity, page.items, q.$populate);
232
+ }
233
+ return page;
234
+ }
235
+ async count(...args) {
236
+ const [entity, q, opts] = entityArgs(args);
217
237
  return this.internalCount(entity, q, opts);
218
238
  }
219
- async exists(entityOrQuery, maybeQueryOrOpts, maybeOpts) {
220
- const [entity, q, opts] = this.resolveEntityQuery(entityOrQuery, maybeQueryOrOpts, maybeOpts);
239
+ async exists(...args) {
240
+ const [entity, q, opts] = entityArgs(args);
221
241
  return (await this.internalCount(entity, { $where: q.$where, $limit: 1 }, opts)) > 0;
222
242
  }
223
243
  /**
@@ -411,8 +431,8 @@ export class AbstractQuerier {
411
431
  assertIdValue(entity, id);
412
432
  return this.deleteMany(entity, { $where: whereIds(getMeta(entity), id) }, opts);
413
433
  }
414
- async deleteMany(entityOrQuery, qOrOpts, maybeOpts) {
415
- const [entity, q, opts] = this.resolveEntityQuery(entityOrQuery, qOrOpts, maybeOpts);
434
+ async deleteMany(...args) {
435
+ const [entity, q, opts] = entityArgs(args);
416
436
  assertNamesRows(entity, 'deleteMany', q, opts);
417
437
  const meta = getMeta(entity);
418
438
  const cascades = cascadesOnDelete(meta);
@@ -687,6 +707,34 @@ export class AbstractQuerier {
687
707
  this.logger.logQuery(query, values, Math.round(performance.now() - startTime));
688
708
  }
689
709
  }
710
+ beginTransaction(opts) {
711
+ return this.serialize(async () => {
712
+ if (this.hasOpenTransaction) {
713
+ throw new UqlUsageError('pending transaction');
714
+ }
715
+ await this.openTransaction(opts);
716
+ });
717
+ }
718
+ /** Strict: this is the check that catches a forgotten `beginTransaction`. */
719
+ commitTransaction() {
720
+ return this.serialize(async () => {
721
+ if (!this.hasOpenTransaction) {
722
+ throw new UqlUsageError('not a pending transaction');
723
+ }
724
+ await this.endTransaction(true);
725
+ });
726
+ }
727
+ /**
728
+ * Rolls the open transaction back, or does nothing when there is none: it is called from `catch` and
729
+ * `finally`, where the caller cannot know whether `beginTransaction` got far enough to open one.
730
+ */
731
+ rollbackTransaction() {
732
+ return this.serialize(async () => {
733
+ if (this.hasOpenTransaction) {
734
+ await this.endTransaction(false);
735
+ }
736
+ });
737
+ }
690
738
  /**
691
739
  * Rolls back an unfinished transaction, then hands the connection back, discarding it if the rollback
692
740
  * 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
  }
@@ -90,14 +90,13 @@ export declare abstract class AbstractSqlQuerier extends AbstractQuerier impleme
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';
@@ -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
+ }
@@ -0,0 +1,19 @@
1
+ import type { CursorPage, EntityMeta, Query, QueryKeyset } from '../type/index.js';
2
+ /**
3
+ * A resolved `findManyPage` query: the query to run, and the function that builds the page from its rows.
4
+ * [The design](../../../../architecture/cursor-pagination.md).
5
+ */
6
+ export type KeysetRead<E> = {
7
+ readonly query: Query<E>;
8
+ /**
9
+ * Builds the page from the rows `query` returns: drops the extra row, restores the order of rows read
10
+ * backward, mints a cursor from the first and last rows, and removes the keys the projection left out.
11
+ */
12
+ readonly page: (rows: readonly E[]) => CursorPage<E>;
13
+ };
14
+ /**
15
+ * Turns a page query into the query to run: checks that `$sort` is total, inverts it for `$before`, turns
16
+ * the cursor into a `$where` for the rows past it, and reads one row over the page size to tell whether
17
+ * another page follows. `nullsSortLowest` says where the engine sorts nulls, for keys with no placement.
18
+ */
19
+ export declare function keysetRead<E extends object>(meta: EntityMeta<E>, q: QueryKeyset<E>, nullsSortLowest: boolean): KeysetRead<E>;