@guren/orm 2.6.2 → 2.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +272 -1173
- package/dist/index.js +389 -1145
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -10,9 +10,7 @@ import { RDSDataClientConfig } from "@aws-sdk/client-rds-data";
|
|
|
10
10
|
type AccessorFn<T = unknown> = (record: PlainObject) => T;
|
|
11
11
|
/** Mutator function: transforms a field value before writing to DB. */
|
|
12
12
|
type MutatorFn<T = unknown> = (value: T, record: PlainObject) => unknown;
|
|
13
|
-
/** Map of field names to accessor functions. */
|
|
14
13
|
type AccessorDefinitions = Record<string, AccessorFn>;
|
|
15
|
-
/** Map of field names to mutator functions. */
|
|
16
14
|
type MutatorDefinitions = Record<string, MutatorFn>;
|
|
17
15
|
/** Apply accessors to a record, returning a new record with computed values. */
|
|
18
16
|
declare function applyAccessors<T extends PlainObject>(record: T, accessors?: AccessorDefinitions): T;
|
|
@@ -22,39 +20,34 @@ declare function applyMutators(data: PlainObject, mutators?: MutatorDefinitions)
|
|
|
22
20
|
//#region src/QueryBuilder.d.ts
|
|
23
21
|
type FieldKey<TRecord extends PlainObject> = keyof TRecord & string;
|
|
24
22
|
/**
|
|
25
|
-
* Key for the prepared-payload update terminal.
|
|
26
|
-
*
|
|
27
|
-
* Exported for `Model` to call across the module boundary, but deliberately
|
|
28
|
-
* absent from the package entry point, so it is not part of the public API.
|
|
23
|
+
* Key for the prepared-payload update terminal. Exported for `Model` across
|
|
24
|
+
* the module boundary, but kept out of the package entry point.
|
|
29
25
|
*/
|
|
30
26
|
declare const PREPARED_UPDATE: unique symbol;
|
|
31
|
-
/**
|
|
27
|
+
/**
|
|
28
|
+
* Key for the global-scope seal. Exported for `Model` across the module
|
|
29
|
+
* boundary, but kept out of the package entry point.
|
|
30
|
+
*/
|
|
31
|
+
declare const SEAL_SCOPES: unique symbol;
|
|
32
32
|
type WhereOperator = '=' | '!=' | '>' | '<' | '>=' | '<=' | 'like' | 'in' | 'not in' | 'is null' | 'is not null';
|
|
33
|
-
/** A single field-level condition. */
|
|
34
33
|
interface SimpleCondition {
|
|
35
34
|
type: 'simple';
|
|
36
35
|
field: string;
|
|
37
36
|
operator: WhereOperator;
|
|
38
37
|
value: unknown;
|
|
39
38
|
}
|
|
40
|
-
/** A group of conditions joined by AND or OR. */
|
|
41
39
|
interface GroupCondition {
|
|
42
40
|
type: 'group';
|
|
43
41
|
boolean: 'and' | 'or';
|
|
44
42
|
conditions: WhereCondition[];
|
|
45
43
|
}
|
|
46
|
-
/** A where condition - either simple or grouped. */
|
|
47
44
|
type WhereCondition = SimpleCondition | GroupCondition;
|
|
48
45
|
/**
|
|
49
|
-
*
|
|
50
|
-
*
|
|
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.
|
|
46
|
+
* Composes a parenthesized condition group. Only the conditions added on the
|
|
47
|
+
* nested builder are read back — ordering, limits, eager loads and terminal
|
|
48
|
+
* calls made inside the callback are not part of the group.
|
|
55
49
|
*/
|
|
56
50
|
type WhereGroupCallback<TRecord extends PlainObject = PlainObject> = (query: QueryBuilder<TRecord>) => void;
|
|
57
|
-
/** Options carried by the QueryBuilder for query execution. */
|
|
58
51
|
interface QueryBuilderOptions {
|
|
59
52
|
orderBy: Array<{
|
|
60
53
|
column: string;
|
|
@@ -66,41 +59,27 @@ interface QueryBuilderOptions {
|
|
|
66
59
|
trx?: unknown;
|
|
67
60
|
}
|
|
68
61
|
/**
|
|
69
|
-
* A callback that further constrains the query
|
|
62
|
+
* A callback that further constrains the query that fetches an eager-loaded
|
|
70
63
|
* relation. Registered through the object form of {@link QueryBuilder.with}.
|
|
71
64
|
*/
|
|
72
65
|
type EagerLoadConstraint = (q: QueryBuilder) => void;
|
|
73
66
|
/**
|
|
74
|
-
* Constraint callbacks keyed by the relation path they constrain
|
|
75
|
-
*
|
|
76
|
-
* constrains the leaf.
|
|
67
|
+
* Constraint callbacks keyed by the relation path they constrain, naming the
|
|
68
|
+
* exact level: `posts` the head, `posts.comments` the leaf.
|
|
77
69
|
*/
|
|
78
70
|
type EagerLoadConstraints = ReadonlyMap<string, EagerLoadConstraint>;
|
|
79
71
|
/**
|
|
80
|
-
* Fluent query builder for the Guren ORM.
|
|
81
|
-
*
|
|
82
|
-
* Provides a chainable API for constructing database queries with
|
|
83
|
-
* support for complex where conditions, ordering, pagination, and more.
|
|
84
|
-
*
|
|
85
|
-
* Implements the thenable pattern so it can be directly awaited,
|
|
86
|
-
* resolving to the result of `get()`.
|
|
72
|
+
* Fluent query builder for the Guren ORM. Thenable, so awaiting a builder
|
|
73
|
+
* resolves to the result of `get()`.
|
|
87
74
|
*
|
|
88
75
|
* @example
|
|
89
|
-
* // Fluent chaining
|
|
90
|
-
* const posts = await Post.where('status', 'published')
|
|
91
|
-
* .where('views', '>', 100)
|
|
92
|
-
* .orderBy('createdAt', 'desc')
|
|
93
|
-
* .limit(10)
|
|
94
|
-
* .get()
|
|
95
|
-
*
|
|
96
|
-
* // Thenable - await directly
|
|
97
76
|
* const active = await User.where('active', true)
|
|
98
|
-
*
|
|
99
|
-
* // Pagination
|
|
100
|
-
* const page = await Post.where('status', 'published').paginate(1, 20)
|
|
101
77
|
*/
|
|
102
78
|
declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult extends PlainObject = TRecord> {
|
|
103
79
|
private conditions;
|
|
80
|
+
private scopeConditions;
|
|
81
|
+
/** Fold this up wherever a nested builder's conditions are (pushCallbackGroup). */
|
|
82
|
+
private droppedUndefinedFilters;
|
|
104
83
|
private options;
|
|
105
84
|
private modelClass;
|
|
106
85
|
private table;
|
|
@@ -111,161 +90,49 @@ declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult ex
|
|
|
111
90
|
trx?: unknown;
|
|
112
91
|
});
|
|
113
92
|
/**
|
|
114
|
-
* Add a where condition (AND)
|
|
115
|
-
*
|
|
116
|
-
*
|
|
117
|
-
* - `where(field, value)` - equality check
|
|
118
|
-
* - `where(field, operator, value)` - comparison
|
|
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)
|
|
93
|
+
* Add a where condition (AND): `where(field, value)`,
|
|
94
|
+
* `where(field, operator, value)`, `where(object)` for several equality
|
|
95
|
+
* checks, or `where(callback)` for a parenthesized group.
|
|
127
96
|
*/
|
|
128
97
|
where(callback: WhereGroupCallback<TRecord>): this;
|
|
129
98
|
where<TKey extends FieldKey<TRecord>>(field: TKey, value: TRecord[TKey]): this;
|
|
130
99
|
where<TKey extends FieldKey<TRecord>>(field: TKey, operator: WhereOperator, value: unknown): this;
|
|
131
100
|
where(conditions: Partial<Record<FieldKey<TRecord>, unknown>>): this;
|
|
132
101
|
/**
|
|
133
|
-
*
|
|
134
|
-
*
|
|
135
|
-
* Same overloads as `where()`, but joins with OR logic.
|
|
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)`.
|
|
102
|
+
* Same overloads as `where()`, joined with OR. With a callback the group is
|
|
103
|
+
* parenthesized whole: `(preceding conditions) OR (callback group)`.
|
|
139
104
|
*/
|
|
140
105
|
orWhere(callback: WhereGroupCallback<TRecord>): this;
|
|
141
106
|
orWhere<TKey extends FieldKey<TRecord>>(field: TKey, value: TRecord[TKey]): this;
|
|
142
107
|
orWhere<TKey extends FieldKey<TRecord>>(field: TKey, operator: WhereOperator, value: unknown): this;
|
|
143
108
|
orWhere(conditions: Partial<Record<FieldKey<TRecord>, unknown>>): this;
|
|
144
|
-
/**
|
|
145
|
-
* Add a WHERE NULL condition.
|
|
146
|
-
* @param field - Column to check for NULL
|
|
147
|
-
*/
|
|
148
109
|
whereNull(field: FieldKey<TRecord>): this;
|
|
149
|
-
/**
|
|
150
|
-
* Add a WHERE NOT NULL condition.
|
|
151
|
-
* @param field - Column to check for NOT NULL
|
|
152
|
-
*/
|
|
153
110
|
whereNotNull(field: FieldKey<TRecord>): this;
|
|
154
|
-
/**
|
|
155
|
-
* Add a WHERE IN condition.
|
|
156
|
-
* @param field - Column to check
|
|
157
|
-
* @param values - Array of values to match against
|
|
158
|
-
*/
|
|
159
111
|
whereIn<TKey extends FieldKey<TRecord>>(field: TKey, values: readonly TRecord[TKey][]): this;
|
|
160
|
-
/**
|
|
161
|
-
* Add a WHERE NOT IN condition.
|
|
162
|
-
* @param field - Column to check
|
|
163
|
-
* @param values - Array of values to exclude
|
|
164
|
-
*/
|
|
165
112
|
whereNotIn<TKey extends FieldKey<TRecord>>(field: TKey, values: readonly TRecord[TKey][]): this;
|
|
166
|
-
/**
|
|
167
|
-
* Add an ORDER BY clause. Can be called multiple times to sort by multiple columns.
|
|
168
|
-
* @param field - Column to sort by
|
|
169
|
-
* @param direction - Sort direction (default: 'asc')
|
|
170
|
-
*/
|
|
113
|
+
/** Can be called multiple times to sort by multiple columns. */
|
|
171
114
|
orderBy(field: FieldKey<TRecord>, direction?: OrderDirection): this;
|
|
172
|
-
/**
|
|
173
|
-
* Set the maximum number of records to return.
|
|
174
|
-
* @param n - Maximum record count
|
|
175
|
-
*/
|
|
176
115
|
limit(n: number): this;
|
|
177
|
-
/**
|
|
178
|
-
* Set the number of records to skip.
|
|
179
|
-
* @param n - Number of records to skip
|
|
180
|
-
*/
|
|
181
116
|
offset(n: number): this;
|
|
182
|
-
/**
|
|
183
|
-
* Limit the columns returned in the result.
|
|
184
|
-
* @param fields - Column names to select
|
|
185
|
-
*/
|
|
186
117
|
select<TKey extends FieldKey<TRecord>>(...fields: readonly TKey[]): QueryBuilder<TRecord, Pick<TRecord, TKey>>;
|
|
187
|
-
/**
|
|
188
|
-
* Apply a named query scope defined on the model.
|
|
189
|
-
*
|
|
190
|
-
* @param name - The scope name
|
|
191
|
-
* @returns this (for chaining)
|
|
192
|
-
*
|
|
193
|
-
* @example
|
|
194
|
-
* const results = await Post.where('author', 'John')
|
|
195
|
-
* .scope('published')
|
|
196
|
-
* .scope('popular')
|
|
197
|
-
* .get()
|
|
198
|
-
*/
|
|
118
|
+
/** Apply a named query scope defined on the model. */
|
|
199
119
|
scope(name: string): this;
|
|
200
120
|
/**
|
|
201
|
-
* Eager-load relationships
|
|
202
|
-
*
|
|
203
|
-
*
|
|
204
|
-
*
|
|
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
|
-
*
|
|
220
|
-
* @example
|
|
221
|
-
* // Simple
|
|
222
|
-
* await User.where('active', true).with('posts').get()
|
|
223
|
-
*
|
|
224
|
-
* // Multiple
|
|
225
|
-
* await User.where('active', true).with('posts', 'comments').get()
|
|
226
|
-
*
|
|
227
|
-
* // Nested (dot notation)
|
|
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()
|
|
121
|
+
* Eager-load relationships by name, dot path, or an object of constraint
|
|
122
|
+
* callbacks, each run after the foreign-key filter on exactly the level its key
|
|
123
|
+
* names. Pitfalls: a top-level `orWhere()` ORs against the foreign-key filter
|
|
124
|
+
* (group it); `select()` must keep the relation's key column or the relation is
|
|
125
|
+
* empty; `limit()` applies to the one batched query, not per parent record.
|
|
237
126
|
*/
|
|
238
127
|
with(...relations: (string | Record<string, EagerLoadConstraint>)[]): this;
|
|
239
|
-
/**
|
|
240
|
-
* Execute the query and return all matching records.
|
|
241
|
-
* @returns Array of matching records
|
|
242
|
-
*/
|
|
243
128
|
get(): Promise<TResult[]>;
|
|
244
|
-
/**
|
|
245
|
-
* Execute the query and return the first matching record.
|
|
246
|
-
* @returns The first record or null
|
|
247
|
-
*/
|
|
248
129
|
first(): Promise<TResult | null>;
|
|
249
|
-
/**
|
|
250
|
-
* Execute the query and return the first matching record, or throw.
|
|
251
|
-
* @returns The first record
|
|
252
|
-
* @throws ModelNotFoundException (404) if no record matches
|
|
253
|
-
*/
|
|
130
|
+
/** @throws ModelNotFoundException (404) if no record matches. */
|
|
254
131
|
firstOrFail(): Promise<TResult>;
|
|
255
|
-
/**
|
|
256
|
-
* Count the number of records matching the current conditions.
|
|
257
|
-
* @returns The count of matching records
|
|
258
|
-
*/
|
|
259
132
|
count(): Promise<number>;
|
|
260
133
|
/**
|
|
261
|
-
*
|
|
262
|
-
*
|
|
263
|
-
* Accepts either positional arguments or the same options object shape as
|
|
264
|
-
* `Model.paginate()` so the two APIs stay interchangeable:
|
|
265
|
-
*
|
|
266
|
-
* @example
|
|
267
|
-
* await Post.where('published', true).paginate(2, 10)
|
|
268
|
-
* await Post.where('published', true).paginate({ page: 2, perPage: 10 })
|
|
134
|
+
* Takes positional arguments or the same options object as
|
|
135
|
+
* `Model.paginate()`, so the two APIs stay interchangeable.
|
|
269
136
|
*/
|
|
270
137
|
paginate(page?: number, perPage?: number): Promise<PaginatedResult<TResult>>;
|
|
271
138
|
paginate(options: {
|
|
@@ -273,95 +140,70 @@ declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult ex
|
|
|
273
140
|
perPage?: number;
|
|
274
141
|
}): Promise<PaginatedResult<TResult>>;
|
|
275
142
|
/**
|
|
276
|
-
* Bulk update
|
|
277
|
-
*
|
|
278
|
-
*
|
|
279
|
-
* with a `fillable` allowlist, out-of-allowlist keys throw a
|
|
280
|
-
* MassAssignmentException. The payload also runs through the same
|
|
281
|
-
* persistence preparation as `Model.update()` — mutators, casts, and
|
|
282
|
-
* `preparePersistencePayload` overrides (e.g. password hashing on
|
|
283
|
-
* authenticatable models). Per-record hooks and observers are still
|
|
284
|
-
* skipped by design.
|
|
285
|
-
*
|
|
286
|
-
* @param data - Data to set on matching records
|
|
287
|
-
* @returns The updated record (adapter-dependent)
|
|
143
|
+
* Bulk update. Mass-assignment protection and persistence preparation
|
|
144
|
+
* (mutators, casts, `preparePersistencePayload`) apply exactly as in
|
|
145
|
+
* `Model.update()`; per-record hooks and observers are skipped by design.
|
|
288
146
|
*/
|
|
289
147
|
update(data: PlainObject): Promise<TRecord>;
|
|
290
148
|
/**
|
|
291
|
-
* Bulk update bypassing mass-assignment protection.
|
|
292
|
-
*
|
|
149
|
+
* Bulk update bypassing mass-assignment protection. Trusted server-side data
|
|
150
|
+
* only, never raw request input.
|
|
293
151
|
*/
|
|
294
152
|
forceUpdate(data: PlainObject): Promise<TRecord>;
|
|
295
153
|
private runBulkUpdate;
|
|
296
154
|
/**
|
|
297
|
-
* Bulk update
|
|
298
|
-
*
|
|
299
|
-
*
|
|
300
|
-
*
|
|
301
|
-
*
|
|
302
|
-
*
|
|
303
|
-
* Keyed by a symbol that this package never re-exports, because a named
|
|
304
|
-
* public method here would be a supported way to write arbitrary columns:
|
|
305
|
-
* it skips both `filterFillable` and `prepareBulkPersistencePayload`, so
|
|
306
|
-
* `User.where(…)[name](requestBody)` would bypass mass-assignment protection
|
|
307
|
-
* entirely. `@internal` is only a doc tag — declarations still emit it.
|
|
155
|
+
* Bulk update with an already-filtered, already-prepared payload, so
|
|
156
|
+
* `Model.update()` can borrow the builder's global-scope-carrying
|
|
157
|
+
* `conditions` without running mutators twice (double-hashing a hashed
|
|
158
|
+
* column). Symbol-keyed and never re-exported: a named public method here
|
|
159
|
+
* would be a supported way to bypass mass-assignment protection entirely.
|
|
308
160
|
*/
|
|
309
161
|
[PREPARED_UPDATE](payload: PlainObject): Promise<TRecord>;
|
|
310
|
-
/**
|
|
311
|
-
* Bulk delete records matching the current conditions.
|
|
312
|
-
* @returns Number of deleted records (adapter-dependent)
|
|
313
|
-
*/
|
|
314
162
|
delete(): Promise<number | PlainObject | void>;
|
|
315
|
-
/**
|
|
316
|
-
* Makes QueryBuilder a thenable so it can be directly awaited.
|
|
317
|
-
* Resolves to the result of `get()`.
|
|
318
|
-
*/
|
|
163
|
+
/** Makes the builder awaitable, resolving to `get()`. */
|
|
319
164
|
then<TResult1 = TResult[], TResult2 = never>(onfulfilled?: ((value: TResult[]) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult1 | TResult2>;
|
|
320
|
-
/**
|
|
321
|
-
* Catch handler for the thenable interface.
|
|
322
|
-
*/
|
|
323
165
|
catch<TCatch = never>(onrejected?: ((reason: unknown) => TCatch | PromiseLike<TCatch>) | null): Promise<TResult[] | TCatch>;
|
|
324
|
-
/** Get the internal conditions (used by adapters). */
|
|
325
166
|
getConditions(): WhereCondition[];
|
|
326
|
-
/**
|
|
167
|
+
/**
|
|
168
|
+
* Freezes the conditions applied so far as this model's global scopes, to be
|
|
169
|
+
* AND-ed around the caller's expression from here on. Left in the same list,
|
|
170
|
+
* a top-level `orWhere()` folds them into its left arm (see
|
|
171
|
+
* `normalizeConditionSequence`) and the query loses tenant isolation and
|
|
172
|
+
* soft-delete filtering.
|
|
173
|
+
*/
|
|
174
|
+
[SEAL_SCOPES](): this;
|
|
327
175
|
getOptions(): QueryBuilderOptions;
|
|
328
176
|
/**
|
|
329
|
-
*
|
|
330
|
-
*
|
|
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.
|
|
177
|
+
* The nested builder skips global scopes on purpose: the outer builder
|
|
178
|
+
* already carries them, and re-applying them inside every group would
|
|
179
|
+
* duplicate — or, inside an OR group, weaken — their filters.
|
|
336
180
|
*/
|
|
337
181
|
private pushCallbackGroup;
|
|
182
|
+
private simpleConditionsFrom;
|
|
183
|
+
private hasConditions;
|
|
184
|
+
/** Flat list, for the basic-adapter conversion that cannot read group nodes. */
|
|
185
|
+
private allConditions;
|
|
186
|
+
/** Global scopes AND the caller's expression, never folded into it. */
|
|
187
|
+
private effectiveConditions;
|
|
188
|
+
/**
|
|
189
|
+
* `where({})` and a deliberately unfiltered builder are untouched: only a
|
|
190
|
+
* filter the caller wrote and then lost counts.
|
|
191
|
+
*/
|
|
192
|
+
private filtersEvaporated;
|
|
193
|
+
private assertFiltersSurvived;
|
|
338
194
|
private addSimpleCondition;
|
|
339
195
|
private executeQuery;
|
|
340
|
-
/**
|
|
341
|
-
* Attempt to convert the current conditions to a simple WhereClause
|
|
342
|
-
* for backward compatibility with basic adapters.
|
|
343
|
-
* Returns null if conditions are too complex.
|
|
344
|
-
*/
|
|
196
|
+
/** Null when the conditions are too complex for a basic adapter's WhereClause. */
|
|
345
197
|
private toSimpleWhereClause;
|
|
346
198
|
/**
|
|
347
|
-
*
|
|
348
|
-
*
|
|
349
|
-
*
|
|
350
|
-
*
|
|
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.
|
|
199
|
+
* Paths are delegated to Model.loadRelationsInto, which recurses the
|
|
200
|
+
* relation chain. The builder's `trx` goes with them: a relation read off
|
|
201
|
+
* the pool while its parents came from an open transaction gets a null
|
|
202
|
+
* relation back on Postgres/MySQL, the parents being uncommitted.
|
|
358
203
|
*/
|
|
359
204
|
private readonly loadEagerRelations;
|
|
360
205
|
}
|
|
361
|
-
/**
|
|
362
|
-
* Extended adapter interface for advanced query builder features.
|
|
363
|
-
* Adapters can optionally implement these methods for full QueryBuilder support.
|
|
364
|
-
*/
|
|
206
|
+
/** Optional adapter methods needed for full QueryBuilder support. */
|
|
365
207
|
interface ORMAdapterAdvanced extends ORMAdapter {
|
|
366
208
|
findManyAdvanced?<TRecord extends PlainObject = PlainObject>(table: unknown, conditions: WhereCondition[], options: {
|
|
367
209
|
orderBy?: OrderByClause;
|
|
@@ -375,30 +217,21 @@ interface ORMAdapterAdvanced extends ORMAdapter {
|
|
|
375
217
|
}
|
|
376
218
|
//#endregion
|
|
377
219
|
//#region src/GlobalScopeRegistry.d.ts
|
|
378
|
-
/** A named global scope function. */
|
|
379
220
|
type ScopeFunction = (q: QueryBuilder<any>) => QueryBuilder<any>;
|
|
380
|
-
/**
|
|
381
|
-
* Registry for named global scopes on a model.
|
|
382
|
-
*
|
|
383
|
-
* Supports adding, removing, and applying multiple named scopes.
|
|
384
|
-
* Used internally by Model to manage global query constraints.
|
|
385
|
-
*/
|
|
221
|
+
/** Registry for the named global scopes applied to every query on a model. */
|
|
386
222
|
declare class GlobalScopeRegistry {
|
|
387
223
|
private scopes;
|
|
388
224
|
add(name: string, fn: ScopeFunction): void;
|
|
389
225
|
remove(name: string): void;
|
|
390
226
|
has(name: string): boolean;
|
|
391
227
|
names(): string[];
|
|
392
|
-
/** Apply all scopes (or all except excluded) to a query builder. */
|
|
393
228
|
apply<T extends PlainObject>(builder: QueryBuilder<T>, except?: string[]): QueryBuilder<T>;
|
|
394
229
|
clear(): void;
|
|
395
230
|
/**
|
|
396
|
-
*
|
|
397
|
-
*
|
|
398
|
-
*
|
|
399
|
-
*
|
|
400
|
-
* mixes in `SoftDeletes` and then adds a `tenant` scope silently loses the
|
|
401
|
-
* `softDelete` filter.
|
|
231
|
+
* A subclass registering its own scope needs a registry of its own, but must
|
|
232
|
+
* keep the inherited entries: starting from empty is how a model that mixes
|
|
233
|
+
* in `SoftDeletes` and then adds a `tenant` scope loses the `softDelete`
|
|
234
|
+
* filter.
|
|
402
235
|
*/
|
|
403
236
|
clone(): GlobalScopeRegistry;
|
|
404
237
|
get size(): number;
|
|
@@ -406,53 +239,21 @@ declare class GlobalScopeRegistry {
|
|
|
406
239
|
//#endregion
|
|
407
240
|
//#region src/hooks.d.ts
|
|
408
241
|
/**
|
|
409
|
-
* Model lifecycle hook names.
|
|
410
|
-
*
|
|
411
|
-
*
|
|
412
|
-
* the database operation. If they return `false`, the operation is aborted.
|
|
413
|
-
*
|
|
414
|
-
* "After" hooks (`created`, `updated`, `deleted`, `saved`) fire after the
|
|
415
|
-
* database operation completes.
|
|
416
|
-
*
|
|
417
|
-
* `saving`/`saved` fire for both create and update operations.
|
|
242
|
+
* Model lifecycle hook names. A "before" hook (`creating`, `updating`,
|
|
243
|
+
* `deleting`, `saving`) aborts the operation by returning `false`.
|
|
244
|
+
* `saving`/`saved` fire for both create and update.
|
|
418
245
|
*/
|
|
419
246
|
type HookName = 'creating' | 'created' | 'updating' | 'updated' | 'deleting' | 'deleted' | 'saving' | 'saved';
|
|
420
|
-
/**
|
|
421
|
-
* Callback signature for model lifecycle hooks.
|
|
422
|
-
*
|
|
423
|
-
* @param data - The record data being operated on
|
|
424
|
-
* @returns void for after-hooks. Returning `false` from a before-hook aborts the operation.
|
|
425
|
-
*/
|
|
247
|
+
/** Callback for a model lifecycle hook; `false` from a before-hook aborts. */
|
|
426
248
|
type HookCallback<T = Record<string, unknown>> = (data: T) => void | Promise<void> | false | Promise<false>;
|
|
427
|
-
/**
|
|
428
|
-
* Map of hook names to their callbacks.
|
|
429
|
-
* All hooks are optional.
|
|
430
|
-
*/
|
|
431
249
|
type ModelHooks = { [K in HookName]?: HookCallback; };
|
|
432
|
-
/**
|
|
433
|
-
* Execute a model hook if it exists.
|
|
434
|
-
*
|
|
435
|
-
* @param hooks - The hooks object from the model
|
|
436
|
-
* @param name - The hook name to execute
|
|
437
|
-
* @param data - The data to pass to the hook
|
|
438
|
-
* @returns `false` if the hook explicitly returned false (operation should be aborted), otherwise `true`
|
|
439
|
-
*/
|
|
250
|
+
/** Runs the hook if present; `false` means the operation should be aborted. */
|
|
440
251
|
declare function executeHook(hooks: ModelHooks | undefined, name: HookName, data: Record<string, unknown>): Promise<boolean>;
|
|
441
252
|
//#endregion
|
|
442
253
|
//#region src/ModelObserver.d.ts
|
|
443
254
|
/**
|
|
444
|
-
*
|
|
445
|
-
*
|
|
446
|
-
* Observers allow extracting lifecycle hook logic into dedicated classes.
|
|
447
|
-
* Each method corresponds to a model lifecycle event and is optional.
|
|
448
|
-
*
|
|
449
|
-
* @example
|
|
450
|
-
* class UserObserver implements ModelObserver {
|
|
451
|
-
* async creating(data) { data.slug = slugify(data.name) }
|
|
452
|
-
* async created(data) { await sendWelcomeEmail(data) }
|
|
453
|
-
* }
|
|
454
|
-
*
|
|
455
|
-
* User.observe(UserObserver)
|
|
255
|
+
* Lifecycle hook logic extracted into a class, registered with
|
|
256
|
+
* `User.observe(UserObserver)`.
|
|
456
257
|
*/
|
|
457
258
|
interface ModelObserver {
|
|
458
259
|
creating?(data: PlainObject): void | Promise<void> | false | Promise<false>;
|
|
@@ -465,14 +266,10 @@ interface ModelObserver {
|
|
|
465
266
|
saved?(data: PlainObject): void | Promise<void>;
|
|
466
267
|
}
|
|
467
268
|
type ModelObserverConstructor = new () => ModelObserver;
|
|
468
|
-
/**
|
|
469
|
-
* Execute all registered observers for a given hook.
|
|
470
|
-
* Returns false if any observer aborts the operation.
|
|
471
|
-
*/
|
|
269
|
+
/** Returns false as soon as an observer aborts the operation. */
|
|
472
270
|
declare function executeObservers(observers: ModelObserver[] | undefined, name: HookName, data: PlainObject): Promise<boolean>;
|
|
473
271
|
//#endregion
|
|
474
272
|
//#region src/Model.d.ts
|
|
475
|
-
/** Generic plain object type used throughout the ORM. */
|
|
476
273
|
type PlainObject = Record<string, unknown>;
|
|
477
274
|
type RelationShape = Record<string, unknown>;
|
|
478
275
|
type TableShape<TSelect extends PlainObject = PlainObject, TInsert extends PlainObject = PlainObject> = {
|
|
@@ -485,114 +282,54 @@ type InferModelRecord<TTable> = TTable extends {
|
|
|
485
282
|
type InferModelInsert<TTable> = TTable extends {
|
|
486
283
|
$inferInsert: infer TInsert;
|
|
487
284
|
} ? TInsert extends PlainObject ? TInsert : PlainObject : PlainObject;
|
|
488
|
-
/** Supported cast types for attribute casting. */
|
|
489
285
|
type CastType = 'json' | 'date' | 'boolean' | 'number' | 'string';
|
|
490
|
-
/**
|
|
491
|
-
* Value type for where clause conditions.
|
|
492
|
-
* Supports single values, arrays (for IN queries), or null.
|
|
493
|
-
*/
|
|
494
286
|
type WhereValue<Value> = Value | readonly Value[] | null;
|
|
495
|
-
/**
|
|
496
|
-
* Where clause for filtering records.
|
|
497
|
-
* Supports equality and IN (array) queries.
|
|
498
|
-
*
|
|
499
|
-
* @example
|
|
500
|
-
* // Single value (equality)
|
|
501
|
-
* { status: 'active' }
|
|
502
|
-
*
|
|
503
|
-
* // Array value (IN query)
|
|
504
|
-
* { id: [1, 2, 3] }
|
|
505
|
-
*
|
|
506
|
-
* // Multiple conditions (AND)
|
|
507
|
-
* { status: 'active', role: 'admin' }
|
|
508
|
-
*/
|
|
287
|
+
/** A single value is an equality test, an array an IN; keys are AND-ed. */
|
|
509
288
|
type WhereClause<TRecord extends PlainObject = PlainObject> = Partial<{ [K in keyof TRecord & string]?: WhereValue<TRecord[K]>; }>;
|
|
510
|
-
/** Sort direction for ordering queries. */
|
|
511
289
|
type OrderDirection = 'asc' | 'desc';
|
|
512
|
-
/** Normalized order definition with column and direction. */
|
|
513
290
|
type OrderDefinition<TRecord extends PlainObject = PlainObject> = {
|
|
514
291
|
column: keyof TRecord & string;
|
|
515
292
|
direction: OrderDirection;
|
|
516
293
|
};
|
|
517
|
-
/**
|
|
518
|
-
* Flexible order expression input.
|
|
519
|
-
* @example
|
|
520
|
-
* 'createdAt' // Column name (ascending)
|
|
521
|
-
* ['createdAt', 'desc'] // Tuple [column, direction]
|
|
522
|
-
* { column: 'createdAt', direction: 'desc' } // Object form
|
|
523
|
-
*/
|
|
524
294
|
type OrderExpression<TRecord extends PlainObject = PlainObject> = (keyof TRecord & string) | readonly [keyof TRecord & string, OrderDirection] | {
|
|
525
295
|
column: keyof TRecord & string;
|
|
526
296
|
direction?: OrderDirection;
|
|
527
297
|
};
|
|
528
|
-
/** Input for orderBy - single expression or array of expressions. */
|
|
529
298
|
type OrderByInput<TRecord extends PlainObject = PlainObject> = OrderExpression<TRecord> | readonly OrderExpression<TRecord>[];
|
|
530
|
-
/** Normalized array of order definitions. */
|
|
531
299
|
type OrderByClause<TRecord extends PlainObject = PlainObject> = readonly OrderDefinition<TRecord>[];
|
|
532
|
-
/** Options for findMany queries. */
|
|
533
300
|
interface FindManyOptions<TRecord extends PlainObject = PlainObject> {
|
|
534
|
-
/** Filter conditions */
|
|
535
301
|
where?: WhereClause<TRecord>;
|
|
536
|
-
/** Sort order */
|
|
537
302
|
orderBy?: OrderByClause<TRecord>;
|
|
538
|
-
/** Maximum number of records to return */
|
|
539
303
|
limit?: number;
|
|
540
|
-
/** Number of records to skip */
|
|
541
304
|
offset?: number;
|
|
542
305
|
}
|
|
543
|
-
/** Options for paginated queries. */
|
|
544
306
|
interface PaginateOptions<TRecord extends PlainObject = PlainObject> {
|
|
545
|
-
/** Page number (1-based, default: 1) */
|
|
546
307
|
page?: number;
|
|
547
|
-
/** Records per page (default: 15) */
|
|
548
308
|
perPage?: number;
|
|
549
|
-
/** Filter conditions */
|
|
550
309
|
where?: WhereClause<TRecord>;
|
|
551
|
-
/** Sort order */
|
|
552
310
|
orderBy?: OrderByInput<TRecord>;
|
|
553
311
|
}
|
|
554
|
-
/** Pagination metadata returned with paginated results. */
|
|
555
312
|
interface ModelPaginationMeta {
|
|
556
|
-
/** Total number of records matching the query */
|
|
557
313
|
total: number;
|
|
558
|
-
/** Number of records per page */
|
|
559
314
|
perPage: number;
|
|
560
|
-
/** Current page number (1-based) */
|
|
561
315
|
currentPage: number;
|
|
562
|
-
/** Total number of pages */
|
|
563
316
|
totalPages: number;
|
|
564
|
-
/** Whether there are more pages after this one */
|
|
565
317
|
hasMore: boolean;
|
|
566
|
-
/** Index of first record on this page (1-based) */
|
|
567
318
|
from: number;
|
|
568
|
-
/** Index of last record on this page */
|
|
569
319
|
to: number;
|
|
570
320
|
}
|
|
571
|
-
/** Result of a paginated query. */
|
|
572
321
|
interface PaginatedResult<TRecord extends PlainObject = PlainObject> {
|
|
573
|
-
/** Records for the current page */
|
|
574
322
|
data: TRecord[];
|
|
575
|
-
/** Pagination metadata */
|
|
576
323
|
meta: ModelPaginationMeta;
|
|
577
324
|
}
|
|
578
|
-
/**
|
|
579
|
-
* Interface for ORM adapters that power the Model class.
|
|
580
|
-
* The default adapter is DrizzleAdapter.
|
|
581
|
-
*/
|
|
325
|
+
/** Interface for ORM adapters that power the Model class; DrizzleAdapter by default. */
|
|
582
326
|
interface ORMAdapter {
|
|
583
|
-
/** Run operations in a database transaction. */
|
|
584
327
|
transaction?<TResult>(callback: (trx: unknown) => Promise<TResult>): Promise<TResult>;
|
|
585
|
-
/** Find multiple records with optional filtering, ordering, and pagination. */
|
|
586
328
|
findMany<TRecord extends PlainObject = PlainObject>(table: unknown, options?: FindManyOptions<TRecord>, queryOptions?: AdapterQueryOptions): Promise<TRecord[]>;
|
|
587
|
-
/** Find a single record by unique criteria. */
|
|
588
329
|
findUnique<TRecord extends PlainObject = PlainObject>(table: unknown, where: WhereClause<TRecord>, queryOptions?: AdapterQueryOptions): Promise<TRecord | null>;
|
|
589
|
-
/** Create a new record. */
|
|
590
330
|
create<TRecord extends PlainObject = PlainObject>(table: unknown, data: PlainObject, writeOptions?: AdapterQueryOptions): Promise<TRecord>;
|
|
591
|
-
/** Update records matching criteria. */
|
|
592
331
|
update?<TRecord extends PlainObject = PlainObject>(table: unknown, where: WhereClause<TRecord>, data: PlainObject, writeOptions?: AdapterQueryOptions): Promise<TRecord>;
|
|
593
|
-
/** Delete records matching criteria. */
|
|
594
332
|
delete?<TRecord extends PlainObject = PlainObject>(table: unknown, where: WhereClause<TRecord>, writeOptions?: AdapterQueryOptions): Promise<number | PlainObject | void>;
|
|
595
|
-
/** Count records matching criteria. */
|
|
596
333
|
count?<TRecord extends PlainObject = PlainObject>(table: unknown, where?: WhereClause<TRecord>, queryOptions?: AdapterQueryOptions): Promise<number>;
|
|
597
334
|
}
|
|
598
335
|
interface AdapterQueryOptions {
|
|
@@ -607,301 +344,109 @@ type SelectFrom<TDatabase> = TDatabase extends {
|
|
|
607
344
|
from: (...args: any[]) => infer TResult;
|
|
608
345
|
} ? TResult : never : never;
|
|
609
346
|
/**
|
|
610
|
-
* ActiveRecord-style base class for database models.
|
|
611
|
-
*
|
|
612
|
-
*
|
|
613
|
-
* CRUD, querying, pagination, and eager-loading of relationships.
|
|
614
|
-
*
|
|
615
|
-
* @example
|
|
616
|
-
* // Define a model — recordType/createType are inferred from the Drizzle table
|
|
617
|
-
* class User extends defineModel(users) {}
|
|
618
|
-
*
|
|
619
|
-
* // Or, when extending Model directly, redeclare the type markers
|
|
620
|
-
* class LegacyUser extends Model<UserRecord> {
|
|
621
|
-
* static override table = users // Drizzle table
|
|
622
|
-
* declare static readonly recordType: UserRecord
|
|
623
|
-
* declare static readonly createType: NewUserRecord
|
|
624
|
-
* }
|
|
625
|
-
*
|
|
626
|
-
* // Query records
|
|
627
|
-
* const allUsers = await User.all()
|
|
628
|
-
* const user = await User.find(1)
|
|
629
|
-
* const activeUsers = await User.where({ status: 'active' })
|
|
630
|
-
*
|
|
631
|
-
* // Create and update
|
|
632
|
-
* const newUser = await User.create({ name: 'John', email: 'john@example.com' })
|
|
633
|
-
* await User.update({ id: 1 }, { name: 'Jane' })
|
|
634
|
-
*
|
|
635
|
-
* // Pagination
|
|
636
|
-
* const page = await User.paginate({ page: 1, perPage: 10 })
|
|
637
|
-
*
|
|
638
|
-
* // Relationships
|
|
639
|
-
* const usersWithPosts = await User.with('posts')
|
|
347
|
+
* ActiveRecord-style base class for database models. Prefer `defineModel(table)`,
|
|
348
|
+
* which infers the type markers; extending `Model` directly means setting
|
|
349
|
+
* `static table` and redeclaring `recordType`/`createType` by hand.
|
|
640
350
|
*/
|
|
641
351
|
declare abstract class Model<TRecord extends PlainObject = PlainObject> {
|
|
642
|
-
/** The ORM adapter used for database operations. */
|
|
643
352
|
protected static ormAdapter: ORMAdapter;
|
|
644
|
-
/** The database table (e.g., Drizzle table schema). */
|
|
645
353
|
protected static table: unknown;
|
|
646
354
|
/** Type marker for TypeScript inference. Set by `defineModel()`; when extending `Model` directly, redeclare as `declare static readonly recordType: YourRecordType`. */
|
|
647
355
|
static readonly recordType: unknown;
|
|
648
356
|
/** Type marker for insert/update payload inference. Set by `defineModel()`; when extending `Model` directly, redeclare as `declare static readonly createType: YourCreateType`. */
|
|
649
357
|
static readonly createType: unknown;
|
|
650
358
|
protected static relationDefinitions?: Map<string, RelationDefinition>;
|
|
651
|
-
/** Type marker for relation types. Define relation types here for type inference. */
|
|
652
359
|
static relationTypes: RelationShape;
|
|
653
360
|
/**
|
|
654
|
-
*
|
|
655
|
-
*
|
|
656
|
-
* @example
|
|
657
|
-
* class Post extends Model<PostRecord> {
|
|
658
|
-
* static scopes = {
|
|
659
|
-
* published: (q: QueryBuilder<PostRecord>) => q.where('status', 'published'),
|
|
660
|
-
* popular: (q: QueryBuilder<PostRecord>) => q.where('views', '>', 1000),
|
|
661
|
-
* }
|
|
662
|
-
* }
|
|
663
|
-
* // Usage: Post.scope('published').scope('popular').get()
|
|
361
|
+
* Reusable query constraints, applied by name with
|
|
362
|
+
* `Post.scope('published').scope('popular')`.
|
|
664
363
|
*/
|
|
665
364
|
static scopes?: Record<string, (q: QueryBuilder<any>) => QueryBuilder<any>>;
|
|
666
365
|
/**
|
|
667
|
-
*
|
|
668
|
-
*
|
|
669
|
-
*
|
|
670
|
-
* @example
|
|
671
|
-
* static defaultScope = (q: QueryBuilder<any>) => q.whereNull('deletedAt')
|
|
366
|
+
* Applied to every query on this model, and — unlike a named global scope —
|
|
367
|
+
* never removable with `withoutGlobalScope()`.
|
|
672
368
|
*/
|
|
673
369
|
static defaultScope?: (q: QueryBuilder<any>) => QueryBuilder<any>;
|
|
674
|
-
/**
|
|
675
|
-
* Model lifecycle hooks that fire during create, update, and delete operations.
|
|
676
|
-
*
|
|
677
|
-
* @example
|
|
678
|
-
* class User extends Model<UserRecord> {
|
|
679
|
-
* static hooks: ModelHooks = {
|
|
680
|
-
* creating: async (data) => { data.password = await hash(data.password as string) },
|
|
681
|
-
* created: async (data) => { console.log('User created:', data) },
|
|
682
|
-
* }
|
|
683
|
-
* }
|
|
684
|
-
*/
|
|
370
|
+
/** Lifecycle hooks firing around create, update and delete. */
|
|
685
371
|
static hooks?: ModelHooks;
|
|
686
|
-
/**
|
|
687
|
-
* Attribute casting definitions for automatic type conversion.
|
|
688
|
-
*
|
|
689
|
-
* Casts are applied when reading records from the database and when
|
|
690
|
-
* writing records to the database.
|
|
691
|
-
*
|
|
692
|
-
* @example
|
|
693
|
-
* class Post extends Model<PostRecord> {
|
|
694
|
-
* static casts = {
|
|
695
|
-
* metadata: 'json',
|
|
696
|
-
* publishedAt: 'date',
|
|
697
|
-
* isActive: 'boolean',
|
|
698
|
-
* viewCount: 'number',
|
|
699
|
-
* }
|
|
700
|
-
* }
|
|
701
|
-
*/
|
|
372
|
+
/** Attribute casts, applied both on read and on write. */
|
|
702
373
|
static casts?: Record<string, CastType>;
|
|
703
374
|
/**
|
|
704
|
-
*
|
|
705
|
-
*
|
|
706
|
-
*
|
|
707
|
-
*
|
|
708
|
-
*
|
|
709
|
-
* trusted server-side data.
|
|
710
|
-
*
|
|
711
|
-
* The primary key (`id`) is always silently stripped from mass-assignment
|
|
712
|
-
* input, and fields returned by `deniedFields()` always throw — neither
|
|
713
|
-
* depends on `fillable`.
|
|
714
|
-
*
|
|
715
|
-
* @example
|
|
716
|
-
* class User extends Model<UserRecord> {
|
|
717
|
-
* static fillable = ['name', 'email', 'password']
|
|
718
|
-
* }
|
|
375
|
+
* Mass-assignment allowlist. When set, any other key in `create()`/`update()`
|
|
376
|
+
* input throws a MassAssignmentException rather than being discarded, so
|
|
377
|
+
* bugs and injection attempts surface; `forceCreate()`/`forceUpdate()` are
|
|
378
|
+
* the trusted-data escape. Independent of it, `id` is always stripped and
|
|
379
|
+
* `deniedFields()` always throws.
|
|
719
380
|
*/
|
|
720
381
|
static fillable?: string[];
|
|
721
382
|
/**
|
|
722
|
-
* Fields that can never be mass-assigned,
|
|
723
|
-
*
|
|
724
|
-
* `AuthenticatableModel` contributes its
|
|
725
|
-
* remember-token columns). Input containing any of these throws a
|
|
726
|
-
* MassAssignmentException regardless of `fillable` — use
|
|
727
|
-
* `forceCreate()` / `forceUpdate()` for trusted server-side values.
|
|
383
|
+
* Fields that can never be mass-assigned, whatever `fillable` says. Resolved
|
|
384
|
+
* at call time so a subclass can derive them from its own configuration
|
|
385
|
+
* (`AuthenticatableModel` contributes its password-hash column).
|
|
728
386
|
*/
|
|
729
387
|
protected static deniedFields(): string[];
|
|
730
|
-
/**
|
|
731
|
-
* Accessor functions for computed/virtual attributes.
|
|
732
|
-
* Applied after reading records from the database.
|
|
733
|
-
*
|
|
734
|
-
* @example
|
|
735
|
-
* class User extends Model<UserRecord> {
|
|
736
|
-
* static accessors = {
|
|
737
|
-
* fullName: (record) => `${record.firstName} ${record.lastName}`,
|
|
738
|
-
* }
|
|
739
|
-
* }
|
|
740
|
-
*/
|
|
388
|
+
/** Computed attributes, applied after a record is read. */
|
|
741
389
|
static accessors?: AccessorDefinitions;
|
|
742
|
-
/**
|
|
743
|
-
* Mutator functions for transforming attributes before persistence.
|
|
744
|
-
*
|
|
745
|
-
* @example
|
|
746
|
-
* class User extends Model<UserRecord> {
|
|
747
|
-
* static mutators = {
|
|
748
|
-
* email: (value) => String(value).toLowerCase(),
|
|
749
|
-
* }
|
|
750
|
-
* }
|
|
751
|
-
*/
|
|
390
|
+
/** Attribute transforms applied before persistence. */
|
|
752
391
|
static mutators?: MutatorDefinitions;
|
|
753
|
-
/**
|
|
754
|
-
* Fields to exclude from serialization output.
|
|
755
|
-
*
|
|
756
|
-
* @example
|
|
757
|
-
* class User extends Model<UserRecord> {
|
|
758
|
-
* static hidden = ['passwordHash', 'rememberToken']
|
|
759
|
-
* }
|
|
760
|
-
*/
|
|
392
|
+
/** Fields to exclude from serialization output. */
|
|
761
393
|
static hidden?: string[];
|
|
762
|
-
/**
|
|
763
|
-
* Whitelist of fields to include in serialization output.
|
|
764
|
-
* When set, only these fields appear. Takes precedence over `hidden`.
|
|
765
|
-
*/
|
|
394
|
+
/** Serialization allowlist; takes precedence over `hidden`. */
|
|
766
395
|
static visible?: string[];
|
|
767
|
-
/**
|
|
768
|
-
* Virtual accessor attributes to include in serialization output.
|
|
769
|
-
*
|
|
770
|
-
* @example
|
|
771
|
-
* class User extends Model<UserRecord> {
|
|
772
|
-
* static appends = ['fullName']
|
|
773
|
-
* static accessors = { fullName: (r) => `${r.firstName} ${r.lastName}` }
|
|
774
|
-
* }
|
|
775
|
-
*/
|
|
396
|
+
/** Accessor names to add to serialization output. */
|
|
776
397
|
static appends?: string[];
|
|
777
|
-
/** Registered model observers. */
|
|
778
398
|
protected static observers?: ModelObserver[];
|
|
779
|
-
/** Named global scopes registry. */
|
|
780
399
|
protected static globalScopeRegistry?: GlobalScopeRegistry;
|
|
781
|
-
/**
|
|
782
|
-
* Set a custom ORM adapter for this model.
|
|
783
|
-
* @param adapter - The adapter to use
|
|
784
|
-
*/
|
|
785
400
|
static useAdapter(adapter: ORMAdapter): void;
|
|
786
|
-
/**
|
|
787
|
-
* Get the current ORM adapter.
|
|
788
|
-
* @returns The configured adapter
|
|
789
|
-
*/
|
|
790
401
|
static getAdapter(): ORMAdapter;
|
|
791
402
|
/**
|
|
792
|
-
* Run operations inside a database transaction.
|
|
793
|
-
*
|
|
794
403
|
* @example
|
|
795
|
-
* await User.transaction(async (trx) => {
|
|
796
|
-
* const user = await User.create({ name: 'John' }, { trx })
|
|
797
|
-
* await Profile.create({ userId: user.id }, { trx })
|
|
798
|
-
* })
|
|
404
|
+
* await User.transaction(async (trx) => User.create({ name: 'John' }, { trx }))
|
|
799
405
|
*/
|
|
800
406
|
static transaction<T extends typeof Model, TResult>(this: T, callback: (trx: TransactionHandle, scope: TransactionModelScope<T>) => Promise<TResult>): Promise<TResult>;
|
|
801
|
-
/**
|
|
802
|
-
* Create a transaction-bound model scope that automatically forwards `trx`
|
|
803
|
-
* to query and write operations.
|
|
804
|
-
*
|
|
805
|
-
* @example
|
|
806
|
-
* await User.transaction(async (trx, txUser) => {
|
|
807
|
-
* await txUser.create({ name: 'Shinji' })
|
|
808
|
-
* await txUser.update({ id: 1 }, { name: 'Ikari' })
|
|
809
|
-
* })
|
|
810
|
-
*/
|
|
407
|
+
/** A model scope that forwards `trx` to every query and write on it. */
|
|
811
408
|
static inTransaction<T extends typeof Model>(this: T, trx: TransactionHandle): TransactionModelScope<T>;
|
|
812
|
-
/**
|
|
813
|
-
* Register a model observer class.
|
|
814
|
-
*
|
|
815
|
-
* @example
|
|
816
|
-
* User.observe(UserObserver)
|
|
817
|
-
*/
|
|
818
409
|
static observe(ObserverClass: ModelObserverConstructor): void;
|
|
819
|
-
/** Clear all registered observers. */
|
|
820
410
|
static clearObservers(): void;
|
|
821
411
|
/**
|
|
822
|
-
* The registry this class may mutate,
|
|
823
|
-
*
|
|
824
|
-
*
|
|
825
|
-
*
|
|
826
|
-
*
|
|
827
|
-
* shadow — and silently drop — every scope it inherited. That is exactly the
|
|
828
|
-
* `class Post extends SoftDeletes(Base)` then `Post.addGlobalScope('tenant')`
|
|
829
|
-
* case, which would otherwise lose the `softDelete` filter.
|
|
830
|
-
*
|
|
831
|
-
* The copy is a snapshot: scopes added to the parent *after* a subclass first
|
|
832
|
-
* registers or removes one do not reach that subclass. Nothing in the
|
|
833
|
-
* framework relies on later propagation — the `SoftDeletes` mixin registers
|
|
834
|
-
* `softDelete` synchronously while building the class, before any user code
|
|
835
|
-
* can touch it.
|
|
412
|
+
* The registry this class may mutate, created on first write and seeded from
|
|
413
|
+
* the inherited one: the read paths resolve it through the prototype chain,
|
|
414
|
+
* so starting empty would shadow and drop every inherited scope (SoftDeletes
|
|
415
|
+
* then `addGlobalScope('tenant')`). The copy is a snapshot — scopes added to
|
|
416
|
+
* the parent afterwards never reach the subclass.
|
|
836
417
|
*/
|
|
837
418
|
protected static getGlobalScopes(): GlobalScopeRegistry;
|
|
838
|
-
/**
|
|
839
|
-
* Register a named global scope.
|
|
840
|
-
*
|
|
841
|
-
* @example
|
|
842
|
-
* User.addGlobalScope('active', (q) => q.where('active', true))
|
|
843
|
-
*/
|
|
844
419
|
static addGlobalScope(name: string, fn: ScopeFunction): void;
|
|
845
|
-
/** Remove a named global scope. */
|
|
846
420
|
static removeGlobalScope(name: string): void;
|
|
847
421
|
/**
|
|
848
|
-
*
|
|
849
|
-
*
|
|
850
|
-
*
|
|
851
|
-
* whatever this is asked to drop. A mixin whose filter users must be able to
|
|
852
|
-
* opt out of therefore has to register a named scope and nothing else —
|
|
853
|
-
* registering as both makes the filter unremovable, which is how `SoftDeletes`
|
|
854
|
-
* once made `withoutGlobalScope('softDelete')` a no-op.
|
|
855
|
-
*
|
|
856
|
-
* @example
|
|
857
|
-
* const all = await User.withoutGlobalScope('active').get()
|
|
422
|
+
* Only *named* scopes can be excluded: `defaultScope` is re-applied whatever
|
|
423
|
+
* this is asked to drop, so a mixin whose filter must be opt-out-able has to
|
|
424
|
+
* register a named scope and nothing else.
|
|
858
425
|
*/
|
|
859
426
|
static withoutGlobalScope<T extends typeof Model>(this: T, ...names: string[]): QueryBuilder<TRecordFor<T>>;
|
|
860
427
|
/**
|
|
861
|
-
*
|
|
862
|
-
*
|
|
863
|
-
* @example
|
|
864
|
-
* const all = await User.withoutGlobalScopes().get()
|
|
428
|
+
* Query options lead here because `names` is a rest parameter and cannot be
|
|
429
|
+
* followed by an optional one; every other entry point takes them trailing.
|
|
865
430
|
*/
|
|
866
|
-
static
|
|
431
|
+
static withoutGlobalScope<T extends typeof Model>(this: T, queryOptions: ModelQueryOptions, ...names: string[]): QueryBuilder<TRecordFor<T>>;
|
|
432
|
+
/** A query with no global scopes applied, `defaultScope` included. */
|
|
433
|
+
static withoutGlobalScopes<T extends typeof Model>(this: T, queryOptions?: ModelQueryOptions): QueryBuilder<TRecordFor<T>>;
|
|
867
434
|
/**
|
|
868
|
-
*
|
|
869
|
-
*
|
|
870
|
-
*
|
|
871
|
-
* @example
|
|
872
|
-
* const json = User.serialize(user)
|
|
435
|
+
* Both write entry points fork on `hasScopes()`, and only one arm reaches a
|
|
436
|
+
* builder — so the refusal belongs above the fork, where every adapter is
|
|
437
|
+
* still in scope.
|
|
873
438
|
*/
|
|
439
|
+
private static assertFiltersSurvived;
|
|
440
|
+
/** Applies hidden/visible filtering, accessors and appends. */
|
|
874
441
|
static serialize<T extends typeof Model>(this: T, record: TRecordFor<T>): PlainObject;
|
|
875
|
-
/**
|
|
876
|
-
* Serialize an array of records.
|
|
877
|
-
*
|
|
878
|
-
* @example
|
|
879
|
-
* const json = User.serializeMany(users)
|
|
880
|
-
*/
|
|
881
442
|
static serializeMany<T extends typeof Model>(this: T, records: TRecordFor<T>[]): PlainObject[];
|
|
882
|
-
/**
|
|
883
|
-
* Apply attribute casts to a record read from the database.
|
|
884
|
-
*
|
|
885
|
-
* @param record - The raw record from the database
|
|
886
|
-
* @returns The record with cast attributes applied
|
|
887
|
-
*/
|
|
888
443
|
static applyCasts<T extends PlainObject>(record: T): T;
|
|
889
|
-
/**
|
|
890
|
-
* Apply all read-time transforms: casts then accessors.
|
|
891
|
-
* Used internally after fetching records from the database.
|
|
892
|
-
*/
|
|
444
|
+
/** Read-time transforms, in order: casts then accessors. */
|
|
893
445
|
protected static applyReadTransforms<T extends PlainObject>(record: T): T;
|
|
894
446
|
/**
|
|
895
|
-
*
|
|
896
|
-
*
|
|
897
|
-
*
|
|
898
|
-
* MassAssignmentException (checked on the raw input, so no other rule
|
|
899
|
-
* can silently swallow them); the primary key (`id`) is silently
|
|
900
|
-
* stripped; when `fillable` is defined, any remaining field outside it
|
|
901
|
-
* throws and only listed fields are kept.
|
|
902
|
-
*
|
|
903
|
-
* @param data - The input data to filter
|
|
904
|
-
* @returns Filtered data safe for mass assignment
|
|
447
|
+
* In order: `deniedFields()` throws, checked on the raw input so no later
|
|
448
|
+
* rule can swallow them; `id` is stripped silently; then, with `fillable`
|
|
449
|
+
* set, anything outside it throws.
|
|
905
450
|
*/
|
|
906
451
|
static filterFillable(data: PlainObject): PlainObject;
|
|
907
452
|
protected static preparePersistencePayload(data: PlainObject): Promise<PlainObject>;
|
|
@@ -911,417 +456,119 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
|
|
|
911
456
|
/** @internal */
|
|
912
457
|
static getRelationDefinition(name: string): RelationDefinition | undefined;
|
|
913
458
|
static resolveTable(): unknown;
|
|
914
|
-
/**
|
|
915
|
-
* Retrieve all records from the table.
|
|
916
|
-
*
|
|
917
|
-
* @returns Array of all records
|
|
918
|
-
*
|
|
919
|
-
* @example
|
|
920
|
-
* const users = await User.all()
|
|
921
|
-
*/
|
|
922
459
|
static all<T extends typeof Model>(this: T, queryOptions?: ModelQueryOptions): Promise<Array<TRecordFor<T>>>;
|
|
923
|
-
/**
|
|
924
|
-
* Find a record by its primary key.
|
|
925
|
-
*
|
|
926
|
-
* @param id - The primary key value
|
|
927
|
-
* @param key - The primary key column name (default: 'id')
|
|
928
|
-
* @returns The record or null if not found
|
|
929
|
-
*
|
|
930
|
-
* @example
|
|
931
|
-
* const user = await User.find(1)
|
|
932
|
-
* const userByEmail = await User.find('john@example.com', 'email')
|
|
933
|
-
*/
|
|
934
460
|
static find<T extends typeof Model>(this: T, id: TRecordFor<T>[keyof TRecordFor<T> & string], key?: keyof TRecordFor<T> & string, queryOptions?: ModelQueryOptions): Promise<TRecordFor<T> | null>;
|
|
935
|
-
/**
|
|
936
|
-
* Find a record by primary key or throw an error.
|
|
937
|
-
*
|
|
938
|
-
* @param id - The primary key value
|
|
939
|
-
* @param key - The primary key column name (default: 'id')
|
|
940
|
-
* @returns The record
|
|
941
|
-
* @throws Error if record not found
|
|
942
|
-
*
|
|
943
|
-
* @example
|
|
944
|
-
* const user = await User.findOrFail(1) // Throws if not found
|
|
945
|
-
*/
|
|
461
|
+
/** @throws ModelNotFoundException (404) when no record matches. */
|
|
946
462
|
static findOrFail<T extends typeof Model>(this: T, id: TRecordFor<T>[keyof TRecordFor<T> & string], key?: keyof TRecordFor<T> & string, queryOptions?: ModelQueryOptions): Promise<TRecordFor<T>>;
|
|
947
|
-
/**
|
|
948
|
-
* Find a record by primary key with eager-loaded relations.
|
|
949
|
-
*
|
|
950
|
-
* @param id - The primary key value
|
|
951
|
-
* @param relations - Relation name(s) to eager load
|
|
952
|
-
* @param key - The primary key column name (default: 'id')
|
|
953
|
-
* @returns The record with loaded relations, or null if not found
|
|
954
|
-
*
|
|
955
|
-
* @example
|
|
956
|
-
* const post = await Post.findWith(1, 'author')
|
|
957
|
-
* const post = await Post.findWith(1, ['author', 'tags'])
|
|
958
|
-
*/
|
|
959
463
|
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>;
|
|
960
464
|
/**
|
|
961
|
-
*
|
|
962
|
-
*
|
|
963
|
-
* @param id - The primary key value
|
|
964
|
-
* @param relations - Relation name(s) to eager load
|
|
965
|
-
* @param key - The primary key column name (default: 'id')
|
|
966
|
-
* @returns The record with loaded relations
|
|
967
|
-
* @throws ModelNotFoundException if record not found
|
|
968
|
-
*
|
|
969
|
-
* @example
|
|
970
|
-
* const post = await Post.findWithOrFail(1, 'author')
|
|
971
|
-
* const post = await Post.findWithOrFail(1, ['author', 'tags'])
|
|
972
|
-
* const post = await Post.findWithOrFail(1, 'comments.author') // nested
|
|
465
|
+
* Relations accept dot-notation paths (`comments.author`).
|
|
466
|
+
* @throws ModelNotFoundException when no record matches.
|
|
973
467
|
*/
|
|
974
468
|
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[]>>;
|
|
975
|
-
/**
|
|
976
|
-
* Get the first record matching the conditions.
|
|
977
|
-
*
|
|
978
|
-
* @param where - Optional filter conditions
|
|
979
|
-
* @returns The first matching record or null
|
|
980
|
-
*
|
|
981
|
-
* @example
|
|
982
|
-
* const admin = await User.first({ role: 'admin' })
|
|
983
|
-
*/
|
|
984
469
|
static first<T extends typeof Model>(this: T, where?: WhereClauseFor<T>, queryOptions?: ModelQueryOptions): Promise<TRecordFor<T> | null>;
|
|
985
470
|
/**
|
|
986
|
-
*
|
|
987
|
-
*
|
|
988
|
-
* Returns a QueryBuilder that is thenable, so it can be directly awaited.
|
|
471
|
+
* Returns a thenable QueryBuilder, so it can be chained or awaited directly.
|
|
989
472
|
*
|
|
990
473
|
* @example
|
|
991
|
-
*
|
|
992
|
-
*
|
|
993
|
-
*
|
|
994
|
-
* // Field + value - equality
|
|
995
|
-
* const admins = await User.where('role', 'admin')
|
|
996
|
-
*
|
|
997
|
-
* // Field + operator + value - comparison
|
|
998
|
-
* const recent = await Post.where('views', '>', 100)
|
|
999
|
-
*
|
|
1000
|
-
* // Fluent chaining
|
|
1001
|
-
* const posts = await Post.where('status', 'published')
|
|
1002
|
-
* .where('views', '>', 100)
|
|
1003
|
-
* .orderBy('createdAt', 'desc')
|
|
1004
|
-
* .limit(10)
|
|
1005
|
-
* .get()
|
|
474
|
+
* await User.where({ status: 'active' })
|
|
475
|
+
* await Post.where('views', '>', 100).orderBy('createdAt', 'desc').get()
|
|
1006
476
|
*/
|
|
1007
477
|
static where<T extends typeof Model>(this: T, callback: WhereGroupCallback<TRecordFor<T>>): QueryBuilder<TRecordFor<T>>;
|
|
1008
478
|
static where<T extends typeof Model>(this: T, conditions: WhereClauseFor<T>): QueryBuilder<TRecordFor<T>>;
|
|
1009
479
|
static where<T extends typeof Model>(this: T, field: keyof TRecordFor<T> & string, value: unknown): QueryBuilder<TRecordFor<T>>;
|
|
1010
480
|
static where<T extends typeof Model>(this: T, field: keyof TRecordFor<T> & string, operator: WhereOperator, value: unknown): QueryBuilder<TRecordFor<T>>;
|
|
1011
|
-
/**
|
|
1012
|
-
* Start a fluent query with a WHERE NULL condition.
|
|
1013
|
-
* @param field - Column to check for NULL
|
|
1014
|
-
*/
|
|
1015
481
|
static whereNull<T extends typeof Model>(this: T, field: keyof TRecordFor<T> & string): QueryBuilder<TRecordFor<T>>;
|
|
1016
|
-
/**
|
|
1017
|
-
* Start a fluent query with a WHERE NOT NULL condition.
|
|
1018
|
-
* @param field - Column to check for NOT NULL
|
|
1019
|
-
*/
|
|
1020
482
|
static whereNotNull<T extends typeof Model>(this: T, field: keyof TRecordFor<T> & string): QueryBuilder<TRecordFor<T>>;
|
|
1021
|
-
/**
|
|
1022
|
-
* Start a fluent query with a WHERE IN condition.
|
|
1023
|
-
* @param field - Column to check
|
|
1024
|
-
* @param values - Array of values to match against
|
|
1025
|
-
*/
|
|
1026
483
|
static whereIn<T extends typeof Model>(this: T, field: keyof TRecordFor<T> & string, values: readonly TRecordFor<T>[keyof TRecordFor<T> & string][]): QueryBuilder<TRecordFor<T>>;
|
|
1027
|
-
/**
|
|
1028
|
-
* Start a fluent query with a WHERE NOT IN condition.
|
|
1029
|
-
* @param field - Column to check
|
|
1030
|
-
* @param values - Array of values to exclude
|
|
1031
|
-
*/
|
|
1032
484
|
static whereNotIn<T extends typeof Model>(this: T, field: keyof TRecordFor<T> & string, values: readonly TRecordFor<T>[keyof TRecordFor<T> & string][]): QueryBuilder<TRecordFor<T>>;
|
|
1033
|
-
/**
|
|
1034
|
-
* Start a fluent query with a typed field selection.
|
|
1035
|
-
*
|
|
1036
|
-
* @example
|
|
1037
|
-
* const rows = await User.select('id', 'name')
|
|
1038
|
-
* const first = await User.select('id').first()
|
|
1039
|
-
*/
|
|
1040
485
|
static select<T extends typeof Model, Keys extends keyof TRecordFor<T> & string>(this: T, ...fields: readonly Keys[]): QueryBuilder<TRecordFor<T>, Pick<TRecordFor<T>, Keys>>;
|
|
1041
|
-
/**
|
|
1042
|
-
* Start a new QueryBuilder for fluent query construction.
|
|
1043
|
-
*
|
|
1044
|
-
* @returns A fresh QueryBuilder instance
|
|
1045
|
-
*
|
|
1046
|
-
* @example
|
|
1047
|
-
* const results = await User.newQuery()
|
|
1048
|
-
* .where('status', 'active')
|
|
1049
|
-
* .orderBy('name')
|
|
1050
|
-
* .limit(10)
|
|
1051
|
-
* .get()
|
|
1052
|
-
*/
|
|
1053
486
|
static newQuery<T extends typeof Model>(this: T, queryOptions?: ModelQueryOptions): QueryBuilder<TRecordFor<T>>;
|
|
1054
487
|
/**
|
|
1055
|
-
*
|
|
1056
|
-
*
|
|
1057
|
-
*
|
|
1058
|
-
* @returns A fresh QueryBuilder instance with no scopes applied
|
|
488
|
+
* The one place a scoped builder is born: applying scopes without sealing
|
|
489
|
+
* them leaves them foldable by a later `orWhere()`, and nothing else would
|
|
490
|
+
* report it. `except` names the global scopes to leave off.
|
|
1059
491
|
*/
|
|
492
|
+
private static buildScopedQuery;
|
|
493
|
+
/** No scopes applied — for soft-deleted records or bypassing global filters. */
|
|
1060
494
|
static newQueryWithoutScopes<T extends typeof Model>(this: T, queryOptions?: ModelQueryOptions): QueryBuilder<TRecordFor<T>>;
|
|
1061
495
|
/**
|
|
1062
|
-
* Whether this model carries a filter
|
|
1063
|
-
*
|
|
1064
|
-
*
|
|
1065
|
-
* whether they can take the fast path; anything that returns a QueryBuilder
|
|
1066
|
-
* goes through `newQuery()` unconditionally.
|
|
496
|
+
* Whether this model carries a filter every query must apply. Checked by the
|
|
497
|
+
* entry points that talk to the adapter directly, to decide whether they can
|
|
498
|
+
* take the fast path.
|
|
1067
499
|
*/
|
|
1068
500
|
protected static hasScopes(): boolean;
|
|
1069
|
-
/**
|
|
1070
|
-
* Apply a named query scope.
|
|
1071
|
-
*
|
|
1072
|
-
* @param name - The scope name defined in `static scopes`
|
|
1073
|
-
* @returns A QueryBuilder with the scope applied
|
|
1074
|
-
*
|
|
1075
|
-
* @example
|
|
1076
|
-
* const published = await Post.scope('published').get()
|
|
1077
|
-
* const popularPublished = await Post.scope('published').scope('popular').get()
|
|
1078
|
-
*/
|
|
501
|
+
/** Apply a scope defined in `static scopes`; chainable. */
|
|
1079
502
|
static scope<T extends typeof Model>(this: T, name: string): QueryBuilder<TRecordFor<T>>;
|
|
1080
503
|
/**
|
|
1081
|
-
*
|
|
1082
|
-
*
|
|
1083
|
-
* @param name - Relation name (used in `with()` calls)
|
|
1084
|
-
* @param related - The related model class
|
|
1085
|
-
* @param foreignKey - Foreign key column on the related model
|
|
1086
|
-
* @param localKey - Local key column on this model
|
|
1087
|
-
*
|
|
1088
|
-
* @example
|
|
1089
|
-
* class User extends Model<UserRecord> {
|
|
1090
|
-
* static {
|
|
1091
|
-
* this.hasMany('posts', Post, 'userId', 'id')
|
|
1092
|
-
* }
|
|
1093
|
-
* }
|
|
1094
|
-
* // Later: User.with('posts')
|
|
504
|
+
* One-to-many: `foreignKey` is on the related model, `localKey` on this one.
|
|
505
|
+
* Declare in a `static {}` block; `name` is what `with()` takes.
|
|
1095
506
|
*/
|
|
1096
507
|
static hasMany<This extends typeof Model, Related extends typeof Model, ForeignKey extends keyof TRecordFor<Related> & string, LocalKey extends keyof TRecordFor<This> & string, Name extends RelationKeyOrString<This>>(this: This, name: Name, related: Related | (() => Related | Promise<Related>), foreignKey: ForeignKey, localKey: LocalKey): void;
|
|
1097
508
|
/**
|
|
1098
|
-
*
|
|
1099
|
-
*
|
|
1100
|
-
* @param name - Relation name (used in `with()` calls)
|
|
1101
|
-
* @param related - The related model class
|
|
1102
|
-
* @param foreignKey - Foreign key column on this model
|
|
1103
|
-
* @param ownerKey - Primary key column on the related model
|
|
1104
|
-
*
|
|
1105
|
-
* @example
|
|
1106
|
-
* class Post extends Model<PostRecord> {
|
|
1107
|
-
* static {
|
|
1108
|
-
* this.belongsTo('author', User, 'userId', 'id')
|
|
1109
|
-
* }
|
|
1110
|
-
* }
|
|
1111
|
-
* // Later: Post.with('author')
|
|
509
|
+
* Many-to-one inverse: `foreignKey` is on *this* model, `ownerKey` on the
|
|
510
|
+
* related one.
|
|
1112
511
|
*/
|
|
1113
512
|
static belongsTo<This extends typeof Model, Related extends typeof Model, ForeignKey extends keyof TRecordFor<This> & string, OwnerKey extends keyof TRecordFor<Related> & string, Name extends RelationKeyOrString<This>>(this: This, name: Name, related: Related | (() => Related | Promise<Related>), foreignKey: ForeignKey, ownerKey: OwnerKey): void;
|
|
1114
513
|
/**
|
|
1115
|
-
*
|
|
1116
|
-
*
|
|
1117
|
-
* @param name - Relation name (used in `with()` calls)
|
|
1118
|
-
* @param related - The related model class
|
|
1119
|
-
* @param foreignKey - Foreign key column on the related model
|
|
1120
|
-
* @param localKey - Local key column on this model
|
|
1121
|
-
*
|
|
1122
|
-
* @example
|
|
1123
|
-
* class User extends Model<UserRecord> {
|
|
1124
|
-
* static {
|
|
1125
|
-
* this.hasOne('profile', Profile, 'userId', 'id')
|
|
1126
|
-
* }
|
|
1127
|
-
* }
|
|
1128
|
-
* // Later: User.with('profile')
|
|
514
|
+
* One-to-one: `foreignKey` is on the related model, `localKey` on this one.
|
|
1129
515
|
*/
|
|
1130
516
|
static hasOne<This extends typeof Model, Related extends typeof Model, ForeignKey extends keyof TRecordFor<Related> & string, LocalKey extends keyof TRecordFor<This> & string, Name extends RelationKeyOrString<This>>(this: This, name: Name, related: Related | (() => Related | Promise<Related>), foreignKey: ForeignKey, localKey: LocalKey): void;
|
|
1131
517
|
/**
|
|
1132
|
-
*
|
|
1133
|
-
*
|
|
1134
|
-
*
|
|
1135
|
-
* @param related - The related model class
|
|
1136
|
-
* @param pivotTable - The pivot/junction table (e.g., Drizzle table schema)
|
|
1137
|
-
* @param foreignPivotKey - Column on pivot table referencing this model
|
|
1138
|
-
* @param relatedPivotKey - Column on pivot table referencing the related model
|
|
1139
|
-
* @param parentKey - Local key on this model (default: 'id')
|
|
1140
|
-
* @param relatedKey - Local key on the related model (default: 'id')
|
|
1141
|
-
*
|
|
518
|
+
* Many-to-many through a pivot table. `foreignPivotKey`/`relatedPivotKey` are
|
|
519
|
+
* both columns *on the pivot*, referencing this model and the related one;
|
|
520
|
+
* `parentKey`/`relatedKey` are the local keys they point at.
|
|
1142
521
|
* @example
|
|
1143
|
-
*
|
|
1144
|
-
* static {
|
|
1145
|
-
* this.belongsToMany('roles', Role, userRoles, 'userId', 'roleId', 'id', 'id')
|
|
1146
|
-
* }
|
|
1147
|
-
* }
|
|
1148
|
-
* // Later: User.with('roles')
|
|
522
|
+
* this.belongsToMany('roles', Role, userRoles, 'userId', 'roleId', 'id', 'id')
|
|
1149
523
|
*/
|
|
1150
524
|
static belongsToMany<This extends typeof Model, Related extends typeof Model, Name extends RelationKeyOrString<This>>(this: This, name: Name, related: Related | (() => Related | Promise<Related>), pivotTable: unknown, foreignPivotKey: string, relatedPivotKey: string, parentKey?: string, relatedKey?: string): void;
|
|
1151
525
|
/**
|
|
1152
|
-
*
|
|
1153
|
-
*
|
|
1154
|
-
*
|
|
1155
|
-
* @param related - The final related model class
|
|
1156
|
-
* @param through - The intermediate model class
|
|
1157
|
-
* @param firstKey - Foreign key on the intermediate model referencing this model
|
|
1158
|
-
* @param secondKey - Foreign key on the related model referencing the intermediate model
|
|
1159
|
-
* @param localKey - Local key on this model (default: 'id')
|
|
1160
|
-
* @param secondLocalKey - Local key on the intermediate model (default: 'id')
|
|
1161
|
-
*
|
|
526
|
+
* Has-many-through: `firstKey` is on the intermediate model referencing this
|
|
527
|
+
* one, `secondKey` on the related model referencing the intermediate;
|
|
528
|
+
* `localKey` and `secondLocalKey` are the keys they point at.
|
|
1162
529
|
* @example
|
|
1163
|
-
*
|
|
1164
|
-
* static {
|
|
1165
|
-
* this.hasManyThrough('posts', Post, User, 'countryId', 'userId', 'id', 'id')
|
|
1166
|
-
* }
|
|
1167
|
-
* }
|
|
1168
|
-
* // Later: Country.with('posts')
|
|
530
|
+
* this.hasManyThrough('posts', Post, User, 'countryId', 'userId', 'id', 'id')
|
|
1169
531
|
*/
|
|
1170
532
|
static hasManyThrough<This extends typeof Model, Related extends typeof Model, Through extends typeof Model, Name extends RelationKeyOrString<This>>(this: This, name: Name, related: Related | (() => Related | Promise<Related>), through: Through | (() => Through | Promise<Through>), firstKey: string, secondKey: string, localKey?: string, secondLocalKey?: string): void;
|
|
1171
|
-
/**
|
|
1172
|
-
* Map of type strings to model classes for polymorphic relationships.
|
|
1173
|
-
*
|
|
1174
|
-
* @example
|
|
1175
|
-
* Model.morphMap = { Post, Video }
|
|
1176
|
-
*/
|
|
533
|
+
/** Type strings to model classes, e.g. `Model.morphMap = { Post, Video }`. */
|
|
1177
534
|
static morphMap?: Record<string, typeof Model>;
|
|
1178
535
|
/**
|
|
1179
|
-
*
|
|
1180
|
-
*
|
|
1181
|
-
* @param name - Relation name
|
|
1182
|
-
* @param related - The related model class
|
|
1183
|
-
* @param morphName - Base name for the type/id columns (e.g. 'commentable' → commentableType + commentableId)
|
|
1184
|
-
* @param localKey - Local key on this model (default: 'id')
|
|
1185
|
-
*
|
|
1186
|
-
* @example
|
|
1187
|
-
* Post.morphMany('comments', Comment, 'commentable', 'id')
|
|
536
|
+
* Polymorphic one-to-many. `morphName` is the base of the column pair:
|
|
537
|
+
* 'commentable' means commentableType + commentableId.
|
|
1188
538
|
*/
|
|
1189
539
|
static morphMany<This extends typeof Model, Related extends typeof Model, Name extends RelationKeyOrString<This>>(this: This, name: Name, related: Related | (() => Related | Promise<Related>), morphName: string, localKey?: string): void;
|
|
1190
|
-
/**
|
|
1191
|
-
* Define the inverse of a polymorphic relationship.
|
|
1192
|
-
*
|
|
1193
|
-
* @param name - Relation name
|
|
1194
|
-
* @param morphName - Base name for the type/id columns
|
|
1195
|
-
*
|
|
1196
|
-
* @example
|
|
1197
|
-
* Comment.morphTo('commentable', 'commentable')
|
|
1198
|
-
*/
|
|
540
|
+
/** Inverse of a polymorphic relation; `morphName` bases the type/id columns. */
|
|
1199
541
|
static morphTo<This extends typeof Model, Name extends RelationKeyOrString<This>>(this: This, name: Name, morphName: string): void;
|
|
1200
542
|
/**
|
|
1201
|
-
* Get records sorted by the specified order.
|
|
1202
|
-
*
|
|
1203
|
-
* @param order - Order expression(s)
|
|
1204
|
-
* @param where - Optional filter conditions
|
|
1205
|
-
* @returns Sorted array of records
|
|
1206
|
-
*
|
|
1207
543
|
* @example
|
|
1208
|
-
* // Single column ascending
|
|
1209
544
|
* await User.orderBy('createdAt')
|
|
1210
|
-
*
|
|
1211
|
-
* // Single column descending
|
|
1212
|
-
* await User.orderBy(['createdAt', 'desc'])
|
|
1213
|
-
*
|
|
1214
|
-
* // Multiple columns
|
|
1215
|
-
* await User.orderBy([['lastName', 'asc'], ['firstName', 'asc']])
|
|
1216
|
-
*
|
|
1217
|
-
* // With where clause
|
|
1218
|
-
* await User.orderBy('name', { status: 'active' })
|
|
545
|
+
* await User.orderBy([['lastName', 'asc'], ['firstName', 'asc']], { status: 'active' })
|
|
1219
546
|
*/
|
|
1220
547
|
static orderBy<T extends typeof Model>(this: T, order: OrderByInput<TRecordFor<T>>, where?: WhereClauseFor<T>, queryOptions?: ModelQueryOptions): Promise<TRecordFor<T>[]>;
|
|
1221
548
|
/**
|
|
1222
|
-
* Get paginated records.
|
|
1223
|
-
*
|
|
1224
|
-
* @param options - Pagination options
|
|
1225
|
-
* @returns Paginated result with data and metadata
|
|
1226
|
-
*
|
|
1227
549
|
* @example
|
|
1228
|
-
*
|
|
1229
|
-
* // result.data - Array of users
|
|
1230
|
-
* // result.meta.total - Total count
|
|
1231
|
-
* // result.meta.hasMore - Whether there are more pages
|
|
1232
|
-
*
|
|
1233
|
-
* // With filtering and ordering
|
|
1234
|
-
* await User.paginate({
|
|
1235
|
-
* page: 2,
|
|
1236
|
-
* perPage: 20,
|
|
1237
|
-
* where: { status: 'active' },
|
|
1238
|
-
* orderBy: ['createdAt', 'desc']
|
|
1239
|
-
* })
|
|
550
|
+
* await User.paginate({ page: 2, perPage: 20, where: { status: 'active' } })
|
|
1240
551
|
*/
|
|
1241
552
|
static paginate<T extends typeof Model>(this: T, options?: PaginateOptions<TRecordFor<T>>, queryOptions?: ModelQueryOptions): Promise<PaginatedResult<TRecordFor<T>>>;
|
|
1242
|
-
/**
|
|
1243
|
-
* Paginate records with eager-loaded relationships.
|
|
1244
|
-
*
|
|
1245
|
-
* @param relations - Relation name(s) to load
|
|
1246
|
-
* @param options - Pagination options
|
|
1247
|
-
* @returns Paginated result with loaded relationships
|
|
1248
|
-
*
|
|
1249
|
-
* @example
|
|
1250
|
-
* const result = await User.withPaginate('posts', { page: 1, perPage: 10 })
|
|
1251
|
-
* // result.data - Users with their posts loaded
|
|
1252
|
-
* // result.meta - Pagination metadata
|
|
1253
|
-
*/
|
|
1254
553
|
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[]>>>;
|
|
1255
|
-
/**
|
|
1256
|
-
* Create a new record.
|
|
1257
|
-
*
|
|
1258
|
-
* @param data - Record data to insert
|
|
1259
|
-
* @returns The created record
|
|
1260
|
-
*
|
|
1261
|
-
* @example
|
|
1262
|
-
* const user = await User.create({
|
|
1263
|
-
* name: 'John Doe',
|
|
1264
|
-
* email: 'john@example.com'
|
|
1265
|
-
* })
|
|
1266
|
-
*/
|
|
1267
554
|
static create<T extends typeof Model>(this: T, data: TCreateFor<T>, writeOptions?: ModelWriteOptions): Promise<TRecordFor<T>>;
|
|
1268
555
|
/**
|
|
1269
|
-
* Create
|
|
1270
|
-
*
|
|
1271
|
-
* records) — never for raw request input.
|
|
1272
|
-
*
|
|
1273
|
-
* @example
|
|
1274
|
-
* const user = await User.forceCreate({
|
|
1275
|
-
* name: profile.name,
|
|
1276
|
-
* email: profile.email,
|
|
1277
|
-
* passwordHash: `oauth:${provider}:${profile.id}`,
|
|
1278
|
-
* })
|
|
556
|
+
* Create bypassing mass-assignment protection. Trusted server-side data only
|
|
557
|
+
* (OAuth linking, seeders, system records), never raw request input.
|
|
1279
558
|
*/
|
|
1280
559
|
static forceCreate<T extends typeof Model>(this: T, data: TCreateFor<T>, writeOptions?: ModelWriteOptions): Promise<TRecordFor<T>>;
|
|
1281
560
|
protected static runCreate<T extends typeof Model>(this: T, data: TCreateFor<T>, writeOptions: ModelWriteOptions | undefined, applyFillable: boolean): Promise<TRecordFor<T>>;
|
|
1282
|
-
/**
|
|
1283
|
-
* Update records matching the conditions.
|
|
1284
|
-
*
|
|
1285
|
-
* @param where - Filter conditions to identify records
|
|
1286
|
-
* @param data - Data to update
|
|
1287
|
-
* @returns The updated record
|
|
1288
|
-
*
|
|
1289
|
-
* @example
|
|
1290
|
-
* await User.update({ id: 1 }, { name: 'Jane Doe' })
|
|
1291
|
-
*/
|
|
1292
561
|
static update<T extends typeof Model>(this: T, where: WhereClauseFor<T>, data: Partial<TCreateFor<T>>, writeOptions?: ModelWriteOptions): Promise<TRecordFor<T>>;
|
|
1293
562
|
/**
|
|
1294
|
-
* Update
|
|
1295
|
-
*
|
|
563
|
+
* Update bypassing mass-assignment protection. Trusted server-side data only,
|
|
564
|
+
* never raw request input.
|
|
1296
565
|
*/
|
|
1297
566
|
static forceUpdate<T extends typeof Model>(this: T, where: WhereClauseFor<T>, data: Partial<TCreateFor<T>>, writeOptions?: ModelWriteOptions): Promise<TRecordFor<T>>;
|
|
1298
567
|
protected static runUpdate<T extends typeof Model>(this: T, where: WhereClauseFor<T>, data: Partial<TCreateFor<T>>, writeOptions: ModelWriteOptions | undefined, applyFillable: boolean): Promise<TRecordFor<T>>;
|
|
1299
|
-
/**
|
|
1300
|
-
* Delete records matching the conditions.
|
|
1301
|
-
*
|
|
1302
|
-
* @param where - Filter conditions to identify records
|
|
1303
|
-
* @returns Number of deleted records or void depending on adapter
|
|
1304
|
-
*
|
|
1305
|
-
* @example
|
|
1306
|
-
* await User.delete({ id: 1 })
|
|
1307
|
-
* await User.delete({ status: 'inactive' })
|
|
1308
|
-
*/
|
|
1309
568
|
static delete<T extends typeof Model>(this: T, where: WhereClauseFor<T>, writeOptions?: ModelWriteOptions): Promise<number | PlainObject | void>;
|
|
1310
569
|
/**
|
|
1311
|
-
*
|
|
1312
|
-
*
|
|
1313
|
-
* @param db - Optional Drizzle database instance
|
|
1314
|
-
* @returns Drizzle query builder starting with `select().from(table)`
|
|
1315
|
-
*
|
|
1316
|
-
* @example
|
|
1317
|
-
* // Simple query
|
|
1318
|
-
* const users = await User.query(db)
|
|
1319
|
-
* .where(eq(users.status, 'active'))
|
|
1320
|
-
* .limit(10)
|
|
1321
|
-
*
|
|
1322
|
-
* // With joins
|
|
1323
|
-
* const usersWithPosts = await User.query(db)
|
|
1324
|
-
* .leftJoin(posts, eq(users.id, posts.userId))
|
|
570
|
+
* A raw Drizzle builder starting at `select().from(table)`. Carries no model
|
|
571
|
+
* scopes, casts or accessors.
|
|
1325
572
|
*/
|
|
1326
573
|
static query<TDatabase extends {
|
|
1327
574
|
select: (...args: any[]) => any;
|
|
@@ -1331,63 +578,35 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
|
|
|
1331
578
|
// eslint-disable-line @typescript-eslint/no-explicit-any
|
|
1332
579
|
this: typeof Model, db?: TDatabase): SelectFrom<TDatabase>;
|
|
1333
580
|
/**
|
|
1334
|
-
* Eager-load
|
|
1335
|
-
*
|
|
1336
|
-
* @param relations - Relation name(s) to load
|
|
1337
|
-
* @param where - Optional filter conditions
|
|
1338
|
-
* @returns Records with loaded relationships
|
|
581
|
+
* Eager-load relations, one name or several, nested via dot notation.
|
|
1339
582
|
*
|
|
1340
583
|
* @example
|
|
1341
|
-
*
|
|
1342
|
-
* const usersWithPosts = await User.with('posts')
|
|
1343
|
-
*
|
|
1344
|
-
* // Multiple relations
|
|
1345
|
-
* const usersWithAll = await User.with(['posts', 'comments'])
|
|
1346
|
-
*
|
|
1347
|
-
* // With filtering
|
|
1348
|
-
* const activeUsersWithPosts = await User.with('posts', { status: 'active' })
|
|
1349
|
-
*
|
|
1350
|
-
* // Nested relations via dot notation
|
|
1351
|
-
* const usersWithPostComments = await User.with('posts.comments')
|
|
584
|
+
* await User.with(['posts.comments', 'profile'], { status: 'active' })
|
|
1352
585
|
*/
|
|
1353
586
|
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[]>>>;
|
|
1354
587
|
/**
|
|
1355
|
-
*
|
|
1356
|
-
*
|
|
1357
|
-
* the related rows themselves; belongsTo yields 0 or 1.
|
|
1358
|
-
*
|
|
1359
|
-
* @example
|
|
1360
|
-
* const users = await User.withCount('posts')
|
|
1361
|
-
* users[0].postsCount // number
|
|
588
|
+
* Attaches a `${name}Count` per record without loading the related rows.
|
|
589
|
+
* belongsTo yields 0 or 1.
|
|
1362
590
|
*/
|
|
1363
591
|
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[]>>>;
|
|
1364
592
|
/** @internal Attaches a `${name}Count` field for one relation. */
|
|
1365
593
|
protected static loadRelationCountInto<T extends typeof Model>(this: T, records: Array<PlainObject>, relationName: string, queryOptions?: ModelQueryOptions): Promise<void>;
|
|
1366
594
|
/**
|
|
1367
|
-
* @internal Used by QueryBuilder for eager loading.
|
|
1368
|
-
*
|
|
1369
|
-
*
|
|
1370
|
-
*
|
|
1371
|
-
* paths is loaded exactly once. Walking `posts.comments` and `posts.tags`
|
|
1372
|
-
* independently would load `posts` twice, and the loaders assign fresh
|
|
1373
|
-
* spread copies — so the second pass would replace the very row objects the
|
|
1374
|
-
* first had already attached children to, and only the last path would
|
|
1375
|
-
* survive.
|
|
595
|
+
* @internal Used by QueryBuilder for eager loading. Paths are grouped by head
|
|
596
|
+
* segment so a shared relation loads once: the loaders assign fresh spread
|
|
597
|
+
* copies, so a second pass over `posts` would replace the very rows the first
|
|
598
|
+
* attached children to and only the last path would survive.
|
|
1376
599
|
*/
|
|
1377
600
|
static loadRelationsInto<T extends typeof Model>(this: T, records: Array<PlainObject>, relationNames: readonly string[], queryOptions?: ModelQueryOptions, constraints?: EagerLoadConstraints, pathPrefix?: string): Promise<void>;
|
|
1378
601
|
/**
|
|
1379
|
-
* @internal Public
|
|
1380
|
-
*
|
|
1381
|
-
* Internal callers should use {@link loadRelationsInto} instead.
|
|
602
|
+
* @internal Public because generated code reaches it; internal callers should
|
|
603
|
+
* use {@link loadRelationsInto}.
|
|
1382
604
|
*/
|
|
1383
605
|
static loadRelationInto<T extends typeof Model>(this: T, records: Array<PlainObject>, relationName: string, queryOptions?: ModelQueryOptions, constraints?: EagerLoadConstraints, pathPrefix?: string): Promise<void>;
|
|
1384
606
|
/**
|
|
1385
|
-
*
|
|
1386
|
-
*
|
|
1387
|
-
*
|
|
1388
|
-
* so `pathPrefix` accumulates the path walked so far as the recursion
|
|
1389
|
-
* descends: at `posts.comments` the leaf looks itself up under that whole
|
|
1390
|
-
* key, not under `comments`.
|
|
607
|
+
* `constraints` are keyed by the full path of the level each constrains, so
|
|
608
|
+
* `pathPrefix` accumulates the path walked so far: at `posts.comments` the
|
|
609
|
+
* leaf looks itself up under that whole key, not under `comments`.
|
|
1391
610
|
*/
|
|
1392
611
|
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>;
|
|
1393
612
|
protected static loadHasMany(records: Array<PlainObject>, definition: HasManyRelationDefinition, queryOptions?: ModelQueryOptions, constraint?: EagerLoadConstraint): Promise<void>;
|
|
@@ -1480,151 +699,87 @@ interface MorphToRelationDefinition {
|
|
|
1480
699
|
related: undefined;
|
|
1481
700
|
morphName: string;
|
|
1482
701
|
}
|
|
1483
|
-
/** Type for hasMany relation results (array of related records). */
|
|
1484
702
|
type HasManyRelationResult<T extends typeof Model> = Array<TRecordFor<T>>;
|
|
1485
|
-
/** Type for belongsTo relation results (single record or null). */
|
|
1486
703
|
type BelongsToRelationResult<T extends typeof Model> = TRecordFor<T> | null;
|
|
1487
|
-
/** Utility type for hasMany relation data shape. */
|
|
1488
704
|
type HasManyRecord<TRecord extends PlainObject> = TRecord[];
|
|
1489
|
-
/** Utility type for belongsTo relation data shape. */
|
|
1490
705
|
type BelongsToRecord<TRecord extends PlainObject> = TRecord | null;
|
|
1491
706
|
/**
|
|
1492
|
-
*
|
|
1493
|
-
*
|
|
1494
|
-
* `declare` modifier so no runtime placeholder value is needed:
|
|
707
|
+
* For a belongsTo backed by a NOT NULL foreign key, where the parent is
|
|
708
|
+
* guaranteed once loaded.
|
|
1495
709
|
*
|
|
1496
710
|
* @example
|
|
1497
711
|
* declare static relationTypes: { author: BelongsToRequiredRecord<UserRecord> }
|
|
1498
712
|
*/
|
|
1499
713
|
type BelongsToRequiredRecord<TRecord extends PlainObject> = TRecord;
|
|
1500
|
-
/** Type for hasOne relation results (single record or null). */
|
|
1501
714
|
type HasOneRelationResult<T extends typeof Model> = TRecordFor<T> | null;
|
|
1502
|
-
/** Type for belongsToMany relation results (array of related records). */
|
|
1503
715
|
type BelongsToManyRelationResult<T extends typeof Model> = Array<TRecordFor<T>>;
|
|
1504
|
-
/** Type for hasManyThrough relation results (array of related records). */
|
|
1505
716
|
type HasManyThroughRelationResult<T extends typeof Model> = Array<TRecordFor<T>>;
|
|
1506
|
-
/** Utility type for hasOne relation data shape. */
|
|
1507
717
|
type HasOneRecord<TRecord extends PlainObject> = TRecord | null;
|
|
1508
|
-
/** Utility type for belongsToMany relation data shape. */
|
|
1509
718
|
type BelongsToManyRecord<TRecord extends PlainObject> = TRecord[];
|
|
1510
|
-
/** Utility type for hasManyThrough relation data shape. */
|
|
1511
719
|
type HasManyThroughRecord<TRecord extends PlainObject> = TRecord[];
|
|
1512
|
-
/** Type for morphMany relation results (array of related records). */
|
|
1513
720
|
type MorphManyRelationResult<T extends typeof Model> = Array<TRecordFor<T>>;
|
|
1514
|
-
/** Utility type for morphMany relation data shape. */
|
|
1515
721
|
type MorphManyRecord<TRecord extends PlainObject> = TRecord[];
|
|
1516
|
-
/** Type for morphTo relation results (single record or null). */
|
|
1517
722
|
type MorphToRelationResult = PlainObject | null;
|
|
1518
|
-
/** Utility type for morphTo relation data shape. */
|
|
1519
723
|
type MorphToRecord = PlainObject | null;
|
|
1520
|
-
/** Utility type: model record with specified relations merged. */
|
|
1521
724
|
type WithRelations<T extends typeof Model, K extends RelationPath<T> | readonly RelationPath<T>[]> = TRecordFor<T> & RelationTypePick<T, K>;
|
|
1522
725
|
type ModelClassWithTable<TTable extends TableShape, TBase extends typeof Model, TCreate extends PlainObject> = TBase & {
|
|
1523
726
|
readonly table: TTable;
|
|
1524
727
|
readonly recordType: InferModelRecord<TTable>;
|
|
1525
728
|
readonly createType: TCreate;
|
|
1526
729
|
};
|
|
1527
|
-
/** A key that can appear in a model's create payload: a table column, or a named field its base contributes. */
|
|
1528
730
|
type CreateKey<TTable extends TableShape, TBase extends typeof Model> = keyof InferModelInsert<TTable> | keyof TCreateFor<TBase>;
|
|
1529
731
|
/**
|
|
1530
|
-
* Named fields a base
|
|
1531
|
-
*
|
|
1532
|
-
*
|
|
1533
|
-
* collapse, or every misspelling would pass the allowlist checks below.
|
|
732
|
+
* Named fields a base contributes to the create payload (`AuthenticatableModel`'s
|
|
733
|
+
* virtual `password`). A plain `Model` base declares no createType, so its keys
|
|
734
|
+
* collapse to `string` — guard that, or every misspelling passes the allowlists.
|
|
1534
735
|
*/
|
|
1535
736
|
type BaseContributedKey<TBase extends typeof Model> = string extends keyof TCreateFor<TBase> & string ? never : keyof TCreateFor<TBase> & string;
|
|
1536
|
-
/** A key valid in a `fillable` allowlist: an insertable column, or a base-contributed field. */
|
|
1537
737
|
type FillableKey<TTable extends TableShape, TBase extends typeof Model> = (keyof InferModelInsert<TTable> & string) | BaseContributedKey<TBase>;
|
|
1538
|
-
/** A key of the record read back from the table. */
|
|
1539
738
|
type RecordKey<TTable extends TableShape> = keyof InferModelRecord<TTable> & string;
|
|
1540
739
|
/**
|
|
1541
|
-
*
|
|
1542
|
-
*
|
|
1543
|
-
*
|
|
1544
|
-
* here: the accessor functions are context-sensitive, which defers inference
|
|
1545
|
-
* past the point where the key type parameter falls back to its default.
|
|
740
|
+
* Homomorphic on purpose, so the key union is inferred from the object
|
|
741
|
+
* literal's keys: the accessor functions are context-sensitive, which under a
|
|
742
|
+
* plain `Record<string, fn>` defers inference past the key parameter's default.
|
|
1546
743
|
*/
|
|
1547
744
|
type AccessorsShape<TTable extends TableShape, TKey extends string> = { [K in TKey]: (record: InferModelRecord<TTable>) => unknown; };
|
|
1548
745
|
type CreateShape<TTable extends TableShape, TBase extends typeof Model, TOptional extends keyof InferModelInsert<TTable>, TRequire extends CreateKey<TTable, TBase>> = Partial<Pick<InferModelInsert<TTable>, TOptional>> & Omit<InferModelInsert<TTable>, TOptional> & TCreateFor<TBase> & Required<Pick<InferModelInsert<TTable> & TCreateFor<TBase>, TRequire & keyof (InferModelInsert<TTable> & TCreateFor<TBase>)>>;
|
|
1549
746
|
/**
|
|
1550
|
-
*
|
|
1551
|
-
*
|
|
1552
|
-
*
|
|
1553
|
-
*
|
|
1554
|
-
*
|
|
1555
|
-
* into `passwordHash`, so a user model wants the column optional and the
|
|
1556
|
-
* virtual field required. `optionalOnCreate` and `requireOnCreate` reshape the
|
|
1557
|
-
* inferred type without any cast.
|
|
1558
|
-
*
|
|
1559
|
-
* The allowlist statics (`fillable`, `hidden`, `visible`, `accessors`,
|
|
1560
|
-
* `appends`) can be passed here instead of declared on the subclass: the
|
|
1561
|
-
* option form checks every name against the table's columns (plus fields the
|
|
1562
|
-
* `base` contributes), so a typo is a compile error instead of a silently
|
|
1563
|
-
* ineffective entry. A `static` declaration on the subclass still works and
|
|
1564
|
-
* shadows the option, matching normal class semantics.
|
|
1565
|
-
*
|
|
1566
|
-
* @example
|
|
1567
|
-
* export class Post extends defineModel(posts, {
|
|
1568
|
-
* fillable: ['title', 'body'],
|
|
1569
|
-
* }) {}
|
|
1570
|
-
*
|
|
1571
|
-
* export class User extends defineModel(users, {
|
|
1572
|
-
* base: AuthenticatableModel,
|
|
1573
|
-
* optionalOnCreate: ['passwordHash'],
|
|
1574
|
-
* requireOnCreate: ['password'],
|
|
1575
|
-
* fillable: ['name', 'email', 'password'],
|
|
1576
|
-
* hidden: ['passwordHash', 'rememberToken'],
|
|
1577
|
-
* }) {}
|
|
747
|
+
* A table-backed model base class: `recordType`/`createType` inferred from the
|
|
748
|
+
* table, `optionalOnCreate`/`requireOnCreate` reshaping the create payload without
|
|
749
|
+
* a cast (`AuthenticatableModel` hashes a virtual `password` into `passwordHash`).
|
|
750
|
+
* Allowlist statics passed as options are checked against the table's columns, so
|
|
751
|
+
* a typo is a compile error; a `static` on the subclass shadows the option.
|
|
1578
752
|
*/
|
|
1579
753
|
declare function defineModel<TTable extends TableShape, TBase extends typeof Model = typeof Model, const TOptional extends keyof InferModelInsert<TTable> = never, const TRequire extends CreateKey<TTable, TBase> = never, TAccessorKey extends string = never>(table: TTable, options?: {
|
|
1580
754
|
base?: TBase;
|
|
1581
|
-
/**
|
|
1582
|
-
* Columns the model fills in itself, so callers need not pass them.
|
|
1583
|
-
* Type-level only.
|
|
1584
|
-
*/
|
|
755
|
+
/** Type-level only: columns the model fills in itself. */
|
|
1585
756
|
optionalOnCreate?: readonly TOptional[];
|
|
1586
757
|
/**
|
|
1587
|
-
*
|
|
1588
|
-
* (Drizzle marks defaulted ones optional) and
|
|
1589
|
-
*
|
|
1590
|
-
* Type-level only.
|
|
758
|
+
* Type-level only: fields to make required on the create payload. Accepts
|
|
759
|
+
* table columns (Drizzle marks defaulted ones optional) and `base`-
|
|
760
|
+
* contributed fields such as the virtual `password`.
|
|
1591
761
|
*/
|
|
1592
762
|
requireOnCreate?: readonly TRequire[];
|
|
1593
|
-
/**
|
|
1594
|
-
* Typed form of `static fillable`: mass-assignment allowlist checked
|
|
1595
|
-
* against insertable columns and base-contributed fields.
|
|
1596
|
-
*/
|
|
763
|
+
/** Typed `static fillable`, checked against insertable and base fields. */
|
|
1597
764
|
fillable?: readonly FillableKey<TTable, TBase>[];
|
|
1598
|
-
/**
|
|
1599
|
-
* Typed form of `static hidden`: fields excluded from serialization,
|
|
1600
|
-
* checked against record columns and declared accessors.
|
|
1601
|
-
*/
|
|
765
|
+
/** Typed `static hidden`, checked against record columns and accessors. */
|
|
1602
766
|
hidden?: readonly (RecordKey<TTable> | NoInfer<TAccessorKey>)[];
|
|
1603
|
-
/**
|
|
1604
|
-
* Typed form of `static visible`: serialization allowlist, checked
|
|
1605
|
-
* against record columns and declared accessors.
|
|
1606
|
-
*/
|
|
767
|
+
/** Typed `static visible`, checked against record columns and accessors. */
|
|
1607
768
|
visible?: readonly (RecordKey<TTable> | NoInfer<TAccessorKey>)[];
|
|
1608
769
|
/**
|
|
1609
|
-
* Typed
|
|
1610
|
-
*
|
|
1611
|
-
*
|
|
1612
|
-
* infer, the mapped type alone collapses to `{}`, which admits anything.
|
|
770
|
+
* Typed `static accessors`; the names here are what `appends` may
|
|
771
|
+
* reference. The Record intersection rejects non-object values — with no
|
|
772
|
+
* keys to infer, the mapped type alone collapses to `{}`.
|
|
1613
773
|
*/
|
|
1614
774
|
accessors?: AccessorsShape<TTable, TAccessorKey> & Record<string, (record: InferModelRecord<TTable>) => unknown>;
|
|
1615
|
-
/**
|
|
1616
|
-
* Typed form of `static appends`: virtual attributes to serialize,
|
|
1617
|
-
* checked against the names declared in `accessors`.
|
|
1618
|
-
*/
|
|
775
|
+
/** Typed `static appends`, checked against the names in `accessors`. */
|
|
1619
776
|
appends?: readonly NoInfer<TAccessorKey>[];
|
|
1620
777
|
}): ModelClassWithTable<TTable, TBase, CreateShape<TTable, TBase, TOptional, TRequire>>;
|
|
1621
778
|
//#endregion
|
|
1622
779
|
//#region src/ModelNotFoundException.d.ts
|
|
1623
780
|
/**
|
|
1624
|
-
*
|
|
1625
|
-
*
|
|
1626
|
-
* Carries a `statusCode` of 404 so that framework exception handlers
|
|
1627
|
-
* can render it as a proper HTTP 404 without coupling to the ORM package.
|
|
781
|
+
* Thrown by findOrFail/firstOrFail. Carries `statusCode` 404 so exception
|
|
782
|
+
* handlers can render it without coupling to the ORM package.
|
|
1628
783
|
*/
|
|
1629
784
|
declare class ModelNotFoundException extends Error {
|
|
1630
785
|
readonly statusCode = 404;
|
|
@@ -1635,16 +790,10 @@ declare class ModelNotFoundException extends Error {
|
|
|
1635
790
|
//#endregion
|
|
1636
791
|
//#region src/MassAssignmentException.d.ts
|
|
1637
792
|
/**
|
|
1638
|
-
* Thrown when mass assignment receives fields it must not write.
|
|
1639
|
-
*
|
|
1640
|
-
*
|
|
1641
|
-
*
|
|
1642
|
-
*
|
|
1643
|
-
* `reason` distinguishes the two rules that throw:
|
|
1644
|
-
* - `'not-fillable'` — the field is outside the model's `fillable` allowlist.
|
|
1645
|
-
* - `'denied'` — the field is in the model's `deniedFields()` (e.g. a
|
|
1646
|
-
* credential column on an authenticatable model) and can never be
|
|
1647
|
-
* mass-assigned, `fillable` notwithstanding.
|
|
793
|
+
* Thrown when mass assignment receives fields it must not write. Discarding
|
|
794
|
+
* them silently hides bugs and can mask injection attempts, so models throw.
|
|
795
|
+
* `reason` is `'not-fillable'` (outside the `fillable` allowlist) or
|
|
796
|
+
* `'denied'` (in `deniedFields()`, unassignable whatever `fillable` says).
|
|
1648
797
|
*/
|
|
1649
798
|
declare class MassAssignmentException extends Error {
|
|
1650
799
|
readonly model: string;
|
|
@@ -1656,48 +805,24 @@ declare class MassAssignmentException extends Error {
|
|
|
1656
805
|
}
|
|
1657
806
|
//#endregion
|
|
1658
807
|
//#region src/SoftDeletes.d.ts
|
|
1659
|
-
/**
|
|
1660
|
-
* Interface describing the static methods added by the SoftDeletes mixin.
|
|
1661
|
-
*/
|
|
808
|
+
/** The static methods the SoftDeletes mixin adds. */
|
|
1662
809
|
interface SoftDeletesStatic {
|
|
1663
|
-
/** Column name used for tracking soft deletion timestamp. */
|
|
1664
810
|
deletedAtColumn: string;
|
|
1665
811
|
/** Start a query that includes soft-deleted records. */
|
|
1666
|
-
withTrashed(): QueryBuilder<PlainObject>;
|
|
812
|
+
withTrashed(queryOptions?: ModelQueryOptions): QueryBuilder<PlainObject>;
|
|
1667
813
|
/** Start a query that returns only soft-deleted records. */
|
|
1668
|
-
onlyTrashed(): QueryBuilder<PlainObject>;
|
|
814
|
+
onlyTrashed(queryOptions?: ModelQueryOptions): QueryBuilder<PlainObject>;
|
|
1669
815
|
/** Restore soft-deleted records by setting deletedAt back to null. */
|
|
1670
|
-
restore(where: Partial<Record<string, unknown
|
|
816
|
+
restore(where: Partial<Record<string, unknown>>, writeOptions?: ModelWriteOptions): Promise<PlainObject>;
|
|
1671
817
|
/** Permanently delete records from the database, bypassing soft delete. */
|
|
1672
|
-
forceDelete(where: Partial<Record<string, unknown
|
|
818
|
+
forceDelete(where: Partial<Record<string, unknown>>, writeOptions?: ModelWriteOptions): Promise<number | PlainObject | void>;
|
|
1673
819
|
}
|
|
1674
820
|
/**
|
|
1675
|
-
* Mixin
|
|
1676
|
-
*
|
|
1677
|
-
* When applied, `delete()` sets a `deletedAt` timestamp instead of removing the
|
|
1678
|
-
* record from the database. All default queries automatically exclude soft-deleted
|
|
1679
|
-
* records via a global scope named 'softDelete'.
|
|
821
|
+
* Mixin where `delete()` sets `deletedAt` instead of removing the row, and a
|
|
822
|
+
* global scope named 'softDelete' excludes those rows from every query.
|
|
1680
823
|
*
|
|
1681
824
|
* @example
|
|
1682
825
|
* class Post extends SoftDeletes(defineModel(posts)) {}
|
|
1683
|
-
*
|
|
1684
|
-
* // Soft delete a record (sets deletedAt)
|
|
1685
|
-
* await Post.delete({ id: 1 })
|
|
1686
|
-
*
|
|
1687
|
-
* // Query only non-deleted records (default behavior)
|
|
1688
|
-
* const posts = await Post.all()
|
|
1689
|
-
*
|
|
1690
|
-
* // Include soft-deleted records
|
|
1691
|
-
* const allPosts = await Post.withTrashed().get()
|
|
1692
|
-
*
|
|
1693
|
-
* // Query only soft-deleted records
|
|
1694
|
-
* const trashed = await Post.onlyTrashed().get()
|
|
1695
|
-
*
|
|
1696
|
-
* // Restore a soft-deleted record
|
|
1697
|
-
* await Post.restore({ id: 1 })
|
|
1698
|
-
*
|
|
1699
|
-
* // Permanently delete a record
|
|
1700
|
-
* await Post.forceDelete({ id: 1 })
|
|
1701
826
|
*/
|
|
1702
827
|
declare function SoftDeletes<TBase extends typeof Model>(Base: TBase): TBase & SoftDeletesStatic;
|
|
1703
828
|
//#endregion
|
|
@@ -1744,33 +869,21 @@ declare const DrizzleAdapter: ORMAdapterAdvanced & {
|
|
|
1744
869
|
//#endregion
|
|
1745
870
|
//#region src/adapters/drizzle-conditions.d.ts
|
|
1746
871
|
/**
|
|
1747
|
-
* Translates an array of QueryBuilder WhereConditions into a single
|
|
1748
|
-
*
|
|
1749
|
-
*
|
|
1750
|
-
*
|
|
1751
|
-
*
|
|
1752
|
-
* .where('a', 1).where('b', 2).orWhere('c', 3)
|
|
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.
|
|
1756
|
-
*
|
|
1757
|
-
* @param table - The Drizzle table object
|
|
1758
|
-
* @param conditions - Array of WhereCondition objects from QueryBuilder
|
|
1759
|
-
* @returns A Drizzle SQL condition or undefined if no conditions
|
|
872
|
+
* Translates an array of QueryBuilder WhereConditions into a single Drizzle ORM
|
|
873
|
+
* condition expression. The list's sequential semantics — an OR group folds
|
|
874
|
+
* everything before it into the OR, so `.where('a',1).where('b',2).orWhere('c',3)`
|
|
875
|
+
* is `(a = 1 AND b = 2) OR (c = 3)` — are already applied by
|
|
876
|
+
* `normalizeConditionSequence`, leaving a flat-join tree to render here.
|
|
1760
877
|
*/
|
|
1761
878
|
declare function buildDrizzleConditions(table: unknown, conditions: WhereCondition[]): SQL | undefined;
|
|
1762
879
|
//#endregion
|
|
1763
880
|
//#region src/migration-utils.d.ts
|
|
1764
881
|
/**
|
|
1765
882
|
* What one `migrateDatabase()` call had to work with. `db:migrate` reports
|
|
1766
|
-
* success off this
|
|
1767
|
-
*
|
|
1768
|
-
*
|
|
1769
|
-
*
|
|
1770
|
-
* It describes the run the driver memoized, not the folder as it stands now.
|
|
1771
|
-
* Migrations are single-flighted per handle, so a second call returns this same
|
|
1772
|
-
* summary without re-reading the folder — which is the pre-existing no-rerun
|
|
1773
|
-
* behaviour, faithfully reported.
|
|
883
|
+
* success off this, not off the call returning: an empty folder applies
|
|
884
|
+
* nothing, and "completed" there reads as an up-to-date database. Describes
|
|
885
|
+
* the run the driver memoized — migrations are single-flighted per handle, so
|
|
886
|
+
* a second call returns this same summary without re-reading the folder.
|
|
1774
887
|
*/
|
|
1775
888
|
interface MigrationRunSummary {
|
|
1776
889
|
/** The folder the migrator read, absolute as the driver resolved it. */
|
|
@@ -1778,10 +891,9 @@ interface MigrationRunSummary {
|
|
|
1778
891
|
/** drizzle-kit migrations found there (one folder each, holding migration.sql). */
|
|
1779
892
|
migrationsFound: number;
|
|
1780
893
|
/**
|
|
1781
|
-
* Loose .sql files
|
|
1782
|
-
*
|
|
1783
|
-
*
|
|
1784
|
-
* no migrations yet.
|
|
894
|
+
* Loose .sql files there, which the drizzle migrator never runs. Non-zero
|
|
895
|
+
* alongside `migrationsFound: 0` means the folder holds nothing to apply,
|
|
896
|
+
* a different problem from having generated no migrations yet.
|
|
1785
897
|
*/
|
|
1786
898
|
looseSqlFiles: number;
|
|
1787
899
|
}
|
|
@@ -1793,13 +905,9 @@ interface MigrationStatusEntry {
|
|
|
1793
905
|
//#endregion
|
|
1794
906
|
//#region src/seeder.d.ts
|
|
1795
907
|
/**
|
|
1796
|
-
* The context a seeder receives. `db`
|
|
1797
|
-
*
|
|
1798
|
-
*
|
|
1799
|
-
* app is not on PostgreSQL.
|
|
1800
|
-
*
|
|
1801
|
-
* The type parameter defaults to `PostgresJsDatabase` for backwards
|
|
1802
|
-
* compatibility — seeders written before this was generic keep compiling.
|
|
908
|
+
* The context a seeder receives. `db`'s type depends on the dialect: annotate
|
|
909
|
+
* the seeder with the matching alias below whenever the app is not on
|
|
910
|
+
* PostgreSQL, which is the default only for backwards compatibility.
|
|
1803
911
|
*/
|
|
1804
912
|
interface SeederContext<TDatabase = PostgresJsDatabase> {
|
|
1805
913
|
db: TDatabase;
|
|
@@ -1815,9 +923,8 @@ type SqliteSeederContext = SeederContext<SQLiteBunDatabase>;
|
|
|
1815
923
|
type AwsDataApiSeederContext = SeederContext<AwsDataApiPgDatabase>;
|
|
1816
924
|
/**
|
|
1817
925
|
* What one `runSeeders()` call had to work with. `db:seed` reports success off
|
|
1818
|
-
* this
|
|
1819
|
-
*
|
|
1820
|
-
* rows the seeders would have written.
|
|
926
|
+
* this, not off the call returning: an empty folder seeds nothing, and
|
|
927
|
+
* "executed" there reads as a database that now holds the seeded rows.
|
|
1821
928
|
*/
|
|
1822
929
|
interface SeederRunSummary {
|
|
1823
930
|
/** The folder that was read, absolute as the driver resolved it. */
|
|
@@ -1825,17 +932,15 @@ interface SeederRunSummary {
|
|
|
1825
932
|
/** How many seeders ran. They run in the order their files sorted. */
|
|
1826
933
|
seedersRan: number;
|
|
1827
934
|
/**
|
|
1828
|
-
* Files with a seeder extension that exported nothing runnable
|
|
1829
|
-
*
|
|
1830
|
-
*
|
|
1831
|
-
* seeder yet, and one `make:seeder` would not solve.
|
|
935
|
+
* Files with a seeder extension that exported nothing runnable. Non-zero
|
|
936
|
+
* alongside `seedersRan: 0` means the folder holds nothing to run — a
|
|
937
|
+
* different problem from having written no seeder, which `make:seeder` fixes.
|
|
1832
938
|
*/
|
|
1833
939
|
filesWithoutSeeder: number;
|
|
1834
940
|
}
|
|
1835
941
|
/**
|
|
1836
|
-
* Seeders
|
|
1837
|
-
*
|
|
1838
|
-
* hand them — the same contract `runSeeders()` fulfils from the driver side.
|
|
942
|
+
* Seeders load as modules, so their dialect is unknowable here: `TDatabase` is
|
|
943
|
+
* the caller stating which database it will hand them.
|
|
1839
944
|
*/
|
|
1840
945
|
declare function loadSeeders<TDatabase = PostgresJsDatabase>(directory: string | URL): Promise<Array<SeederHandler<TDatabase>>>;
|
|
1841
946
|
/** Runs every seeder in `directory` and reports what the folder held. */
|
|
@@ -1850,9 +955,9 @@ interface PostgresDatabaseOptions {
|
|
|
1850
955
|
clientOptions?: postgres.Options<Record<string, never>>;
|
|
1851
956
|
seedersFolder?: string | URL;
|
|
1852
957
|
/**
|
|
1853
|
-
* Drizzle relations for RQB v2 (`db.query.*`)
|
|
1854
|
-
*
|
|
1855
|
-
*
|
|
958
|
+
* Drizzle relations for RQB v2 (`db.query.*`): `defineRelations(schema, ...)`
|
|
959
|
+
* from `drizzle-orm`, or `relations()` from `drizzle-orm/_relations` for the
|
|
960
|
+
* RQB v1 partial-upgrade path.
|
|
1856
961
|
*/
|
|
1857
962
|
relations?: Record<string, unknown>;
|
|
1858
963
|
}
|
|
@@ -1880,9 +985,9 @@ interface MySqlDatabaseOptions {
|
|
|
1880
985
|
clientOptions?: MySqlConnectionOptions;
|
|
1881
986
|
seedersFolder?: string | URL;
|
|
1882
987
|
/**
|
|
1883
|
-
* Drizzle relations for RQB v2 (`db.query.*`)
|
|
1884
|
-
*
|
|
1885
|
-
*
|
|
988
|
+
* Drizzle relations for RQB v2 (`db.query.*`): `defineRelations(schema, ...)`
|
|
989
|
+
* from `drizzle-orm`, or `relations()` from `drizzle-orm/_relations` for the
|
|
990
|
+
* RQB v1 partial-upgrade path.
|
|
1886
991
|
*/
|
|
1887
992
|
relations?: Record<string, unknown>;
|
|
1888
993
|
}
|
|
@@ -1909,9 +1014,9 @@ interface SqliteDatabaseOptions {
|
|
|
1909
1014
|
filename?: ConnectionResolver$1;
|
|
1910
1015
|
seedersFolder?: string | URL;
|
|
1911
1016
|
/**
|
|
1912
|
-
* Drizzle relations for RQB v2 (`db.query.*`)
|
|
1913
|
-
*
|
|
1914
|
-
*
|
|
1017
|
+
* Drizzle relations for RQB v2 (`db.query.*`): `defineRelations(schema, ...)`
|
|
1018
|
+
* from `drizzle-orm`, or `relations()` from `drizzle-orm/_relations` for the
|
|
1019
|
+
* RQB v1 partial-upgrade path.
|
|
1915
1020
|
*/
|
|
1916
1021
|
relations?: Record<string, unknown>;
|
|
1917
1022
|
}
|
|
@@ -1925,9 +1030,8 @@ interface SqliteDatabase {
|
|
|
1925
1030
|
seedDatabase(): Promise<SeederRunSummary>;
|
|
1926
1031
|
/**
|
|
1927
1032
|
* Drops every table and view (including the drizzle migration tracker), then
|
|
1928
|
-
* re-applies migrations — same end state as `guren db:reset`.
|
|
1929
|
-
*
|
|
1930
|
-
* there was no migration run to report.
|
|
1033
|
+
* re-applies migrations — same end state as `guren db:reset`. Undefined only
|
|
1034
|
+
* when a concurrent `closeDatabase()` left nothing to drop.
|
|
1931
1035
|
*/
|
|
1932
1036
|
resetDatabase(): Promise<MigrationRunSummary | undefined>;
|
|
1933
1037
|
/** Per-migration applied state derived from the drizzle-kit journal and the __drizzle_migrations table. */
|
|
@@ -1945,14 +1049,14 @@ interface D1DatabaseOptions {
|
|
|
1945
1049
|
binding: () => unknown;
|
|
1946
1050
|
/**
|
|
1947
1051
|
* Drizzle-kit migrations folder. D1 migrations are applied out-of-band via
|
|
1948
|
-
* `wrangler d1 migrations apply` (point `d1_databases[].migrations_dir`
|
|
1949
|
-
*
|
|
1052
|
+
* `wrangler d1 migrations apply` (point `d1_databases[].migrations_dir` here);
|
|
1053
|
+
* the factory only names it in error guidance.
|
|
1950
1054
|
*/
|
|
1951
1055
|
migrationsFolder?: string | URL;
|
|
1952
1056
|
/**
|
|
1953
|
-
* Drizzle relations for RQB v2 (`db.query.*`)
|
|
1954
|
-
*
|
|
1955
|
-
*
|
|
1057
|
+
* Drizzle relations for RQB v2 (`db.query.*`): `defineRelations(schema, ...)`
|
|
1058
|
+
* from `drizzle-orm`, or `relations()` from `drizzle-orm/_relations` for the
|
|
1059
|
+
* RQB v1 partial-upgrade path.
|
|
1956
1060
|
*/
|
|
1957
1061
|
relations?: Record<string, unknown>;
|
|
1958
1062
|
}
|
|
@@ -1971,8 +1075,8 @@ interface D1DatabaseHandle {
|
|
|
1971
1075
|
}
|
|
1972
1076
|
/**
|
|
1973
1077
|
* Cloudflare D1 database factory. D1 speaks the SQLite dialect, so schemas
|
|
1974
|
-
* written for `createSqliteDatabase` port unchanged;
|
|
1975
|
-
*
|
|
1078
|
+
* written for `createSqliteDatabase` port unchanged; wrangler owns migrations
|
|
1079
|
+
* (RFC 0003).
|
|
1976
1080
|
*/
|
|
1977
1081
|
declare function createD1Database(options: D1DatabaseOptions): D1DatabaseHandle;
|
|
1978
1082
|
//#endregion
|
|
@@ -1990,18 +1094,17 @@ interface AwsDataApiDatabaseOptions {
|
|
|
1990
1094
|
/** Extra RDSDataClient configuration (region, credentials, ...). */
|
|
1991
1095
|
clientOptions?: RDSDataClientConfig;
|
|
1992
1096
|
/**
|
|
1993
|
-
* Run pending migrations on the first `getDatabase()` call
|
|
1994
|
-
*
|
|
1995
|
-
*
|
|
1996
|
-
*
|
|
1997
|
-
* or the console handler (`{"command": "db:migrate"}`) once deployed.
|
|
1097
|
+
* Run pending migrations on the first `getDatabase()` call. Off by default:
|
|
1098
|
+
* on Lambda it costs several serialized Data API round trips on every cold
|
|
1099
|
+
* start. Migrate out of band instead — `db:migrate`, or the console handler
|
|
1100
|
+
* (`{"command": "db:migrate"}`) once deployed.
|
|
1998
1101
|
*/
|
|
1999
1102
|
migrateOnStart?: boolean;
|
|
2000
1103
|
seedersFolder?: string | URL;
|
|
2001
1104
|
/**
|
|
2002
|
-
* Drizzle relations for RQB v2 (`db.query.*`)
|
|
2003
|
-
*
|
|
2004
|
-
*
|
|
1105
|
+
* Drizzle relations for RQB v2 (`db.query.*`): `defineRelations(schema, ...)`
|
|
1106
|
+
* from `drizzle-orm`, or `relations()` from `drizzle-orm/_relations` for the
|
|
1107
|
+
* RQB v1 partial-upgrade path.
|
|
2005
1108
|
*/
|
|
2006
1109
|
relations?: Record<string, unknown>;
|
|
2007
1110
|
}
|
|
@@ -2021,11 +1124,7 @@ interface AwsDataApiDatabase {
|
|
|
2021
1124
|
declare function createAwsDataApiDatabase(options: AwsDataApiDatabaseOptions): AwsDataApiDatabase;
|
|
2022
1125
|
//#endregion
|
|
2023
1126
|
//#region src/serialization.d.ts
|
|
2024
|
-
/**
|
|
2025
|
-
* Serialize a model record for API/JSON output.
|
|
2026
|
-
*
|
|
2027
|
-
* Applies hidden/visible filtering, casts, accessors, and appends.
|
|
2028
|
-
*/
|
|
1127
|
+
/** Serializes a record for JSON output: appends, then visible/hidden filtering. */
|
|
2029
1128
|
declare function serializeRecord(record: PlainObject, options: {
|
|
2030
1129
|
hidden?: string[];
|
|
2031
1130
|
visible?: string[];
|