@guren/orm 2.6.3 → 2.7.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/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. */
@@ -396,8 +424,19 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
396
424
  * register a named scope and nothing else.
397
425
  */
398
426
  static withoutGlobalScope<T extends typeof Model>(this: T, ...names: string[]): QueryBuilder<TRecordFor<T>>;
427
+ /**
428
+ * Query options lead here because `names` is a rest parameter and cannot be
429
+ * followed by an optional one; every other entry point takes them trailing.
430
+ */
431
+ static withoutGlobalScope<T extends typeof Model>(this: T, queryOptions: ModelQueryOptions, ...names: string[]): QueryBuilder<TRecordFor<T>>;
399
432
  /** A query with no global scopes applied, `defaultScope` included. */
400
- static withoutGlobalScopes<T extends typeof Model>(this: T): QueryBuilder<TRecordFor<T>>;
433
+ static withoutGlobalScopes<T extends typeof Model>(this: T, queryOptions?: ModelQueryOptions): QueryBuilder<TRecordFor<T>>;
434
+ /**
435
+ * Both write entry points fork on `hasScopes()`, and only one arm reaches a
436
+ * builder — so the refusal belongs above the fork, where every adapter is
437
+ * still in scope.
438
+ */
439
+ private static assertFiltersSurvived;
401
440
  /** Applies hidden/visible filtering, accessors and appends. */
402
441
  static serialize<T extends typeof Model>(this: T, record: TRecordFor<T>): PlainObject;
403
442
  static serializeMany<T extends typeof Model>(this: T, records: TRecordFor<T>[]): PlainObject[];
@@ -445,6 +484,12 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
445
484
  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
485
  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
486
  static newQuery<T extends typeof Model>(this: T, queryOptions?: ModelQueryOptions): QueryBuilder<TRecordFor<T>>;
487
+ /**
488
+ * The one place a scoped builder is born: applying scopes without sealing
489
+ * them leaves them foldable by a later `orWhere()`, and nothing else would
490
+ * report it. `except` names the global scopes to leave off.
491
+ */
492
+ private static buildScopedQuery;
448
493
  /** No scopes applied — for soft-deleted records or bypassing global filters. */
449
494
  static newQueryWithoutScopes<T extends typeof Model>(this: T, queryOptions?: ModelQueryOptions): QueryBuilder<TRecordFor<T>>;
450
495
  /**
@@ -764,13 +809,13 @@ declare class MassAssignmentException extends Error {
764
809
  interface SoftDeletesStatic {
765
810
  deletedAtColumn: string;
766
811
  /** Start a query that includes soft-deleted records. */
767
- withTrashed(): QueryBuilder<PlainObject>;
812
+ withTrashed(queryOptions?: ModelQueryOptions): QueryBuilder<PlainObject>;
768
813
  /** Start a query that returns only soft-deleted records. */
769
- onlyTrashed(): QueryBuilder<PlainObject>;
814
+ onlyTrashed(queryOptions?: ModelQueryOptions): QueryBuilder<PlainObject>;
770
815
  /** Restore soft-deleted records by setting deletedAt back to null. */
771
- restore(where: Partial<Record<string, unknown>>): Promise<PlainObject>;
816
+ restore(where: Partial<Record<string, unknown>>, writeOptions?: ModelWriteOptions): Promise<PlainObject>;
772
817
  /** Permanently delete records from the database, bypassing soft delete. */
773
- forceDelete(where: Partial<Record<string, unknown>>): Promise<number | PlainObject | void>;
818
+ forceDelete(where: Partial<Record<string, unknown>>, writeOptions?: ModelWriteOptions): Promise<number | PlainObject | void>;
774
819
  }
775
820
  /**
776
821
  * Mixin where `delete()` sets `deletedAt` instead of removing the row, and a
package/dist/index.js CHANGED
@@ -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];
@@ -425,6 +449,11 @@ var ModelNotFoundException = class extends Error {
425
449
  */
426
450
  const PREPARED_UPDATE = Symbol("guren.orm.preparedUpdate");
427
451
  /**
452
+ * Key for the global-scope seal. Exported for `Model` across the module
453
+ * boundary, but kept out of the package entry point.
454
+ */
455
+ const SEAL_SCOPES = Symbol("guren.orm.sealScopes");
456
+ /**
428
457
  * Fluent query builder for the Guren ORM. Thenable, so awaiting a builder
429
458
  * resolves to the result of `get()`.
430
459
  *
@@ -433,6 +462,9 @@ const PREPARED_UPDATE = Symbol("guren.orm.preparedUpdate");
433
462
  */
434
463
  var QueryBuilder = class QueryBuilder {
435
464
  conditions = [];
465
+ scopeConditions = [];
466
+ /** Fold this up wherever a nested builder's conditions are (pushCallbackGroup). */
467
+ droppedUndefinedFilters = false;
436
468
  options = { orderBy: [] };
437
469
  modelClass;
438
470
  table;
@@ -451,7 +483,7 @@ var QueryBuilder = class QueryBuilder {
451
483
  return this;
452
484
  }
453
485
  if (typeof fieldOrConditions === "object" && fieldOrConditions !== null) {
454
- for (const [key, val] of Object.entries(fieldOrConditions)) if (val !== void 0) this.addSimpleCondition(key, Array.isArray(val) ? "in" : "=", val);
486
+ this.conditions.push(...this.simpleConditionsFrom(fieldOrConditions));
455
487
  return this;
456
488
  }
457
489
  const field = fieldOrConditions;
@@ -465,14 +497,8 @@ var QueryBuilder = class QueryBuilder {
465
497
  return this;
466
498
  }
467
499
  const orConditions = [];
468
- if (typeof fieldOrConditions === "object" && fieldOrConditions !== null) {
469
- for (const [key, val] of Object.entries(fieldOrConditions)) if (val !== void 0) orConditions.push({
470
- type: "simple",
471
- field: key,
472
- operator: Array.isArray(val) ? "in" : "=",
473
- value: val
474
- });
475
- } else {
500
+ if (typeof fieldOrConditions === "object" && fieldOrConditions !== null) orConditions.push(...this.simpleConditionsFrom(fieldOrConditions));
501
+ else {
476
502
  const field = fieldOrConditions;
477
503
  if (arguments.length === 2) orConditions.push({
478
504
  type: "simple",
@@ -558,6 +584,7 @@ var QueryBuilder = class QueryBuilder {
558
584
  return this.loadEagerRelations(results);
559
585
  }
560
586
  async first() {
587
+ if (this.filtersEvaporated()) return null;
561
588
  const prev = this.options.limitValue;
562
589
  this.options.limitValue = 1;
563
590
  try {
@@ -573,9 +600,9 @@ var QueryBuilder = class QueryBuilder {
573
600
  return record;
574
601
  }
575
602
  async count() {
576
- if (typeof this.adapter.count === "function" && this.conditions.length === 0) return this.adapter.count(this.table, void 0, { trx: this.options.trx });
603
+ if (typeof this.adapter.count === "function" && !this.hasConditions()) return this.adapter.count(this.table, void 0, { trx: this.options.trx });
577
604
  const advancedAdapter = this.adapter;
578
- if (typeof advancedAdapter.countAdvanced === "function") return advancedAdapter.countAdvanced(this.table, this.conditions, { trx: this.options.trx });
605
+ if (typeof advancedAdapter.countAdvanced === "function") return advancedAdapter.countAdvanced(this.table, this.effectiveConditions(), { trx: this.options.trx });
579
606
  return (await this.executeQuery()).length;
580
607
  }
581
608
  async paginate(pageOrOptions = 1, perPageArg = 15) {
@@ -643,16 +670,18 @@ var QueryBuilder = class QueryBuilder {
643
670
  */
644
671
  async [PREPARED_UPDATE](payload) {
645
672
  if (!this.adapter.update) throw new Error("Configured adapter does not support update operations.");
673
+ this.assertFiltersSurvived("update");
646
674
  const advancedAdapter = this.adapter;
647
- if (typeof advancedAdapter.updateAdvanced === "function") return advancedAdapter.updateAdvanced(this.table, this.conditions, payload, { trx: this.options.trx });
675
+ if (typeof advancedAdapter.updateAdvanced === "function") return advancedAdapter.updateAdvanced(this.table, this.effectiveConditions(), payload, { trx: this.options.trx });
648
676
  const simpleWhere = this.toSimpleWhereClause();
649
677
  if (simpleWhere) return this.adapter.update(this.table, simpleWhere, payload, { trx: this.options.trx });
650
678
  throw new Error("Advanced conditions require an adapter that supports updateAdvanced.");
651
679
  }
652
680
  async delete() {
653
681
  if (!this.adapter.delete) throw new Error("Configured adapter does not support delete operations.");
682
+ this.assertFiltersSurvived("delete");
654
683
  const advancedAdapter = this.adapter;
655
- if (typeof advancedAdapter.deleteAdvanced === "function") return advancedAdapter.deleteAdvanced(this.table, this.conditions, { trx: this.options.trx });
684
+ if (typeof advancedAdapter.deleteAdvanced === "function") return advancedAdapter.deleteAdvanced(this.table, this.effectiveConditions(), { trx: this.options.trx });
656
685
  const simpleWhere = this.toSimpleWhereClause();
657
686
  if (simpleWhere) return this.adapter.delete(this.table, simpleWhere, { trx: this.options.trx });
658
687
  throw new Error("Advanced conditions require an adapter that supports deleteAdvanced.");
@@ -665,7 +694,19 @@ var QueryBuilder = class QueryBuilder {
665
694
  return this.get().catch(onrejected);
666
695
  }
667
696
  getConditions() {
668
- return this.conditions;
697
+ return this.effectiveConditions();
698
+ }
699
+ /**
700
+ * Freezes the conditions applied so far as this model's global scopes, to be
701
+ * AND-ed around the caller's expression from here on. Left in the same list,
702
+ * a top-level `orWhere()` folds them into its left arm (see
703
+ * `normalizeConditionSequence`) and the query loses tenant isolation and
704
+ * soft-delete filtering.
705
+ */
706
+ [SEAL_SCOPES]() {
707
+ this.scopeConditions.push(...this.conditions);
708
+ this.conditions = [];
709
+ return this;
669
710
  }
670
711
  getOptions() {
671
712
  return { ...this.options };
@@ -678,14 +719,49 @@ var QueryBuilder = class QueryBuilder {
678
719
  pushCallbackGroup(callback, boolean) {
679
720
  const nested = new QueryBuilder(this.modelClass, { trx: this.options.trx });
680
721
  callback(nested);
681
- const grouped = normalizeConditionSequence(nested.conditions);
682
- if (!grouped) return;
683
- const needsWrap = boolean === "or" || grouped.type === "group" && grouped.boolean === "or";
684
- this.conditions.push(needsWrap ? {
685
- type: "group",
686
- boolean,
687
- conditions: [grouped]
688
- } : grouped);
722
+ this.droppedUndefinedFilters ||= nested.droppedUndefinedFilters;
723
+ const grouped = groupConditionSequence(nested.conditions, boolean);
724
+ if (grouped) this.conditions.push(grouped);
725
+ }
726
+ simpleConditionsFrom(criteria) {
727
+ const conditions = [];
728
+ for (const [field, value] of Object.entries(criteria)) {
729
+ if (value === void 0) {
730
+ this.droppedUndefinedFilters = true;
731
+ continue;
732
+ }
733
+ conditions.push({
734
+ type: "simple",
735
+ field,
736
+ operator: Array.isArray(value) ? "in" : "=",
737
+ value
738
+ });
739
+ }
740
+ return conditions;
741
+ }
742
+ hasConditions() {
743
+ return this.scopeConditions.length > 0 || this.conditions.length > 0;
744
+ }
745
+ /** Flat list, for the basic-adapter conversion that cannot read group nodes. */
746
+ allConditions() {
747
+ return this.scopeConditions.length === 0 ? this.conditions : [...this.scopeConditions, ...this.conditions];
748
+ }
749
+ /** Global scopes AND the caller's expression, never folded into it. */
750
+ effectiveConditions() {
751
+ if (this.scopeConditions.length === 0) return this.conditions;
752
+ const caller = groupConditionSequence(this.conditions);
753
+ return caller ? [...this.scopeConditions, caller] : [...this.scopeConditions];
754
+ }
755
+ /**
756
+ * `where({})` and a deliberately unfiltered builder are untouched: only a
757
+ * filter the caller wrote and then lost counts.
758
+ */
759
+ filtersEvaporated() {
760
+ return this.droppedUndefinedFilters && this.conditions.length === 0;
761
+ }
762
+ assertFiltersSurvived(operation) {
763
+ if (!this.filtersEvaporated()) return;
764
+ throw new Error(`${this.modelClass.name}: refusing to ${operation} unfiltered — every value in the where clause was undefined.`);
689
765
  }
690
766
  addSimpleCondition(field, operator, value) {
691
767
  this.conditions.push({
@@ -697,14 +773,14 @@ var QueryBuilder = class QueryBuilder {
697
773
  }
698
774
  async executeQuery() {
699
775
  const advancedAdapter = this.adapter;
700
- if (typeof advancedAdapter.findManyAdvanced === "function") return advancedAdapter.findManyAdvanced(this.table, this.conditions, {
776
+ if (typeof advancedAdapter.findManyAdvanced === "function") return advancedAdapter.findManyAdvanced(this.table, this.effectiveConditions(), {
701
777
  orderBy: this.options.orderBy.length > 0 ? this.options.orderBy : void 0,
702
778
  limit: this.options.limitValue,
703
779
  offset: this.options.offsetValue,
704
780
  select: this.options.selectFields
705
781
  }, { trx: this.options.trx });
706
782
  const simpleWhere = this.toSimpleWhereClause();
707
- if (simpleWhere === null && this.conditions.length > 0) 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.`);
783
+ 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
784
  return this.adapter.findMany(this.table, {
709
785
  where: simpleWhere ?? void 0,
710
786
  orderBy: this.options.orderBy.length > 0 ? this.options.orderBy : void 0,
@@ -714,9 +790,10 @@ var QueryBuilder = class QueryBuilder {
714
790
  }
715
791
  /** Null when the conditions are too complex for a basic adapter's WhereClause. */
716
792
  toSimpleWhereClause() {
717
- if (this.conditions.length === 0) return null;
793
+ const conditions = this.allConditions();
794
+ if (conditions.length === 0) return null;
718
795
  const result = {};
719
- for (const condition of this.conditions) {
796
+ for (const condition of conditions) {
720
797
  if (condition.type !== "simple") return null;
721
798
  let value;
722
799
  if (condition.operator === "=" || condition.operator === "in") value = condition.value;
@@ -902,20 +979,23 @@ var Model = class Model {
902
979
  static removeGlobalScope(name) {
903
980
  this.getGlobalScopes().remove(name);
904
981
  }
905
- /**
906
- * Only *named* scopes can be excluded: `defaultScope` is re-applied whatever
907
- * this is asked to drop, so a mixin whose filter must be opt-out-able has to
908
- * register a named scope and nothing else.
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;
982
+ static withoutGlobalScope(...args) {
983
+ const [first, ...rest] = args;
984
+ if (typeof first === "string" || first === void 0) return this.buildScopedQuery(void 0, args);
985
+ return this.buildScopedQuery(first, rest);
915
986
  }
916
987
  /** A query with no global scopes applied, `defaultScope` included. */
917
- static withoutGlobalScopes() {
918
- return new QueryBuilder(this);
988
+ static withoutGlobalScopes(queryOptions) {
989
+ return new QueryBuilder(this, queryOptions);
990
+ }
991
+ /**
992
+ * Both write entry points fork on `hasScopes()`, and only one arm reaches a
993
+ * builder — so the refusal belongs above the fork, where every adapter is
994
+ * still in scope.
995
+ */
996
+ static assertFiltersSurvived(where, operation) {
997
+ if (!everyFilterDropped(where)) return;
998
+ throw new Error(`${this.name}: refusing to ${operation} unfiltered — every value in the where clause was undefined.`);
919
999
  }
920
1000
  /** Applies hidden/visible filtering, accessors and appends. */
921
1001
  static serialize(record) {
@@ -1041,6 +1121,7 @@ var Model = class Model {
1041
1121
  return records;
1042
1122
  }
1043
1123
  static async find(id, key = "id", queryOptions) {
1124
+ if (id === void 0) return null;
1044
1125
  if (this.hasScopes()) return this.newQuery(queryOptions).where(key, id).first();
1045
1126
  const table = this.resolveTable();
1046
1127
  const where = { [key]: id };
@@ -1072,6 +1153,7 @@ var Model = class Model {
1072
1153
  return copy;
1073
1154
  }
1074
1155
  static async first(where, queryOptions) {
1156
+ if (everyFilterDropped(where)) return null;
1075
1157
  if (this.hasScopes()) {
1076
1158
  const builder = this.newQuery(queryOptions).limit(1);
1077
1159
  if (where) builder.where(where);
@@ -1108,11 +1190,19 @@ var Model = class Model {
1108
1190
  return this.newQuery().select(...fields);
1109
1191
  }
1110
1192
  static newQuery(queryOptions) {
1193
+ return this.buildScopedQuery(queryOptions);
1194
+ }
1195
+ /**
1196
+ * The one place a scoped builder is born: applying scopes without sealing
1197
+ * them leaves them foldable by a later `orWhere()`, and nothing else would
1198
+ * report it. `except` names the global scopes to leave off.
1199
+ */
1200
+ static buildScopedQuery(queryOptions, except) {
1111
1201
  const builder = new QueryBuilder(this, queryOptions);
1112
1202
  if (this.defaultScope) this.defaultScope(builder);
1113
1203
  const registry = this.globalScopeRegistry;
1114
- if (registry && registry.size > 0) registry.apply(builder);
1115
- return builder;
1204
+ if (registry && registry.size > 0) registry.apply(builder, except);
1205
+ return builder[SEAL_SCOPES]();
1116
1206
  }
1117
1207
  /** No scopes applied — for soft-deleted records or bypassing global filters. */
1118
1208
  static newQueryWithoutScopes(queryOptions) {
@@ -1363,6 +1453,7 @@ var Model = class Model {
1363
1453
  const table = this.resolveTable();
1364
1454
  const adapter = this.getAdapter();
1365
1455
  if (!adapter.update) throw new Error("Configured adapter does not support update operations.");
1456
+ this.assertFiltersSurvived(where, "update");
1366
1457
  const filtered = applyFillable ? this.filterFillable(data) : { ...data };
1367
1458
  const payload = await this.preparePersistencePayload(filtered);
1368
1459
  const hooks = this.hooks;
@@ -1393,6 +1484,7 @@ var Model = class Model {
1393
1484
  const table = this.resolveTable();
1394
1485
  const adapter = this.getAdapter();
1395
1486
  if (!adapter.delete) throw new Error("Configured adapter does not support delete operations.");
1487
+ this.assertFiltersSurvived(where, "delete");
1396
1488
  const hooks = this.hooks;
1397
1489
  const observers = this.observers;
1398
1490
  const whereData = where;
@@ -1810,16 +1902,20 @@ function resolveQueryableDatabase(adapter) {
1810
1902
  }
1811
1903
  //#endregion
1812
1904
  //#region src/SoftDeletes.ts
1813
- /** A query carrying every global scope this model has, including softDelete. */
1814
- function scopedQuery(model, where) {
1815
- return model.newQuery().where(where);
1905
+ /**
1906
+ * A query carrying every global scope this model has, including softDelete.
1907
+ * `queryOptions` carries the caller's `trx`; dropping it here sends the write to
1908
+ * the default connection, outside the transaction meant to own it.
1909
+ */
1910
+ function scopedQuery(model, where, queryOptions) {
1911
+ return model.newQuery(queryOptions).where(where);
1816
1912
  }
1817
1913
  /** A query carrying every global scope *except* softDelete, so it sees trashed rows. */
1818
- function withoutSoftDeleteScope(model) {
1819
- return model.withoutGlobalScope("softDelete");
1914
+ function withoutSoftDeleteScope(model, queryOptions) {
1915
+ return model.withoutGlobalScope(queryOptions ?? {}, "softDelete");
1820
1916
  }
1821
- function trashedScopedQuery(model, where) {
1822
- return withoutSoftDeleteScope(model).where(where);
1917
+ function trashedScopedQuery(model, where, queryOptions) {
1918
+ return withoutSoftDeleteScope(model, queryOptions).where(where);
1823
1919
  }
1824
1920
  /**
1825
1921
  * Mixin where `delete()` sets `deletedAt` instead of removing the row, and a
@@ -1833,26 +1929,26 @@ function SoftDeletes(Base) {
1833
1929
  SoftDeleteModel.deletedAtColumn = "deletedAt";
1834
1930
  const scopeFn = (q) => q.whereNull("deletedAt");
1835
1931
  SoftDeleteModel.addGlobalScope("softDelete", scopeFn);
1836
- SoftDeleteModel.delete = async function(where) {
1932
+ SoftDeleteModel.delete = async function(where, writeOptions) {
1837
1933
  if (!this.getAdapter().update) throw new Error("Configured adapter does not support update operations (needed for soft delete).");
1838
1934
  const column = this.deletedAtColumn;
1839
- return scopedQuery(this, where)[PREPARED_UPDATE]({ [column]: /* @__PURE__ */ new Date() });
1935
+ return scopedQuery(this, where, writeOptions)[PREPARED_UPDATE]({ [column]: /* @__PURE__ */ new Date() });
1840
1936
  };
1841
- SoftDeleteModel.withTrashed = function() {
1842
- return withoutSoftDeleteScope(this);
1937
+ SoftDeleteModel.withTrashed = function(queryOptions) {
1938
+ return withoutSoftDeleteScope(this, queryOptions);
1843
1939
  };
1844
- SoftDeleteModel.onlyTrashed = function() {
1940
+ SoftDeleteModel.onlyTrashed = function(queryOptions) {
1845
1941
  const column = this.deletedAtColumn;
1846
- return withoutSoftDeleteScope(this).whereNotNull(column);
1942
+ return withoutSoftDeleteScope(this, queryOptions).whereNotNull(column);
1847
1943
  };
1848
- SoftDeleteModel.restore = async function(where) {
1944
+ SoftDeleteModel.restore = async function(where, writeOptions) {
1849
1945
  if (!this.getAdapter().update) throw new Error("Configured adapter does not support update operations (needed for restore).");
1850
1946
  const column = this.deletedAtColumn;
1851
- return trashedScopedQuery(this, where)[PREPARED_UPDATE]({ [column]: null });
1947
+ return trashedScopedQuery(this, where, writeOptions)[PREPARED_UPDATE]({ [column]: null });
1852
1948
  };
1853
- SoftDeleteModel.forceDelete = async function(where) {
1949
+ SoftDeleteModel.forceDelete = async function(where, writeOptions) {
1854
1950
  if (!this.getAdapter().delete) throw new Error("Configured adapter does not support delete operations.");
1855
- return trashedScopedQuery(this, where).delete();
1951
+ return trashedScopedQuery(this, where, writeOptions).delete();
1856
1952
  };
1857
1953
  return SoftDeleteModel;
1858
1954
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/orm",
3
- "version": "2.6.3",
3
+ "version": "2.7.0",
4
4
  "type": "module",
5
5
  "sideEffects": [
6
6
  "./src/instance-guard.ts",