@guren/orm 2.6.2 → 2.6.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +228 -1174
- package/dist/index.js +242 -1094
- 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
|
-
*
|
|
11
|
-
*
|
|
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,11 @@ else {
|
|
|
36
29
|
//#endregion
|
|
37
30
|
//#region src/where-conditions.ts
|
|
38
31
|
/**
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
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
|
+
* Folds a builder's condition list into one node, or null when it holds
|
|
33
|
+
* nothing renderable. An OR group folds everything before it into the OR, so
|
|
34
|
+
* `.where(a).where(b).orWhere(c)` reads `(a AND b) OR c`. The one
|
|
35
|
+
* implementation of that fold: the Drizzle renderer applies it to the
|
|
36
|
+
* top-level list, QueryBuilder to a grouping callback's, so they cannot drift.
|
|
50
37
|
*/
|
|
51
38
|
function normalizeConditionSequence(conditions) {
|
|
52
39
|
let pending = [];
|
|
@@ -81,9 +68,6 @@ function resolveColumn(table, field) {
|
|
|
81
68
|
if (!column) throw new Error(`DrizzleConditions: unknown column "${field}" on provided table.`);
|
|
82
69
|
return column;
|
|
83
70
|
}
|
|
84
|
-
/**
|
|
85
|
-
* Builds a Drizzle ORM condition from a single SimpleCondition.
|
|
86
|
-
*/
|
|
87
71
|
function buildSimpleCondition(table, condition) {
|
|
88
72
|
const column = resolveColumn(table, condition.field);
|
|
89
73
|
switch (condition.operator) {
|
|
@@ -105,9 +89,6 @@ function buildSimpleCondition(table, condition) {
|
|
|
105
89
|
default: throw new Error(`DrizzleConditions: unsupported operator "${condition.operator}".`);
|
|
106
90
|
}
|
|
107
91
|
}
|
|
108
|
-
/**
|
|
109
|
-
* Builds a Drizzle ORM condition from a GroupCondition.
|
|
110
|
-
*/
|
|
111
92
|
function buildGroupCondition(table, group) {
|
|
112
93
|
const parts = group.conditions.map((c) => buildSingleCondition(table, c)).filter((c) => c !== void 0);
|
|
113
94
|
if (parts.length === 0) return;
|
|
@@ -115,27 +96,16 @@ function buildGroupCondition(table, group) {
|
|
|
115
96
|
if (group.boolean === "or") return or(...parts);
|
|
116
97
|
return and(...parts);
|
|
117
98
|
}
|
|
118
|
-
/**
|
|
119
|
-
* Builds a Drizzle ORM condition from any WhereCondition.
|
|
120
|
-
*/
|
|
121
99
|
function buildSingleCondition(table, condition) {
|
|
122
100
|
if (condition.type === "simple") return buildSimpleCondition(table, condition);
|
|
123
101
|
return buildGroupCondition(table, condition);
|
|
124
102
|
}
|
|
125
103
|
/**
|
|
126
|
-
* Translates an array of QueryBuilder WhereConditions into a single
|
|
127
|
-
*
|
|
128
|
-
*
|
|
129
|
-
*
|
|
130
|
-
*
|
|
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
|
|
104
|
+
* Translates an array of QueryBuilder WhereConditions into a single Drizzle ORM
|
|
105
|
+
* condition expression. The list's sequential semantics — an OR group folds
|
|
106
|
+
* everything before it into the OR, so `.where('a',1).where('b',2).orWhere('c',3)`
|
|
107
|
+
* is `(a = 1 AND b = 2) OR (c = 3)` — are already applied by
|
|
108
|
+
* `normalizeConditionSequence`, leaving a flat-join tree to render here.
|
|
139
109
|
*/
|
|
140
110
|
function buildDrizzleConditions(table, conditions) {
|
|
141
111
|
const normalized = normalizeConditionSequence(conditions);
|
|
@@ -206,11 +176,9 @@ function isPromiseLike(value) {
|
|
|
206
176
|
return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
|
|
207
177
|
}
|
|
208
178
|
/**
|
|
209
|
-
* Eagerly call `.returning()`
|
|
210
|
-
*
|
|
211
|
-
*
|
|
212
|
-
* `resolveMutation`'s `isPromiseLike` check would otherwise win
|
|
213
|
-
* before the `.returning()` check is reached.
|
|
179
|
+
* Eagerly call `.returning()` if available: bun-sqlite's query builders are
|
|
180
|
+
* thenable, so `resolveMutation`'s `isPromiseLike` check would otherwise win
|
|
181
|
+
* first and the driver would hand back a RunResult instead of rows.
|
|
214
182
|
*/
|
|
215
183
|
async function resolveWithReturning(query) {
|
|
216
184
|
if (query && typeof query === "object" && "returning" in query && typeof query.returning === "function") {
|
|
@@ -372,12 +340,7 @@ function applyMutators(data, mutators) {
|
|
|
372
340
|
}
|
|
373
341
|
//#endregion
|
|
374
342
|
//#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
|
-
*/
|
|
343
|
+
/** Registry for the named global scopes applied to every query on a model. */
|
|
381
344
|
var GlobalScopeRegistry = class GlobalScopeRegistry {
|
|
382
345
|
scopes = /* @__PURE__ */ new Map();
|
|
383
346
|
add(name, fn) {
|
|
@@ -392,7 +355,6 @@ var GlobalScopeRegistry = class GlobalScopeRegistry {
|
|
|
392
355
|
names() {
|
|
393
356
|
return Array.from(this.scopes.keys());
|
|
394
357
|
}
|
|
395
|
-
/** Apply all scopes (or all except excluded) to a query builder. */
|
|
396
358
|
apply(builder, except) {
|
|
397
359
|
for (const [name, fn] of this.scopes) {
|
|
398
360
|
if (except && except.includes(name)) continue;
|
|
@@ -404,12 +366,10 @@ var GlobalScopeRegistry = class GlobalScopeRegistry {
|
|
|
404
366
|
this.scopes.clear();
|
|
405
367
|
}
|
|
406
368
|
/**
|
|
407
|
-
*
|
|
408
|
-
*
|
|
409
|
-
*
|
|
410
|
-
*
|
|
411
|
-
* mixes in `SoftDeletes` and then adds a `tenant` scope silently loses the
|
|
412
|
-
* `softDelete` filter.
|
|
369
|
+
* A subclass registering its own scope needs a registry of its own, but must
|
|
370
|
+
* keep the inherited entries: starting from empty is how a model that mixes
|
|
371
|
+
* in `SoftDeletes` and then adds a `tenant` scope loses the `softDelete`
|
|
372
|
+
* filter.
|
|
413
373
|
*/
|
|
414
374
|
clone() {
|
|
415
375
|
const copy = new GlobalScopeRegistry();
|
|
@@ -422,24 +382,14 @@ var GlobalScopeRegistry = class GlobalScopeRegistry {
|
|
|
422
382
|
};
|
|
423
383
|
//#endregion
|
|
424
384
|
//#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
|
-
*/
|
|
385
|
+
/** Runs the hook if present; `false` means the operation should be aborted. */
|
|
433
386
|
async function executeHook(hooks, name, data) {
|
|
434
387
|
if (!hooks || typeof hooks[name] !== "function") return true;
|
|
435
388
|
return await hooks[name](data) !== false;
|
|
436
389
|
}
|
|
437
390
|
//#endregion
|
|
438
391
|
//#region src/ModelObserver.ts
|
|
439
|
-
/**
|
|
440
|
-
* Execute all registered observers for a given hook.
|
|
441
|
-
* Returns false if any observer aborts the operation.
|
|
442
|
-
*/
|
|
392
|
+
/** Returns false as soon as an observer aborts the operation. */
|
|
443
393
|
async function executeObservers(observers, name, data) {
|
|
444
394
|
if (!observers || observers.length === 0) return true;
|
|
445
395
|
for (const observer of observers) {
|
|
@@ -453,10 +403,8 @@ async function executeObservers(observers, name, data) {
|
|
|
453
403
|
//#endregion
|
|
454
404
|
//#region src/ModelNotFoundException.ts
|
|
455
405
|
/**
|
|
456
|
-
*
|
|
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.
|
|
406
|
+
* Thrown by findOrFail/firstOrFail. Carries `statusCode` 404 so exception
|
|
407
|
+
* handlers can render it without coupling to the ORM package.
|
|
460
408
|
*/
|
|
461
409
|
var ModelNotFoundException = class extends Error {
|
|
462
410
|
statusCode = 404;
|
|
@@ -472,34 +420,16 @@ var ModelNotFoundException = class extends Error {
|
|
|
472
420
|
//#endregion
|
|
473
421
|
//#region src/QueryBuilder.ts
|
|
474
422
|
/**
|
|
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.
|
|
423
|
+
* Key for the prepared-payload update terminal. Exported for `Model` across
|
|
424
|
+
* the module boundary, but kept out of the package entry point.
|
|
479
425
|
*/
|
|
480
426
|
const PREPARED_UPDATE = Symbol("guren.orm.preparedUpdate");
|
|
481
427
|
/**
|
|
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()`.
|
|
428
|
+
* Fluent query builder for the Guren ORM. Thenable, so awaiting a builder
|
|
429
|
+
* resolves to the result of `get()`.
|
|
489
430
|
*
|
|
490
431
|
* @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
432
|
* const active = await User.where('active', true)
|
|
500
|
-
*
|
|
501
|
-
* // Pagination
|
|
502
|
-
* const page = await Post.where('status', 'published').paginate(1, 20)
|
|
503
433
|
*/
|
|
504
434
|
var QueryBuilder = class QueryBuilder {
|
|
505
435
|
conditions = [];
|
|
@@ -564,45 +494,23 @@ var QueryBuilder = class QueryBuilder {
|
|
|
564
494
|
});
|
|
565
495
|
return this;
|
|
566
496
|
}
|
|
567
|
-
/**
|
|
568
|
-
* Add a WHERE NULL condition.
|
|
569
|
-
* @param field - Column to check for NULL
|
|
570
|
-
*/
|
|
571
497
|
whereNull(field) {
|
|
572
498
|
this.addSimpleCondition(field, "is null", null);
|
|
573
499
|
return this;
|
|
574
500
|
}
|
|
575
|
-
/**
|
|
576
|
-
* Add a WHERE NOT NULL condition.
|
|
577
|
-
* @param field - Column to check for NOT NULL
|
|
578
|
-
*/
|
|
579
501
|
whereNotNull(field) {
|
|
580
502
|
this.addSimpleCondition(field, "is not null", null);
|
|
581
503
|
return this;
|
|
582
504
|
}
|
|
583
|
-
/**
|
|
584
|
-
* Add a WHERE IN condition.
|
|
585
|
-
* @param field - Column to check
|
|
586
|
-
* @param values - Array of values to match against
|
|
587
|
-
*/
|
|
588
505
|
whereIn(field, values) {
|
|
589
506
|
this.addSimpleCondition(field, "in", values);
|
|
590
507
|
return this;
|
|
591
508
|
}
|
|
592
|
-
/**
|
|
593
|
-
* Add a WHERE NOT IN condition.
|
|
594
|
-
* @param field - Column to check
|
|
595
|
-
* @param values - Array of values to exclude
|
|
596
|
-
*/
|
|
597
509
|
whereNotIn(field, values) {
|
|
598
510
|
this.addSimpleCondition(field, "not in", values);
|
|
599
511
|
return this;
|
|
600
512
|
}
|
|
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
|
-
*/
|
|
513
|
+
/** Can be called multiple times to sort by multiple columns. */
|
|
606
514
|
orderBy(field, direction = "asc") {
|
|
607
515
|
this.options.orderBy.push({
|
|
608
516
|
column: field,
|
|
@@ -610,42 +518,19 @@ var QueryBuilder = class QueryBuilder {
|
|
|
610
518
|
});
|
|
611
519
|
return this;
|
|
612
520
|
}
|
|
613
|
-
/**
|
|
614
|
-
* Set the maximum number of records to return.
|
|
615
|
-
* @param n - Maximum record count
|
|
616
|
-
*/
|
|
617
521
|
limit(n) {
|
|
618
522
|
this.options.limitValue = n;
|
|
619
523
|
return this;
|
|
620
524
|
}
|
|
621
|
-
/**
|
|
622
|
-
* Set the number of records to skip.
|
|
623
|
-
* @param n - Number of records to skip
|
|
624
|
-
*/
|
|
625
525
|
offset(n) {
|
|
626
526
|
this.options.offsetValue = n;
|
|
627
527
|
return this;
|
|
628
528
|
}
|
|
629
|
-
/**
|
|
630
|
-
* Limit the columns returned in the result.
|
|
631
|
-
* @param fields - Column names to select
|
|
632
|
-
*/
|
|
633
529
|
select(...fields) {
|
|
634
530
|
this.options.selectFields = [...fields];
|
|
635
531
|
return this;
|
|
636
532
|
}
|
|
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
|
-
*/
|
|
533
|
+
/** Apply a named query scope defined on the model. */
|
|
649
534
|
scope(name) {
|
|
650
535
|
const modelScopes = this.modelClass.scopes;
|
|
651
536
|
if (!modelScopes || typeof modelScopes[name] !== "function") throw new Error(`${this.modelClass.name}: unknown scope "${name}".`);
|
|
@@ -653,42 +538,11 @@ var QueryBuilder = class QueryBuilder {
|
|
|
653
538
|
return this;
|
|
654
539
|
}
|
|
655
540
|
/**
|
|
656
|
-
* Eager-load relationships
|
|
657
|
-
*
|
|
658
|
-
*
|
|
659
|
-
*
|
|
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()
|
|
541
|
+
* Eager-load relationships by name, dot path, or an object of constraint
|
|
542
|
+
* callbacks, each run after the foreign-key filter on exactly the level its key
|
|
543
|
+
* names. Pitfalls: a top-level `orWhere()` ORs against the foreign-key filter
|
|
544
|
+
* (group it); `select()` must keep the relation's key column or the relation is
|
|
545
|
+
* empty; `limit()` applies to the one batched query, not per parent record.
|
|
692
546
|
*/
|
|
693
547
|
with(...relations) {
|
|
694
548
|
for (const rel of relations) if (typeof rel === "string") {
|
|
@@ -699,18 +553,10 @@ var QueryBuilder = class QueryBuilder {
|
|
|
699
553
|
}
|
|
700
554
|
return this;
|
|
701
555
|
}
|
|
702
|
-
/**
|
|
703
|
-
* Execute the query and return all matching records.
|
|
704
|
-
* @returns Array of matching records
|
|
705
|
-
*/
|
|
706
556
|
async get() {
|
|
707
557
|
const results = await this.executeQuery();
|
|
708
558
|
return this.loadEagerRelations(results);
|
|
709
559
|
}
|
|
710
|
-
/**
|
|
711
|
-
* Execute the query and return the first matching record.
|
|
712
|
-
* @returns The first record or null
|
|
713
|
-
*/
|
|
714
560
|
async first() {
|
|
715
561
|
const prev = this.options.limitValue;
|
|
716
562
|
this.options.limitValue = 1;
|
|
@@ -720,20 +566,12 @@ var QueryBuilder = class QueryBuilder {
|
|
|
720
566
|
this.options.limitValue = prev;
|
|
721
567
|
}
|
|
722
568
|
}
|
|
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
|
-
*/
|
|
569
|
+
/** @throws ModelNotFoundException (404) if no record matches. */
|
|
728
570
|
async firstOrFail() {
|
|
729
571
|
const record = await this.first();
|
|
730
572
|
if (record === null) throw new ModelNotFoundException(this.modelClass.name);
|
|
731
573
|
return record;
|
|
732
574
|
}
|
|
733
|
-
/**
|
|
734
|
-
* Count the number of records matching the current conditions.
|
|
735
|
-
* @returns The count of matching records
|
|
736
|
-
*/
|
|
737
575
|
async count() {
|
|
738
576
|
if (typeof this.adapter.count === "function" && this.conditions.length === 0) return this.adapter.count(this.table, void 0, { trx: this.options.trx });
|
|
739
577
|
const advancedAdapter = this.adapter;
|
|
@@ -776,25 +614,16 @@ var QueryBuilder = class QueryBuilder {
|
|
|
776
614
|
};
|
|
777
615
|
}
|
|
778
616
|
/**
|
|
779
|
-
* Bulk update
|
|
780
|
-
*
|
|
781
|
-
*
|
|
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)
|
|
617
|
+
* Bulk update. Mass-assignment protection and persistence preparation
|
|
618
|
+
* (mutators, casts, `preparePersistencePayload`) apply exactly as in
|
|
619
|
+
* `Model.update()`; per-record hooks and observers are skipped by design.
|
|
791
620
|
*/
|
|
792
621
|
async update(data) {
|
|
793
622
|
return this.runBulkUpdate(data, true);
|
|
794
623
|
}
|
|
795
624
|
/**
|
|
796
|
-
* Bulk update bypassing mass-assignment protection.
|
|
797
|
-
*
|
|
625
|
+
* Bulk update bypassing mass-assignment protection. Trusted server-side data
|
|
626
|
+
* only, never raw request input.
|
|
798
627
|
*/
|
|
799
628
|
async forceUpdate(data) {
|
|
800
629
|
return this.runBulkUpdate(data, false);
|
|
@@ -806,17 +635,11 @@ var QueryBuilder = class QueryBuilder {
|
|
|
806
635
|
return this[PREPARED_UPDATE](payload);
|
|
807
636
|
}
|
|
808
637
|
/**
|
|
809
|
-
* Bulk update
|
|
810
|
-
*
|
|
811
|
-
*
|
|
812
|
-
*
|
|
813
|
-
*
|
|
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.
|
|
638
|
+
* Bulk update with an already-filtered, already-prepared payload, so
|
|
639
|
+
* `Model.update()` can borrow the builder's global-scope-carrying
|
|
640
|
+
* `conditions` without running mutators twice (double-hashing a hashed
|
|
641
|
+
* column). Symbol-keyed and never re-exported: a named public method here
|
|
642
|
+
* would be a supported way to bypass mass-assignment protection entirely.
|
|
820
643
|
*/
|
|
821
644
|
async [PREPARED_UPDATE](payload) {
|
|
822
645
|
if (!this.adapter.update) throw new Error("Configured adapter does not support update operations.");
|
|
@@ -826,10 +649,6 @@ var QueryBuilder = class QueryBuilder {
|
|
|
826
649
|
if (simpleWhere) return this.adapter.update(this.table, simpleWhere, payload, { trx: this.options.trx });
|
|
827
650
|
throw new Error("Advanced conditions require an adapter that supports updateAdvanced.");
|
|
828
651
|
}
|
|
829
|
-
/**
|
|
830
|
-
* Bulk delete records matching the current conditions.
|
|
831
|
-
* @returns Number of deleted records (adapter-dependent)
|
|
832
|
-
*/
|
|
833
652
|
async delete() {
|
|
834
653
|
if (!this.adapter.delete) throw new Error("Configured adapter does not support delete operations.");
|
|
835
654
|
const advancedAdapter = this.adapter;
|
|
@@ -838,35 +657,23 @@ var QueryBuilder = class QueryBuilder {
|
|
|
838
657
|
if (simpleWhere) return this.adapter.delete(this.table, simpleWhere, { trx: this.options.trx });
|
|
839
658
|
throw new Error("Advanced conditions require an adapter that supports deleteAdvanced.");
|
|
840
659
|
}
|
|
841
|
-
/**
|
|
842
|
-
* Makes QueryBuilder a thenable so it can be directly awaited.
|
|
843
|
-
* Resolves to the result of `get()`.
|
|
844
|
-
*/
|
|
660
|
+
/** Makes the builder awaitable, resolving to `get()`. */
|
|
845
661
|
then(onfulfilled, onrejected) {
|
|
846
662
|
return this.get().then(onfulfilled, onrejected);
|
|
847
663
|
}
|
|
848
|
-
/**
|
|
849
|
-
* Catch handler for the thenable interface.
|
|
850
|
-
*/
|
|
851
664
|
catch(onrejected) {
|
|
852
665
|
return this.get().catch(onrejected);
|
|
853
666
|
}
|
|
854
|
-
/** Get the internal conditions (used by adapters). */
|
|
855
667
|
getConditions() {
|
|
856
668
|
return this.conditions;
|
|
857
669
|
}
|
|
858
|
-
/** Get the internal query options (used by adapters). */
|
|
859
670
|
getOptions() {
|
|
860
671
|
return { ...this.options };
|
|
861
672
|
}
|
|
862
673
|
/**
|
|
863
|
-
*
|
|
864
|
-
*
|
|
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.
|
|
674
|
+
* The nested builder skips global scopes on purpose: the outer builder
|
|
675
|
+
* already carries them, and re-applying them inside every group would
|
|
676
|
+
* duplicate — or, inside an OR group, weaken — their filters.
|
|
870
677
|
*/
|
|
871
678
|
pushCallbackGroup(callback, boolean) {
|
|
872
679
|
const nested = new QueryBuilder(this.modelClass, { trx: this.options.trx });
|
|
@@ -905,11 +712,7 @@ var QueryBuilder = class QueryBuilder {
|
|
|
905
712
|
offset: this.options.offsetValue
|
|
906
713
|
}, { trx: this.options.trx });
|
|
907
714
|
}
|
|
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
|
-
*/
|
|
715
|
+
/** Null when the conditions are too complex for a basic adapter's WhereClause. */
|
|
913
716
|
toSimpleWhereClause() {
|
|
914
717
|
if (this.conditions.length === 0) return null;
|
|
915
718
|
const result = {};
|
|
@@ -925,17 +728,10 @@ var QueryBuilder = class QueryBuilder {
|
|
|
925
728
|
return result;
|
|
926
729
|
}
|
|
927
730
|
/**
|
|
928
|
-
*
|
|
929
|
-
*
|
|
930
|
-
*
|
|
931
|
-
*
|
|
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.
|
|
731
|
+
* Paths are delegated to Model.loadRelationsInto, which recurses the
|
|
732
|
+
* relation chain. The builder's `trx` goes with them: a relation read off
|
|
733
|
+
* the pool while its parents came from an open transaction gets a null
|
|
734
|
+
* relation back on Postgres/MySQL, the parents being uncommitted.
|
|
939
735
|
*/
|
|
940
736
|
loadEagerRelations = async (results) => {
|
|
941
737
|
if (this.eagerLoad.length === 0 || results.length === 0) return results;
|
|
@@ -946,11 +742,7 @@ var QueryBuilder = class QueryBuilder {
|
|
|
946
742
|
};
|
|
947
743
|
//#endregion
|
|
948
744
|
//#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
|
-
*/
|
|
745
|
+
/** Serializes a record for JSON output: appends, then visible/hidden filtering. */
|
|
954
746
|
function serializeRecord(record, options) {
|
|
955
747
|
let result = { ...record };
|
|
956
748
|
if (options.appends && options.accessors) {
|
|
@@ -970,16 +762,10 @@ function serializeRecords(records, options) {
|
|
|
970
762
|
//#endregion
|
|
971
763
|
//#region src/MassAssignmentException.ts
|
|
972
764
|
/**
|
|
973
|
-
* Thrown when mass assignment receives fields it must not write.
|
|
974
|
-
*
|
|
975
|
-
*
|
|
976
|
-
*
|
|
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.
|
|
765
|
+
* Thrown when mass assignment receives fields it must not write. Discarding
|
|
766
|
+
* them silently hides bugs and can mask injection attempts, so models throw.
|
|
767
|
+
* `reason` is `'not-fillable'` (outside the `fillable` allowlist) or
|
|
768
|
+
* `'denied'` (in `deniedFields()`, unassignable whatever `fillable` says).
|
|
983
769
|
*/
|
|
984
770
|
var MassAssignmentException = class extends Error {
|
|
985
771
|
model;
|
|
@@ -997,217 +783,77 @@ var MassAssignmentException = class extends Error {
|
|
|
997
783
|
}
|
|
998
784
|
};
|
|
999
785
|
/**
|
|
1000
|
-
* ActiveRecord-style base class for database models.
|
|
1001
|
-
*
|
|
1002
|
-
*
|
|
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')
|
|
786
|
+
* ActiveRecord-style base class for database models. Prefer `defineModel(table)`,
|
|
787
|
+
* which infers the type markers; extending `Model` directly means setting
|
|
788
|
+
* `static table` and redeclaring `recordType`/`createType` by hand.
|
|
1030
789
|
*/
|
|
1031
790
|
var Model = class Model {
|
|
1032
|
-
/** The ORM adapter used for database operations. */
|
|
1033
791
|
static ormAdapter = DrizzleAdapter;
|
|
1034
|
-
/** The database table (e.g., Drizzle table schema). */
|
|
1035
792
|
static table;
|
|
1036
793
|
/** Type marker for TypeScript inference. Set by `defineModel()`; when extending `Model` directly, redeclare as `declare static readonly recordType: YourRecordType`. */
|
|
1037
794
|
static recordType = void 0;
|
|
1038
795
|
/** Type marker for insert/update payload inference. Set by `defineModel()`; when extending `Model` directly, redeclare as `declare static readonly createType: YourCreateType`. */
|
|
1039
796
|
static createType = void 0;
|
|
1040
797
|
static relationDefinitions;
|
|
1041
|
-
/** Type marker for relation types. Define relation types here for type inference. */
|
|
1042
798
|
static relationTypes = {};
|
|
1043
799
|
/**
|
|
1044
|
-
*
|
|
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()
|
|
800
|
+
* Reusable query constraints, applied by name with
|
|
801
|
+
* `Post.scope('published').scope('popular')`.
|
|
1054
802
|
*/
|
|
1055
803
|
static scopes;
|
|
1056
804
|
/**
|
|
1057
|
-
*
|
|
1058
|
-
*
|
|
1059
|
-
*
|
|
1060
|
-
* @example
|
|
1061
|
-
* static defaultScope = (q: QueryBuilder<any>) => q.whereNull('deletedAt')
|
|
805
|
+
* Applied to every query on this model, and — unlike a named global scope —
|
|
806
|
+
* never removable with `withoutGlobalScope()`.
|
|
1062
807
|
*/
|
|
1063
808
|
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
|
-
*/
|
|
809
|
+
/** Lifecycle hooks firing around create, update and delete. */
|
|
1075
810
|
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
|
-
*/
|
|
811
|
+
/** Attribute casts, applied both on read and on write. */
|
|
1092
812
|
static casts;
|
|
1093
813
|
/**
|
|
1094
|
-
*
|
|
1095
|
-
*
|
|
1096
|
-
*
|
|
1097
|
-
*
|
|
1098
|
-
*
|
|
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
|
-
* }
|
|
814
|
+
* Mass-assignment allowlist. When set, any other key in `create()`/`update()`
|
|
815
|
+
* input throws a MassAssignmentException rather than being discarded, so
|
|
816
|
+
* bugs and injection attempts surface; `forceCreate()`/`forceUpdate()` are
|
|
817
|
+
* the trusted-data escape. Independent of it, `id` is always stripped and
|
|
818
|
+
* `deniedFields()` always throws.
|
|
1109
819
|
*/
|
|
1110
820
|
static fillable;
|
|
1111
821
|
/**
|
|
1112
|
-
* Fields that can never be mass-assigned,
|
|
1113
|
-
*
|
|
1114
|
-
* `AuthenticatableModel` contributes its
|
|
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.
|
|
822
|
+
* Fields that can never be mass-assigned, whatever `fillable` says. Resolved
|
|
823
|
+
* at call time so a subclass can derive them from its own configuration
|
|
824
|
+
* (`AuthenticatableModel` contributes its password-hash column).
|
|
1118
825
|
*/
|
|
1119
826
|
static deniedFields() {
|
|
1120
827
|
return [];
|
|
1121
828
|
}
|
|
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
|
-
*/
|
|
829
|
+
/** Computed attributes, applied after a record is read. */
|
|
1133
830
|
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
|
-
*/
|
|
831
|
+
/** Attribute transforms applied before persistence. */
|
|
1144
832
|
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
|
-
*/
|
|
833
|
+
/** Fields to exclude from serialization output. */
|
|
1153
834
|
static hidden;
|
|
1154
|
-
/**
|
|
1155
|
-
* Whitelist of fields to include in serialization output.
|
|
1156
|
-
* When set, only these fields appear. Takes precedence over `hidden`.
|
|
1157
|
-
*/
|
|
835
|
+
/** Serialization allowlist; takes precedence over `hidden`. */
|
|
1158
836
|
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
|
-
*/
|
|
837
|
+
/** Accessor names to add to serialization output. */
|
|
1168
838
|
static appends;
|
|
1169
|
-
/** Registered model observers. */
|
|
1170
839
|
static observers;
|
|
1171
|
-
/** Named global scopes registry. */
|
|
1172
840
|
static globalScopeRegistry;
|
|
1173
|
-
/**
|
|
1174
|
-
* Set a custom ORM adapter for this model.
|
|
1175
|
-
* @param adapter - The adapter to use
|
|
1176
|
-
*/
|
|
1177
841
|
static useAdapter(adapter) {
|
|
1178
842
|
this.ormAdapter = adapter;
|
|
1179
843
|
}
|
|
1180
|
-
/**
|
|
1181
|
-
* Get the current ORM adapter.
|
|
1182
|
-
* @returns The configured adapter
|
|
1183
|
-
*/
|
|
1184
844
|
static getAdapter() {
|
|
1185
845
|
return this.ormAdapter;
|
|
1186
846
|
}
|
|
1187
847
|
/**
|
|
1188
|
-
* Run operations inside a database transaction.
|
|
1189
|
-
*
|
|
1190
848
|
* @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
|
-
* })
|
|
849
|
+
* await User.transaction(async (trx) => User.create({ name: 'John' }, { trx }))
|
|
1195
850
|
*/
|
|
1196
851
|
static async transaction(callback) {
|
|
1197
852
|
const adapter = this.getAdapter();
|
|
1198
853
|
if (typeof adapter.transaction !== "function") throw new Error("Configured adapter does not support transactions.");
|
|
1199
854
|
return adapter.transaction((trx) => callback(trx, this.inTransaction(trx)));
|
|
1200
855
|
}
|
|
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
|
-
*/
|
|
856
|
+
/** A model scope that forwards `trx` to every query and write on it. */
|
|
1211
857
|
static inTransaction(trx) {
|
|
1212
858
|
const where = (fieldOrConditions, operatorOrValue, value) => {
|
|
1213
859
|
if (typeof fieldOrConditions === "function") return this.newQuery({ trx }).where(fieldOrConditions);
|
|
@@ -1229,35 +875,19 @@ var Model = class Model {
|
|
|
1229
875
|
paginate: (options) => this.paginate(options, { trx })
|
|
1230
876
|
};
|
|
1231
877
|
}
|
|
1232
|
-
/**
|
|
1233
|
-
* Register a model observer class.
|
|
1234
|
-
*
|
|
1235
|
-
* @example
|
|
1236
|
-
* User.observe(UserObserver)
|
|
1237
|
-
*/
|
|
1238
878
|
static observe(ObserverClass) {
|
|
1239
879
|
if (!Object.prototype.hasOwnProperty.call(this, "observers") || !this.observers) this.observers = [];
|
|
1240
880
|
this.observers.push(new ObserverClass());
|
|
1241
881
|
}
|
|
1242
|
-
/** Clear all registered observers. */
|
|
1243
882
|
static clearObservers() {
|
|
1244
883
|
this.observers = [];
|
|
1245
884
|
}
|
|
1246
885
|
/**
|
|
1247
|
-
* The registry this class may mutate,
|
|
1248
|
-
*
|
|
1249
|
-
*
|
|
1250
|
-
*
|
|
1251
|
-
*
|
|
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.
|
|
886
|
+
* The registry this class may mutate, created on first write and seeded from
|
|
887
|
+
* the inherited one: the read paths resolve it through the prototype chain,
|
|
888
|
+
* so starting empty would shadow and drop every inherited scope (SoftDeletes
|
|
889
|
+
* then `addGlobalScope('tenant')`). The copy is a snapshot — scopes added to
|
|
890
|
+
* the parent afterwards never reach the subclass.
|
|
1261
891
|
*/
|
|
1262
892
|
static getGlobalScopes() {
|
|
1263
893
|
if (!Object.prototype.hasOwnProperty.call(this, "globalScopeRegistry") || !this.globalScopeRegistry) {
|
|
@@ -1266,30 +896,16 @@ var Model = class Model {
|
|
|
1266
896
|
}
|
|
1267
897
|
return this.globalScopeRegistry;
|
|
1268
898
|
}
|
|
1269
|
-
/**
|
|
1270
|
-
* Register a named global scope.
|
|
1271
|
-
*
|
|
1272
|
-
* @example
|
|
1273
|
-
* User.addGlobalScope('active', (q) => q.where('active', true))
|
|
1274
|
-
*/
|
|
1275
899
|
static addGlobalScope(name, fn) {
|
|
1276
900
|
this.getGlobalScopes().add(name, fn);
|
|
1277
901
|
}
|
|
1278
|
-
/** Remove a named global scope. */
|
|
1279
902
|
static removeGlobalScope(name) {
|
|
1280
903
|
this.getGlobalScopes().remove(name);
|
|
1281
904
|
}
|
|
1282
905
|
/**
|
|
1283
|
-
*
|
|
1284
|
-
*
|
|
1285
|
-
*
|
|
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()
|
|
906
|
+
* Only *named* scopes can be excluded: `defaultScope` is re-applied whatever
|
|
907
|
+
* this is asked to drop, so a mixin whose filter must be opt-out-able has to
|
|
908
|
+
* register a named scope and nothing else.
|
|
1293
909
|
*/
|
|
1294
910
|
static withoutGlobalScope(...names) {
|
|
1295
911
|
const builder = new QueryBuilder(this);
|
|
@@ -1297,22 +913,11 @@ var Model = class Model {
|
|
|
1297
913
|
this.getGlobalScopes().apply(builder, names);
|
|
1298
914
|
return builder;
|
|
1299
915
|
}
|
|
1300
|
-
/**
|
|
1301
|
-
* Start a query with no global scopes applied (also skips defaultScope).
|
|
1302
|
-
*
|
|
1303
|
-
* @example
|
|
1304
|
-
* const all = await User.withoutGlobalScopes().get()
|
|
1305
|
-
*/
|
|
916
|
+
/** A query with no global scopes applied, `defaultScope` included. */
|
|
1306
917
|
static withoutGlobalScopes() {
|
|
1307
918
|
return new QueryBuilder(this);
|
|
1308
919
|
}
|
|
1309
|
-
/**
|
|
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)
|
|
1315
|
-
*/
|
|
920
|
+
/** Applies hidden/visible filtering, accessors and appends. */
|
|
1316
921
|
static serialize(record) {
|
|
1317
922
|
return serializeRecord(record, {
|
|
1318
923
|
hidden: this.hidden,
|
|
@@ -1321,12 +926,6 @@ var Model = class Model {
|
|
|
1321
926
|
accessors: this.accessors
|
|
1322
927
|
});
|
|
1323
928
|
}
|
|
1324
|
-
/**
|
|
1325
|
-
* Serialize an array of records.
|
|
1326
|
-
*
|
|
1327
|
-
* @example
|
|
1328
|
-
* const json = User.serializeMany(users)
|
|
1329
|
-
*/
|
|
1330
929
|
static serializeMany(records) {
|
|
1331
930
|
return serializeRecords(records, {
|
|
1332
931
|
hidden: this.hidden,
|
|
@@ -1335,12 +934,6 @@ var Model = class Model {
|
|
|
1335
934
|
accessors: this.accessors
|
|
1336
935
|
});
|
|
1337
936
|
}
|
|
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
937
|
static applyCasts(record) {
|
|
1345
938
|
const castDefs = this.casts;
|
|
1346
939
|
if (!castDefs) return record;
|
|
@@ -1370,10 +963,7 @@ var Model = class Model {
|
|
|
1370
963
|
}
|
|
1371
964
|
return result;
|
|
1372
965
|
}
|
|
1373
|
-
/**
|
|
1374
|
-
* Apply all read-time transforms: casts then accessors.
|
|
1375
|
-
* Used internally after fetching records from the database.
|
|
1376
|
-
*/
|
|
966
|
+
/** Read-time transforms, in order: casts then accessors. */
|
|
1377
967
|
static applyReadTransforms(record) {
|
|
1378
968
|
let result = record;
|
|
1379
969
|
if (this.casts) result = this.applyCasts(result);
|
|
@@ -1381,16 +971,9 @@ var Model = class Model {
|
|
|
1381
971
|
return result;
|
|
1382
972
|
}
|
|
1383
973
|
/**
|
|
1384
|
-
*
|
|
1385
|
-
*
|
|
1386
|
-
*
|
|
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
|
|
974
|
+
* In order: `deniedFields()` throws, checked on the raw input so no later
|
|
975
|
+
* rule can swallow them; `id` is stripped silently; then, with `fillable`
|
|
976
|
+
* set, anything outside it throws.
|
|
1394
977
|
*/
|
|
1395
978
|
static filterFillable(data) {
|
|
1396
979
|
const denied = this.deniedFields().filter((field) => field in data);
|
|
@@ -1450,14 +1033,6 @@ var Model = class Model {
|
|
|
1450
1033
|
if (!this.table) throw new Error(`${this.name}.table must be defined before using the model.`);
|
|
1451
1034
|
return this.table;
|
|
1452
1035
|
}
|
|
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
1036
|
static async all(queryOptions) {
|
|
1462
1037
|
if (this.hasScopes()) return this.newQuery(queryOptions).get();
|
|
1463
1038
|
const table = this.resolveTable();
|
|
@@ -1465,17 +1040,6 @@ var Model = class Model {
|
|
|
1465
1040
|
if (this.casts || this.accessors) return records.map((r) => this.applyReadTransforms(r));
|
|
1466
1041
|
return records;
|
|
1467
1042
|
}
|
|
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
1043
|
static async find(id, key = "id", queryOptions) {
|
|
1480
1044
|
if (this.hasScopes()) return this.newQuery(queryOptions).where(key, id).first();
|
|
1481
1045
|
const table = this.resolveTable();
|
|
@@ -1484,17 +1048,7 @@ var Model = class Model {
|
|
|
1484
1048
|
if (record && (this.casts || this.accessors)) return this.applyReadTransforms(record);
|
|
1485
1049
|
return record;
|
|
1486
1050
|
}
|
|
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
|
-
*/
|
|
1051
|
+
/** @throws ModelNotFoundException (404) when no record matches. */
|
|
1498
1052
|
static async findOrFail(id, key = "id", queryOptions) {
|
|
1499
1053
|
const record = await this.find(id, key, queryOptions);
|
|
1500
1054
|
if (record == null) throw new ModelNotFoundException(this.name, id, key);
|
|
@@ -1517,15 +1071,6 @@ var Model = class Model {
|
|
|
1517
1071
|
await this.loadRelationsInto([copy], relationList, queryOptions);
|
|
1518
1072
|
return copy;
|
|
1519
1073
|
}
|
|
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
1074
|
static async first(where, queryOptions) {
|
|
1530
1075
|
if (this.hasScopes()) {
|
|
1531
1076
|
const builder = this.newQuery(queryOptions).limit(1);
|
|
@@ -1547,58 +1092,21 @@ var Model = class Model {
|
|
|
1547
1092
|
if (arguments.length === 3) return builder.where(fieldOrConditions, operatorOrValue, value);
|
|
1548
1093
|
return builder.where(fieldOrConditions, operatorOrValue);
|
|
1549
1094
|
}
|
|
1550
|
-
/**
|
|
1551
|
-
* Start a fluent query with a WHERE NULL condition.
|
|
1552
|
-
* @param field - Column to check for NULL
|
|
1553
|
-
*/
|
|
1554
1095
|
static whereNull(field) {
|
|
1555
1096
|
return this.newQuery().whereNull(field);
|
|
1556
1097
|
}
|
|
1557
|
-
/**
|
|
1558
|
-
* Start a fluent query with a WHERE NOT NULL condition.
|
|
1559
|
-
* @param field - Column to check for NOT NULL
|
|
1560
|
-
*/
|
|
1561
1098
|
static whereNotNull(field) {
|
|
1562
1099
|
return this.newQuery().whereNotNull(field);
|
|
1563
1100
|
}
|
|
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
1101
|
static whereIn(field, values) {
|
|
1570
1102
|
return this.newQuery().whereIn(field, values);
|
|
1571
1103
|
}
|
|
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
1104
|
static whereNotIn(field, values) {
|
|
1578
1105
|
return this.newQuery().whereNotIn(field, values);
|
|
1579
1106
|
}
|
|
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
1107
|
static select(...fields) {
|
|
1588
1108
|
return this.newQuery().select(...fields);
|
|
1589
1109
|
}
|
|
1590
|
-
/**
|
|
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()
|
|
1601
|
-
*/
|
|
1602
1110
|
static newQuery(queryOptions) {
|
|
1603
1111
|
const builder = new QueryBuilder(this, queryOptions);
|
|
1604
1112
|
if (this.defaultScope) this.defaultScope(builder);
|
|
@@ -1606,35 +1114,19 @@ var Model = class Model {
|
|
|
1606
1114
|
if (registry && registry.size > 0) registry.apply(builder);
|
|
1607
1115
|
return builder;
|
|
1608
1116
|
}
|
|
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
|
-
*/
|
|
1117
|
+
/** No scopes applied — for soft-deleted records or bypassing global filters. */
|
|
1615
1118
|
static newQueryWithoutScopes(queryOptions) {
|
|
1616
1119
|
return new QueryBuilder(this, queryOptions);
|
|
1617
1120
|
}
|
|
1618
1121
|
/**
|
|
1619
|
-
* Whether this model carries a filter
|
|
1620
|
-
*
|
|
1621
|
-
*
|
|
1622
|
-
* whether they can take the fast path; anything that returns a QueryBuilder
|
|
1623
|
-
* goes through `newQuery()` unconditionally.
|
|
1122
|
+
* Whether this model carries a filter every query must apply. Checked by the
|
|
1123
|
+
* entry points that talk to the adapter directly, to decide whether they can
|
|
1124
|
+
* take the fast path.
|
|
1624
1125
|
*/
|
|
1625
1126
|
static hasScopes() {
|
|
1626
1127
|
return Boolean(this.defaultScope) || Boolean(this.globalScopeRegistry && this.globalScopeRegistry.size > 0);
|
|
1627
1128
|
}
|
|
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
|
-
*/
|
|
1129
|
+
/** Apply a scope defined in `static scopes`; chainable. */
|
|
1638
1130
|
static scope(name) {
|
|
1639
1131
|
const scopes = this.scopes;
|
|
1640
1132
|
if (!scopes || typeof scopes[name] !== "function") throw new Error(`${this.name}: unknown scope "${name}".`);
|
|
@@ -1642,20 +1134,8 @@ var Model = class Model {
|
|
|
1642
1134
|
return scopes[name](builder);
|
|
1643
1135
|
}
|
|
1644
1136
|
/**
|
|
1645
|
-
*
|
|
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')
|
|
1137
|
+
* One-to-many: `foreignKey` is on the related model, `localKey` on this one.
|
|
1138
|
+
* Declare in a `static {}` block; `name` is what `with()` takes.
|
|
1659
1139
|
*/
|
|
1660
1140
|
static hasMany(name, related, foreignKey, localKey) {
|
|
1661
1141
|
this.getRelationDefinitions().set(name, {
|
|
@@ -1667,20 +1147,8 @@ var Model = class Model {
|
|
|
1667
1147
|
});
|
|
1668
1148
|
}
|
|
1669
1149
|
/**
|
|
1670
|
-
*
|
|
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')
|
|
1150
|
+
* Many-to-one inverse: `foreignKey` is on *this* model, `ownerKey` on the
|
|
1151
|
+
* related one.
|
|
1684
1152
|
*/
|
|
1685
1153
|
static belongsTo(name, related, foreignKey, ownerKey) {
|
|
1686
1154
|
this.getRelationDefinitions().set(name, {
|
|
@@ -1692,20 +1160,7 @@ var Model = class Model {
|
|
|
1692
1160
|
});
|
|
1693
1161
|
}
|
|
1694
1162
|
/**
|
|
1695
|
-
*
|
|
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')
|
|
1163
|
+
* One-to-one: `foreignKey` is on the related model, `localKey` on this one.
|
|
1709
1164
|
*/
|
|
1710
1165
|
static hasOne(name, related, foreignKey, localKey) {
|
|
1711
1166
|
this.getRelationDefinitions().set(name, {
|
|
@@ -1717,23 +1172,11 @@ var Model = class Model {
|
|
|
1717
1172
|
});
|
|
1718
1173
|
}
|
|
1719
1174
|
/**
|
|
1720
|
-
*
|
|
1721
|
-
*
|
|
1722
|
-
*
|
|
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
|
-
*
|
|
1175
|
+
* Many-to-many through a pivot table. `foreignPivotKey`/`relatedPivotKey` are
|
|
1176
|
+
* both columns *on the pivot*, referencing this model and the related one;
|
|
1177
|
+
* `parentKey`/`relatedKey` are the local keys they point at.
|
|
1730
1178
|
* @example
|
|
1731
|
-
*
|
|
1732
|
-
* static {
|
|
1733
|
-
* this.belongsToMany('roles', Role, userRoles, 'userId', 'roleId', 'id', 'id')
|
|
1734
|
-
* }
|
|
1735
|
-
* }
|
|
1736
|
-
* // Later: User.with('roles')
|
|
1179
|
+
* this.belongsToMany('roles', Role, userRoles, 'userId', 'roleId', 'id', 'id')
|
|
1737
1180
|
*/
|
|
1738
1181
|
static belongsToMany(name, related, pivotTable, foreignPivotKey, relatedPivotKey, parentKey, relatedKey) {
|
|
1739
1182
|
this.getRelationDefinitions().set(name, {
|
|
@@ -1748,23 +1191,11 @@ var Model = class Model {
|
|
|
1748
1191
|
});
|
|
1749
1192
|
}
|
|
1750
1193
|
/**
|
|
1751
|
-
*
|
|
1752
|
-
*
|
|
1753
|
-
*
|
|
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
|
-
*
|
|
1194
|
+
* Has-many-through: `firstKey` is on the intermediate model referencing this
|
|
1195
|
+
* one, `secondKey` on the related model referencing the intermediate;
|
|
1196
|
+
* `localKey` and `secondLocalKey` are the keys they point at.
|
|
1761
1197
|
* @example
|
|
1762
|
-
*
|
|
1763
|
-
* static {
|
|
1764
|
-
* this.hasManyThrough('posts', Post, User, 'countryId', 'userId', 'id', 'id')
|
|
1765
|
-
* }
|
|
1766
|
-
* }
|
|
1767
|
-
* // Later: Country.with('posts')
|
|
1198
|
+
* this.hasManyThrough('posts', Post, User, 'countryId', 'userId', 'id', 'id')
|
|
1768
1199
|
*/
|
|
1769
1200
|
static hasManyThrough(name, related, through, firstKey, secondKey, localKey, secondLocalKey) {
|
|
1770
1201
|
this.getRelationDefinitions().set(name, {
|
|
@@ -1778,23 +1209,11 @@ var Model = class Model {
|
|
|
1778
1209
|
secondLocalKey: secondLocalKey ?? "id"
|
|
1779
1210
|
});
|
|
1780
1211
|
}
|
|
1781
|
-
/**
|
|
1782
|
-
* Map of type strings to model classes for polymorphic relationships.
|
|
1783
|
-
*
|
|
1784
|
-
* @example
|
|
1785
|
-
* Model.morphMap = { Post, Video }
|
|
1786
|
-
*/
|
|
1212
|
+
/** Type strings to model classes, e.g. `Model.morphMap = { Post, Video }`. */
|
|
1787
1213
|
static morphMap;
|
|
1788
1214
|
/**
|
|
1789
|
-
*
|
|
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')
|
|
1215
|
+
* Polymorphic one-to-many. `morphName` is the base of the column pair:
|
|
1216
|
+
* 'commentable' means commentableType + commentableId.
|
|
1798
1217
|
*/
|
|
1799
1218
|
static morphMany(name, related, morphName, localKey) {
|
|
1800
1219
|
this.getRelationDefinitions().set(name, {
|
|
@@ -1805,15 +1224,7 @@ var Model = class Model {
|
|
|
1805
1224
|
localKey: localKey ?? "id"
|
|
1806
1225
|
});
|
|
1807
1226
|
}
|
|
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
|
-
*/
|
|
1227
|
+
/** Inverse of a polymorphic relation; `morphName` bases the type/id columns. */
|
|
1817
1228
|
static morphTo(name, morphName) {
|
|
1818
1229
|
this.getRelationDefinitions().set(name, {
|
|
1819
1230
|
type: "morphTo",
|
|
@@ -1823,24 +1234,9 @@ var Model = class Model {
|
|
|
1823
1234
|
});
|
|
1824
1235
|
}
|
|
1825
1236
|
/**
|
|
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
1237
|
* @example
|
|
1833
|
-
* // Single column ascending
|
|
1834
1238
|
* 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' })
|
|
1239
|
+
* await User.orderBy([['lastName', 'asc'], ['firstName', 'asc']], { status: 'active' })
|
|
1844
1240
|
*/
|
|
1845
1241
|
static async orderBy(order, where, queryOptions) {
|
|
1846
1242
|
const orderBy = normalizeOrderBy(order);
|
|
@@ -1856,24 +1252,8 @@ var Model = class Model {
|
|
|
1856
1252
|
return this.getAdapter().findMany(table, options, queryOptions);
|
|
1857
1253
|
}
|
|
1858
1254
|
/**
|
|
1859
|
-
* Get paginated records.
|
|
1860
|
-
*
|
|
1861
|
-
* @param options - Pagination options
|
|
1862
|
-
* @returns Paginated result with data and metadata
|
|
1863
|
-
*
|
|
1864
1255
|
* @example
|
|
1865
|
-
*
|
|
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
|
-
* })
|
|
1256
|
+
* await User.paginate({ page: 2, perPage: 20, where: { status: 'active' } })
|
|
1877
1257
|
*/
|
|
1878
1258
|
static async paginate(options = {}, queryOptions) {
|
|
1879
1259
|
if (this.hasScopes()) {
|
|
@@ -1931,32 +1311,12 @@ var Model = class Model {
|
|
|
1931
1311
|
meta: result.meta
|
|
1932
1312
|
};
|
|
1933
1313
|
}
|
|
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
1314
|
static async create(data, writeOptions) {
|
|
1947
1315
|
return this.runCreate(data, writeOptions, true);
|
|
1948
1316
|
}
|
|
1949
1317
|
/**
|
|
1950
|
-
* Create
|
|
1951
|
-
*
|
|
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
|
-
* })
|
|
1318
|
+
* Create bypassing mass-assignment protection. Trusted server-side data only
|
|
1319
|
+
* (OAuth linking, seeders, system records), never raw request input.
|
|
1960
1320
|
*/
|
|
1961
1321
|
static async forceCreate(data, writeOptions) {
|
|
1962
1322
|
return this.runCreate(data, writeOptions, false);
|
|
@@ -1989,22 +1349,12 @@ var Model = class Model {
|
|
|
1989
1349
|
if (this.casts || this.accessors) return this.applyReadTransforms(result);
|
|
1990
1350
|
return result;
|
|
1991
1351
|
}
|
|
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
1352
|
static async update(where, data, writeOptions) {
|
|
2003
1353
|
return this.runUpdate(where, data, writeOptions, true);
|
|
2004
1354
|
}
|
|
2005
1355
|
/**
|
|
2006
|
-
* Update
|
|
2007
|
-
*
|
|
1356
|
+
* Update bypassing mass-assignment protection. Trusted server-side data only,
|
|
1357
|
+
* never raw request input.
|
|
2008
1358
|
*/
|
|
2009
1359
|
static async forceUpdate(where, data, writeOptions) {
|
|
2010
1360
|
return this.runUpdate(where, data, writeOptions, false);
|
|
@@ -2039,16 +1389,6 @@ var Model = class Model {
|
|
|
2039
1389
|
if (this.casts || this.accessors) return this.applyReadTransforms(result);
|
|
2040
1390
|
return result;
|
|
2041
1391
|
}
|
|
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
1392
|
static async delete(where, writeOptions) {
|
|
2053
1393
|
const table = this.resolveTable();
|
|
2054
1394
|
const adapter = this.getAdapter();
|
|
@@ -2068,20 +1408,8 @@ var Model = class Model {
|
|
|
2068
1408
|
return result;
|
|
2069
1409
|
}
|
|
2070
1410
|
/**
|
|
2071
|
-
*
|
|
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))
|
|
1411
|
+
* A raw Drizzle builder starting at `select().from(table)`. Carries no model
|
|
1412
|
+
* scopes, casts or accessors.
|
|
2085
1413
|
*/
|
|
2086
1414
|
static query(db) {
|
|
2087
1415
|
const table = this.resolveTable();
|
|
@@ -2162,15 +1490,10 @@ var Model = class Model {
|
|
|
2162
1490
|
}
|
|
2163
1491
|
}
|
|
2164
1492
|
/**
|
|
2165
|
-
* @internal Used by QueryBuilder for eager loading.
|
|
2166
|
-
*
|
|
2167
|
-
*
|
|
2168
|
-
*
|
|
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.
|
|
1493
|
+
* @internal Used by QueryBuilder for eager loading. Paths are grouped by head
|
|
1494
|
+
* segment so a shared relation loads once: the loaders assign fresh spread
|
|
1495
|
+
* copies, so a second pass over `posts` would replace the very rows the first
|
|
1496
|
+
* attached children to and only the last path would survive.
|
|
2174
1497
|
*/
|
|
2175
1498
|
static async loadRelationsInto(records, relationNames, queryOptions, constraints, pathPrefix = "") {
|
|
2176
1499
|
if (relationNames.length === 0) return;
|
|
@@ -2187,20 +1510,16 @@ var Model = class Model {
|
|
|
2187
1510
|
for (const [head, tails] of groups) await this.loadRelationLevel(records, head, tails, queryOptions, constraints, pathPrefix);
|
|
2188
1511
|
}
|
|
2189
1512
|
/**
|
|
2190
|
-
* @internal Public
|
|
2191
|
-
*
|
|
2192
|
-
* Internal callers should use {@link loadRelationsInto} instead.
|
|
1513
|
+
* @internal Public because generated code reaches it; internal callers should
|
|
1514
|
+
* use {@link loadRelationsInto}.
|
|
2193
1515
|
*/
|
|
2194
1516
|
static async loadRelationInto(records, relationName, queryOptions, constraints, pathPrefix = "") {
|
|
2195
1517
|
await this.loadRelationsInto(records, [relationName], queryOptions, constraints, pathPrefix);
|
|
2196
1518
|
}
|
|
2197
1519
|
/**
|
|
2198
|
-
*
|
|
2199
|
-
*
|
|
2200
|
-
*
|
|
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`.
|
|
1520
|
+
* `constraints` are keyed by the full path of the level each constrains, so
|
|
1521
|
+
* `pathPrefix` accumulates the path walked so far: at `posts.comments` the
|
|
1522
|
+
* leaf looks itself up under that whole key, not under `comments`.
|
|
2204
1523
|
*/
|
|
2205
1524
|
static async loadRelationLevel(records, head, tails, queryOptions, constraints, pathPrefix = "") {
|
|
2206
1525
|
const definition = this.getRelationDefinition(head);
|
|
@@ -2396,12 +1715,10 @@ var Model = class Model {
|
|
|
2396
1715
|
}
|
|
2397
1716
|
};
|
|
2398
1717
|
/**
|
|
2399
|
-
*
|
|
2400
|
-
*
|
|
2401
|
-
*
|
|
2402
|
-
*
|
|
2403
|
-
* full filter (morphMany, which groups on the morph id) must not rely on the
|
|
2404
|
-
* query alone to keep other rows out.
|
|
1718
|
+
* The callback runs with the foreign-key filter already on the builder, so a
|
|
1719
|
+
* `where()` narrows it and a top-level `orWhere()` widens it — a loader that
|
|
1720
|
+
* groups on something weaker than the full filter (morphMany, on the morph id)
|
|
1721
|
+
* must not rely on the query alone to keep other rows out.
|
|
2405
1722
|
*/
|
|
2406
1723
|
async function applyEagerConstraint(query, constraint) {
|
|
2407
1724
|
constraint?.(query);
|
|
@@ -2436,34 +1753,11 @@ async function resolveModelReference(reference) {
|
|
|
2436
1753
|
return await reference();
|
|
2437
1754
|
}
|
|
2438
1755
|
/**
|
|
2439
|
-
*
|
|
2440
|
-
*
|
|
2441
|
-
*
|
|
2442
|
-
*
|
|
2443
|
-
*
|
|
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
|
-
* }) {}
|
|
1756
|
+
* A table-backed model base class: `recordType`/`createType` inferred from the
|
|
1757
|
+
* table, `optionalOnCreate`/`requireOnCreate` reshaping the create payload without
|
|
1758
|
+
* a cast (`AuthenticatableModel` hashes a virtual `password` into `passwordHash`).
|
|
1759
|
+
* Allowlist statics passed as options are checked against the table's columns, so
|
|
1760
|
+
* a typo is a compile error; a `static` on the subclass shadows the option.
|
|
2467
1761
|
*/
|
|
2468
1762
|
function defineModel(table, options = {}) {
|
|
2469
1763
|
const BaseClass = options.base ?? Model;
|
|
@@ -2528,32 +1822,11 @@ function trashedScopedQuery(model, where) {
|
|
|
2528
1822
|
return withoutSoftDeleteScope(model).where(where);
|
|
2529
1823
|
}
|
|
2530
1824
|
/**
|
|
2531
|
-
* Mixin
|
|
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'.
|
|
1825
|
+
* Mixin where `delete()` sets `deletedAt` instead of removing the row, and a
|
|
1826
|
+
* global scope named 'softDelete' excludes those rows from every query.
|
|
2536
1827
|
*
|
|
2537
1828
|
* @example
|
|
2538
1829
|
* 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
1830
|
*/
|
|
2558
1831
|
function SoftDeletes(Base) {
|
|
2559
1832
|
const SoftDeleteModel = class extends Base {};
|
|
@@ -2587,12 +1860,9 @@ function SoftDeletes(Base) {
|
|
|
2587
1860
|
//#region src/active-connections.ts
|
|
2588
1861
|
const REGISTRY_KEY = Symbol.for("guren.orm.activeConnections");
|
|
2589
1862
|
/**
|
|
2590
|
-
*
|
|
2591
|
-
*
|
|
2592
|
-
*
|
|
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.
|
|
1863
|
+
* Awaiting the teardown is the back-pressure that keeps a burst of reloads from
|
|
1864
|
+
* stacking up connections, but it runs on the path to the first query after a
|
|
1865
|
+
* reload, so a socket that never finishes closing must not wedge the dev server.
|
|
2596
1866
|
*/
|
|
2597
1867
|
const TEARDOWN_TIMEOUT_MS = 5e3;
|
|
2598
1868
|
function getRegistry() {
|
|
@@ -2603,13 +1873,7 @@ function getRegistry() {
|
|
|
2603
1873
|
scope[REGISTRY_KEY] = registry;
|
|
2604
1874
|
return registry;
|
|
2605
1875
|
}
|
|
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
|
-
*/
|
|
1876
|
+
/** `bun --watch` restarts the process instead, so `--hot` is the only mode that leaks. */
|
|
2613
1877
|
function isHotReloadRuntime() {
|
|
2614
1878
|
return typeof process !== "undefined" && Array.isArray(process.execArgv) && process.execArgv.includes("--hot");
|
|
2615
1879
|
}
|
|
@@ -2627,15 +1891,10 @@ function isDigitAt(text, index) {
|
|
|
2627
1891
|
return code >= 48 && code <= 57;
|
|
2628
1892
|
}
|
|
2629
1893
|
/**
|
|
2630
|
-
* Where a frame's trailing `:line[:column]` may begin,
|
|
2631
|
-
* `(.+?):\d+(?::\d+)?`
|
|
2632
|
-
*
|
|
2633
|
-
*
|
|
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.
|
|
1894
|
+
* Where a frame's trailing `:line[:column]` may begin, `:line:column` split
|
|
1895
|
+
* first, in the order the lazy `(.+?):\d+(?::\d+)?` this replaces settled on
|
|
1896
|
+
* them. Walking the digits back from `end` finds both in one pass; the pattern
|
|
1897
|
+
* re-tested the suffix at every prefix length, which made it quadratic.
|
|
2639
1898
|
*/
|
|
2640
1899
|
function locationSplits(frame, end) {
|
|
2641
1900
|
let cursor = end;
|
|
@@ -2651,29 +1910,11 @@ function pathBefore(frame, from, splits) {
|
|
|
2651
1910
|
for (const split of splits) if (split > from) return frame.slice(from, split);
|
|
2652
1911
|
}
|
|
2653
1912
|
/**
|
|
2654
|
-
* The index of the `(`
|
|
2655
|
-
*
|
|
2656
|
-
*
|
|
2657
|
-
*
|
|
2658
|
-
*
|
|
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.
|
|
1913
|
+
* The index of the `(` matching the final `)` at `closeIndex`. Both a path and
|
|
1914
|
+
* the function name in front of it may contain `(`, so only depth tells the
|
|
1915
|
+
* outer pair apart; the leftmost `(` passed is the fallback for a location
|
|
1916
|
+
* holding an unmatched `)`. Compared by code: this runs over every character of
|
|
1917
|
+
* every frame. Twin of `packages/server/src/support/stack-frames.ts` — keep in step.
|
|
2677
1918
|
*/
|
|
2678
1919
|
function matchingOpenParen(frame, closeIndex) {
|
|
2679
1920
|
if (frame.charCodeAt(closeIndex) !== CLOSE_PAREN) return;
|
|
@@ -2692,29 +1933,10 @@ function matchingOpenParen(frame, closeIndex) {
|
|
|
2692
1933
|
}
|
|
2693
1934
|
/**
|
|
2694
1935
|
* The path a single stack frame points at, without its line and column.
|
|
2695
|
-
*
|
|
2696
|
-
*
|
|
2697
|
-
*
|
|
2698
|
-
*
|
|
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.
|
|
1936
|
+
* `at fn (/path/file.ts:1:2)` is tried first because its parens bound the path;
|
|
1937
|
+
* a whitespace-bounded rule would truncate `/Users/me/My Projects/app`. Both
|
|
1938
|
+
* shapes require a trailing `:line`, and a V8 `eval at ...` group is rejected:
|
|
1939
|
+
* keying on text that is not a path is worse than leaving the handle unkeyed.
|
|
2718
1940
|
*/
|
|
2719
1941
|
function parseFrameLocation(frame) {
|
|
2720
1942
|
const end = frame.trimEnd().length;
|
|
@@ -2739,17 +1961,11 @@ function parseFrameLocation(frame) {
|
|
|
2739
1961
|
return path !== void 0 && !LINE_TERMINATOR.test(path) ? path : void 0;
|
|
2740
1962
|
}
|
|
2741
1963
|
/**
|
|
2742
|
-
* Paths the engine reports for code
|
|
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
|
|
1964
|
+
* Paths the engine reports for code with no source location — a class field
|
|
1965
|
+
* initializer as `at new Owner (unknown:1:17)`, a built-in caller as
|
|
2747
1966
|
* `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.
|
|
1967
|
+
* and only this set rejects them. Twin in
|
|
1968
|
+
* `packages/server/src/hot-reload/hot-disposables.ts` — keep the two in step.
|
|
2753
1969
|
*/
|
|
2754
1970
|
const SYNTHETIC_FRAME_PATHS = /* @__PURE__ */ new Set([
|
|
2755
1971
|
"unknown",
|
|
@@ -2757,22 +1973,11 @@ const SYNTHETIC_FRAME_PATHS = /* @__PURE__ */ new Set([
|
|
|
2757
1973
|
"<anonymous>"
|
|
2758
1974
|
]);
|
|
2759
1975
|
/**
|
|
2760
|
-
* The file that called a `create*Database()` factory.
|
|
2761
|
-
*
|
|
2762
|
-
*
|
|
2763
|
-
*
|
|
2764
|
-
*
|
|
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.
|
|
1976
|
+
* The file that called a `create*Database()` factory. `stack` must come from an
|
|
1977
|
+
* `Error` constructed inside the factory: frame 0 is `Error`, 1 the factory, 2
|
|
1978
|
+
* the caller — or the first later frame naming a real file. A class field
|
|
1979
|
+
* initializer leaves no frame of its own, so a handle built there keys to
|
|
1980
|
+
* wherever `new` was written instead.
|
|
2776
1981
|
*/
|
|
2777
1982
|
function describeCallerFile(stack) {
|
|
2778
1983
|
for (const frame of stack?.split("\n").slice(2) ?? []) {
|
|
@@ -2807,16 +2012,10 @@ async function closeWithTimeout(teardown, timeoutMs) {
|
|
|
2807
2012
|
}
|
|
2808
2013
|
/**
|
|
2809
2014
|
* Records `teardown` as the active client for `key` and closes whichever client
|
|
2810
|
-
* held the slot before it.
|
|
2811
|
-
*
|
|
2812
|
-
*
|
|
2813
|
-
*
|
|
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.
|
|
2015
|
+
* held the slot before it. Claims on one key are serialized: without that, three
|
|
2016
|
+
* reloads inside the teardown window let the third close the second's client
|
|
2017
|
+
* mid-initialization, handing its caller an already-closed one. `timeoutMs` is
|
|
2018
|
+
* for tests; callers should leave it at the default.
|
|
2820
2019
|
*/
|
|
2821
2020
|
async function replaceActiveConnection(key, teardown, timeoutMs = TEARDOWN_TIMEOUT_MS) {
|
|
2822
2021
|
const registry = getRegistry();
|
|
@@ -2842,11 +2041,7 @@ function releaseActiveConnection(key, teardown) {
|
|
|
2842
2041
|
}
|
|
2843
2042
|
//#endregion
|
|
2844
2043
|
//#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
|
-
*/
|
|
2044
|
+
/** One directory listing answering both questions a run summary asks of it. */
|
|
2850
2045
|
function inspectMigrationsFolder(migrationsFolder) {
|
|
2851
2046
|
if (!existsSync(migrationsFolder)) return {
|
|
2852
2047
|
migrationsFolder,
|
|
@@ -2862,12 +2057,9 @@ function inspectMigrationsFolder(migrationsFolder) {
|
|
|
2862
2057
|
}
|
|
2863
2058
|
/**
|
|
2864
2059
|
* Reports a run that found nothing to apply, naming the loose .sql files if
|
|
2865
|
-
* that is why the folder looked empty
|
|
2866
|
-
*
|
|
2867
|
-
*
|
|
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.
|
|
2060
|
+
* that is why the folder looked empty. The names cost a second read, so it
|
|
2061
|
+
* only happens when there are some; a folder the migrator did run from is
|
|
2062
|
+
* never warned about, or the warning would fire on every app boot.
|
|
2871
2063
|
*/
|
|
2872
2064
|
function noMigrationsToRun(summary) {
|
|
2873
2065
|
if (summary.looseSqlFiles === 0) return summary;
|
|
@@ -2876,15 +2068,11 @@ function noMigrationsToRun(summary) {
|
|
|
2876
2068
|
return summary;
|
|
2877
2069
|
}
|
|
2878
2070
|
/**
|
|
2879
|
-
*
|
|
2880
|
-
*
|
|
2881
|
-
*
|
|
2882
|
-
*
|
|
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.
|
|
2071
|
+
* Codes meaning the server was never reached, so the statement drizzle was
|
|
2072
|
+
* sending is noise. Excludes mid-flight failures (ECONNRESET, EPIPE), where
|
|
2073
|
+
* the query text is the useful part. ETIMEDOUT is out for the same reason and
|
|
2074
|
+
* is caught instead by `syscall: 'connect'` below — mysql2 sets that on a
|
|
2075
|
+
* connect timeout but not on a read that times out mid-query.
|
|
2888
2076
|
*/
|
|
2889
2077
|
const PRE_CONNECTION_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
2890
2078
|
"CONNECT_TIMEOUT",
|
|
@@ -2900,31 +2088,37 @@ function failedWhileConnecting(error) {
|
|
|
2900
2088
|
if (typeof code !== "string" || code === "") return false;
|
|
2901
2089
|
return PRE_CONNECTION_ERROR_CODES.has(code) || syscall === "connect";
|
|
2902
2090
|
}
|
|
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
|
-
*/
|
|
2091
|
+
/** Collects the cause chain and AggregateError members, outwards-in. `seen` bounds self-referencing chains. */
|
|
2907
2092
|
function collectCauses(error, seen = /* @__PURE__ */ new Set()) {
|
|
2908
2093
|
if (error == null || typeof error !== "object" || seen.has(error)) return [];
|
|
2909
2094
|
seen.add(error);
|
|
2910
2095
|
return [error, ...[...Array.isArray(error.errors) ? error.errors : [], ..."cause" in error ? [error.cause] : []].flatMap((child) => collectCauses(child, seen))];
|
|
2911
2096
|
}
|
|
2912
|
-
/**
|
|
2913
|
-
|
|
2914
|
-
|
|
2097
|
+
/**
|
|
2098
|
+
* Each driver's own signal for "that table does not exist", read off the
|
|
2099
|
+
* driver error rather than the wrapper drizzle puts around it.
|
|
2100
|
+
*/
|
|
2101
|
+
const MISSING_TABLE = {
|
|
2102
|
+
postgres: (cause) => cause.code === "42P01",
|
|
2103
|
+
mysql: (cause) => cause.code === "ER_NO_SUCH_TABLE" || cause.errno === 1146,
|
|
2104
|
+
sqlite: (cause) => typeof cause.message === "string" && /no such table/i.test(cause.message)
|
|
2105
|
+
};
|
|
2106
|
+
/**
|
|
2107
|
+
* True when a query against the drizzle migration tracker failed because the
|
|
2108
|
+
* tracker table does not exist yet — the one failure `migrationStatus()` may
|
|
2109
|
+
* read as "nothing applied". Anything else (a denied SELECT, a tracker whose
|
|
2110
|
+
* columns drifted, a broken `drizzle` schema) has to surface: reported as
|
|
2111
|
+
* all-pending it invites a re-run of migrations that were applied.
|
|
2112
|
+
*/
|
|
2113
|
+
function isMissingTrackerTable(error, dialect) {
|
|
2114
|
+
return collectCauses(error).some(MISSING_TABLE[dialect]);
|
|
2915
2115
|
}
|
|
2916
2116
|
/**
|
|
2917
|
-
*
|
|
2918
|
-
*
|
|
2919
|
-
*
|
|
2920
|
-
*
|
|
2921
|
-
*
|
|
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.
|
|
2117
|
+
* Names the actual problem behind a database failure: DrizzleQueryError's
|
|
2118
|
+
* message is the SQL it was running (on a fresh database the migrator's own
|
|
2119
|
+
* `CREATE SCHEMA`), while the real cause sits on `cause` (postgres-js puts
|
|
2120
|
+
* `ECONNREFUSED` there with an empty message). `endpoint` is host:port only,
|
|
2121
|
+
* never the connection string, which carries credentials.
|
|
2928
2122
|
*/
|
|
2929
2123
|
function describeDatabaseFailure(error, endpoint) {
|
|
2930
2124
|
const causes = collectCauses(error);
|
|
@@ -2959,19 +2153,14 @@ function describeConnectionEndpoint(connectionString) {
|
|
|
2959
2153
|
return;
|
|
2960
2154
|
}
|
|
2961
2155
|
}
|
|
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
|
-
*/
|
|
2156
|
+
/** drizzle-kit migrations, sorted the way the drizzle migrator applies them. */
|
|
2967
2157
|
function listLocalMigrations(migrationsFolder) {
|
|
2968
2158
|
if (!existsSync(migrationsFolder)) return [];
|
|
2969
2159
|
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
2160
|
}
|
|
2971
2161
|
/**
|
|
2972
|
-
* Joins local migration folders with the
|
|
2973
|
-
*
|
|
2974
|
-
* membership, so status uses the same rule.
|
|
2162
|
+
* Joins local migration folders with the migrator's tracker rows. Drizzle
|
|
2163
|
+
* decides pending migrations by name membership, so status uses that rule.
|
|
2975
2164
|
*/
|
|
2976
2165
|
function buildMigrationStatus(localMigrations, appliedRows) {
|
|
2977
2166
|
const appliedByName = /* @__PURE__ */ new Map();
|
|
@@ -3036,11 +2225,7 @@ async function loadSeederModule(path) {
|
|
|
3036
2225
|
if (handler) return handler;
|
|
3037
2226
|
}
|
|
3038
2227
|
}
|
|
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
|
-
*/
|
|
2228
|
+
/** One read of the folder: the handlers it yielded, and the files that yielded none. */
|
|
3044
2229
|
async function collectSeeders(directory) {
|
|
3045
2230
|
const root = directory instanceof URL ? fileURLToPath(directory) : resolve(directory);
|
|
3046
2231
|
let entries;
|
|
@@ -3067,9 +2252,8 @@ async function collectSeeders(directory) {
|
|
|
3067
2252
|
};
|
|
3068
2253
|
}
|
|
3069
2254
|
/**
|
|
3070
|
-
* Seeders
|
|
3071
|
-
*
|
|
3072
|
-
* hand them — the same contract `runSeeders()` fulfils from the driver side.
|
|
2255
|
+
* Seeders load as modules, so their dialect is unknowable here: `TDatabase` is
|
|
2256
|
+
* the caller stating which database it will hand them.
|
|
3073
2257
|
*/
|
|
3074
2258
|
async function loadSeeders(directory) {
|
|
3075
2259
|
return (await collectSeeders(directory)).seeders;
|
|
@@ -3241,8 +2425,8 @@ function createPostgresDatabase(options) {
|
|
|
3241
2425
|
};
|
|
3242
2426
|
});
|
|
3243
2427
|
} catch (error) {
|
|
3244
|
-
if (
|
|
3245
|
-
|
|
2428
|
+
if (isMissingTrackerTable(error, "postgres")) return [];
|
|
2429
|
+
throw error;
|
|
3246
2430
|
}
|
|
3247
2431
|
}));
|
|
3248
2432
|
}
|
|
@@ -3398,8 +2582,8 @@ function createMySqlDatabase(options) {
|
|
|
3398
2582
|
appliedAt: row.applied_at
|
|
3399
2583
|
}));
|
|
3400
2584
|
} catch (error) {
|
|
3401
|
-
if (
|
|
3402
|
-
|
|
2585
|
+
if (isMissingTrackerTable(error, "mysql")) return [];
|
|
2586
|
+
throw error;
|
|
3403
2587
|
}
|
|
3404
2588
|
}));
|
|
3405
2589
|
}
|
|
@@ -3424,31 +2608,11 @@ function isInMemory(dbPath) {
|
|
|
3424
2608
|
return dbPath === ":memory:" || dbPath === "" || dbPath.startsWith("file::memory:");
|
|
3425
2609
|
}
|
|
3426
2610
|
/**
|
|
3427
|
-
*
|
|
3428
|
-
*
|
|
3429
|
-
*
|
|
3430
|
-
*
|
|
3431
|
-
*
|
|
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.
|
|
2611
|
+
* Path to open for `dbPath`; undefined for in-memory forms and unresolvable
|
|
2612
|
+
* URIs, which `new Database()` refuses with no directory created. `file:` URI
|
|
2613
|
+
* support is compile-time `SQLITE_USE_URI` (measured: on for Bun/macOS via system
|
|
2614
|
+
* libsqlite3, off in Bun's Linux build, which opens `file:local.db` literally), so
|
|
2615
|
+
* parsing follows https://sqlite.org/uri.html, not WHATWG (`/local.db` vs the cwd).
|
|
3452
2616
|
*/
|
|
3453
2617
|
function sqliteFilePath(dbPath) {
|
|
3454
2618
|
if (isInMemory(dbPath)) return void 0;
|
|
@@ -3473,29 +2637,17 @@ function sqliteFilePath(dbPath) {
|
|
|
3473
2637
|
}
|
|
3474
2638
|
/**
|
|
3475
2639
|
* A scheme *with an authority* — the `//` is what separates a connection URI
|
|
3476
|
-
* from a filename
|
|
3477
|
-
*
|
|
3478
|
-
*
|
|
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.
|
|
2640
|
+
* from a filename. Two exclusions keep legal filenames out: `file:` never
|
|
2641
|
+
* addresses a server, so every form of it stays legal; and a one-letter scheme
|
|
2642
|
+
* is `C://db`, a Windows drive path with a doubled separator.
|
|
3486
2643
|
*/
|
|
3487
2644
|
const CONNECTION_URI = /^(?!file:)[a-z][a-z0-9+.-]+:\/\//i;
|
|
3488
2645
|
/**
|
|
3489
|
-
* This driver `mkdir -p`s the filename's directory,
|
|
3490
|
-
*
|
|
3491
|
-
*
|
|
3492
|
-
*
|
|
3493
|
-
*
|
|
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.
|
|
2646
|
+
* This driver `mkdir -p`s the filename's directory, so `postgres://u:pw@host/db`
|
|
2647
|
+
* does not fail but *succeeds*: it creates a `postgres:/u:pw@host/db` tree and
|
|
2648
|
+
* migrates into a database nobody reads. Rejecting before the mkdir is the
|
|
2649
|
+
* difference between a stop and a silent success. The resolved value is
|
|
2650
|
+
* checked, not the option, so an ambient `DATABASE_URL` is covered too.
|
|
3499
2651
|
*/
|
|
3500
2652
|
function assertNotConnectionUri(dbPath, source) {
|
|
3501
2653
|
if (!CONNECTION_URI.test(dbPath)) return;
|
|
@@ -3601,7 +2753,9 @@ function createSqliteDatabase(options) {
|
|
|
3601
2753
|
name: row.name,
|
|
3602
2754
|
appliedAt: row.applied_at
|
|
3603
2755
|
}));
|
|
3604
|
-
} catch {
|
|
2756
|
+
} catch (error) {
|
|
2757
|
+
if (!isMissingTrackerTable(error, "sqlite")) throw error;
|
|
2758
|
+
}
|
|
3605
2759
|
return buildMigrationStatus(localMigrations, appliedRows);
|
|
3606
2760
|
},
|
|
3607
2761
|
async configureOrm() {
|
|
@@ -3624,8 +2778,8 @@ function createSqliteDatabase(options) {
|
|
|
3624
2778
|
//#region src/d1.ts
|
|
3625
2779
|
/**
|
|
3626
2780
|
* Cloudflare D1 database factory. D1 speaks the SQLite dialect, so schemas
|
|
3627
|
-
* written for `createSqliteDatabase` port unchanged;
|
|
3628
|
-
*
|
|
2781
|
+
* written for `createSqliteDatabase` port unchanged; wrangler owns migrations
|
|
2782
|
+
* (RFC 0003).
|
|
3629
2783
|
*/
|
|
3630
2784
|
function createD1Database(options) {
|
|
3631
2785
|
const { binding, migrationsFolder, relations } = options;
|
|
@@ -3796,12 +2950,6 @@ function createAwsDataApiDatabase(options) {
|
|
|
3796
2950
|
migrationStatus
|
|
3797
2951
|
};
|
|
3798
2952
|
}
|
|
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
2953
|
function isMissingTrackerTableError(error) {
|
|
3806
2954
|
const message = error instanceof Error ? error.message : String(error);
|
|
3807
2955
|
return /does not exist/i.test(message) && /drizzle|__drizzle_migrations|schema/i.test(message);
|