@guren/orm 2.6.1 → 2.6.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +228 -1174
- package/dist/index.js +275 -1076
- 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,29 @@ 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
|
-
/** Comparison operators supported by the QueryBuilder. */
|
|
32
27
|
type WhereOperator = '=' | '!=' | '>' | '<' | '>=' | '<=' | 'like' | 'in' | 'not in' | 'is null' | 'is not null';
|
|
33
|
-
/** A single field-level condition. */
|
|
34
28
|
interface SimpleCondition {
|
|
35
29
|
type: 'simple';
|
|
36
30
|
field: string;
|
|
37
31
|
operator: WhereOperator;
|
|
38
32
|
value: unknown;
|
|
39
33
|
}
|
|
40
|
-
/** A group of conditions joined by AND or OR. */
|
|
41
34
|
interface GroupCondition {
|
|
42
35
|
type: 'group';
|
|
43
36
|
boolean: 'and' | 'or';
|
|
44
37
|
conditions: WhereCondition[];
|
|
45
38
|
}
|
|
46
|
-
/** A where condition - either simple or grouped. */
|
|
47
39
|
type WhereCondition = SimpleCondition | GroupCondition;
|
|
48
40
|
/**
|
|
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.
|
|
41
|
+
* Composes a parenthesized condition group. Only the conditions added on the
|
|
42
|
+
* nested builder are read back — ordering, limits, eager loads and terminal
|
|
43
|
+
* calls made inside the callback are not part of the group.
|
|
55
44
|
*/
|
|
56
45
|
type WhereGroupCallback<TRecord extends PlainObject = PlainObject> = (query: QueryBuilder<TRecord>) => void;
|
|
57
|
-
/** Options carried by the QueryBuilder for query execution. */
|
|
58
46
|
interface QueryBuilderOptions {
|
|
59
47
|
orderBy: Array<{
|
|
60
48
|
column: string;
|
|
@@ -66,38 +54,21 @@ interface QueryBuilderOptions {
|
|
|
66
54
|
trx?: unknown;
|
|
67
55
|
}
|
|
68
56
|
/**
|
|
69
|
-
* A callback that further constrains the query
|
|
57
|
+
* A callback that further constrains the query that fetches an eager-loaded
|
|
70
58
|
* relation. Registered through the object form of {@link QueryBuilder.with}.
|
|
71
59
|
*/
|
|
72
60
|
type EagerLoadConstraint = (q: QueryBuilder) => void;
|
|
73
61
|
/**
|
|
74
|
-
* Constraint callbacks keyed by the relation path they constrain
|
|
75
|
-
*
|
|
76
|
-
* constrains the leaf.
|
|
62
|
+
* Constraint callbacks keyed by the relation path they constrain, naming the
|
|
63
|
+
* exact level: `posts` the head, `posts.comments` the leaf.
|
|
77
64
|
*/
|
|
78
65
|
type EagerLoadConstraints = ReadonlyMap<string, EagerLoadConstraint>;
|
|
79
66
|
/**
|
|
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()`.
|
|
67
|
+
* Fluent query builder for the Guren ORM. Thenable, so awaiting a builder
|
|
68
|
+
* resolves to the result of `get()`.
|
|
87
69
|
*
|
|
88
70
|
* @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
71
|
* const active = await User.where('active', true)
|
|
98
|
-
*
|
|
99
|
-
* // Pagination
|
|
100
|
-
* const page = await Post.where('status', 'published').paginate(1, 20)
|
|
101
72
|
*/
|
|
102
73
|
declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult extends PlainObject = TRecord> {
|
|
103
74
|
private conditions;
|
|
@@ -111,161 +82,49 @@ declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult ex
|
|
|
111
82
|
trx?: unknown;
|
|
112
83
|
});
|
|
113
84
|
/**
|
|
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)
|
|
85
|
+
* Add a where condition (AND): `where(field, value)`,
|
|
86
|
+
* `where(field, operator, value)`, `where(object)` for several equality
|
|
87
|
+
* checks, or `where(callback)` for a parenthesized group.
|
|
127
88
|
*/
|
|
128
89
|
where(callback: WhereGroupCallback<TRecord>): this;
|
|
129
90
|
where<TKey extends FieldKey<TRecord>>(field: TKey, value: TRecord[TKey]): this;
|
|
130
91
|
where<TKey extends FieldKey<TRecord>>(field: TKey, operator: WhereOperator, value: unknown): this;
|
|
131
92
|
where(conditions: Partial<Record<FieldKey<TRecord>, unknown>>): this;
|
|
132
93
|
/**
|
|
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)`.
|
|
94
|
+
* Same overloads as `where()`, joined with OR. With a callback the group is
|
|
95
|
+
* parenthesized whole: `(preceding conditions) OR (callback group)`.
|
|
139
96
|
*/
|
|
140
97
|
orWhere(callback: WhereGroupCallback<TRecord>): this;
|
|
141
98
|
orWhere<TKey extends FieldKey<TRecord>>(field: TKey, value: TRecord[TKey]): this;
|
|
142
99
|
orWhere<TKey extends FieldKey<TRecord>>(field: TKey, operator: WhereOperator, value: unknown): this;
|
|
143
100
|
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
101
|
whereNull(field: FieldKey<TRecord>): this;
|
|
149
|
-
/**
|
|
150
|
-
* Add a WHERE NOT NULL condition.
|
|
151
|
-
* @param field - Column to check for NOT NULL
|
|
152
|
-
*/
|
|
153
102
|
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
103
|
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
104
|
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
|
-
*/
|
|
105
|
+
/** Can be called multiple times to sort by multiple columns. */
|
|
171
106
|
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
107
|
limit(n: number): this;
|
|
177
|
-
/**
|
|
178
|
-
* Set the number of records to skip.
|
|
179
|
-
* @param n - Number of records to skip
|
|
180
|
-
*/
|
|
181
108
|
offset(n: number): this;
|
|
182
|
-
/**
|
|
183
|
-
* Limit the columns returned in the result.
|
|
184
|
-
* @param fields - Column names to select
|
|
185
|
-
*/
|
|
186
109
|
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
|
-
*/
|
|
110
|
+
/** Apply a named query scope defined on the model. */
|
|
199
111
|
scope(name: string): this;
|
|
200
112
|
/**
|
|
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()
|
|
113
|
+
* Eager-load relationships by name, dot path, or an object of constraint
|
|
114
|
+
* callbacks, each run after the foreign-key filter on exactly the level its key
|
|
115
|
+
* names. Pitfalls: a top-level `orWhere()` ORs against the foreign-key filter
|
|
116
|
+
* (group it); `select()` must keep the relation's key column or the relation is
|
|
117
|
+
* empty; `limit()` applies to the one batched query, not per parent record.
|
|
237
118
|
*/
|
|
238
119
|
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
120
|
get(): Promise<TResult[]>;
|
|
244
|
-
/**
|
|
245
|
-
* Execute the query and return the first matching record.
|
|
246
|
-
* @returns The first record or null
|
|
247
|
-
*/
|
|
248
121
|
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
|
-
*/
|
|
122
|
+
/** @throws ModelNotFoundException (404) if no record matches. */
|
|
254
123
|
firstOrFail(): Promise<TResult>;
|
|
255
|
-
/**
|
|
256
|
-
* Count the number of records matching the current conditions.
|
|
257
|
-
* @returns The count of matching records
|
|
258
|
-
*/
|
|
259
124
|
count(): Promise<number>;
|
|
260
125
|
/**
|
|
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 })
|
|
126
|
+
* Takes positional arguments or the same options object as
|
|
127
|
+
* `Model.paginate()`, so the two APIs stay interchangeable.
|
|
269
128
|
*/
|
|
270
129
|
paginate(page?: number, perPage?: number): Promise<PaginatedResult<TResult>>;
|
|
271
130
|
paginate(options: {
|
|
@@ -273,95 +132,50 @@ declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult ex
|
|
|
273
132
|
perPage?: number;
|
|
274
133
|
}): Promise<PaginatedResult<TResult>>;
|
|
275
134
|
/**
|
|
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)
|
|
135
|
+
* Bulk update. Mass-assignment protection and persistence preparation
|
|
136
|
+
* (mutators, casts, `preparePersistencePayload`) apply exactly as in
|
|
137
|
+
* `Model.update()`; per-record hooks and observers are skipped by design.
|
|
288
138
|
*/
|
|
289
139
|
update(data: PlainObject): Promise<TRecord>;
|
|
290
140
|
/**
|
|
291
|
-
* Bulk update bypassing mass-assignment protection.
|
|
292
|
-
*
|
|
141
|
+
* Bulk update bypassing mass-assignment protection. Trusted server-side data
|
|
142
|
+
* only, never raw request input.
|
|
293
143
|
*/
|
|
294
144
|
forceUpdate(data: PlainObject): Promise<TRecord>;
|
|
295
145
|
private runBulkUpdate;
|
|
296
146
|
/**
|
|
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.
|
|
147
|
+
* Bulk update with an already-filtered, already-prepared payload, so
|
|
148
|
+
* `Model.update()` can borrow the builder's global-scope-carrying
|
|
149
|
+
* `conditions` without running mutators twice (double-hashing a hashed
|
|
150
|
+
* column). Symbol-keyed and never re-exported: a named public method here
|
|
151
|
+
* would be a supported way to bypass mass-assignment protection entirely.
|
|
308
152
|
*/
|
|
309
153
|
[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
154
|
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
|
-
*/
|
|
155
|
+
/** Makes the builder awaitable, resolving to `get()`. */
|
|
319
156
|
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
157
|
catch<TCatch = never>(onrejected?: ((reason: unknown) => TCatch | PromiseLike<TCatch>) | null): Promise<TResult[] | TCatch>;
|
|
324
|
-
/** Get the internal conditions (used by adapters). */
|
|
325
158
|
getConditions(): WhereCondition[];
|
|
326
|
-
/** Get the internal query options (used by adapters). */
|
|
327
159
|
getOptions(): QueryBuilderOptions;
|
|
328
160
|
/**
|
|
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.
|
|
161
|
+
* The nested builder skips global scopes on purpose: the outer builder
|
|
162
|
+
* already carries them, and re-applying them inside every group would
|
|
163
|
+
* duplicate — or, inside an OR group, weaken — their filters.
|
|
336
164
|
*/
|
|
337
165
|
private pushCallbackGroup;
|
|
338
166
|
private addSimpleCondition;
|
|
339
167
|
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
|
-
*/
|
|
168
|
+
/** Null when the conditions are too complex for a basic adapter's WhereClause. */
|
|
345
169
|
private toSimpleWhereClause;
|
|
346
170
|
/**
|
|
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.
|
|
171
|
+
* Paths are delegated to Model.loadRelationsInto, which recurses the
|
|
172
|
+
* relation chain. The builder's `trx` goes with them: a relation read off
|
|
173
|
+
* the pool while its parents came from an open transaction gets a null
|
|
174
|
+
* relation back on Postgres/MySQL, the parents being uncommitted.
|
|
358
175
|
*/
|
|
359
176
|
private readonly loadEagerRelations;
|
|
360
177
|
}
|
|
361
|
-
/**
|
|
362
|
-
* Extended adapter interface for advanced query builder features.
|
|
363
|
-
* Adapters can optionally implement these methods for full QueryBuilder support.
|
|
364
|
-
*/
|
|
178
|
+
/** Optional adapter methods needed for full QueryBuilder support. */
|
|
365
179
|
interface ORMAdapterAdvanced extends ORMAdapter {
|
|
366
180
|
findManyAdvanced?<TRecord extends PlainObject = PlainObject>(table: unknown, conditions: WhereCondition[], options: {
|
|
367
181
|
orderBy?: OrderByClause;
|
|
@@ -375,30 +189,21 @@ interface ORMAdapterAdvanced extends ORMAdapter {
|
|
|
375
189
|
}
|
|
376
190
|
//#endregion
|
|
377
191
|
//#region src/GlobalScopeRegistry.d.ts
|
|
378
|
-
/** A named global scope function. */
|
|
379
192
|
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
|
-
*/
|
|
193
|
+
/** Registry for the named global scopes applied to every query on a model. */
|
|
386
194
|
declare class GlobalScopeRegistry {
|
|
387
195
|
private scopes;
|
|
388
196
|
add(name: string, fn: ScopeFunction): void;
|
|
389
197
|
remove(name: string): void;
|
|
390
198
|
has(name: string): boolean;
|
|
391
199
|
names(): string[];
|
|
392
|
-
/** Apply all scopes (or all except excluded) to a query builder. */
|
|
393
200
|
apply<T extends PlainObject>(builder: QueryBuilder<T>, except?: string[]): QueryBuilder<T>;
|
|
394
201
|
clear(): void;
|
|
395
202
|
/**
|
|
396
|
-
*
|
|
397
|
-
*
|
|
398
|
-
*
|
|
399
|
-
*
|
|
400
|
-
* mixes in `SoftDeletes` and then adds a `tenant` scope silently loses the
|
|
401
|
-
* `softDelete` filter.
|
|
203
|
+
* A subclass registering its own scope needs a registry of its own, but must
|
|
204
|
+
* keep the inherited entries: starting from empty is how a model that mixes
|
|
205
|
+
* in `SoftDeletes` and then adds a `tenant` scope loses the `softDelete`
|
|
206
|
+
* filter.
|
|
402
207
|
*/
|
|
403
208
|
clone(): GlobalScopeRegistry;
|
|
404
209
|
get size(): number;
|
|
@@ -406,53 +211,21 @@ declare class GlobalScopeRegistry {
|
|
|
406
211
|
//#endregion
|
|
407
212
|
//#region src/hooks.d.ts
|
|
408
213
|
/**
|
|
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.
|
|
214
|
+
* Model lifecycle hook names. A "before" hook (`creating`, `updating`,
|
|
215
|
+
* `deleting`, `saving`) aborts the operation by returning `false`.
|
|
216
|
+
* `saving`/`saved` fire for both create and update.
|
|
418
217
|
*/
|
|
419
218
|
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
|
-
*/
|
|
219
|
+
/** Callback for a model lifecycle hook; `false` from a before-hook aborts. */
|
|
426
220
|
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
221
|
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
|
-
*/
|
|
222
|
+
/** Runs the hook if present; `false` means the operation should be aborted. */
|
|
440
223
|
declare function executeHook(hooks: ModelHooks | undefined, name: HookName, data: Record<string, unknown>): Promise<boolean>;
|
|
441
224
|
//#endregion
|
|
442
225
|
//#region src/ModelObserver.d.ts
|
|
443
226
|
/**
|
|
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)
|
|
227
|
+
* Lifecycle hook logic extracted into a class, registered with
|
|
228
|
+
* `User.observe(UserObserver)`.
|
|
456
229
|
*/
|
|
457
230
|
interface ModelObserver {
|
|
458
231
|
creating?(data: PlainObject): void | Promise<void> | false | Promise<false>;
|
|
@@ -465,14 +238,10 @@ interface ModelObserver {
|
|
|
465
238
|
saved?(data: PlainObject): void | Promise<void>;
|
|
466
239
|
}
|
|
467
240
|
type ModelObserverConstructor = new () => ModelObserver;
|
|
468
|
-
/**
|
|
469
|
-
* Execute all registered observers for a given hook.
|
|
470
|
-
* Returns false if any observer aborts the operation.
|
|
471
|
-
*/
|
|
241
|
+
/** Returns false as soon as an observer aborts the operation. */
|
|
472
242
|
declare function executeObservers(observers: ModelObserver[] | undefined, name: HookName, data: PlainObject): Promise<boolean>;
|
|
473
243
|
//#endregion
|
|
474
244
|
//#region src/Model.d.ts
|
|
475
|
-
/** Generic plain object type used throughout the ORM. */
|
|
476
245
|
type PlainObject = Record<string, unknown>;
|
|
477
246
|
type RelationShape = Record<string, unknown>;
|
|
478
247
|
type TableShape<TSelect extends PlainObject = PlainObject, TInsert extends PlainObject = PlainObject> = {
|
|
@@ -485,114 +254,54 @@ type InferModelRecord<TTable> = TTable extends {
|
|
|
485
254
|
type InferModelInsert<TTable> = TTable extends {
|
|
486
255
|
$inferInsert: infer TInsert;
|
|
487
256
|
} ? TInsert extends PlainObject ? TInsert : PlainObject : PlainObject;
|
|
488
|
-
/** Supported cast types for attribute casting. */
|
|
489
257
|
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
258
|
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
|
-
*/
|
|
259
|
+
/** A single value is an equality test, an array an IN; keys are AND-ed. */
|
|
509
260
|
type WhereClause<TRecord extends PlainObject = PlainObject> = Partial<{ [K in keyof TRecord & string]?: WhereValue<TRecord[K]>; }>;
|
|
510
|
-
/** Sort direction for ordering queries. */
|
|
511
261
|
type OrderDirection = 'asc' | 'desc';
|
|
512
|
-
/** Normalized order definition with column and direction. */
|
|
513
262
|
type OrderDefinition<TRecord extends PlainObject = PlainObject> = {
|
|
514
263
|
column: keyof TRecord & string;
|
|
515
264
|
direction: OrderDirection;
|
|
516
265
|
};
|
|
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
266
|
type OrderExpression<TRecord extends PlainObject = PlainObject> = (keyof TRecord & string) | readonly [keyof TRecord & string, OrderDirection] | {
|
|
525
267
|
column: keyof TRecord & string;
|
|
526
268
|
direction?: OrderDirection;
|
|
527
269
|
};
|
|
528
|
-
/** Input for orderBy - single expression or array of expressions. */
|
|
529
270
|
type OrderByInput<TRecord extends PlainObject = PlainObject> = OrderExpression<TRecord> | readonly OrderExpression<TRecord>[];
|
|
530
|
-
/** Normalized array of order definitions. */
|
|
531
271
|
type OrderByClause<TRecord extends PlainObject = PlainObject> = readonly OrderDefinition<TRecord>[];
|
|
532
|
-
/** Options for findMany queries. */
|
|
533
272
|
interface FindManyOptions<TRecord extends PlainObject = PlainObject> {
|
|
534
|
-
/** Filter conditions */
|
|
535
273
|
where?: WhereClause<TRecord>;
|
|
536
|
-
/** Sort order */
|
|
537
274
|
orderBy?: OrderByClause<TRecord>;
|
|
538
|
-
/** Maximum number of records to return */
|
|
539
275
|
limit?: number;
|
|
540
|
-
/** Number of records to skip */
|
|
541
276
|
offset?: number;
|
|
542
277
|
}
|
|
543
|
-
/** Options for paginated queries. */
|
|
544
278
|
interface PaginateOptions<TRecord extends PlainObject = PlainObject> {
|
|
545
|
-
/** Page number (1-based, default: 1) */
|
|
546
279
|
page?: number;
|
|
547
|
-
/** Records per page (default: 15) */
|
|
548
280
|
perPage?: number;
|
|
549
|
-
/** Filter conditions */
|
|
550
281
|
where?: WhereClause<TRecord>;
|
|
551
|
-
/** Sort order */
|
|
552
282
|
orderBy?: OrderByInput<TRecord>;
|
|
553
283
|
}
|
|
554
|
-
/** Pagination metadata returned with paginated results. */
|
|
555
284
|
interface ModelPaginationMeta {
|
|
556
|
-
/** Total number of records matching the query */
|
|
557
285
|
total: number;
|
|
558
|
-
/** Number of records per page */
|
|
559
286
|
perPage: number;
|
|
560
|
-
/** Current page number (1-based) */
|
|
561
287
|
currentPage: number;
|
|
562
|
-
/** Total number of pages */
|
|
563
288
|
totalPages: number;
|
|
564
|
-
/** Whether there are more pages after this one */
|
|
565
289
|
hasMore: boolean;
|
|
566
|
-
/** Index of first record on this page (1-based) */
|
|
567
290
|
from: number;
|
|
568
|
-
/** Index of last record on this page */
|
|
569
291
|
to: number;
|
|
570
292
|
}
|
|
571
|
-
/** Result of a paginated query. */
|
|
572
293
|
interface PaginatedResult<TRecord extends PlainObject = PlainObject> {
|
|
573
|
-
/** Records for the current page */
|
|
574
294
|
data: TRecord[];
|
|
575
|
-
/** Pagination metadata */
|
|
576
295
|
meta: ModelPaginationMeta;
|
|
577
296
|
}
|
|
578
|
-
/**
|
|
579
|
-
* Interface for ORM adapters that power the Model class.
|
|
580
|
-
* The default adapter is DrizzleAdapter.
|
|
581
|
-
*/
|
|
297
|
+
/** Interface for ORM adapters that power the Model class; DrizzleAdapter by default. */
|
|
582
298
|
interface ORMAdapter {
|
|
583
|
-
/** Run operations in a database transaction. */
|
|
584
299
|
transaction?<TResult>(callback: (trx: unknown) => Promise<TResult>): Promise<TResult>;
|
|
585
|
-
/** Find multiple records with optional filtering, ordering, and pagination. */
|
|
586
300
|
findMany<TRecord extends PlainObject = PlainObject>(table: unknown, options?: FindManyOptions<TRecord>, queryOptions?: AdapterQueryOptions): Promise<TRecord[]>;
|
|
587
|
-
/** Find a single record by unique criteria. */
|
|
588
301
|
findUnique<TRecord extends PlainObject = PlainObject>(table: unknown, where: WhereClause<TRecord>, queryOptions?: AdapterQueryOptions): Promise<TRecord | null>;
|
|
589
|
-
/** Create a new record. */
|
|
590
302
|
create<TRecord extends PlainObject = PlainObject>(table: unknown, data: PlainObject, writeOptions?: AdapterQueryOptions): Promise<TRecord>;
|
|
591
|
-
/** Update records matching criteria. */
|
|
592
303
|
update?<TRecord extends PlainObject = PlainObject>(table: unknown, where: WhereClause<TRecord>, data: PlainObject, writeOptions?: AdapterQueryOptions): Promise<TRecord>;
|
|
593
|
-
/** Delete records matching criteria. */
|
|
594
304
|
delete?<TRecord extends PlainObject = PlainObject>(table: unknown, where: WhereClause<TRecord>, writeOptions?: AdapterQueryOptions): Promise<number | PlainObject | void>;
|
|
595
|
-
/** Count records matching criteria. */
|
|
596
305
|
count?<TRecord extends PlainObject = PlainObject>(table: unknown, where?: WhereClause<TRecord>, queryOptions?: AdapterQueryOptions): Promise<number>;
|
|
597
306
|
}
|
|
598
307
|
interface AdapterQueryOptions {
|
|
@@ -607,301 +316,98 @@ type SelectFrom<TDatabase> = TDatabase extends {
|
|
|
607
316
|
from: (...args: any[]) => infer TResult;
|
|
608
317
|
} ? TResult : never : never;
|
|
609
318
|
/**
|
|
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')
|
|
319
|
+
* ActiveRecord-style base class for database models. Prefer `defineModel(table)`,
|
|
320
|
+
* which infers the type markers; extending `Model` directly means setting
|
|
321
|
+
* `static table` and redeclaring `recordType`/`createType` by hand.
|
|
640
322
|
*/
|
|
641
323
|
declare abstract class Model<TRecord extends PlainObject = PlainObject> {
|
|
642
|
-
/** The ORM adapter used for database operations. */
|
|
643
324
|
protected static ormAdapter: ORMAdapter;
|
|
644
|
-
/** The database table (e.g., Drizzle table schema). */
|
|
645
325
|
protected static table: unknown;
|
|
646
326
|
/** Type marker for TypeScript inference. Set by `defineModel()`; when extending `Model` directly, redeclare as `declare static readonly recordType: YourRecordType`. */
|
|
647
327
|
static readonly recordType: unknown;
|
|
648
328
|
/** Type marker for insert/update payload inference. Set by `defineModel()`; when extending `Model` directly, redeclare as `declare static readonly createType: YourCreateType`. */
|
|
649
329
|
static readonly createType: unknown;
|
|
650
330
|
protected static relationDefinitions?: Map<string, RelationDefinition>;
|
|
651
|
-
/** Type marker for relation types. Define relation types here for type inference. */
|
|
652
331
|
static relationTypes: RelationShape;
|
|
653
332
|
/**
|
|
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()
|
|
333
|
+
* Reusable query constraints, applied by name with
|
|
334
|
+
* `Post.scope('published').scope('popular')`.
|
|
664
335
|
*/
|
|
665
336
|
static scopes?: Record<string, (q: QueryBuilder<any>) => QueryBuilder<any>>;
|
|
666
337
|
/**
|
|
667
|
-
*
|
|
668
|
-
*
|
|
669
|
-
*
|
|
670
|
-
* @example
|
|
671
|
-
* static defaultScope = (q: QueryBuilder<any>) => q.whereNull('deletedAt')
|
|
338
|
+
* Applied to every query on this model, and — unlike a named global scope —
|
|
339
|
+
* never removable with `withoutGlobalScope()`.
|
|
672
340
|
*/
|
|
673
341
|
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
|
-
*/
|
|
342
|
+
/** Lifecycle hooks firing around create, update and delete. */
|
|
685
343
|
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
|
-
*/
|
|
344
|
+
/** Attribute casts, applied both on read and on write. */
|
|
702
345
|
static casts?: Record<string, CastType>;
|
|
703
346
|
/**
|
|
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
|
-
* }
|
|
347
|
+
* Mass-assignment allowlist. When set, any other key in `create()`/`update()`
|
|
348
|
+
* input throws a MassAssignmentException rather than being discarded, so
|
|
349
|
+
* bugs and injection attempts surface; `forceCreate()`/`forceUpdate()` are
|
|
350
|
+
* the trusted-data escape. Independent of it, `id` is always stripped and
|
|
351
|
+
* `deniedFields()` always throws.
|
|
719
352
|
*/
|
|
720
353
|
static fillable?: string[];
|
|
721
354
|
/**
|
|
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.
|
|
355
|
+
* Fields that can never be mass-assigned, whatever `fillable` says. Resolved
|
|
356
|
+
* at call time so a subclass can derive them from its own configuration
|
|
357
|
+
* (`AuthenticatableModel` contributes its password-hash column).
|
|
728
358
|
*/
|
|
729
359
|
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
|
-
*/
|
|
360
|
+
/** Computed attributes, applied after a record is read. */
|
|
741
361
|
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
|
-
*/
|
|
362
|
+
/** Attribute transforms applied before persistence. */
|
|
752
363
|
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
|
-
*/
|
|
364
|
+
/** Fields to exclude from serialization output. */
|
|
761
365
|
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
|
-
*/
|
|
366
|
+
/** Serialization allowlist; takes precedence over `hidden`. */
|
|
766
367
|
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
|
-
*/
|
|
368
|
+
/** Accessor names to add to serialization output. */
|
|
776
369
|
static appends?: string[];
|
|
777
|
-
/** Registered model observers. */
|
|
778
370
|
protected static observers?: ModelObserver[];
|
|
779
|
-
/** Named global scopes registry. */
|
|
780
371
|
protected static globalScopeRegistry?: GlobalScopeRegistry;
|
|
781
|
-
/**
|
|
782
|
-
* Set a custom ORM adapter for this model.
|
|
783
|
-
* @param adapter - The adapter to use
|
|
784
|
-
*/
|
|
785
372
|
static useAdapter(adapter: ORMAdapter): void;
|
|
786
|
-
/**
|
|
787
|
-
* Get the current ORM adapter.
|
|
788
|
-
* @returns The configured adapter
|
|
789
|
-
*/
|
|
790
373
|
static getAdapter(): ORMAdapter;
|
|
791
374
|
/**
|
|
792
|
-
* Run operations inside a database transaction.
|
|
793
|
-
*
|
|
794
375
|
* @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
|
-
* })
|
|
376
|
+
* await User.transaction(async (trx) => User.create({ name: 'John' }, { trx }))
|
|
799
377
|
*/
|
|
800
378
|
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
|
-
*/
|
|
379
|
+
/** A model scope that forwards `trx` to every query and write on it. */
|
|
811
380
|
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
381
|
static observe(ObserverClass: ModelObserverConstructor): void;
|
|
819
|
-
/** Clear all registered observers. */
|
|
820
382
|
static clearObservers(): void;
|
|
821
383
|
/**
|
|
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.
|
|
384
|
+
* The registry this class may mutate, created on first write and seeded from
|
|
385
|
+
* the inherited one: the read paths resolve it through the prototype chain,
|
|
386
|
+
* so starting empty would shadow and drop every inherited scope (SoftDeletes
|
|
387
|
+
* then `addGlobalScope('tenant')`). The copy is a snapshot — scopes added to
|
|
388
|
+
* the parent afterwards never reach the subclass.
|
|
836
389
|
*/
|
|
837
390
|
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
391
|
static addGlobalScope(name: string, fn: ScopeFunction): void;
|
|
845
|
-
/** Remove a named global scope. */
|
|
846
392
|
static removeGlobalScope(name: string): void;
|
|
847
393
|
/**
|
|
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()
|
|
394
|
+
* Only *named* scopes can be excluded: `defaultScope` is re-applied whatever
|
|
395
|
+
* this is asked to drop, so a mixin whose filter must be opt-out-able has to
|
|
396
|
+
* register a named scope and nothing else.
|
|
858
397
|
*/
|
|
859
398
|
static withoutGlobalScope<T extends typeof Model>(this: T, ...names: string[]): QueryBuilder<TRecordFor<T>>;
|
|
860
|
-
/**
|
|
861
|
-
* Start a query with no global scopes applied (also skips defaultScope).
|
|
862
|
-
*
|
|
863
|
-
* @example
|
|
864
|
-
* const all = await User.withoutGlobalScopes().get()
|
|
865
|
-
*/
|
|
399
|
+
/** A query with no global scopes applied, `defaultScope` included. */
|
|
866
400
|
static withoutGlobalScopes<T extends typeof Model>(this: T): QueryBuilder<TRecordFor<T>>;
|
|
867
|
-
/**
|
|
868
|
-
* Serialize a record for API/JSON output.
|
|
869
|
-
* Applies hidden/visible filtering, accessors, and appends.
|
|
870
|
-
*
|
|
871
|
-
* @example
|
|
872
|
-
* const json = User.serialize(user)
|
|
873
|
-
*/
|
|
401
|
+
/** Applies hidden/visible filtering, accessors and appends. */
|
|
874
402
|
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
403
|
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
404
|
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
|
-
*/
|
|
405
|
+
/** Read-time transforms, in order: casts then accessors. */
|
|
893
406
|
protected static applyReadTransforms<T extends PlainObject>(record: T): T;
|
|
894
407
|
/**
|
|
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
|
|
408
|
+
* In order: `deniedFields()` throws, checked on the raw input so no later
|
|
409
|
+
* rule can swallow them; `id` is stripped silently; then, with `fillable`
|
|
410
|
+
* set, anything outside it throws.
|
|
905
411
|
*/
|
|
906
412
|
static filterFillable(data: PlainObject): PlainObject;
|
|
907
413
|
protected static preparePersistencePayload(data: PlainObject): Promise<PlainObject>;
|
|
@@ -911,417 +417,113 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
|
|
|
911
417
|
/** @internal */
|
|
912
418
|
static getRelationDefinition(name: string): RelationDefinition | undefined;
|
|
913
419
|
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
420
|
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
421
|
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
|
-
*/
|
|
422
|
+
/** @throws ModelNotFoundException (404) when no record matches. */
|
|
946
423
|
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
424
|
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
425
|
/**
|
|
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
|
|
426
|
+
* Relations accept dot-notation paths (`comments.author`).
|
|
427
|
+
* @throws ModelNotFoundException when no record matches.
|
|
973
428
|
*/
|
|
974
429
|
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
430
|
static first<T extends typeof Model>(this: T, where?: WhereClauseFor<T>, queryOptions?: ModelQueryOptions): Promise<TRecordFor<T> | null>;
|
|
985
431
|
/**
|
|
986
|
-
*
|
|
987
|
-
*
|
|
988
|
-
* Returns a QueryBuilder that is thenable, so it can be directly awaited.
|
|
432
|
+
* Returns a thenable QueryBuilder, so it can be chained or awaited directly.
|
|
989
433
|
*
|
|
990
434
|
* @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()
|
|
435
|
+
* await User.where({ status: 'active' })
|
|
436
|
+
* await Post.where('views', '>', 100).orderBy('createdAt', 'desc').get()
|
|
1006
437
|
*/
|
|
1007
438
|
static where<T extends typeof Model>(this: T, callback: WhereGroupCallback<TRecordFor<T>>): QueryBuilder<TRecordFor<T>>;
|
|
1008
439
|
static where<T extends typeof Model>(this: T, conditions: WhereClauseFor<T>): QueryBuilder<TRecordFor<T>>;
|
|
1009
440
|
static where<T extends typeof Model>(this: T, field: keyof TRecordFor<T> & string, value: unknown): QueryBuilder<TRecordFor<T>>;
|
|
1010
441
|
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
442
|
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
443
|
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
444
|
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
445
|
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
446
|
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
447
|
static newQuery<T extends typeof Model>(this: T, queryOptions?: ModelQueryOptions): QueryBuilder<TRecordFor<T>>;
|
|
1054
|
-
/**
|
|
1055
|
-
* Create a new QueryBuilder without applying any default scopes.
|
|
1056
|
-
* Useful for querying soft-deleted records or bypassing global filters.
|
|
1057
|
-
*
|
|
1058
|
-
* @returns A fresh QueryBuilder instance with no scopes applied
|
|
1059
|
-
*/
|
|
448
|
+
/** No scopes applied — for soft-deleted records or bypassing global filters. */
|
|
1060
449
|
static newQueryWithoutScopes<T extends typeof Model>(this: T, queryOptions?: ModelQueryOptions): QueryBuilder<TRecordFor<T>>;
|
|
1061
450
|
/**
|
|
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.
|
|
451
|
+
* Whether this model carries a filter every query must apply. Checked by the
|
|
452
|
+
* entry points that talk to the adapter directly, to decide whether they can
|
|
453
|
+
* take the fast path.
|
|
1067
454
|
*/
|
|
1068
455
|
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
|
-
*/
|
|
456
|
+
/** Apply a scope defined in `static scopes`; chainable. */
|
|
1079
457
|
static scope<T extends typeof Model>(this: T, name: string): QueryBuilder<TRecordFor<T>>;
|
|
1080
458
|
/**
|
|
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')
|
|
459
|
+
* One-to-many: `foreignKey` is on the related model, `localKey` on this one.
|
|
460
|
+
* Declare in a `static {}` block; `name` is what `with()` takes.
|
|
1095
461
|
*/
|
|
1096
462
|
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
463
|
/**
|
|
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')
|
|
464
|
+
* Many-to-one inverse: `foreignKey` is on *this* model, `ownerKey` on the
|
|
465
|
+
* related one.
|
|
1112
466
|
*/
|
|
1113
467
|
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
468
|
/**
|
|
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')
|
|
469
|
+
* One-to-one: `foreignKey` is on the related model, `localKey` on this one.
|
|
1129
470
|
*/
|
|
1130
471
|
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
472
|
/**
|
|
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
|
-
*
|
|
473
|
+
* Many-to-many through a pivot table. `foreignPivotKey`/`relatedPivotKey` are
|
|
474
|
+
* both columns *on the pivot*, referencing this model and the related one;
|
|
475
|
+
* `parentKey`/`relatedKey` are the local keys they point at.
|
|
1142
476
|
* @example
|
|
1143
|
-
*
|
|
1144
|
-
* static {
|
|
1145
|
-
* this.belongsToMany('roles', Role, userRoles, 'userId', 'roleId', 'id', 'id')
|
|
1146
|
-
* }
|
|
1147
|
-
* }
|
|
1148
|
-
* // Later: User.with('roles')
|
|
477
|
+
* this.belongsToMany('roles', Role, userRoles, 'userId', 'roleId', 'id', 'id')
|
|
1149
478
|
*/
|
|
1150
479
|
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
480
|
/**
|
|
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
|
-
*
|
|
481
|
+
* Has-many-through: `firstKey` is on the intermediate model referencing this
|
|
482
|
+
* one, `secondKey` on the related model referencing the intermediate;
|
|
483
|
+
* `localKey` and `secondLocalKey` are the keys they point at.
|
|
1162
484
|
* @example
|
|
1163
|
-
*
|
|
1164
|
-
* static {
|
|
1165
|
-
* this.hasManyThrough('posts', Post, User, 'countryId', 'userId', 'id', 'id')
|
|
1166
|
-
* }
|
|
1167
|
-
* }
|
|
1168
|
-
* // Later: Country.with('posts')
|
|
485
|
+
* this.hasManyThrough('posts', Post, User, 'countryId', 'userId', 'id', 'id')
|
|
1169
486
|
*/
|
|
1170
487
|
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
|
-
*/
|
|
488
|
+
/** Type strings to model classes, e.g. `Model.morphMap = { Post, Video }`. */
|
|
1177
489
|
static morphMap?: Record<string, typeof Model>;
|
|
1178
490
|
/**
|
|
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')
|
|
491
|
+
* Polymorphic one-to-many. `morphName` is the base of the column pair:
|
|
492
|
+
* 'commentable' means commentableType + commentableId.
|
|
1188
493
|
*/
|
|
1189
494
|
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
|
-
*/
|
|
495
|
+
/** Inverse of a polymorphic relation; `morphName` bases the type/id columns. */
|
|
1199
496
|
static morphTo<This extends typeof Model, Name extends RelationKeyOrString<This>>(this: This, name: Name, morphName: string): void;
|
|
1200
497
|
/**
|
|
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
498
|
* @example
|
|
1208
|
-
* // Single column ascending
|
|
1209
499
|
* 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' })
|
|
500
|
+
* await User.orderBy([['lastName', 'asc'], ['firstName', 'asc']], { status: 'active' })
|
|
1219
501
|
*/
|
|
1220
502
|
static orderBy<T extends typeof Model>(this: T, order: OrderByInput<TRecordFor<T>>, where?: WhereClauseFor<T>, queryOptions?: ModelQueryOptions): Promise<TRecordFor<T>[]>;
|
|
1221
503
|
/**
|
|
1222
|
-
* Get paginated records.
|
|
1223
|
-
*
|
|
1224
|
-
* @param options - Pagination options
|
|
1225
|
-
* @returns Paginated result with data and metadata
|
|
1226
|
-
*
|
|
1227
504
|
* @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
|
-
* })
|
|
505
|
+
* await User.paginate({ page: 2, perPage: 20, where: { status: 'active' } })
|
|
1240
506
|
*/
|
|
1241
507
|
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
508
|
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
509
|
static create<T extends typeof Model>(this: T, data: TCreateFor<T>, writeOptions?: ModelWriteOptions): Promise<TRecordFor<T>>;
|
|
1268
510
|
/**
|
|
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
|
-
* })
|
|
511
|
+
* Create bypassing mass-assignment protection. Trusted server-side data only
|
|
512
|
+
* (OAuth linking, seeders, system records), never raw request input.
|
|
1279
513
|
*/
|
|
1280
514
|
static forceCreate<T extends typeof Model>(this: T, data: TCreateFor<T>, writeOptions?: ModelWriteOptions): Promise<TRecordFor<T>>;
|
|
1281
515
|
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
516
|
static update<T extends typeof Model>(this: T, where: WhereClauseFor<T>, data: Partial<TCreateFor<T>>, writeOptions?: ModelWriteOptions): Promise<TRecordFor<T>>;
|
|
1293
517
|
/**
|
|
1294
|
-
* Update
|
|
1295
|
-
*
|
|
518
|
+
* Update bypassing mass-assignment protection. Trusted server-side data only,
|
|
519
|
+
* never raw request input.
|
|
1296
520
|
*/
|
|
1297
521
|
static forceUpdate<T extends typeof Model>(this: T, where: WhereClauseFor<T>, data: Partial<TCreateFor<T>>, writeOptions?: ModelWriteOptions): Promise<TRecordFor<T>>;
|
|
1298
522
|
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
523
|
static delete<T extends typeof Model>(this: T, where: WhereClauseFor<T>, writeOptions?: ModelWriteOptions): Promise<number | PlainObject | void>;
|
|
1310
524
|
/**
|
|
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))
|
|
525
|
+
* A raw Drizzle builder starting at `select().from(table)`. Carries no model
|
|
526
|
+
* scopes, casts or accessors.
|
|
1325
527
|
*/
|
|
1326
528
|
static query<TDatabase extends {
|
|
1327
529
|
select: (...args: any[]) => any;
|
|
@@ -1331,63 +533,35 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
|
|
|
1331
533
|
// eslint-disable-line @typescript-eslint/no-explicit-any
|
|
1332
534
|
this: typeof Model, db?: TDatabase): SelectFrom<TDatabase>;
|
|
1333
535
|
/**
|
|
1334
|
-
* Eager-load
|
|
1335
|
-
*
|
|
1336
|
-
* @param relations - Relation name(s) to load
|
|
1337
|
-
* @param where - Optional filter conditions
|
|
1338
|
-
* @returns Records with loaded relationships
|
|
536
|
+
* Eager-load relations, one name or several, nested via dot notation.
|
|
1339
537
|
*
|
|
1340
538
|
* @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')
|
|
539
|
+
* await User.with(['posts.comments', 'profile'], { status: 'active' })
|
|
1352
540
|
*/
|
|
1353
541
|
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
542
|
/**
|
|
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
|
|
543
|
+
* Attaches a `${name}Count` per record without loading the related rows.
|
|
544
|
+
* belongsTo yields 0 or 1.
|
|
1362
545
|
*/
|
|
1363
546
|
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
547
|
/** @internal Attaches a `${name}Count` field for one relation. */
|
|
1365
548
|
protected static loadRelationCountInto<T extends typeof Model>(this: T, records: Array<PlainObject>, relationName: string, queryOptions?: ModelQueryOptions): Promise<void>;
|
|
1366
549
|
/**
|
|
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.
|
|
550
|
+
* @internal Used by QueryBuilder for eager loading. Paths are grouped by head
|
|
551
|
+
* segment so a shared relation loads once: the loaders assign fresh spread
|
|
552
|
+
* copies, so a second pass over `posts` would replace the very rows the first
|
|
553
|
+
* attached children to and only the last path would survive.
|
|
1376
554
|
*/
|
|
1377
555
|
static loadRelationsInto<T extends typeof Model>(this: T, records: Array<PlainObject>, relationNames: readonly string[], queryOptions?: ModelQueryOptions, constraints?: EagerLoadConstraints, pathPrefix?: string): Promise<void>;
|
|
1378
556
|
/**
|
|
1379
|
-
* @internal Public
|
|
1380
|
-
*
|
|
1381
|
-
* Internal callers should use {@link loadRelationsInto} instead.
|
|
557
|
+
* @internal Public because generated code reaches it; internal callers should
|
|
558
|
+
* use {@link loadRelationsInto}.
|
|
1382
559
|
*/
|
|
1383
560
|
static loadRelationInto<T extends typeof Model>(this: T, records: Array<PlainObject>, relationName: string, queryOptions?: ModelQueryOptions, constraints?: EagerLoadConstraints, pathPrefix?: string): Promise<void>;
|
|
1384
561
|
/**
|
|
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`.
|
|
562
|
+
* `constraints` are keyed by the full path of the level each constrains, so
|
|
563
|
+
* `pathPrefix` accumulates the path walked so far: at `posts.comments` the
|
|
564
|
+
* leaf looks itself up under that whole key, not under `comments`.
|
|
1391
565
|
*/
|
|
1392
566
|
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
567
|
protected static loadHasMany(records: Array<PlainObject>, definition: HasManyRelationDefinition, queryOptions?: ModelQueryOptions, constraint?: EagerLoadConstraint): Promise<void>;
|
|
@@ -1480,151 +654,87 @@ interface MorphToRelationDefinition {
|
|
|
1480
654
|
related: undefined;
|
|
1481
655
|
morphName: string;
|
|
1482
656
|
}
|
|
1483
|
-
/** Type for hasMany relation results (array of related records). */
|
|
1484
657
|
type HasManyRelationResult<T extends typeof Model> = Array<TRecordFor<T>>;
|
|
1485
|
-
/** Type for belongsTo relation results (single record or null). */
|
|
1486
658
|
type BelongsToRelationResult<T extends typeof Model> = TRecordFor<T> | null;
|
|
1487
|
-
/** Utility type for hasMany relation data shape. */
|
|
1488
659
|
type HasManyRecord<TRecord extends PlainObject> = TRecord[];
|
|
1489
|
-
/** Utility type for belongsTo relation data shape. */
|
|
1490
660
|
type BelongsToRecord<TRecord extends PlainObject> = TRecord | null;
|
|
1491
661
|
/**
|
|
1492
|
-
*
|
|
1493
|
-
*
|
|
1494
|
-
* `declare` modifier so no runtime placeholder value is needed:
|
|
662
|
+
* For a belongsTo backed by a NOT NULL foreign key, where the parent is
|
|
663
|
+
* guaranteed once loaded.
|
|
1495
664
|
*
|
|
1496
665
|
* @example
|
|
1497
666
|
* declare static relationTypes: { author: BelongsToRequiredRecord<UserRecord> }
|
|
1498
667
|
*/
|
|
1499
668
|
type BelongsToRequiredRecord<TRecord extends PlainObject> = TRecord;
|
|
1500
|
-
/** Type for hasOne relation results (single record or null). */
|
|
1501
669
|
type HasOneRelationResult<T extends typeof Model> = TRecordFor<T> | null;
|
|
1502
|
-
/** Type for belongsToMany relation results (array of related records). */
|
|
1503
670
|
type BelongsToManyRelationResult<T extends typeof Model> = Array<TRecordFor<T>>;
|
|
1504
|
-
/** Type for hasManyThrough relation results (array of related records). */
|
|
1505
671
|
type HasManyThroughRelationResult<T extends typeof Model> = Array<TRecordFor<T>>;
|
|
1506
|
-
/** Utility type for hasOne relation data shape. */
|
|
1507
672
|
type HasOneRecord<TRecord extends PlainObject> = TRecord | null;
|
|
1508
|
-
/** Utility type for belongsToMany relation data shape. */
|
|
1509
673
|
type BelongsToManyRecord<TRecord extends PlainObject> = TRecord[];
|
|
1510
|
-
/** Utility type for hasManyThrough relation data shape. */
|
|
1511
674
|
type HasManyThroughRecord<TRecord extends PlainObject> = TRecord[];
|
|
1512
|
-
/** Type for morphMany relation results (array of related records). */
|
|
1513
675
|
type MorphManyRelationResult<T extends typeof Model> = Array<TRecordFor<T>>;
|
|
1514
|
-
/** Utility type for morphMany relation data shape. */
|
|
1515
676
|
type MorphManyRecord<TRecord extends PlainObject> = TRecord[];
|
|
1516
|
-
/** Type for morphTo relation results (single record or null). */
|
|
1517
677
|
type MorphToRelationResult = PlainObject | null;
|
|
1518
|
-
/** Utility type for morphTo relation data shape. */
|
|
1519
678
|
type MorphToRecord = PlainObject | null;
|
|
1520
|
-
/** Utility type: model record with specified relations merged. */
|
|
1521
679
|
type WithRelations<T extends typeof Model, K extends RelationPath<T> | readonly RelationPath<T>[]> = TRecordFor<T> & RelationTypePick<T, K>;
|
|
1522
680
|
type ModelClassWithTable<TTable extends TableShape, TBase extends typeof Model, TCreate extends PlainObject> = TBase & {
|
|
1523
681
|
readonly table: TTable;
|
|
1524
682
|
readonly recordType: InferModelRecord<TTable>;
|
|
1525
683
|
readonly createType: TCreate;
|
|
1526
684
|
};
|
|
1527
|
-
/** A key that can appear in a model's create payload: a table column, or a named field its base contributes. */
|
|
1528
685
|
type CreateKey<TTable extends TableShape, TBase extends typeof Model> = keyof InferModelInsert<TTable> | keyof TCreateFor<TBase>;
|
|
1529
686
|
/**
|
|
1530
|
-
* Named fields a base
|
|
1531
|
-
*
|
|
1532
|
-
*
|
|
1533
|
-
* collapse, or every misspelling would pass the allowlist checks below.
|
|
687
|
+
* Named fields a base contributes to the create payload (`AuthenticatableModel`'s
|
|
688
|
+
* virtual `password`). A plain `Model` base declares no createType, so its keys
|
|
689
|
+
* collapse to `string` — guard that, or every misspelling passes the allowlists.
|
|
1534
690
|
*/
|
|
1535
691
|
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
692
|
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
693
|
type RecordKey<TTable extends TableShape> = keyof InferModelRecord<TTable> & string;
|
|
1540
694
|
/**
|
|
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.
|
|
695
|
+
* Homomorphic on purpose, so the key union is inferred from the object
|
|
696
|
+
* literal's keys: the accessor functions are context-sensitive, which under a
|
|
697
|
+
* plain `Record<string, fn>` defers inference past the key parameter's default.
|
|
1546
698
|
*/
|
|
1547
699
|
type AccessorsShape<TTable extends TableShape, TKey extends string> = { [K in TKey]: (record: InferModelRecord<TTable>) => unknown; };
|
|
1548
700
|
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
701
|
/**
|
|
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
|
-
* }) {}
|
|
702
|
+
* A table-backed model base class: `recordType`/`createType` inferred from the
|
|
703
|
+
* table, `optionalOnCreate`/`requireOnCreate` reshaping the create payload without
|
|
704
|
+
* a cast (`AuthenticatableModel` hashes a virtual `password` into `passwordHash`).
|
|
705
|
+
* Allowlist statics passed as options are checked against the table's columns, so
|
|
706
|
+
* a typo is a compile error; a `static` on the subclass shadows the option.
|
|
1578
707
|
*/
|
|
1579
708
|
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
709
|
base?: TBase;
|
|
1581
|
-
/**
|
|
1582
|
-
* Columns the model fills in itself, so callers need not pass them.
|
|
1583
|
-
* Type-level only.
|
|
1584
|
-
*/
|
|
710
|
+
/** Type-level only: columns the model fills in itself. */
|
|
1585
711
|
optionalOnCreate?: readonly TOptional[];
|
|
1586
712
|
/**
|
|
1587
|
-
*
|
|
1588
|
-
* (Drizzle marks defaulted ones optional) and
|
|
1589
|
-
*
|
|
1590
|
-
* Type-level only.
|
|
713
|
+
* Type-level only: fields to make required on the create payload. Accepts
|
|
714
|
+
* table columns (Drizzle marks defaulted ones optional) and `base`-
|
|
715
|
+
* contributed fields such as the virtual `password`.
|
|
1591
716
|
*/
|
|
1592
717
|
requireOnCreate?: readonly TRequire[];
|
|
1593
|
-
/**
|
|
1594
|
-
* Typed form of `static fillable`: mass-assignment allowlist checked
|
|
1595
|
-
* against insertable columns and base-contributed fields.
|
|
1596
|
-
*/
|
|
718
|
+
/** Typed `static fillable`, checked against insertable and base fields. */
|
|
1597
719
|
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
|
-
*/
|
|
720
|
+
/** Typed `static hidden`, checked against record columns and accessors. */
|
|
1602
721
|
hidden?: readonly (RecordKey<TTable> | NoInfer<TAccessorKey>)[];
|
|
1603
|
-
/**
|
|
1604
|
-
* Typed form of `static visible`: serialization allowlist, checked
|
|
1605
|
-
* against record columns and declared accessors.
|
|
1606
|
-
*/
|
|
722
|
+
/** Typed `static visible`, checked against record columns and accessors. */
|
|
1607
723
|
visible?: readonly (RecordKey<TTable> | NoInfer<TAccessorKey>)[];
|
|
1608
724
|
/**
|
|
1609
|
-
* Typed
|
|
1610
|
-
*
|
|
1611
|
-
*
|
|
1612
|
-
* infer, the mapped type alone collapses to `{}`, which admits anything.
|
|
725
|
+
* Typed `static accessors`; the names here are what `appends` may
|
|
726
|
+
* reference. The Record intersection rejects non-object values — with no
|
|
727
|
+
* keys to infer, the mapped type alone collapses to `{}`.
|
|
1613
728
|
*/
|
|
1614
729
|
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
|
-
*/
|
|
730
|
+
/** Typed `static appends`, checked against the names in `accessors`. */
|
|
1619
731
|
appends?: readonly NoInfer<TAccessorKey>[];
|
|
1620
732
|
}): ModelClassWithTable<TTable, TBase, CreateShape<TTable, TBase, TOptional, TRequire>>;
|
|
1621
733
|
//#endregion
|
|
1622
734
|
//#region src/ModelNotFoundException.d.ts
|
|
1623
735
|
/**
|
|
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.
|
|
736
|
+
* Thrown by findOrFail/firstOrFail. Carries `statusCode` 404 so exception
|
|
737
|
+
* handlers can render it without coupling to the ORM package.
|
|
1628
738
|
*/
|
|
1629
739
|
declare class ModelNotFoundException extends Error {
|
|
1630
740
|
readonly statusCode = 404;
|
|
@@ -1635,16 +745,10 @@ declare class ModelNotFoundException extends Error {
|
|
|
1635
745
|
//#endregion
|
|
1636
746
|
//#region src/MassAssignmentException.d.ts
|
|
1637
747
|
/**
|
|
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.
|
|
748
|
+
* Thrown when mass assignment receives fields it must not write. Discarding
|
|
749
|
+
* them silently hides bugs and can mask injection attempts, so models throw.
|
|
750
|
+
* `reason` is `'not-fillable'` (outside the `fillable` allowlist) or
|
|
751
|
+
* `'denied'` (in `deniedFields()`, unassignable whatever `fillable` says).
|
|
1648
752
|
*/
|
|
1649
753
|
declare class MassAssignmentException extends Error {
|
|
1650
754
|
readonly model: string;
|
|
@@ -1656,11 +760,8 @@ declare class MassAssignmentException extends Error {
|
|
|
1656
760
|
}
|
|
1657
761
|
//#endregion
|
|
1658
762
|
//#region src/SoftDeletes.d.ts
|
|
1659
|
-
/**
|
|
1660
|
-
* Interface describing the static methods added by the SoftDeletes mixin.
|
|
1661
|
-
*/
|
|
763
|
+
/** The static methods the SoftDeletes mixin adds. */
|
|
1662
764
|
interface SoftDeletesStatic {
|
|
1663
|
-
/** Column name used for tracking soft deletion timestamp. */
|
|
1664
765
|
deletedAtColumn: string;
|
|
1665
766
|
/** Start a query that includes soft-deleted records. */
|
|
1666
767
|
withTrashed(): QueryBuilder<PlainObject>;
|
|
@@ -1672,32 +773,11 @@ interface SoftDeletesStatic {
|
|
|
1672
773
|
forceDelete(where: Partial<Record<string, unknown>>): Promise<number | PlainObject | void>;
|
|
1673
774
|
}
|
|
1674
775
|
/**
|
|
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'.
|
|
776
|
+
* Mixin where `delete()` sets `deletedAt` instead of removing the row, and a
|
|
777
|
+
* global scope named 'softDelete' excludes those rows from every query.
|
|
1680
778
|
*
|
|
1681
779
|
* @example
|
|
1682
780
|
* 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
781
|
*/
|
|
1702
782
|
declare function SoftDeletes<TBase extends typeof Model>(Base: TBase): TBase & SoftDeletesStatic;
|
|
1703
783
|
//#endregion
|
|
@@ -1744,33 +824,21 @@ declare const DrizzleAdapter: ORMAdapterAdvanced & {
|
|
|
1744
824
|
//#endregion
|
|
1745
825
|
//#region src/adapters/drizzle-conditions.d.ts
|
|
1746
826
|
/**
|
|
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
|
|
827
|
+
* Translates an array of QueryBuilder WhereConditions into a single Drizzle ORM
|
|
828
|
+
* condition expression. The list's sequential semantics — an OR group folds
|
|
829
|
+
* everything before it into the OR, so `.where('a',1).where('b',2).orWhere('c',3)`
|
|
830
|
+
* is `(a = 1 AND b = 2) OR (c = 3)` — are already applied by
|
|
831
|
+
* `normalizeConditionSequence`, leaving a flat-join tree to render here.
|
|
1760
832
|
*/
|
|
1761
833
|
declare function buildDrizzleConditions(table: unknown, conditions: WhereCondition[]): SQL | undefined;
|
|
1762
834
|
//#endregion
|
|
1763
835
|
//#region src/migration-utils.d.ts
|
|
1764
836
|
/**
|
|
1765
837
|
* 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.
|
|
838
|
+
* success off this, not off the call returning: an empty folder applies
|
|
839
|
+
* nothing, and "completed" there reads as an up-to-date database. Describes
|
|
840
|
+
* the run the driver memoized — migrations are single-flighted per handle, so
|
|
841
|
+
* a second call returns this same summary without re-reading the folder.
|
|
1774
842
|
*/
|
|
1775
843
|
interface MigrationRunSummary {
|
|
1776
844
|
/** The folder the migrator read, absolute as the driver resolved it. */
|
|
@@ -1778,10 +846,9 @@ interface MigrationRunSummary {
|
|
|
1778
846
|
/** drizzle-kit migrations found there (one folder each, holding migration.sql). */
|
|
1779
847
|
migrationsFound: number;
|
|
1780
848
|
/**
|
|
1781
|
-
* Loose .sql files
|
|
1782
|
-
*
|
|
1783
|
-
*
|
|
1784
|
-
* no migrations yet.
|
|
849
|
+
* Loose .sql files there, which the drizzle migrator never runs. Non-zero
|
|
850
|
+
* alongside `migrationsFound: 0` means the folder holds nothing to apply,
|
|
851
|
+
* a different problem from having generated no migrations yet.
|
|
1785
852
|
*/
|
|
1786
853
|
looseSqlFiles: number;
|
|
1787
854
|
}
|
|
@@ -1793,13 +860,9 @@ interface MigrationStatusEntry {
|
|
|
1793
860
|
//#endregion
|
|
1794
861
|
//#region src/seeder.d.ts
|
|
1795
862
|
/**
|
|
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.
|
|
863
|
+
* The context a seeder receives. `db`'s type depends on the dialect: annotate
|
|
864
|
+
* the seeder with the matching alias below whenever the app is not on
|
|
865
|
+
* PostgreSQL, which is the default only for backwards compatibility.
|
|
1803
866
|
*/
|
|
1804
867
|
interface SeederContext<TDatabase = PostgresJsDatabase> {
|
|
1805
868
|
db: TDatabase;
|
|
@@ -1815,9 +878,8 @@ type SqliteSeederContext = SeederContext<SQLiteBunDatabase>;
|
|
|
1815
878
|
type AwsDataApiSeederContext = SeederContext<AwsDataApiPgDatabase>;
|
|
1816
879
|
/**
|
|
1817
880
|
* What one `runSeeders()` call had to work with. `db:seed` reports success off
|
|
1818
|
-
* this
|
|
1819
|
-
*
|
|
1820
|
-
* rows the seeders would have written.
|
|
881
|
+
* this, not off the call returning: an empty folder seeds nothing, and
|
|
882
|
+
* "executed" there reads as a database that now holds the seeded rows.
|
|
1821
883
|
*/
|
|
1822
884
|
interface SeederRunSummary {
|
|
1823
885
|
/** The folder that was read, absolute as the driver resolved it. */
|
|
@@ -1825,17 +887,15 @@ interface SeederRunSummary {
|
|
|
1825
887
|
/** How many seeders ran. They run in the order their files sorted. */
|
|
1826
888
|
seedersRan: number;
|
|
1827
889
|
/**
|
|
1828
|
-
* Files with a seeder extension that exported nothing runnable
|
|
1829
|
-
*
|
|
1830
|
-
*
|
|
1831
|
-
* seeder yet, and one `make:seeder` would not solve.
|
|
890
|
+
* Files with a seeder extension that exported nothing runnable. Non-zero
|
|
891
|
+
* alongside `seedersRan: 0` means the folder holds nothing to run — a
|
|
892
|
+
* different problem from having written no seeder, which `make:seeder` fixes.
|
|
1832
893
|
*/
|
|
1833
894
|
filesWithoutSeeder: number;
|
|
1834
895
|
}
|
|
1835
896
|
/**
|
|
1836
|
-
* Seeders
|
|
1837
|
-
*
|
|
1838
|
-
* hand them — the same contract `runSeeders()` fulfils from the driver side.
|
|
897
|
+
* Seeders load as modules, so their dialect is unknowable here: `TDatabase` is
|
|
898
|
+
* the caller stating which database it will hand them.
|
|
1839
899
|
*/
|
|
1840
900
|
declare function loadSeeders<TDatabase = PostgresJsDatabase>(directory: string | URL): Promise<Array<SeederHandler<TDatabase>>>;
|
|
1841
901
|
/** Runs every seeder in `directory` and reports what the folder held. */
|
|
@@ -1850,9 +910,9 @@ interface PostgresDatabaseOptions {
|
|
|
1850
910
|
clientOptions?: postgres.Options<Record<string, never>>;
|
|
1851
911
|
seedersFolder?: string | URL;
|
|
1852
912
|
/**
|
|
1853
|
-
* Drizzle relations for RQB v2 (`db.query.*`)
|
|
1854
|
-
*
|
|
1855
|
-
*
|
|
913
|
+
* Drizzle relations for RQB v2 (`db.query.*`): `defineRelations(schema, ...)`
|
|
914
|
+
* from `drizzle-orm`, or `relations()` from `drizzle-orm/_relations` for the
|
|
915
|
+
* RQB v1 partial-upgrade path.
|
|
1856
916
|
*/
|
|
1857
917
|
relations?: Record<string, unknown>;
|
|
1858
918
|
}
|
|
@@ -1880,9 +940,9 @@ interface MySqlDatabaseOptions {
|
|
|
1880
940
|
clientOptions?: MySqlConnectionOptions;
|
|
1881
941
|
seedersFolder?: string | URL;
|
|
1882
942
|
/**
|
|
1883
|
-
* Drizzle relations for RQB v2 (`db.query.*`)
|
|
1884
|
-
*
|
|
1885
|
-
*
|
|
943
|
+
* Drizzle relations for RQB v2 (`db.query.*`): `defineRelations(schema, ...)`
|
|
944
|
+
* from `drizzle-orm`, or `relations()` from `drizzle-orm/_relations` for the
|
|
945
|
+
* RQB v1 partial-upgrade path.
|
|
1886
946
|
*/
|
|
1887
947
|
relations?: Record<string, unknown>;
|
|
1888
948
|
}
|
|
@@ -1909,9 +969,9 @@ interface SqliteDatabaseOptions {
|
|
|
1909
969
|
filename?: ConnectionResolver$1;
|
|
1910
970
|
seedersFolder?: string | URL;
|
|
1911
971
|
/**
|
|
1912
|
-
* Drizzle relations for RQB v2 (`db.query.*`)
|
|
1913
|
-
*
|
|
1914
|
-
*
|
|
972
|
+
* Drizzle relations for RQB v2 (`db.query.*`): `defineRelations(schema, ...)`
|
|
973
|
+
* from `drizzle-orm`, or `relations()` from `drizzle-orm/_relations` for the
|
|
974
|
+
* RQB v1 partial-upgrade path.
|
|
1915
975
|
*/
|
|
1916
976
|
relations?: Record<string, unknown>;
|
|
1917
977
|
}
|
|
@@ -1925,9 +985,8 @@ interface SqliteDatabase {
|
|
|
1925
985
|
seedDatabase(): Promise<SeederRunSummary>;
|
|
1926
986
|
/**
|
|
1927
987
|
* 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.
|
|
988
|
+
* re-applies migrations — same end state as `guren db:reset`. Undefined only
|
|
989
|
+
* when a concurrent `closeDatabase()` left nothing to drop.
|
|
1931
990
|
*/
|
|
1932
991
|
resetDatabase(): Promise<MigrationRunSummary | undefined>;
|
|
1933
992
|
/** Per-migration applied state derived from the drizzle-kit journal and the __drizzle_migrations table. */
|
|
@@ -1945,14 +1004,14 @@ interface D1DatabaseOptions {
|
|
|
1945
1004
|
binding: () => unknown;
|
|
1946
1005
|
/**
|
|
1947
1006
|
* Drizzle-kit migrations folder. D1 migrations are applied out-of-band via
|
|
1948
|
-
* `wrangler d1 migrations apply` (point `d1_databases[].migrations_dir`
|
|
1949
|
-
*
|
|
1007
|
+
* `wrangler d1 migrations apply` (point `d1_databases[].migrations_dir` here);
|
|
1008
|
+
* the factory only names it in error guidance.
|
|
1950
1009
|
*/
|
|
1951
1010
|
migrationsFolder?: string | URL;
|
|
1952
1011
|
/**
|
|
1953
|
-
* Drizzle relations for RQB v2 (`db.query.*`)
|
|
1954
|
-
*
|
|
1955
|
-
*
|
|
1012
|
+
* Drizzle relations for RQB v2 (`db.query.*`): `defineRelations(schema, ...)`
|
|
1013
|
+
* from `drizzle-orm`, or `relations()` from `drizzle-orm/_relations` for the
|
|
1014
|
+
* RQB v1 partial-upgrade path.
|
|
1956
1015
|
*/
|
|
1957
1016
|
relations?: Record<string, unknown>;
|
|
1958
1017
|
}
|
|
@@ -1971,8 +1030,8 @@ interface D1DatabaseHandle {
|
|
|
1971
1030
|
}
|
|
1972
1031
|
/**
|
|
1973
1032
|
* Cloudflare D1 database factory. D1 speaks the SQLite dialect, so schemas
|
|
1974
|
-
* written for `createSqliteDatabase` port unchanged;
|
|
1975
|
-
*
|
|
1033
|
+
* written for `createSqliteDatabase` port unchanged; wrangler owns migrations
|
|
1034
|
+
* (RFC 0003).
|
|
1976
1035
|
*/
|
|
1977
1036
|
declare function createD1Database(options: D1DatabaseOptions): D1DatabaseHandle;
|
|
1978
1037
|
//#endregion
|
|
@@ -1990,18 +1049,17 @@ interface AwsDataApiDatabaseOptions {
|
|
|
1990
1049
|
/** Extra RDSDataClient configuration (region, credentials, ...). */
|
|
1991
1050
|
clientOptions?: RDSDataClientConfig;
|
|
1992
1051
|
/**
|
|
1993
|
-
* Run pending migrations on the first `getDatabase()` call
|
|
1994
|
-
*
|
|
1995
|
-
*
|
|
1996
|
-
*
|
|
1997
|
-
* or the console handler (`{"command": "db:migrate"}`) once deployed.
|
|
1052
|
+
* Run pending migrations on the first `getDatabase()` call. Off by default:
|
|
1053
|
+
* on Lambda it costs several serialized Data API round trips on every cold
|
|
1054
|
+
* start. Migrate out of band instead — `db:migrate`, or the console handler
|
|
1055
|
+
* (`{"command": "db:migrate"}`) once deployed.
|
|
1998
1056
|
*/
|
|
1999
1057
|
migrateOnStart?: boolean;
|
|
2000
1058
|
seedersFolder?: string | URL;
|
|
2001
1059
|
/**
|
|
2002
|
-
* Drizzle relations for RQB v2 (`db.query.*`)
|
|
2003
|
-
*
|
|
2004
|
-
*
|
|
1060
|
+
* Drizzle relations for RQB v2 (`db.query.*`): `defineRelations(schema, ...)`
|
|
1061
|
+
* from `drizzle-orm`, or `relations()` from `drizzle-orm/_relations` for the
|
|
1062
|
+
* RQB v1 partial-upgrade path.
|
|
2005
1063
|
*/
|
|
2006
1064
|
relations?: Record<string, unknown>;
|
|
2007
1065
|
}
|
|
@@ -2021,11 +1079,7 @@ interface AwsDataApiDatabase {
|
|
|
2021
1079
|
declare function createAwsDataApiDatabase(options: AwsDataApiDatabaseOptions): AwsDataApiDatabase;
|
|
2022
1080
|
//#endregion
|
|
2023
1081
|
//#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
|
-
*/
|
|
1082
|
+
/** Serializes a record for JSON output: appends, then visible/hidden filtering. */
|
|
2029
1083
|
declare function serializeRecord(record: PlainObject, options: {
|
|
2030
1084
|
hidden?: string[];
|
|
2031
1085
|
visible?: string[];
|