uql-orm 0.28.2 → 0.30.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.
- package/dist/browser/querier/httpQuerier.d.ts +5 -5
- package/dist/browser/uql-browser.min.js +2 -2
- package/dist/browser/uql-browser.min.js.map +3 -3
- package/dist/dialect/abstractSqlDialect.d.ts +6 -4
- package/dist/dialect/abstractSqlDialect.js +29 -29
- package/dist/dialect/mysqlLikeSqlDialect.d.ts +3 -1
- package/dist/dialect/mysqlLikeSqlDialect.js +9 -0
- package/dist/dialect/vectorSqlDialect.js +8 -1
- package/dist/mongo/mongoDialect.d.ts +3 -3
- package/dist/mongo/mongoDialect.js +17 -9
- package/dist/mongo/mongodbQuerier.d.ts +9 -4
- package/dist/mongo/mongodbQuerier.js +15 -7
- package/dist/mysql/mysql2Querier.d.ts +1 -1
- package/dist/mysql/mysql2Querier.js +7 -1
- package/dist/nestjs/uqlContextInterceptor.d.ts +2 -2
- package/dist/nestjs/uqlContextInterceptor.js +2 -2
- package/dist/nestjs/uqlModule.d.ts +3 -3
- package/dist/nestjs/uqlModule.js +5 -6
- package/dist/postgres/abstractPgQuerier.d.ts +3 -2
- package/dist/postgres/abstractPgQuerier.js +2 -2
- package/dist/querier/abstractPoolQuerier.d.ts +2 -2
- package/dist/querier/abstractPoolQuerier.js +7 -7
- package/dist/querier/abstractQuerier.d.ts +45 -16
- package/dist/querier/abstractQuerier.js +99 -40
- package/dist/querier/abstractQuerierPool.d.ts +7 -7
- package/dist/querier/abstractSqlQuerier.d.ts +17 -6
- package/dist/querier/abstractSqlQuerier.js +61 -34
- package/dist/querier/index.d.ts +0 -2
- package/dist/querier/index.js +0 -2
- package/dist/sqlite/abstractSqliteQuerier.d.ts +1 -2
- package/dist/sqlite/abstractSqliteQuerier.js +2 -8
- package/dist/sqlite/hranaQuerier.d.ts +5 -0
- package/dist/sqlite/hranaQuerier.js +10 -6
- package/dist/type/entity.d.ts +34 -11
- package/dist/type/querier.d.ts +26 -10
- package/dist/type/query.d.ts +22 -9
- package/dist/type/queryAggregate.d.ts +67 -24
- package/dist/type/queryWhere.d.ts +4 -1
- package/dist/type/universalQuerier.d.ts +11 -11
- package/dist/util/dialect.util.d.ts +26 -4
- package/dist/util/dialect.util.js +42 -0
- package/package.json +4 -5
- package/dist/querier/querierContext.browser.d.ts +0 -12
- package/dist/querier/querierContext.browser.js +0 -18
- package/dist/querier/querierContext.d.ts +0 -22
- package/dist/querier/querierContext.js +0 -42
- package/dist/querier/transactional.d.ts +0 -26
- package/dist/querier/transactional.js +0 -43
|
@@ -3,6 +3,14 @@ import { getMeta } from '../entity/index.js';
|
|
|
3
3
|
import { buildUpdateResult, cascadesOnDelete, clone, getInsertFieldKeys, getRelationRequestSummary, isAutoIncrement, obtainAttrsPaths, throwNoPendingTransaction, throwPendingTransaction, unflatObject, unflatObjects, withoutSoftDeleteFilter, } from '../util/index.js';
|
|
4
4
|
import { AbstractQuerier } from './abstractQuerier.js';
|
|
5
5
|
import { enrichError } from './queryError.js';
|
|
6
|
+
/**
|
|
7
|
+
* Whether `q` picks a specific slice of the matching rows rather than all of them. A write that
|
|
8
|
+
* does has to settle those rows and name them: `ORDER BY`/`LIMIT` on an UPDATE or DELETE is MySQL's
|
|
9
|
+
* alone.
|
|
10
|
+
*/
|
|
11
|
+
function isPaged(q) {
|
|
12
|
+
return q.$sort !== undefined || q.$limit !== undefined || q.$skip !== undefined;
|
|
13
|
+
}
|
|
6
14
|
export class AbstractSqlQuerier extends AbstractQuerier {
|
|
7
15
|
dialect;
|
|
8
16
|
extra;
|
|
@@ -35,10 +43,15 @@ export class AbstractSqlQuerier extends AbstractQuerier {
|
|
|
35
43
|
return Number.isInteger(value) && value > 0 ? value : 1;
|
|
36
44
|
}
|
|
37
45
|
/**
|
|
38
|
-
* Hook for subclasses (e.g. pool queriers) to establish a connection.
|
|
39
|
-
*
|
|
46
|
+
* Hook for subclasses (e.g. pool queriers) to establish a connection. Called before every query and
|
|
47
|
+
* before `BEGIN`, outside the timing window, which makes it the one place a released querier is
|
|
48
|
+
* caught for every SQL backend.
|
|
40
49
|
*/
|
|
41
|
-
async lazyConnect() {
|
|
50
|
+
async lazyConnect() {
|
|
51
|
+
if (this.released) {
|
|
52
|
+
throw new TypeError('querier already released');
|
|
53
|
+
}
|
|
54
|
+
}
|
|
42
55
|
async all(query, values) {
|
|
43
56
|
return this.serialize(async () => {
|
|
44
57
|
await this.lazyConnect();
|
|
@@ -214,12 +227,30 @@ export class AbstractSqlQuerier extends AbstractQuerier {
|
|
|
214
227
|
}
|
|
215
228
|
async internalUpdateMany(entity, q, payload, opts) {
|
|
216
229
|
payload = clone(payload);
|
|
230
|
+
// Settled first for the reason `internalDeleteMany` settles: `ORDER BY`/`LIMIT` on an UPDATE is
|
|
231
|
+
// MySQL's alone, so a paged update has to name the rows it picked.
|
|
232
|
+
let target = q;
|
|
233
|
+
if (isPaged(q)) {
|
|
234
|
+
const ids = await this.settleIds(entity, q, opts);
|
|
235
|
+
if (!ids.length) {
|
|
236
|
+
return 0;
|
|
237
|
+
}
|
|
238
|
+
target = { $where: ids };
|
|
239
|
+
}
|
|
217
240
|
const ctx = this.dialect.createContext();
|
|
218
|
-
this.dialect.update(ctx, entity,
|
|
241
|
+
this.dialect.update(ctx, entity, target, payload, opts);
|
|
219
242
|
const { changes = 0 } = await this.run(ctx.sql, ctx.values);
|
|
220
|
-
await this.updateRelations(entity,
|
|
243
|
+
await this.updateRelations(entity, target, payload, opts);
|
|
221
244
|
return changes;
|
|
222
245
|
}
|
|
246
|
+
/** The ids matching `q`, in `q`'s own order and page, so a write can name the rows it settled on. */
|
|
247
|
+
async settleIds(entity, q, opts) {
|
|
248
|
+
const meta = getMeta(entity);
|
|
249
|
+
const ctx = this.dialect.createContext();
|
|
250
|
+
this.dialect.find(ctx, entity, { ...q, $select: { [meta.id]: true } }, opts);
|
|
251
|
+
const founds = await this.all(ctx.sql, ctx.values);
|
|
252
|
+
return founds.map((it) => it[meta.id]);
|
|
253
|
+
}
|
|
223
254
|
async upsertOne(entity, conflictPaths, payload) {
|
|
224
255
|
return this.upsertMany(entity, conflictPaths, [payload]);
|
|
225
256
|
}
|
|
@@ -247,8 +278,7 @@ export class AbstractSqlQuerier extends AbstractQuerier {
|
|
|
247
278
|
// parents' ids to find their children, and no engine but MySQL accepts `ORDER BY`/`LIMIT` on a
|
|
248
279
|
// DELETE, so a paged delete has to name the rows it settled on. A plain predicate needs neither,
|
|
249
280
|
// and there the round trip buys nothing: the statement can say what the caller already said.
|
|
250
|
-
|
|
251
|
-
if (!hasPagination && !cascadesOnDelete(meta)) {
|
|
281
|
+
if (!isPaged(q) && !cascadesOnDelete(meta)) {
|
|
252
282
|
const ctx = this.dialect.createContext();
|
|
253
283
|
this.dialect.delete(ctx, entity, q, opts);
|
|
254
284
|
const { changes = 0 } = await this.run(ctx.sql, ctx.values);
|
|
@@ -256,13 +286,10 @@ export class AbstractSqlQuerier extends AbstractQuerier {
|
|
|
256
286
|
}
|
|
257
287
|
// A hard delete also targets already-soft-deleted rows, so drop the soft-delete filter when finding ids.
|
|
258
288
|
const findOpts = opts?.hardDelete ? { ...opts, filters: withoutSoftDeleteFilter(opts.filters) } : opts;
|
|
259
|
-
const
|
|
260
|
-
|
|
261
|
-
const founds = await this.all(findCtx.sql, findCtx.values);
|
|
262
|
-
if (!founds.length) {
|
|
289
|
+
const ids = await this.settleIds(entity, q, findOpts);
|
|
290
|
+
if (!ids.length) {
|
|
263
291
|
return 0;
|
|
264
292
|
}
|
|
265
|
-
const ids = founds.map((it) => it[meta.id]);
|
|
266
293
|
// Children first: they hold the foreign key, so deleting the parent ahead of them is rejected
|
|
267
294
|
// outright by any schema that declares the constraint without `ON DELETE CASCADE`.
|
|
268
295
|
await this.deleteRelations(entity, ids, opts);
|
|
@@ -281,12 +308,7 @@ export class AbstractSqlQuerier extends AbstractQuerier {
|
|
|
281
308
|
}
|
|
282
309
|
await this.lazyConnect();
|
|
283
310
|
for (const sql of this.dialect.getBeginTransactionStatements(opts?.isolationLevel)) {
|
|
284
|
-
|
|
285
|
-
await this.internalRun(sql);
|
|
286
|
-
}
|
|
287
|
-
catch (err) {
|
|
288
|
-
throw enrichError(err, this.logger, sql);
|
|
289
|
-
}
|
|
311
|
+
await this.runTransactionCommand(sql);
|
|
290
312
|
}
|
|
291
313
|
this.hasPendingTransaction = true;
|
|
292
314
|
});
|
|
@@ -296,27 +318,32 @@ export class AbstractSqlQuerier extends AbstractQuerier {
|
|
|
296
318
|
if (!this.hasPendingTransaction) {
|
|
297
319
|
throwNoPendingTransaction();
|
|
298
320
|
}
|
|
299
|
-
|
|
300
|
-
await this.internalRun(this.dialect.commitTransactionCommand);
|
|
301
|
-
}
|
|
302
|
-
catch (err) {
|
|
303
|
-
throw enrichError(err, this.logger, this.dialect.commitTransactionCommand);
|
|
304
|
-
}
|
|
305
|
-
this.hasPendingTransaction = false;
|
|
321
|
+
await this.endTransactionWith(this.dialect.commitTransactionCommand);
|
|
306
322
|
});
|
|
307
323
|
}
|
|
308
324
|
async rollbackTransaction() {
|
|
309
325
|
return this.serialize(async () => {
|
|
310
|
-
if (
|
|
311
|
-
|
|
312
|
-
}
|
|
313
|
-
try {
|
|
314
|
-
await this.internalRun(this.dialect.rollbackTransactionCommand);
|
|
315
|
-
}
|
|
316
|
-
catch (err) {
|
|
317
|
-
throw enrichError(err, this.logger, this.dialect.rollbackTransactionCommand);
|
|
326
|
+
if (this.hasPendingTransaction) {
|
|
327
|
+
await this.endTransactionWith(this.dialect.rollbackTransactionCommand);
|
|
318
328
|
}
|
|
319
|
-
this.hasPendingTransaction = false;
|
|
320
329
|
});
|
|
321
330
|
}
|
|
331
|
+
/**
|
|
332
|
+
* Only a statement that succeeded ends the transaction. A `COMMIT` that fails can leave it open
|
|
333
|
+
* (SQLite answers `SQLITE_BUSY` and keeps it), so the flag has to stay set for the `catch` in
|
|
334
|
+
* {@link AbstractQuerier.transaction} or {@link AbstractQuerier.release} to roll it back.
|
|
335
|
+
*/
|
|
336
|
+
async endTransactionWith(command) {
|
|
337
|
+
await this.runTransactionCommand(command);
|
|
338
|
+
this.hasPendingTransaction = false;
|
|
339
|
+
}
|
|
340
|
+
/** Transaction statements skip `timed()`, so they attach their own query context to a failure. */
|
|
341
|
+
async runTransactionCommand(sql) {
|
|
342
|
+
try {
|
|
343
|
+
await this.internalRun(sql);
|
|
344
|
+
}
|
|
345
|
+
catch (err) {
|
|
346
|
+
throw enrichError(err, this.logger, sql);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
322
349
|
}
|
package/dist/querier/index.d.ts
CHANGED
|
@@ -2,6 +2,4 @@ export * from './abstractQuerier.js';
|
|
|
2
2
|
export * from './abstractQuerierPool.js';
|
|
3
3
|
export * from './abstractSqlQuerier.js';
|
|
4
4
|
export * from './abstractSqlQuerierPool.js';
|
|
5
|
-
export * from './querierContext.js';
|
|
6
5
|
export * from './queryError.js';
|
|
7
|
-
export * from './transactional.js';
|
package/dist/querier/index.js
CHANGED
|
@@ -2,6 +2,4 @@ export * from './abstractQuerier.js';
|
|
|
2
2
|
export * from './abstractQuerierPool.js';
|
|
3
3
|
export * from './abstractSqlQuerier.js';
|
|
4
4
|
export * from './abstractSqlQuerierPool.js';
|
|
5
|
-
export * from './querierContext.js';
|
|
6
5
|
export * from './queryError.js';
|
|
7
|
-
export * from './transactional.js';
|
|
@@ -30,8 +30,7 @@ export type SqlitePreparedStatement = {
|
|
|
30
30
|
export declare abstract class AbstractSqliteQuerier extends AbstractSqlQuerier {
|
|
31
31
|
/**
|
|
32
32
|
* SQLite drivers hold a single shared handle rather than a connection from a pool, so releasing
|
|
33
|
-
* a querier returns nothing
|
|
34
|
-
* closable per-querier connection override this.
|
|
33
|
+
* a querier returns nothing at all. Drivers owning a closable per-querier connection override this.
|
|
35
34
|
*/
|
|
36
35
|
internalRelease(): Promise<void>;
|
|
37
36
|
}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { AbstractSqlQuerier } from '../querier/index.js';
|
|
2
|
-
import { throwPendingTransaction } from '../util/index.js';
|
|
3
2
|
/** Bound parameters reach a driver as `unknown[]` from the compiler; every driver types them narrowly. */
|
|
4
3
|
export function toSqliteBindValues(values) {
|
|
5
4
|
return (values || []);
|
|
@@ -7,14 +6,9 @@ export function toSqliteBindValues(values) {
|
|
|
7
6
|
export class AbstractSqliteQuerier extends AbstractSqlQuerier {
|
|
8
7
|
/**
|
|
9
8
|
* SQLite drivers hold a single shared handle rather than a connection from a pool, so releasing
|
|
10
|
-
* a querier returns nothing
|
|
11
|
-
* closable per-querier connection override this.
|
|
9
|
+
* a querier returns nothing at all. Drivers owning a closable per-querier connection override this.
|
|
12
10
|
*/
|
|
13
|
-
async internalRelease() {
|
|
14
|
-
if (this.hasOpenTransaction) {
|
|
15
|
-
throwPendingTransaction();
|
|
16
|
-
}
|
|
17
|
-
}
|
|
11
|
+
async internalRelease() { }
|
|
18
12
|
}
|
|
19
13
|
/**
|
|
20
14
|
* Querier for the SQLite drivers that expose prepared statements: `better-sqlite3`, `bun:sqlite`
|
|
@@ -48,6 +48,11 @@ export declare class HranaQuerier extends AbstractSqliteQuerier {
|
|
|
48
48
|
internalRun(query: string, values?: unknown[]): Promise<import("../type/query.js").QueryUpdateResult>;
|
|
49
49
|
get hasOpenTransaction(): boolean;
|
|
50
50
|
beginTransaction(_opts?: TransactionOptions): Promise<void>;
|
|
51
|
+
/**
|
|
52
|
+
* Both drop the handle before the call, not after: one that outlived a failed commit or rollback left
|
|
53
|
+
* the querier unreleasable. The optional call in the rollback is also what makes it a no-op when
|
|
54
|
+
* there is nothing open.
|
|
55
|
+
*/
|
|
51
56
|
commitTransaction(): Promise<void>;
|
|
52
57
|
rollbackTransaction(): Promise<void>;
|
|
53
58
|
internalRelease(): Promise<void>;
|
|
@@ -41,22 +41,26 @@ export class HranaQuerier extends AbstractSqliteQuerier {
|
|
|
41
41
|
this.tx = await this.client.transaction('write');
|
|
42
42
|
});
|
|
43
43
|
}
|
|
44
|
+
/**
|
|
45
|
+
* Both drop the handle before the call, not after: one that outlived a failed commit or rollback left
|
|
46
|
+
* the querier unreleasable. The optional call in the rollback is also what makes it a no-op when
|
|
47
|
+
* there is nothing open.
|
|
48
|
+
*/
|
|
44
49
|
async commitTransaction() {
|
|
45
50
|
return this.serialize(async () => {
|
|
46
|
-
|
|
51
|
+
const tx = this.tx;
|
|
52
|
+
if (!tx) {
|
|
47
53
|
throwNoPendingTransaction();
|
|
48
54
|
}
|
|
49
|
-
await this.tx.commit();
|
|
50
55
|
this.tx = undefined;
|
|
56
|
+
await tx.commit();
|
|
51
57
|
});
|
|
52
58
|
}
|
|
53
59
|
async rollbackTransaction() {
|
|
54
60
|
return this.serialize(async () => {
|
|
55
|
-
|
|
56
|
-
throwNoPendingTransaction();
|
|
57
|
-
}
|
|
58
|
-
await this.tx.rollback();
|
|
61
|
+
const tx = this.tx;
|
|
59
62
|
this.tx = undefined;
|
|
63
|
+
await tx?.rollback();
|
|
60
64
|
});
|
|
61
65
|
}
|
|
62
66
|
async internalRelease() {
|
package/dist/type/entity.d.ts
CHANGED
|
@@ -16,16 +16,20 @@ export type Key<E> = keyof E & string;
|
|
|
16
16
|
* Includes scalar fields, JSON fields, and scalar arrays (e.g. vector `number[]`).
|
|
17
17
|
* The `-?` modifier strips optionality so the indexed access yields clean key unions
|
|
18
18
|
* (without it, optional properties leak `undefined` into the union).
|
|
19
|
+
*
|
|
20
|
+
* The check is bracketed so `any` resolves once rather than matching both this and
|
|
21
|
+
* {@link RelationKey}: an unbracketed `any extends X` satisfies either branch.
|
|
19
22
|
*/
|
|
20
23
|
export type FieldKey<E> = {
|
|
21
|
-
readonly [K in keyof E]-?: NonNullable<E[K]> extends Scalar | Scalar[] | Json ? K : never;
|
|
24
|
+
readonly [K in keyof E]-?: [NonNullable<E[K]>] extends [Scalar | Scalar[] | Json] ? K : never;
|
|
22
25
|
}[Key<E>];
|
|
23
26
|
/**
|
|
24
|
-
* Infers the relation names of an entity
|
|
27
|
+
* Infers the relation names of an entity: whatever is left once its fields and its methods are
|
|
28
|
+
* taken out. Stated as the complement rather than as {@link FieldKey}'s test negated, so the two
|
|
29
|
+
* cannot drift; methods are subtracted because one is not a `Scalar` and would otherwise read as a
|
|
30
|
+
* relation.
|
|
25
31
|
*/
|
|
26
|
-
export type RelationKey<E> =
|
|
27
|
-
readonly [K in keyof E]-?: NonNullable<E[K]> extends Scalar | Scalar[] | Json ? never : K;
|
|
28
|
-
}[Key<E>];
|
|
32
|
+
export type RelationKey<E> = Exclude<Key<E>, FieldKey<E> | MethodKey<E>>;
|
|
29
33
|
/**
|
|
30
34
|
* Whether `T` carries the `Json` brand. Checks for the `__json` marker key explicitly:
|
|
31
35
|
* a bare `extends Json<infer T>` is not discriminating in check position (primitives match it,
|
|
@@ -117,14 +121,29 @@ export type JsonUpdateOp<T = unknown> = {
|
|
|
117
121
|
*/
|
|
118
122
|
type JsonUpdateOpFor<V, T = UnwrapJson<NonNullable<V>>> = [T] extends [never] ? never : T extends readonly unknown[] ? never : JsonUpdateOp<T>;
|
|
119
123
|
/**
|
|
120
|
-
* Accepted value for a single field in an update payload: the value itself, `
|
|
121
|
-
* expression (e.g. `raw('NOW()')`), and - for JSON object
|
|
124
|
+
* Accepted value for a single field in an update payload: the value itself, `null` where the column
|
|
125
|
+
* is nullable, `QueryRaw` for a raw SQL expression (e.g. `raw('NOW()')`), and - for JSON object
|
|
126
|
+
* fields - the JSON operators.
|
|
127
|
+
*
|
|
128
|
+
* An optional property is a nullable column, and clearing one is what an update is for, so `null`
|
|
129
|
+
* belongs in the declared type rather than behind a cast.
|
|
122
130
|
*/
|
|
123
|
-
type UpdateFieldValue<V> = V | QueryRaw | JsonUpdateOpFor<V>;
|
|
131
|
+
type UpdateFieldValue<V> = V | (undefined extends V ? null : never) | QueryRaw | JsonUpdateOpFor<V>;
|
|
124
132
|
/**
|
|
125
|
-
*
|
|
126
|
-
*
|
|
127
|
-
*
|
|
133
|
+
* An entity's fields and relations, each keeping its declared optionality: what the whole-record
|
|
134
|
+
* writes (`insertOne`, `saveOne`, `upsertOne`, and their `*Many`) persist.
|
|
135
|
+
*
|
|
136
|
+
* Not `E`: that *demands* back every method the class declares, so on an entity carrying a
|
|
137
|
+
* lifecycle hook - `@BeforeInsert() generateSlug()` - a plain `{ title: 'Hello' }` was rejected as
|
|
138
|
+
* "missing the following properties". Method-free entities were unaffected, which is why the other
|
|
139
|
+
* examples worked. No runtime filter can help; the call never gets that far. `Pick` because it
|
|
140
|
+
* stays indexable by `IdKey<E>`, which the write path needs.
|
|
141
|
+
*/
|
|
142
|
+
export type EntityData<E> = Pick<E, FieldKey<E> | RelationKey<E>>;
|
|
143
|
+
/**
|
|
144
|
+
* Payload type for update operations: {@link EntityData} made partial, and widened per field to
|
|
145
|
+
* accept `QueryRaw` or `JsonUpdateOp` (for JSON fields), which gives IDE autocomplete for
|
|
146
|
+
* `$set`/`$push`/`$pull` keys via `Json<infer T>`.
|
|
128
147
|
*/
|
|
129
148
|
export type UpdatePayload<E> = {
|
|
130
149
|
[K in FieldKey<E>]?: UpdateFieldValue<E[K]>;
|
|
@@ -149,6 +168,10 @@ export type IdKey<E> = E extends {
|
|
|
149
168
|
} ? 'uuid' & FieldKey<E> : FieldKey<E>;
|
|
150
169
|
/**
|
|
151
170
|
* Infers the value of the key identifier on an entity.
|
|
171
|
+
*
|
|
172
|
+
* Nullable, because an entity declares its id optional - nothing has assigned one before the
|
|
173
|
+
* insert. That puts `undefined` inside every by-id method's parameter, where it would mean "no
|
|
174
|
+
* filter"; `assertIdValue` is what rejects it.
|
|
152
175
|
*/
|
|
153
176
|
export type IdValue<E> = E[IdKey<E>];
|
|
154
177
|
/**
|
package/dist/type/querier.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ import type { SqlDialectName } from './dialect.js';
|
|
|
4
4
|
import type { HookEvent } from './entity.js';
|
|
5
5
|
import type { LoggingOptions } from './logger.js';
|
|
6
6
|
import type { NamingStrategy } from './namingStrategy.js';
|
|
7
|
-
import type { Query, QueryOne, QueryOptions, QuerySearch, QueryUpdateResult } from './query.js';
|
|
7
|
+
import type { Query, QueryFilter, QueryOne, QueryOptions, QuerySearch, QueryUpdateResult } from './query.js';
|
|
8
8
|
import type { UniversalQuerier } from './universalQuerier.js';
|
|
9
9
|
import type { Type } from './utility.js';
|
|
10
10
|
/**
|
|
@@ -15,54 +15,67 @@ export type IsolationLevel = 'read uncommitted' | 'read committed' | 'repeatable
|
|
|
15
15
|
* Options for starting a transaction.
|
|
16
16
|
*/
|
|
17
17
|
export type TransactionOptions = {
|
|
18
|
+
/**
|
|
19
|
+
* Applies to this transaction only.
|
|
20
|
+
*
|
|
21
|
+
* @remarks MySQL and MariaDB set it as a statement of its own ahead of `START TRANSACTION`, so a
|
|
22
|
+
* `START TRANSACTION` that then fails leaves the level applied to whatever the pooled connection
|
|
23
|
+
* runs next. Set it per transaction that needs it rather than relying on what a connection carries.
|
|
24
|
+
*/
|
|
18
25
|
readonly isolationLevel?: IsolationLevel;
|
|
19
26
|
};
|
|
20
27
|
export type DialectName = SqlDialectName | 'mongodb';
|
|
28
|
+
/**
|
|
29
|
+
* The read and delete methods below take the entity as an argument or as the query's `$entity` key.
|
|
30
|
+
* In each pair the `$entity` overload comes **first** on purpose: when no overload matches,
|
|
31
|
+
* TypeScript reports the error from the *last* one, so keeping the entity-argument form last is
|
|
32
|
+
* what makes a typo'd query key report as itself rather than as a missing `$entity`.
|
|
33
|
+
*/
|
|
21
34
|
export interface Querier extends UniversalQuerier {
|
|
22
35
|
/**
|
|
23
36
|
* Find one record. Supports both entity-as-argument and entity-as-field patterns.
|
|
24
37
|
*/
|
|
25
|
-
findOne<E extends object>(entity: Type<E>, q: QueryOne<E>, opts?: QueryOptions): Promise<E | undefined>;
|
|
26
38
|
findOne<E extends object>(q: QueryOne<E> & {
|
|
27
39
|
$entity: Type<E>;
|
|
28
40
|
}, opts?: QueryOptions): Promise<E | undefined>;
|
|
41
|
+
findOne<E extends object>(entity: Type<E>, q: QueryOne<E>, opts?: QueryOptions): Promise<E | undefined>;
|
|
29
42
|
/**
|
|
30
43
|
* Find many records. Supports both entity-as-argument and entity-as-field patterns.
|
|
31
44
|
*/
|
|
32
|
-
findMany<E extends object>(entity: Type<E>, q: Query<E>, opts?: QueryOptions): Promise<E[]>;
|
|
33
45
|
findMany<E extends object>(q: Query<E> & {
|
|
34
46
|
$entity: Type<E>;
|
|
35
47
|
}, opts?: QueryOptions): Promise<E[]>;
|
|
48
|
+
findMany<E extends object>(entity: Type<E>, q: Query<E>, opts?: QueryOptions): Promise<E[]>;
|
|
36
49
|
/**
|
|
37
50
|
* Stream records as an async iterable. Supports both patterns.
|
|
38
51
|
* Does not fill relations or fire lifecycle hooks.
|
|
39
52
|
*/
|
|
40
|
-
findManyStream<E extends object>(entity: Type<E>, q: Query<E>, opts?: QueryOptions): AsyncIterable<E>;
|
|
41
53
|
findManyStream<E extends object>(q: Query<E> & {
|
|
42
54
|
$entity: Type<E>;
|
|
43
55
|
}, opts?: QueryOptions): AsyncIterable<E>;
|
|
56
|
+
findManyStream<E extends object>(entity: Type<E>, q: Query<E>, opts?: QueryOptions): AsyncIterable<E>;
|
|
44
57
|
/**
|
|
45
58
|
* Find many records and count. Supports both patterns.
|
|
46
59
|
*/
|
|
47
|
-
findManyAndCount<E extends object>(entity: Type<E>, q: Query<E>, opts?: QueryOptions): Promise<[E[], number]>;
|
|
48
60
|
findManyAndCount<E extends object>(q: Query<E> & {
|
|
49
61
|
$entity: Type<E>;
|
|
50
62
|
}, opts?: QueryOptions): Promise<[E[], number]>;
|
|
63
|
+
findManyAndCount<E extends object>(entity: Type<E>, q: Query<E>, opts?: QueryOptions): Promise<[E[], number]>;
|
|
51
64
|
/**
|
|
52
65
|
* Count records. Supports both patterns.
|
|
53
66
|
*/
|
|
54
|
-
count<E extends object>(
|
|
55
|
-
count<E extends object>(q: QuerySearch<E> & {
|
|
67
|
+
count<E extends object>(q: QueryFilter<E> & {
|
|
56
68
|
$entity: Type<E>;
|
|
57
69
|
}, opts?: QueryOptions): Promise<number>;
|
|
70
|
+
count<E extends object>(entity: Type<E>, q?: QueryFilter<E>, opts?: QueryOptions): Promise<number>;
|
|
58
71
|
/**
|
|
59
72
|
* Delete many records (soft-deletes when the entity has a soft-delete field, else removes them).
|
|
60
73
|
* Supports both entity-as-argument and entity-as-field patterns.
|
|
61
74
|
*/
|
|
62
|
-
deleteMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, opts?: QueryOptions): Promise<number>;
|
|
63
75
|
deleteMany<E extends object>(q: QuerySearch<E> & {
|
|
64
76
|
$entity: Type<E>;
|
|
65
77
|
}, opts?: QueryOptions): Promise<number>;
|
|
78
|
+
deleteMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, opts?: QueryOptions): Promise<number>;
|
|
66
79
|
/**
|
|
67
80
|
* whether this querier is in a transaction or not.
|
|
68
81
|
*/
|
|
@@ -80,11 +93,14 @@ export interface Querier extends UniversalQuerier {
|
|
|
80
93
|
*/
|
|
81
94
|
commitTransaction(): Promise<void>;
|
|
82
95
|
/**
|
|
83
|
-
* aborts the currently active transaction
|
|
96
|
+
* aborts the currently active transaction, or does nothing when there is none, so it is safe from a
|
|
97
|
+
* `catch` / `finally` without checking {@link hasOpenTransaction} first. `commitTransaction` is strict
|
|
98
|
+
* instead: a caller who believes their work was committed has to hear that it was not.
|
|
84
99
|
*/
|
|
85
100
|
rollbackTransaction(): Promise<void>;
|
|
86
101
|
/**
|
|
87
|
-
*
|
|
102
|
+
* rolls back any unfinished transaction and releases the querier to the pool. A pooled querier is
|
|
103
|
+
* finished afterwards: using it again throws rather than taking a second connection nothing owns.
|
|
88
104
|
*/
|
|
89
105
|
release(): Promise<void>;
|
|
90
106
|
/**
|
package/dist/type/query.d.ts
CHANGED
|
@@ -142,21 +142,29 @@ export type QueryPager = {
|
|
|
142
142
|
$limit?: number;
|
|
143
143
|
};
|
|
144
144
|
/**
|
|
145
|
-
*
|
|
145
|
+
* Which rows a statement addresses. `count` takes exactly this: how many rows match is all a count
|
|
146
|
+
* can answer, so an ordering or a page on it is a clause it could only drop or choke on.
|
|
146
147
|
*/
|
|
147
|
-
export type
|
|
148
|
+
export type QueryFilter<E> = {
|
|
148
149
|
/**
|
|
149
150
|
* filtering options.
|
|
150
151
|
*/
|
|
151
152
|
$where?: QueryWhere<E>;
|
|
153
|
+
};
|
|
154
|
+
/**
|
|
155
|
+
* A filter plus the ordering and page `updateMany`/`deleteMany` take. Both settle the rows they
|
|
156
|
+
* picked before writing, so the page is portable rather than MySQL-only.
|
|
157
|
+
*
|
|
158
|
+
* `$sort` excludes vector search here for the reason `$lock` is declared on {@link Query} instead:
|
|
159
|
+
* a vector search ranks rows into a projected distance column, and only a SELECT has a projection
|
|
160
|
+
* list to hold one. Passing `QuerySortMap` its `Vector = false` is what keeps it off these.
|
|
161
|
+
*/
|
|
162
|
+
export type QuerySearch<E> = QueryFilter<E> & {
|
|
152
163
|
/**
|
|
153
164
|
* sorting options.
|
|
154
165
|
*/
|
|
155
|
-
$sort?: QuerySortMap<E>;
|
|
166
|
+
$sort?: QuerySortMap<E, false>;
|
|
156
167
|
} & QueryPager;
|
|
157
|
-
/**
|
|
158
|
-
* criteria one options.
|
|
159
|
-
*/
|
|
160
168
|
/**
|
|
161
169
|
* query options.
|
|
162
170
|
*/
|
|
@@ -177,6 +185,11 @@ export type Query<E> = {
|
|
|
177
185
|
* regardless, since subtracting them would leave the relation unfilled.
|
|
178
186
|
*/
|
|
179
187
|
$exclude?: QueryExclude<E>;
|
|
188
|
+
/**
|
|
189
|
+
* sorting options, vector similarity search included: a SELECT is the one statement with a
|
|
190
|
+
* projection list to hold the distance such a search computes.
|
|
191
|
+
*/
|
|
192
|
+
$sort?: QuerySortMap<E>;
|
|
180
193
|
/**
|
|
181
194
|
* whether to return only distinct rows.
|
|
182
195
|
*/
|
|
@@ -187,11 +200,11 @@ export type Query<E> = {
|
|
|
187
200
|
* the rows, so it is rejected rather than emitted. Locks only the queried entity, never anything
|
|
188
201
|
* reached through `$populate`. SQL only; MongoDB and the SQLite family reject it.
|
|
189
202
|
*
|
|
190
|
-
*
|
|
191
|
-
*
|
|
203
|
+
* Declared here rather than on {@link QuerySearch}, which `update`/`delete` take: that placement
|
|
204
|
+
* is what keeps the clause off those statements at the type level.
|
|
192
205
|
*/
|
|
193
206
|
$lock?: QueryLock;
|
|
194
|
-
} &
|
|
207
|
+
} & QueryFilter<E> & QueryPager;
|
|
195
208
|
/**
|
|
196
209
|
* options to get a single record.
|
|
197
210
|
*/
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { FieldKey } from './entity.js';
|
|
2
|
-
import type { QueryPager, QuerySortDirection
|
|
2
|
+
import type { QueryPager, QuerySortDirection } from './query.js';
|
|
3
3
|
import type { QueryWhere, QueryWhereFieldValue } from './queryWhere.js';
|
|
4
4
|
/**
|
|
5
5
|
* Maps the offending keys to `never`, turning an excess key into a compile error; resolves to
|
|
@@ -10,6 +10,22 @@ import type { QueryWhere, QueryWhereFieldValue } from './queryWhere.js';
|
|
|
10
10
|
* @internal
|
|
11
11
|
*/
|
|
12
12
|
type Reject<K> = [K] extends [never] ? unknown : Record<K & string, never>;
|
|
13
|
+
/**
|
|
14
|
+
* The columns `$group` actually names: keys whose value is literally `true`, not `keyof G`.
|
|
15
|
+
* Wherever `G` cannot be inferred - `$group` omitted, hoisted, or annotated - it *is* its own
|
|
16
|
+
* constraint, whose every value is `true | undefined`, and keying off values yields `never` there
|
|
17
|
+
* rather than every field of the entity.
|
|
18
|
+
* @internal
|
|
19
|
+
*/
|
|
20
|
+
type GroupedKeys<G> = {
|
|
21
|
+
[K in keyof G]: G[K] extends true ? K : never;
|
|
22
|
+
}[keyof G];
|
|
23
|
+
/**
|
|
24
|
+
* The keys `T` declares by name, or `never` when `T` is only an index signature - which is what an
|
|
25
|
+
* uninferred `$agg` is, and what would otherwise make every key look like a declared alias.
|
|
26
|
+
* @internal
|
|
27
|
+
*/
|
|
28
|
+
type NamedKeys<T> = string extends keyof T ? never : keyof T;
|
|
13
29
|
declare const QUERY_AGGREGATE_OPS: readonly ['$count', '$sum', '$avg', '$min', '$max'];
|
|
14
30
|
/**
|
|
15
31
|
* Supported aggregate operations.
|
|
@@ -44,10 +60,29 @@ export declare function resolveAggregateOp(key: string): {
|
|
|
44
60
|
};
|
|
45
61
|
/** The argument of an aggregate function: a field, or `'*'` (only meaningful for `COUNT(*)`). */
|
|
46
62
|
export type QueryAggregateArg<E> = FieldKey<E> | '*';
|
|
47
|
-
/**
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
63
|
+
/**
|
|
64
|
+
* Fields `SUM`/`AVG` can total. Restricted to numeric columns because the result is declared
|
|
65
|
+
* `number`: totalling a text or date column is either an engine error or a coercion, and neither
|
|
66
|
+
* produces the value the signature promises.
|
|
67
|
+
*/
|
|
68
|
+
type NumericFieldKey<E> = {
|
|
69
|
+
readonly [K in FieldKey<E>]: [NonNullable<E[K]>] extends [number | bigint] ? K : never;
|
|
70
|
+
}[FieldKey<E>];
|
|
71
|
+
/** Every aggregate op, plain and DISTINCT-qualified. */
|
|
72
|
+
type AggregateOp = QueryAggregateOp | QueryAggregateDistinctOp;
|
|
73
|
+
/**
|
|
74
|
+
* Names a subset of {@link AggregateOp}. The constraint is the point, and why this is not `Extract`:
|
|
75
|
+
* renaming an op stops these literals satisfying it and breaks the subsets below at compile time,
|
|
76
|
+
* where `Extract` would quietly drop the renamed member and leave the subset wrong but valid.
|
|
77
|
+
*/
|
|
78
|
+
type OpsOf<K extends AggregateOp> = K;
|
|
79
|
+
/** Ops that total a column, so their argument has to be numeric. */
|
|
80
|
+
type TotallingOp = OpsOf<'$sum' | '$avg' | '$sumDistinct' | '$avgDistinct'>;
|
|
81
|
+
/**
|
|
82
|
+
* Every aggregate op mapped to the argument it accepts: `$count` a field or `'*'` (`COUNT(*)`),
|
|
83
|
+
* the totalling ops a numeric field, `$min`/`$max`/`$countDistinct` any field.
|
|
84
|
+
*/
|
|
85
|
+
type QueryAggregateArgMap<E> = Record<'$count', QueryAggregateArg<E>> & Record<TotallingOp, NumericFieldKey<E>> & Record<Exclude<AggregateOp, '$count' | TotallingOp>, FieldKey<E>>;
|
|
51
86
|
/** Exactly one key of `T`: the chosen op with its value; every other op key is forbidden (`never`). */
|
|
52
87
|
type ExactlyOne<T> = {
|
|
53
88
|
[K in keyof T]: Readonly<Record<K, T[K]>> & Partial<Readonly<Record<Exclude<keyof T, K>, never>>>;
|
|
@@ -64,17 +99,14 @@ type ExactlyOne<T> = {
|
|
|
64
99
|
* @example { $avg: 'age' } → AVG("age")
|
|
65
100
|
*/
|
|
66
101
|
export type QueryAggregateFn<E> = ExactlyOne<QueryAggregateArgMap<E>>;
|
|
67
|
-
/**
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
*/
|
|
71
|
-
type QueryAggregateNumericOp = QueryAggregateDistinctOp | (typeof QUERY_AGGREGATE_DISTINCT_OP_BASE)[QueryAggregateDistinctOp];
|
|
72
|
-
/** A single-key `{ [op]: unknown }` shape for each {@link QueryAggregateNumericOp}, matched to infer a `number` result. */
|
|
73
|
-
type QueryAggregateNumericFn = {
|
|
74
|
-
[K in QueryAggregateNumericOp]: {
|
|
102
|
+
/** A single-key `{ [op]: unknown }` shape for each op in `Ops`, matched to infer that op's result. */
|
|
103
|
+
type FnWithOp<Ops extends string> = {
|
|
104
|
+
[K in Ops]: {
|
|
75
105
|
readonly [P in K]: unknown;
|
|
76
106
|
};
|
|
77
|
-
}[
|
|
107
|
+
}[Ops];
|
|
108
|
+
/** Ops that count rows. Alone among the ops they answer `0`, never NULL, over an empty group. */
|
|
109
|
+
type CountingOp = OpsOf<'$count' | '$countDistinct'>;
|
|
78
110
|
/**
|
|
79
111
|
* Group-by columns: an object mapping entity field keys to `true`, exactly like {@link QuerySelect}.
|
|
80
112
|
* Typed against the entity, so a typo'd column is a compile error. Compute aggregate columns with
|
|
@@ -105,18 +137,22 @@ export type QueryAggMap<E> = {
|
|
|
105
137
|
/** The entity type of an aggregated field reference `F`, or `unknown` if it is not a known field. */
|
|
106
138
|
type FieldValueType<E, F> = F extends keyof E ? E[F] : unknown;
|
|
107
139
|
/**
|
|
108
|
-
* Resolves a single computed column's type from its aggregate function: `$count
|
|
109
|
-
*
|
|
140
|
+
* Resolves a single computed column's type from its aggregate function: `$count` is always
|
|
141
|
+
* `number`; `$sum`/`$avg` total to a `number` or to `null`; `$min`/`$max` keep the aggregated
|
|
142
|
+
* field's own type, likewise or `null`.
|
|
143
|
+
*
|
|
144
|
+
* Everything but `$count` is nullable: an aggregate over zero rows is NULL, and an ungrouped one
|
|
145
|
+
* still returns a row, so a `$where` matching nothing hands back a row of NULLs.
|
|
110
146
|
*
|
|
111
147
|
* `$sum`/`$avg` are exact to 2^53: Postgres widens a sum over BIGINT to NUMERIC, and decoding that
|
|
112
148
|
* text to satisfy this `number` drops the digits past that bound. Use `raw()` for a wider total.
|
|
113
149
|
* @internal
|
|
114
150
|
*/
|
|
115
|
-
type QueryAggregateFnResult<E, Fn> = Fn extends
|
|
151
|
+
type QueryAggregateFnResult<E, Fn> = Fn extends FnWithOp<CountingOp> ? number : Fn extends FnWithOp<TotallingOp> ? number | null : Fn extends {
|
|
116
152
|
readonly $min: infer F;
|
|
117
|
-
}
|
|
153
|
+
} | {
|
|
118
154
|
readonly $max: infer F;
|
|
119
|
-
} ? FieldValueType<E, F> : unknown;
|
|
155
|
+
} ? FieldValueType<E, F> | null : unknown;
|
|
120
156
|
/**
|
|
121
157
|
* Flattens an intersection into a single object literal for readable editor hovers.
|
|
122
158
|
* @internal
|
|
@@ -127,9 +163,12 @@ type Simplify<T> = {
|
|
|
127
163
|
/**
|
|
128
164
|
* Infers the aggregated result row: grouped columns (`G`) keep their entity type; computed columns
|
|
129
165
|
* (`A`) resolve from their aggregate function via {@link QueryAggregateFnResult}.
|
|
166
|
+
*
|
|
167
|
+
* Grouped columns come from {@link GroupedKeys}, not `keyof G`, so a `$group` the compiler could
|
|
168
|
+
* not read contributes none rather than all of them.
|
|
130
169
|
*/
|
|
131
170
|
export type QueryAggregateResult<E, G, A> = Simplify<{
|
|
132
|
-
-readonly [K in
|
|
171
|
+
-readonly [K in GroupedKeys<G> & FieldKey<E>]: E[K];
|
|
133
172
|
} & {
|
|
134
173
|
-readonly [K in keyof A]: QueryAggregateFnResult<E, A[K]>;
|
|
135
174
|
}>;
|
|
@@ -171,8 +210,11 @@ export type QueryAggregate<E, G extends QueryGroupMap<E> = QueryGroupMap<E>, A e
|
|
|
171
210
|
readonly $group?: G & Reject<Exclude<keyof G, FieldKey<E>>>;
|
|
172
211
|
/**
|
|
173
212
|
* Computed aggregate columns - `{ count: { $count: '*' }, avgAge: { $avg: 'age' } }`.
|
|
213
|
+
*
|
|
214
|
+
* An alias repeating a `$group` column is rejected: both would be emitted under that one name,
|
|
215
|
+
* leaving the driver to keep whichever it read last.
|
|
174
216
|
*/
|
|
175
|
-
readonly $agg?: A
|
|
217
|
+
readonly $agg?: A & Reject<NamedKeys<A> & GroupedKeys<G>>;
|
|
176
218
|
/**
|
|
177
219
|
* Post-aggregation filtering, applied after grouping (SQL `HAVING`, MongoDB post-group `$match`).
|
|
178
220
|
* Keyed by the result columns (grouped columns + computed aliases), and each value is typed to that
|
|
@@ -184,10 +226,11 @@ export type QueryAggregate<E, G extends QueryGroupMap<E> = QueryGroupMap<E>, A e
|
|
|
184
226
|
readonly [K in keyof QueryAggregateResult<E, G, A>]?: QueryWhereFieldValue<QueryAggregateResult<E, G, A>[K]>;
|
|
185
227
|
};
|
|
186
228
|
/**
|
|
187
|
-
* Sort the aggregated results by a grouped column
|
|
229
|
+
* Sort the aggregated results by a grouped column or a computed alias - an aggregate's rows are
|
|
230
|
+
* its groups, so any other entity field names a value the statement never produced.
|
|
188
231
|
*/
|
|
189
|
-
readonly $sort?:
|
|
190
|
-
readonly [K in
|
|
232
|
+
readonly $sort?: {
|
|
233
|
+
readonly [K in keyof QueryAggregateResult<E, G, A>]?: QuerySortDirection;
|
|
191
234
|
};
|
|
192
235
|
} & QueryPager;
|
|
193
236
|
export {};
|