@guren/orm 2.6.2 → 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.
Files changed (3) hide show
  1. package/dist/index.d.ts +272 -1173
  2. package/dist/index.js +389 -1145
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -5,17 +5,10 @@ import { existsSync, readdirSync } from "node:fs";
5
5
  import { readdir } from "node:fs/promises";
6
6
  //#region src/instance-guard.ts
7
7
  /**
8
- * Detects multiple loaded copies of @guren/orm in one process.
9
- *
10
- * Model and DrizzleAdapter keep module-level state (the configured database,
11
- * relation registries). When two copies of the package are loaded — usually
12
- * because mixed @guren/* versions made the package manager nest a second
13
- * copy under another @guren package — `configureOrm()` configures one copy
14
- * while models imported through the other copy stay unconfigured, and every
15
- * query fails with "database has not been configured".
16
- *
17
- * The runtime cannot merge the copies, but it can make the failure mode
18
- * obvious instead of silent.
8
+ * Detects multiple loaded copies of @guren/orm in one process. Model and
9
+ * DrizzleAdapter keep module-level state, so `configureOrm()` configures one
10
+ * copy while models imported through the other fail with "database has not
11
+ * been configured". The runtime cannot merge them, only make it non-silent.
19
12
  */
20
13
  const INSTANCE_KEY = Symbol.for("guren.orm.loaded");
21
14
  const globalScope = globalThis;
@@ -36,17 +29,21 @@ else {
36
29
  //#endregion
37
30
  //#region src/where-conditions.ts
38
31
  /**
39
- * Fold a builder's sequential condition list into one condition node.
40
- *
41
- * A condition list has sequential semantics: an OR group folds everything
42
- * before it into the OR, so `.where(a).where(b).orWhere(c)` reads
43
- * `(a AND b) OR c`. Inside a GroupCondition, members are joined flatly
44
- * with the group's boolean. This is the one implementation of that fold —
45
- * the Drizzle renderer applies it to the top-level list before rendering,
46
- * and QueryBuilder applies it to a grouping callback's collected list, so
47
- * the two can never drift apart.
48
- *
49
- * Returns null when the list holds no renderable condition.
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
+ /**
42
+ * Folds a builder's condition list into one node, or null when it holds
43
+ * nothing renderable. An OR group folds everything before it into the OR, so
44
+ * `.where(a).where(b).orWhere(c)` reads `(a AND b) OR c`. The one
45
+ * implementation of that fold: the Drizzle renderer applies it to the
46
+ * top-level list, QueryBuilder to a grouping callback's, so they cannot drift.
50
47
  */
51
48
  function normalizeConditionSequence(conditions) {
52
49
  let pending = [];
@@ -61,6 +58,20 @@ function normalizeConditionSequence(conditions) {
61
58
  }
62
59
  return combine("and", pending);
63
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
+ }
64
75
  function combine(boolean, parts) {
65
76
  if (parts.length === 0) return null;
66
77
  if (parts.length === 1) return parts[0];
@@ -81,9 +92,6 @@ function resolveColumn(table, field) {
81
92
  if (!column) throw new Error(`DrizzleConditions: unknown column "${field}" on provided table.`);
82
93
  return column;
83
94
  }
84
- /**
85
- * Builds a Drizzle ORM condition from a single SimpleCondition.
86
- */
87
95
  function buildSimpleCondition(table, condition) {
88
96
  const column = resolveColumn(table, condition.field);
89
97
  switch (condition.operator) {
@@ -105,9 +113,6 @@ function buildSimpleCondition(table, condition) {
105
113
  default: throw new Error(`DrizzleConditions: unsupported operator "${condition.operator}".`);
106
114
  }
107
115
  }
108
- /**
109
- * Builds a Drizzle ORM condition from a GroupCondition.
110
- */
111
116
  function buildGroupCondition(table, group) {
112
117
  const parts = group.conditions.map((c) => buildSingleCondition(table, c)).filter((c) => c !== void 0);
113
118
  if (parts.length === 0) return;
@@ -115,27 +120,16 @@ function buildGroupCondition(table, group) {
115
120
  if (group.boolean === "or") return or(...parts);
116
121
  return and(...parts);
117
122
  }
118
- /**
119
- * Builds a Drizzle ORM condition from any WhereCondition.
120
- */
121
123
  function buildSingleCondition(table, condition) {
122
124
  if (condition.type === "simple") return buildSimpleCondition(table, condition);
123
125
  return buildGroupCondition(table, condition);
124
126
  }
125
127
  /**
126
- * Translates an array of QueryBuilder WhereConditions into a single
127
- * Drizzle ORM condition expression.
128
- *
129
- * The list's sequential semantics — top-level conditions AND together,
130
- * an OR group folds everything before it into the OR, so
131
- * .where('a', 1).where('b', 2).orWhere('c', 3)
132
- * produces `(a = 1 AND b = 2) OR (c = 3)` — are applied by
133
- * `normalizeConditionSequence` (shared with QueryBuilder's grouping
134
- * callbacks), leaving only a flat-join tree to render here.
135
- *
136
- * @param table - The Drizzle table object
137
- * @param conditions - Array of WhereCondition objects from QueryBuilder
138
- * @returns A Drizzle SQL condition or undefined if no conditions
128
+ * Translates an array of QueryBuilder WhereConditions into a single Drizzle ORM
129
+ * condition expression. The list's sequential semantics — an OR group folds
130
+ * everything before it into the OR, so `.where('a',1).where('b',2).orWhere('c',3)`
131
+ * is `(a = 1 AND b = 2) OR (c = 3)` — are already applied by
132
+ * `normalizeConditionSequence`, leaving a flat-join tree to render here.
139
133
  */
140
134
  function buildDrizzleConditions(table, conditions) {
141
135
  const normalized = normalizeConditionSequence(conditions);
@@ -206,11 +200,9 @@ function isPromiseLike(value) {
206
200
  return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
207
201
  }
208
202
  /**
209
- * Eagerly call `.returning()` on a query builder if available.
210
- * This ensures SQLite (bun-sqlite) drivers return inserted/updated rows
211
- * instead of RunResult, since their query builders are thenable —
212
- * `resolveMutation`'s `isPromiseLike` check would otherwise win
213
- * before the `.returning()` check is reached.
203
+ * Eagerly call `.returning()` if available: bun-sqlite's query builders are
204
+ * thenable, so `resolveMutation`'s `isPromiseLike` check would otherwise win
205
+ * first and the driver would hand back a RunResult instead of rows.
214
206
  */
215
207
  async function resolveWithReturning(query) {
216
208
  if (query && typeof query === "object" && "returning" in query && typeof query.returning === "function") {
@@ -372,12 +364,7 @@ function applyMutators(data, mutators) {
372
364
  }
373
365
  //#endregion
374
366
  //#region src/GlobalScopeRegistry.ts
375
- /**
376
- * Registry for named global scopes on a model.
377
- *
378
- * Supports adding, removing, and applying multiple named scopes.
379
- * Used internally by Model to manage global query constraints.
380
- */
367
+ /** Registry for the named global scopes applied to every query on a model. */
381
368
  var GlobalScopeRegistry = class GlobalScopeRegistry {
382
369
  scopes = /* @__PURE__ */ new Map();
383
370
  add(name, fn) {
@@ -392,7 +379,6 @@ var GlobalScopeRegistry = class GlobalScopeRegistry {
392
379
  names() {
393
380
  return Array.from(this.scopes.keys());
394
381
  }
395
- /** Apply all scopes (or all except excluded) to a query builder. */
396
382
  apply(builder, except) {
397
383
  for (const [name, fn] of this.scopes) {
398
384
  if (except && except.includes(name)) continue;
@@ -404,12 +390,10 @@ var GlobalScopeRegistry = class GlobalScopeRegistry {
404
390
  this.scopes.clear();
405
391
  }
406
392
  /**
407
- * Copy this registry's entries into a new one.
408
- *
409
- * A subclass that registers its own scope needs a registry of its own, but it
410
- * must keep the ones it inherited: starting from empty is how a model that
411
- * mixes in `SoftDeletes` and then adds a `tenant` scope silently loses the
412
- * `softDelete` filter.
393
+ * A subclass registering its own scope needs a registry of its own, but must
394
+ * keep the inherited entries: starting from empty is how a model that mixes
395
+ * in `SoftDeletes` and then adds a `tenant` scope loses the `softDelete`
396
+ * filter.
413
397
  */
414
398
  clone() {
415
399
  const copy = new GlobalScopeRegistry();
@@ -422,24 +406,14 @@ var GlobalScopeRegistry = class GlobalScopeRegistry {
422
406
  };
423
407
  //#endregion
424
408
  //#region src/hooks.ts
425
- /**
426
- * Execute a model hook if it exists.
427
- *
428
- * @param hooks - The hooks object from the model
429
- * @param name - The hook name to execute
430
- * @param data - The data to pass to the hook
431
- * @returns `false` if the hook explicitly returned false (operation should be aborted), otherwise `true`
432
- */
409
+ /** Runs the hook if present; `false` means the operation should be aborted. */
433
410
  async function executeHook(hooks, name, data) {
434
411
  if (!hooks || typeof hooks[name] !== "function") return true;
435
412
  return await hooks[name](data) !== false;
436
413
  }
437
414
  //#endregion
438
415
  //#region src/ModelObserver.ts
439
- /**
440
- * Execute all registered observers for a given hook.
441
- * Returns false if any observer aborts the operation.
442
- */
416
+ /** Returns false as soon as an observer aborts the operation. */
443
417
  async function executeObservers(observers, name, data) {
444
418
  if (!observers || observers.length === 0) return true;
445
419
  for (const observer of observers) {
@@ -453,10 +427,8 @@ async function executeObservers(observers, name, data) {
453
427
  //#endregion
454
428
  //#region src/ModelNotFoundException.ts
455
429
  /**
456
- * Exception thrown when a model is not found via findOrFail or firstOrFail.
457
- *
458
- * Carries a `statusCode` of 404 so that framework exception handlers
459
- * can render it as a proper HTTP 404 without coupling to the ORM package.
430
+ * Thrown by findOrFail/firstOrFail. Carries `statusCode` 404 so exception
431
+ * handlers can render it without coupling to the ORM package.
460
432
  */
461
433
  var ModelNotFoundException = class extends Error {
462
434
  statusCode = 404;
@@ -472,37 +444,27 @@ var ModelNotFoundException = class extends Error {
472
444
  //#endregion
473
445
  //#region src/QueryBuilder.ts
474
446
  /**
475
- * Key for the prepared-payload update terminal.
476
- *
477
- * Exported for `Model` to call across the module boundary, but deliberately
478
- * absent from the package entry point, so it is not part of the public API.
447
+ * Key for the prepared-payload update terminal. Exported for `Model` across
448
+ * the module boundary, but kept out of the package entry point.
479
449
  */
480
450
  const PREPARED_UPDATE = Symbol("guren.orm.preparedUpdate");
481
451
  /**
482
- * Fluent query builder for the Guren ORM.
483
- *
484
- * Provides a chainable API for constructing database queries with
485
- * support for complex where conditions, ordering, pagination, and more.
486
- *
487
- * Implements the thenable pattern so it can be directly awaited,
488
- * resolving to the result of `get()`.
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
+ /**
457
+ * Fluent query builder for the Guren ORM. Thenable, so awaiting a builder
458
+ * resolves to the result of `get()`.
489
459
  *
490
460
  * @example
491
- * // Fluent chaining
492
- * const posts = await Post.where('status', 'published')
493
- * .where('views', '>', 100)
494
- * .orderBy('createdAt', 'desc')
495
- * .limit(10)
496
- * .get()
497
- *
498
- * // Thenable - await directly
499
461
  * const active = await User.where('active', true)
500
- *
501
- * // Pagination
502
- * const page = await Post.where('status', 'published').paginate(1, 20)
503
462
  */
504
463
  var QueryBuilder = class QueryBuilder {
505
464
  conditions = [];
465
+ scopeConditions = [];
466
+ /** Fold this up wherever a nested builder's conditions are (pushCallbackGroup). */
467
+ droppedUndefinedFilters = false;
506
468
  options = { orderBy: [] };
507
469
  modelClass;
508
470
  table;
@@ -521,7 +483,7 @@ var QueryBuilder = class QueryBuilder {
521
483
  return this;
522
484
  }
523
485
  if (typeof fieldOrConditions === "object" && fieldOrConditions !== null) {
524
- 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));
525
487
  return this;
526
488
  }
527
489
  const field = fieldOrConditions;
@@ -535,14 +497,8 @@ var QueryBuilder = class QueryBuilder {
535
497
  return this;
536
498
  }
537
499
  const orConditions = [];
538
- if (typeof fieldOrConditions === "object" && fieldOrConditions !== null) {
539
- for (const [key, val] of Object.entries(fieldOrConditions)) if (val !== void 0) orConditions.push({
540
- type: "simple",
541
- field: key,
542
- operator: Array.isArray(val) ? "in" : "=",
543
- value: val
544
- });
545
- } else {
500
+ if (typeof fieldOrConditions === "object" && fieldOrConditions !== null) orConditions.push(...this.simpleConditionsFrom(fieldOrConditions));
501
+ else {
546
502
  const field = fieldOrConditions;
547
503
  if (arguments.length === 2) orConditions.push({
548
504
  type: "simple",
@@ -564,45 +520,23 @@ var QueryBuilder = class QueryBuilder {
564
520
  });
565
521
  return this;
566
522
  }
567
- /**
568
- * Add a WHERE NULL condition.
569
- * @param field - Column to check for NULL
570
- */
571
523
  whereNull(field) {
572
524
  this.addSimpleCondition(field, "is null", null);
573
525
  return this;
574
526
  }
575
- /**
576
- * Add a WHERE NOT NULL condition.
577
- * @param field - Column to check for NOT NULL
578
- */
579
527
  whereNotNull(field) {
580
528
  this.addSimpleCondition(field, "is not null", null);
581
529
  return this;
582
530
  }
583
- /**
584
- * Add a WHERE IN condition.
585
- * @param field - Column to check
586
- * @param values - Array of values to match against
587
- */
588
531
  whereIn(field, values) {
589
532
  this.addSimpleCondition(field, "in", values);
590
533
  return this;
591
534
  }
592
- /**
593
- * Add a WHERE NOT IN condition.
594
- * @param field - Column to check
595
- * @param values - Array of values to exclude
596
- */
597
535
  whereNotIn(field, values) {
598
536
  this.addSimpleCondition(field, "not in", values);
599
537
  return this;
600
538
  }
601
- /**
602
- * Add an ORDER BY clause. Can be called multiple times to sort by multiple columns.
603
- * @param field - Column to sort by
604
- * @param direction - Sort direction (default: 'asc')
605
- */
539
+ /** Can be called multiple times to sort by multiple columns. */
606
540
  orderBy(field, direction = "asc") {
607
541
  this.options.orderBy.push({
608
542
  column: field,
@@ -610,42 +544,19 @@ var QueryBuilder = class QueryBuilder {
610
544
  });
611
545
  return this;
612
546
  }
613
- /**
614
- * Set the maximum number of records to return.
615
- * @param n - Maximum record count
616
- */
617
547
  limit(n) {
618
548
  this.options.limitValue = n;
619
549
  return this;
620
550
  }
621
- /**
622
- * Set the number of records to skip.
623
- * @param n - Number of records to skip
624
- */
625
551
  offset(n) {
626
552
  this.options.offsetValue = n;
627
553
  return this;
628
554
  }
629
- /**
630
- * Limit the columns returned in the result.
631
- * @param fields - Column names to select
632
- */
633
555
  select(...fields) {
634
556
  this.options.selectFields = [...fields];
635
557
  return this;
636
558
  }
637
- /**
638
- * Apply a named query scope defined on the model.
639
- *
640
- * @param name - The scope name
641
- * @returns this (for chaining)
642
- *
643
- * @example
644
- * const results = await Post.where('author', 'John')
645
- * .scope('published')
646
- * .scope('popular')
647
- * .get()
648
- */
559
+ /** Apply a named query scope defined on the model. */
649
560
  scope(name) {
650
561
  const modelScopes = this.modelClass.scopes;
651
562
  if (!modelScopes || typeof modelScopes[name] !== "function") throw new Error(`${this.modelClass.name}: unknown scope "${name}".`);
@@ -653,42 +564,11 @@ var QueryBuilder = class QueryBuilder {
653
564
  return this;
654
565
  }
655
566
  /**
656
- * Eager-load relationships on query results.
657
- *
658
- * Supports string names, arrays, dot notation for nested relations,
659
- * and constraint callbacks.
660
- *
661
- * A constraint callback receives the query builder used to fetch that
662
- * relation, and runs after the foreign-key filter is already on it, so a
663
- * `where()` narrows that filter. Each object key constrains exactly the
664
- * level it names, in any order: `posts` constrains the head,
665
- * `posts.comments` constrains the leaf and leaves `posts` unfiltered.
666
- *
667
- * Three things behave differently than they may look:
668
- * - `orWhere()` at the top level of a callback *widens* the query rather
669
- * than narrowing it, because it ORs against the foreign-key filter. Group
670
- * it (`q.where((g) => g.where(...).orWhere(...))`) to keep it contained.
671
- * - `select()` must include the column the relation is keyed on, or the
672
- * loader cannot match rows back to their parent and the relation is empty.
673
- * - `limit()` applies to the single batched query, not per parent record.
674
- *
675
- * @example
676
- * // Simple
677
- * await User.where('active', true).with('posts').get()
678
- *
679
- * // Multiple
680
- * await User.where('active', true).with('posts', 'comments').get()
681
- *
682
- * // Nested (dot notation)
683
- * await User.where('active', true).with('posts.comments').get()
684
- *
685
- * // Constrained
686
- * await User.newQuery().with({ posts: (q) => q.where('published', true) }).get()
687
- *
688
- * // Constrained at both levels
689
- * await User.newQuery()
690
- * .with({ posts: (q) => q.where('published', true), 'posts.comments': (q) => q.orderBy('id') })
691
- * .get()
567
+ * Eager-load relationships by name, dot path, or an object of constraint
568
+ * callbacks, each run after the foreign-key filter on exactly the level its key
569
+ * names. Pitfalls: a top-level `orWhere()` ORs against the foreign-key filter
570
+ * (group it); `select()` must keep the relation's key column or the relation is
571
+ * empty; `limit()` applies to the one batched query, not per parent record.
692
572
  */
693
573
  with(...relations) {
694
574
  for (const rel of relations) if (typeof rel === "string") {
@@ -699,19 +579,12 @@ var QueryBuilder = class QueryBuilder {
699
579
  }
700
580
  return this;
701
581
  }
702
- /**
703
- * Execute the query and return all matching records.
704
- * @returns Array of matching records
705
- */
706
582
  async get() {
707
583
  const results = await this.executeQuery();
708
584
  return this.loadEagerRelations(results);
709
585
  }
710
- /**
711
- * Execute the query and return the first matching record.
712
- * @returns The first record or null
713
- */
714
586
  async first() {
587
+ if (this.filtersEvaporated()) return null;
715
588
  const prev = this.options.limitValue;
716
589
  this.options.limitValue = 1;
717
590
  try {
@@ -720,24 +593,16 @@ var QueryBuilder = class QueryBuilder {
720
593
  this.options.limitValue = prev;
721
594
  }
722
595
  }
723
- /**
724
- * Execute the query and return the first matching record, or throw.
725
- * @returns The first record
726
- * @throws ModelNotFoundException (404) if no record matches
727
- */
596
+ /** @throws ModelNotFoundException (404) if no record matches. */
728
597
  async firstOrFail() {
729
598
  const record = await this.first();
730
599
  if (record === null) throw new ModelNotFoundException(this.modelClass.name);
731
600
  return record;
732
601
  }
733
- /**
734
- * Count the number of records matching the current conditions.
735
- * @returns The count of matching records
736
- */
737
602
  async count() {
738
- 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 });
739
604
  const advancedAdapter = this.adapter;
740
- 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 });
741
606
  return (await this.executeQuery()).length;
742
607
  }
743
608
  async paginate(pageOrOptions = 1, perPageArg = 15) {
@@ -776,25 +641,16 @@ var QueryBuilder = class QueryBuilder {
776
641
  };
777
642
  }
778
643
  /**
779
- * Bulk update records matching the current conditions.
780
- *
781
- * Mass-assignment protection applies exactly as in `Model.update()`:
782
- * with a `fillable` allowlist, out-of-allowlist keys throw a
783
- * MassAssignmentException. The payload also runs through the same
784
- * persistence preparation as `Model.update()` — mutators, casts, and
785
- * `preparePersistencePayload` overrides (e.g. password hashing on
786
- * authenticatable models). Per-record hooks and observers are still
787
- * skipped by design.
788
- *
789
- * @param data - Data to set on matching records
790
- * @returns The updated record (adapter-dependent)
644
+ * Bulk update. Mass-assignment protection and persistence preparation
645
+ * (mutators, casts, `preparePersistencePayload`) apply exactly as in
646
+ * `Model.update()`; per-record hooks and observers are skipped by design.
791
647
  */
792
648
  async update(data) {
793
649
  return this.runBulkUpdate(data, true);
794
650
  }
795
651
  /**
796
- * Bulk update bypassing mass-assignment protection. Use for trusted,
797
- * server-side-assembled data — never for raw request input.
652
+ * Bulk update bypassing mass-assignment protection. Trusted server-side data
653
+ * only, never raw request input.
798
654
  */
799
655
  async forceUpdate(data) {
800
656
  return this.runBulkUpdate(data, false);
@@ -806,79 +662,106 @@ var QueryBuilder = class QueryBuilder {
806
662
  return this[PREPARED_UPDATE](payload);
807
663
  }
808
664
  /**
809
- * Bulk update using a payload the caller has already run through
810
- * mass-assignment filtering and persistence preparation. This exists so the
811
- * static `Model.update()` write path can borrow the builder's
812
- * global-scope-carrying `conditions` without re-preparing the payload —
813
- * running mutators twice would, for example, double-hash a hashed column.
814
- *
815
- * Keyed by a symbol that this package never re-exports, because a named
816
- * public method here would be a supported way to write arbitrary columns:
817
- * it skips both `filterFillable` and `prepareBulkPersistencePayload`, so
818
- * `User.where(…)[name](requestBody)` would bypass mass-assignment protection
819
- * entirely. `@internal` is only a doc tag — declarations still emit it.
665
+ * Bulk update with an already-filtered, already-prepared payload, so
666
+ * `Model.update()` can borrow the builder's global-scope-carrying
667
+ * `conditions` without running mutators twice (double-hashing a hashed
668
+ * column). Symbol-keyed and never re-exported: a named public method here
669
+ * would be a supported way to bypass mass-assignment protection entirely.
820
670
  */
821
671
  async [PREPARED_UPDATE](payload) {
822
672
  if (!this.adapter.update) throw new Error("Configured adapter does not support update operations.");
673
+ this.assertFiltersSurvived("update");
823
674
  const advancedAdapter = this.adapter;
824
- 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 });
825
676
  const simpleWhere = this.toSimpleWhereClause();
826
677
  if (simpleWhere) return this.adapter.update(this.table, simpleWhere, payload, { trx: this.options.trx });
827
678
  throw new Error("Advanced conditions require an adapter that supports updateAdvanced.");
828
679
  }
829
- /**
830
- * Bulk delete records matching the current conditions.
831
- * @returns Number of deleted records (adapter-dependent)
832
- */
833
680
  async delete() {
834
681
  if (!this.adapter.delete) throw new Error("Configured adapter does not support delete operations.");
682
+ this.assertFiltersSurvived("delete");
835
683
  const advancedAdapter = this.adapter;
836
- 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 });
837
685
  const simpleWhere = this.toSimpleWhereClause();
838
686
  if (simpleWhere) return this.adapter.delete(this.table, simpleWhere, { trx: this.options.trx });
839
687
  throw new Error("Advanced conditions require an adapter that supports deleteAdvanced.");
840
688
  }
841
- /**
842
- * Makes QueryBuilder a thenable so it can be directly awaited.
843
- * Resolves to the result of `get()`.
844
- */
689
+ /** Makes the builder awaitable, resolving to `get()`. */
845
690
  then(onfulfilled, onrejected) {
846
691
  return this.get().then(onfulfilled, onrejected);
847
692
  }
848
- /**
849
- * Catch handler for the thenable interface.
850
- */
851
693
  catch(onrejected) {
852
694
  return this.get().catch(onrejected);
853
695
  }
854
- /** Get the internal conditions (used by adapters). */
855
696
  getConditions() {
856
- 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;
857
710
  }
858
- /** Get the internal query options (used by adapters). */
859
711
  getOptions() {
860
712
  return { ...this.options };
861
713
  }
862
714
  /**
863
- * Run a grouping callback against a nested builder, fold the collected
864
- * conditions into a single node, and push it joined by `boolean`.
865
- *
866
- * The nested builder intentionally skips global scopes (`defaultScope`,
867
- * SoftDeletes): the outer builder already carries them, and re-applying
868
- * them inside every group would duplicate — or, inside an OR group,
869
- * weaken — their filters.
715
+ * The nested builder skips global scopes on purpose: the outer builder
716
+ * already carries them, and re-applying them inside every group would
717
+ * duplicate — or, inside an OR group, weaken — their filters.
870
718
  */
871
719
  pushCallbackGroup(callback, boolean) {
872
720
  const nested = new QueryBuilder(this.modelClass, { trx: this.options.trx });
873
721
  callback(nested);
874
- const grouped = normalizeConditionSequence(nested.conditions);
875
- if (!grouped) return;
876
- const needsWrap = boolean === "or" || grouped.type === "group" && grouped.boolean === "or";
877
- this.conditions.push(needsWrap ? {
878
- type: "group",
879
- boolean,
880
- conditions: [grouped]
881
- } : 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.`);
882
765
  }
883
766
  addSimpleCondition(field, operator, value) {
884
767
  this.conditions.push({
@@ -890,14 +773,14 @@ var QueryBuilder = class QueryBuilder {
890
773
  }
891
774
  async executeQuery() {
892
775
  const advancedAdapter = this.adapter;
893
- 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(), {
894
777
  orderBy: this.options.orderBy.length > 0 ? this.options.orderBy : void 0,
895
778
  limit: this.options.limitValue,
896
779
  offset: this.options.offsetValue,
897
780
  select: this.options.selectFields
898
781
  }, { trx: this.options.trx });
899
782
  const simpleWhere = this.toSimpleWhereClause();
900
- 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.`);
901
784
  return this.adapter.findMany(this.table, {
902
785
  where: simpleWhere ?? void 0,
903
786
  orderBy: this.options.orderBy.length > 0 ? this.options.orderBy : void 0,
@@ -905,15 +788,12 @@ var QueryBuilder = class QueryBuilder {
905
788
  offset: this.options.offsetValue
906
789
  }, { trx: this.options.trx });
907
790
  }
908
- /**
909
- * Attempt to convert the current conditions to a simple WhereClause
910
- * for backward compatibility with basic adapters.
911
- * Returns null if conditions are too complex.
912
- */
791
+ /** Null when the conditions are too complex for a basic adapter's WhereClause. */
913
792
  toSimpleWhereClause() {
914
- if (this.conditions.length === 0) return null;
793
+ const conditions = this.allConditions();
794
+ if (conditions.length === 0) return null;
915
795
  const result = {};
916
- for (const condition of this.conditions) {
796
+ for (const condition of conditions) {
917
797
  if (condition.type !== "simple") return null;
918
798
  let value;
919
799
  if (condition.operator === "=" || condition.operator === "in") value = condition.value;
@@ -925,17 +805,10 @@ var QueryBuilder = class QueryBuilder {
925
805
  return result;
926
806
  }
927
807
  /**
928
- * Load eager relations onto fetched results.
929
- * Supports dot notation for nested relations at any depth
930
- * (e.g., 'posts.comments.author') — the paths are delegated to
931
- * Model.loadRelationsInto, which recurses through the relation chain.
932
- * Constraint callbacks registered by the object form of `with()` travel
933
- * alongside, keyed by the path segment each one constrains.
934
- *
935
- * The builder's `trx` goes with it: a relation loaded for rows read inside
936
- * a transaction has to be read on that same handle, or the parents come
937
- * from the transaction and their children from the pool — which on
938
- * Postgres/MySQL means uncommitted parents get a null relation back.
808
+ * Paths are delegated to Model.loadRelationsInto, which recurses the
809
+ * relation chain. The builder's `trx` goes with them: a relation read off
810
+ * the pool while its parents came from an open transaction gets a null
811
+ * relation back on Postgres/MySQL, the parents being uncommitted.
939
812
  */
940
813
  loadEagerRelations = async (results) => {
941
814
  if (this.eagerLoad.length === 0 || results.length === 0) return results;
@@ -946,11 +819,7 @@ var QueryBuilder = class QueryBuilder {
946
819
  };
947
820
  //#endregion
948
821
  //#region src/serialization.ts
949
- /**
950
- * Serialize a model record for API/JSON output.
951
- *
952
- * Applies hidden/visible filtering, casts, accessors, and appends.
953
- */
822
+ /** Serializes a record for JSON output: appends, then visible/hidden filtering. */
954
823
  function serializeRecord(record, options) {
955
824
  let result = { ...record };
956
825
  if (options.appends && options.accessors) {
@@ -970,16 +839,10 @@ function serializeRecords(records, options) {
970
839
  //#endregion
971
840
  //#region src/MassAssignmentException.ts
972
841
  /**
973
- * Thrown when mass assignment receives fields it must not write. Silently
974
- * discarding them hides bugs (a typo'd fillable entry surfaces as a NOT NULL
975
- * violation much later) and can mask injection attempts, so models fail
976
- * loudly instead.
977
- *
978
- * `reason` distinguishes the two rules that throw:
979
- * - `'not-fillable'` — the field is outside the model's `fillable` allowlist.
980
- * - `'denied'` — the field is in the model's `deniedFields()` (e.g. a
981
- * credential column on an authenticatable model) and can never be
982
- * mass-assigned, `fillable` notwithstanding.
842
+ * Thrown when mass assignment receives fields it must not write. Discarding
843
+ * them silently hides bugs and can mask injection attempts, so models throw.
844
+ * `reason` is `'not-fillable'` (outside the `fillable` allowlist) or
845
+ * `'denied'` (in `deniedFields()`, unassignable whatever `fillable` says).
983
846
  */
984
847
  var MassAssignmentException = class extends Error {
985
848
  model;
@@ -997,217 +860,77 @@ var MassAssignmentException = class extends Error {
997
860
  }
998
861
  };
999
862
  /**
1000
- * ActiveRecord-style base class for database models.
1001
- *
1002
- * Provides a Laravel Eloquent-like API for database operations including
1003
- * CRUD, querying, pagination, and eager-loading of relationships.
1004
- *
1005
- * @example
1006
- * // Define a model — recordType/createType are inferred from the Drizzle table
1007
- * class User extends defineModel(users) {}
1008
- *
1009
- * // Or, when extending Model directly, redeclare the type markers
1010
- * class LegacyUser extends Model<UserRecord> {
1011
- * static override table = users // Drizzle table
1012
- * declare static readonly recordType: UserRecord
1013
- * declare static readonly createType: NewUserRecord
1014
- * }
1015
- *
1016
- * // Query records
1017
- * const allUsers = await User.all()
1018
- * const user = await User.find(1)
1019
- * const activeUsers = await User.where({ status: 'active' })
1020
- *
1021
- * // Create and update
1022
- * const newUser = await User.create({ name: 'John', email: 'john@example.com' })
1023
- * await User.update({ id: 1 }, { name: 'Jane' })
1024
- *
1025
- * // Pagination
1026
- * const page = await User.paginate({ page: 1, perPage: 10 })
1027
- *
1028
- * // Relationships
1029
- * const usersWithPosts = await User.with('posts')
863
+ * ActiveRecord-style base class for database models. Prefer `defineModel(table)`,
864
+ * which infers the type markers; extending `Model` directly means setting
865
+ * `static table` and redeclaring `recordType`/`createType` by hand.
1030
866
  */
1031
867
  var Model = class Model {
1032
- /** The ORM adapter used for database operations. */
1033
868
  static ormAdapter = DrizzleAdapter;
1034
- /** The database table (e.g., Drizzle table schema). */
1035
869
  static table;
1036
870
  /** Type marker for TypeScript inference. Set by `defineModel()`; when extending `Model` directly, redeclare as `declare static readonly recordType: YourRecordType`. */
1037
871
  static recordType = void 0;
1038
872
  /** Type marker for insert/update payload inference. Set by `defineModel()`; when extending `Model` directly, redeclare as `declare static readonly createType: YourCreateType`. */
1039
873
  static createType = void 0;
1040
874
  static relationDefinitions;
1041
- /** Type marker for relation types. Define relation types here for type inference. */
1042
875
  static relationTypes = {};
1043
876
  /**
1044
- * Named query scopes for reusable query constraints.
1045
- *
1046
- * @example
1047
- * class Post extends Model<PostRecord> {
1048
- * static scopes = {
1049
- * published: (q: QueryBuilder<PostRecord>) => q.where('status', 'published'),
1050
- * popular: (q: QueryBuilder<PostRecord>) => q.where('views', '>', 1000),
1051
- * }
1052
- * }
1053
- * // Usage: Post.scope('published').scope('popular').get()
877
+ * Reusable query constraints, applied by name with
878
+ * `Post.scope('published').scope('popular')`.
1054
879
  */
1055
880
  static scopes;
1056
881
  /**
1057
- * Default scope applied to all queries on this model.
1058
- * Override this to automatically filter queries (e.g., soft deletes).
1059
- *
1060
- * @example
1061
- * static defaultScope = (q: QueryBuilder<any>) => q.whereNull('deletedAt')
882
+ * Applied to every query on this model, and — unlike a named global scope —
883
+ * never removable with `withoutGlobalScope()`.
1062
884
  */
1063
885
  static defaultScope;
1064
- /**
1065
- * Model lifecycle hooks that fire during create, update, and delete operations.
1066
- *
1067
- * @example
1068
- * class User extends Model<UserRecord> {
1069
- * static hooks: ModelHooks = {
1070
- * creating: async (data) => { data.password = await hash(data.password as string) },
1071
- * created: async (data) => { console.log('User created:', data) },
1072
- * }
1073
- * }
1074
- */
886
+ /** Lifecycle hooks firing around create, update and delete. */
1075
887
  static hooks;
1076
- /**
1077
- * Attribute casting definitions for automatic type conversion.
1078
- *
1079
- * Casts are applied when reading records from the database and when
1080
- * writing records to the database.
1081
- *
1082
- * @example
1083
- * class Post extends Model<PostRecord> {
1084
- * static casts = {
1085
- * metadata: 'json',
1086
- * publishedAt: 'date',
1087
- * isActive: 'boolean',
1088
- * viewCount: 'number',
1089
- * }
1090
- * }
1091
- */
888
+ /** Attribute casts, applied both on read and on write. */
1092
889
  static casts;
1093
890
  /**
1094
- * Whitelist of fields allowed for mass assignment.
1095
- * If set, `create()` and `update()` accept only these fields — input
1096
- * containing any other key throws a MassAssignmentException so bugs
1097
- * (and injection attempts) surface immediately instead of being
1098
- * silently discarded. Use `forceCreate()` / `forceUpdate()` for
1099
- * trusted server-side data.
1100
- *
1101
- * The primary key (`id`) is always silently stripped from mass-assignment
1102
- * input, and fields returned by `deniedFields()` always throw — neither
1103
- * depends on `fillable`.
1104
- *
1105
- * @example
1106
- * class User extends Model<UserRecord> {
1107
- * static fillable = ['name', 'email', 'password']
1108
- * }
891
+ * Mass-assignment allowlist. When set, any other key in `create()`/`update()`
892
+ * input throws a MassAssignmentException rather than being discarded, so
893
+ * bugs and injection attempts surface; `forceCreate()`/`forceUpdate()` are
894
+ * the trusted-data escape. Independent of it, `id` is always stripped and
895
+ * `deniedFields()` always throws.
1109
896
  */
1110
897
  static fillable;
1111
898
  /**
1112
- * Fields that can never be mass-assigned, resolved at call time so
1113
- * subclasses can derive them from their own configuration (e.g.
1114
- * `AuthenticatableModel` contributes its resolved password-hash and
1115
- * remember-token columns). Input containing any of these throws a
1116
- * MassAssignmentException regardless of `fillable` — use
1117
- * `forceCreate()` / `forceUpdate()` for trusted server-side values.
899
+ * Fields that can never be mass-assigned, whatever `fillable` says. Resolved
900
+ * at call time so a subclass can derive them from its own configuration
901
+ * (`AuthenticatableModel` contributes its password-hash column).
1118
902
  */
1119
903
  static deniedFields() {
1120
904
  return [];
1121
905
  }
1122
- /**
1123
- * Accessor functions for computed/virtual attributes.
1124
- * Applied after reading records from the database.
1125
- *
1126
- * @example
1127
- * class User extends Model<UserRecord> {
1128
- * static accessors = {
1129
- * fullName: (record) => `${record.firstName} ${record.lastName}`,
1130
- * }
1131
- * }
1132
- */
906
+ /** Computed attributes, applied after a record is read. */
1133
907
  static accessors;
1134
- /**
1135
- * Mutator functions for transforming attributes before persistence.
1136
- *
1137
- * @example
1138
- * class User extends Model<UserRecord> {
1139
- * static mutators = {
1140
- * email: (value) => String(value).toLowerCase(),
1141
- * }
1142
- * }
1143
- */
908
+ /** Attribute transforms applied before persistence. */
1144
909
  static mutators;
1145
- /**
1146
- * Fields to exclude from serialization output.
1147
- *
1148
- * @example
1149
- * class User extends Model<UserRecord> {
1150
- * static hidden = ['passwordHash', 'rememberToken']
1151
- * }
1152
- */
910
+ /** Fields to exclude from serialization output. */
1153
911
  static hidden;
1154
- /**
1155
- * Whitelist of fields to include in serialization output.
1156
- * When set, only these fields appear. Takes precedence over `hidden`.
1157
- */
912
+ /** Serialization allowlist; takes precedence over `hidden`. */
1158
913
  static visible;
1159
- /**
1160
- * Virtual accessor attributes to include in serialization output.
1161
- *
1162
- * @example
1163
- * class User extends Model<UserRecord> {
1164
- * static appends = ['fullName']
1165
- * static accessors = { fullName: (r) => `${r.firstName} ${r.lastName}` }
1166
- * }
1167
- */
914
+ /** Accessor names to add to serialization output. */
1168
915
  static appends;
1169
- /** Registered model observers. */
1170
916
  static observers;
1171
- /** Named global scopes registry. */
1172
917
  static globalScopeRegistry;
1173
- /**
1174
- * Set a custom ORM adapter for this model.
1175
- * @param adapter - The adapter to use
1176
- */
1177
918
  static useAdapter(adapter) {
1178
919
  this.ormAdapter = adapter;
1179
920
  }
1180
- /**
1181
- * Get the current ORM adapter.
1182
- * @returns The configured adapter
1183
- */
1184
921
  static getAdapter() {
1185
922
  return this.ormAdapter;
1186
923
  }
1187
924
  /**
1188
- * Run operations inside a database transaction.
1189
- *
1190
925
  * @example
1191
- * await User.transaction(async (trx) => {
1192
- * const user = await User.create({ name: 'John' }, { trx })
1193
- * await Profile.create({ userId: user.id }, { trx })
1194
- * })
926
+ * await User.transaction(async (trx) => User.create({ name: 'John' }, { trx }))
1195
927
  */
1196
928
  static async transaction(callback) {
1197
929
  const adapter = this.getAdapter();
1198
930
  if (typeof adapter.transaction !== "function") throw new Error("Configured adapter does not support transactions.");
1199
931
  return adapter.transaction((trx) => callback(trx, this.inTransaction(trx)));
1200
932
  }
1201
- /**
1202
- * Create a transaction-bound model scope that automatically forwards `trx`
1203
- * to query and write operations.
1204
- *
1205
- * @example
1206
- * await User.transaction(async (trx, txUser) => {
1207
- * await txUser.create({ name: 'Shinji' })
1208
- * await txUser.update({ id: 1 }, { name: 'Ikari' })
1209
- * })
1210
- */
933
+ /** A model scope that forwards `trx` to every query and write on it. */
1211
934
  static inTransaction(trx) {
1212
935
  const where = (fieldOrConditions, operatorOrValue, value) => {
1213
936
  if (typeof fieldOrConditions === "function") return this.newQuery({ trx }).where(fieldOrConditions);
@@ -1229,35 +952,19 @@ var Model = class Model {
1229
952
  paginate: (options) => this.paginate(options, { trx })
1230
953
  };
1231
954
  }
1232
- /**
1233
- * Register a model observer class.
1234
- *
1235
- * @example
1236
- * User.observe(UserObserver)
1237
- */
1238
955
  static observe(ObserverClass) {
1239
956
  if (!Object.prototype.hasOwnProperty.call(this, "observers") || !this.observers) this.observers = [];
1240
957
  this.observers.push(new ObserverClass());
1241
958
  }
1242
- /** Clear all registered observers. */
1243
959
  static clearObservers() {
1244
960
  this.observers = [];
1245
961
  }
1246
962
  /**
1247
- * The registry this class may mutate, creating it on first write.
1248
- *
1249
- * The new registry is seeded from the inherited one: the read paths
1250
- * (`newQuery()`, `hasScopes()`) resolve `globalScopeRegistry` through the
1251
- * prototype chain, so a subclass that started from an empty registry would
1252
- * shadow — and silently drop — every scope it inherited. That is exactly the
1253
- * `class Post extends SoftDeletes(Base)` then `Post.addGlobalScope('tenant')`
1254
- * case, which would otherwise lose the `softDelete` filter.
1255
- *
1256
- * The copy is a snapshot: scopes added to the parent *after* a subclass first
1257
- * registers or removes one do not reach that subclass. Nothing in the
1258
- * framework relies on later propagation — the `SoftDeletes` mixin registers
1259
- * `softDelete` synchronously while building the class, before any user code
1260
- * can touch it.
963
+ * The registry this class may mutate, created on first write and seeded from
964
+ * the inherited one: the read paths resolve it through the prototype chain,
965
+ * so starting empty would shadow and drop every inherited scope (SoftDeletes
966
+ * then `addGlobalScope('tenant')`). The copy is a snapshot — scopes added to
967
+ * the parent afterwards never reach the subclass.
1261
968
  */
1262
969
  static getGlobalScopes() {
1263
970
  if (!Object.prototype.hasOwnProperty.call(this, "globalScopeRegistry") || !this.globalScopeRegistry) {
@@ -1266,53 +973,31 @@ var Model = class Model {
1266
973
  }
1267
974
  return this.globalScopeRegistry;
1268
975
  }
1269
- /**
1270
- * Register a named global scope.
1271
- *
1272
- * @example
1273
- * User.addGlobalScope('active', (q) => q.where('active', true))
1274
- */
1275
976
  static addGlobalScope(name, fn) {
1276
977
  this.getGlobalScopes().add(name, fn);
1277
978
  }
1278
- /** Remove a named global scope. */
1279
979
  static removeGlobalScope(name) {
1280
980
  this.getGlobalScopes().remove(name);
1281
981
  }
1282
- /**
1283
- * Start a query excluding specific global scope(s).
1284
- *
1285
- * Only *named* scopes can be excluded: `defaultScope` is re-applied here
1286
- * whatever this is asked to drop. A mixin whose filter users must be able to
1287
- * opt out of therefore has to register a named scope and nothing else —
1288
- * registering as both makes the filter unremovable, which is how `SoftDeletes`
1289
- * once made `withoutGlobalScope('softDelete')` a no-op.
1290
- *
1291
- * @example
1292
- * const all = await User.withoutGlobalScope('active').get()
1293
- */
1294
- static withoutGlobalScope(...names) {
1295
- const builder = new QueryBuilder(this);
1296
- if (this.defaultScope) this.defaultScope(builder);
1297
- this.getGlobalScopes().apply(builder, names);
1298
- 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);
1299
986
  }
1300
- /**
1301
- * Start a query with no global scopes applied (also skips defaultScope).
1302
- *
1303
- * @example
1304
- * const all = await User.withoutGlobalScopes().get()
1305
- */
1306
- static withoutGlobalScopes() {
1307
- return new QueryBuilder(this);
987
+ /** A query with no global scopes applied, `defaultScope` included. */
988
+ static withoutGlobalScopes(queryOptions) {
989
+ return new QueryBuilder(this, queryOptions);
1308
990
  }
1309
991
  /**
1310
- * Serialize a record for API/JSON output.
1311
- * Applies hidden/visible filtering, accessors, and appends.
1312
- *
1313
- * @example
1314
- * const json = User.serialize(user)
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.
1315
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.`);
999
+ }
1000
+ /** Applies hidden/visible filtering, accessors and appends. */
1316
1001
  static serialize(record) {
1317
1002
  return serializeRecord(record, {
1318
1003
  hidden: this.hidden,
@@ -1321,12 +1006,6 @@ var Model = class Model {
1321
1006
  accessors: this.accessors
1322
1007
  });
1323
1008
  }
1324
- /**
1325
- * Serialize an array of records.
1326
- *
1327
- * @example
1328
- * const json = User.serializeMany(users)
1329
- */
1330
1009
  static serializeMany(records) {
1331
1010
  return serializeRecords(records, {
1332
1011
  hidden: this.hidden,
@@ -1335,12 +1014,6 @@ var Model = class Model {
1335
1014
  accessors: this.accessors
1336
1015
  });
1337
1016
  }
1338
- /**
1339
- * Apply attribute casts to a record read from the database.
1340
- *
1341
- * @param record - The raw record from the database
1342
- * @returns The record with cast attributes applied
1343
- */
1344
1017
  static applyCasts(record) {
1345
1018
  const castDefs = this.casts;
1346
1019
  if (!castDefs) return record;
@@ -1370,10 +1043,7 @@ var Model = class Model {
1370
1043
  }
1371
1044
  return result;
1372
1045
  }
1373
- /**
1374
- * Apply all read-time transforms: casts then accessors.
1375
- * Used internally after fetching records from the database.
1376
- */
1046
+ /** Read-time transforms, in order: casts then accessors. */
1377
1047
  static applyReadTransforms(record) {
1378
1048
  let result = record;
1379
1049
  if (this.casts) result = this.applyCasts(result);
@@ -1381,16 +1051,9 @@ var Model = class Model {
1381
1051
  return result;
1382
1052
  }
1383
1053
  /**
1384
- * Filter input data based on mass assignment protection rules.
1385
- *
1386
- * Applied in order: fields returned by `deniedFields()` throw a
1387
- * MassAssignmentException (checked on the raw input, so no other rule
1388
- * can silently swallow them); the primary key (`id`) is silently
1389
- * stripped; when `fillable` is defined, any remaining field outside it
1390
- * throws and only listed fields are kept.
1391
- *
1392
- * @param data - The input data to filter
1393
- * @returns Filtered data safe for mass assignment
1054
+ * In order: `deniedFields()` throws, checked on the raw input so no later
1055
+ * rule can swallow them; `id` is stripped silently; then, with `fillable`
1056
+ * set, anything outside it throws.
1394
1057
  */
1395
1058
  static filterFillable(data) {
1396
1059
  const denied = this.deniedFields().filter((field) => field in data);
@@ -1450,14 +1113,6 @@ var Model = class Model {
1450
1113
  if (!this.table) throw new Error(`${this.name}.table must be defined before using the model.`);
1451
1114
  return this.table;
1452
1115
  }
1453
- /**
1454
- * Retrieve all records from the table.
1455
- *
1456
- * @returns Array of all records
1457
- *
1458
- * @example
1459
- * const users = await User.all()
1460
- */
1461
1116
  static async all(queryOptions) {
1462
1117
  if (this.hasScopes()) return this.newQuery(queryOptions).get();
1463
1118
  const table = this.resolveTable();
@@ -1465,18 +1120,8 @@ var Model = class Model {
1465
1120
  if (this.casts || this.accessors) return records.map((r) => this.applyReadTransforms(r));
1466
1121
  return records;
1467
1122
  }
1468
- /**
1469
- * Find a record by its primary key.
1470
- *
1471
- * @param id - The primary key value
1472
- * @param key - The primary key column name (default: 'id')
1473
- * @returns The record or null if not found
1474
- *
1475
- * @example
1476
- * const user = await User.find(1)
1477
- * const userByEmail = await User.find('john@example.com', 'email')
1478
- */
1479
1123
  static async find(id, key = "id", queryOptions) {
1124
+ if (id === void 0) return null;
1480
1125
  if (this.hasScopes()) return this.newQuery(queryOptions).where(key, id).first();
1481
1126
  const table = this.resolveTable();
1482
1127
  const where = { [key]: id };
@@ -1484,17 +1129,7 @@ var Model = class Model {
1484
1129
  if (record && (this.casts || this.accessors)) return this.applyReadTransforms(record);
1485
1130
  return record;
1486
1131
  }
1487
- /**
1488
- * Find a record by primary key or throw an error.
1489
- *
1490
- * @param id - The primary key value
1491
- * @param key - The primary key column name (default: 'id')
1492
- * @returns The record
1493
- * @throws Error if record not found
1494
- *
1495
- * @example
1496
- * const user = await User.findOrFail(1) // Throws if not found
1497
- */
1132
+ /** @throws ModelNotFoundException (404) when no record matches. */
1498
1133
  static async findOrFail(id, key = "id", queryOptions) {
1499
1134
  const record = await this.find(id, key, queryOptions);
1500
1135
  if (record == null) throw new ModelNotFoundException(this.name, id, key);
@@ -1517,16 +1152,8 @@ var Model = class Model {
1517
1152
  await this.loadRelationsInto([copy], relationList, queryOptions);
1518
1153
  return copy;
1519
1154
  }
1520
- /**
1521
- * Get the first record matching the conditions.
1522
- *
1523
- * @param where - Optional filter conditions
1524
- * @returns The first matching record or null
1525
- *
1526
- * @example
1527
- * const admin = await User.first({ role: 'admin' })
1528
- */
1529
1155
  static async first(where, queryOptions) {
1156
+ if (everyFilterDropped(where)) return null;
1530
1157
  if (this.hasScopes()) {
1531
1158
  const builder = this.newQuery(queryOptions).limit(1);
1532
1159
  if (where) builder.where(where);
@@ -1547,94 +1174,49 @@ var Model = class Model {
1547
1174
  if (arguments.length === 3) return builder.where(fieldOrConditions, operatorOrValue, value);
1548
1175
  return builder.where(fieldOrConditions, operatorOrValue);
1549
1176
  }
1550
- /**
1551
- * Start a fluent query with a WHERE NULL condition.
1552
- * @param field - Column to check for NULL
1553
- */
1554
1177
  static whereNull(field) {
1555
1178
  return this.newQuery().whereNull(field);
1556
1179
  }
1557
- /**
1558
- * Start a fluent query with a WHERE NOT NULL condition.
1559
- * @param field - Column to check for NOT NULL
1560
- */
1561
1180
  static whereNotNull(field) {
1562
1181
  return this.newQuery().whereNotNull(field);
1563
1182
  }
1564
- /**
1565
- * Start a fluent query with a WHERE IN condition.
1566
- * @param field - Column to check
1567
- * @param values - Array of values to match against
1568
- */
1569
1183
  static whereIn(field, values) {
1570
1184
  return this.newQuery().whereIn(field, values);
1571
1185
  }
1572
- /**
1573
- * Start a fluent query with a WHERE NOT IN condition.
1574
- * @param field - Column to check
1575
- * @param values - Array of values to exclude
1576
- */
1577
1186
  static whereNotIn(field, values) {
1578
1187
  return this.newQuery().whereNotIn(field, values);
1579
1188
  }
1580
- /**
1581
- * Start a fluent query with a typed field selection.
1582
- *
1583
- * @example
1584
- * const rows = await User.select('id', 'name')
1585
- * const first = await User.select('id').first()
1586
- */
1587
1189
  static select(...fields) {
1588
1190
  return this.newQuery().select(...fields);
1589
1191
  }
1192
+ static newQuery(queryOptions) {
1193
+ return this.buildScopedQuery(queryOptions);
1194
+ }
1590
1195
  /**
1591
- * Start a new QueryBuilder for fluent query construction.
1592
- *
1593
- * @returns A fresh QueryBuilder instance
1594
- *
1595
- * @example
1596
- * const results = await User.newQuery()
1597
- * .where('status', 'active')
1598
- * .orderBy('name')
1599
- * .limit(10)
1600
- * .get()
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.
1601
1199
  */
1602
- static newQuery(queryOptions) {
1200
+ static buildScopedQuery(queryOptions, except) {
1603
1201
  const builder = new QueryBuilder(this, queryOptions);
1604
1202
  if (this.defaultScope) this.defaultScope(builder);
1605
1203
  const registry = this.globalScopeRegistry;
1606
- if (registry && registry.size > 0) registry.apply(builder);
1607
- return builder;
1204
+ if (registry && registry.size > 0) registry.apply(builder, except);
1205
+ return builder[SEAL_SCOPES]();
1608
1206
  }
1609
- /**
1610
- * Create a new QueryBuilder without applying any default scopes.
1611
- * Useful for querying soft-deleted records or bypassing global filters.
1612
- *
1613
- * @returns A fresh QueryBuilder instance with no scopes applied
1614
- */
1207
+ /** No scopes applied — for soft-deleted records or bypassing global filters. */
1615
1208
  static newQueryWithoutScopes(queryOptions) {
1616
1209
  return new QueryBuilder(this, queryOptions);
1617
1210
  }
1618
1211
  /**
1619
- * Whether this model carries a filter that every query must apply.
1620
- *
1621
- * The entry points that talk to the adapter directly check this to decide
1622
- * whether they can take the fast path; anything that returns a QueryBuilder
1623
- * goes through `newQuery()` unconditionally.
1212
+ * Whether this model carries a filter every query must apply. Checked by the
1213
+ * entry points that talk to the adapter directly, to decide whether they can
1214
+ * take the fast path.
1624
1215
  */
1625
1216
  static hasScopes() {
1626
1217
  return Boolean(this.defaultScope) || Boolean(this.globalScopeRegistry && this.globalScopeRegistry.size > 0);
1627
1218
  }
1628
- /**
1629
- * Apply a named query scope.
1630
- *
1631
- * @param name - The scope name defined in `static scopes`
1632
- * @returns A QueryBuilder with the scope applied
1633
- *
1634
- * @example
1635
- * const published = await Post.scope('published').get()
1636
- * const popularPublished = await Post.scope('published').scope('popular').get()
1637
- */
1219
+ /** Apply a scope defined in `static scopes`; chainable. */
1638
1220
  static scope(name) {
1639
1221
  const scopes = this.scopes;
1640
1222
  if (!scopes || typeof scopes[name] !== "function") throw new Error(`${this.name}: unknown scope "${name}".`);
@@ -1642,20 +1224,8 @@ var Model = class Model {
1642
1224
  return scopes[name](builder);
1643
1225
  }
1644
1226
  /**
1645
- * Define a one-to-many relationship.
1646
- *
1647
- * @param name - Relation name (used in `with()` calls)
1648
- * @param related - The related model class
1649
- * @param foreignKey - Foreign key column on the related model
1650
- * @param localKey - Local key column on this model
1651
- *
1652
- * @example
1653
- * class User extends Model<UserRecord> {
1654
- * static {
1655
- * this.hasMany('posts', Post, 'userId', 'id')
1656
- * }
1657
- * }
1658
- * // Later: User.with('posts')
1227
+ * One-to-many: `foreignKey` is on the related model, `localKey` on this one.
1228
+ * Declare in a `static {}` block; `name` is what `with()` takes.
1659
1229
  */
1660
1230
  static hasMany(name, related, foreignKey, localKey) {
1661
1231
  this.getRelationDefinitions().set(name, {
@@ -1667,20 +1237,8 @@ var Model = class Model {
1667
1237
  });
1668
1238
  }
1669
1239
  /**
1670
- * Define a many-to-one (inverse) relationship.
1671
- *
1672
- * @param name - Relation name (used in `with()` calls)
1673
- * @param related - The related model class
1674
- * @param foreignKey - Foreign key column on this model
1675
- * @param ownerKey - Primary key column on the related model
1676
- *
1677
- * @example
1678
- * class Post extends Model<PostRecord> {
1679
- * static {
1680
- * this.belongsTo('author', User, 'userId', 'id')
1681
- * }
1682
- * }
1683
- * // Later: Post.with('author')
1240
+ * Many-to-one inverse: `foreignKey` is on *this* model, `ownerKey` on the
1241
+ * related one.
1684
1242
  */
1685
1243
  static belongsTo(name, related, foreignKey, ownerKey) {
1686
1244
  this.getRelationDefinitions().set(name, {
@@ -1692,20 +1250,7 @@ var Model = class Model {
1692
1250
  });
1693
1251
  }
1694
1252
  /**
1695
- * Define a one-to-one relationship.
1696
- *
1697
- * @param name - Relation name (used in `with()` calls)
1698
- * @param related - The related model class
1699
- * @param foreignKey - Foreign key column on the related model
1700
- * @param localKey - Local key column on this model
1701
- *
1702
- * @example
1703
- * class User extends Model<UserRecord> {
1704
- * static {
1705
- * this.hasOne('profile', Profile, 'userId', 'id')
1706
- * }
1707
- * }
1708
- * // Later: User.with('profile')
1253
+ * One-to-one: `foreignKey` is on the related model, `localKey` on this one.
1709
1254
  */
1710
1255
  static hasOne(name, related, foreignKey, localKey) {
1711
1256
  this.getRelationDefinitions().set(name, {
@@ -1717,23 +1262,11 @@ var Model = class Model {
1717
1262
  });
1718
1263
  }
1719
1264
  /**
1720
- * Define a many-to-many relationship via a pivot table.
1721
- *
1722
- * @param name - Relation name (used in `with()` calls)
1723
- * @param related - The related model class
1724
- * @param pivotTable - The pivot/junction table (e.g., Drizzle table schema)
1725
- * @param foreignPivotKey - Column on pivot table referencing this model
1726
- * @param relatedPivotKey - Column on pivot table referencing the related model
1727
- * @param parentKey - Local key on this model (default: 'id')
1728
- * @param relatedKey - Local key on the related model (default: 'id')
1729
- *
1265
+ * Many-to-many through a pivot table. `foreignPivotKey`/`relatedPivotKey` are
1266
+ * both columns *on the pivot*, referencing this model and the related one;
1267
+ * `parentKey`/`relatedKey` are the local keys they point at.
1730
1268
  * @example
1731
- * class User extends Model<UserRecord> {
1732
- * static {
1733
- * this.belongsToMany('roles', Role, userRoles, 'userId', 'roleId', 'id', 'id')
1734
- * }
1735
- * }
1736
- * // Later: User.with('roles')
1269
+ * this.belongsToMany('roles', Role, userRoles, 'userId', 'roleId', 'id', 'id')
1737
1270
  */
1738
1271
  static belongsToMany(name, related, pivotTable, foreignPivotKey, relatedPivotKey, parentKey, relatedKey) {
1739
1272
  this.getRelationDefinitions().set(name, {
@@ -1748,23 +1281,11 @@ var Model = class Model {
1748
1281
  });
1749
1282
  }
1750
1283
  /**
1751
- * Define a has-many-through relationship.
1752
- *
1753
- * @param name - Relation name (used in `with()` calls)
1754
- * @param related - The final related model class
1755
- * @param through - The intermediate model class
1756
- * @param firstKey - Foreign key on the intermediate model referencing this model
1757
- * @param secondKey - Foreign key on the related model referencing the intermediate model
1758
- * @param localKey - Local key on this model (default: 'id')
1759
- * @param secondLocalKey - Local key on the intermediate model (default: 'id')
1760
- *
1284
+ * Has-many-through: `firstKey` is on the intermediate model referencing this
1285
+ * one, `secondKey` on the related model referencing the intermediate;
1286
+ * `localKey` and `secondLocalKey` are the keys they point at.
1761
1287
  * @example
1762
- * class Country extends Model<CountryRecord> {
1763
- * static {
1764
- * this.hasManyThrough('posts', Post, User, 'countryId', 'userId', 'id', 'id')
1765
- * }
1766
- * }
1767
- * // Later: Country.with('posts')
1288
+ * this.hasManyThrough('posts', Post, User, 'countryId', 'userId', 'id', 'id')
1768
1289
  */
1769
1290
  static hasManyThrough(name, related, through, firstKey, secondKey, localKey, secondLocalKey) {
1770
1291
  this.getRelationDefinitions().set(name, {
@@ -1778,23 +1299,11 @@ var Model = class Model {
1778
1299
  secondLocalKey: secondLocalKey ?? "id"
1779
1300
  });
1780
1301
  }
1781
- /**
1782
- * Map of type strings to model classes for polymorphic relationships.
1783
- *
1784
- * @example
1785
- * Model.morphMap = { Post, Video }
1786
- */
1302
+ /** Type strings to model classes, e.g. `Model.morphMap = { Post, Video }`. */
1787
1303
  static morphMap;
1788
1304
  /**
1789
- * Define a one-to-many polymorphic relationship.
1790
- *
1791
- * @param name - Relation name
1792
- * @param related - The related model class
1793
- * @param morphName - Base name for the type/id columns (e.g. 'commentable' → commentableType + commentableId)
1794
- * @param localKey - Local key on this model (default: 'id')
1795
- *
1796
- * @example
1797
- * Post.morphMany('comments', Comment, 'commentable', 'id')
1305
+ * Polymorphic one-to-many. `morphName` is the base of the column pair:
1306
+ * 'commentable' means commentableType + commentableId.
1798
1307
  */
1799
1308
  static morphMany(name, related, morphName, localKey) {
1800
1309
  this.getRelationDefinitions().set(name, {
@@ -1805,15 +1314,7 @@ var Model = class Model {
1805
1314
  localKey: localKey ?? "id"
1806
1315
  });
1807
1316
  }
1808
- /**
1809
- * Define the inverse of a polymorphic relationship.
1810
- *
1811
- * @param name - Relation name
1812
- * @param morphName - Base name for the type/id columns
1813
- *
1814
- * @example
1815
- * Comment.morphTo('commentable', 'commentable')
1816
- */
1317
+ /** Inverse of a polymorphic relation; `morphName` bases the type/id columns. */
1817
1318
  static morphTo(name, morphName) {
1818
1319
  this.getRelationDefinitions().set(name, {
1819
1320
  type: "morphTo",
@@ -1823,24 +1324,9 @@ var Model = class Model {
1823
1324
  });
1824
1325
  }
1825
1326
  /**
1826
- * Get records sorted by the specified order.
1827
- *
1828
- * @param order - Order expression(s)
1829
- * @param where - Optional filter conditions
1830
- * @returns Sorted array of records
1831
- *
1832
1327
  * @example
1833
- * // Single column ascending
1834
1328
  * await User.orderBy('createdAt')
1835
- *
1836
- * // Single column descending
1837
- * await User.orderBy(['createdAt', 'desc'])
1838
- *
1839
- * // Multiple columns
1840
- * await User.orderBy([['lastName', 'asc'], ['firstName', 'asc']])
1841
- *
1842
- * // With where clause
1843
- * await User.orderBy('name', { status: 'active' })
1329
+ * await User.orderBy([['lastName', 'asc'], ['firstName', 'asc']], { status: 'active' })
1844
1330
  */
1845
1331
  static async orderBy(order, where, queryOptions) {
1846
1332
  const orderBy = normalizeOrderBy(order);
@@ -1856,24 +1342,8 @@ var Model = class Model {
1856
1342
  return this.getAdapter().findMany(table, options, queryOptions);
1857
1343
  }
1858
1344
  /**
1859
- * Get paginated records.
1860
- *
1861
- * @param options - Pagination options
1862
- * @returns Paginated result with data and metadata
1863
- *
1864
1345
  * @example
1865
- * const result = await User.paginate({ page: 1, perPage: 10 })
1866
- * // result.data - Array of users
1867
- * // result.meta.total - Total count
1868
- * // result.meta.hasMore - Whether there are more pages
1869
- *
1870
- * // With filtering and ordering
1871
- * await User.paginate({
1872
- * page: 2,
1873
- * perPage: 20,
1874
- * where: { status: 'active' },
1875
- * orderBy: ['createdAt', 'desc']
1876
- * })
1346
+ * await User.paginate({ page: 2, perPage: 20, where: { status: 'active' } })
1877
1347
  */
1878
1348
  static async paginate(options = {}, queryOptions) {
1879
1349
  if (this.hasScopes()) {
@@ -1931,32 +1401,12 @@ var Model = class Model {
1931
1401
  meta: result.meta
1932
1402
  };
1933
1403
  }
1934
- /**
1935
- * Create a new record.
1936
- *
1937
- * @param data - Record data to insert
1938
- * @returns The created record
1939
- *
1940
- * @example
1941
- * const user = await User.create({
1942
- * name: 'John Doe',
1943
- * email: 'john@example.com'
1944
- * })
1945
- */
1946
1404
  static async create(data, writeOptions) {
1947
1405
  return this.runCreate(data, writeOptions, true);
1948
1406
  }
1949
1407
  /**
1950
- * Create a record bypassing mass-assignment protection. Use for trusted,
1951
- * server-side-assembled data (OAuth account linking, seeders, system
1952
- * records) — never for raw request input.
1953
- *
1954
- * @example
1955
- * const user = await User.forceCreate({
1956
- * name: profile.name,
1957
- * email: profile.email,
1958
- * passwordHash: `oauth:${provider}:${profile.id}`,
1959
- * })
1408
+ * Create bypassing mass-assignment protection. Trusted server-side data only
1409
+ * (OAuth linking, seeders, system records), never raw request input.
1960
1410
  */
1961
1411
  static async forceCreate(data, writeOptions) {
1962
1412
  return this.runCreate(data, writeOptions, false);
@@ -1989,22 +1439,12 @@ var Model = class Model {
1989
1439
  if (this.casts || this.accessors) return this.applyReadTransforms(result);
1990
1440
  return result;
1991
1441
  }
1992
- /**
1993
- * Update records matching the conditions.
1994
- *
1995
- * @param where - Filter conditions to identify records
1996
- * @param data - Data to update
1997
- * @returns The updated record
1998
- *
1999
- * @example
2000
- * await User.update({ id: 1 }, { name: 'Jane Doe' })
2001
- */
2002
1442
  static async update(where, data, writeOptions) {
2003
1443
  return this.runUpdate(where, data, writeOptions, true);
2004
1444
  }
2005
1445
  /**
2006
- * Update records bypassing mass-assignment protection. Use for trusted,
2007
- * server-side-assembled data — never for raw request input.
1446
+ * Update bypassing mass-assignment protection. Trusted server-side data only,
1447
+ * never raw request input.
2008
1448
  */
2009
1449
  static async forceUpdate(where, data, writeOptions) {
2010
1450
  return this.runUpdate(where, data, writeOptions, false);
@@ -2013,6 +1453,7 @@ var Model = class Model {
2013
1453
  const table = this.resolveTable();
2014
1454
  const adapter = this.getAdapter();
2015
1455
  if (!adapter.update) throw new Error("Configured adapter does not support update operations.");
1456
+ this.assertFiltersSurvived(where, "update");
2016
1457
  const filtered = applyFillable ? this.filterFillable(data) : { ...data };
2017
1458
  const payload = await this.preparePersistencePayload(filtered);
2018
1459
  const hooks = this.hooks;
@@ -2039,20 +1480,11 @@ var Model = class Model {
2039
1480
  if (this.casts || this.accessors) return this.applyReadTransforms(result);
2040
1481
  return result;
2041
1482
  }
2042
- /**
2043
- * Delete records matching the conditions.
2044
- *
2045
- * @param where - Filter conditions to identify records
2046
- * @returns Number of deleted records or void depending on adapter
2047
- *
2048
- * @example
2049
- * await User.delete({ id: 1 })
2050
- * await User.delete({ status: 'inactive' })
2051
- */
2052
1483
  static async delete(where, writeOptions) {
2053
1484
  const table = this.resolveTable();
2054
1485
  const adapter = this.getAdapter();
2055
1486
  if (!adapter.delete) throw new Error("Configured adapter does not support delete operations.");
1487
+ this.assertFiltersSurvived(where, "delete");
2056
1488
  const hooks = this.hooks;
2057
1489
  const observers = this.observers;
2058
1490
  const whereData = where;
@@ -2068,20 +1500,8 @@ var Model = class Model {
2068
1500
  return result;
2069
1501
  }
2070
1502
  /**
2071
- * Get a raw Drizzle query builder for complex queries.
2072
- *
2073
- * @param db - Optional Drizzle database instance
2074
- * @returns Drizzle query builder starting with `select().from(table)`
2075
- *
2076
- * @example
2077
- * // Simple query
2078
- * const users = await User.query(db)
2079
- * .where(eq(users.status, 'active'))
2080
- * .limit(10)
2081
- *
2082
- * // With joins
2083
- * const usersWithPosts = await User.query(db)
2084
- * .leftJoin(posts, eq(users.id, posts.userId))
1503
+ * A raw Drizzle builder starting at `select().from(table)`. Carries no model
1504
+ * scopes, casts or accessors.
2085
1505
  */
2086
1506
  static query(db) {
2087
1507
  const table = this.resolveTable();
@@ -2162,15 +1582,10 @@ var Model = class Model {
2162
1582
  }
2163
1583
  }
2164
1584
  /**
2165
- * @internal Used by QueryBuilder for eager loading.
2166
- * Supports nested paths with dot notation, e.g. `posts.comments`.
2167
- *
2168
- * Paths are grouped by their head segment so a relation shared by several
2169
- * paths is loaded exactly once. Walking `posts.comments` and `posts.tags`
2170
- * independently would load `posts` twice, and the loaders assign fresh
2171
- * spread copies — so the second pass would replace the very row objects the
2172
- * first had already attached children to, and only the last path would
2173
- * survive.
1585
+ * @internal Used by QueryBuilder for eager loading. Paths are grouped by head
1586
+ * segment so a shared relation loads once: the loaders assign fresh spread
1587
+ * copies, so a second pass over `posts` would replace the very rows the first
1588
+ * attached children to and only the last path would survive.
2174
1589
  */
2175
1590
  static async loadRelationsInto(records, relationNames, queryOptions, constraints, pathPrefix = "") {
2176
1591
  if (relationNames.length === 0) return;
@@ -2187,20 +1602,16 @@ var Model = class Model {
2187
1602
  for (const [head, tails] of groups) await this.loadRelationLevel(records, head, tails, queryOptions, constraints, pathPrefix);
2188
1603
  }
2189
1604
  /**
2190
- * @internal Public since it is reachable from generated code; kept for
2191
- * backwards compatibility now that the eager loader walks whole path lists.
2192
- * Internal callers should use {@link loadRelationsInto} instead.
1605
+ * @internal Public because generated code reaches it; internal callers should
1606
+ * use {@link loadRelationsInto}.
2193
1607
  */
2194
1608
  static async loadRelationInto(records, relationName, queryOptions, constraints, pathPrefix = "") {
2195
1609
  await this.loadRelationsInto(records, [relationName], queryOptions, constraints, pathPrefix);
2196
1610
  }
2197
1611
  /**
2198
- * Load one relation level and recurse into the tails beneath it.
2199
- *
2200
- * `constraints` are keyed by the full path of the level each one constrains,
2201
- * so `pathPrefix` accumulates the path walked so far as the recursion
2202
- * descends: at `posts.comments` the leaf looks itself up under that whole
2203
- * key, not under `comments`.
1612
+ * `constraints` are keyed by the full path of the level each constrains, so
1613
+ * `pathPrefix` accumulates the path walked so far: at `posts.comments` the
1614
+ * leaf looks itself up under that whole key, not under `comments`.
2204
1615
  */
2205
1616
  static async loadRelationLevel(records, head, tails, queryOptions, constraints, pathPrefix = "") {
2206
1617
  const definition = this.getRelationDefinition(head);
@@ -2396,12 +1807,10 @@ var Model = class Model {
2396
1807
  }
2397
1808
  };
2398
1809
  /**
2399
- * Apply an eager-load constraint callback to the query that fetches a
2400
- * relation, then execute it. The callback runs with the foreign-key filter
2401
- * already on the builder, so a `where()` narrows it. A top-level `orWhere()`
2402
- * widens it instead — loaders that group results on something weaker than the
2403
- * full filter (morphMany, which groups on the morph id) must not rely on the
2404
- * query alone to keep other rows out.
1810
+ * The callback runs with the foreign-key filter already on the builder, so a
1811
+ * `where()` narrows it and a top-level `orWhere()` widens it — a loader that
1812
+ * groups on something weaker than the full filter (morphMany, on the morph id)
1813
+ * must not rely on the query alone to keep other rows out.
2405
1814
  */
2406
1815
  async function applyEagerConstraint(query, constraint) {
2407
1816
  constraint?.(query);
@@ -2436,34 +1845,11 @@ async function resolveModelReference(reference) {
2436
1845
  return await reference();
2437
1846
  }
2438
1847
  /**
2439
- * Create a table-backed model base class from a Drizzle table.
2440
- *
2441
- * `recordType` and `createType` are inferred from the table. The inferred
2442
- * createType requires every non-defaulted column, which is not always the
2443
- * payload a model accepts: `AuthenticatableModel` hashes a plain `password`
2444
- * into `passwordHash`, so a user model wants the column optional and the
2445
- * virtual field required. `optionalOnCreate` and `requireOnCreate` reshape the
2446
- * inferred type without any cast.
2447
- *
2448
- * The allowlist statics (`fillable`, `hidden`, `visible`, `accessors`,
2449
- * `appends`) can be passed here instead of declared on the subclass: the
2450
- * option form checks every name against the table's columns (plus fields the
2451
- * `base` contributes), so a typo is a compile error instead of a silently
2452
- * ineffective entry. A `static` declaration on the subclass still works and
2453
- * shadows the option, matching normal class semantics.
2454
- *
2455
- * @example
2456
- * export class Post extends defineModel(posts, {
2457
- * fillable: ['title', 'body'],
2458
- * }) {}
2459
- *
2460
- * export class User extends defineModel(users, {
2461
- * base: AuthenticatableModel,
2462
- * optionalOnCreate: ['passwordHash'],
2463
- * requireOnCreate: ['password'],
2464
- * fillable: ['name', 'email', 'password'],
2465
- * hidden: ['passwordHash', 'rememberToken'],
2466
- * }) {}
1848
+ * A table-backed model base class: `recordType`/`createType` inferred from the
1849
+ * table, `optionalOnCreate`/`requireOnCreate` reshaping the create payload without
1850
+ * a cast (`AuthenticatableModel` hashes a virtual `password` into `passwordHash`).
1851
+ * Allowlist statics passed as options are checked against the table's columns, so
1852
+ * a typo is a compile error; a `static` on the subclass shadows the option.
2467
1853
  */
2468
1854
  function defineModel(table, options = {}) {
2469
1855
  const BaseClass = options.base ?? Model;
@@ -2516,70 +1902,53 @@ function resolveQueryableDatabase(adapter) {
2516
1902
  }
2517
1903
  //#endregion
2518
1904
  //#region src/SoftDeletes.ts
2519
- /** A query carrying every global scope this model has, including softDelete. */
2520
- function scopedQuery(model, where) {
2521
- 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);
2522
1912
  }
2523
1913
  /** A query carrying every global scope *except* softDelete, so it sees trashed rows. */
2524
- function withoutSoftDeleteScope(model) {
2525
- return model.withoutGlobalScope("softDelete");
1914
+ function withoutSoftDeleteScope(model, queryOptions) {
1915
+ return model.withoutGlobalScope(queryOptions ?? {}, "softDelete");
2526
1916
  }
2527
- function trashedScopedQuery(model, where) {
2528
- return withoutSoftDeleteScope(model).where(where);
1917
+ function trashedScopedQuery(model, where, queryOptions) {
1918
+ return withoutSoftDeleteScope(model, queryOptions).where(where);
2529
1919
  }
2530
1920
  /**
2531
- * Mixin that adds soft delete behavior to a Model.
2532
- *
2533
- * When applied, `delete()` sets a `deletedAt` timestamp instead of removing the
2534
- * record from the database. All default queries automatically exclude soft-deleted
2535
- * records via a global scope named 'softDelete'.
1921
+ * Mixin where `delete()` sets `deletedAt` instead of removing the row, and a
1922
+ * global scope named 'softDelete' excludes those rows from every query.
2536
1923
  *
2537
1924
  * @example
2538
1925
  * class Post extends SoftDeletes(defineModel(posts)) {}
2539
- *
2540
- * // Soft delete a record (sets deletedAt)
2541
- * await Post.delete({ id: 1 })
2542
- *
2543
- * // Query only non-deleted records (default behavior)
2544
- * const posts = await Post.all()
2545
- *
2546
- * // Include soft-deleted records
2547
- * const allPosts = await Post.withTrashed().get()
2548
- *
2549
- * // Query only soft-deleted records
2550
- * const trashed = await Post.onlyTrashed().get()
2551
- *
2552
- * // Restore a soft-deleted record
2553
- * await Post.restore({ id: 1 })
2554
- *
2555
- * // Permanently delete a record
2556
- * await Post.forceDelete({ id: 1 })
2557
1926
  */
2558
1927
  function SoftDeletes(Base) {
2559
1928
  const SoftDeleteModel = class extends Base {};
2560
1929
  SoftDeleteModel.deletedAtColumn = "deletedAt";
2561
1930
  const scopeFn = (q) => q.whereNull("deletedAt");
2562
1931
  SoftDeleteModel.addGlobalScope("softDelete", scopeFn);
2563
- SoftDeleteModel.delete = async function(where) {
1932
+ SoftDeleteModel.delete = async function(where, writeOptions) {
2564
1933
  if (!this.getAdapter().update) throw new Error("Configured adapter does not support update operations (needed for soft delete).");
2565
1934
  const column = this.deletedAtColumn;
2566
- return scopedQuery(this, where)[PREPARED_UPDATE]({ [column]: /* @__PURE__ */ new Date() });
1935
+ return scopedQuery(this, where, writeOptions)[PREPARED_UPDATE]({ [column]: /* @__PURE__ */ new Date() });
2567
1936
  };
2568
- SoftDeleteModel.withTrashed = function() {
2569
- return withoutSoftDeleteScope(this);
1937
+ SoftDeleteModel.withTrashed = function(queryOptions) {
1938
+ return withoutSoftDeleteScope(this, queryOptions);
2570
1939
  };
2571
- SoftDeleteModel.onlyTrashed = function() {
1940
+ SoftDeleteModel.onlyTrashed = function(queryOptions) {
2572
1941
  const column = this.deletedAtColumn;
2573
- return withoutSoftDeleteScope(this).whereNotNull(column);
1942
+ return withoutSoftDeleteScope(this, queryOptions).whereNotNull(column);
2574
1943
  };
2575
- SoftDeleteModel.restore = async function(where) {
1944
+ SoftDeleteModel.restore = async function(where, writeOptions) {
2576
1945
  if (!this.getAdapter().update) throw new Error("Configured adapter does not support update operations (needed for restore).");
2577
1946
  const column = this.deletedAtColumn;
2578
- return trashedScopedQuery(this, where)[PREPARED_UPDATE]({ [column]: null });
1947
+ return trashedScopedQuery(this, where, writeOptions)[PREPARED_UPDATE]({ [column]: null });
2579
1948
  };
2580
- SoftDeleteModel.forceDelete = async function(where) {
1949
+ SoftDeleteModel.forceDelete = async function(where, writeOptions) {
2581
1950
  if (!this.getAdapter().delete) throw new Error("Configured adapter does not support delete operations.");
2582
- return trashedScopedQuery(this, where).delete();
1951
+ return trashedScopedQuery(this, where, writeOptions).delete();
2583
1952
  };
2584
1953
  return SoftDeleteModel;
2585
1954
  }
@@ -2587,12 +1956,9 @@ function SoftDeletes(Base) {
2587
1956
  //#region src/active-connections.ts
2588
1957
  const REGISTRY_KEY = Symbol.for("guren.orm.activeConnections");
2589
1958
  /**
2590
- * How long to wait for the previous client to close before giving up on it.
2591
- *
2592
- * The teardown is awaited so the replacement never runs alongside the client it
2593
- * replaces — that back-pressure is what keeps a burst of reloads from stacking
2594
- * up connections. But it runs on the path to the first query after a reload, so
2595
- * a client whose socket never finishes closing must not wedge the dev server.
1959
+ * Awaiting the teardown is the back-pressure that keeps a burst of reloads from
1960
+ * stacking up connections, but it runs on the path to the first query after a
1961
+ * reload, so a socket that never finishes closing must not wedge the dev server.
2596
1962
  */
2597
1963
  const TEARDOWN_TIMEOUT_MS = 5e3;
2598
1964
  function getRegistry() {
@@ -2603,13 +1969,7 @@ function getRegistry() {
2603
1969
  scope[REGISTRY_KEY] = registry;
2604
1970
  return registry;
2605
1971
  }
2606
- /**
2607
- * Whether modules can be re-evaluated in this process.
2608
- *
2609
- * `bun --watch` restarts the process instead, which closes every connection on
2610
- * its own, so `--hot` is the only mode that leaks. Everywhere else — production,
2611
- * tests, CLI commands, serverless — nothing is ever torn down automatically.
2612
- */
1972
+ /** `bun --watch` restarts the process instead, so `--hot` is the only mode that leaks. */
2613
1973
  function isHotReloadRuntime() {
2614
1974
  return typeof process !== "undefined" && Array.isArray(process.execArgv) && process.execArgv.includes("--hot");
2615
1975
  }
@@ -2627,15 +1987,10 @@ function isDigitAt(text, index) {
2627
1987
  return code >= 48 && code <= 57;
2628
1988
  }
2629
1989
  /**
2630
- * Where a frame's trailing `:line[:column]` may begin, in the order the lazy
2631
- * `(.+?):\d+(?::\d+)?` these replace settled on them: the `:line:column` split
2632
- * first, because a lazy path stops at the earliest suffix that satisfies the
2633
- * rest, then the `:column`-only split it backtracked to when the shorter path
2634
- * came out empty.
2635
- *
2636
- * Walking the digits back from `end` finds both in one pass. The pattern
2637
- * instead re-tested the suffix at every prefix length, which is what made it
2638
- * quadratic in the length of a frame.
1990
+ * Where a frame's trailing `:line[:column]` may begin, `:line:column` split
1991
+ * first, in the order the lazy `(.+?):\d+(?::\d+)?` this replaces settled on
1992
+ * them. Walking the digits back from `end` finds both in one pass; the pattern
1993
+ * re-tested the suffix at every prefix length, which made it quadratic.
2639
1994
  */
2640
1995
  function locationSplits(frame, end) {
2641
1996
  let cursor = end;
@@ -2651,29 +2006,11 @@ function pathBefore(frame, from, splits) {
2651
2006
  for (const split of splits) if (split > from) return frame.slice(from, split);
2652
2007
  }
2653
2008
  /**
2654
- * The index of the `(` that matches the `)` at `closeIndex`, or `undefined`
2655
- * when the frame carries no usable `(` at all. `closeIndex` must point at the
2656
- * frame's final `)`; anything else is rejected.
2657
- *
2658
- * Neither the leftmost nor the rightmost `(` is right in general. A path may
2659
- * contain one — `at fn (/app (old)/x.ts:1:2)` needs the outer, *leftmost*
2660
- * pair — and so may the function name in front of it — `at weird (name)
2661
- * (/app/x.ts:1:2)` needs the outer, *rightmost* pair. Depth is what actually
2662
- * tells the two apart; a fixed "first" or "last" gets one of them wrong.
2663
- *
2664
- * Depth alone would reject a frame whose location holds an *unmatched* `)`, as
2665
- * `/app/name).ts` or a URL ending `?label=)` does — the scan runs off the front
2666
- * still owing a paren. So the leftmost `(` it passed is kept as a fallback for
2667
- * exactly that case. Only frames the depth rule rejects outright can reach it.
2668
- *
2669
- * The scan stops at a line terminator: a path could never span one, so neither
2670
- * a balanced `(` nor the fallback may come from the far side of a break.
2671
- * Characters are compared by code rather than tested against `LINE_TERMINATOR`
2672
- * because this loop runs over every character of every frame.
2673
- *
2674
- * Its twin is `packages/server/src/support/stack-frames.ts`. The body there is
2675
- * identical character for character on purpose; only this prose differs. Keep
2676
- * the two in step.
2009
+ * The index of the `(` matching the final `)` at `closeIndex`. Both a path and
2010
+ * the function name in front of it may contain `(`, so only depth tells the
2011
+ * outer pair apart; the leftmost `(` passed is the fallback for a location
2012
+ * holding an unmatched `)`. Compared by code: this runs over every character of
2013
+ * every frame. Twin of `packages/server/src/support/stack-frames.ts` — keep in step.
2677
2014
  */
2678
2015
  function matchingOpenParen(frame, closeIndex) {
2679
2016
  if (frame.charCodeAt(closeIndex) !== CLOSE_PAREN) return;
@@ -2692,29 +2029,10 @@ function matchingOpenParen(frame, closeIndex) {
2692
2029
  }
2693
2030
  /**
2694
2031
  * The path a single stack frame points at, without its line and column.
2695
- *
2696
- * The two shapes a frame comes in are read separately rather than by one rule
2697
- * loose enough to cover both. `at fn (/path/file.ts:1:2)` is tried first,
2698
- * because its parentheses bound the path; a rule that also had to accept the
2699
- * bare `at /path/file.ts:1:2` could only bound it by whitespace, and would
2700
- * truncate `/Users/me/My Projects/app/config` to `Projects/app/config`.
2701
- * Nothing constrains what the path itself may contain — spaces and parentheses
2702
- * are both ordinary in a macOS directory name, and excluding either is how the
2703
- * truncation happened in the first place.
2704
- *
2705
- * Neither the leftmost nor the rightmost `(` bounds the opening paren in
2706
- * general — see `matchingOpenParen` — so the two shapes below no longer search
2707
- * for one at a fixed end.
2708
- *
2709
- * Both shapes require a trailing `:line`, so frames that name no location at
2710
- * all — `at native`, `at <anonymous>` — are rejected instead of being read as a
2711
- * path. That is a check on the frame's shape, not on what it points at: the
2712
- * engine also emits those same names *with* a location, and rejecting those is
2713
- * `SYNTHETIC_FRAME_PATHS`'s job below, not this function's. An `eval` group is
2714
- * rejected outright here, though: V8 nests the real location inside
2715
- * `eval at fn (/app/x.ts:1:2), <anonymous>:1:1`, and keying a connection on
2716
- * text that is not a path is worse than not keying it — a handle with no key
2717
- * is left alone, which is the safe failure.
2032
+ * `at fn (/path/file.ts:1:2)` is tried first because its parens bound the path;
2033
+ * a whitespace-bounded rule would truncate `/Users/me/My Projects/app`. Both
2034
+ * shapes require a trailing `:line`, and a V8 `eval at ...` group is rejected:
2035
+ * keying on text that is not a path is worse than leaving the handle unkeyed.
2718
2036
  */
2719
2037
  function parseFrameLocation(frame) {
2720
2038
  const end = frame.trimEnd().length;
@@ -2739,17 +2057,11 @@ function parseFrameLocation(frame) {
2739
2057
  return path !== void 0 && !LINE_TERMINATOR.test(path) ? path : void 0;
2740
2058
  }
2741
2059
  /**
2742
- * Paths the engine reports for code that has no source location.
2743
- *
2744
- * A class field initializer, or a subclass that declares no constructor of its
2745
- * own, runs inside a function nobody wrote, and JSC reports it as
2746
- * `at new Owner (unknown:1:17)`; a built-in doing the calling reports
2060
+ * Paths the engine reports for code with no source location — a class field
2061
+ * initializer as `at new Owner (unknown:1:17)`, a built-in caller as
2747
2062
  * `at map (native:1:11)`. Both carry a `:line`, so they parse as ordinary paths
2748
- * and only this set rejects them.
2749
- *
2750
- * Why taking one is worse than taking nothing is spelled out beside the twin's
2751
- * copy in `packages/server/src/hot-reload/hot-disposables.ts` — keep the two in
2752
- * step.
2063
+ * and only this set rejects them. Twin in
2064
+ * `packages/server/src/hot-reload/hot-disposables.ts` — keep the two in step.
2753
2065
  */
2754
2066
  const SYNTHETIC_FRAME_PATHS = /* @__PURE__ */ new Set([
2755
2067
  "unknown",
@@ -2757,22 +2069,11 @@ const SYNTHETIC_FRAME_PATHS = /* @__PURE__ */ new Set([
2757
2069
  "<anonymous>"
2758
2070
  ]);
2759
2071
  /**
2760
- * The file that called a `create*Database()` factory.
2761
- *
2762
- * `stack` must come from an `Error` constructed inside the factory itself, so
2763
- * frame 0 is `Error`, frame 1 is the factory, and frame 2 is the caller — or the
2764
- * first frame after it that names a real file, since the engine may have
2765
- * synthesized the frames in between. Only the path is kept: a reload re-runs the
2766
- * same file, but not necessarily at the same line.
2767
- *
2768
- * The frame taken may sit further out than the call — a shared bootstrap, say —
2769
- * widening the file-level collision the header describes; the target in the key
2770
- * is what keeps those apart.
2771
- *
2772
- * One case the header's escape hatch does not reach: a field initializer leaves
2773
- * no frame of its own, so the file the class is declared in never appears in the
2774
- * stack, and giving that class its own module changes nothing. Such a handle is
2775
- * keyed to wherever `new` was written instead.
2072
+ * The file that called a `create*Database()` factory. `stack` must come from an
2073
+ * `Error` constructed inside the factory: frame 0 is `Error`, 1 the factory, 2
2074
+ * the caller — or the first later frame naming a real file. A class field
2075
+ * initializer leaves no frame of its own, so a handle built there keys to
2076
+ * wherever `new` was written instead.
2776
2077
  */
2777
2078
  function describeCallerFile(stack) {
2778
2079
  for (const frame of stack?.split("\n").slice(2) ?? []) {
@@ -2807,16 +2108,10 @@ async function closeWithTimeout(teardown, timeoutMs) {
2807
2108
  }
2808
2109
  /**
2809
2110
  * Records `teardown` as the active client for `key` and closes whichever client
2810
- * held the slot before it.
2811
- *
2812
- * Claims on one key are serialized: a claim waits for the claim it supersedes to
2813
- * finish its own replacement before tearing it down. Without that, three reloads
2814
- * arriving inside the teardown window let the third close the second's client
2815
- * while the second was still initializing, and the second would go on to hand
2816
- * its caller a client that is already closed.
2817
- *
2818
- * `timeoutMs` exists so tests can exercise the give-up path without waiting out
2819
- * the real budget; callers should leave it at the default.
2111
+ * held the slot before it. Claims on one key are serialized: without that, three
2112
+ * reloads inside the teardown window let the third close the second's client
2113
+ * mid-initialization, handing its caller an already-closed one. `timeoutMs` is
2114
+ * for tests; callers should leave it at the default.
2820
2115
  */
2821
2116
  async function replaceActiveConnection(key, teardown, timeoutMs = TEARDOWN_TIMEOUT_MS) {
2822
2117
  const registry = getRegistry();
@@ -2842,11 +2137,7 @@ function releaseActiveConnection(key, teardown) {
2842
2137
  }
2843
2138
  //#endregion
2844
2139
  //#region src/migration-utils.ts
2845
- /**
2846
- * One read of the migrations folder, answering both questions a run summary
2847
- * asks of it. Kept together because they come from the same directory listing:
2848
- * counting the loose files separately would read it twice to report on one run.
2849
- */
2140
+ /** One directory listing answering both questions a run summary asks of it. */
2850
2141
  function inspectMigrationsFolder(migrationsFolder) {
2851
2142
  if (!existsSync(migrationsFolder)) return {
2852
2143
  migrationsFolder,
@@ -2862,12 +2153,9 @@ function inspectMigrationsFolder(migrationsFolder) {
2862
2153
  }
2863
2154
  /**
2864
2155
  * Reports a run that found nothing to apply, naming the loose .sql files if
2865
- * that is why the folder looked empty — without this, `db:migrate` reports the
2866
- * folder as having no migrations while files that look like migrations sit in
2867
- * it. The names cost a second read, so this only happens when there are some.
2868
- *
2869
- * A folder the migrator did run from is never warned about: it has already
2870
- * produced a database, and the warning would fire on every app boot.
2156
+ * that is why the folder looked empty. The names cost a second read, so it
2157
+ * only happens when there are some; a folder the migrator did run from is
2158
+ * never warned about, or the warning would fire on every app boot.
2871
2159
  */
2872
2160
  function noMigrationsToRun(summary) {
2873
2161
  if (summary.looseSqlFiles === 0) return summary;
@@ -2876,15 +2164,11 @@ function noMigrationsToRun(summary) {
2876
2164
  return summary;
2877
2165
  }
2878
2166
  /**
2879
- * Driver error codes that mean the server was never reached, so the statement
2880
- * drizzle happened to be sending is noise. Deliberately excludes mid-flight
2881
- * failures like ECONNRESET and EPIPE — those can hit halfway through a
2882
- * migration run, where the query text is the useful part.
2883
- *
2884
- * ETIMEDOUT is absent for the same reason, and is instead recognised through
2885
- * `syscall: 'connect'` below: mysql2 reports a connect timeout as
2886
- * `ETIMEDOUT`/`syscall: 'connect'`, while a read that times out mid-query does
2887
- * not carry that syscall.
2167
+ * Codes meaning the server was never reached, so the statement drizzle was
2168
+ * sending is noise. Excludes mid-flight failures (ECONNRESET, EPIPE), where
2169
+ * the query text is the useful part. ETIMEDOUT is out for the same reason and
2170
+ * is caught instead by `syscall: 'connect'` below — mysql2 sets that on a
2171
+ * connect timeout but not on a read that times out mid-query.
2888
2172
  */
2889
2173
  const PRE_CONNECTION_ERROR_CODES = /* @__PURE__ */ new Set([
2890
2174
  "CONNECT_TIMEOUT",
@@ -2900,31 +2184,37 @@ function failedWhileConnecting(error) {
2900
2184
  if (typeof code !== "string" || code === "") return false;
2901
2185
  return PRE_CONNECTION_ERROR_CODES.has(code) || syscall === "connect";
2902
2186
  }
2903
- /**
2904
- * Walks the cause chain (and AggregateError members) collecting every nested
2905
- * error, outwards-in. `seen` bounds the walk on self-referencing chains.
2906
- */
2187
+ /** Collects the cause chain and AggregateError members, outwards-in. `seen` bounds self-referencing chains. */
2907
2188
  function collectCauses(error, seen = /* @__PURE__ */ new Set()) {
2908
2189
  if (error == null || typeof error !== "object" || seen.has(error)) return [];
2909
2190
  seen.add(error);
2910
2191
  return [error, ...[...Array.isArray(error.errors) ? error.errors : [], ..."cause" in error ? [error.cause] : []].flatMap((child) => collectCauses(child, seen))];
2911
2192
  }
2912
- /** True when the failure means the database server was never reached. */
2913
- function isConnectionFailure(error) {
2914
- return collectCauses(error).some(failedWhileConnecting);
2193
+ /**
2194
+ * Each driver's own signal for "that table does not exist", read off the
2195
+ * driver error rather than the wrapper drizzle puts around it.
2196
+ */
2197
+ const MISSING_TABLE = {
2198
+ postgres: (cause) => cause.code === "42P01",
2199
+ mysql: (cause) => cause.code === "ER_NO_SUCH_TABLE" || cause.errno === 1146,
2200
+ sqlite: (cause) => typeof cause.message === "string" && /no such table/i.test(cause.message)
2201
+ };
2202
+ /**
2203
+ * True when a query against the drizzle migration tracker failed because the
2204
+ * tracker table does not exist yet — the one failure `migrationStatus()` may
2205
+ * read as "nothing applied". Anything else (a denied SELECT, a tracker whose
2206
+ * columns drifted, a broken `drizzle` schema) has to surface: reported as
2207
+ * all-pending it invites a re-run of migrations that were applied.
2208
+ */
2209
+ function isMissingTrackerTable(error, dialect) {
2210
+ return collectCauses(error).some(MISSING_TABLE[dialect]);
2915
2211
  }
2916
2212
  /**
2917
- * Turns a database failure into a message that names the actual problem.
2918
- *
2919
- * Drizzle wraps driver failures in a DrizzleQueryError whose message is the SQL
2920
- * it was running — for a fresh database that is `CREATE SCHEMA IF NOT EXISTS
2921
- * "drizzle"`, the migrator's own bookkeeping statement. Reporting only that
2922
- * message blames a statement the user never wrote for what is usually an
2923
- * unreachable server (postgres-js reports `ECONNREFUSED` on `cause` and leaves
2924
- * that error's message empty) or a SQL error whose text also lives on `cause`.
2925
- *
2926
- * `endpoint` is included only as host:port — never the connection string, which
2927
- * carries credentials.
2213
+ * Names the actual problem behind a database failure: DrizzleQueryError's
2214
+ * message is the SQL it was running (on a fresh database the migrator's own
2215
+ * `CREATE SCHEMA`), while the real cause sits on `cause` (postgres-js puts
2216
+ * `ECONNREFUSED` there with an empty message). `endpoint` is host:port only,
2217
+ * never the connection string, which carries credentials.
2928
2218
  */
2929
2219
  function describeDatabaseFailure(error, endpoint) {
2930
2220
  const causes = collectCauses(error);
@@ -2959,19 +2249,14 @@ function describeConnectionEndpoint(connectionString) {
2959
2249
  return;
2960
2250
  }
2961
2251
  }
2962
- /**
2963
- * Lists drizzle-kit generated migrations (one folder per migration, each
2964
- * containing migration.sql), sorted the same way the drizzle migrator
2965
- * applies them.
2966
- */
2252
+ /** drizzle-kit migrations, sorted the way the drizzle migrator applies them. */
2967
2253
  function listLocalMigrations(migrationsFolder) {
2968
2254
  if (!existsSync(migrationsFolder)) return [];
2969
2255
  return readdirSync(migrationsFolder, { withFileTypes: true }).filter((entry) => entry.isDirectory() && existsSync(resolve(migrationsFolder, entry.name, "migration.sql"))).map((entry) => ({ name: entry.name })).sort((a, b) => a.name.localeCompare(b.name));
2970
2256
  }
2971
2257
  /**
2972
- * Joins local migration folders with the rows the drizzle migrator recorded
2973
- * in its tracker table. Drizzle itself decides pending migrations by name
2974
- * membership, so status uses the same rule.
2258
+ * Joins local migration folders with the migrator's tracker rows. Drizzle
2259
+ * decides pending migrations by name membership, so status uses that rule.
2975
2260
  */
2976
2261
  function buildMigrationStatus(localMigrations, appliedRows) {
2977
2262
  const appliedByName = /* @__PURE__ */ new Map();
@@ -3036,11 +2321,7 @@ async function loadSeederModule(path) {
3036
2321
  if (handler) return handler;
3037
2322
  }
3038
2323
  }
3039
- /**
3040
- * One read of the seeders folder: the handlers it yielded, and the files that
3041
- * yielded none. Kept together because they come from the same listing — the
3042
- * skipped count cannot be recovered from the handler array alone.
3043
- */
2324
+ /** One read of the folder: the handlers it yielded, and the files that yielded none. */
3044
2325
  async function collectSeeders(directory) {
3045
2326
  const root = directory instanceof URL ? fileURLToPath(directory) : resolve(directory);
3046
2327
  let entries;
@@ -3067,9 +2348,8 @@ async function collectSeeders(directory) {
3067
2348
  };
3068
2349
  }
3069
2350
  /**
3070
- * Seeders are loaded as modules, so the dialect they were written against is
3071
- * unknowable here. `TDatabase` is the caller stating which database it will
3072
- * hand them — the same contract `runSeeders()` fulfils from the driver side.
2351
+ * Seeders load as modules, so their dialect is unknowable here: `TDatabase` is
2352
+ * the caller stating which database it will hand them.
3073
2353
  */
3074
2354
  async function loadSeeders(directory) {
3075
2355
  return (await collectSeeders(directory)).seeders;
@@ -3241,8 +2521,8 @@ function createPostgresDatabase(options) {
3241
2521
  };
3242
2522
  });
3243
2523
  } catch (error) {
3244
- if (isConnectionFailure(error)) throw error;
3245
- return [];
2524
+ if (isMissingTrackerTable(error, "postgres")) return [];
2525
+ throw error;
3246
2526
  }
3247
2527
  }));
3248
2528
  }
@@ -3398,8 +2678,8 @@ function createMySqlDatabase(options) {
3398
2678
  appliedAt: row.applied_at
3399
2679
  }));
3400
2680
  } catch (error) {
3401
- if (isConnectionFailure(error)) throw error;
3402
- return [];
2681
+ if (isMissingTrackerTable(error, "mysql")) return [];
2682
+ throw error;
3403
2683
  }
3404
2684
  }));
3405
2685
  }
@@ -3424,31 +2704,11 @@ function isInMemory(dbPath) {
3424
2704
  return dbPath === ":memory:" || dbPath === "" || dbPath.startsWith("file::memory:");
3425
2705
  }
3426
2706
  /**
3427
- * The filesystem path to open for `dbPath`, or undefined when there is no file
3428
- * to name — the in-memory forms, and the URIs this cannot resolve.
3429
- *
3430
- * `file:` is sqlite's own URI scheme, so `file://…` names a *file* and not a
3431
- * server — which is why the connection-URI guard below lets every form of it
3432
- * through. What it is not is a path: handed to `resolve()` it is taken as a
3433
- * relative name, so the `mkdir -p` below used to prepare a `file:/…` tree under
3434
- * the cwd.
3435
- *
3436
- * **Whether the host's sqlite would have parsed it is not knowable from here,
3437
- * which is why the driver parses it itself and opens the plain path.** URI
3438
- * filenames are a compile-time option (`SQLITE_USE_URI`), and the two builds
3439
- * Guren runs on disagree: measured, Bun on macOS goes through the system
3440
- * libsqlite3, which has it on, while Bun's own Linux build has it off and takes
3441
- * `file:local.db` as a filename that literally starts with `file:`. The stray
3442
- * tree was therefore not the same defect on both — empty on macOS, holding the
3443
- * actual database on Linux. Resolving here is what makes one filename mean one
3444
- * file on every host.
3445
- *
3446
- * The rules are sqlite's (https://sqlite.org/uri.html), not the WHATWG URL
3447
- * parser's — `new URL('file:local.db')` resolves to `/local.db`, an absolute
3448
- * path at the filesystem root, where sqlite resolves it against the cwd.
3449
- * A URI sqlite itself rejects (an authority that is neither empty nor
3450
- * `localhost`) resolves to undefined, and the original string is handed to
3451
- * `new Database()` to be refused there, with no directory created on the way.
2707
+ * Path to open for `dbPath`; undefined for in-memory forms and unresolvable
2708
+ * URIs, which `new Database()` refuses with no directory created. `file:` URI
2709
+ * support is compile-time `SQLITE_USE_URI` (measured: on for Bun/macOS via system
2710
+ * libsqlite3, off in Bun's Linux build, which opens `file:local.db` literally), so
2711
+ * parsing follows https://sqlite.org/uri.html, not WHATWG (`/local.db` vs the cwd).
3452
2712
  */
3453
2713
  function sqliteFilePath(dbPath) {
3454
2714
  if (isInMemory(dbPath)) return void 0;
@@ -3473,29 +2733,17 @@ function sqliteFilePath(dbPath) {
3473
2733
  }
3474
2734
  /**
3475
2735
  * A scheme *with an authority* — the `//` is what separates a connection URI
3476
- * from a filename — for every scheme that could name a database server.
3477
- *
3478
- * Two exclusions keep legal filenames out of it. `file:` is sqlite's own URI
3479
- * scheme and never addresses a server, so all of its forms stay legal, the
3480
- * authority-shaped `file:///absolute/path.db` included. And the scheme must be
3481
- * at least two characters: no registered scheme is one letter, while `C://db`
3482
- * is a Windows drive path whose separator merely got doubled.
3483
- *
3484
- * Everything without a scheme is untouched — `:memory:`, `file::memory:`,
3485
- * `file:local.db`, and every relative and absolute path.
2736
+ * from a filename. Two exclusions keep legal filenames out: `file:` never
2737
+ * addresses a server, so every form of it stays legal; and a one-letter scheme
2738
+ * is `C://db`, a Windows drive path with a doubled separator.
3486
2739
  */
3487
2740
  const CONNECTION_URI = /^(?!file:)[a-z][a-z0-9+.-]+:\/\//i;
3488
2741
  /**
3489
- * This driver `mkdir -p`s the filename's directory, which is what makes a
3490
- * connection string dangerous rather than merely wrong: `postgres://u:pw@host/db`
3491
- * does not fail, it *succeeds* — creating a `postgres:/u:pw@host/db` tree and
3492
- * migrating into a database nobody ever reads, while `db:migrate` and
3493
- * `db:status` agree with each other on that stray file. Rejecting before the
3494
- * mkdir is the difference between a stop and a silent success.
3495
- *
3496
- * The likeliest source is an ambient `DATABASE_URL` that a sqlite app never
3497
- * meant to consume — the resolved value is checked, not the option, so the
3498
- * env fallback below is covered too.
2742
+ * This driver `mkdir -p`s the filename's directory, so `postgres://u:pw@host/db`
2743
+ * does not fail but *succeeds*: it creates a `postgres:/u:pw@host/db` tree and
2744
+ * migrates into a database nobody reads. Rejecting before the mkdir is the
2745
+ * difference between a stop and a silent success. The resolved value is
2746
+ * checked, not the option, so an ambient `DATABASE_URL` is covered too.
3499
2747
  */
3500
2748
  function assertNotConnectionUri(dbPath, source) {
3501
2749
  if (!CONNECTION_URI.test(dbPath)) return;
@@ -3601,7 +2849,9 @@ function createSqliteDatabase(options) {
3601
2849
  name: row.name,
3602
2850
  appliedAt: row.applied_at
3603
2851
  }));
3604
- } catch {}
2852
+ } catch (error) {
2853
+ if (!isMissingTrackerTable(error, "sqlite")) throw error;
2854
+ }
3605
2855
  return buildMigrationStatus(localMigrations, appliedRows);
3606
2856
  },
3607
2857
  async configureOrm() {
@@ -3624,8 +2874,8 @@ function createSqliteDatabase(options) {
3624
2874
  //#region src/d1.ts
3625
2875
  /**
3626
2876
  * Cloudflare D1 database factory. D1 speaks the SQLite dialect, so schemas
3627
- * written for `createSqliteDatabase` port unchanged; only the connection and
3628
- * the migration workflow differ (wrangler owns migrations, see RFC 0003).
2877
+ * written for `createSqliteDatabase` port unchanged; wrangler owns migrations
2878
+ * (RFC 0003).
3629
2879
  */
3630
2880
  function createD1Database(options) {
3631
2881
  const { binding, migrationsFolder, relations } = options;
@@ -3796,12 +3046,6 @@ function createAwsDataApiDatabase(options) {
3796
3046
  migrationStatus
3797
3047
  };
3798
3048
  }
3799
- /**
3800
- * Whether a query failure means the drizzle tracker table (or its schema) has
3801
- * not been created yet. The Data API surfaces Postgres errors as message text
3802
- * (e.g. `relation "drizzle.__drizzle_migrations" does not exist`), so the
3803
- * undefined-table condition is matched there.
3804
- */
3805
3049
  function isMissingTrackerTableError(error) {
3806
3050
  const message = error instanceof Error ? error.message : String(error);
3807
3051
  return /does not exist/i.test(message) && /drizzle|__drizzle_migrations|schema/i.test(message);