@guren/orm 2.6.3 → 2.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +52 -5
- package/dist/index.js +228 -59
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -24,6 +24,11 @@ type FieldKey<TRecord extends PlainObject> = keyof TRecord & string;
|
|
|
24
24
|
* the module boundary, but kept out of the package entry point.
|
|
25
25
|
*/
|
|
26
26
|
declare const PREPARED_UPDATE: unique symbol;
|
|
27
|
+
/**
|
|
28
|
+
* Key for the global-scope seal. Exported for `Model` across the module
|
|
29
|
+
* boundary, but kept out of the package entry point.
|
|
30
|
+
*/
|
|
31
|
+
declare const SEAL_SCOPES: unique symbol;
|
|
27
32
|
type WhereOperator = '=' | '!=' | '>' | '<' | '>=' | '<=' | 'like' | 'in' | 'not in' | 'is null' | 'is not null';
|
|
28
33
|
interface SimpleCondition {
|
|
29
34
|
type: 'simple';
|
|
@@ -72,6 +77,9 @@ type EagerLoadConstraints = ReadonlyMap<string, EagerLoadConstraint>;
|
|
|
72
77
|
*/
|
|
73
78
|
declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult extends PlainObject = TRecord> {
|
|
74
79
|
private conditions;
|
|
80
|
+
private scopeConditions;
|
|
81
|
+
/** Fold this up wherever a nested builder's conditions are (pushCallbackGroup). */
|
|
82
|
+
private droppedUndefinedFilters;
|
|
75
83
|
private options;
|
|
76
84
|
private modelClass;
|
|
77
85
|
private table;
|
|
@@ -156,6 +164,14 @@ declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult ex
|
|
|
156
164
|
then<TResult1 = TResult[], TResult2 = never>(onfulfilled?: ((value: TResult[]) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult1 | TResult2>;
|
|
157
165
|
catch<TCatch = never>(onrejected?: ((reason: unknown) => TCatch | PromiseLike<TCatch>) | null): Promise<TResult[] | TCatch>;
|
|
158
166
|
getConditions(): WhereCondition[];
|
|
167
|
+
/**
|
|
168
|
+
* Freezes the conditions applied so far as this model's global scopes, to be
|
|
169
|
+
* AND-ed around the caller's expression from here on. Left in the same list,
|
|
170
|
+
* a top-level `orWhere()` folds them into its left arm (see
|
|
171
|
+
* `normalizeConditionSequence`) and the query loses tenant isolation and
|
|
172
|
+
* soft-delete filtering.
|
|
173
|
+
*/
|
|
174
|
+
[SEAL_SCOPES](): this;
|
|
159
175
|
getOptions(): QueryBuilderOptions;
|
|
160
176
|
/**
|
|
161
177
|
* The nested builder skips global scopes on purpose: the outer builder
|
|
@@ -163,6 +179,18 @@ declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult ex
|
|
|
163
179
|
* duplicate — or, inside an OR group, weaken — their filters.
|
|
164
180
|
*/
|
|
165
181
|
private pushCallbackGroup;
|
|
182
|
+
private simpleConditionsFrom;
|
|
183
|
+
private hasConditions;
|
|
184
|
+
/** Flat list, for the basic-adapter conversion that cannot read group nodes. */
|
|
185
|
+
private allConditions;
|
|
186
|
+
/** Global scopes AND the caller's expression, never folded into it. */
|
|
187
|
+
private effectiveConditions;
|
|
188
|
+
/**
|
|
189
|
+
* `where({})` and a deliberately unfiltered builder are untouched: only a
|
|
190
|
+
* filter the caller wrote and then lost counts.
|
|
191
|
+
*/
|
|
192
|
+
private filtersEvaporated;
|
|
193
|
+
private assertFiltersSurvived;
|
|
166
194
|
private addSimpleCondition;
|
|
167
195
|
private executeQuery;
|
|
168
196
|
/** Null when the conditions are too complex for a basic adapter's WhereClause. */
|
|
@@ -296,6 +324,7 @@ interface PaginatedResult<TRecord extends PlainObject = PlainObject> {
|
|
|
296
324
|
}
|
|
297
325
|
/** Interface for ORM adapters that power the Model class; DrizzleAdapter by default. */
|
|
298
326
|
interface ORMAdapter {
|
|
327
|
+
/** Must not commit before the callback's promise settles: drizzle's bun-sqlite does. */
|
|
299
328
|
transaction?<TResult>(callback: (trx: unknown) => Promise<TResult>): Promise<TResult>;
|
|
300
329
|
findMany<TRecord extends PlainObject = PlainObject>(table: unknown, options?: FindManyOptions<TRecord>, queryOptions?: AdapterQueryOptions): Promise<TRecord[]>;
|
|
301
330
|
findUnique<TRecord extends PlainObject = PlainObject>(table: unknown, where: WhereClause<TRecord>, queryOptions?: AdapterQueryOptions): Promise<TRecord | null>;
|
|
@@ -396,8 +425,19 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
|
|
|
396
425
|
* register a named scope and nothing else.
|
|
397
426
|
*/
|
|
398
427
|
static withoutGlobalScope<T extends typeof Model>(this: T, ...names: string[]): QueryBuilder<TRecordFor<T>>;
|
|
428
|
+
/**
|
|
429
|
+
* Query options lead here because `names` is a rest parameter and cannot be
|
|
430
|
+
* followed by an optional one; every other entry point takes them trailing.
|
|
431
|
+
*/
|
|
432
|
+
static withoutGlobalScope<T extends typeof Model>(this: T, queryOptions: ModelQueryOptions, ...names: string[]): QueryBuilder<TRecordFor<T>>;
|
|
399
433
|
/** A query with no global scopes applied, `defaultScope` included. */
|
|
400
|
-
static withoutGlobalScopes<T extends typeof Model>(this: T): QueryBuilder<TRecordFor<T>>;
|
|
434
|
+
static withoutGlobalScopes<T extends typeof Model>(this: T, queryOptions?: ModelQueryOptions): QueryBuilder<TRecordFor<T>>;
|
|
435
|
+
/**
|
|
436
|
+
* Both write entry points fork on `hasScopes()`, and only one arm reaches a
|
|
437
|
+
* builder — so the refusal belongs above the fork, where every adapter is
|
|
438
|
+
* still in scope.
|
|
439
|
+
*/
|
|
440
|
+
private static assertFiltersSurvived;
|
|
401
441
|
/** Applies hidden/visible filtering, accessors and appends. */
|
|
402
442
|
static serialize<T extends typeof Model>(this: T, record: TRecordFor<T>): PlainObject;
|
|
403
443
|
static serializeMany<T extends typeof Model>(this: T, records: TRecordFor<T>[]): PlainObject[];
|
|
@@ -445,6 +485,12 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
|
|
|
445
485
|
static whereNotIn<T extends typeof Model>(this: T, field: keyof TRecordFor<T> & string, values: readonly TRecordFor<T>[keyof TRecordFor<T> & string][]): QueryBuilder<TRecordFor<T>>;
|
|
446
486
|
static select<T extends typeof Model, Keys extends keyof TRecordFor<T> & string>(this: T, ...fields: readonly Keys[]): QueryBuilder<TRecordFor<T>, Pick<TRecordFor<T>, Keys>>;
|
|
447
487
|
static newQuery<T extends typeof Model>(this: T, queryOptions?: ModelQueryOptions): QueryBuilder<TRecordFor<T>>;
|
|
488
|
+
/**
|
|
489
|
+
* The one place a scoped builder is born: applying scopes without sealing
|
|
490
|
+
* them leaves them foldable by a later `orWhere()`, and nothing else would
|
|
491
|
+
* report it. `except` names the global scopes to leave off.
|
|
492
|
+
*/
|
|
493
|
+
private static buildScopedQuery;
|
|
448
494
|
/** No scopes applied — for soft-deleted records or bypassing global filters. */
|
|
449
495
|
static newQueryWithoutScopes<T extends typeof Model>(this: T, queryOptions?: ModelQueryOptions): QueryBuilder<TRecordFor<T>>;
|
|
450
496
|
/**
|
|
@@ -764,13 +810,13 @@ declare class MassAssignmentException extends Error {
|
|
|
764
810
|
interface SoftDeletesStatic {
|
|
765
811
|
deletedAtColumn: string;
|
|
766
812
|
/** Start a query that includes soft-deleted records. */
|
|
767
|
-
withTrashed(): QueryBuilder<PlainObject>;
|
|
813
|
+
withTrashed(queryOptions?: ModelQueryOptions): QueryBuilder<PlainObject>;
|
|
768
814
|
/** Start a query that returns only soft-deleted records. */
|
|
769
|
-
onlyTrashed(): QueryBuilder<PlainObject>;
|
|
815
|
+
onlyTrashed(queryOptions?: ModelQueryOptions): QueryBuilder<PlainObject>;
|
|
770
816
|
/** Restore soft-deleted records by setting deletedAt back to null. */
|
|
771
|
-
restore(where: Partial<Record<string, unknown
|
|
817
|
+
restore(where: Partial<Record<string, unknown>>, writeOptions?: ModelWriteOptions): Promise<PlainObject>;
|
|
772
818
|
/** Permanently delete records from the database, bypassing soft delete. */
|
|
773
|
-
forceDelete(where: Partial<Record<string, unknown
|
|
819
|
+
forceDelete(where: Partial<Record<string, unknown>>, writeOptions?: ModelWriteOptions): Promise<number | PlainObject | void>;
|
|
774
820
|
}
|
|
775
821
|
/**
|
|
776
822
|
* Mixin where `delete()` sets `deletedAt` instead of removing the row, and a
|
|
@@ -815,6 +861,7 @@ type DrizzleDatabase = {
|
|
|
815
861
|
insert(table: unknown): DrizzleLikeInsert;
|
|
816
862
|
update?(table: unknown): DrizzleLikeUpdate;
|
|
817
863
|
delete?(table: unknown): DrizzleLikeDelete;
|
|
864
|
+
run?(query: unknown): Promise<unknown>;
|
|
818
865
|
transaction?<TResult>(callback: (trx: unknown) => Promise<TResult>): Promise<TResult>;
|
|
819
866
|
};
|
|
820
867
|
declare const DrizzleAdapter: ORMAdapterAdvanced & {
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { and, asc, count, desc, eq, gt, gte, inArray, isNotNull, isNull, like, lt, lte, ne, notInArray, or } from "drizzle-orm";
|
|
1
|
+
import { and, asc, count, desc, eq, gt, gte, inArray, isNotNull, isNull, like, lt, lte, ne, notInArray, or, sql } from "drizzle-orm";
|
|
2
2
|
import { extname, relative, resolve } from "node:path";
|
|
3
3
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
4
4
|
import { existsSync, readdirSync } from "node:fs";
|
|
@@ -29,6 +29,16 @@ else {
|
|
|
29
29
|
//#endregion
|
|
30
30
|
//#region src/where-conditions.ts
|
|
31
31
|
/**
|
|
32
|
+
* True when the caller wrote filters and every one of them was `undefined`.
|
|
33
|
+
* Such a criteria object renders no WHERE clause at all, so the query reaches
|
|
34
|
+
* every row; an explicitly empty `{}` still means "no filter" and is false.
|
|
35
|
+
*/
|
|
36
|
+
function everyFilterDropped(where) {
|
|
37
|
+
if (!where || typeof where !== "object") return false;
|
|
38
|
+
const values = Object.values(where);
|
|
39
|
+
return values.length > 0 && values.every((value) => value === void 0);
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
32
42
|
* Folds a builder's condition list into one node, or null when it holds
|
|
33
43
|
* nothing renderable. An OR group folds everything before it into the OR, so
|
|
34
44
|
* `.where(a).where(b).orWhere(c)` reads `(a AND b) OR c`. The one
|
|
@@ -48,6 +58,20 @@ function normalizeConditionSequence(conditions) {
|
|
|
48
58
|
}
|
|
49
59
|
return combine("and", pending);
|
|
50
60
|
}
|
|
61
|
+
/**
|
|
62
|
+
* Folds a list and makes the result safe to splice into another list. An
|
|
63
|
+
* or-group means two things by position: a parenthesized disjunction in member
|
|
64
|
+
* position, an orWhere continuation at the head. Wrapping selects the first.
|
|
65
|
+
*/
|
|
66
|
+
function groupConditionSequence(conditions, boolean = "and") {
|
|
67
|
+
const folded = normalizeConditionSequence(conditions);
|
|
68
|
+
if (!folded) return null;
|
|
69
|
+
return boolean === "or" || folded.type === "group" && folded.boolean === "or" ? {
|
|
70
|
+
type: "group",
|
|
71
|
+
boolean,
|
|
72
|
+
conditions: [folded]
|
|
73
|
+
} : folded;
|
|
74
|
+
}
|
|
51
75
|
function combine(boolean, parts) {
|
|
52
76
|
if (parts.length === 0) return null;
|
|
53
77
|
if (parts.length === 1) return parts[0];
|
|
@@ -114,6 +138,9 @@ function buildDrizzleConditions(table, conditions) {
|
|
|
114
138
|
//#endregion
|
|
115
139
|
//#region src/adapters/drizzle-adapter.ts
|
|
116
140
|
let database;
|
|
141
|
+
let transactionAwaitsCallback;
|
|
142
|
+
let transactionQueue = Promise.resolve();
|
|
143
|
+
let transactionScope;
|
|
117
144
|
function ensureDatabase() {
|
|
118
145
|
if (!database) throw new Error("DrizzleAdapter: database has not been configured. Call DrizzleAdapter.configure(db).");
|
|
119
146
|
return database;
|
|
@@ -193,9 +220,78 @@ async function resolveWithReturning(query) {
|
|
|
193
220
|
row: void 0
|
|
194
221
|
};
|
|
195
222
|
}
|
|
223
|
+
const NOOP = () => void 0;
|
|
224
|
+
/**
|
|
225
|
+
* Whether `db.transaction()` awaits its callback before committing: drizzle's
|
|
226
|
+
* bun-sqlite COMMITs on whatever the callback returns, d1 and every pg/mysql
|
|
227
|
+
* driver await it. Probed rather than matched against a driver list, because
|
|
228
|
+
* this adapter takes any drizzle-shaped handle and one a list never named gets
|
|
229
|
+
* the wrong path silently. Costs one empty transaction per configured database.
|
|
230
|
+
*/
|
|
231
|
+
async function awaitsItsCallback(db) {
|
|
232
|
+
if (transactionAwaitsCallback === void 0) {
|
|
233
|
+
const probe = db.transaction?.(NOOP);
|
|
234
|
+
transactionAwaitsCallback = isPromiseLike(probe);
|
|
235
|
+
if (isPromiseLike(probe)) await probe.catch(NOOP);
|
|
236
|
+
}
|
|
237
|
+
return transactionAwaitsCallback;
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Imported on demand so `node:async_hooks` stays off the module graph of a
|
|
241
|
+
* Workers or Lambda bundle, whose drivers all await their callback and never
|
|
242
|
+
* reach this branch. The promise is what is memoized, not the storage: two
|
|
243
|
+
* concurrent first callers must not end up asking different instances.
|
|
244
|
+
*/
|
|
245
|
+
function loadTransactionScope() {
|
|
246
|
+
transactionScope ??= import("node:async_hooks").then(({ AsyncLocalStorage }) => {
|
|
247
|
+
const store = new AsyncLocalStorage();
|
|
248
|
+
return {
|
|
249
|
+
run: (fn) => store.run(true, fn),
|
|
250
|
+
isInside: () => store.getStore() === true
|
|
251
|
+
};
|
|
252
|
+
});
|
|
253
|
+
return transactionScope;
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Serializes what `runExclusively` drives, since one connection takes one
|
|
257
|
+
* transaction. Waiting is only safe for a caller that is not already inside one:
|
|
258
|
+
* that caller would be queued behind itself. Async context is what separates the
|
|
259
|
+
* two, and it is the only thing that can — arrival order cannot tell a nested
|
|
260
|
+
* call from an unrelated concurrent one, and refusing both punishes the second.
|
|
261
|
+
*/
|
|
262
|
+
async function runOwnTransaction(db, callback) {
|
|
263
|
+
if (typeof db.run !== "function") throw new Error("DrizzleAdapter: the configured database commits before its transaction callback has awaited anything, and exposes no run() to drive BEGIN/COMMIT with, so transactions on it cannot be made atomic.");
|
|
264
|
+
const scope = await loadTransactionScope();
|
|
265
|
+
if (scope.isInside()) throw new Error("DrizzleAdapter: cannot begin a transaction inside another one. This driver holds a single connection, which takes one transaction at a time, so the inner transaction would wait on the outer one to finish and the outer on the inner.");
|
|
266
|
+
const run = db.run.bind(db);
|
|
267
|
+
const slot = transactionQueue.then(() => runExclusively(db, run, scope, callback));
|
|
268
|
+
transactionQueue = slot.then(NOOP, NOOP);
|
|
269
|
+
return slot;
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* BEGIN/COMMIT/ROLLBACK driven here so an async callback is honoured on a driver
|
|
273
|
+
* that would otherwise commit before awaiting it. The handle itself is the
|
|
274
|
+
* transaction scope: these drivers hold one connection, so every statement
|
|
275
|
+
* between BEGIN and COMMIT is inside it. Callers reach this one at a time.
|
|
276
|
+
*/
|
|
277
|
+
async function runExclusively(db, run, scope, callback) {
|
|
278
|
+
await run(sql.raw("begin"));
|
|
279
|
+
try {
|
|
280
|
+
const result = await scope.run(() => callback(db));
|
|
281
|
+
await run(sql.raw("commit"));
|
|
282
|
+
return result;
|
|
283
|
+
} catch (error) {
|
|
284
|
+
try {
|
|
285
|
+
await run(sql.raw("rollback"));
|
|
286
|
+
} catch {}
|
|
287
|
+
throw error;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
196
290
|
const DrizzleAdapter = {
|
|
197
291
|
configure(db) {
|
|
198
292
|
database = db;
|
|
293
|
+
transactionAwaitsCallback = void 0;
|
|
294
|
+
transactionQueue = Promise.resolve();
|
|
199
295
|
},
|
|
200
296
|
getDatabase() {
|
|
201
297
|
return ensureDatabase();
|
|
@@ -315,7 +411,8 @@ const DrizzleAdapter = {
|
|
|
315
411
|
async transaction(callback) {
|
|
316
412
|
const db = ensureDatabase();
|
|
317
413
|
if (typeof db.transaction !== "function") throw new Error("DrizzleAdapter: configured database does not support transactions.");
|
|
318
|
-
return db.transaction(callback);
|
|
414
|
+
if (await awaitsItsCallback(db)) return db.transaction(callback);
|
|
415
|
+
return runOwnTransaction(db, callback);
|
|
319
416
|
}
|
|
320
417
|
};
|
|
321
418
|
//#endregion
|
|
@@ -425,6 +522,11 @@ var ModelNotFoundException = class extends Error {
|
|
|
425
522
|
*/
|
|
426
523
|
const PREPARED_UPDATE = Symbol("guren.orm.preparedUpdate");
|
|
427
524
|
/**
|
|
525
|
+
* Key for the global-scope seal. Exported for `Model` across the module
|
|
526
|
+
* boundary, but kept out of the package entry point.
|
|
527
|
+
*/
|
|
528
|
+
const SEAL_SCOPES = Symbol("guren.orm.sealScopes");
|
|
529
|
+
/**
|
|
428
530
|
* Fluent query builder for the Guren ORM. Thenable, so awaiting a builder
|
|
429
531
|
* resolves to the result of `get()`.
|
|
430
532
|
*
|
|
@@ -433,6 +535,9 @@ const PREPARED_UPDATE = Symbol("guren.orm.preparedUpdate");
|
|
|
433
535
|
*/
|
|
434
536
|
var QueryBuilder = class QueryBuilder {
|
|
435
537
|
conditions = [];
|
|
538
|
+
scopeConditions = [];
|
|
539
|
+
/** Fold this up wherever a nested builder's conditions are (pushCallbackGroup). */
|
|
540
|
+
droppedUndefinedFilters = false;
|
|
436
541
|
options = { orderBy: [] };
|
|
437
542
|
modelClass;
|
|
438
543
|
table;
|
|
@@ -451,7 +556,7 @@ var QueryBuilder = class QueryBuilder {
|
|
|
451
556
|
return this;
|
|
452
557
|
}
|
|
453
558
|
if (typeof fieldOrConditions === "object" && fieldOrConditions !== null) {
|
|
454
|
-
|
|
559
|
+
this.conditions.push(...this.simpleConditionsFrom(fieldOrConditions));
|
|
455
560
|
return this;
|
|
456
561
|
}
|
|
457
562
|
const field = fieldOrConditions;
|
|
@@ -465,14 +570,8 @@ var QueryBuilder = class QueryBuilder {
|
|
|
465
570
|
return this;
|
|
466
571
|
}
|
|
467
572
|
const orConditions = [];
|
|
468
|
-
if (typeof fieldOrConditions === "object" && fieldOrConditions !== null)
|
|
469
|
-
|
|
470
|
-
type: "simple",
|
|
471
|
-
field: key,
|
|
472
|
-
operator: Array.isArray(val) ? "in" : "=",
|
|
473
|
-
value: val
|
|
474
|
-
});
|
|
475
|
-
} else {
|
|
573
|
+
if (typeof fieldOrConditions === "object" && fieldOrConditions !== null) orConditions.push(...this.simpleConditionsFrom(fieldOrConditions));
|
|
574
|
+
else {
|
|
476
575
|
const field = fieldOrConditions;
|
|
477
576
|
if (arguments.length === 2) orConditions.push({
|
|
478
577
|
type: "simple",
|
|
@@ -558,6 +657,7 @@ var QueryBuilder = class QueryBuilder {
|
|
|
558
657
|
return this.loadEagerRelations(results);
|
|
559
658
|
}
|
|
560
659
|
async first() {
|
|
660
|
+
if (this.filtersEvaporated()) return null;
|
|
561
661
|
const prev = this.options.limitValue;
|
|
562
662
|
this.options.limitValue = 1;
|
|
563
663
|
try {
|
|
@@ -573,9 +673,9 @@ var QueryBuilder = class QueryBuilder {
|
|
|
573
673
|
return record;
|
|
574
674
|
}
|
|
575
675
|
async count() {
|
|
576
|
-
if (typeof this.adapter.count === "function" && this.
|
|
676
|
+
if (typeof this.adapter.count === "function" && !this.hasConditions()) return this.adapter.count(this.table, void 0, { trx: this.options.trx });
|
|
577
677
|
const advancedAdapter = this.adapter;
|
|
578
|
-
if (typeof advancedAdapter.countAdvanced === "function") return advancedAdapter.countAdvanced(this.table, this.
|
|
678
|
+
if (typeof advancedAdapter.countAdvanced === "function") return advancedAdapter.countAdvanced(this.table, this.effectiveConditions(), { trx: this.options.trx });
|
|
579
679
|
return (await this.executeQuery()).length;
|
|
580
680
|
}
|
|
581
681
|
async paginate(pageOrOptions = 1, perPageArg = 15) {
|
|
@@ -643,16 +743,18 @@ var QueryBuilder = class QueryBuilder {
|
|
|
643
743
|
*/
|
|
644
744
|
async [PREPARED_UPDATE](payload) {
|
|
645
745
|
if (!this.adapter.update) throw new Error("Configured adapter does not support update operations.");
|
|
746
|
+
this.assertFiltersSurvived("update");
|
|
646
747
|
const advancedAdapter = this.adapter;
|
|
647
|
-
if (typeof advancedAdapter.updateAdvanced === "function") return advancedAdapter.updateAdvanced(this.table, this.
|
|
748
|
+
if (typeof advancedAdapter.updateAdvanced === "function") return advancedAdapter.updateAdvanced(this.table, this.effectiveConditions(), payload, { trx: this.options.trx });
|
|
648
749
|
const simpleWhere = this.toSimpleWhereClause();
|
|
649
750
|
if (simpleWhere) return this.adapter.update(this.table, simpleWhere, payload, { trx: this.options.trx });
|
|
650
751
|
throw new Error("Advanced conditions require an adapter that supports updateAdvanced.");
|
|
651
752
|
}
|
|
652
753
|
async delete() {
|
|
653
754
|
if (!this.adapter.delete) throw new Error("Configured adapter does not support delete operations.");
|
|
755
|
+
this.assertFiltersSurvived("delete");
|
|
654
756
|
const advancedAdapter = this.adapter;
|
|
655
|
-
if (typeof advancedAdapter.deleteAdvanced === "function") return advancedAdapter.deleteAdvanced(this.table, this.
|
|
757
|
+
if (typeof advancedAdapter.deleteAdvanced === "function") return advancedAdapter.deleteAdvanced(this.table, this.effectiveConditions(), { trx: this.options.trx });
|
|
656
758
|
const simpleWhere = this.toSimpleWhereClause();
|
|
657
759
|
if (simpleWhere) return this.adapter.delete(this.table, simpleWhere, { trx: this.options.trx });
|
|
658
760
|
throw new Error("Advanced conditions require an adapter that supports deleteAdvanced.");
|
|
@@ -665,7 +767,19 @@ var QueryBuilder = class QueryBuilder {
|
|
|
665
767
|
return this.get().catch(onrejected);
|
|
666
768
|
}
|
|
667
769
|
getConditions() {
|
|
668
|
-
return this.
|
|
770
|
+
return this.effectiveConditions();
|
|
771
|
+
}
|
|
772
|
+
/**
|
|
773
|
+
* Freezes the conditions applied so far as this model's global scopes, to be
|
|
774
|
+
* AND-ed around the caller's expression from here on. Left in the same list,
|
|
775
|
+
* a top-level `orWhere()` folds them into its left arm (see
|
|
776
|
+
* `normalizeConditionSequence`) and the query loses tenant isolation and
|
|
777
|
+
* soft-delete filtering.
|
|
778
|
+
*/
|
|
779
|
+
[SEAL_SCOPES]() {
|
|
780
|
+
this.scopeConditions.push(...this.conditions);
|
|
781
|
+
this.conditions = [];
|
|
782
|
+
return this;
|
|
669
783
|
}
|
|
670
784
|
getOptions() {
|
|
671
785
|
return { ...this.options };
|
|
@@ -678,14 +792,49 @@ var QueryBuilder = class QueryBuilder {
|
|
|
678
792
|
pushCallbackGroup(callback, boolean) {
|
|
679
793
|
const nested = new QueryBuilder(this.modelClass, { trx: this.options.trx });
|
|
680
794
|
callback(nested);
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
795
|
+
this.droppedUndefinedFilters ||= nested.droppedUndefinedFilters;
|
|
796
|
+
const grouped = groupConditionSequence(nested.conditions, boolean);
|
|
797
|
+
if (grouped) this.conditions.push(grouped);
|
|
798
|
+
}
|
|
799
|
+
simpleConditionsFrom(criteria) {
|
|
800
|
+
const conditions = [];
|
|
801
|
+
for (const [field, value] of Object.entries(criteria)) {
|
|
802
|
+
if (value === void 0) {
|
|
803
|
+
this.droppedUndefinedFilters = true;
|
|
804
|
+
continue;
|
|
805
|
+
}
|
|
806
|
+
conditions.push({
|
|
807
|
+
type: "simple",
|
|
808
|
+
field,
|
|
809
|
+
operator: Array.isArray(value) ? "in" : "=",
|
|
810
|
+
value
|
|
811
|
+
});
|
|
812
|
+
}
|
|
813
|
+
return conditions;
|
|
814
|
+
}
|
|
815
|
+
hasConditions() {
|
|
816
|
+
return this.scopeConditions.length > 0 || this.conditions.length > 0;
|
|
817
|
+
}
|
|
818
|
+
/** Flat list, for the basic-adapter conversion that cannot read group nodes. */
|
|
819
|
+
allConditions() {
|
|
820
|
+
return this.scopeConditions.length === 0 ? this.conditions : [...this.scopeConditions, ...this.conditions];
|
|
821
|
+
}
|
|
822
|
+
/** Global scopes AND the caller's expression, never folded into it. */
|
|
823
|
+
effectiveConditions() {
|
|
824
|
+
if (this.scopeConditions.length === 0) return this.conditions;
|
|
825
|
+
const caller = groupConditionSequence(this.conditions);
|
|
826
|
+
return caller ? [...this.scopeConditions, caller] : [...this.scopeConditions];
|
|
827
|
+
}
|
|
828
|
+
/**
|
|
829
|
+
* `where({})` and a deliberately unfiltered builder are untouched: only a
|
|
830
|
+
* filter the caller wrote and then lost counts.
|
|
831
|
+
*/
|
|
832
|
+
filtersEvaporated() {
|
|
833
|
+
return this.droppedUndefinedFilters && this.conditions.length === 0;
|
|
834
|
+
}
|
|
835
|
+
assertFiltersSurvived(operation) {
|
|
836
|
+
if (!this.filtersEvaporated()) return;
|
|
837
|
+
throw new Error(`${this.modelClass.name}: refusing to ${operation} unfiltered — every value in the where clause was undefined.`);
|
|
689
838
|
}
|
|
690
839
|
addSimpleCondition(field, operator, value) {
|
|
691
840
|
this.conditions.push({
|
|
@@ -697,14 +846,14 @@ var QueryBuilder = class QueryBuilder {
|
|
|
697
846
|
}
|
|
698
847
|
async executeQuery() {
|
|
699
848
|
const advancedAdapter = this.adapter;
|
|
700
|
-
if (typeof advancedAdapter.findManyAdvanced === "function") return advancedAdapter.findManyAdvanced(this.table, this.
|
|
849
|
+
if (typeof advancedAdapter.findManyAdvanced === "function") return advancedAdapter.findManyAdvanced(this.table, this.effectiveConditions(), {
|
|
701
850
|
orderBy: this.options.orderBy.length > 0 ? this.options.orderBy : void 0,
|
|
702
851
|
limit: this.options.limitValue,
|
|
703
852
|
offset: this.options.offsetValue,
|
|
704
853
|
select: this.options.selectFields
|
|
705
854
|
}, { trx: this.options.trx });
|
|
706
855
|
const simpleWhere = this.toSimpleWhereClause();
|
|
707
|
-
if (simpleWhere === null && this.
|
|
856
|
+
if (simpleWhere === null && this.hasConditions()) throw new Error(`${this.modelClass.name}: this query uses conditions the configured adapter cannot express (it implements neither findManyAdvanced nor countAdvanced). Running it would drop every condition, including any global scope, and return unfiltered rows.`);
|
|
708
857
|
return this.adapter.findMany(this.table, {
|
|
709
858
|
where: simpleWhere ?? void 0,
|
|
710
859
|
orderBy: this.options.orderBy.length > 0 ? this.options.orderBy : void 0,
|
|
@@ -714,9 +863,10 @@ var QueryBuilder = class QueryBuilder {
|
|
|
714
863
|
}
|
|
715
864
|
/** Null when the conditions are too complex for a basic adapter's WhereClause. */
|
|
716
865
|
toSimpleWhereClause() {
|
|
717
|
-
|
|
866
|
+
const conditions = this.allConditions();
|
|
867
|
+
if (conditions.length === 0) return null;
|
|
718
868
|
const result = {};
|
|
719
|
-
for (const condition of
|
|
869
|
+
for (const condition of conditions) {
|
|
720
870
|
if (condition.type !== "simple") return null;
|
|
721
871
|
let value;
|
|
722
872
|
if (condition.operator === "=" || condition.operator === "in") value = condition.value;
|
|
@@ -902,20 +1052,23 @@ var Model = class Model {
|
|
|
902
1052
|
static removeGlobalScope(name) {
|
|
903
1053
|
this.getGlobalScopes().remove(name);
|
|
904
1054
|
}
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
*/
|
|
910
|
-
static withoutGlobalScope(...names) {
|
|
911
|
-
const builder = new QueryBuilder(this);
|
|
912
|
-
if (this.defaultScope) this.defaultScope(builder);
|
|
913
|
-
this.getGlobalScopes().apply(builder, names);
|
|
914
|
-
return builder;
|
|
1055
|
+
static withoutGlobalScope(...args) {
|
|
1056
|
+
const [first, ...rest] = args;
|
|
1057
|
+
if (typeof first === "string" || first === void 0) return this.buildScopedQuery(void 0, args);
|
|
1058
|
+
return this.buildScopedQuery(first, rest);
|
|
915
1059
|
}
|
|
916
1060
|
/** A query with no global scopes applied, `defaultScope` included. */
|
|
917
|
-
static withoutGlobalScopes() {
|
|
918
|
-
return new QueryBuilder(this);
|
|
1061
|
+
static withoutGlobalScopes(queryOptions) {
|
|
1062
|
+
return new QueryBuilder(this, queryOptions);
|
|
1063
|
+
}
|
|
1064
|
+
/**
|
|
1065
|
+
* Both write entry points fork on `hasScopes()`, and only one arm reaches a
|
|
1066
|
+
* builder — so the refusal belongs above the fork, where every adapter is
|
|
1067
|
+
* still in scope.
|
|
1068
|
+
*/
|
|
1069
|
+
static assertFiltersSurvived(where, operation) {
|
|
1070
|
+
if (!everyFilterDropped(where)) return;
|
|
1071
|
+
throw new Error(`${this.name}: refusing to ${operation} unfiltered — every value in the where clause was undefined.`);
|
|
919
1072
|
}
|
|
920
1073
|
/** Applies hidden/visible filtering, accessors and appends. */
|
|
921
1074
|
static serialize(record) {
|
|
@@ -1041,6 +1194,7 @@ var Model = class Model {
|
|
|
1041
1194
|
return records;
|
|
1042
1195
|
}
|
|
1043
1196
|
static async find(id, key = "id", queryOptions) {
|
|
1197
|
+
if (id === void 0) return null;
|
|
1044
1198
|
if (this.hasScopes()) return this.newQuery(queryOptions).where(key, id).first();
|
|
1045
1199
|
const table = this.resolveTable();
|
|
1046
1200
|
const where = { [key]: id };
|
|
@@ -1072,6 +1226,7 @@ var Model = class Model {
|
|
|
1072
1226
|
return copy;
|
|
1073
1227
|
}
|
|
1074
1228
|
static async first(where, queryOptions) {
|
|
1229
|
+
if (everyFilterDropped(where)) return null;
|
|
1075
1230
|
if (this.hasScopes()) {
|
|
1076
1231
|
const builder = this.newQuery(queryOptions).limit(1);
|
|
1077
1232
|
if (where) builder.where(where);
|
|
@@ -1108,11 +1263,19 @@ var Model = class Model {
|
|
|
1108
1263
|
return this.newQuery().select(...fields);
|
|
1109
1264
|
}
|
|
1110
1265
|
static newQuery(queryOptions) {
|
|
1266
|
+
return this.buildScopedQuery(queryOptions);
|
|
1267
|
+
}
|
|
1268
|
+
/**
|
|
1269
|
+
* The one place a scoped builder is born: applying scopes without sealing
|
|
1270
|
+
* them leaves them foldable by a later `orWhere()`, and nothing else would
|
|
1271
|
+
* report it. `except` names the global scopes to leave off.
|
|
1272
|
+
*/
|
|
1273
|
+
static buildScopedQuery(queryOptions, except) {
|
|
1111
1274
|
const builder = new QueryBuilder(this, queryOptions);
|
|
1112
1275
|
if (this.defaultScope) this.defaultScope(builder);
|
|
1113
1276
|
const registry = this.globalScopeRegistry;
|
|
1114
|
-
if (registry && registry.size > 0) registry.apply(builder);
|
|
1115
|
-
return builder;
|
|
1277
|
+
if (registry && registry.size > 0) registry.apply(builder, except);
|
|
1278
|
+
return builder[SEAL_SCOPES]();
|
|
1116
1279
|
}
|
|
1117
1280
|
/** No scopes applied — for soft-deleted records or bypassing global filters. */
|
|
1118
1281
|
static newQueryWithoutScopes(queryOptions) {
|
|
@@ -1363,6 +1526,7 @@ var Model = class Model {
|
|
|
1363
1526
|
const table = this.resolveTable();
|
|
1364
1527
|
const adapter = this.getAdapter();
|
|
1365
1528
|
if (!adapter.update) throw new Error("Configured adapter does not support update operations.");
|
|
1529
|
+
this.assertFiltersSurvived(where, "update");
|
|
1366
1530
|
const filtered = applyFillable ? this.filterFillable(data) : { ...data };
|
|
1367
1531
|
const payload = await this.preparePersistencePayload(filtered);
|
|
1368
1532
|
const hooks = this.hooks;
|
|
@@ -1393,6 +1557,7 @@ var Model = class Model {
|
|
|
1393
1557
|
const table = this.resolveTable();
|
|
1394
1558
|
const adapter = this.getAdapter();
|
|
1395
1559
|
if (!adapter.delete) throw new Error("Configured adapter does not support delete operations.");
|
|
1560
|
+
this.assertFiltersSurvived(where, "delete");
|
|
1396
1561
|
const hooks = this.hooks;
|
|
1397
1562
|
const observers = this.observers;
|
|
1398
1563
|
const whereData = where;
|
|
@@ -1810,16 +1975,20 @@ function resolveQueryableDatabase(adapter) {
|
|
|
1810
1975
|
}
|
|
1811
1976
|
//#endregion
|
|
1812
1977
|
//#region src/SoftDeletes.ts
|
|
1813
|
-
/**
|
|
1814
|
-
|
|
1815
|
-
|
|
1978
|
+
/**
|
|
1979
|
+
* A query carrying every global scope this model has, including softDelete.
|
|
1980
|
+
* `queryOptions` carries the caller's `trx`; dropping it here sends the write to
|
|
1981
|
+
* the default connection, outside the transaction meant to own it.
|
|
1982
|
+
*/
|
|
1983
|
+
function scopedQuery(model, where, queryOptions) {
|
|
1984
|
+
return model.newQuery(queryOptions).where(where);
|
|
1816
1985
|
}
|
|
1817
1986
|
/** A query carrying every global scope *except* softDelete, so it sees trashed rows. */
|
|
1818
|
-
function withoutSoftDeleteScope(model) {
|
|
1819
|
-
return model.withoutGlobalScope("softDelete");
|
|
1987
|
+
function withoutSoftDeleteScope(model, queryOptions) {
|
|
1988
|
+
return model.withoutGlobalScope(queryOptions ?? {}, "softDelete");
|
|
1820
1989
|
}
|
|
1821
|
-
function trashedScopedQuery(model, where) {
|
|
1822
|
-
return withoutSoftDeleteScope(model).where(where);
|
|
1990
|
+
function trashedScopedQuery(model, where, queryOptions) {
|
|
1991
|
+
return withoutSoftDeleteScope(model, queryOptions).where(where);
|
|
1823
1992
|
}
|
|
1824
1993
|
/**
|
|
1825
1994
|
* Mixin where `delete()` sets `deletedAt` instead of removing the row, and a
|
|
@@ -1833,26 +2002,26 @@ function SoftDeletes(Base) {
|
|
|
1833
2002
|
SoftDeleteModel.deletedAtColumn = "deletedAt";
|
|
1834
2003
|
const scopeFn = (q) => q.whereNull("deletedAt");
|
|
1835
2004
|
SoftDeleteModel.addGlobalScope("softDelete", scopeFn);
|
|
1836
|
-
SoftDeleteModel.delete = async function(where) {
|
|
2005
|
+
SoftDeleteModel.delete = async function(where, writeOptions) {
|
|
1837
2006
|
if (!this.getAdapter().update) throw new Error("Configured adapter does not support update operations (needed for soft delete).");
|
|
1838
2007
|
const column = this.deletedAtColumn;
|
|
1839
|
-
return scopedQuery(this, where)[PREPARED_UPDATE]({ [column]: /* @__PURE__ */ new Date() });
|
|
2008
|
+
return scopedQuery(this, where, writeOptions)[PREPARED_UPDATE]({ [column]: /* @__PURE__ */ new Date() });
|
|
1840
2009
|
};
|
|
1841
|
-
SoftDeleteModel.withTrashed = function() {
|
|
1842
|
-
return withoutSoftDeleteScope(this);
|
|
2010
|
+
SoftDeleteModel.withTrashed = function(queryOptions) {
|
|
2011
|
+
return withoutSoftDeleteScope(this, queryOptions);
|
|
1843
2012
|
};
|
|
1844
|
-
SoftDeleteModel.onlyTrashed = function() {
|
|
2013
|
+
SoftDeleteModel.onlyTrashed = function(queryOptions) {
|
|
1845
2014
|
const column = this.deletedAtColumn;
|
|
1846
|
-
return withoutSoftDeleteScope(this).whereNotNull(column);
|
|
2015
|
+
return withoutSoftDeleteScope(this, queryOptions).whereNotNull(column);
|
|
1847
2016
|
};
|
|
1848
|
-
SoftDeleteModel.restore = async function(where) {
|
|
2017
|
+
SoftDeleteModel.restore = async function(where, writeOptions) {
|
|
1849
2018
|
if (!this.getAdapter().update) throw new Error("Configured adapter does not support update operations (needed for restore).");
|
|
1850
2019
|
const column = this.deletedAtColumn;
|
|
1851
|
-
return trashedScopedQuery(this, where)[PREPARED_UPDATE]({ [column]: null });
|
|
2020
|
+
return trashedScopedQuery(this, where, writeOptions)[PREPARED_UPDATE]({ [column]: null });
|
|
1852
2021
|
};
|
|
1853
|
-
SoftDeleteModel.forceDelete = async function(where) {
|
|
2022
|
+
SoftDeleteModel.forceDelete = async function(where, writeOptions) {
|
|
1854
2023
|
if (!this.getAdapter().delete) throw new Error("Configured adapter does not support delete operations.");
|
|
1855
|
-
return trashedScopedQuery(this, where).delete();
|
|
2024
|
+
return trashedScopedQuery(this, where, writeOptions).delete();
|
|
1856
2025
|
};
|
|
1857
2026
|
return SoftDeleteModel;
|
|
1858
2027
|
}
|