@guren/orm 0.2.0-alpha.7 → 1.0.0-rc.9
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/drizzle.d.ts +1 -0
- package/dist/drizzle.js +11 -1
- package/dist/index.d.ts +1331 -28
- package/dist/index.js +2318 -79
- package/package.json +10 -4
package/dist/index.d.ts
CHANGED
|
@@ -1,92 +1,1173 @@
|
|
|
1
|
+
import { SQL } from 'drizzle-orm';
|
|
1
2
|
import { PostgresJsDatabase } from 'drizzle-orm/postgres-js';
|
|
2
3
|
import postgres from 'postgres';
|
|
4
|
+
import { MySql2Database } from 'drizzle-orm/mysql2';
|
|
3
5
|
|
|
6
|
+
/** Accessor function: transforms a record field value after reading from DB. */
|
|
7
|
+
type AccessorFn<T = unknown> = (record: PlainObject) => T;
|
|
8
|
+
/** Mutator function: transforms a field value before writing to DB. */
|
|
9
|
+
type MutatorFn<T = unknown> = (value: T, record: PlainObject) => unknown;
|
|
10
|
+
/** Map of field names to accessor functions. */
|
|
11
|
+
type AccessorDefinitions = Record<string, AccessorFn>;
|
|
12
|
+
/** Map of field names to mutator functions. */
|
|
13
|
+
type MutatorDefinitions = Record<string, MutatorFn>;
|
|
14
|
+
/** Apply accessors to a record, returning a new record with computed values. */
|
|
15
|
+
declare function applyAccessors<T extends PlainObject>(record: T, accessors?: AccessorDefinitions): T;
|
|
16
|
+
/** Apply mutators to data before persistence, returning a new object. */
|
|
17
|
+
declare function applyMutators(data: PlainObject, mutators?: MutatorDefinitions): PlainObject;
|
|
18
|
+
|
|
19
|
+
type FieldKey<TRecord extends PlainObject> = keyof TRecord & string;
|
|
20
|
+
/** Comparison operators supported by the QueryBuilder. */
|
|
21
|
+
type WhereOperator = '=' | '!=' | '>' | '<' | '>=' | '<=' | 'like' | 'in' | 'not in' | 'is null' | 'is not null';
|
|
22
|
+
/** A single field-level condition. */
|
|
23
|
+
interface SimpleCondition {
|
|
24
|
+
type: 'simple';
|
|
25
|
+
field: string;
|
|
26
|
+
operator: WhereOperator;
|
|
27
|
+
value: unknown;
|
|
28
|
+
}
|
|
29
|
+
/** A group of conditions joined by AND or OR. */
|
|
30
|
+
interface GroupCondition {
|
|
31
|
+
type: 'group';
|
|
32
|
+
boolean: 'and' | 'or';
|
|
33
|
+
conditions: WhereCondition[];
|
|
34
|
+
}
|
|
35
|
+
/** A where condition - either simple or grouped. */
|
|
36
|
+
type WhereCondition = SimpleCondition | GroupCondition;
|
|
37
|
+
/** Options carried by the QueryBuilder for query execution. */
|
|
38
|
+
interface QueryBuilderOptions {
|
|
39
|
+
orderBy: Array<{
|
|
40
|
+
column: string;
|
|
41
|
+
direction: OrderDirection;
|
|
42
|
+
}>;
|
|
43
|
+
limitValue?: number;
|
|
44
|
+
offsetValue?: number;
|
|
45
|
+
selectFields?: readonly string[];
|
|
46
|
+
trx?: unknown;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Fluent query builder for the Guren ORM.
|
|
50
|
+
*
|
|
51
|
+
* Provides a chainable API for constructing database queries with
|
|
52
|
+
* support for complex where conditions, ordering, pagination, and more.
|
|
53
|
+
*
|
|
54
|
+
* Implements the thenable pattern so it can be directly awaited,
|
|
55
|
+
* resolving to the result of `get()`.
|
|
56
|
+
*
|
|
57
|
+
* @example
|
|
58
|
+
* // Fluent chaining
|
|
59
|
+
* const posts = await Post.where('status', 'published')
|
|
60
|
+
* .where('views', '>', 100)
|
|
61
|
+
* .orderBy('createdAt', 'desc')
|
|
62
|
+
* .limit(10)
|
|
63
|
+
* .get()
|
|
64
|
+
*
|
|
65
|
+
* // Thenable - await directly
|
|
66
|
+
* const active = await User.where('active', true)
|
|
67
|
+
*
|
|
68
|
+
* // Pagination
|
|
69
|
+
* const page = await Post.where('status', 'published').paginate(1, 20)
|
|
70
|
+
*/
|
|
71
|
+
declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult extends PlainObject = TRecord> {
|
|
72
|
+
private conditions;
|
|
73
|
+
private options;
|
|
74
|
+
private modelClass;
|
|
75
|
+
private table;
|
|
76
|
+
private adapter;
|
|
77
|
+
private eagerLoad;
|
|
78
|
+
private eagerLoadConstraints;
|
|
79
|
+
constructor(modelClass: typeof Model, options?: {
|
|
80
|
+
trx?: unknown;
|
|
81
|
+
});
|
|
82
|
+
/**
|
|
83
|
+
* Add a where condition (AND).
|
|
84
|
+
*
|
|
85
|
+
* Supports three calling signatures:
|
|
86
|
+
* - `where(field, value)` - equality check
|
|
87
|
+
* - `where(field, operator, value)` - comparison
|
|
88
|
+
* - `where(object)` - multiple equality conditions
|
|
89
|
+
*/
|
|
90
|
+
where<TKey extends FieldKey<TRecord>>(field: TKey, value: TRecord[TKey]): this;
|
|
91
|
+
where<TKey extends FieldKey<TRecord>>(field: TKey, operator: WhereOperator, value: unknown): this;
|
|
92
|
+
where(conditions: Partial<Record<FieldKey<TRecord>, unknown>>): this;
|
|
93
|
+
/**
|
|
94
|
+
* Add an OR where condition.
|
|
95
|
+
*
|
|
96
|
+
* Same overloads as `where()`, but joins with OR logic.
|
|
97
|
+
* Creates an OR group containing the new condition(s).
|
|
98
|
+
*/
|
|
99
|
+
orWhere<TKey extends FieldKey<TRecord>>(field: TKey, value: TRecord[TKey]): this;
|
|
100
|
+
orWhere<TKey extends FieldKey<TRecord>>(field: TKey, operator: WhereOperator, value: unknown): this;
|
|
101
|
+
orWhere(conditions: Partial<Record<FieldKey<TRecord>, unknown>>): this;
|
|
102
|
+
/**
|
|
103
|
+
* Add a WHERE NULL condition.
|
|
104
|
+
* @param field - Column to check for NULL
|
|
105
|
+
*/
|
|
106
|
+
whereNull(field: FieldKey<TRecord>): this;
|
|
107
|
+
/**
|
|
108
|
+
* Add a WHERE NOT NULL condition.
|
|
109
|
+
* @param field - Column to check for NOT NULL
|
|
110
|
+
*/
|
|
111
|
+
whereNotNull(field: FieldKey<TRecord>): this;
|
|
112
|
+
/**
|
|
113
|
+
* Add a WHERE IN condition.
|
|
114
|
+
* @param field - Column to check
|
|
115
|
+
* @param values - Array of values to match against
|
|
116
|
+
*/
|
|
117
|
+
whereIn<TKey extends FieldKey<TRecord>>(field: TKey, values: readonly TRecord[TKey][]): this;
|
|
118
|
+
/**
|
|
119
|
+
* Add a WHERE NOT IN condition.
|
|
120
|
+
* @param field - Column to check
|
|
121
|
+
* @param values - Array of values to exclude
|
|
122
|
+
*/
|
|
123
|
+
whereNotIn<TKey extends FieldKey<TRecord>>(field: TKey, values: readonly TRecord[TKey][]): this;
|
|
124
|
+
/**
|
|
125
|
+
* Add an ORDER BY clause. Can be called multiple times to sort by multiple columns.
|
|
126
|
+
* @param field - Column to sort by
|
|
127
|
+
* @param direction - Sort direction (default: 'asc')
|
|
128
|
+
*/
|
|
129
|
+
orderBy(field: FieldKey<TRecord>, direction?: OrderDirection): this;
|
|
130
|
+
/**
|
|
131
|
+
* Set the maximum number of records to return.
|
|
132
|
+
* @param n - Maximum record count
|
|
133
|
+
*/
|
|
134
|
+
limit(n: number): this;
|
|
135
|
+
/**
|
|
136
|
+
* Set the number of records to skip.
|
|
137
|
+
* @param n - Number of records to skip
|
|
138
|
+
*/
|
|
139
|
+
offset(n: number): this;
|
|
140
|
+
/**
|
|
141
|
+
* Limit the columns returned in the result.
|
|
142
|
+
* @param fields - Column names to select
|
|
143
|
+
*/
|
|
144
|
+
select<TKey extends FieldKey<TRecord>>(...fields: readonly TKey[]): QueryBuilder<TRecord, Pick<TRecord, TKey>>;
|
|
145
|
+
/**
|
|
146
|
+
* Apply a named query scope defined on the model.
|
|
147
|
+
*
|
|
148
|
+
* @param name - The scope name
|
|
149
|
+
* @returns this (for chaining)
|
|
150
|
+
*
|
|
151
|
+
* @example
|
|
152
|
+
* const results = await Post.where('author', 'John')
|
|
153
|
+
* .scope('published')
|
|
154
|
+
* .scope('popular')
|
|
155
|
+
* .get()
|
|
156
|
+
*/
|
|
157
|
+
scope(name: string): this;
|
|
158
|
+
/**
|
|
159
|
+
* Eager-load relationships on query results.
|
|
160
|
+
*
|
|
161
|
+
* Supports string names, arrays, dot notation for nested relations,
|
|
162
|
+
* and constraint callbacks.
|
|
163
|
+
*
|
|
164
|
+
* @example
|
|
165
|
+
* // Simple
|
|
166
|
+
* await User.where('active', true).with('posts').get()
|
|
167
|
+
*
|
|
168
|
+
* // Multiple
|
|
169
|
+
* await User.where('active', true).with('posts', 'comments').get()
|
|
170
|
+
*
|
|
171
|
+
* // Nested (dot notation)
|
|
172
|
+
* await User.where('active', true).with('posts.comments').get()
|
|
173
|
+
*/
|
|
174
|
+
with(...relations: (string | Record<string, (q: QueryBuilder<any>) => void>)[]): this;
|
|
175
|
+
/**
|
|
176
|
+
* Execute the query and return all matching records.
|
|
177
|
+
* @returns Array of matching records
|
|
178
|
+
*/
|
|
179
|
+
get(): Promise<TResult[]>;
|
|
180
|
+
/**
|
|
181
|
+
* Execute the query and return the first matching record.
|
|
182
|
+
* @returns The first record or null
|
|
183
|
+
*/
|
|
184
|
+
first(): Promise<TResult | null>;
|
|
185
|
+
/**
|
|
186
|
+
* Execute the query and return the first matching record, or throw.
|
|
187
|
+
* @returns The first record
|
|
188
|
+
* @throws Error if no record matches
|
|
189
|
+
*/
|
|
190
|
+
firstOrFail(): Promise<TResult>;
|
|
191
|
+
/**
|
|
192
|
+
* Count the number of records matching the current conditions.
|
|
193
|
+
* @returns The count of matching records
|
|
194
|
+
*/
|
|
195
|
+
count(): Promise<number>;
|
|
196
|
+
/**
|
|
197
|
+
* Paginate the query results.
|
|
198
|
+
* @param page - Page number (1-based, default: 1)
|
|
199
|
+
* @param perPage - Records per page (default: 15)
|
|
200
|
+
* @returns Paginated result with data and metadata
|
|
201
|
+
*/
|
|
202
|
+
paginate(page?: number, perPage?: number): Promise<PaginatedResult<TResult>>;
|
|
203
|
+
/**
|
|
204
|
+
* Bulk update records matching the current conditions.
|
|
205
|
+
* @param data - Data to set on matching records
|
|
206
|
+
* @returns The updated record (adapter-dependent)
|
|
207
|
+
*/
|
|
208
|
+
update(data: PlainObject): Promise<TRecord>;
|
|
209
|
+
/**
|
|
210
|
+
* Bulk delete records matching the current conditions.
|
|
211
|
+
* @returns Number of deleted records (adapter-dependent)
|
|
212
|
+
*/
|
|
213
|
+
delete(): Promise<number | PlainObject | void>;
|
|
214
|
+
/**
|
|
215
|
+
* Makes QueryBuilder a thenable so it can be directly awaited.
|
|
216
|
+
* Resolves to the result of `get()`.
|
|
217
|
+
*/
|
|
218
|
+
then<TResult1 = TResult[], TResult2 = never>(onfulfilled?: ((value: TResult[]) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult1 | TResult2>;
|
|
219
|
+
/**
|
|
220
|
+
* Catch handler for the thenable interface.
|
|
221
|
+
*/
|
|
222
|
+
catch<TCatch = never>(onrejected?: ((reason: unknown) => TCatch | PromiseLike<TCatch>) | null): Promise<TResult[] | TCatch>;
|
|
223
|
+
/** Get the internal conditions (used by adapters). */
|
|
224
|
+
getConditions(): WhereCondition[];
|
|
225
|
+
/** Get the internal query options (used by adapters). */
|
|
226
|
+
getOptions(): QueryBuilderOptions;
|
|
227
|
+
private addSimpleCondition;
|
|
228
|
+
private executeQuery;
|
|
229
|
+
/**
|
|
230
|
+
* Attempt to convert the current conditions to a simple WhereClause
|
|
231
|
+
* for backward compatibility with basic adapters.
|
|
232
|
+
* Returns null if conditions are too complex.
|
|
233
|
+
*/
|
|
234
|
+
private toSimpleWhereClause;
|
|
235
|
+
/**
|
|
236
|
+
* Load eager relations onto fetched results.
|
|
237
|
+
* Supports dot notation for nested relations (e.g., 'posts.comments').
|
|
238
|
+
*/
|
|
239
|
+
private readonly loadEagerRelations;
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* Extended adapter interface for advanced query builder features.
|
|
243
|
+
* Adapters can optionally implement these methods for full QueryBuilder support.
|
|
244
|
+
*/
|
|
245
|
+
interface ORMAdapterAdvanced extends ORMAdapter {
|
|
246
|
+
findManyAdvanced?<TRecord extends PlainObject = PlainObject>(table: unknown, conditions: WhereCondition[], options: {
|
|
247
|
+
orderBy?: OrderByClause;
|
|
248
|
+
limit?: number;
|
|
249
|
+
offset?: number;
|
|
250
|
+
select?: readonly string[];
|
|
251
|
+
}, queryOptions?: AdapterQueryOptions): Promise<TRecord[]>;
|
|
252
|
+
countAdvanced?<TRecord extends PlainObject = PlainObject>(table: unknown, conditions: WhereCondition[], queryOptions?: AdapterQueryOptions): Promise<number>;
|
|
253
|
+
updateAdvanced?<TRecord extends PlainObject = PlainObject>(table: unknown, conditions: WhereCondition[], data: PlainObject, writeOptions?: AdapterQueryOptions): Promise<TRecord>;
|
|
254
|
+
deleteAdvanced?<TRecord extends PlainObject = PlainObject>(table: unknown, conditions: WhereCondition[], writeOptions?: AdapterQueryOptions): Promise<number | PlainObject | void>;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** A named global scope function. */
|
|
258
|
+
type ScopeFunction = (q: QueryBuilder<any>) => QueryBuilder<any>;
|
|
259
|
+
/**
|
|
260
|
+
* Registry for named global scopes on a model.
|
|
261
|
+
*
|
|
262
|
+
* Supports adding, removing, and applying multiple named scopes.
|
|
263
|
+
* Used internally by Model to manage global query constraints.
|
|
264
|
+
*/
|
|
265
|
+
declare class GlobalScopeRegistry {
|
|
266
|
+
private scopes;
|
|
267
|
+
add(name: string, fn: ScopeFunction): void;
|
|
268
|
+
remove(name: string): void;
|
|
269
|
+
has(name: string): boolean;
|
|
270
|
+
names(): string[];
|
|
271
|
+
/** Apply all scopes (or all except excluded) to a query builder. */
|
|
272
|
+
apply<T extends PlainObject>(builder: QueryBuilder<T>, except?: string[]): QueryBuilder<T>;
|
|
273
|
+
clear(): void;
|
|
274
|
+
get size(): number;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Model lifecycle hook names.
|
|
279
|
+
*
|
|
280
|
+
* "Before" hooks (`creating`, `updating`, `deleting`, `saving`) fire before
|
|
281
|
+
* the database operation. If they return `false`, the operation is aborted.
|
|
282
|
+
*
|
|
283
|
+
* "After" hooks (`created`, `updated`, `deleted`, `saved`) fire after the
|
|
284
|
+
* database operation completes.
|
|
285
|
+
*
|
|
286
|
+
* `saving`/`saved` fire for both create and update operations.
|
|
287
|
+
*/
|
|
288
|
+
type HookName = 'creating' | 'created' | 'updating' | 'updated' | 'deleting' | 'deleted' | 'saving' | 'saved';
|
|
289
|
+
/**
|
|
290
|
+
* Callback signature for model lifecycle hooks.
|
|
291
|
+
*
|
|
292
|
+
* @param data - The record data being operated on
|
|
293
|
+
* @returns void for after-hooks. Returning `false` from a before-hook aborts the operation.
|
|
294
|
+
*/
|
|
295
|
+
type HookCallback<T = Record<string, unknown>> = (data: T) => void | Promise<void> | false | Promise<false>;
|
|
296
|
+
/**
|
|
297
|
+
* Map of hook names to their callbacks.
|
|
298
|
+
* All hooks are optional.
|
|
299
|
+
*/
|
|
300
|
+
type ModelHooks = {
|
|
301
|
+
[K in HookName]?: HookCallback;
|
|
302
|
+
};
|
|
303
|
+
/**
|
|
304
|
+
* Execute a model hook if it exists.
|
|
305
|
+
*
|
|
306
|
+
* @param hooks - The hooks object from the model
|
|
307
|
+
* @param name - The hook name to execute
|
|
308
|
+
* @param data - The data to pass to the hook
|
|
309
|
+
* @returns `false` if the hook explicitly returned false (operation should be aborted), otherwise `true`
|
|
310
|
+
*/
|
|
311
|
+
declare function executeHook(hooks: ModelHooks | undefined, name: HookName, data: Record<string, unknown>): Promise<boolean>;
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* Base interface for model observers.
|
|
315
|
+
*
|
|
316
|
+
* Observers allow extracting lifecycle hook logic into dedicated classes.
|
|
317
|
+
* Each method corresponds to a model lifecycle event and is optional.
|
|
318
|
+
*
|
|
319
|
+
* @example
|
|
320
|
+
* class UserObserver implements ModelObserver {
|
|
321
|
+
* async creating(data) { data.slug = slugify(data.name) }
|
|
322
|
+
* async created(data) { await sendWelcomeEmail(data) }
|
|
323
|
+
* }
|
|
324
|
+
*
|
|
325
|
+
* User.observe(UserObserver)
|
|
326
|
+
*/
|
|
327
|
+
interface ModelObserver {
|
|
328
|
+
creating?(data: PlainObject): void | Promise<void> | false | Promise<false>;
|
|
329
|
+
created?(data: PlainObject): void | Promise<void>;
|
|
330
|
+
updating?(data: PlainObject): void | Promise<void> | false | Promise<false>;
|
|
331
|
+
updated?(data: PlainObject): void | Promise<void>;
|
|
332
|
+
deleting?(data: PlainObject): void | Promise<void> | false | Promise<false>;
|
|
333
|
+
deleted?(data: PlainObject): void | Promise<void>;
|
|
334
|
+
saving?(data: PlainObject): void | Promise<void> | false | Promise<false>;
|
|
335
|
+
saved?(data: PlainObject): void | Promise<void>;
|
|
336
|
+
}
|
|
337
|
+
type ModelObserverConstructor = new () => ModelObserver;
|
|
338
|
+
/**
|
|
339
|
+
* Execute all registered observers for a given hook.
|
|
340
|
+
* Returns false if any observer aborts the operation.
|
|
341
|
+
*/
|
|
342
|
+
declare function executeObservers(observers: ModelObserver[] | undefined, name: HookName, data: PlainObject): Promise<boolean>;
|
|
343
|
+
|
|
344
|
+
/** Generic plain object type used throughout the ORM. */
|
|
4
345
|
type PlainObject = Record<string, unknown>;
|
|
5
346
|
type RelationShape = Record<string, unknown>;
|
|
347
|
+
type TableShape<TSelect extends PlainObject = PlainObject, TInsert extends PlainObject = PlainObject> = {
|
|
348
|
+
$inferSelect: TSelect;
|
|
349
|
+
$inferInsert?: TInsert;
|
|
350
|
+
};
|
|
351
|
+
type InferModelRecord<TTable> = TTable extends {
|
|
352
|
+
$inferSelect: infer TRecord;
|
|
353
|
+
} ? TRecord extends PlainObject ? TRecord : PlainObject : PlainObject;
|
|
354
|
+
type InferModelInsert<TTable> = TTable extends {
|
|
355
|
+
$inferInsert: infer TInsert;
|
|
356
|
+
} ? TInsert extends PlainObject ? TInsert : PlainObject : PlainObject;
|
|
357
|
+
/** Supported cast types for attribute casting. */
|
|
358
|
+
type CastType = 'json' | 'date' | 'boolean' | 'number' | 'string';
|
|
359
|
+
/**
|
|
360
|
+
* Value type for where clause conditions.
|
|
361
|
+
* Supports single values, arrays (for IN queries), or null.
|
|
362
|
+
*/
|
|
6
363
|
type WhereValue<Value> = Value | readonly Value[] | null;
|
|
364
|
+
/**
|
|
365
|
+
* Where clause for filtering records.
|
|
366
|
+
* Supports equality and IN (array) queries.
|
|
367
|
+
*
|
|
368
|
+
* @example
|
|
369
|
+
* // Single value (equality)
|
|
370
|
+
* { status: 'active' }
|
|
371
|
+
*
|
|
372
|
+
* // Array value (IN query)
|
|
373
|
+
* { id: [1, 2, 3] }
|
|
374
|
+
*
|
|
375
|
+
* // Multiple conditions (AND)
|
|
376
|
+
* { status: 'active', role: 'admin' }
|
|
377
|
+
*/
|
|
7
378
|
type WhereClause<TRecord extends PlainObject = PlainObject> = Partial<{
|
|
8
379
|
[K in keyof TRecord & string]?: WhereValue<TRecord[K]>;
|
|
9
380
|
}>;
|
|
381
|
+
/** Sort direction for ordering queries. */
|
|
10
382
|
type OrderDirection = 'asc' | 'desc';
|
|
383
|
+
/** Normalized order definition with column and direction. */
|
|
11
384
|
type OrderDefinition<TRecord extends PlainObject = PlainObject> = {
|
|
12
385
|
column: keyof TRecord & string;
|
|
13
386
|
direction: OrderDirection;
|
|
14
387
|
};
|
|
388
|
+
/**
|
|
389
|
+
* Flexible order expression input.
|
|
390
|
+
* @example
|
|
391
|
+
* 'createdAt' // Column name (ascending)
|
|
392
|
+
* ['createdAt', 'desc'] // Tuple [column, direction]
|
|
393
|
+
* { column: 'createdAt', direction: 'desc' } // Object form
|
|
394
|
+
*/
|
|
15
395
|
type OrderExpression<TRecord extends PlainObject = PlainObject> = (keyof TRecord & string) | readonly [keyof TRecord & string, OrderDirection] | {
|
|
16
396
|
column: keyof TRecord & string;
|
|
17
397
|
direction?: OrderDirection;
|
|
18
398
|
};
|
|
399
|
+
/** Input for orderBy - single expression or array of expressions. */
|
|
19
400
|
type OrderByInput<TRecord extends PlainObject = PlainObject> = OrderExpression<TRecord> | readonly OrderExpression<TRecord>[];
|
|
401
|
+
/** Normalized array of order definitions. */
|
|
20
402
|
type OrderByClause<TRecord extends PlainObject = PlainObject> = readonly OrderDefinition<TRecord>[];
|
|
403
|
+
/** Options for findMany queries. */
|
|
21
404
|
interface FindManyOptions<TRecord extends PlainObject = PlainObject> {
|
|
405
|
+
/** Filter conditions */
|
|
22
406
|
where?: WhereClause<TRecord>;
|
|
407
|
+
/** Sort order */
|
|
23
408
|
orderBy?: OrderByClause<TRecord>;
|
|
409
|
+
/** Maximum number of records to return */
|
|
24
410
|
limit?: number;
|
|
411
|
+
/** Number of records to skip */
|
|
25
412
|
offset?: number;
|
|
26
413
|
}
|
|
414
|
+
/** Options for paginated queries. */
|
|
27
415
|
interface PaginateOptions<TRecord extends PlainObject = PlainObject> {
|
|
416
|
+
/** Page number (1-based, default: 1) */
|
|
28
417
|
page?: number;
|
|
418
|
+
/** Records per page (default: 15) */
|
|
29
419
|
perPage?: number;
|
|
420
|
+
/** Filter conditions */
|
|
30
421
|
where?: WhereClause<TRecord>;
|
|
422
|
+
/** Sort order */
|
|
31
423
|
orderBy?: OrderByInput<TRecord>;
|
|
32
424
|
}
|
|
425
|
+
/** Pagination metadata returned with paginated results. */
|
|
33
426
|
interface PaginationMeta {
|
|
427
|
+
/** Total number of records matching the query */
|
|
34
428
|
total: number;
|
|
429
|
+
/** Number of records per page */
|
|
35
430
|
perPage: number;
|
|
431
|
+
/** Current page number (1-based) */
|
|
36
432
|
currentPage: number;
|
|
433
|
+
/** Total number of pages */
|
|
37
434
|
totalPages: number;
|
|
435
|
+
/** Whether there are more pages after this one */
|
|
38
436
|
hasMore: boolean;
|
|
437
|
+
/** Index of first record on this page (1-based) */
|
|
39
438
|
from: number;
|
|
439
|
+
/** Index of last record on this page */
|
|
40
440
|
to: number;
|
|
41
441
|
}
|
|
442
|
+
/** Result of a paginated query. */
|
|
42
443
|
interface PaginatedResult<TRecord extends PlainObject = PlainObject> {
|
|
444
|
+
/** Records for the current page */
|
|
43
445
|
data: TRecord[];
|
|
446
|
+
/** Pagination metadata */
|
|
44
447
|
meta: PaginationMeta;
|
|
45
448
|
}
|
|
449
|
+
/**
|
|
450
|
+
* Interface for ORM adapters that power the Model class.
|
|
451
|
+
* The default adapter is DrizzleAdapter.
|
|
452
|
+
*/
|
|
46
453
|
interface ORMAdapter {
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
454
|
+
/** Run operations in a database transaction. */
|
|
455
|
+
transaction?<TResult>(callback: (trx: unknown) => Promise<TResult>): Promise<TResult>;
|
|
456
|
+
/** Find multiple records with optional filtering, ordering, and pagination. */
|
|
457
|
+
findMany<TRecord extends PlainObject = PlainObject>(table: unknown, options?: FindManyOptions<TRecord>, queryOptions?: AdapterQueryOptions): Promise<TRecord[]>;
|
|
458
|
+
/** Find a single record by unique criteria. */
|
|
459
|
+
findUnique<TRecord extends PlainObject = PlainObject>(table: unknown, where: WhereClause<TRecord>, queryOptions?: AdapterQueryOptions): Promise<TRecord | null>;
|
|
460
|
+
/** Create a new record. */
|
|
461
|
+
create<TRecord extends PlainObject = PlainObject>(table: unknown, data: PlainObject, writeOptions?: AdapterQueryOptions): Promise<TRecord>;
|
|
462
|
+
/** Update records matching criteria. */
|
|
463
|
+
update?<TRecord extends PlainObject = PlainObject>(table: unknown, where: WhereClause<TRecord>, data: PlainObject, writeOptions?: AdapterQueryOptions): Promise<TRecord>;
|
|
464
|
+
/** Delete records matching criteria. */
|
|
465
|
+
delete?<TRecord extends PlainObject = PlainObject>(table: unknown, where: WhereClause<TRecord>, writeOptions?: AdapterQueryOptions): Promise<number | PlainObject | void>;
|
|
466
|
+
/** Count records matching criteria. */
|
|
467
|
+
count?<TRecord extends PlainObject = PlainObject>(table: unknown, where?: WhereClause<TRecord>, queryOptions?: AdapterQueryOptions): Promise<number>;
|
|
468
|
+
}
|
|
469
|
+
interface AdapterQueryOptions {
|
|
470
|
+
trx?: unknown;
|
|
53
471
|
}
|
|
472
|
+
type ModelWriteOptions = AdapterQueryOptions;
|
|
473
|
+
type ModelQueryOptions = AdapterQueryOptions;
|
|
474
|
+
type TransactionHandle = NonNullable<AdapterQueryOptions['trx']>;
|
|
475
|
+
type SelectFrom<TDatabase> = TDatabase extends {
|
|
476
|
+
select: (...args: any[]) => infer TSelect;
|
|
477
|
+
} ? TSelect extends {
|
|
478
|
+
from: (...args: any[]) => infer TResult;
|
|
479
|
+
} ? TResult : never : never;
|
|
54
480
|
/**
|
|
55
|
-
*
|
|
56
|
-
*
|
|
481
|
+
* ActiveRecord-style base class for database models.
|
|
482
|
+
*
|
|
483
|
+
* Provides a Laravel Eloquent-like API for database operations including
|
|
484
|
+
* CRUD, querying, pagination, and eager-loading of relationships.
|
|
485
|
+
*
|
|
486
|
+
* @example
|
|
487
|
+
* // Define a model
|
|
488
|
+
* class User extends Model<UserRecord> {
|
|
489
|
+
* static override table = users // Drizzle table
|
|
490
|
+
* static override readonly recordType = {} as UserRecord
|
|
491
|
+
* }
|
|
492
|
+
*
|
|
493
|
+
* // Query records
|
|
494
|
+
* const allUsers = await User.all()
|
|
495
|
+
* const user = await User.find(1)
|
|
496
|
+
* const activeUsers = await User.where({ status: 'active' })
|
|
497
|
+
*
|
|
498
|
+
* // Create and update
|
|
499
|
+
* const newUser = await User.create({ name: 'John', email: 'john@example.com' })
|
|
500
|
+
* await User.update({ id: 1 }, { name: 'Jane' })
|
|
501
|
+
*
|
|
502
|
+
* // Pagination
|
|
503
|
+
* const page = await User.paginate({ page: 1, perPage: 10 })
|
|
504
|
+
*
|
|
505
|
+
* // Relationships
|
|
506
|
+
* const usersWithPosts = await User.with('posts')
|
|
57
507
|
*/
|
|
58
508
|
declare abstract class Model<TRecord extends PlainObject = PlainObject> {
|
|
509
|
+
/** The ORM adapter used for database operations. */
|
|
59
510
|
protected static ormAdapter: ORMAdapter;
|
|
511
|
+
/** The database table (e.g., Drizzle table schema). */
|
|
60
512
|
protected static table: unknown;
|
|
513
|
+
/** Type marker for TypeScript inference. Define as `{} as YourRecordType`. */
|
|
61
514
|
static readonly recordType: unknown;
|
|
515
|
+
/** Type marker for insert/update payload inference. Define as `{} as typeof table.$inferInsert`. */
|
|
516
|
+
static readonly createType: unknown;
|
|
62
517
|
protected static relationDefinitions?: Map<string, RelationDefinition>;
|
|
518
|
+
/** Type marker for relation types. Define relation types here for type inference. */
|
|
63
519
|
static relationTypes: RelationShape;
|
|
520
|
+
/**
|
|
521
|
+
* Named query scopes for reusable query constraints.
|
|
522
|
+
*
|
|
523
|
+
* @example
|
|
524
|
+
* class Post extends Model<PostRecord> {
|
|
525
|
+
* static scopes = {
|
|
526
|
+
* published: (q: QueryBuilder<PostRecord>) => q.where('status', 'published'),
|
|
527
|
+
* popular: (q: QueryBuilder<PostRecord>) => q.where('views', '>', 1000),
|
|
528
|
+
* }
|
|
529
|
+
* }
|
|
530
|
+
* // Usage: Post.scope('published').scope('popular').get()
|
|
531
|
+
*/
|
|
532
|
+
static scopes?: Record<string, (q: QueryBuilder<any>) => QueryBuilder<any>>;
|
|
533
|
+
/**
|
|
534
|
+
* Default scope applied to all queries on this model.
|
|
535
|
+
* Override this to automatically filter queries (e.g., soft deletes).
|
|
536
|
+
*
|
|
537
|
+
* @example
|
|
538
|
+
* static defaultScope = (q: QueryBuilder<any>) => q.whereNull('deletedAt')
|
|
539
|
+
*/
|
|
540
|
+
static defaultScope?: (q: QueryBuilder<any>) => QueryBuilder<any>;
|
|
541
|
+
/**
|
|
542
|
+
* Model lifecycle hooks that fire during create, update, and delete operations.
|
|
543
|
+
*
|
|
544
|
+
* @example
|
|
545
|
+
* class User extends Model<UserRecord> {
|
|
546
|
+
* static hooks: ModelHooks = {
|
|
547
|
+
* creating: async (data) => { data.password = await hash(data.password as string) },
|
|
548
|
+
* created: async (data) => { console.log('User created:', data) },
|
|
549
|
+
* }
|
|
550
|
+
* }
|
|
551
|
+
*/
|
|
552
|
+
static hooks?: ModelHooks;
|
|
553
|
+
/**
|
|
554
|
+
* Attribute casting definitions for automatic type conversion.
|
|
555
|
+
*
|
|
556
|
+
* Casts are applied when reading records from the database and when
|
|
557
|
+
* writing records to the database.
|
|
558
|
+
*
|
|
559
|
+
* @example
|
|
560
|
+
* class Post extends Model<PostRecord> {
|
|
561
|
+
* static casts = {
|
|
562
|
+
* metadata: 'json',
|
|
563
|
+
* publishedAt: 'date',
|
|
564
|
+
* isActive: 'boolean',
|
|
565
|
+
* viewCount: 'number',
|
|
566
|
+
* }
|
|
567
|
+
* }
|
|
568
|
+
*/
|
|
569
|
+
static casts?: Record<string, CastType>;
|
|
570
|
+
/**
|
|
571
|
+
* Whitelist of fields allowed for mass assignment.
|
|
572
|
+
* If set, only these fields will be accepted in `create()` and `update()`.
|
|
573
|
+
*
|
|
574
|
+
* @example
|
|
575
|
+
* class User extends Model<UserRecord> {
|
|
576
|
+
* static fillable = ['name', 'email', 'password']
|
|
577
|
+
* }
|
|
578
|
+
*/
|
|
579
|
+
static fillable?: string[];
|
|
580
|
+
/**
|
|
581
|
+
* Blacklist of fields excluded from mass assignment.
|
|
582
|
+
* Defaults to `['id']`. Ignored if `fillable` is set.
|
|
583
|
+
*
|
|
584
|
+
* @example
|
|
585
|
+
* class Post extends Model<PostRecord> {
|
|
586
|
+
* static guarded = ['id', 'createdAt']
|
|
587
|
+
* }
|
|
588
|
+
*/
|
|
589
|
+
static guarded?: string[];
|
|
590
|
+
/**
|
|
591
|
+
* Accessor functions for computed/virtual attributes.
|
|
592
|
+
* Applied after reading records from the database.
|
|
593
|
+
*
|
|
594
|
+
* @example
|
|
595
|
+
* class User extends Model<UserRecord> {
|
|
596
|
+
* static accessors = {
|
|
597
|
+
* fullName: (record) => `${record.firstName} ${record.lastName}`,
|
|
598
|
+
* }
|
|
599
|
+
* }
|
|
600
|
+
*/
|
|
601
|
+
static accessors?: AccessorDefinitions;
|
|
602
|
+
/**
|
|
603
|
+
* Mutator functions for transforming attributes before persistence.
|
|
604
|
+
*
|
|
605
|
+
* @example
|
|
606
|
+
* class User extends Model<UserRecord> {
|
|
607
|
+
* static mutators = {
|
|
608
|
+
* email: (value) => String(value).toLowerCase(),
|
|
609
|
+
* }
|
|
610
|
+
* }
|
|
611
|
+
*/
|
|
612
|
+
static mutators?: MutatorDefinitions;
|
|
613
|
+
/**
|
|
614
|
+
* Fields to exclude from serialization output.
|
|
615
|
+
*
|
|
616
|
+
* @example
|
|
617
|
+
* class User extends Model<UserRecord> {
|
|
618
|
+
* static hidden = ['passwordHash', 'rememberToken']
|
|
619
|
+
* }
|
|
620
|
+
*/
|
|
621
|
+
static hidden?: string[];
|
|
622
|
+
/**
|
|
623
|
+
* Whitelist of fields to include in serialization output.
|
|
624
|
+
* When set, only these fields appear. Takes precedence over `hidden`.
|
|
625
|
+
*/
|
|
626
|
+
static visible?: string[];
|
|
627
|
+
/**
|
|
628
|
+
* Virtual accessor attributes to include in serialization output.
|
|
629
|
+
*
|
|
630
|
+
* @example
|
|
631
|
+
* class User extends Model<UserRecord> {
|
|
632
|
+
* static appends = ['fullName']
|
|
633
|
+
* static accessors = { fullName: (r) => `${r.firstName} ${r.lastName}` }
|
|
634
|
+
* }
|
|
635
|
+
*/
|
|
636
|
+
static appends?: string[];
|
|
637
|
+
/** Registered model observers. */
|
|
638
|
+
protected static observers?: ModelObserver[];
|
|
639
|
+
/** Named global scopes registry. */
|
|
640
|
+
protected static globalScopeRegistry?: GlobalScopeRegistry;
|
|
641
|
+
/**
|
|
642
|
+
* Set a custom ORM adapter for this model.
|
|
643
|
+
* @param adapter - The adapter to use
|
|
644
|
+
*/
|
|
64
645
|
static useAdapter(adapter: ORMAdapter): void;
|
|
646
|
+
/**
|
|
647
|
+
* Get the current ORM adapter.
|
|
648
|
+
* @returns The configured adapter
|
|
649
|
+
*/
|
|
65
650
|
static getAdapter(): ORMAdapter;
|
|
651
|
+
/**
|
|
652
|
+
* Run operations inside a database transaction.
|
|
653
|
+
*
|
|
654
|
+
* @example
|
|
655
|
+
* await User.transaction(async (trx) => {
|
|
656
|
+
* const user = await User.create({ name: 'John' }, { trx })
|
|
657
|
+
* await Profile.create({ userId: user.id }, { trx })
|
|
658
|
+
* })
|
|
659
|
+
*/
|
|
660
|
+
static transaction<T extends typeof Model, TResult>(this: T, callback: (trx: TransactionHandle, scope: TransactionModelScope<T>) => Promise<TResult>): Promise<TResult>;
|
|
661
|
+
/**
|
|
662
|
+
* Create a transaction-bound model scope that automatically forwards `trx`
|
|
663
|
+
* to query and write operations.
|
|
664
|
+
*
|
|
665
|
+
* @example
|
|
666
|
+
* await User.transaction(async (trx, txUser) => {
|
|
667
|
+
* await txUser.create({ name: 'Shinji' })
|
|
668
|
+
* await txUser.update({ id: 1 }, { name: 'Ikari' })
|
|
669
|
+
* })
|
|
670
|
+
*/
|
|
671
|
+
static inTransaction<T extends typeof Model>(this: T, trx: TransactionHandle): TransactionModelScope<T>;
|
|
672
|
+
/**
|
|
673
|
+
* Register a model observer class.
|
|
674
|
+
*
|
|
675
|
+
* @example
|
|
676
|
+
* User.observe(UserObserver)
|
|
677
|
+
*/
|
|
678
|
+
static observe(ObserverClass: ModelObserverConstructor): void;
|
|
679
|
+
/** Clear all registered observers. */
|
|
680
|
+
static clearObservers(): void;
|
|
681
|
+
protected static getGlobalScopes(): GlobalScopeRegistry;
|
|
682
|
+
/**
|
|
683
|
+
* Register a named global scope.
|
|
684
|
+
*
|
|
685
|
+
* @example
|
|
686
|
+
* User.addGlobalScope('active', (q) => q.where('active', true))
|
|
687
|
+
*/
|
|
688
|
+
static addGlobalScope(name: string, fn: ScopeFunction): void;
|
|
689
|
+
/** Remove a named global scope. */
|
|
690
|
+
static removeGlobalScope(name: string): void;
|
|
691
|
+
/**
|
|
692
|
+
* Start a query excluding specific global scope(s).
|
|
693
|
+
*
|
|
694
|
+
* @example
|
|
695
|
+
* const all = await User.withoutGlobalScope('active').get()
|
|
696
|
+
*/
|
|
697
|
+
static withoutGlobalScope<T extends typeof Model>(this: T, ...names: string[]): QueryBuilder<TRecordFor<T>>;
|
|
698
|
+
/**
|
|
699
|
+
* Start a query with no global scopes applied (also skips defaultScope).
|
|
700
|
+
*
|
|
701
|
+
* @example
|
|
702
|
+
* const all = await User.withoutGlobalScopes().get()
|
|
703
|
+
*/
|
|
704
|
+
static withoutGlobalScopes<T extends typeof Model>(this: T): QueryBuilder<TRecordFor<T>>;
|
|
705
|
+
/**
|
|
706
|
+
* Serialize a record for API/JSON output.
|
|
707
|
+
* Applies hidden/visible filtering, accessors, and appends.
|
|
708
|
+
*
|
|
709
|
+
* @example
|
|
710
|
+
* const json = User.serialize(user)
|
|
711
|
+
*/
|
|
712
|
+
static serialize<T extends typeof Model>(this: T, record: TRecordFor<T>): PlainObject;
|
|
713
|
+
/**
|
|
714
|
+
* Serialize an array of records.
|
|
715
|
+
*
|
|
716
|
+
* @example
|
|
717
|
+
* const json = User.serializeMany(users)
|
|
718
|
+
*/
|
|
719
|
+
static serializeMany<T extends typeof Model>(this: T, records: TRecordFor<T>[]): PlainObject[];
|
|
720
|
+
/**
|
|
721
|
+
* Apply attribute casts to a record read from the database.
|
|
722
|
+
*
|
|
723
|
+
* @param record - The raw record from the database
|
|
724
|
+
* @returns The record with cast attributes applied
|
|
725
|
+
*/
|
|
726
|
+
static applyCasts<T extends PlainObject>(record: T): T;
|
|
727
|
+
/**
|
|
728
|
+
* Apply all read-time transforms: casts then accessors.
|
|
729
|
+
* Used internally after fetching records from the database.
|
|
730
|
+
*/
|
|
731
|
+
protected static applyReadTransforms<T extends PlainObject>(record: T): T;
|
|
732
|
+
/**
|
|
733
|
+
* Filter input data based on mass assignment protection rules.
|
|
734
|
+
*
|
|
735
|
+
* If `fillable` is defined, only fields listed in `fillable` are kept.
|
|
736
|
+
* Otherwise, fields listed in `guarded` (default: `['id']`) are removed.
|
|
737
|
+
*
|
|
738
|
+
* @param data - The input data to filter
|
|
739
|
+
* @returns Filtered data safe for mass assignment
|
|
740
|
+
*/
|
|
741
|
+
static filterFillable(data: PlainObject): PlainObject;
|
|
66
742
|
protected static preparePersistencePayload(data: PlainObject): Promise<PlainObject>;
|
|
67
743
|
protected static getRelationDefinitions(): Map<string, RelationDefinition>;
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
static
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
744
|
+
/** @internal */
|
|
745
|
+
static getRelationDefinition(name: string): RelationDefinition | undefined;
|
|
746
|
+
static resolveTable(): unknown;
|
|
747
|
+
/**
|
|
748
|
+
* Retrieve all records from the table.
|
|
749
|
+
*
|
|
750
|
+
* @returns Array of all records
|
|
751
|
+
*
|
|
752
|
+
* @example
|
|
753
|
+
* const users = await User.all()
|
|
754
|
+
*/
|
|
755
|
+
static all<T extends typeof Model>(this: T, queryOptions?: ModelQueryOptions): Promise<Array<TRecordFor<T>>>;
|
|
756
|
+
/**
|
|
757
|
+
* Find a record by its primary key.
|
|
758
|
+
*
|
|
759
|
+
* @param id - The primary key value
|
|
760
|
+
* @param key - The primary key column name (default: 'id')
|
|
761
|
+
* @returns The record or null if not found
|
|
762
|
+
*
|
|
763
|
+
* @example
|
|
764
|
+
* const user = await User.find(1)
|
|
765
|
+
* const userByEmail = await User.find('john@example.com', 'email')
|
|
766
|
+
*/
|
|
767
|
+
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>;
|
|
768
|
+
/**
|
|
769
|
+
* Find a record by primary key or throw an error.
|
|
770
|
+
*
|
|
771
|
+
* @param id - The primary key value
|
|
772
|
+
* @param key - The primary key column name (default: 'id')
|
|
773
|
+
* @returns The record
|
|
774
|
+
* @throws Error if record not found
|
|
775
|
+
*
|
|
776
|
+
* @example
|
|
777
|
+
* const user = await User.findOrFail(1) // Throws if not found
|
|
778
|
+
*/
|
|
779
|
+
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>>;
|
|
780
|
+
/**
|
|
781
|
+
* Find a record by primary key with eager-loaded relations.
|
|
782
|
+
*
|
|
783
|
+
* @param id - The primary key value
|
|
784
|
+
* @param relations - Relation name(s) to eager load
|
|
785
|
+
* @param key - The primary key column name (default: 'id')
|
|
786
|
+
* @returns The record with loaded relations, or null if not found
|
|
787
|
+
*
|
|
788
|
+
* @example
|
|
789
|
+
* const post = await Post.findWith(1, 'author')
|
|
790
|
+
* const post = await Post.findWith(1, ['author', 'tags'])
|
|
791
|
+
*/
|
|
792
|
+
static findWith<T extends typeof Model, K extends RelationKey<T>>(this: T, id: TRecordFor<T>[keyof TRecordFor<T> & string], relations: K | readonly K[], key?: keyof TRecordFor<T> & string): Promise<(TRecordFor<T> & RelationTypePick<T, K | readonly K[]>) | null>;
|
|
793
|
+
/**
|
|
794
|
+
* Find a record by primary key with eager-loaded relations, or throw.
|
|
795
|
+
*
|
|
796
|
+
* @param id - The primary key value
|
|
797
|
+
* @param relations - Relation name(s) to eager load
|
|
798
|
+
* @param key - The primary key column name (default: 'id')
|
|
799
|
+
* @returns The record with loaded relations
|
|
800
|
+
* @throws ModelNotFoundException if record not found
|
|
801
|
+
*
|
|
802
|
+
* @example
|
|
803
|
+
* const post = await Post.findWithOrFail(1, 'author')
|
|
804
|
+
* const post = await Post.findWithOrFail(1, ['author', 'tags'])
|
|
805
|
+
*/
|
|
806
|
+
static findWithOrFail<T extends typeof Model, K extends RelationKey<T>>(this: T, id: TRecordFor<T>[keyof TRecordFor<T> & string], relations: K | readonly K[], key?: keyof TRecordFor<T> & string): Promise<TRecordFor<T> & RelationTypePick<T, K | readonly K[]>>;
|
|
807
|
+
/**
|
|
808
|
+
* Get the first record matching the conditions.
|
|
809
|
+
*
|
|
810
|
+
* @param where - Optional filter conditions
|
|
811
|
+
* @returns The first matching record or null
|
|
812
|
+
*
|
|
813
|
+
* @example
|
|
814
|
+
* const admin = await User.first({ role: 'admin' })
|
|
815
|
+
*/
|
|
816
|
+
static first<T extends typeof Model>(this: T, where?: WhereClauseFor<T>, queryOptions?: ModelQueryOptions): Promise<TRecordFor<T> | null>;
|
|
817
|
+
/**
|
|
818
|
+
* Start a fluent query with where conditions.
|
|
819
|
+
*
|
|
820
|
+
* Returns a QueryBuilder that is thenable, so it can be directly awaited.
|
|
821
|
+
*
|
|
822
|
+
* @example
|
|
823
|
+
* // Object form - multiple equality conditions
|
|
824
|
+
* const activeUsers = await User.where({ status: 'active' })
|
|
825
|
+
*
|
|
826
|
+
* // Field + value - equality
|
|
827
|
+
* const admins = await User.where('role', 'admin')
|
|
828
|
+
*
|
|
829
|
+
* // Field + operator + value - comparison
|
|
830
|
+
* const recent = await Post.where('views', '>', 100)
|
|
831
|
+
*
|
|
832
|
+
* // Fluent chaining
|
|
833
|
+
* const posts = await Post.where('status', 'published')
|
|
834
|
+
* .where('views', '>', 100)
|
|
835
|
+
* .orderBy('createdAt', 'desc')
|
|
836
|
+
* .limit(10)
|
|
837
|
+
* .get()
|
|
838
|
+
*/
|
|
839
|
+
static where<T extends typeof Model>(this: T, conditions: WhereClauseFor<T>): QueryBuilder<TRecordFor<T>>;
|
|
840
|
+
static where<T extends typeof Model>(this: T, field: keyof TRecordFor<T> & string, value: unknown): QueryBuilder<TRecordFor<T>>;
|
|
841
|
+
static where<T extends typeof Model>(this: T, field: keyof TRecordFor<T> & string, operator: WhereOperator, value: unknown): QueryBuilder<TRecordFor<T>>;
|
|
842
|
+
/**
|
|
843
|
+
* Start a fluent query with a WHERE NULL condition.
|
|
844
|
+
* @param field - Column to check for NULL
|
|
845
|
+
*/
|
|
846
|
+
static whereNull<T extends typeof Model>(this: T, field: keyof TRecordFor<T> & string): QueryBuilder<TRecordFor<T>>;
|
|
847
|
+
/**
|
|
848
|
+
* Start a fluent query with a WHERE NOT NULL condition.
|
|
849
|
+
* @param field - Column to check for NOT NULL
|
|
850
|
+
*/
|
|
851
|
+
static whereNotNull<T extends typeof Model>(this: T, field: keyof TRecordFor<T> & string): QueryBuilder<TRecordFor<T>>;
|
|
852
|
+
/**
|
|
853
|
+
* Start a fluent query with a WHERE IN condition.
|
|
854
|
+
* @param field - Column to check
|
|
855
|
+
* @param values - Array of values to match against
|
|
856
|
+
*/
|
|
857
|
+
static whereIn<T extends typeof Model>(this: T, field: keyof TRecordFor<T> & string, values: readonly TRecordFor<T>[keyof TRecordFor<T> & string][]): QueryBuilder<TRecordFor<T>>;
|
|
858
|
+
/**
|
|
859
|
+
* Start a fluent query with a WHERE NOT IN condition.
|
|
860
|
+
* @param field - Column to check
|
|
861
|
+
* @param values - Array of values to exclude
|
|
862
|
+
*/
|
|
863
|
+
static whereNotIn<T extends typeof Model>(this: T, field: keyof TRecordFor<T> & string, values: readonly TRecordFor<T>[keyof TRecordFor<T> & string][]): QueryBuilder<TRecordFor<T>>;
|
|
864
|
+
/**
|
|
865
|
+
* Start a fluent query with a typed field selection.
|
|
866
|
+
*
|
|
867
|
+
* @example
|
|
868
|
+
* const rows = await User.select('id', 'name')
|
|
869
|
+
* const first = await User.select('id').first()
|
|
870
|
+
*/
|
|
871
|
+
static select<T extends typeof Model, Keys extends keyof TRecordFor<T> & string>(this: T, ...fields: readonly Keys[]): QueryBuilder<TRecordFor<T>, Pick<TRecordFor<T>, Keys>>;
|
|
872
|
+
/**
|
|
873
|
+
* Start a new QueryBuilder for fluent query construction.
|
|
874
|
+
*
|
|
875
|
+
* @returns A fresh QueryBuilder instance
|
|
876
|
+
*
|
|
877
|
+
* @example
|
|
878
|
+
* const results = await User.newQuery()
|
|
879
|
+
* .where('status', 'active')
|
|
880
|
+
* .orderBy('name')
|
|
881
|
+
* .limit(10)
|
|
882
|
+
* .get()
|
|
883
|
+
*/
|
|
884
|
+
static newQuery<T extends typeof Model>(this: T, queryOptions?: ModelQueryOptions): QueryBuilder<TRecordFor<T>>;
|
|
885
|
+
/**
|
|
886
|
+
* Create a new QueryBuilder without applying any default scopes.
|
|
887
|
+
* Useful for querying soft-deleted records or bypassing global filters.
|
|
888
|
+
*
|
|
889
|
+
* @returns A fresh QueryBuilder instance with no scopes applied
|
|
890
|
+
*/
|
|
891
|
+
static newQueryWithoutScopes<T extends typeof Model>(this: T, queryOptions?: ModelQueryOptions): QueryBuilder<TRecordFor<T>>;
|
|
892
|
+
/**
|
|
893
|
+
* Apply a named query scope.
|
|
894
|
+
*
|
|
895
|
+
* @param name - The scope name defined in `static scopes`
|
|
896
|
+
* @returns A QueryBuilder with the scope applied
|
|
897
|
+
*
|
|
898
|
+
* @example
|
|
899
|
+
* const published = await Post.scope('published').get()
|
|
900
|
+
* const popularPublished = await Post.scope('published').scope('popular').get()
|
|
901
|
+
*/
|
|
902
|
+
static scope<T extends typeof Model>(this: T, name: string): QueryBuilder<TRecordFor<T>>;
|
|
903
|
+
/**
|
|
904
|
+
* Define a one-to-many relationship.
|
|
905
|
+
*
|
|
906
|
+
* @param name - Relation name (used in `with()` calls)
|
|
907
|
+
* @param related - The related model class
|
|
908
|
+
* @param foreignKey - Foreign key column on the related model
|
|
909
|
+
* @param localKey - Local key column on this model
|
|
910
|
+
*
|
|
911
|
+
* @example
|
|
912
|
+
* class User extends Model<UserRecord> {
|
|
913
|
+
* static {
|
|
914
|
+
* this.hasMany('posts', Post, 'userId', 'id')
|
|
915
|
+
* }
|
|
916
|
+
* }
|
|
917
|
+
* // Later: User.with('posts')
|
|
918
|
+
*/
|
|
919
|
+
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;
|
|
920
|
+
/**
|
|
921
|
+
* Define a many-to-one (inverse) relationship.
|
|
922
|
+
*
|
|
923
|
+
* @param name - Relation name (used in `with()` calls)
|
|
924
|
+
* @param related - The related model class
|
|
925
|
+
* @param foreignKey - Foreign key column on this model
|
|
926
|
+
* @param ownerKey - Primary key column on the related model
|
|
927
|
+
*
|
|
928
|
+
* @example
|
|
929
|
+
* class Post extends Model<PostRecord> {
|
|
930
|
+
* static {
|
|
931
|
+
* this.belongsTo('author', User, 'userId', 'id')
|
|
932
|
+
* }
|
|
933
|
+
* }
|
|
934
|
+
* // Later: Post.with('author')
|
|
935
|
+
*/
|
|
936
|
+
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;
|
|
937
|
+
/**
|
|
938
|
+
* Define a one-to-one relationship.
|
|
939
|
+
*
|
|
940
|
+
* @param name - Relation name (used in `with()` calls)
|
|
941
|
+
* @param related - The related model class
|
|
942
|
+
* @param foreignKey - Foreign key column on the related model
|
|
943
|
+
* @param localKey - Local key column on this model
|
|
944
|
+
*
|
|
945
|
+
* @example
|
|
946
|
+
* class User extends Model<UserRecord> {
|
|
947
|
+
* static {
|
|
948
|
+
* this.hasOne('profile', Profile, 'userId', 'id')
|
|
949
|
+
* }
|
|
950
|
+
* }
|
|
951
|
+
* // Later: User.with('profile')
|
|
952
|
+
*/
|
|
953
|
+
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;
|
|
954
|
+
/**
|
|
955
|
+
* Define a many-to-many relationship via a pivot table.
|
|
956
|
+
*
|
|
957
|
+
* @param name - Relation name (used in `with()` calls)
|
|
958
|
+
* @param related - The related model class
|
|
959
|
+
* @param pivotTable - The pivot/junction table (e.g., Drizzle table schema)
|
|
960
|
+
* @param foreignPivotKey - Column on pivot table referencing this model
|
|
961
|
+
* @param relatedPivotKey - Column on pivot table referencing the related model
|
|
962
|
+
* @param parentKey - Local key on this model (default: 'id')
|
|
963
|
+
* @param relatedKey - Local key on the related model (default: 'id')
|
|
964
|
+
*
|
|
965
|
+
* @example
|
|
966
|
+
* class User extends Model<UserRecord> {
|
|
967
|
+
* static {
|
|
968
|
+
* this.belongsToMany('roles', Role, userRoles, 'userId', 'roleId', 'id', 'id')
|
|
969
|
+
* }
|
|
970
|
+
* }
|
|
971
|
+
* // Later: User.with('roles')
|
|
972
|
+
*/
|
|
973
|
+
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;
|
|
974
|
+
/**
|
|
975
|
+
* Define a has-many-through relationship.
|
|
976
|
+
*
|
|
977
|
+
* @param name - Relation name (used in `with()` calls)
|
|
978
|
+
* @param related - The final related model class
|
|
979
|
+
* @param through - The intermediate model class
|
|
980
|
+
* @param firstKey - Foreign key on the intermediate model referencing this model
|
|
981
|
+
* @param secondKey - Foreign key on the related model referencing the intermediate model
|
|
982
|
+
* @param localKey - Local key on this model (default: 'id')
|
|
983
|
+
* @param secondLocalKey - Local key on the intermediate model (default: 'id')
|
|
984
|
+
*
|
|
985
|
+
* @example
|
|
986
|
+
* class Country extends Model<CountryRecord> {
|
|
987
|
+
* static {
|
|
988
|
+
* this.hasManyThrough('posts', Post, User, 'countryId', 'userId', 'id', 'id')
|
|
989
|
+
* }
|
|
990
|
+
* }
|
|
991
|
+
* // Later: Country.with('posts')
|
|
992
|
+
*/
|
|
993
|
+
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;
|
|
994
|
+
/**
|
|
995
|
+
* Map of type strings to model classes for polymorphic relationships.
|
|
996
|
+
*
|
|
997
|
+
* @example
|
|
998
|
+
* Model.morphMap = { Post, Video }
|
|
999
|
+
*/
|
|
1000
|
+
static morphMap?: Record<string, typeof Model>;
|
|
1001
|
+
/**
|
|
1002
|
+
* Define a one-to-many polymorphic relationship.
|
|
1003
|
+
*
|
|
1004
|
+
* @param name - Relation name
|
|
1005
|
+
* @param related - The related model class
|
|
1006
|
+
* @param morphName - Base name for the type/id columns (e.g. 'commentable' → commentableType + commentableId)
|
|
1007
|
+
* @param localKey - Local key on this model (default: 'id')
|
|
1008
|
+
*
|
|
1009
|
+
* @example
|
|
1010
|
+
* Post.morphMany('comments', Comment, 'commentable', 'id')
|
|
1011
|
+
*/
|
|
1012
|
+
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;
|
|
1013
|
+
/**
|
|
1014
|
+
* Define the inverse of a polymorphic relationship.
|
|
1015
|
+
*
|
|
1016
|
+
* @param name - Relation name
|
|
1017
|
+
* @param morphName - Base name for the type/id columns
|
|
1018
|
+
*
|
|
1019
|
+
* @example
|
|
1020
|
+
* Comment.morphTo('commentable', 'commentable')
|
|
1021
|
+
*/
|
|
1022
|
+
static morphTo<This extends typeof Model, Name extends RelationKeyOrString<This>>(this: This, name: Name, morphName: string): void;
|
|
1023
|
+
/**
|
|
1024
|
+
* Get records sorted by the specified order.
|
|
1025
|
+
*
|
|
1026
|
+
* @param order - Order expression(s)
|
|
1027
|
+
* @param where - Optional filter conditions
|
|
1028
|
+
* @returns Sorted array of records
|
|
1029
|
+
*
|
|
1030
|
+
* @example
|
|
1031
|
+
* // Single column ascending
|
|
1032
|
+
* await User.orderBy('createdAt')
|
|
1033
|
+
*
|
|
1034
|
+
* // Single column descending
|
|
1035
|
+
* await User.orderBy(['createdAt', 'desc'])
|
|
1036
|
+
*
|
|
1037
|
+
* // Multiple columns
|
|
1038
|
+
* await User.orderBy([['lastName', 'asc'], ['firstName', 'asc']])
|
|
1039
|
+
*
|
|
1040
|
+
* // With where clause
|
|
1041
|
+
* await User.orderBy('name', { status: 'active' })
|
|
1042
|
+
*/
|
|
1043
|
+
static orderBy<T extends typeof Model>(this: T, order: OrderByInput<TRecordFor<T>>, where?: WhereClauseFor<T>, queryOptions?: ModelQueryOptions): Promise<TRecordFor<T>[]>;
|
|
1044
|
+
/**
|
|
1045
|
+
* Get paginated records.
|
|
1046
|
+
*
|
|
1047
|
+
* @param options - Pagination options
|
|
1048
|
+
* @returns Paginated result with data and metadata
|
|
1049
|
+
*
|
|
1050
|
+
* @example
|
|
1051
|
+
* const result = await User.paginate({ page: 1, perPage: 10 })
|
|
1052
|
+
* // result.data - Array of users
|
|
1053
|
+
* // result.meta.total - Total count
|
|
1054
|
+
* // result.meta.hasMore - Whether there are more pages
|
|
1055
|
+
*
|
|
1056
|
+
* // With filtering and ordering
|
|
1057
|
+
* await User.paginate({
|
|
1058
|
+
* page: 2,
|
|
1059
|
+
* perPage: 20,
|
|
1060
|
+
* where: { status: 'active' },
|
|
1061
|
+
* orderBy: ['createdAt', 'desc']
|
|
1062
|
+
* })
|
|
1063
|
+
*/
|
|
1064
|
+
static paginate<T extends typeof Model>(this: T, options?: PaginateOptions<TRecordFor<T>>, queryOptions?: ModelQueryOptions): Promise<PaginatedResult<TRecordFor<T>>>;
|
|
1065
|
+
/**
|
|
1066
|
+
* Paginate records with eager-loaded relationships.
|
|
1067
|
+
*
|
|
1068
|
+
* @param relations - Relation name(s) to load
|
|
1069
|
+
* @param options - Pagination options
|
|
1070
|
+
* @returns Paginated result with loaded relationships
|
|
1071
|
+
*
|
|
1072
|
+
* @example
|
|
1073
|
+
* const result = await User.withPaginate('posts', { page: 1, perPage: 10 })
|
|
1074
|
+
* // result.data - Users with their posts loaded
|
|
1075
|
+
* // result.meta - Pagination metadata
|
|
1076
|
+
*/
|
|
77
1077
|
static withPaginate<T extends typeof Model, K extends RelationKey<T>>(this: T, relations: K | readonly K[], options?: PaginateOptions<TRecordFor<T>>): Promise<PaginatedResult<TRecordFor<T> & RelationTypePick<T, K | readonly K[]>>>;
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
1078
|
+
/**
|
|
1079
|
+
* Create a new record.
|
|
1080
|
+
*
|
|
1081
|
+
* @param data - Record data to insert
|
|
1082
|
+
* @returns The created record
|
|
1083
|
+
*
|
|
1084
|
+
* @example
|
|
1085
|
+
* const user = await User.create({
|
|
1086
|
+
* name: 'John Doe',
|
|
1087
|
+
* email: 'john@example.com'
|
|
1088
|
+
* })
|
|
1089
|
+
*/
|
|
1090
|
+
static create<T extends typeof Model>(this: T, data: TCreateFor<T>, writeOptions?: ModelWriteOptions): Promise<TRecordFor<T>>;
|
|
1091
|
+
/**
|
|
1092
|
+
* Update records matching the conditions.
|
|
1093
|
+
*
|
|
1094
|
+
* @param where - Filter conditions to identify records
|
|
1095
|
+
* @param data - Data to update
|
|
1096
|
+
* @returns The updated record
|
|
1097
|
+
*
|
|
1098
|
+
* @example
|
|
1099
|
+
* await User.update({ id: 1 }, { name: 'Jane Doe' })
|
|
1100
|
+
*/
|
|
1101
|
+
static update<T extends typeof Model>(this: T, where: WhereClauseFor<T>, data: Partial<TCreateFor<T>>, writeOptions?: ModelWriteOptions): Promise<TRecordFor<T>>;
|
|
1102
|
+
/**
|
|
1103
|
+
* Delete records matching the conditions.
|
|
1104
|
+
*
|
|
1105
|
+
* @param where - Filter conditions to identify records
|
|
1106
|
+
* @returns Number of deleted records or void depending on adapter
|
|
1107
|
+
*
|
|
1108
|
+
* @example
|
|
1109
|
+
* await User.delete({ id: 1 })
|
|
1110
|
+
* await User.delete({ status: 'inactive' })
|
|
1111
|
+
*/
|
|
1112
|
+
static delete<T extends typeof Model>(this: T, where: WhereClauseFor<T>, writeOptions?: ModelWriteOptions): Promise<number | PlainObject | void>;
|
|
1113
|
+
/**
|
|
1114
|
+
* Get a raw Drizzle query builder for complex queries.
|
|
1115
|
+
*
|
|
1116
|
+
* @param db - Optional Drizzle database instance
|
|
1117
|
+
* @returns Drizzle query builder starting with `select().from(table)`
|
|
1118
|
+
*
|
|
1119
|
+
* @example
|
|
1120
|
+
* // Simple query
|
|
1121
|
+
* const users = await User.query(db)
|
|
1122
|
+
* .where(eq(users.status, 'active'))
|
|
1123
|
+
* .limit(10)
|
|
1124
|
+
*
|
|
1125
|
+
* // With joins
|
|
1126
|
+
* const usersWithPosts = await User.query(db)
|
|
1127
|
+
* .leftJoin(posts, eq(users.id, posts.userId))
|
|
1128
|
+
*/
|
|
1129
|
+
static query<TDatabase extends {
|
|
1130
|
+
select: (...args: any[]) => any;
|
|
1131
|
+
} = {
|
|
1132
|
+
select: (...args: any[]) => any;
|
|
1133
|
+
}>(// eslint-disable-line @typescript-eslint/no-explicit-any
|
|
1134
|
+
this: typeof Model, db?: TDatabase): SelectFrom<TDatabase>;
|
|
1135
|
+
/**
|
|
1136
|
+
* Eager-load relationships on records.
|
|
1137
|
+
*
|
|
1138
|
+
* @param relations - Relation name(s) to load
|
|
1139
|
+
* @param where - Optional filter conditions
|
|
1140
|
+
* @returns Records with loaded relationships
|
|
1141
|
+
*
|
|
1142
|
+
* @example
|
|
1143
|
+
* // Single relation
|
|
1144
|
+
* const usersWithPosts = await User.with('posts')
|
|
1145
|
+
*
|
|
1146
|
+
* // Multiple relations
|
|
1147
|
+
* const usersWithAll = await User.with(['posts', 'comments'])
|
|
1148
|
+
*
|
|
1149
|
+
* // With filtering
|
|
1150
|
+
* const activeUsersWithPosts = await User.with('posts', { status: 'active' })
|
|
1151
|
+
*/
|
|
81
1152
|
static with<T extends typeof Model, K extends RelationKey<T>>(this: T, relations: K | readonly K[], where?: WhereClauseFor<T>): Promise<Array<TRecordFor<T> & RelationTypePick<T, K | readonly K[]>>>;
|
|
82
|
-
|
|
1153
|
+
/** @internal Used by QueryBuilder for eager loading. */
|
|
1154
|
+
static loadRelationInto<T extends typeof Model>(this: T, records: Array<PlainObject>, relationName: string): Promise<void>;
|
|
83
1155
|
protected static loadHasMany(records: Array<PlainObject>, definition: HasManyRelationDefinition): Promise<void>;
|
|
1156
|
+
protected static loadHasOne(records: Array<PlainObject>, definition: HasOneRelationDefinition): Promise<void>;
|
|
84
1157
|
protected static loadBelongsTo(records: Array<PlainObject>, definition: BelongsToRelationDefinition): Promise<void>;
|
|
1158
|
+
protected static loadBelongsToMany(records: Array<PlainObject>, definition: BelongsToManyRelationDefinition): Promise<void>;
|
|
1159
|
+
protected static loadHasManyThrough(records: Array<PlainObject>, definition: HasManyThroughRelationDefinition): Promise<void>;
|
|
1160
|
+
protected static loadMorphMany(records: Array<PlainObject>, definition: MorphManyRelationDefinition): Promise<void>;
|
|
1161
|
+
protected static loadMorphTo(records: Array<PlainObject>, definition: MorphToRelationDefinition): Promise<void>;
|
|
85
1162
|
}
|
|
86
1163
|
type TRecordFor<T extends typeof Model> = T extends {
|
|
87
1164
|
recordType: infer R;
|
|
88
1165
|
} ? R extends PlainObject ? R : PlainObject : PlainObject;
|
|
1166
|
+
type TCreateFor<T extends typeof Model> = T extends {
|
|
1167
|
+
createType: infer R;
|
|
1168
|
+
} ? R extends PlainObject ? R : PlainObject : PlainObject;
|
|
89
1169
|
type WhereClauseFor<T extends typeof Model> = WhereClause<TRecordFor<T>>;
|
|
1170
|
+
type FieldFor<T extends typeof Model> = keyof TRecordFor<T> & string;
|
|
90
1171
|
type RelationTypesFor<T extends typeof Model> = T extends {
|
|
91
1172
|
relationTypes: infer R;
|
|
92
1173
|
} ? R extends RelationShape ? R : {} : {};
|
|
@@ -96,26 +1177,177 @@ type RelationNameUnion<Names> = Names extends readonly (infer Items)[] ? Items :
|
|
|
96
1177
|
type RelationTypePick<T extends typeof Model, Names> = RelationNameUnion<Names> extends infer Keys ? Keys extends string ? {
|
|
97
1178
|
[K in Keys & keyof RelationTypesFor<T>]: RelationTypesFor<T>[K];
|
|
98
1179
|
} : {} : {};
|
|
1180
|
+
interface TransactionModelScope<T extends typeof Model> {
|
|
1181
|
+
readonly trx: TransactionHandle;
|
|
1182
|
+
all(): Promise<TRecordFor<T>[]>;
|
|
1183
|
+
find(id: unknown): Promise<TRecordFor<T> | null>;
|
|
1184
|
+
findOrFail(id: unknown): Promise<TRecordFor<T>>;
|
|
1185
|
+
first(where?: WhereClauseFor<T>): Promise<TRecordFor<T> | null>;
|
|
1186
|
+
where(conditions: WhereClauseFor<T>): QueryBuilder<TRecordFor<T>>;
|
|
1187
|
+
where(field: FieldFor<T>, value: unknown): QueryBuilder<TRecordFor<T>>;
|
|
1188
|
+
where(field: FieldFor<T>, operator: WhereOperator, value: unknown): QueryBuilder<TRecordFor<T>>;
|
|
1189
|
+
newQuery(): QueryBuilder<TRecordFor<T>>;
|
|
1190
|
+
create(data: TCreateFor<T>): Promise<TRecordFor<T>>;
|
|
1191
|
+
update(where: WhereClauseFor<T>, data: Partial<TCreateFor<T>>): Promise<TRecordFor<T>>;
|
|
1192
|
+
delete(where: WhereClauseFor<T>): Promise<number | PlainObject | void>;
|
|
1193
|
+
paginate(options?: PaginateOptions<TRecordFor<T>>): Promise<PaginatedResult<TRecordFor<T>>>;
|
|
1194
|
+
}
|
|
99
1195
|
interface BaseRelationDefinition {
|
|
100
|
-
type: 'hasMany' | 'belongsTo';
|
|
1196
|
+
type: 'hasMany' | 'hasOne' | 'belongsTo' | 'belongsToMany' | 'hasManyThrough' | 'morphMany' | 'morphTo';
|
|
101
1197
|
name: string;
|
|
102
|
-
related: typeof Model;
|
|
1198
|
+
related: typeof Model | (() => typeof Model | Promise<typeof Model>);
|
|
103
1199
|
}
|
|
104
1200
|
interface HasManyRelationDefinition extends BaseRelationDefinition {
|
|
105
1201
|
type: 'hasMany';
|
|
106
1202
|
foreignKey: string;
|
|
107
1203
|
localKey: string;
|
|
108
1204
|
}
|
|
1205
|
+
interface HasOneRelationDefinition extends BaseRelationDefinition {
|
|
1206
|
+
type: 'hasOne';
|
|
1207
|
+
foreignKey: string;
|
|
1208
|
+
localKey: string;
|
|
1209
|
+
}
|
|
109
1210
|
interface BelongsToRelationDefinition extends BaseRelationDefinition {
|
|
110
1211
|
type: 'belongsTo';
|
|
111
1212
|
foreignKey: string;
|
|
112
1213
|
ownerKey: string;
|
|
113
1214
|
}
|
|
114
|
-
|
|
1215
|
+
interface BelongsToManyRelationDefinition extends BaseRelationDefinition {
|
|
1216
|
+
type: 'belongsToMany';
|
|
1217
|
+
pivotTable: unknown;
|
|
1218
|
+
foreignPivotKey: string;
|
|
1219
|
+
relatedPivotKey: string;
|
|
1220
|
+
parentKey: string;
|
|
1221
|
+
relatedKey: string;
|
|
1222
|
+
}
|
|
1223
|
+
interface HasManyThroughRelationDefinition extends BaseRelationDefinition {
|
|
1224
|
+
type: 'hasManyThrough';
|
|
1225
|
+
through: typeof Model | (() => typeof Model | Promise<typeof Model>);
|
|
1226
|
+
firstKey: string;
|
|
1227
|
+
secondKey: string;
|
|
1228
|
+
localKey: string;
|
|
1229
|
+
secondLocalKey: string;
|
|
1230
|
+
}
|
|
1231
|
+
type RelationDefinition = HasManyRelationDefinition | HasOneRelationDefinition | BelongsToRelationDefinition | BelongsToManyRelationDefinition | HasManyThroughRelationDefinition | MorphManyRelationDefinition | MorphToRelationDefinition;
|
|
1232
|
+
interface MorphManyRelationDefinition extends BaseRelationDefinition {
|
|
1233
|
+
type: 'morphMany';
|
|
1234
|
+
morphName: string;
|
|
1235
|
+
localKey: string;
|
|
1236
|
+
}
|
|
1237
|
+
interface MorphToRelationDefinition {
|
|
1238
|
+
type: 'morphTo';
|
|
1239
|
+
name: string;
|
|
1240
|
+
related: undefined;
|
|
1241
|
+
morphName: string;
|
|
1242
|
+
}
|
|
1243
|
+
/** Type for hasMany relation results (array of related records). */
|
|
115
1244
|
type HasManyRelationResult<T extends typeof Model> = Array<TRecordFor<T>>;
|
|
1245
|
+
/** Type for belongsTo relation results (single record or null). */
|
|
116
1246
|
type BelongsToRelationResult<T extends typeof Model> = TRecordFor<T> | null;
|
|
1247
|
+
/** Utility type for hasMany relation data shape. */
|
|
117
1248
|
type HasManyRecord<TRecord extends PlainObject> = TRecord[];
|
|
1249
|
+
/** Utility type for belongsTo relation data shape. */
|
|
118
1250
|
type BelongsToRecord<TRecord extends PlainObject> = TRecord | null;
|
|
1251
|
+
/** Type for hasOne relation results (single record or null). */
|
|
1252
|
+
type HasOneRelationResult<T extends typeof Model> = TRecordFor<T> | null;
|
|
1253
|
+
/** Type for belongsToMany relation results (array of related records). */
|
|
1254
|
+
type BelongsToManyRelationResult<T extends typeof Model> = Array<TRecordFor<T>>;
|
|
1255
|
+
/** Type for hasManyThrough relation results (array of related records). */
|
|
1256
|
+
type HasManyThroughRelationResult<T extends typeof Model> = Array<TRecordFor<T>>;
|
|
1257
|
+
/** Utility type for hasOne relation data shape. */
|
|
1258
|
+
type HasOneRecord<TRecord extends PlainObject> = TRecord | null;
|
|
1259
|
+
/** Utility type for belongsToMany relation data shape. */
|
|
1260
|
+
type BelongsToManyRecord<TRecord extends PlainObject> = TRecord[];
|
|
1261
|
+
/** Utility type for hasManyThrough relation data shape. */
|
|
1262
|
+
type HasManyThroughRecord<TRecord extends PlainObject> = TRecord[];
|
|
1263
|
+
/** Type for morphMany relation results (array of related records). */
|
|
1264
|
+
type MorphManyRelationResult<T extends typeof Model> = Array<TRecordFor<T>>;
|
|
1265
|
+
/** Utility type for morphMany relation data shape. */
|
|
1266
|
+
type MorphManyRecord<TRecord extends PlainObject> = TRecord[];
|
|
1267
|
+
/** Type for morphTo relation results (single record or null). */
|
|
1268
|
+
type MorphToRelationResult = PlainObject | null;
|
|
1269
|
+
/** Utility type for morphTo relation data shape. */
|
|
1270
|
+
type MorphToRecord = PlainObject | null;
|
|
1271
|
+
/** Utility type: model record with specified relations merged. */
|
|
1272
|
+
type WithRelations<T extends typeof Model, K extends RelationKey<T> | readonly RelationKey<T>[]> = TRecordFor<T> & RelationTypePick<T, K>;
|
|
1273
|
+
type ModelClassWithTable<TTable extends TableShape, TBase extends typeof Model = typeof Model, TCreate extends PlainObject = InferModelInsert<TTable> & TCreateFor<TBase>> = TBase & {
|
|
1274
|
+
readonly table: TTable;
|
|
1275
|
+
readonly recordType: InferModelRecord<TTable>;
|
|
1276
|
+
readonly createType: TCreate;
|
|
1277
|
+
};
|
|
1278
|
+
/**
|
|
1279
|
+
* Create a table-backed model base class from a Drizzle table.
|
|
1280
|
+
*
|
|
1281
|
+
* @example
|
|
1282
|
+
* export class Post extends defineModel(posts) {}
|
|
1283
|
+
* export class User extends defineModel(users, { base: AuthenticatableModel }) {}
|
|
1284
|
+
*/
|
|
1285
|
+
declare function defineModel<TTable extends TableShape, TBase extends typeof Model = typeof Model, TCreate extends PlainObject = InferModelInsert<TTable> & TCreateFor<TBase>>(table: TTable, options?: {
|
|
1286
|
+
base?: TBase;
|
|
1287
|
+
createType?: TCreate;
|
|
1288
|
+
}): ModelClassWithTable<TTable, TBase, TCreate>;
|
|
1289
|
+
|
|
1290
|
+
/**
|
|
1291
|
+
* Exception thrown when a model is not found via findOrFail.
|
|
1292
|
+
*
|
|
1293
|
+
* Carries a `statusCode` of 404 so that framework exception handlers
|
|
1294
|
+
* can render it as a proper HTTP 404 without coupling to the ORM package.
|
|
1295
|
+
*/
|
|
1296
|
+
declare class ModelNotFoundException extends Error {
|
|
1297
|
+
readonly statusCode = 404;
|
|
1298
|
+
readonly modelName: string;
|
|
1299
|
+
readonly modelId: unknown;
|
|
1300
|
+
constructor(modelName: string, id: unknown, key?: string);
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
/**
|
|
1304
|
+
* Interface describing the static methods added by the SoftDeletes mixin.
|
|
1305
|
+
*/
|
|
1306
|
+
interface SoftDeletesStatic {
|
|
1307
|
+
/** Column name used for tracking soft deletion timestamp. */
|
|
1308
|
+
deletedAtColumn: string;
|
|
1309
|
+
/** Default scope that excludes soft-deleted records. */
|
|
1310
|
+
defaultScope: (q: QueryBuilder<any>) => QueryBuilder<any>;
|
|
1311
|
+
/** Start a query that includes soft-deleted records. */
|
|
1312
|
+
withTrashed(): QueryBuilder<PlainObject>;
|
|
1313
|
+
/** Start a query that returns only soft-deleted records. */
|
|
1314
|
+
onlyTrashed(): QueryBuilder<PlainObject>;
|
|
1315
|
+
/** Restore soft-deleted records by setting deletedAt back to null. */
|
|
1316
|
+
restore(where: Partial<Record<string, unknown>>): Promise<PlainObject>;
|
|
1317
|
+
/** Permanently delete records from the database, bypassing soft delete. */
|
|
1318
|
+
forceDelete(where: Partial<Record<string, unknown>>): Promise<number | PlainObject | void>;
|
|
1319
|
+
}
|
|
1320
|
+
/**
|
|
1321
|
+
* Mixin that adds soft delete behavior to a Model.
|
|
1322
|
+
*
|
|
1323
|
+
* When applied, `delete()` sets a `deletedAt` timestamp instead of removing the
|
|
1324
|
+
* record from the database. All default queries automatically exclude soft-deleted
|
|
1325
|
+
* records via a global scope named 'softDelete'.
|
|
1326
|
+
*
|
|
1327
|
+
* @example
|
|
1328
|
+
* class Post extends SoftDeletes(Model)<PostRecord> {
|
|
1329
|
+
* static table = posts
|
|
1330
|
+
* }
|
|
1331
|
+
*
|
|
1332
|
+
* // Soft delete a record (sets deletedAt)
|
|
1333
|
+
* await Post.delete({ id: 1 })
|
|
1334
|
+
*
|
|
1335
|
+
* // Query only non-deleted records (default behavior)
|
|
1336
|
+
* const posts = await Post.all()
|
|
1337
|
+
*
|
|
1338
|
+
* // Include soft-deleted records
|
|
1339
|
+
* const allPosts = await Post.withTrashed().get()
|
|
1340
|
+
*
|
|
1341
|
+
* // Query only soft-deleted records
|
|
1342
|
+
* const trashed = await Post.onlyTrashed().get()
|
|
1343
|
+
*
|
|
1344
|
+
* // Restore a soft-deleted record
|
|
1345
|
+
* await Post.restore({ id: 1 })
|
|
1346
|
+
*
|
|
1347
|
+
* // Permanently delete a record
|
|
1348
|
+
* await Post.forceDelete({ id: 1 })
|
|
1349
|
+
*/
|
|
1350
|
+
declare function SoftDeletes<TBase extends typeof Model>(Base: TBase): TBase & SoftDeletesStatic;
|
|
119
1351
|
|
|
120
1352
|
type DrizzleLikeSelect = {
|
|
121
1353
|
where?: (clause: unknown) => DrizzleLikeSelect;
|
|
@@ -150,16 +1382,38 @@ type DrizzleDatabase = {
|
|
|
150
1382
|
insert(table: unknown): DrizzleLikeInsert;
|
|
151
1383
|
update?(table: unknown): DrizzleLikeUpdate;
|
|
152
1384
|
delete?(table: unknown): DrizzleLikeDelete;
|
|
1385
|
+
transaction?<TResult>(callback: (trx: unknown) => Promise<TResult>): Promise<TResult>;
|
|
153
1386
|
};
|
|
154
|
-
declare const DrizzleAdapter:
|
|
1387
|
+
declare const DrizzleAdapter: ORMAdapterAdvanced & {
|
|
155
1388
|
configure(db: DrizzleDatabase): void;
|
|
1389
|
+
getDatabase<TDatabase extends DrizzleDatabase = DrizzleDatabase>(): TDatabase;
|
|
156
1390
|
};
|
|
157
1391
|
|
|
158
|
-
|
|
1392
|
+
/**
|
|
1393
|
+
* Translates an array of QueryBuilder WhereConditions into a single
|
|
1394
|
+
* Drizzle ORM condition expression.
|
|
1395
|
+
*
|
|
1396
|
+
* The top-level conditions are joined with AND. OR conditions are
|
|
1397
|
+
* represented as GroupCondition nodes with `boolean: 'or'`.
|
|
1398
|
+
*
|
|
1399
|
+
* When an OR group is encountered, it creates:
|
|
1400
|
+
* AND(previous_conditions, OR(previous_and_block, or_conditions))
|
|
1401
|
+
*
|
|
1402
|
+
* This matches the typical SQL builder behavior where:
|
|
1403
|
+
* .where('a', 1).where('b', 2).orWhere('c', 3)
|
|
1404
|
+
* produces: (a = 1 AND b = 2) OR (c = 3)
|
|
1405
|
+
*
|
|
1406
|
+
* @param table - The Drizzle table object
|
|
1407
|
+
* @param conditions - Array of WhereCondition objects from QueryBuilder
|
|
1408
|
+
* @returns A Drizzle SQL condition or undefined if no conditions
|
|
1409
|
+
*/
|
|
1410
|
+
declare function buildDrizzleConditions(table: unknown, conditions: WhereCondition[]): SQL | undefined;
|
|
1411
|
+
|
|
1412
|
+
type ConnectionResolver$2 = string | (() => string | undefined);
|
|
159
1413
|
interface PostgresDatabaseOptions<TSchema extends Record<string, unknown>> {
|
|
160
1414
|
schema: TSchema;
|
|
161
1415
|
migrationsFolder: string | URL;
|
|
162
|
-
connectionString?: ConnectionResolver;
|
|
1416
|
+
connectionString?: ConnectionResolver$2;
|
|
163
1417
|
clientOptions?: postgres.Options<Record<string, never>>;
|
|
164
1418
|
seedersFolder?: string | URL;
|
|
165
1419
|
}
|
|
@@ -172,6 +1426,41 @@ interface PostgresDatabase<TSchema extends Record<string, unknown>> {
|
|
|
172
1426
|
}
|
|
173
1427
|
declare function createPostgresDatabase<TSchema extends Record<string, unknown>>(options: PostgresDatabaseOptions<TSchema>): PostgresDatabase<TSchema>;
|
|
174
1428
|
|
|
1429
|
+
type ConnectionResolver$1 = string | (() => string | undefined);
|
|
1430
|
+
type MySqlConnectionOptions = Record<string, unknown>;
|
|
1431
|
+
interface MySqlDatabaseOptions<TSchema extends Record<string, unknown>> {
|
|
1432
|
+
schema: TSchema;
|
|
1433
|
+
migrationsFolder: string | URL;
|
|
1434
|
+
connectionString?: ConnectionResolver$1;
|
|
1435
|
+
clientOptions?: MySqlConnectionOptions;
|
|
1436
|
+
seedersFolder?: string | URL;
|
|
1437
|
+
}
|
|
1438
|
+
interface MySqlDatabase<TSchema extends Record<string, unknown>> {
|
|
1439
|
+
getDatabase(): Promise<MySql2Database<TSchema>>;
|
|
1440
|
+
migrateDatabase(): Promise<void>;
|
|
1441
|
+
closeDatabase(): Promise<void>;
|
|
1442
|
+
configureOrm(): Promise<void>;
|
|
1443
|
+
seedDatabase(): Promise<void>;
|
|
1444
|
+
}
|
|
1445
|
+
declare function createMySqlDatabase<TSchema extends Record<string, unknown>>(options: MySqlDatabaseOptions<TSchema>): MySqlDatabase<TSchema>;
|
|
1446
|
+
|
|
1447
|
+
type ConnectionResolver = string | (() => string | undefined);
|
|
1448
|
+
interface SqliteDatabaseOptions<TSchema extends Record<string, unknown>> {
|
|
1449
|
+
schema: TSchema;
|
|
1450
|
+
migrationsFolder: string | URL;
|
|
1451
|
+
/** Path to the SQLite database file. Defaults to `./data/guren.db`. */
|
|
1452
|
+
filename?: ConnectionResolver;
|
|
1453
|
+
seedersFolder?: string | URL;
|
|
1454
|
+
}
|
|
1455
|
+
interface SqliteDatabase<TSchema extends Record<string, unknown>> {
|
|
1456
|
+
getDatabase(): Promise<unknown>;
|
|
1457
|
+
migrateDatabase(): Promise<void>;
|
|
1458
|
+
closeDatabase(): Promise<void>;
|
|
1459
|
+
configureOrm(): Promise<void>;
|
|
1460
|
+
seedDatabase(): Promise<void>;
|
|
1461
|
+
}
|
|
1462
|
+
declare function createSqliteDatabase<TSchema extends Record<string, unknown>>(options: SqliteDatabaseOptions<TSchema>): SqliteDatabase<TSchema>;
|
|
1463
|
+
|
|
175
1464
|
interface SeederContext<TSchema extends Record<string, unknown>> {
|
|
176
1465
|
db: PostgresJsDatabase<TSchema>;
|
|
177
1466
|
}
|
|
@@ -180,4 +1469,18 @@ declare function loadSeeders<TSchema extends Record<string, unknown>>(directory:
|
|
|
180
1469
|
declare function runSeeders<TSchema extends Record<string, unknown>>(db: PostgresJsDatabase<TSchema>, directory: string | URL): Promise<void>;
|
|
181
1470
|
declare function defineSeeder<TSchema extends Record<string, unknown>>(handler: SeederHandler<TSchema>): SeederHandler<TSchema>;
|
|
182
1471
|
|
|
183
|
-
|
|
1472
|
+
/**
|
|
1473
|
+
* Serialize a model record for API/JSON output.
|
|
1474
|
+
*
|
|
1475
|
+
* Applies hidden/visible filtering, casts, accessors, and appends.
|
|
1476
|
+
*/
|
|
1477
|
+
declare function serializeRecord(record: PlainObject, options: {
|
|
1478
|
+
hidden?: string[];
|
|
1479
|
+
visible?: string[];
|
|
1480
|
+
appends?: string[];
|
|
1481
|
+
accessors?: AccessorDefinitions;
|
|
1482
|
+
}): PlainObject;
|
|
1483
|
+
/** Serialize an array of records. */
|
|
1484
|
+
declare function serializeRecords(records: PlainObject[], options: Parameters<typeof serializeRecord>[1]): PlainObject[];
|
|
1485
|
+
|
|
1486
|
+
export { type AccessorDefinitions, type AccessorFn, type BelongsToManyRecord, type BelongsToManyRelationResult, type BelongsToRecord, type BelongsToRelationResult, type CastType, DrizzleAdapter, type FindManyOptions, GlobalScopeRegistry, type GroupCondition, type HasManyRecord, type HasManyRelationResult, type HasManyThroughRecord, type HasManyThroughRelationResult, type HasOneRecord, type HasOneRelationResult, type HookCallback, type HookName, type InferModelInsert, type InferModelRecord, Model, type ModelHooks, ModelNotFoundException, type ModelObserver, type ModelObserverConstructor, type MorphManyRecord, type MorphManyRelationResult, type MorphToRecord, type MorphToRelationResult, type MutatorDefinitions, type MutatorFn, type MySqlDatabase, type MySqlDatabaseOptions, type ORMAdapter, type ORMAdapterAdvanced, type OrderByClause, type OrderByInput, type OrderDefinition, type OrderDirection, type PaginateOptions, type PaginatedResult, type PaginationMeta, type PlainObject, type PostgresDatabase, type PostgresDatabaseOptions, QueryBuilder, type QueryBuilderOptions, type ScopeFunction, type SeederContext, type SeederHandler, type SimpleCondition, SoftDeletes, type SoftDeletesStatic, type SqliteDatabase, type SqliteDatabaseOptions, type TransactionHandle, type TransactionModelScope, type WhereClause, type WhereCondition, type WhereOperator, type WithRelations, applyAccessors, applyMutators, buildDrizzleConditions, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, executeHook, executeObservers, loadSeeders, runSeeders, serializeRecord, serializeRecords };
|