@guren/orm 2.3.0 → 2.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +122 -31
- package/dist/index.js +237 -119
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -45,6 +45,15 @@ interface GroupCondition {
|
|
|
45
45
|
}
|
|
46
46
|
/** A where condition - either simple or grouped. */
|
|
47
47
|
type WhereCondition = SimpleCondition | GroupCondition;
|
|
48
|
+
/**
|
|
49
|
+
* Callback receiving a nested builder to compose a parenthesized
|
|
50
|
+
* condition group, mirroring Laravel's `where(fn ($q) => ...)`.
|
|
51
|
+
*
|
|
52
|
+
* Only the conditions added on the nested builder are read back —
|
|
53
|
+
* ordering, limits, eager loads, and terminal calls made inside the
|
|
54
|
+
* callback are not part of the group.
|
|
55
|
+
*/
|
|
56
|
+
type WhereGroupCallback<TRecord extends PlainObject = PlainObject> = (query: QueryBuilder<TRecord>) => void;
|
|
48
57
|
/** Options carried by the QueryBuilder for query execution. */
|
|
49
58
|
interface QueryBuilderOptions {
|
|
50
59
|
orderBy: Array<{
|
|
@@ -56,6 +65,17 @@ interface QueryBuilderOptions {
|
|
|
56
65
|
selectFields?: readonly string[];
|
|
57
66
|
trx?: unknown;
|
|
58
67
|
}
|
|
68
|
+
/**
|
|
69
|
+
* A callback that further constrains the query used to fetch an eager-loaded
|
|
70
|
+
* relation. Registered through the object form of {@link QueryBuilder.with}.
|
|
71
|
+
*/
|
|
72
|
+
type EagerLoadConstraint = (q: QueryBuilder) => void;
|
|
73
|
+
/**
|
|
74
|
+
* Constraint callbacks keyed by the relation path they constrain. A key names
|
|
75
|
+
* the exact level it applies to: `posts` constrains the head, `posts.comments`
|
|
76
|
+
* constrains the leaf.
|
|
77
|
+
*/
|
|
78
|
+
type EagerLoadConstraints = ReadonlyMap<string, EagerLoadConstraint>;
|
|
59
79
|
/**
|
|
60
80
|
* Fluent query builder for the Guren ORM.
|
|
61
81
|
*
|
|
@@ -93,11 +113,19 @@ declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult ex
|
|
|
93
113
|
/**
|
|
94
114
|
* Add a where condition (AND).
|
|
95
115
|
*
|
|
96
|
-
* Supports
|
|
116
|
+
* Supports four calling signatures:
|
|
97
117
|
* - `where(field, value)` - equality check
|
|
98
118
|
* - `where(field, operator, value)` - comparison
|
|
99
119
|
* - `where(object)` - multiple equality conditions
|
|
120
|
+
* - `where(callback)` - parenthesized condition group, AND-ed with the rest
|
|
121
|
+
*
|
|
122
|
+
* @example
|
|
123
|
+
* // (title LIKE ? OR excerpt LIKE ?) AND published = true
|
|
124
|
+
* await Post.where((q) => {
|
|
125
|
+
* q.where('title', 'like', pattern).orWhere('excerpt', 'like', pattern)
|
|
126
|
+
* }).where('published', true)
|
|
100
127
|
*/
|
|
128
|
+
where(callback: WhereGroupCallback<TRecord>): this;
|
|
101
129
|
where<TKey extends FieldKey<TRecord>>(field: TKey, value: TRecord[TKey]): this;
|
|
102
130
|
where<TKey extends FieldKey<TRecord>>(field: TKey, operator: WhereOperator, value: unknown): this;
|
|
103
131
|
where(conditions: Partial<Record<FieldKey<TRecord>, unknown>>): this;
|
|
@@ -106,7 +134,10 @@ declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult ex
|
|
|
106
134
|
*
|
|
107
135
|
* Same overloads as `where()`, but joins with OR logic.
|
|
108
136
|
* Creates an OR group containing the new condition(s).
|
|
137
|
+
* With a callback, the group's conditions are parenthesized as a whole:
|
|
138
|
+
* `(preceding conditions) OR (callback group)`.
|
|
109
139
|
*/
|
|
140
|
+
orWhere(callback: WhereGroupCallback<TRecord>): this;
|
|
110
141
|
orWhere<TKey extends FieldKey<TRecord>>(field: TKey, value: TRecord[TKey]): this;
|
|
111
142
|
orWhere<TKey extends FieldKey<TRecord>>(field: TKey, operator: WhereOperator, value: unknown): this;
|
|
112
143
|
orWhere(conditions: Partial<Record<FieldKey<TRecord>, unknown>>): this;
|
|
@@ -172,6 +203,20 @@ declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult ex
|
|
|
172
203
|
* Supports string names, arrays, dot notation for nested relations,
|
|
173
204
|
* and constraint callbacks.
|
|
174
205
|
*
|
|
206
|
+
* A constraint callback receives the query builder used to fetch that
|
|
207
|
+
* relation, and runs after the foreign-key filter is already on it, so a
|
|
208
|
+
* `where()` narrows that filter. Each object key constrains exactly the
|
|
209
|
+
* level it names, in any order: `posts` constrains the head,
|
|
210
|
+
* `posts.comments` constrains the leaf and leaves `posts` unfiltered.
|
|
211
|
+
*
|
|
212
|
+
* Three things behave differently than they may look:
|
|
213
|
+
* - `orWhere()` at the top level of a callback *widens* the query rather
|
|
214
|
+
* than narrowing it, because it ORs against the foreign-key filter. Group
|
|
215
|
+
* it (`q.where((g) => g.where(...).orWhere(...))`) to keep it contained.
|
|
216
|
+
* - `select()` must include the column the relation is keyed on, or the
|
|
217
|
+
* loader cannot match rows back to their parent and the relation is empty.
|
|
218
|
+
* - `limit()` applies to the single batched query, not per parent record.
|
|
219
|
+
*
|
|
175
220
|
* @example
|
|
176
221
|
* // Simple
|
|
177
222
|
* await User.where('active', true).with('posts').get()
|
|
@@ -181,8 +226,16 @@ declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult ex
|
|
|
181
226
|
*
|
|
182
227
|
* // Nested (dot notation)
|
|
183
228
|
* await User.where('active', true).with('posts.comments').get()
|
|
229
|
+
*
|
|
230
|
+
* // Constrained
|
|
231
|
+
* await User.newQuery().with({ posts: (q) => q.where('published', true) }).get()
|
|
232
|
+
*
|
|
233
|
+
* // Constrained at both levels
|
|
234
|
+
* await User.newQuery()
|
|
235
|
+
* .with({ posts: (q) => q.where('published', true), 'posts.comments': (q) => q.orderBy('id') })
|
|
236
|
+
* .get()
|
|
184
237
|
*/
|
|
185
|
-
with(...relations: (string | Record<string,
|
|
238
|
+
with(...relations: (string | Record<string, EagerLoadConstraint>)[]): this;
|
|
186
239
|
/**
|
|
187
240
|
* Execute the query and return all matching records.
|
|
188
241
|
* @returns Array of matching records
|
|
@@ -272,6 +325,16 @@ declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult ex
|
|
|
272
325
|
getConditions(): WhereCondition[];
|
|
273
326
|
/** Get the internal query options (used by adapters). */
|
|
274
327
|
getOptions(): QueryBuilderOptions;
|
|
328
|
+
/**
|
|
329
|
+
* Run a grouping callback against a nested builder, fold the collected
|
|
330
|
+
* conditions into a single node, and push it joined by `boolean`.
|
|
331
|
+
*
|
|
332
|
+
* The nested builder intentionally skips global scopes (`defaultScope`,
|
|
333
|
+
* SoftDeletes): the outer builder already carries them, and re-applying
|
|
334
|
+
* them inside every group would duplicate — or, inside an OR group,
|
|
335
|
+
* weaken — their filters.
|
|
336
|
+
*/
|
|
337
|
+
private pushCallbackGroup;
|
|
275
338
|
private addSimpleCondition;
|
|
276
339
|
private executeQuery;
|
|
277
340
|
/**
|
|
@@ -283,8 +346,15 @@ declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult ex
|
|
|
283
346
|
/**
|
|
284
347
|
* Load eager relations onto fetched results.
|
|
285
348
|
* Supports dot notation for nested relations at any depth
|
|
286
|
-
* (e.g., 'posts.comments.author') — the
|
|
287
|
-
* Model.
|
|
349
|
+
* (e.g., 'posts.comments.author') — the paths are delegated to
|
|
350
|
+
* Model.loadRelationsInto, which recurses through the relation chain.
|
|
351
|
+
* Constraint callbacks registered by the object form of `with()` travel
|
|
352
|
+
* alongside, keyed by the path segment each one constrains.
|
|
353
|
+
*
|
|
354
|
+
* The builder's `trx` goes with it: a relation loaded for rows read inside
|
|
355
|
+
* a transaction has to be read on that same handle, or the parents come
|
|
356
|
+
* from the transaction and their children from the pool — which on
|
|
357
|
+
* Postgres/MySQL means uncommitted parents get a null relation back.
|
|
288
358
|
*/
|
|
289
359
|
private readonly loadEagerRelations;
|
|
290
360
|
}
|
|
@@ -886,7 +956,7 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
|
|
|
886
956
|
* const post = await Post.findWith(1, 'author')
|
|
887
957
|
* const post = await Post.findWith(1, ['author', 'tags'])
|
|
888
958
|
*/
|
|
889
|
-
static findWith<T extends typeof Model, K extends RelationPath<T>>(this: T, id: TRecordFor<T>[keyof TRecordFor<T> & string], relations: K | readonly K[], key?: keyof TRecordFor<T> & string): Promise<(TRecordFor<T> & RelationTypePick<T, K | readonly K[]>) | null>;
|
|
959
|
+
static findWith<T extends typeof Model, K extends RelationPath<T>>(this: T, id: TRecordFor<T>[keyof TRecordFor<T> & string], relations: K | readonly K[], key?: keyof TRecordFor<T> & string, queryOptions?: ModelQueryOptions): Promise<(TRecordFor<T> & RelationTypePick<T, K | readonly K[]>) | null>;
|
|
890
960
|
/**
|
|
891
961
|
* Find a record by primary key with eager-loaded relations, or throw.
|
|
892
962
|
*
|
|
@@ -901,7 +971,7 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
|
|
|
901
971
|
* const post = await Post.findWithOrFail(1, ['author', 'tags'])
|
|
902
972
|
* const post = await Post.findWithOrFail(1, 'comments.author') // nested
|
|
903
973
|
*/
|
|
904
|
-
static findWithOrFail<T extends typeof Model, K extends RelationPath<T>>(this: T, id: TRecordFor<T>[keyof TRecordFor<T> & string], relations: K | readonly K[], key?: keyof TRecordFor<T> & string): Promise<TRecordFor<T> & RelationTypePick<T, K | readonly K[]>>;
|
|
974
|
+
static findWithOrFail<T extends typeof Model, K extends RelationPath<T>>(this: T, id: TRecordFor<T>[keyof TRecordFor<T> & string], relations: K | readonly K[], key?: keyof TRecordFor<T> & string, queryOptions?: ModelQueryOptions): Promise<TRecordFor<T> & RelationTypePick<T, K | readonly K[]>>;
|
|
905
975
|
/**
|
|
906
976
|
* Get the first record matching the conditions.
|
|
907
977
|
*
|
|
@@ -934,6 +1004,7 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
|
|
|
934
1004
|
* .limit(10)
|
|
935
1005
|
* .get()
|
|
936
1006
|
*/
|
|
1007
|
+
static where<T extends typeof Model>(this: T, callback: WhereGroupCallback<TRecordFor<T>>): QueryBuilder<TRecordFor<T>>;
|
|
937
1008
|
static where<T extends typeof Model>(this: T, conditions: WhereClauseFor<T>): QueryBuilder<TRecordFor<T>>;
|
|
938
1009
|
static where<T extends typeof Model>(this: T, field: keyof TRecordFor<T> & string, value: unknown): QueryBuilder<TRecordFor<T>>;
|
|
939
1010
|
static where<T extends typeof Model>(this: T, field: keyof TRecordFor<T> & string, operator: WhereOperator, value: unknown): QueryBuilder<TRecordFor<T>>;
|
|
@@ -1180,7 +1251,7 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
|
|
|
1180
1251
|
* // result.data - Users with their posts loaded
|
|
1181
1252
|
* // result.meta - Pagination metadata
|
|
1182
1253
|
*/
|
|
1183
|
-
static withPaginate<T extends typeof Model, K extends RelationPath<T>>(this: T, relations: K | readonly K[], options?: PaginateOptions<TRecordFor<T
|
|
1254
|
+
static withPaginate<T extends typeof Model, K extends RelationPath<T>>(this: T, relations: K | readonly K[], options?: PaginateOptions<TRecordFor<T>>, queryOptions?: ModelQueryOptions): Promise<PaginatedResult<TRecordFor<T> & RelationTypePick<T, K | readonly K[]>>>;
|
|
1184
1255
|
/**
|
|
1185
1256
|
* Create a new record.
|
|
1186
1257
|
*
|
|
@@ -1278,7 +1349,7 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
|
|
|
1278
1349
|
* // Nested relations via dot notation
|
|
1279
1350
|
* const usersWithPostComments = await User.with('posts.comments')
|
|
1280
1351
|
*/
|
|
1281
|
-
static with<T extends typeof Model, K extends RelationPath<T>>(this: T, relations: K | readonly K[], where?: WhereClauseFor<T
|
|
1352
|
+
static with<T extends typeof Model, K extends RelationPath<T>>(this: T, relations: K | readonly K[], where?: WhereClauseFor<T>, queryOptions?: ModelQueryOptions): Promise<Array<TRecordFor<T> & RelationTypePick<T, K | readonly K[]>>>;
|
|
1282
1353
|
/**
|
|
1283
1354
|
* Fetch records with related record counts attached as `${name}Count`.
|
|
1284
1355
|
* Counts hasMany/hasOne/morphMany children per record without attaching
|
|
@@ -1288,21 +1359,43 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
|
|
|
1288
1359
|
* const users = await User.withCount('posts')
|
|
1289
1360
|
* users[0].postsCount // number
|
|
1290
1361
|
*/
|
|
1291
|
-
static withCount<T extends typeof Model, K extends RelationKey<T>>(this: T, relations: K | readonly K[], where?: WhereClauseFor<T
|
|
1362
|
+
static withCount<T extends typeof Model, K extends RelationKey<T>>(this: T, relations: K | readonly K[], where?: WhereClauseFor<T>, queryOptions?: ModelQueryOptions): Promise<Array<TRecordFor<T> & RelationCountPick<K | readonly K[]>>>;
|
|
1292
1363
|
/** @internal Attaches a `${name}Count` field for one relation. */
|
|
1293
|
-
protected static loadRelationCountInto<T extends typeof Model>(this: T, records: Array<PlainObject>, relationName: string): Promise<void>;
|
|
1364
|
+
protected static loadRelationCountInto<T extends typeof Model>(this: T, records: Array<PlainObject>, relationName: string, queryOptions?: ModelQueryOptions): Promise<void>;
|
|
1294
1365
|
/**
|
|
1295
1366
|
* @internal Used by QueryBuilder for eager loading.
|
|
1296
1367
|
* Supports nested paths with dot notation, e.g. `posts.comments`.
|
|
1368
|
+
*
|
|
1369
|
+
* Paths are grouped by their head segment so a relation shared by several
|
|
1370
|
+
* paths is loaded exactly once. Walking `posts.comments` and `posts.tags`
|
|
1371
|
+
* independently would load `posts` twice, and the loaders assign fresh
|
|
1372
|
+
* spread copies — so the second pass would replace the very row objects the
|
|
1373
|
+
* first had already attached children to, and only the last path would
|
|
1374
|
+
* survive.
|
|
1297
1375
|
*/
|
|
1298
|
-
static
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1376
|
+
static loadRelationsInto<T extends typeof Model>(this: T, records: Array<PlainObject>, relationNames: readonly string[], queryOptions?: ModelQueryOptions, constraints?: EagerLoadConstraints, pathPrefix?: string): Promise<void>;
|
|
1377
|
+
/**
|
|
1378
|
+
* @internal Public since it is reachable from generated code; kept for
|
|
1379
|
+
* backwards compatibility now that the eager loader walks whole path lists.
|
|
1380
|
+
* Internal callers should use {@link loadRelationsInto} instead.
|
|
1381
|
+
*/
|
|
1382
|
+
static loadRelationInto<T extends typeof Model>(this: T, records: Array<PlainObject>, relationName: string, queryOptions?: ModelQueryOptions, constraints?: EagerLoadConstraints, pathPrefix?: string): Promise<void>;
|
|
1383
|
+
/**
|
|
1384
|
+
* Load one relation level and recurse into the tails beneath it.
|
|
1385
|
+
*
|
|
1386
|
+
* `constraints` are keyed by the full path of the level each one constrains,
|
|
1387
|
+
* so `pathPrefix` accumulates the path walked so far as the recursion
|
|
1388
|
+
* descends: at `posts.comments` the leaf looks itself up under that whole
|
|
1389
|
+
* key, not under `comments`.
|
|
1390
|
+
*/
|
|
1391
|
+
protected static loadRelationLevel<T extends typeof Model>(this: T, records: Array<PlainObject>, head: string, tails: readonly string[], queryOptions?: ModelQueryOptions, constraints?: EagerLoadConstraints, pathPrefix?: string): Promise<void>;
|
|
1392
|
+
protected static loadHasMany(records: Array<PlainObject>, definition: HasManyRelationDefinition, queryOptions?: ModelQueryOptions, constraint?: EagerLoadConstraint): Promise<void>;
|
|
1393
|
+
protected static loadHasOne(records: Array<PlainObject>, definition: HasOneRelationDefinition, queryOptions?: ModelQueryOptions, constraint?: EagerLoadConstraint): Promise<void>;
|
|
1394
|
+
protected static loadBelongsTo(records: Array<PlainObject>, definition: BelongsToRelationDefinition, queryOptions?: ModelQueryOptions, constraint?: EagerLoadConstraint): Promise<void>;
|
|
1395
|
+
protected static loadBelongsToMany(records: Array<PlainObject>, definition: BelongsToManyRelationDefinition, queryOptions?: ModelQueryOptions, constraint?: EagerLoadConstraint): Promise<void>;
|
|
1396
|
+
protected static loadHasManyThrough(records: Array<PlainObject>, definition: HasManyThroughRelationDefinition, queryOptions?: ModelQueryOptions, constraint?: EagerLoadConstraint): Promise<void>;
|
|
1397
|
+
protected static loadMorphMany(records: Array<PlainObject>, definition: MorphManyRelationDefinition, queryOptions?: ModelQueryOptions, constraint?: EagerLoadConstraint): Promise<void>;
|
|
1398
|
+
protected static loadMorphTo(records: Array<PlainObject>, definition: MorphToRelationDefinition, queryOptions?: ModelQueryOptions, constraint?: EagerLoadConstraint): Promise<void>;
|
|
1306
1399
|
}
|
|
1307
1400
|
type TRecordFor<T extends typeof Model> = T extends {
|
|
1308
1401
|
recordType: infer R;
|
|
@@ -1332,6 +1425,7 @@ interface TransactionModelScope<T extends typeof Model> {
|
|
|
1332
1425
|
find(id: unknown): Promise<TRecordFor<T> | null>;
|
|
1333
1426
|
findOrFail(id: unknown): Promise<TRecordFor<T>>;
|
|
1334
1427
|
first(where?: WhereClauseFor<T>): Promise<TRecordFor<T> | null>;
|
|
1428
|
+
where(callback: WhereGroupCallback<TRecordFor<T>>): QueryBuilder<TRecordFor<T>>;
|
|
1335
1429
|
where(conditions: WhereClauseFor<T>): QueryBuilder<TRecordFor<T>>;
|
|
1336
1430
|
where(field: FieldFor<T>, value: unknown): QueryBuilder<TRecordFor<T>>;
|
|
1337
1431
|
where(field: FieldFor<T>, operator: WhereOperator, value: unknown): QueryBuilder<TRecordFor<T>>;
|
|
@@ -1653,15 +1747,12 @@ declare const DrizzleAdapter: ORMAdapterAdvanced & {
|
|
|
1653
1747
|
* Translates an array of QueryBuilder WhereConditions into a single
|
|
1654
1748
|
* Drizzle ORM condition expression.
|
|
1655
1749
|
*
|
|
1656
|
-
* The top-level conditions
|
|
1657
|
-
*
|
|
1658
|
-
*
|
|
1659
|
-
* When an OR group is encountered, it creates:
|
|
1660
|
-
* AND(previous_conditions, OR(previous_and_block, or_conditions))
|
|
1661
|
-
*
|
|
1662
|
-
* This matches the typical SQL builder behavior where:
|
|
1750
|
+
* The list's sequential semantics — top-level conditions AND together,
|
|
1751
|
+
* an OR group folds everything before it into the OR, so
|
|
1663
1752
|
* .where('a', 1).where('b', 2).orWhere('c', 3)
|
|
1664
|
-
* produces
|
|
1753
|
+
* produces `(a = 1 AND b = 2) OR (c = 3)` — are applied by
|
|
1754
|
+
* `normalizeConditionSequence` (shared with QueryBuilder's grouping
|
|
1755
|
+
* callbacks), leaving only a flat-join tree to render here.
|
|
1665
1756
|
*
|
|
1666
1757
|
* @param table - The Drizzle table object
|
|
1667
1758
|
* @param conditions - Array of WhereCondition objects from QueryBuilder
|
|
@@ -1694,7 +1785,7 @@ interface PostgresDatabase {
|
|
|
1694
1785
|
closeDatabase(): Promise<void>;
|
|
1695
1786
|
configureOrm(): Promise<void>;
|
|
1696
1787
|
seedDatabase(): Promise<void>;
|
|
1697
|
-
/** Drops the public schema (and the drizzle tracker schema)
|
|
1788
|
+
/** Drops the public schema (and the drizzle tracker schema), then re-applies migrations — same end state as `guren db:reset`. */
|
|
1698
1789
|
resetDatabase(): Promise<void>;
|
|
1699
1790
|
/** Per-migration applied state derived from the drizzle-kit journal and drizzle.__drizzle_migrations. */
|
|
1700
1791
|
migrationStatus(): Promise<MigrationStatusEntry[]>;
|
|
@@ -1721,7 +1812,7 @@ interface MySqlDatabase {
|
|
|
1721
1812
|
closeDatabase(): Promise<void>;
|
|
1722
1813
|
configureOrm(): Promise<void>;
|
|
1723
1814
|
seedDatabase(): Promise<void>;
|
|
1724
|
-
/** Drops every table and view (including the drizzle migration tracker)
|
|
1815
|
+
/** Drops every table and view (including the drizzle migration tracker), then re-applies migrations — same end state as `guren db:reset`. */
|
|
1725
1816
|
resetDatabase(): Promise<void>;
|
|
1726
1817
|
/** Per-migration applied state derived from the drizzle-kit journal and the __drizzle_migrations table. */
|
|
1727
1818
|
migrationStatus(): Promise<MigrationStatusEntry[]>;
|
|
@@ -1747,7 +1838,7 @@ interface SqliteDatabase {
|
|
|
1747
1838
|
closeDatabase(): Promise<void>;
|
|
1748
1839
|
configureOrm(): Promise<void>;
|
|
1749
1840
|
seedDatabase(): Promise<void>;
|
|
1750
|
-
/** Drops every table and view (including the drizzle migration tracker)
|
|
1841
|
+
/** Drops every table and view (including the drizzle migration tracker), then re-applies migrations — same end state as `guren db:reset`. */
|
|
1751
1842
|
resetDatabase(): Promise<void>;
|
|
1752
1843
|
/** Per-migration applied state derived from the drizzle-kit journal and the __drizzle_migrations table. */
|
|
1753
1844
|
migrationStatus(): Promise<MigrationStatusEntry[]>;
|
|
@@ -1828,7 +1919,7 @@ interface AwsDataApiDatabase {
|
|
|
1828
1919
|
closeDatabase(): Promise<void>;
|
|
1829
1920
|
configureOrm(): Promise<void>;
|
|
1830
1921
|
seedDatabase(): Promise<void>;
|
|
1831
|
-
/** Drops the public schema (and the drizzle tracker schema)
|
|
1922
|
+
/** Drops the public schema (and the drizzle tracker schema), then re-applies migrations — same end state as `guren db:reset`. */
|
|
1832
1923
|
resetDatabase(): Promise<void>;
|
|
1833
1924
|
/** Per-migration applied state derived from the drizzle-kit journal and drizzle.__drizzle_migrations. */
|
|
1834
1925
|
migrationStatus(): Promise<MigrationStatusEntry[]>;
|
|
@@ -1879,4 +1970,4 @@ declare function serializeRecord(record: PlainObject, options: {
|
|
|
1879
1970
|
/** Serialize an array of records. */
|
|
1880
1971
|
declare function serializeRecords(records: PlainObject[], options: Parameters<typeof serializeRecord>[1]): PlainObject[];
|
|
1881
1972
|
|
|
1882
|
-
export { type AccessorDefinitions, type AccessorFn, type AwsDataApiDatabase, type AwsDataApiDatabaseOptions, type AwsDataApiSeederContext, type BelongsToManyRecord, type BelongsToManyRelationResult, type BelongsToRecord, type BelongsToRelationResult, type BelongsToRequiredRecord, type CastType, type D1DatabaseHandle, type D1DatabaseOptions, DrizzleAdapter, type FindManyOptions, GlobalScopeRegistry, type GroupCondition, type HasManyRecord, type HasManyRelationResult, type HasManyThroughRecord, type HasManyThroughRelationResult, type HasOneRecord, type HasOneRelationResult, type HookCallback, type HookName, type InferModelInsert, type InferModelRecord, MassAssignmentException, type MigrationStatusEntry, Model, type ModelHooks, ModelNotFoundException, type ModelObserver, type ModelObserverConstructor, type ModelPaginationMeta, type MorphManyRecord, type MorphManyRelationResult, type MorphToRecord, type MorphToRelationResult, type MutatorDefinitions, type MutatorFn, type MySqlDatabase, type MySqlDatabaseOptions, type MySqlSeederContext, type ORMAdapter, type ORMAdapterAdvanced, type OrderByClause, type OrderByInput, type OrderDefinition, type OrderDirection, type PaginateOptions, type PaginatedResult, type PlainObject, type PostgresDatabase, type PostgresDatabaseOptions, type PostgresSeederContext, QueryBuilder, type QueryBuilderOptions, type ScopeFunction, type SeederContext, type SeederHandler, type SimpleCondition, SoftDeletes, type SoftDeletesStatic, type SqliteDatabase, type SqliteDatabaseOptions, type SqliteSeederContext, type TransactionHandle, type TransactionModelScope, type WhereClause, type WhereCondition, type WhereOperator, type WithRelations, applyAccessors, applyMutators, buildDrizzleConditions, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, executeHook, executeObservers, loadSeeders, runSeeders, serializeRecord, serializeRecords };
|
|
1973
|
+
export { type AccessorDefinitions, type AccessorFn, type AwsDataApiDatabase, type AwsDataApiDatabaseOptions, type AwsDataApiSeederContext, type BelongsToManyRecord, type BelongsToManyRelationResult, type BelongsToRecord, type BelongsToRelationResult, type BelongsToRequiredRecord, type CastType, type D1DatabaseHandle, type D1DatabaseOptions, DrizzleAdapter, type EagerLoadConstraint, type FindManyOptions, GlobalScopeRegistry, type GroupCondition, type HasManyRecord, type HasManyRelationResult, type HasManyThroughRecord, type HasManyThroughRelationResult, type HasOneRecord, type HasOneRelationResult, type HookCallback, type HookName, type InferModelInsert, type InferModelRecord, MassAssignmentException, type MigrationStatusEntry, Model, type ModelHooks, ModelNotFoundException, type ModelObserver, type ModelObserverConstructor, type ModelPaginationMeta, type ModelQueryOptions, type MorphManyRecord, type MorphManyRelationResult, type MorphToRecord, type MorphToRelationResult, type MutatorDefinitions, type MutatorFn, type MySqlDatabase, type MySqlDatabaseOptions, type MySqlSeederContext, type ORMAdapter, type ORMAdapterAdvanced, type OrderByClause, type OrderByInput, type OrderDefinition, type OrderDirection, type PaginateOptions, type PaginatedResult, type PlainObject, type PostgresDatabase, type PostgresDatabaseOptions, type PostgresSeederContext, QueryBuilder, type QueryBuilderOptions, type ScopeFunction, type SeederContext, type SeederHandler, type SimpleCondition, SoftDeletes, type SoftDeletesStatic, type SqliteDatabase, type SqliteDatabaseOptions, type SqliteSeederContext, type TransactionHandle, type TransactionModelScope, type WhereClause, type WhereCondition, type WhereGroupCallback, type WhereOperator, type WithRelations, applyAccessors, applyMutators, buildDrizzleConditions, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, executeHook, executeObservers, loadSeeders, runSeeders, serializeRecord, serializeRecords };
|
package/dist/index.js
CHANGED
|
@@ -21,6 +21,28 @@ import { and as and2, asc, count, desc, eq as eq2, inArray as inArray2, isNull a
|
|
|
21
21
|
|
|
22
22
|
// src/adapters/drizzle-conditions.ts
|
|
23
23
|
import { and, eq, gt, gte, inArray, isNotNull, isNull, like, lt, lte, ne, notInArray, or } from "drizzle-orm";
|
|
24
|
+
|
|
25
|
+
// src/where-conditions.ts
|
|
26
|
+
function normalizeConditionSequence(conditions) {
|
|
27
|
+
let pending = [];
|
|
28
|
+
for (const condition of conditions) {
|
|
29
|
+
if (!(condition.type === "group" && condition.boolean === "or")) {
|
|
30
|
+
pending.push(condition);
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
if (condition.conditions.length === 0) continue;
|
|
34
|
+
const andBlock = combine("and", pending);
|
|
35
|
+
pending = [combine("or", andBlock ? [andBlock, ...condition.conditions] : condition.conditions)];
|
|
36
|
+
}
|
|
37
|
+
return combine("and", pending);
|
|
38
|
+
}
|
|
39
|
+
function combine(boolean, parts) {
|
|
40
|
+
if (parts.length === 0) return null;
|
|
41
|
+
if (parts.length === 1) return parts[0];
|
|
42
|
+
return { type: "group", boolean, conditions: [...parts] };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// src/adapters/drizzle-conditions.ts
|
|
24
46
|
function resolveColumn(table, field) {
|
|
25
47
|
const tableRecord = table;
|
|
26
48
|
const column = tableRecord[field];
|
|
@@ -84,45 +106,8 @@ function buildSingleCondition(table, condition) {
|
|
|
84
106
|
return buildGroupCondition(table, condition);
|
|
85
107
|
}
|
|
86
108
|
function buildDrizzleConditions(table, conditions) {
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
}
|
|
90
|
-
let currentAnd = [];
|
|
91
|
-
let result;
|
|
92
|
-
for (const condition of conditions) {
|
|
93
|
-
if (condition.type === "group" && condition.boolean === "or") {
|
|
94
|
-
const orParts = condition.conditions.map((c) => buildSingleCondition(table, c)).filter((c) => c !== void 0);
|
|
95
|
-
if (orParts.length > 0) {
|
|
96
|
-
const andBlock = combineAnd(currentAnd, result);
|
|
97
|
-
if (andBlock) {
|
|
98
|
-
result = or(andBlock, ...orParts);
|
|
99
|
-
} else {
|
|
100
|
-
result = orParts.length === 1 ? orParts[0] : or(...orParts);
|
|
101
|
-
}
|
|
102
|
-
currentAnd = [];
|
|
103
|
-
}
|
|
104
|
-
} else {
|
|
105
|
-
const built = buildSingleCondition(table, condition);
|
|
106
|
-
if (built) {
|
|
107
|
-
currentAnd.push(built);
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
return combineAnd(currentAnd, result);
|
|
112
|
-
}
|
|
113
|
-
function combineAnd(andParts, existing) {
|
|
114
|
-
const all = [];
|
|
115
|
-
if (existing) {
|
|
116
|
-
all.push(existing);
|
|
117
|
-
}
|
|
118
|
-
all.push(...andParts);
|
|
119
|
-
if (all.length === 0) {
|
|
120
|
-
return void 0;
|
|
121
|
-
}
|
|
122
|
-
if (all.length === 1) {
|
|
123
|
-
return all[0];
|
|
124
|
-
}
|
|
125
|
-
return and(...all);
|
|
109
|
+
const normalized = normalizeConditionSequence(conditions);
|
|
110
|
+
return normalized ? buildSingleCondition(table, normalized) : void 0;
|
|
126
111
|
}
|
|
127
112
|
|
|
128
113
|
// src/adapters/drizzle-adapter.ts
|
|
@@ -519,7 +504,7 @@ var ModelNotFoundException = class extends Error {
|
|
|
519
504
|
|
|
520
505
|
// src/QueryBuilder.ts
|
|
521
506
|
var PREPARED_UPDATE = /* @__PURE__ */ Symbol("guren.orm.preparedUpdate");
|
|
522
|
-
var QueryBuilder = class {
|
|
507
|
+
var QueryBuilder = class _QueryBuilder {
|
|
523
508
|
conditions = [];
|
|
524
509
|
options = { orderBy: [] };
|
|
525
510
|
modelClass;
|
|
@@ -527,7 +512,6 @@ var QueryBuilder = class {
|
|
|
527
512
|
adapter;
|
|
528
513
|
eagerLoad = [];
|
|
529
514
|
eagerLoadConstraints = /* @__PURE__ */ new Map();
|
|
530
|
-
// eslint-disable-line @typescript-eslint/no-explicit-any
|
|
531
515
|
constructor(modelClass, options = {}) {
|
|
532
516
|
this.modelClass = modelClass;
|
|
533
517
|
this.table = modelClass.resolveTable();
|
|
@@ -535,6 +519,10 @@ var QueryBuilder = class {
|
|
|
535
519
|
this.options.trx = options.trx;
|
|
536
520
|
}
|
|
537
521
|
where(fieldOrConditions, operatorOrValue, value) {
|
|
522
|
+
if (typeof fieldOrConditions === "function") {
|
|
523
|
+
this.pushCallbackGroup(fieldOrConditions, "and");
|
|
524
|
+
return this;
|
|
525
|
+
}
|
|
538
526
|
if (typeof fieldOrConditions === "object" && fieldOrConditions !== null) {
|
|
539
527
|
for (const [key, val] of Object.entries(fieldOrConditions)) {
|
|
540
528
|
if (val !== void 0) {
|
|
@@ -552,6 +540,10 @@ var QueryBuilder = class {
|
|
|
552
540
|
return this;
|
|
553
541
|
}
|
|
554
542
|
orWhere(fieldOrConditions, operatorOrValue, value) {
|
|
543
|
+
if (typeof fieldOrConditions === "function") {
|
|
544
|
+
this.pushCallbackGroup(fieldOrConditions, "or");
|
|
545
|
+
return this;
|
|
546
|
+
}
|
|
555
547
|
const orConditions = [];
|
|
556
548
|
if (typeof fieldOrConditions === "object" && fieldOrConditions !== null) {
|
|
557
549
|
for (const [key, val] of Object.entries(fieldOrConditions)) {
|
|
@@ -674,6 +666,20 @@ var QueryBuilder = class {
|
|
|
674
666
|
* Supports string names, arrays, dot notation for nested relations,
|
|
675
667
|
* and constraint callbacks.
|
|
676
668
|
*
|
|
669
|
+
* A constraint callback receives the query builder used to fetch that
|
|
670
|
+
* relation, and runs after the foreign-key filter is already on it, so a
|
|
671
|
+
* `where()` narrows that filter. Each object key constrains exactly the
|
|
672
|
+
* level it names, in any order: `posts` constrains the head,
|
|
673
|
+
* `posts.comments` constrains the leaf and leaves `posts` unfiltered.
|
|
674
|
+
*
|
|
675
|
+
* Three things behave differently than they may look:
|
|
676
|
+
* - `orWhere()` at the top level of a callback *widens* the query rather
|
|
677
|
+
* than narrowing it, because it ORs against the foreign-key filter. Group
|
|
678
|
+
* it (`q.where((g) => g.where(...).orWhere(...))`) to keep it contained.
|
|
679
|
+
* - `select()` must include the column the relation is keyed on, or the
|
|
680
|
+
* loader cannot match rows back to their parent and the relation is empty.
|
|
681
|
+
* - `limit()` applies to the single batched query, not per parent record.
|
|
682
|
+
*
|
|
677
683
|
* @example
|
|
678
684
|
* // Simple
|
|
679
685
|
* await User.where('active', true).with('posts').get()
|
|
@@ -683,6 +689,14 @@ var QueryBuilder = class {
|
|
|
683
689
|
*
|
|
684
690
|
* // Nested (dot notation)
|
|
685
691
|
* await User.where('active', true).with('posts.comments').get()
|
|
692
|
+
*
|
|
693
|
+
* // Constrained
|
|
694
|
+
* await User.newQuery().with({ posts: (q) => q.where('published', true) }).get()
|
|
695
|
+
*
|
|
696
|
+
* // Constrained at both levels
|
|
697
|
+
* await User.newQuery()
|
|
698
|
+
* .with({ posts: (q) => q.where('published', true), 'posts.comments': (q) => q.orderBy('id') })
|
|
699
|
+
* .get()
|
|
686
700
|
*/
|
|
687
701
|
with(...relations) {
|
|
688
702
|
for (const rel of relations) {
|
|
@@ -715,11 +729,12 @@ var QueryBuilder = class {
|
|
|
715
729
|
async first() {
|
|
716
730
|
const prev = this.options.limitValue;
|
|
717
731
|
this.options.limitValue = 1;
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
732
|
+
try {
|
|
733
|
+
const results = await this.get();
|
|
734
|
+
return results[0] ?? null;
|
|
735
|
+
} finally {
|
|
736
|
+
this.options.limitValue = prev;
|
|
737
|
+
}
|
|
723
738
|
}
|
|
724
739
|
/**
|
|
725
740
|
* Execute the query and return the first matching record, or throw.
|
|
@@ -761,9 +776,13 @@ var QueryBuilder = class {
|
|
|
761
776
|
const prevOffset = this.options.offsetValue;
|
|
762
777
|
this.options.limitValue = sanitizedPerPage;
|
|
763
778
|
this.options.offsetValue = offset;
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
779
|
+
let data;
|
|
780
|
+
try {
|
|
781
|
+
data = await this.get();
|
|
782
|
+
} finally {
|
|
783
|
+
this.options.limitValue = prevLimit;
|
|
784
|
+
this.options.offsetValue = prevOffset;
|
|
785
|
+
}
|
|
767
786
|
const from = total === 0 ? 0 : offset + 1;
|
|
768
787
|
const to = total === 0 ? 0 : offset + data.length;
|
|
769
788
|
const meta = {
|
|
@@ -879,6 +898,23 @@ var QueryBuilder = class {
|
|
|
879
898
|
getOptions() {
|
|
880
899
|
return { ...this.options };
|
|
881
900
|
}
|
|
901
|
+
/**
|
|
902
|
+
* Run a grouping callback against a nested builder, fold the collected
|
|
903
|
+
* conditions into a single node, and push it joined by `boolean`.
|
|
904
|
+
*
|
|
905
|
+
* The nested builder intentionally skips global scopes (`defaultScope`,
|
|
906
|
+
* SoftDeletes): the outer builder already carries them, and re-applying
|
|
907
|
+
* them inside every group would duplicate — or, inside an OR group,
|
|
908
|
+
* weaken — their filters.
|
|
909
|
+
*/
|
|
910
|
+
pushCallbackGroup(callback, boolean) {
|
|
911
|
+
const nested = new _QueryBuilder(this.modelClass, { trx: this.options.trx });
|
|
912
|
+
callback(nested);
|
|
913
|
+
const grouped = normalizeConditionSequence(nested.conditions);
|
|
914
|
+
if (!grouped) return;
|
|
915
|
+
const needsWrap = boolean === "or" || grouped.type === "group" && grouped.boolean === "or";
|
|
916
|
+
this.conditions.push(needsWrap ? { type: "group", boolean, conditions: [grouped] } : grouped);
|
|
917
|
+
}
|
|
882
918
|
addSimpleCondition(field, operator, value) {
|
|
883
919
|
this.conditions.push({
|
|
884
920
|
type: "simple",
|
|
@@ -942,16 +978,25 @@ var QueryBuilder = class {
|
|
|
942
978
|
/**
|
|
943
979
|
* Load eager relations onto fetched results.
|
|
944
980
|
* Supports dot notation for nested relations at any depth
|
|
945
|
-
* (e.g., 'posts.comments.author') — the
|
|
946
|
-
* Model.
|
|
981
|
+
* (e.g., 'posts.comments.author') — the paths are delegated to
|
|
982
|
+
* Model.loadRelationsInto, which recurses through the relation chain.
|
|
983
|
+
* Constraint callbacks registered by the object form of `with()` travel
|
|
984
|
+
* alongside, keyed by the path segment each one constrains.
|
|
985
|
+
*
|
|
986
|
+
* The builder's `trx` goes with it: a relation loaded for rows read inside
|
|
987
|
+
* a transaction has to be read on that same handle, or the parents come
|
|
988
|
+
* from the transaction and their children from the pool — which on
|
|
989
|
+
* Postgres/MySQL means uncommitted parents get a null relation back.
|
|
947
990
|
*/
|
|
948
991
|
loadEagerRelations = async (results) => {
|
|
949
992
|
if (this.eagerLoad.length === 0 || results.length === 0) return results;
|
|
950
993
|
const copies = results.map((r) => ({ ...r }));
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
994
|
+
await this.modelClass.loadRelationsInto(
|
|
995
|
+
copies,
|
|
996
|
+
this.eagerLoad,
|
|
997
|
+
{ trx: this.options.trx },
|
|
998
|
+
this.eagerLoadConstraints
|
|
999
|
+
);
|
|
955
1000
|
return copies;
|
|
956
1001
|
};
|
|
957
1002
|
};
|
|
@@ -1190,6 +1235,9 @@ var Model = class _Model {
|
|
|
1190
1235
|
*/
|
|
1191
1236
|
static inTransaction(trx) {
|
|
1192
1237
|
const where = (fieldOrConditions, operatorOrValue, value) => {
|
|
1238
|
+
if (typeof fieldOrConditions === "function") {
|
|
1239
|
+
return this.newQuery({ trx }).where(fieldOrConditions);
|
|
1240
|
+
}
|
|
1193
1241
|
if (typeof fieldOrConditions === "object" && fieldOrConditions !== null) {
|
|
1194
1242
|
return this.newQuery({ trx }).where(fieldOrConditions);
|
|
1195
1243
|
}
|
|
@@ -1559,29 +1607,25 @@ var Model = class _Model {
|
|
|
1559
1607
|
}
|
|
1560
1608
|
return record;
|
|
1561
1609
|
}
|
|
1562
|
-
static async findWith(id, relations, key) {
|
|
1563
|
-
const record = await this.find(id, key);
|
|
1610
|
+
static async findWith(id, relations, key, queryOptions) {
|
|
1611
|
+
const record = await this.find(id, key, queryOptions);
|
|
1564
1612
|
if (record == null) return null;
|
|
1565
1613
|
const relationList = normalizeRelations(relations);
|
|
1566
1614
|
if (relationList.length === 0) {
|
|
1567
1615
|
return record;
|
|
1568
1616
|
}
|
|
1569
1617
|
const copy = { ...record };
|
|
1570
|
-
|
|
1571
|
-
await this.loadRelationInto([copy], rel);
|
|
1572
|
-
}
|
|
1618
|
+
await this.loadRelationsInto([copy], relationList, queryOptions);
|
|
1573
1619
|
return copy;
|
|
1574
1620
|
}
|
|
1575
|
-
static async findWithOrFail(id, relations, key) {
|
|
1576
|
-
const record = await this.findOrFail(id, key);
|
|
1621
|
+
static async findWithOrFail(id, relations, key, queryOptions) {
|
|
1622
|
+
const record = await this.findOrFail(id, key, queryOptions);
|
|
1577
1623
|
const relationList = normalizeRelations(relations);
|
|
1578
1624
|
if (relationList.length === 0) {
|
|
1579
1625
|
return record;
|
|
1580
1626
|
}
|
|
1581
1627
|
const copy = { ...record };
|
|
1582
|
-
|
|
1583
|
-
await this.loadRelationInto([copy], rel);
|
|
1584
|
-
}
|
|
1628
|
+
await this.loadRelationsInto([copy], relationList, queryOptions);
|
|
1585
1629
|
return copy;
|
|
1586
1630
|
}
|
|
1587
1631
|
/**
|
|
@@ -1612,6 +1656,9 @@ var Model = class _Model {
|
|
|
1612
1656
|
}
|
|
1613
1657
|
static where(fieldOrConditions, operatorOrValue, value) {
|
|
1614
1658
|
const builder = this.newQuery();
|
|
1659
|
+
if (typeof fieldOrConditions === "function") {
|
|
1660
|
+
return builder.where(fieldOrConditions);
|
|
1661
|
+
}
|
|
1615
1662
|
if (typeof fieldOrConditions === "object" && fieldOrConditions !== null) {
|
|
1616
1663
|
return builder.where(fieldOrConditions);
|
|
1617
1664
|
}
|
|
@@ -2018,16 +2065,14 @@ var Model = class _Model {
|
|
|
2018
2065
|
};
|
|
2019
2066
|
return { data, meta };
|
|
2020
2067
|
}
|
|
2021
|
-
static async withPaginate(relations, options = {}) {
|
|
2022
|
-
const result = await this.paginate(options);
|
|
2068
|
+
static async withPaginate(relations, options = {}, queryOptions) {
|
|
2069
|
+
const result = await this.paginate(options, queryOptions);
|
|
2023
2070
|
const relationList = normalizeRelations(relations);
|
|
2024
2071
|
if (relationList.length === 0 || result.data.length === 0) {
|
|
2025
2072
|
return result;
|
|
2026
2073
|
}
|
|
2027
2074
|
const records = result.data.map((record) => ({ ...record }));
|
|
2028
|
-
|
|
2029
|
-
await this.loadRelationInto(records, relationName);
|
|
2030
|
-
}
|
|
2075
|
+
await this.loadRelationsInto(records, relationList, queryOptions);
|
|
2031
2076
|
return {
|
|
2032
2077
|
data: records,
|
|
2033
2078
|
meta: result.meta
|
|
@@ -2233,8 +2278,8 @@ var Model = class _Model {
|
|
|
2233
2278
|
}
|
|
2234
2279
|
return fallbackBuilder.from(table);
|
|
2235
2280
|
}
|
|
2236
|
-
static async with(relations, where) {
|
|
2237
|
-
const records = where ? await this.where(where) : await this.all();
|
|
2281
|
+
static async with(relations, where, queryOptions) {
|
|
2282
|
+
const records = where ? await this.newQuery(queryOptions).where(where).get() : await this.all(queryOptions);
|
|
2238
2283
|
if (!records.length) {
|
|
2239
2284
|
return records;
|
|
2240
2285
|
}
|
|
@@ -2243,25 +2288,23 @@ var Model = class _Model {
|
|
|
2243
2288
|
return records;
|
|
2244
2289
|
}
|
|
2245
2290
|
const copies = records.map((record) => ({ ...record }));
|
|
2246
|
-
|
|
2247
|
-
await this.loadRelationInto(copies, relationName);
|
|
2248
|
-
}
|
|
2291
|
+
await this.loadRelationsInto(copies, relationList, queryOptions);
|
|
2249
2292
|
return copies;
|
|
2250
2293
|
}
|
|
2251
|
-
static async withCount(relations, where) {
|
|
2252
|
-
const records = where ? await this.where(where) : await this.all();
|
|
2294
|
+
static async withCount(relations, where, queryOptions) {
|
|
2295
|
+
const records = where ? await this.newQuery(queryOptions).where(where).get() : await this.all(queryOptions);
|
|
2253
2296
|
if (!records.length) {
|
|
2254
2297
|
return records;
|
|
2255
2298
|
}
|
|
2256
2299
|
const relationList = normalizeRelations(relations);
|
|
2257
2300
|
const copies = records.map((record) => ({ ...record }));
|
|
2258
2301
|
for (const relationName of relationList) {
|
|
2259
|
-
await this.loadRelationCountInto(copies, relationName);
|
|
2302
|
+
await this.loadRelationCountInto(copies, relationName, queryOptions);
|
|
2260
2303
|
}
|
|
2261
2304
|
return copies;
|
|
2262
2305
|
}
|
|
2263
2306
|
/** @internal Attaches a `${name}Count` field for one relation. */
|
|
2264
|
-
static async loadRelationCountInto(records, relationName) {
|
|
2307
|
+
static async loadRelationCountInto(records, relationName, queryOptions) {
|
|
2265
2308
|
if (relationName.includes(".")) {
|
|
2266
2309
|
throw new Error(`${this.name}: withCount does not support nested relation "${relationName}".`);
|
|
2267
2310
|
}
|
|
@@ -2280,7 +2323,7 @@ var Model = class _Model {
|
|
|
2280
2323
|
);
|
|
2281
2324
|
const counts = /* @__PURE__ */ new Map();
|
|
2282
2325
|
if (values.length > 0) {
|
|
2283
|
-
const relatedRecords = await related.where({ [foreignKey]: values });
|
|
2326
|
+
const relatedRecords = await related.newQuery(queryOptions).where({ [foreignKey]: values });
|
|
2284
2327
|
for (const item of relatedRecords) {
|
|
2285
2328
|
const key = item[foreignKey];
|
|
2286
2329
|
counts.set(key, (counts.get(key) ?? 0) + 1);
|
|
@@ -2293,7 +2336,7 @@ var Model = class _Model {
|
|
|
2293
2336
|
}
|
|
2294
2337
|
case "morphMany": {
|
|
2295
2338
|
const withRelation = records.map((record) => ({ ...record }));
|
|
2296
|
-
await this.loadRelationInto(withRelation, relationName);
|
|
2339
|
+
await this.loadRelationInto(withRelation, relationName, queryOptions);
|
|
2297
2340
|
for (const [index, record] of records.entries()) {
|
|
2298
2341
|
const value = withRelation[index]?.[relationName];
|
|
2299
2342
|
record[countField] = Array.isArray(value) ? value.length : 0;
|
|
@@ -2308,7 +2351,7 @@ var Model = class _Model {
|
|
|
2308
2351
|
);
|
|
2309
2352
|
const ownerKeys = /* @__PURE__ */ new Set();
|
|
2310
2353
|
if (values.length > 0) {
|
|
2311
|
-
const owners = await related.where({ [ownerKey]: values });
|
|
2354
|
+
const owners = await related.newQuery(queryOptions).where({ [ownerKey]: values });
|
|
2312
2355
|
for (const owner of owners) {
|
|
2313
2356
|
ownerKeys.add(owner[ownerKey]);
|
|
2314
2357
|
}
|
|
@@ -2328,37 +2371,79 @@ var Model = class _Model {
|
|
|
2328
2371
|
/**
|
|
2329
2372
|
* @internal Used by QueryBuilder for eager loading.
|
|
2330
2373
|
* Supports nested paths with dot notation, e.g. `posts.comments`.
|
|
2374
|
+
*
|
|
2375
|
+
* Paths are grouped by their head segment so a relation shared by several
|
|
2376
|
+
* paths is loaded exactly once. Walking `posts.comments` and `posts.tags`
|
|
2377
|
+
* independently would load `posts` twice, and the loaders assign fresh
|
|
2378
|
+
* spread copies — so the second pass would replace the very row objects the
|
|
2379
|
+
* first had already attached children to, and only the last path would
|
|
2380
|
+
* survive.
|
|
2381
|
+
*/
|
|
2382
|
+
static async loadRelationsInto(records, relationNames, queryOptions, constraints, pathPrefix = "") {
|
|
2383
|
+
if (relationNames.length === 0) return;
|
|
2384
|
+
const groups = /* @__PURE__ */ new Map();
|
|
2385
|
+
for (const path of relationNames) {
|
|
2386
|
+
const [head, ...rest] = path.split(".");
|
|
2387
|
+
const tails = groups.get(head) ?? [];
|
|
2388
|
+
groups.set(head, tails);
|
|
2389
|
+
if (rest.length > 0) {
|
|
2390
|
+
const tail = rest.join(".");
|
|
2391
|
+
if (!tails.includes(tail)) {
|
|
2392
|
+
tails.push(tail);
|
|
2393
|
+
}
|
|
2394
|
+
}
|
|
2395
|
+
}
|
|
2396
|
+
for (const [head, tails] of groups) {
|
|
2397
|
+
await this.loadRelationLevel(records, head, tails, queryOptions, constraints, pathPrefix);
|
|
2398
|
+
}
|
|
2399
|
+
}
|
|
2400
|
+
/**
|
|
2401
|
+
* @internal Public since it is reachable from generated code; kept for
|
|
2402
|
+
* backwards compatibility now that the eager loader walks whole path lists.
|
|
2403
|
+
* Internal callers should use {@link loadRelationsInto} instead.
|
|
2331
2404
|
*/
|
|
2332
|
-
static async loadRelationInto(records, relationName) {
|
|
2333
|
-
|
|
2405
|
+
static async loadRelationInto(records, relationName, queryOptions, constraints, pathPrefix = "") {
|
|
2406
|
+
await this.loadRelationsInto(records, [relationName], queryOptions, constraints, pathPrefix);
|
|
2407
|
+
}
|
|
2408
|
+
/**
|
|
2409
|
+
* Load one relation level and recurse into the tails beneath it.
|
|
2410
|
+
*
|
|
2411
|
+
* `constraints` are keyed by the full path of the level each one constrains,
|
|
2412
|
+
* so `pathPrefix` accumulates the path walked so far as the recursion
|
|
2413
|
+
* descends: at `posts.comments` the leaf looks itself up under that whole
|
|
2414
|
+
* key, not under `comments`.
|
|
2415
|
+
*/
|
|
2416
|
+
static async loadRelationLevel(records, head, tails, queryOptions, constraints, pathPrefix = "") {
|
|
2334
2417
|
const definition = this.getRelationDefinition(head);
|
|
2335
2418
|
if (!definition) {
|
|
2336
2419
|
throw new Error(`${this.name}: unknown relation "${head}".`);
|
|
2337
2420
|
}
|
|
2421
|
+
const currentPath = pathPrefix ? `${pathPrefix}.${head}` : head;
|
|
2422
|
+
const constraint = constraints?.get(currentPath);
|
|
2338
2423
|
switch (definition.type) {
|
|
2339
2424
|
case "hasMany":
|
|
2340
|
-
await this.loadHasMany(records, definition);
|
|
2425
|
+
await this.loadHasMany(records, definition, queryOptions, constraint);
|
|
2341
2426
|
break;
|
|
2342
2427
|
case "hasOne":
|
|
2343
|
-
await this.loadHasOne(records, definition);
|
|
2428
|
+
await this.loadHasOne(records, definition, queryOptions, constraint);
|
|
2344
2429
|
break;
|
|
2345
2430
|
case "belongsTo":
|
|
2346
|
-
await this.loadBelongsTo(records, definition);
|
|
2431
|
+
await this.loadBelongsTo(records, definition, queryOptions, constraint);
|
|
2347
2432
|
break;
|
|
2348
2433
|
case "belongsToMany":
|
|
2349
|
-
await this.loadBelongsToMany(records, definition);
|
|
2434
|
+
await this.loadBelongsToMany(records, definition, queryOptions, constraint);
|
|
2350
2435
|
break;
|
|
2351
2436
|
case "hasManyThrough":
|
|
2352
|
-
await this.loadHasManyThrough(records, definition);
|
|
2437
|
+
await this.loadHasManyThrough(records, definition, queryOptions, constraint);
|
|
2353
2438
|
break;
|
|
2354
2439
|
case "morphMany":
|
|
2355
|
-
await this.loadMorphMany(records, definition);
|
|
2440
|
+
await this.loadMorphMany(records, definition, queryOptions, constraint);
|
|
2356
2441
|
break;
|
|
2357
2442
|
case "morphTo":
|
|
2358
|
-
await this.loadMorphTo(records, definition);
|
|
2443
|
+
await this.loadMorphTo(records, definition, queryOptions, constraint);
|
|
2359
2444
|
break;
|
|
2360
2445
|
}
|
|
2361
|
-
if (
|
|
2446
|
+
if (tails.length === 0) {
|
|
2362
2447
|
return;
|
|
2363
2448
|
}
|
|
2364
2449
|
if (definition.type === "morphTo") {
|
|
@@ -2382,24 +2467,24 @@ var Model = class _Model {
|
|
|
2382
2467
|
return;
|
|
2383
2468
|
}
|
|
2384
2469
|
const related = await resolveModelReference(definition.related);
|
|
2385
|
-
await related.
|
|
2470
|
+
await related.loadRelationsInto(children, tails, queryOptions, constraints, currentPath);
|
|
2386
2471
|
}
|
|
2387
|
-
static async loadHasMany(records, definition) {
|
|
2472
|
+
static async loadHasMany(records, definition, queryOptions, constraint) {
|
|
2388
2473
|
const { foreignKey, localKey, name } = definition;
|
|
2389
2474
|
const related = await resolveModelReference(definition.related);
|
|
2390
|
-
await loadRelationData(records, name, related, localKey, foreignKey, true);
|
|
2475
|
+
await loadRelationData(records, name, related, localKey, foreignKey, true, queryOptions, constraint);
|
|
2391
2476
|
}
|
|
2392
|
-
static async loadHasOne(records, definition) {
|
|
2477
|
+
static async loadHasOne(records, definition, queryOptions, constraint) {
|
|
2393
2478
|
const { foreignKey, localKey, name } = definition;
|
|
2394
2479
|
const related = await resolveModelReference(definition.related);
|
|
2395
|
-
await loadRelationData(records, name, related, localKey, foreignKey, false);
|
|
2480
|
+
await loadRelationData(records, name, related, localKey, foreignKey, false, queryOptions, constraint);
|
|
2396
2481
|
}
|
|
2397
|
-
static async loadBelongsTo(records, definition) {
|
|
2482
|
+
static async loadBelongsTo(records, definition, queryOptions, constraint) {
|
|
2398
2483
|
const { foreignKey, ownerKey, name } = definition;
|
|
2399
2484
|
const related = await resolveModelReference(definition.related);
|
|
2400
|
-
await loadRelationData(records, name, related, foreignKey, ownerKey, false);
|
|
2485
|
+
await loadRelationData(records, name, related, foreignKey, ownerKey, false, queryOptions, constraint);
|
|
2401
2486
|
}
|
|
2402
|
-
static async loadBelongsToMany(records, definition) {
|
|
2487
|
+
static async loadBelongsToMany(records, definition, queryOptions, constraint) {
|
|
2403
2488
|
const { pivotTable, foreignPivotKey, relatedPivotKey, parentKey, relatedKey, name } = definition;
|
|
2404
2489
|
const related = await resolveModelReference(definition.related);
|
|
2405
2490
|
const parentValues = Array.from(
|
|
@@ -2414,7 +2499,7 @@ var Model = class _Model {
|
|
|
2414
2499
|
const adapter = this.getAdapter();
|
|
2415
2500
|
const pivotRows = await adapter.findMany(pivotTable, {
|
|
2416
2501
|
where: { [foreignPivotKey]: parentValues }
|
|
2417
|
-
});
|
|
2502
|
+
}, queryOptions);
|
|
2418
2503
|
const pivotMap = /* @__PURE__ */ new Map();
|
|
2419
2504
|
const allRelatedIds = /* @__PURE__ */ new Set();
|
|
2420
2505
|
for (const row of pivotRows) {
|
|
@@ -2430,9 +2515,10 @@ var Model = class _Model {
|
|
|
2430
2515
|
}
|
|
2431
2516
|
return;
|
|
2432
2517
|
}
|
|
2433
|
-
const relatedRecords = await
|
|
2434
|
-
[relatedKey]: Array.from(allRelatedIds)
|
|
2435
|
-
|
|
2518
|
+
const relatedRecords = await applyEagerConstraint(
|
|
2519
|
+
related.newQuery(queryOptions).where({ [relatedKey]: Array.from(allRelatedIds) }),
|
|
2520
|
+
constraint
|
|
2521
|
+
);
|
|
2436
2522
|
const relatedMap = /* @__PURE__ */ new Map();
|
|
2437
2523
|
for (const item of relatedRecords) {
|
|
2438
2524
|
relatedMap.set(item[relatedKey], { ...item });
|
|
@@ -2447,7 +2533,7 @@ var Model = class _Model {
|
|
|
2447
2533
|
record[name] = relatedIds.map((id) => relatedMap.get(id)).filter((item) => item != null);
|
|
2448
2534
|
}
|
|
2449
2535
|
}
|
|
2450
|
-
static async loadHasManyThrough(records, definition) {
|
|
2536
|
+
static async loadHasManyThrough(records, definition, queryOptions, constraint) {
|
|
2451
2537
|
const { firstKey, secondKey, localKey, secondLocalKey, name } = definition;
|
|
2452
2538
|
const related = await resolveModelReference(definition.related);
|
|
2453
2539
|
const through = await resolveModelReference(definition.through);
|
|
@@ -2460,7 +2546,7 @@ var Model = class _Model {
|
|
|
2460
2546
|
}
|
|
2461
2547
|
return;
|
|
2462
2548
|
}
|
|
2463
|
-
const throughRecords = await through.where({
|
|
2549
|
+
const throughRecords = await through.newQuery(queryOptions).where({
|
|
2464
2550
|
[firstKey]: localValues
|
|
2465
2551
|
});
|
|
2466
2552
|
const throughMap = /* @__PURE__ */ new Map();
|
|
@@ -2478,9 +2564,10 @@ var Model = class _Model {
|
|
|
2478
2564
|
}
|
|
2479
2565
|
return;
|
|
2480
2566
|
}
|
|
2481
|
-
const relatedRecords = await
|
|
2482
|
-
[secondKey]: Array.from(allThroughIds)
|
|
2483
|
-
|
|
2567
|
+
const relatedRecords = await applyEagerConstraint(
|
|
2568
|
+
related.newQuery(queryOptions).where({ [secondKey]: Array.from(allThroughIds) }),
|
|
2569
|
+
constraint
|
|
2570
|
+
);
|
|
2484
2571
|
const relatedByKey = /* @__PURE__ */ new Map();
|
|
2485
2572
|
for (const item of relatedRecords) {
|
|
2486
2573
|
const key = item[secondKey];
|
|
@@ -2502,7 +2589,7 @@ var Model = class _Model {
|
|
|
2502
2589
|
record[name] = items;
|
|
2503
2590
|
}
|
|
2504
2591
|
}
|
|
2505
|
-
static async loadMorphMany(records, definition) {
|
|
2592
|
+
static async loadMorphMany(records, definition, queryOptions, constraint) {
|
|
2506
2593
|
const { morphName, localKey, name } = definition;
|
|
2507
2594
|
const related = await resolveModelReference(definition.related);
|
|
2508
2595
|
const typeColumn = `${morphName}Type`;
|
|
@@ -2515,12 +2602,13 @@ var Model = class _Model {
|
|
|
2515
2602
|
for (const record of records) record[name] = [];
|
|
2516
2603
|
return;
|
|
2517
2604
|
}
|
|
2518
|
-
const allRelated = await
|
|
2519
|
-
[typeColumn]: parentType,
|
|
2520
|
-
|
|
2521
|
-
|
|
2605
|
+
const allRelated = await applyEagerConstraint(
|
|
2606
|
+
related.newQuery(queryOptions).where({ [typeColumn]: parentType, [idColumn]: localValues }),
|
|
2607
|
+
constraint
|
|
2608
|
+
);
|
|
2522
2609
|
const map = /* @__PURE__ */ new Map();
|
|
2523
2610
|
for (const item of allRelated) {
|
|
2611
|
+
if (item[typeColumn] !== parentType) continue;
|
|
2524
2612
|
const key = item[idColumn];
|
|
2525
2613
|
if (!map.has(key)) map.set(key, []);
|
|
2526
2614
|
map.get(key).push({ ...item });
|
|
@@ -2530,7 +2618,7 @@ var Model = class _Model {
|
|
|
2530
2618
|
record[name] = key != null ? map.get(key) ?? [] : [];
|
|
2531
2619
|
}
|
|
2532
2620
|
}
|
|
2533
|
-
static async loadMorphTo(records, definition) {
|
|
2621
|
+
static async loadMorphTo(records, definition, queryOptions, constraint) {
|
|
2534
2622
|
const { morphName, name } = definition;
|
|
2535
2623
|
const typeColumn = `${morphName}Type`;
|
|
2536
2624
|
const idColumn = `${morphName}Id`;
|
|
@@ -2548,7 +2636,10 @@ var Model = class _Model {
|
|
|
2548
2636
|
const modelClass = morphMap[type];
|
|
2549
2637
|
if (!modelClass) continue;
|
|
2550
2638
|
const uniqueIds = Array.from(new Set(ids));
|
|
2551
|
-
const results = await
|
|
2639
|
+
const results = await applyEagerConstraint(
|
|
2640
|
+
modelClass.newQuery(queryOptions).where({ id: uniqueIds }),
|
|
2641
|
+
constraint
|
|
2642
|
+
);
|
|
2552
2643
|
const idMap = /* @__PURE__ */ new Map();
|
|
2553
2644
|
for (const r of results) idMap.set(r.id, { ...r });
|
|
2554
2645
|
resolved.set(type, idMap);
|
|
@@ -2564,7 +2655,11 @@ var Model = class _Model {
|
|
|
2564
2655
|
}
|
|
2565
2656
|
}
|
|
2566
2657
|
};
|
|
2567
|
-
async function
|
|
2658
|
+
async function applyEagerConstraint(query, constraint) {
|
|
2659
|
+
constraint?.(query);
|
|
2660
|
+
return await query;
|
|
2661
|
+
}
|
|
2662
|
+
async function loadRelationData(records, name, related, parentKey, relatedKey, isArray, queryOptions, constraint) {
|
|
2568
2663
|
const values = Array.from(
|
|
2569
2664
|
new Set(records.map((r) => r[parentKey]).filter((v) => v != null))
|
|
2570
2665
|
);
|
|
@@ -2574,7 +2669,10 @@ async function loadRelationData(records, name, related, parentKey, relatedKey, i
|
|
|
2574
2669
|
}
|
|
2575
2670
|
return;
|
|
2576
2671
|
}
|
|
2577
|
-
const relatedRecords = await
|
|
2672
|
+
const relatedRecords = await applyEagerConstraint(
|
|
2673
|
+
related.newQuery(queryOptions).where({ [relatedKey]: values }),
|
|
2674
|
+
constraint
|
|
2675
|
+
);
|
|
2578
2676
|
const map = /* @__PURE__ */ new Map();
|
|
2579
2677
|
for (const item of relatedRecords) {
|
|
2580
2678
|
const key = item[relatedKey];
|
|
@@ -3200,6 +3298,7 @@ function createPostgresDatabase(options) {
|
|
|
3200
3298
|
await adminClient.unsafe("DROP SCHEMA IF EXISTS drizzle CASCADE");
|
|
3201
3299
|
});
|
|
3202
3300
|
migrations.reset();
|
|
3301
|
+
await migrations.get();
|
|
3203
3302
|
}
|
|
3204
3303
|
async function migrationStatus() {
|
|
3205
3304
|
const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
|
|
@@ -3366,6 +3465,7 @@ function createMySqlDatabase(options) {
|
|
|
3366
3465
|
}
|
|
3367
3466
|
});
|
|
3368
3467
|
migrations.reset();
|
|
3468
|
+
await migrations.get();
|
|
3369
3469
|
}
|
|
3370
3470
|
async function migrationStatus() {
|
|
3371
3471
|
const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
|
|
@@ -3406,6 +3506,13 @@ import { fileURLToPath as fileURLToPath4 } from "url";
|
|
|
3406
3506
|
function isInMemory(dbPath) {
|
|
3407
3507
|
return dbPath === ":memory:" || dbPath === "" || dbPath.startsWith("file::memory:");
|
|
3408
3508
|
}
|
|
3509
|
+
var CONNECTION_URI = /^(?!file:)[a-z][a-z0-9+.-]+:\/\//i;
|
|
3510
|
+
function assertNotConnectionUri(dbPath, source) {
|
|
3511
|
+
if (!CONNECTION_URI.test(dbPath)) return;
|
|
3512
|
+
throw new Error(
|
|
3513
|
+
`createSqliteDatabase() received a connection URI where it expects a file path: ${dbPath} (from ${source}). Left alone it would be created as a directory tree and migrated into silently. Pass a path such as "./data/guren.db", or ":memory:".`
|
|
3514
|
+
);
|
|
3515
|
+
}
|
|
3409
3516
|
function createSqliteDatabase(options) {
|
|
3410
3517
|
const { migrationsFolder, filename, seedersFolder, relations } = options;
|
|
3411
3518
|
const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath4(migrationsFolder) : resolve5(String(migrationsFolder));
|
|
@@ -3415,7 +3522,16 @@ function createSqliteDatabase(options) {
|
|
|
3415
3522
|
const callSite = new Error().stack;
|
|
3416
3523
|
function resolveFilename() {
|
|
3417
3524
|
const value = typeof filename === "function" ? filename() : filename;
|
|
3418
|
-
|
|
3525
|
+
if (value != null) {
|
|
3526
|
+
assertNotConnectionUri(value, 'the "filename" option');
|
|
3527
|
+
return value;
|
|
3528
|
+
}
|
|
3529
|
+
const fromEnv = process.env.DATABASE_URL;
|
|
3530
|
+
if (fromEnv != null) {
|
|
3531
|
+
assertNotConnectionUri(fromEnv, "DATABASE_URL");
|
|
3532
|
+
return fromEnv;
|
|
3533
|
+
}
|
|
3534
|
+
return "./data/guren.db";
|
|
3419
3535
|
}
|
|
3420
3536
|
const database2 = singleFlight(async () => {
|
|
3421
3537
|
const dbPath = resolveFilename();
|
|
@@ -3487,6 +3603,7 @@ function createSqliteDatabase(options) {
|
|
|
3487
3603
|
sqliteClient.exec("PRAGMA foreign_keys = ON;");
|
|
3488
3604
|
}
|
|
3489
3605
|
migrations.reset();
|
|
3606
|
+
await migrations.get();
|
|
3490
3607
|
},
|
|
3491
3608
|
async migrationStatus() {
|
|
3492
3609
|
const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
|
|
@@ -3689,6 +3806,7 @@ function createAwsDataApiDatabase(options) {
|
|
|
3689
3806
|
await adminDb.execute(sql.raw("DROP SCHEMA IF EXISTS drizzle CASCADE"));
|
|
3690
3807
|
});
|
|
3691
3808
|
migrations.reset();
|
|
3809
|
+
await migrations.get();
|
|
3692
3810
|
}
|
|
3693
3811
|
async function migrationStatus() {
|
|
3694
3812
|
const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
|