@orieljs/database 0.1.0-alpha.1

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.
@@ -0,0 +1,2447 @@
1
+ import { OrielError, ModelNotFoundError as ModelNotFoundError$1, DriverName, DatabaseConnection, Row, QueryBuilder, Operator, DatabaseManager, Token, ModelInstance, Application, ConsoleKernel, RouteModelResolver, Class } from '@orieljs/contracts';
2
+ import { SqliteDatabase, SqliteStatement, Dialect, RawBuilder, Kysely, CompiledQuery, QueryResult } from 'kysely';
3
+ import { Collection, LazyCollection } from '@orieljs/collections';
4
+ import * as _orieljs_support from '@orieljs/support';
5
+ import { ServiceProvider } from '@orieljs/support';
6
+
7
+ /** Thrown by findOrFail()/firstOrFail() and route model binding. Renders as 404. */
8
+ declare class ModelNotFoundError extends Error implements ModelNotFoundError$1 {
9
+ readonly model: string;
10
+ readonly ids: unknown[];
11
+ readonly kind: "ModelNotFound";
12
+ readonly status = 404;
13
+ readonly name = "ModelNotFoundError";
14
+ constructor(model: string, ids?: unknown[]);
15
+ }
16
+ /**
17
+ * Base of every other Database error: a server error (bug or infrastructure failure). The exception handler reports
18
+ * it and renders a 500, hiding the message unless app.debug is on.
19
+ */
20
+ declare abstract class DatabaseError extends Error implements OrielError {
21
+ readonly kind: "Server";
22
+ readonly status = 500;
23
+ }
24
+ /** A failed SQL statement, with the SQL and connection in the message (Laravel's QueryException). */
25
+ declare class QueryError extends DatabaseError {
26
+ readonly connectionName: string;
27
+ readonly sql: string;
28
+ readonly bindings: readonly unknown[];
29
+ readonly name = "QueryError";
30
+ constructor(connectionName: string, sql: string, bindings: readonly unknown[], cause: unknown);
31
+ }
32
+ /** Mass assignment on a model whose `guarded` is ['*'] (Laravel's MassAssignmentException). */
33
+ declare class MassAssignmentError extends DatabaseError {
34
+ readonly model: string;
35
+ readonly attribute: string;
36
+ readonly name = "MassAssignmentError";
37
+ constructor(model: string, attribute: string);
38
+ }
39
+ declare class RelationNotFoundError extends DatabaseError {
40
+ readonly model: string;
41
+ readonly relation: string;
42
+ readonly name = "RelationNotFoundError";
43
+ constructor(model: string, relation: string);
44
+ }
45
+ declare class RelationNotLoadedError extends DatabaseError {
46
+ readonly model: string;
47
+ readonly relation: string;
48
+ readonly name = "RelationNotLoadedError";
49
+ constructor(model: string, relation: string);
50
+ }
51
+ declare class InvalidCastError extends DatabaseError {
52
+ readonly model: string;
53
+ readonly column: string;
54
+ readonly castType: string;
55
+ readonly name = "InvalidCastError";
56
+ constructor(model: string, column: string, castType: string);
57
+ }
58
+ /** Bad or missing database configuration (unknown connection, unsupported driver). */
59
+ declare class DatabaseConfigError extends DatabaseError {
60
+ readonly name = "DatabaseConfigError";
61
+ }
62
+ /** Thrown when an operation needs a feature the model hasn't enabled (e.g. restore() without soft deletes). */
63
+ declare class LogicError extends DatabaseError {
64
+ readonly name = "LogicError";
65
+ }
66
+
67
+ /** True when running on Bun (bun:sqlite is used instead of better-sqlite3). */
68
+ declare const isBun: () => boolean;
69
+
70
+ /** The part of bun:sqlite's Statement this adapter uses. */
71
+ interface BunStatement {
72
+ readonly columnNames: string[];
73
+ all(...parameters: unknown[]): unknown[];
74
+ run(...parameters: unknown[]): {
75
+ changes: number | bigint;
76
+ lastInsertRowid: number | bigint;
77
+ };
78
+ iterate(...parameters: unknown[]): IterableIterator<unknown>;
79
+ }
80
+ /** The part of bun:sqlite's Database this adapter uses. */
81
+ interface BunDatabase {
82
+ prepare(sql: string): BunStatement;
83
+ close(): void;
84
+ }
85
+ /** Adapts bun:sqlite to the better-sqlite3 shape Kysely's SqliteDialect expects. */
86
+ declare class BunSqliteDatabase implements SqliteDatabase {
87
+ private readonly database;
88
+ constructor(database: BunDatabase);
89
+ close(): void;
90
+ prepare(sql: string): SqliteStatement;
91
+ }
92
+ /** Opens a SQLite database with bun:sqlite on Bun and better-sqlite3 on Node. */
93
+ declare function openSqlite(filename: string): Promise<SqliteDatabase>;
94
+
95
+ /** One entry of `config('database.connections')`, in Laravel's config/database.php shape. */
96
+ interface ConnectionConfig {
97
+ driver: DriverName;
98
+ url?: string;
99
+ database?: string;
100
+ host?: string;
101
+ port?: string | number;
102
+ username?: string;
103
+ password?: string;
104
+ charset?: string;
105
+ collation?: string;
106
+ /** pgsql only. */
107
+ search_path?: string;
108
+ /** sqlite only. Defaults to true, like Laravel's DB_FOREIGN_KEYS. */
109
+ foreign_key_constraints?: boolean;
110
+ pool?: {
111
+ max?: number;
112
+ };
113
+ }
114
+ /**
115
+ * The mysql2 pool options for a connection. When `url` is set its parts (host, port, user, password,
116
+ * database) win over the individual keys, like Laravel; keys it leaves out fall back to the config.
117
+ */
118
+ declare function mysqlPoolOptions(config: ConnectionConfig): Record<string, unknown>;
119
+ /** Builds the Kysely dialect for a connection. Driver modules are imported lazily, on the first query. */
120
+ declare function createDialect(config: ConnectionConfig): Dialect;
121
+
122
+ /** A raw SQL fragment, never escaped: DB.raw('count(*) as total'). Use `?` placeholders for values. */
123
+ declare class Expression {
124
+ readonly value: string;
125
+ readonly bindings: readonly unknown[];
126
+ constructor(value: string, bindings?: readonly unknown[]);
127
+ toString(): string;
128
+ }
129
+ declare const raw: (value: string, bindings?: readonly unknown[]) => Expression;
130
+ /**
131
+ * Turns `select * from users where id = ?` + bindings into a Kysely RawBuilder, so each dialect gets its own
132
+ * placeholders ($1 on Postgres). `?` inside quoted strings isn't special-cased: bind such values instead.
133
+ */
134
+ declare function rawWithBindings(query: string, bindings?: readonly unknown[]): RawBuilder<unknown>;
135
+
136
+ type ColumnType = 'bigInteger' | 'integer' | 'mediumInteger' | 'smallInteger' | 'tinyInteger' | 'string' | 'char' | 'text' | 'mediumText' | 'longText' | 'boolean' | 'date' | 'dateTime' | 'time' | 'timestamp' | 'decimal' | 'float' | 'double' | 'json' | 'jsonb' | 'uuid' | 'ulid' | 'binary' | 'enum';
137
+ /** Everything a column definition can carry. Grammars read these; the fluent methods set them. */
138
+ interface ColumnAttributes {
139
+ type: ColumnType;
140
+ name: string;
141
+ length?: number;
142
+ total?: number;
143
+ places?: number;
144
+ precision?: number;
145
+ allowed?: readonly string[];
146
+ autoIncrement?: boolean;
147
+ unsigned?: boolean;
148
+ nullable?: boolean;
149
+ default?: unknown;
150
+ primary?: boolean;
151
+ unique?: boolean | string;
152
+ index?: boolean | string;
153
+ comment?: string;
154
+ after?: string;
155
+ first?: boolean;
156
+ onUpdate?: Expression;
157
+ }
158
+ /** A column in a Blueprint, with Laravel's fluent modifiers: t.string('email').nullable().unique(). */
159
+ declare class ColumnDefinition {
160
+ readonly attributes: ColumnAttributes;
161
+ constructor(attributes: ColumnAttributes);
162
+ get name(): string;
163
+ /** Allows NULL (the default is NOT NULL). */
164
+ nullable(value?: boolean): this;
165
+ /** A default value. Strings, numbers and booleans are quoted as literals; DB.raw() passes through unescaped. */
166
+ default(value: unknown): this;
167
+ unsigned(): this;
168
+ autoIncrement(): this;
169
+ primary(value?: boolean): this;
170
+ /** Adds a unique index on this column, optionally with a name. */
171
+ unique(name?: string): this;
172
+ /** Adds a plain index on this column, optionally with a name. */
173
+ index(name?: string): this;
174
+ /** Column comment (MySQL and Postgres; ignored on SQLite). */
175
+ comment(text: string): this;
176
+ /** MySQL only: place the column after another one. Ignored elsewhere. */
177
+ after(column: string): this;
178
+ /** MySQL only: place the column first. Ignored elsewhere. */
179
+ first(): this;
180
+ /** default CURRENT_TIMESTAMP. */
181
+ useCurrent(): this;
182
+ /** MySQL only: on update CURRENT_TIMESTAMP. */
183
+ useCurrentOnUpdate(): this;
184
+ }
185
+
186
+ type ReferentialAction = 'cascade' | 'restrict' | 'set null' | 'no action' | 'set default';
187
+ /** t.foreign('user_id').references('id').on('users').cascadeOnDelete() */
188
+ declare class ForeignKeyDefinition {
189
+ readonly columns: string[];
190
+ indexName: string;
191
+ referencedColumns: string[];
192
+ referencedTable: string | undefined;
193
+ deleteAction: ReferentialAction | undefined;
194
+ updateAction: ReferentialAction | undefined;
195
+ constructor(columns: string[], indexName: string);
196
+ references(columns: string | string[]): this;
197
+ on(table: string): this;
198
+ onDelete(action: ReferentialAction): this;
199
+ onUpdate(action: ReferentialAction): this;
200
+ cascadeOnDelete(): this;
201
+ restrictOnDelete(): this;
202
+ nullOnDelete(): this;
203
+ noActionOnDelete(): this;
204
+ cascadeOnUpdate(): this;
205
+ restrictOnUpdate(): this;
206
+ nullOnUpdate(): this;
207
+ noActionOnUpdate(): this;
208
+ /** Overrides the constraint name (default: {table}_{columns}_foreign). */
209
+ name(name: string): this;
210
+ }
211
+ /** foreignId('user_id').constrained(): the column plus, on demand, its foreign key. */
212
+ declare class ForeignIdColumnDefinition extends ColumnDefinition {
213
+ private readonly addForeign;
214
+ constructor(attributes: ColumnAttributes, addForeign: (column: string) => ForeignKeyDefinition);
215
+ /**
216
+ * A foreign key to `table` (default: the column name without `_id`, pluralized: user_id → users) on `column`.
217
+ * Chain cascadeOnDelete() etc. on the returned definition.
218
+ */
219
+ constrained(table?: string, column?: string, indexName?: string): ForeignKeyDefinition;
220
+ /** A foreign key on this column to `column`; chain on('table'). */
221
+ references(column: string): ForeignKeyDefinition;
222
+ }
223
+
224
+ type IndexType = 'primary' | 'unique' | 'index';
225
+ type BlueprintCommand = {
226
+ name: 'create';
227
+ } | {
228
+ name: IndexType;
229
+ columns: string[];
230
+ index: string;
231
+ } | {
232
+ name: 'foreign';
233
+ foreign: ForeignKeyDefinition;
234
+ } | {
235
+ name: 'dropColumn';
236
+ columns: string[];
237
+ } | {
238
+ name: 'renameColumn';
239
+ from: string;
240
+ to: string;
241
+ } | {
242
+ name: 'dropPrimary' | 'dropUnique' | 'dropIndex' | 'dropForeign';
243
+ index: string;
244
+ } | {
245
+ name: 'rename';
246
+ to: string;
247
+ } | {
248
+ name: 'drop' | 'dropIfExists';
249
+ };
250
+ /**
251
+ * The table definition passed to Schema.create()/Schema.table() callbacks, with Laravel's column types and
252
+ * commands. It only records; the schema grammar turns it into DDL for one driver.
253
+ */
254
+ declare class Blueprint {
255
+ readonly table: string;
256
+ readonly creating: boolean;
257
+ readonly columns: ColumnDefinition[];
258
+ readonly commands: BlueprintCommand[];
259
+ constructor(table: string, creating?: boolean);
260
+ addColumn(type: ColumnType, name: string, attributes?: Partial<ColumnAttributes>): ColumnDefinition;
261
+ /** An auto-incrementing unsigned big integer primary key (Laravel's id()). */
262
+ id(column?: string): ColumnDefinition;
263
+ increments(column: string): ColumnDefinition;
264
+ bigIncrements(column: string): ColumnDefinition;
265
+ integer(column: string, autoIncrement?: boolean, unsigned?: boolean): ColumnDefinition;
266
+ bigInteger(column: string, autoIncrement?: boolean, unsigned?: boolean): ColumnDefinition;
267
+ mediumInteger(column: string, autoIncrement?: boolean, unsigned?: boolean): ColumnDefinition;
268
+ smallInteger(column: string, autoIncrement?: boolean, unsigned?: boolean): ColumnDefinition;
269
+ tinyInteger(column: string, autoIncrement?: boolean, unsigned?: boolean): ColumnDefinition;
270
+ unsignedInteger(column: string): ColumnDefinition;
271
+ unsignedBigInteger(column: string): ColumnDefinition;
272
+ unsignedSmallInteger(column: string): ColumnDefinition;
273
+ unsignedTinyInteger(column: string): ColumnDefinition;
274
+ /** An unsigned big integer meant for a foreign key: t.foreignId('user_id').constrained().cascadeOnDelete(). */
275
+ foreignId(column: string): ForeignIdColumnDefinition;
276
+ string(column: string, length?: number): ColumnDefinition;
277
+ char(column: string, length?: number): ColumnDefinition;
278
+ text(column: string): ColumnDefinition;
279
+ mediumText(column: string): ColumnDefinition;
280
+ longText(column: string): ColumnDefinition;
281
+ boolean(column: string): ColumnDefinition;
282
+ date(column: string): ColumnDefinition;
283
+ dateTime(column: string, precision?: number): ColumnDefinition;
284
+ time(column: string, precision?: number): ColumnDefinition;
285
+ timestamp(column: string, precision?: number): ColumnDefinition;
286
+ /** Nullable created_at and updated_at. */
287
+ timestamps(precision?: number): void;
288
+ nullableTimestamps(precision?: number): void;
289
+ /** A nullable deleted_at timestamp for soft deletes. */
290
+ softDeletes(column?: string, precision?: number): ColumnDefinition;
291
+ decimal(column: string, total?: number, places?: number): ColumnDefinition;
292
+ float(column: string, precision?: number): ColumnDefinition;
293
+ double(column: string): ColumnDefinition;
294
+ json(column: string): ColumnDefinition;
295
+ jsonb(column: string): ColumnDefinition;
296
+ uuid(column?: string): ColumnDefinition;
297
+ ulid(column?: string): ColumnDefinition;
298
+ binary(column: string): ColumnDefinition;
299
+ enum(column: string, allowed: readonly string[]): ColumnDefinition;
300
+ /** remember_token varchar(100) null. */
301
+ rememberToken(): ColumnDefinition;
302
+ /** {name}_type + {name}_id, indexed together: the columns of a polymorphic relation. */
303
+ morphs(name: string, indexName?: string): void;
304
+ nullableMorphs(name: string, indexName?: string): void;
305
+ primary(columns: string | string[], name?: string): void;
306
+ unique(columns: string | string[], name?: string): void;
307
+ index(columns: string | string[], name?: string): void;
308
+ /** t.foreign('user_id').references('id').on('users') */
309
+ foreign(columns: string | string[], name?: string): ForeignKeyDefinition;
310
+ dropColumn(...columns: Array<string | string[]>): void;
311
+ renameColumn(from: string, to: string): void;
312
+ dropPrimary(name?: string): void;
313
+ /** By name, or by columns (the conventional {table}_{columns}_unique name). */
314
+ dropUnique(index: string | string[]): void;
315
+ dropIndex(index: string | string[]): void;
316
+ dropForeign(index: string | string[]): void;
317
+ /** Drops the foreign key on the column, then the column. */
318
+ dropConstrainedForeignId(column: string): void;
319
+ dropTimestamps(): void;
320
+ dropSoftDeletes(column?: string): void;
321
+ dropRememberToken(): void;
322
+ dropMorphs(name: string, indexName?: string): void;
323
+ rename(to: string): void;
324
+ drop(): void;
325
+ dropIfExists(): void;
326
+ /** Laravel's default index name: {table}_{columns}_{type}, lowercased, with - and . replaced by _. */
327
+ createIndexName(type: IndexType | 'foreign', columns: string[]): string;
328
+ /** The index commands implied by column modifiers (t.string('email').unique()), in column order. */
329
+ fluentIndexCommands(): BlueprintCommand[];
330
+ private indexCommand;
331
+ private indexNameFor;
332
+ }
333
+
334
+ type Sql$1 = RawBuilder<unknown>;
335
+ /** One column of an existing table, as reported by Schema.getColumns(). */
336
+ interface ColumnInfo {
337
+ name: string;
338
+ /** The base type, lowercased: 'varchar', 'bigint', 'int8', 'tinyint', 'timestamp', … (driver-specific). */
339
+ type_name: string;
340
+ /** The full type, lowercased: 'varchar(255)', 'tinyint(1)', 'timestamp(0) without time zone', … */
341
+ type: string;
342
+ nullable: boolean;
343
+ default: string | null;
344
+ auto_increment: boolean;
345
+ }
346
+ /**
347
+ * Turns a Blueprint into DDL for one driver (Laravel's Schema\Grammars). Identifiers go through sql.id();
348
+ * default values and comments are quoted literals (sql.lit); only DB.raw() defaults are written as-is.
349
+ */
350
+ declare abstract class SchemaGrammar {
351
+ protected readonly config: Partial<ConnectionConfig>;
352
+ abstract readonly driver: DriverName;
353
+ constructor(config?: Partial<ConnectionConfig>);
354
+ static for(driver: DriverName, config?: Partial<ConnectionConfig>): SchemaGrammar;
355
+ /** Every statement for the blueprint: create/add first, then commands in order, then indexes from column modifiers. */
356
+ compile(blueprint: Blueprint): Sql$1[];
357
+ protected compileCreate(blueprint: Blueprint, _commands: BlueprintCommand[], _handled: Set<BlueprintCommand>): Sql$1;
358
+ protected compileAdd(blueprint: Blueprint, _commands: BlueprintCommand[], _handled: Set<BlueprintCommand>): Sql$1[];
359
+ protected compileCommand(blueprint: Blueprint, command: BlueprintCommand): Sql$1[];
360
+ compileRename(from: string, to: string): Sql$1;
361
+ compileDrop(table: string): Sql$1;
362
+ compileDropIfExists(table: string): Sql$1;
363
+ protected compileUnique(blueprint: Blueprint, index: string, columns: string[]): Sql$1;
364
+ protected compileIndex(blueprint: Blueprint, index: string, columns: string[]): Sql$1;
365
+ protected compileDropPrimary(blueprint: Blueprint, index: string): Sql$1;
366
+ protected compileDropUnique(blueprint: Blueprint, index: string): Sql$1;
367
+ protected compileDropIndex(_blueprint: Blueprint, index: string): Sql$1;
368
+ protected compileDropForeign(blueprint: Blueprint, index: string): Sql$1;
369
+ protected compileComments(_blueprint: Blueprint): Sql$1[];
370
+ /** `foreign key ("user_id") references "users" ("id") on delete cascade` */
371
+ protected foreignKeyClause(foreign: ForeignKeyDefinition): Sql$1;
372
+ /** `references "users" ("id") on delete cascade on update …` */
373
+ protected referencesClause(foreign: ForeignKeyDefinition): Sql$1;
374
+ /** `"name" type modifiers` */
375
+ columnDefinition(column: ColumnDefinition): Sql$1;
376
+ protected abstract type(column: ColumnDefinition): Sql$1;
377
+ protected abstract modifiers(column: ColumnDefinition): Sql$1[];
378
+ /** Laravel's getDefaultValue(): raw expressions as-is, booleans as '1'/'0', everything else as a quoted literal. */
379
+ protected defaultValue(value: unknown): Sql$1;
380
+ protected nullable(column: ColumnDefinition): Sql$1;
381
+ protected default(column: ColumnDefinition): Sql$1 | undefined;
382
+ protected enumCheck(column: ColumnDefinition, type: string): Sql$1;
383
+ abstract compileTables(): Sql$1;
384
+ abstract compileColumns(table: string): Sql$1;
385
+ abstract normalizeColumns(rows: Array<Record<string, unknown>>, tableSql?: string): ColumnInfo[];
386
+ abstract compileEnableForeignKeyConstraints(): Sql$1;
387
+ abstract compileDisableForeignKeyConstraints(): Sql$1;
388
+ }
389
+ declare class SqliteSchemaGrammar extends SchemaGrammar {
390
+ readonly driver: "sqlite";
391
+ /** SQLite can't add keys to an existing table, so primary and foreign keys go inside create table. */
392
+ protected compileCreate(blueprint: Blueprint, commands: BlueprintCommand[], handled: Set<BlueprintCommand>): Sql$1;
393
+ /** New columns may carry an inline `references` clause (the only foreign key SQLite can add later). */
394
+ protected compileAdd(blueprint: Blueprint, commands: BlueprintCommand[], handled: Set<BlueprintCommand>): Sql$1[];
395
+ protected compileCommand(blueprint: Blueprint, command: BlueprintCommand): Sql$1[];
396
+ protected compileUnique(blueprint: Blueprint, index: string, columns: string[]): Sql$1;
397
+ protected compileDropUnique(_blueprint: Blueprint, index: string): Sql$1;
398
+ protected type(column: ColumnDefinition): Sql$1;
399
+ protected modifiers(column: ColumnDefinition): Sql$1[];
400
+ compileTables(): Sql$1;
401
+ compileColumns(table: string): Sql$1;
402
+ normalizeColumns(rows: Array<Record<string, unknown>>): ColumnInfo[];
403
+ compileEnableForeignKeyConstraints(): Sql$1;
404
+ compileDisableForeignKeyConstraints(): Sql$1;
405
+ }
406
+ declare class PostgresSchemaGrammar extends SchemaGrammar {
407
+ readonly driver: "pgsql";
408
+ protected compileComments(blueprint: Blueprint): Sql$1[];
409
+ protected type(column: ColumnDefinition): Sql$1;
410
+ protected modifiers(column: ColumnDefinition): Sql$1[];
411
+ compileTables(): Sql$1;
412
+ compileColumns(table: string): Sql$1;
413
+ normalizeColumns(rows: Array<Record<string, unknown>>): ColumnInfo[];
414
+ compileEnableForeignKeyConstraints(): Sql$1;
415
+ compileDisableForeignKeyConstraints(): Sql$1;
416
+ }
417
+ declare class MySqlSchemaGrammar extends SchemaGrammar {
418
+ readonly driver: "mysql";
419
+ protected compileCreate(blueprint: Blueprint, commands: BlueprintCommand[], handled: Set<BlueprintCommand>): Sql$1;
420
+ protected compileAdd(blueprint: Blueprint): Sql$1[];
421
+ protected compileUnique(blueprint: Blueprint, index: string, columns: string[]): Sql$1;
422
+ protected compileIndex(blueprint: Blueprint, index: string, columns: string[]): Sql$1;
423
+ protected compileDropPrimary(blueprint: Blueprint): Sql$1;
424
+ protected compileDropUnique(blueprint: Blueprint, index: string): Sql$1;
425
+ protected compileDropIndex(blueprint: Blueprint, index: string): Sql$1;
426
+ protected compileDropForeign(blueprint: Blueprint, index: string): Sql$1;
427
+ protected type(column: ColumnDefinition): Sql$1;
428
+ protected modifiers(column: ColumnDefinition): Sql$1[];
429
+ compileTables(): Sql$1;
430
+ compileColumns(table: string): Sql$1;
431
+ normalizeColumns(rows: Array<Record<string, unknown>>): ColumnInfo[];
432
+ compileEnableForeignKeyConstraints(): Sql$1;
433
+ compileDisableForeignKeyConstraints(): Sql$1;
434
+ }
435
+
436
+ /**
437
+ * Laravel's Schema builder for one connection: Schema.create('posts', (t) => { t.id(); t.string('title') }).
438
+ * Each blueprint compiles to one or more statements, run in order.
439
+ */
440
+ declare class SchemaBuilder {
441
+ protected readonly db: Connection;
442
+ private readonly resolveConnection?;
443
+ readonly grammar: SchemaGrammar;
444
+ constructor(db: Connection, resolveConnection?: ((name: string) => Connection) | undefined);
445
+ getConnection(): Connection;
446
+ /** The schema builder of another connection: Schema.connection('pgsql').create(…). */
447
+ connection(name: string): SchemaBuilder;
448
+ create(table: string, callback: (table: Blueprint) => void): Promise<void>;
449
+ /** Changes an existing table: add columns, indexes and foreign keys, drop or rename columns. */
450
+ table(table: string, callback: (table: Blueprint) => void): Promise<void>;
451
+ drop(table: string): Promise<void>;
452
+ dropIfExists(table: string): Promise<void>;
453
+ rename(from: string, to: string): Promise<void>;
454
+ /** Runs a blueprint's statements. Also useful to inspect the DDL: grammar.compile(blueprint). */
455
+ build(blueprint: Blueprint): Promise<void>;
456
+ /** The table names of the connection's database (or current schema on Postgres). */
457
+ getTables(): Promise<string[]>;
458
+ hasTable(table: string): Promise<boolean>;
459
+ getColumns(table: string): Promise<ColumnInfo[]>;
460
+ getColumnListing(table: string): Promise<string[]>;
461
+ /** Case-insensitive, like Laravel. */
462
+ hasColumn(table: string, column: string): Promise<boolean>;
463
+ hasColumns(table: string, columns: string[]): Promise<boolean>;
464
+ enableForeignKeyConstraints(): Promise<void>;
465
+ disableForeignKeyConstraints(): Promise<void>;
466
+ /**
467
+ * Runs fn with foreign key checks off. On MySQL and Postgres the connection is pinned (a transaction) so the
468
+ * setting and fn's statements share one pooled connection; SQLite has a single connection already.
469
+ */
470
+ withoutForeignKeyConstraints<R>(fn: () => Promise<R>): Promise<R>;
471
+ /** Drops every table (migrate:fresh). */
472
+ dropAllTables(): Promise<void>;
473
+ private run;
474
+ }
475
+
476
+ interface LoggedQuery {
477
+ query: string;
478
+ bindings: readonly unknown[];
479
+ time: number;
480
+ }
481
+ /**
482
+ * A named database connection on Kysely.
483
+ *
484
+ * Transactions: `transaction(fn)` is bound to the async context that called it (AsyncLocalStorage), so a
485
+ * transaction in one request never captures another request's queries. `beginTransaction()` instead pins the
486
+ * transaction to the whole connection until `commit()`/`rollBack()`; that is what RefreshDatabase needs.
487
+ * Nested levels use savepoints (trans2, trans3, …) either way.
488
+ */
489
+ declare class Connection implements DatabaseConnection {
490
+ protected readonly name: string;
491
+ protected readonly config: ConnectionConfig;
492
+ protected readonly db: Kysely<any>;
493
+ private readonly context;
494
+ private readonly pinned;
495
+ private loggingQueries;
496
+ private queryLog;
497
+ constructor(name: string, config: ConnectionConfig);
498
+ getName(): string;
499
+ getDriverName(): DriverName;
500
+ getConfig(): ConnectionConfig;
501
+ /** A query builder for a table: connection.table('users').where('votes', '>', 100).get(). */
502
+ table<T = Row>(table: string | Expression): Builder$1<T>;
503
+ /** A query builder with no table yet (use from()). */
504
+ query<T = Row>(): Builder$1<T>;
505
+ /** Schema operations on this connection (Laravel's getSchemaBuilder()). */
506
+ getSchemaBuilder(): SchemaBuilder;
507
+ /** Raw Kysely access. Inside a transaction this is the transaction, so queries join it. */
508
+ kysely(): Kysely<any>;
509
+ /** Normalizes a value for this driver (booleans, Dates, JSON). */
510
+ prepareValue(value: unknown): unknown;
511
+ /** Compiles a Kysely raw builder against this connection's dialect. */
512
+ compile(query: RawBuilder<unknown>): CompiledQuery;
513
+ /** Runs a compiled statement on the current executor (the transaction, when one is open). */
514
+ execute<T = Row>(query: RawBuilder<unknown> | CompiledQuery): Promise<QueryResult<T>>;
515
+ /** Raw select with `?` placeholders. */
516
+ select<T = Row>(query: string, bindings?: readonly unknown[]): Promise<T[]>;
517
+ /** Raw statement with `?` placeholders. */
518
+ statement(query: string, bindings?: readonly unknown[]): Promise<void>;
519
+ /** Raw statement; returns the number of affected rows. */
520
+ affectingStatement(query: string, bindings?: readonly unknown[]): Promise<number>;
521
+ private raw;
522
+ /** Runs fn in a transaction (a savepoint when nested). Commits when fn resolves, rolls back and rethrows when it throws. */
523
+ transaction<R>(fn: (connection: this) => Promise<R>): Promise<R>;
524
+ /** Starts a transaction that stays open, for every async context, until commit()/rollBack(). */
525
+ beginTransaction(): Promise<void>;
526
+ commit(): Promise<void>;
527
+ /** Rolls back the innermost level opened by beginTransaction(). Does nothing when none is open. */
528
+ rollBack(): Promise<void>;
529
+ transactionLevel(): number;
530
+ enableQueryLog(): void;
531
+ disableQueryLog(): void;
532
+ getQueryLog(): LoggedQuery[];
533
+ flushQueryLog(): void;
534
+ disconnect(): Promise<void>;
535
+ /** The innermost open level: the context's own transaction or a pinned one, whichever is deeper. */
536
+ private current;
537
+ private open;
538
+ private close;
539
+ }
540
+
541
+ interface PaginatorOptions {
542
+ /** The base URL of the page links (default: the current request's URL, or '/'). */
543
+ path?: string;
544
+ /** Extra query string values added to every link. */
545
+ query?: Record<string, unknown>;
546
+ fragment?: string;
547
+ pageName?: string;
548
+ }
549
+ /** Laravel's Arr::query(): nested values become key[0]=…, encoded as RFC 3986. */
550
+ declare function buildQuery(values: Record<string, unknown>, prefix?: string): string;
551
+ /**
552
+ * Shared paginator state and URL building (Laravel's AbstractPaginator).
553
+ * The static resolvers read the current request; DatabaseServiceProvider points them at HttpRequest.
554
+ */
555
+ declare abstract class AbstractPaginator<T> implements Iterable<T> {
556
+ protected readonly perPageValue: number;
557
+ static currentPathResolver: () => string;
558
+ static currentPageResolver: (pageName: string) => number;
559
+ static queryStringResolver: () => Record<string, unknown>;
560
+ static currentCursorResolver: (cursorName: string) => unknown;
561
+ static resolveCurrentPath(): string;
562
+ static resolveCurrentPage(pageName?: string): number;
563
+ /** Restores the defaults (page 1, path '/'). Used by tests and when the provider is torn down. */
564
+ static resetResolvers(): void;
565
+ protected collection: Collection<T>;
566
+ protected pathValue: string;
567
+ protected queryValues: Record<string, unknown>;
568
+ protected fragmentValue: string | undefined;
569
+ protected pageName: string;
570
+ /** The resolved page number: page-based paginators pass it in; cursor pagination never reads it. */
571
+ protected readonly currentPageValue: number;
572
+ onEachSideCount: number;
573
+ protected constructor(items: Iterable<T>, perPageValue: number, options: PaginatorOptions, currentPage?: number);
574
+ currentPage(): number;
575
+ /** The 1-based position of the first item on this page, or null when the page is empty. */
576
+ firstItem(): number | null;
577
+ lastItem(): number | null;
578
+ onFirstPage(): boolean;
579
+ previousPageUrl(): string | null;
580
+ /** The URL for a page number: path?query&page=n#fragment. */
581
+ url(page: number): string;
582
+ protected buildFragment(): string;
583
+ path(): string;
584
+ withPath(path: string): this;
585
+ setPath(path: string): this;
586
+ /** Adds values to every link's query string. */
587
+ appends(key: string | Record<string, unknown>, value?: unknown): this;
588
+ /** Keeps the current request's query string on every link. */
589
+ withQueryString(): this;
590
+ fragment(fragment: string): this;
591
+ getPageName(): string;
592
+ setPageName(name: string): this;
593
+ onEachSide(count: number): this;
594
+ /** The items on this page, as an array (Laravel's items()). */
595
+ items(): T[];
596
+ getCollection(): Collection<T>;
597
+ setCollection(items: Collection<T>): this;
598
+ /** Transforms each item in place, typically for serialization: paginator.through(post => ({ id: post.id })). */
599
+ through(callback: (item: T, index: number) => unknown): this;
600
+ perPage(): number;
601
+ count(): number;
602
+ isEmpty(): boolean;
603
+ isNotEmpty(): boolean;
604
+ [Symbol.iterator](): Iterator<T>;
605
+ protected itemsToArray(): unknown[];
606
+ abstract toArray(): Record<string, unknown>;
607
+ toJSON(): Record<string, unknown>;
608
+ toJson(): string;
609
+ }
610
+
611
+ /** A position in a cursor-paginated result: the ordered columns' values of an edge item, plus the direction. */
612
+ declare class Cursor {
613
+ protected readonly parameters: Record<string, unknown>;
614
+ protected readonly pointsToNext: boolean;
615
+ constructor(parameters: Record<string, unknown>, pointsToNext?: boolean);
616
+ parameter(name: string): unknown;
617
+ pointsToNextItems(): boolean;
618
+ pointsToPreviousItems(): boolean;
619
+ toArray(): Record<string, unknown>;
620
+ /** URL-safe base64 of the JSON parameters (Laravel's format). */
621
+ encode(): string;
622
+ /** Decodes a cursor from the query string. Anything malformed gives undefined (the first page). */
623
+ static fromEncoded(encoded: unknown): Cursor | undefined;
624
+ }
625
+ interface CursorPaginatorOptions extends Omit<PaginatorOptions, 'pageName'> {
626
+ cursorName?: string;
627
+ /** The ordered columns whose values make up each cursor. */
628
+ parameters: string[];
629
+ }
630
+ /**
631
+ * cursorPaginate(): "next"/"previous" by the ordered columns' values instead of an offset, so it stays fast and
632
+ * stable on large, changing tables (Laravel's CursorPaginator). JSON: data, path, per_page, next_cursor,
633
+ * next_page_url, prev_cursor, prev_page_url.
634
+ */
635
+ declare class CursorPaginator<T> extends AbstractPaginator<T> {
636
+ protected readonly cursorValue: Cursor | undefined;
637
+ protected readonly hasMore: boolean;
638
+ protected readonly cursorName: string;
639
+ protected readonly parameters: string[];
640
+ constructor(items: Iterable<T>, perPage: number, cursorValue: Cursor | undefined, options: CursorPaginatorOptions);
641
+ /** The cursor in the current request's query string (?cursor=…), if any. */
642
+ static resolveCurrentCursor(cursorName?: string): Cursor | undefined;
643
+ cursor(): Cursor | undefined;
644
+ getCursorName(): string;
645
+ hasMorePages(): boolean;
646
+ onFirstPage(): boolean;
647
+ nextCursor(): Cursor | undefined;
648
+ previousCursor(): Cursor | undefined;
649
+ nextPageUrl(): string | null;
650
+ previousPageUrl(): string | null;
651
+ /** The URL for a cursor: path?query&cursor=…#fragment. */
652
+ url(cursor: Cursor | number): string;
653
+ protected cursorFor(item: T, pointsToNext: boolean): Cursor;
654
+ toArray(): Record<string, unknown>;
655
+ }
656
+
657
+ interface PaginationLink {
658
+ url: string | null;
659
+ label: string;
660
+ active: boolean;
661
+ }
662
+ /** Page number → URL, in page order. */
663
+ type UrlRange = Array<[number, string]>;
664
+ /**
665
+ * paginate(): knows the total, so it can render every page link (Laravel's LengthAwarePaginator).
666
+ * JSON: current_page, data, first_page_url, from, last_page, last_page_url, links, next_page_url, path, per_page,
667
+ * prev_page_url, to, total.
668
+ */
669
+ declare class LengthAwarePaginator<T> extends AbstractPaginator<T> {
670
+ protected readonly totalValue: number;
671
+ protected readonly lastPageValue: number;
672
+ constructor(items: Iterable<T>, totalValue: number, perPage: number, currentPage?: number, options?: PaginatorOptions);
673
+ total(): number;
674
+ lastPage(): number;
675
+ hasPages(): boolean;
676
+ hasMorePages(): boolean;
677
+ onLastPage(): boolean;
678
+ nextPageUrl(): string | null;
679
+ /** The page links Laravel renders: previous, the page window with '...' gaps, next. */
680
+ linkCollection(): PaginationLink[];
681
+ /** Laravel's UrlWindow: the first pages, the slider around the current page and the last pages, with '...' between. */
682
+ protected elements(): Array<UrlRange | '...'>;
683
+ private urlWindow;
684
+ private range;
685
+ toArray(): Record<string, unknown>;
686
+ }
687
+
688
+ /**
689
+ * simplePaginate(): no total, only "is there a next page". The query fetches perPage + 1 rows; the extra row only
690
+ * sets hasMorePages() (Laravel's Paginator).
691
+ */
692
+ declare class Paginator<T> extends AbstractPaginator<T> {
693
+ protected readonly hasMore: boolean;
694
+ constructor(items: Iterable<T>, perPage: number, currentPage?: number, options?: PaginatorOptions);
695
+ hasMorePages(): boolean;
696
+ hasPages(): boolean;
697
+ onLastPage(): boolean;
698
+ nextPageUrl(): string | null;
699
+ toArray(): Record<string, unknown>;
700
+ }
701
+
702
+ type Sql = RawBuilder<unknown>;
703
+ /** The operators accepted by where()/having(). Anything else is rejected: operators are written into the SQL. */
704
+ declare const OPERATORS: Set<string>;
705
+ /**
706
+ * Compiles a query builder's state into a Kysely `sql` template for one driver, like Laravel's Query\Grammars.
707
+ * Identifiers go through sql.id() (quoted per dialect); values are always bound parameters.
708
+ */
709
+ declare class Grammar {
710
+ readonly driver: DriverName;
711
+ constructor(driver: DriverName);
712
+ /** 'users.name' → "users"."name", 'users.*' → "users".*, 'name as n' → "name" as "n". Expressions pass through raw. */
713
+ wrap(value: string | Expression): Sql;
714
+ wrapTable(table: string | Expression): Sql;
715
+ prepare(value: unknown): unknown;
716
+ /** A bound value, the raw SQL of an Expression, or a Kysely sql fragment as-is. */
717
+ parameter(value: unknown): Sql;
718
+ operator(operator: string): string;
719
+ columnize(columns: ReadonlyArray<string | Expression>): Sql;
720
+ compileSelect(query: Builder$1<unknown>): Sql;
721
+ /** Everything after the select list: from, joins, where, group by, having, order by, limit/offset, lock. */
722
+ compileComponents(query: Builder$1<unknown>): Sql;
723
+ compileOrders(query: Builder$1<unknown>): Sql | undefined;
724
+ compileWheres(wheres: readonly Where[], keyword?: 'where' | 'on'): Sql | undefined;
725
+ compileWhere(where: Where): Sql;
726
+ compileJoin(joinClause: JoinClause): Sql;
727
+ compileHavings(havings: readonly Having[]): Sql | undefined;
728
+ compileLimitOffset(limit: number | undefined, offset: number | undefined): Sql | undefined;
729
+ compileLock(mode: 'update' | 'share' | undefined): Sql | undefined;
730
+ /** `select count(*) as aggregate …`. Orders, limit and offset are dropped; grouped or distinct queries are wrapped. */
731
+ compileAggregate(query: Builder$1<unknown>, fn: string, column: string | Expression): Sql;
732
+ compileExists(query: Builder$1<unknown>): Sql;
733
+ compileInsert(query: Builder$1<unknown>, rows: readonly Row[]): Sql;
734
+ compileInsertOrIgnore(query: Builder$1<unknown>, rows: readonly Row[]): Sql;
735
+ /** `into "table" ("a", "b") values (?, ?), (?, ?)`. Columns are the union of every row's keys; a missing key binds null. */
736
+ compileInsertBody(query: Builder$1<unknown>, rows: readonly Row[]): Sql;
737
+ compileInsertGetId(query: Builder$1<unknown>, row: Row, keyName: string): Sql;
738
+ compileUpsert(query: Builder$1<unknown>, rows: readonly Row[], uniqueBy: readonly string[], update: readonly string[]): Sql;
739
+ compileUpdate(query: Builder$1<unknown>, values: Row): Sql;
740
+ compileDelete(query: Builder$1<unknown>): Sql;
741
+ compileTruncate(query: Builder$1<unknown>): Sql[];
742
+ compileRandom(): Expression;
743
+ private assertSimpleMutation;
744
+ private mysqlOrderAndLimit;
745
+ }
746
+
747
+ type WhereBoolean = 'and' | 'or';
748
+ type Direction = 'asc' | 'desc';
749
+ type ColumnRef = string | Expression;
750
+ type Where = {
751
+ type: 'basic';
752
+ column: ColumnRef | Builder$1<unknown>;
753
+ operator: string;
754
+ value: unknown;
755
+ boolean: WhereBoolean;
756
+ } | {
757
+ type: 'in';
758
+ column: ColumnRef;
759
+ values: readonly unknown[] | Builder$1<unknown>;
760
+ not: boolean;
761
+ boolean: WhereBoolean;
762
+ } | {
763
+ type: 'null';
764
+ column: ColumnRef;
765
+ not: boolean;
766
+ boolean: WhereBoolean;
767
+ } | {
768
+ type: 'between';
769
+ column: ColumnRef;
770
+ values: readonly [unknown, unknown];
771
+ not: boolean;
772
+ boolean: WhereBoolean;
773
+ } | {
774
+ type: 'column';
775
+ first: ColumnRef;
776
+ operator: string;
777
+ second: ColumnRef;
778
+ boolean: WhereBoolean;
779
+ } | {
780
+ type: 'nested';
781
+ query: Builder$1<unknown>;
782
+ not: boolean;
783
+ boolean: WhereBoolean;
784
+ } | {
785
+ type: 'exists';
786
+ query: Builder$1<unknown>;
787
+ not: boolean;
788
+ boolean: WhereBoolean;
789
+ } | {
790
+ type: 'raw';
791
+ sql: string;
792
+ bindings: readonly unknown[];
793
+ boolean: WhereBoolean;
794
+ };
795
+ type Having = {
796
+ column: ColumnRef;
797
+ operator: string;
798
+ value: unknown;
799
+ boolean: WhereBoolean;
800
+ } | {
801
+ raw: Expression;
802
+ boolean: WhereBoolean;
803
+ };
804
+ type Order = {
805
+ column: ColumnRef;
806
+ direction: Direction;
807
+ } | {
808
+ raw: Expression;
809
+ };
810
+ type SelectColumn = ColumnRef | {
811
+ query: Builder$1<unknown>;
812
+ as: string;
813
+ };
814
+ type NestedCallback<Q> = (query: Q) => unknown;
815
+ /** The key a selected column comes back under: 'users.name' → 'name', 'name as n' → 'n'. */
816
+ declare function columnKey(column: string): string;
817
+ /**
818
+ * Laravel's query builder: DB.table('users').where('votes', '>', 100).get().
819
+ * Implements the QueryBuilder contract other components use (Queue, Cache, Session, Validation).
820
+ */
821
+ declare class Builder$1<T = Row> implements QueryBuilder<T> {
822
+ readonly connection: Connection;
823
+ readonly grammar: Grammar;
824
+ columns: SelectColumn[];
825
+ distinctRows: boolean;
826
+ fromTable: string | Expression | undefined;
827
+ joins: JoinClause[];
828
+ wheres: Where[];
829
+ groups: ColumnRef[];
830
+ havings: Having[];
831
+ orders: Order[];
832
+ limitValue: number | undefined;
833
+ offsetValue: number | undefined;
834
+ lockMode: 'update' | 'share' | undefined;
835
+ constructor(connection: Connection, table?: string | Expression);
836
+ from(table: string | Expression): this;
837
+ select(...columns: Array<ColumnRef | ColumnRef[]>): this;
838
+ addSelect(...columns: Array<ColumnRef | ColumnRef[]>): this;
839
+ selectRaw(expression: string, bindings?: readonly unknown[]): this;
840
+ /** Adds `(subquery) as alias` to the select list. */
841
+ selectSub(query: Builder$1<unknown>, as: string): this;
842
+ distinct(): this;
843
+ where(column: ColumnRef, value: unknown): this;
844
+ where(column: ColumnRef, operator: Operator | string, value: unknown): this;
845
+ where(conditions: Row): this;
846
+ where(callback: NestedCallback<Builder$1<T>>): this;
847
+ orWhere(column: ColumnRef, value: unknown): this;
848
+ orWhere(column: ColumnRef, operator: Operator | string, value: unknown): this;
849
+ orWhere(conditions: Row): this;
850
+ orWhere(callback: NestedCallback<Builder$1<T>>): this;
851
+ /** where not (…): whereNot(q => q.where('a', 1).orWhere('b', 2)). */
852
+ whereNot(callback: NestedCallback<Builder$1<T>>): this;
853
+ orWhereNot(callback: NestedCallback<Builder$1<T>>): this;
854
+ whereIn(column: ColumnRef, values: readonly unknown[] | Builder$1<unknown>): this;
855
+ orWhereIn(column: ColumnRef, values: readonly unknown[] | Builder$1<unknown>): this;
856
+ whereNotIn(column: ColumnRef, values: readonly unknown[] | Builder$1<unknown>): this;
857
+ orWhereNotIn(column: ColumnRef, values: readonly unknown[] | Builder$1<unknown>): this;
858
+ whereNull(columns: ColumnRef | ColumnRef[]): this;
859
+ orWhereNull(column: ColumnRef): this;
860
+ whereNotNull(columns: ColumnRef | ColumnRef[]): this;
861
+ orWhereNotNull(column: ColumnRef): this;
862
+ whereBetween(column: ColumnRef, values: readonly [unknown, unknown]): this;
863
+ orWhereBetween(column: ColumnRef, values: readonly [unknown, unknown]): this;
864
+ whereNotBetween(column: ColumnRef, values: readonly [unknown, unknown]): this;
865
+ /** Compares two columns: whereColumn('updated_at', '>', 'created_at'). */
866
+ whereColumn(first: ColumnRef, operatorOrSecond: string, second?: ColumnRef, boolean?: WhereBoolean): this;
867
+ orWhereColumn(first: ColumnRef, operatorOrSecond: string, second?: ColumnRef): this;
868
+ whereRaw(sql: string, bindings?: readonly unknown[], boolean?: WhereBoolean): this;
869
+ orWhereRaw(sql: string, bindings?: readonly unknown[]): this;
870
+ whereExists(query: Builder$1<unknown> | NestedCallback<Builder$1<Row>>, boolean?: WhereBoolean, not?: boolean): this;
871
+ orWhereExists(query: Builder$1<unknown> | NestedCallback<Builder$1<Row>>): this;
872
+ whereNotExists(query: Builder$1<unknown> | NestedCallback<Builder$1<Row>>): this;
873
+ /** `(select …) <operator> value`: used by has('comments', '>=', 3). */
874
+ whereSub(query: Builder$1<unknown>, operator: string, value: unknown, boolean?: WhereBoolean): this;
875
+ /** Appends another builder's where clauses as one nested group. */
876
+ addNestedWhereQuery(query: Builder$1<unknown>, boolean?: WhereBoolean, not?: boolean): this;
877
+ join(table: string | Expression, first: ColumnRef | ((join: JoinClause) => unknown), operator?: string, second?: ColumnRef, type?: JoinType): this;
878
+ leftJoin(table: string | Expression, first: ColumnRef | ((join: JoinClause) => unknown), operator?: string, second?: ColumnRef): this;
879
+ rightJoin(table: string | Expression, first: ColumnRef | ((join: JoinClause) => unknown), operator?: string, second?: ColumnRef): this;
880
+ crossJoin(table: string | Expression): this;
881
+ groupBy(...columns: ColumnRef[]): this;
882
+ having(column: ColumnRef, operatorOrValue: unknown, value?: unknown, boolean?: WhereBoolean): this;
883
+ havingRaw(sql: string, bindings?: readonly unknown[], boolean?: WhereBoolean): this;
884
+ orderBy(column: ColumnRef, direction?: Direction | Uppercase<Direction>): this;
885
+ orderByDesc(column: ColumnRef): this;
886
+ latest(column?: ColumnRef): this;
887
+ oldest(column?: ColumnRef): this;
888
+ inRandomOrder(): this;
889
+ orderByRaw(sql: string, bindings?: readonly unknown[]): this;
890
+ /** Removes existing orders, optionally adding a new one. */
891
+ reorder(column?: ColumnRef, direction?: Direction): this;
892
+ limit(count: number): this;
893
+ take(count: number): this;
894
+ offset(count: number): this;
895
+ skip(count: number): this;
896
+ forPage(page: number, perPage?: number): this;
897
+ lockForUpdate(): this;
898
+ sharedLock(): this;
899
+ /** Calls callback(this, value) when value is truthy (or the default callback otherwise). */
900
+ when<V>(value: V, callback: (query: this, value: V) => unknown, otherwise?: (query: this, value: V) => unknown): this;
901
+ tap(callback: (query: this) => unknown): this;
902
+ get(): Promise<Collection<T>>;
903
+ /** The raw rows, without a Collection around them. */
904
+ runSelect(): Promise<T[]>;
905
+ first(): Promise<T | undefined>;
906
+ find(id: unknown, keyName?: string): Promise<T | undefined>;
907
+ value<V = unknown>(column: string): Promise<V | undefined>;
908
+ pluck<V = unknown>(column: string): Promise<Collection<V>>;
909
+ count(column?: ColumnRef): Promise<number>;
910
+ min<V = unknown>(column: ColumnRef): Promise<V | undefined>;
911
+ max<V = unknown>(column: ColumnRef): Promise<V | undefined>;
912
+ sum(column: ColumnRef): Promise<number>;
913
+ avg(column: ColumnRef): Promise<number | undefined>;
914
+ aggregate(fn: 'count' | 'min' | 'max' | 'sum' | 'avg', column: ColumnRef): Promise<unknown>;
915
+ exists(): Promise<boolean>;
916
+ doesntExist(): Promise<boolean>;
917
+ insert(values: Row | Row[]): Promise<void>;
918
+ /** Inserts one row and returns its auto-increment id. */
919
+ insertGetId(values: Row, keyName?: string): Promise<number | string>;
920
+ /** Inserts rows, skipping the ones that violate a unique constraint. Returns how many were inserted. */
921
+ insertOrIgnore(values: Row | Row[]): Promise<number>;
922
+ update(values: Row): Promise<number>;
923
+ /** Updates the row matching attributes, or inserts attributes + values. */
924
+ updateOrInsert(attributes: Row, values?: Row): Promise<boolean>;
925
+ /**
926
+ * Inserts rows, updating `update` (default: every inserted column except uniqueBy) when a row already exists.
927
+ * uniqueBy must be a primary key or unique index (Postgres and SQLite need it for ON CONFLICT).
928
+ */
929
+ upsert(values: Row | Row[], uniqueBy: string[], update?: string[]): Promise<number>;
930
+ increment(column: string, amount?: number, extra?: Row): Promise<number>;
931
+ decrement(column: string, amount?: number, extra?: Row): Promise<number>;
932
+ delete(id?: unknown): Promise<number>;
933
+ truncate(): Promise<void>;
934
+ /**
935
+ * Paginates with a total count (two queries: count, then the page). The page comes from ?page= on the current
936
+ * request unless given: DB.table('users').orderBy('id').paginate(15).
937
+ */
938
+ paginate(perPage?: number, columns?: ColumnRef[], pageName?: string, page?: number): Promise<LengthAwarePaginator<T>>;
939
+ /** Paginates without a count: fetches perPage + 1 rows to know whether there is a next page. */
940
+ simplePaginate(perPage?: number, columns?: ColumnRef[], pageName?: string, page?: number): Promise<Paginator<T>>;
941
+ /**
942
+ * Paginates by the ordered columns' values instead of an offset. Needs an orderBy (Eloquent adds the primary key);
943
+ * the cursor comes from ?cursor= on the current request unless given.
944
+ */
945
+ cursorPaginate(perPage?: number, columns?: ColumnRef[], cursorName?: string, cursor?: Cursor | string): Promise<CursorPaginator<T>>;
946
+ /**
947
+ * Runs the query page by page and passes each chunk to callback. Return false to stop. Needs an orderBy, so that
948
+ * pages don't overlap. Don't update the ordered column inside the callback; use chunkById() for that.
949
+ */
950
+ chunk(count: number, callback: (results: Collection<T>, page: number) => unknown): Promise<boolean>;
951
+ /** Chunks by comparing the key (where id > last id), so it is safe to update or delete rows inside the callback. */
952
+ chunkById(count: number, callback: (results: Collection<T>, page: number) => unknown, column?: string, alias?: string): Promise<boolean>;
953
+ /** Calls callback for every row, fetching `count` rows per query. Return false to stop. */
954
+ each(callback: (item: T, index: number) => unknown, count?: number): Promise<boolean>;
955
+ /** A LazyCollection that runs one query per chunk as it is iterated: for await (const user of query.lazy()). */
956
+ lazy(chunkSize?: number): LazyCollection<T>;
957
+ /** Like lazy(), but pages by key, so rows can be updated while iterating. */
958
+ lazyById(chunkSize?: number, column?: string, alias?: string): LazyCollection<T>;
959
+ /** where column > lastId order by column limit perPage (existing orders on the column are replaced). */
960
+ forPageAfterId(perPage?: number, lastId?: unknown, column?: string): this;
961
+ /** chunk() and lazy() need a stable order. Eloquent orders by the primary key instead of throwing. */
962
+ protected enforceOrderBy(): void;
963
+ /** The key chunkById()/lazyById() use by default. Eloquent uses the model's key. */
964
+ protected defaultKeyName(): string;
965
+ /** The page size when none is given. Eloquent uses the model's perPage. */
966
+ protected defaultPerPage(): number;
967
+ /** Laravel's get($columns): only applies when no columns were selected yet. */
968
+ private withColumns;
969
+ /** The column orders cursor pagination compares on; reversed (in the query too) when paging backwards. */
970
+ private ordersForCursor;
971
+ /** (a > ?) or (a = ? and (b > ? or (b = ? and …))), Laravel's cursor conditions. */
972
+ private whereCursor;
973
+ /** The compiled SQL (placeholders included), for debugging and tests. */
974
+ toSql(): string;
975
+ getBindings(): unknown[];
976
+ clone(): Builder$1<T>;
977
+ /** A fresh builder on the same connection and table (for nested where groups). */
978
+ newQuery(): Builder$1<Row>;
979
+ requireTable(): string | Expression;
980
+ private subQuery;
981
+ private addNested;
982
+ private addWhere;
983
+ private pushNull;
984
+ }
985
+ type JoinType = 'inner' | 'left' | 'right' | 'cross';
986
+ /** The `on …` part of a join. `where()` on a join binds a value; `on()` compares columns. */
987
+ declare class JoinClause extends Builder$1<Row> {
988
+ readonly joinType: JoinType;
989
+ readonly table: string | Expression;
990
+ constructor(parent: Builder$1<unknown>, joinType: JoinType, table: string | Expression);
991
+ on(first: ColumnRef, operator: string, second?: ColumnRef, boolean?: WhereBoolean): this;
992
+ orOn(first: ColumnRef, operator: string, second?: ColumnRef): this;
993
+ }
994
+
995
+ /** Laravel's storage format ('Y-m-d H:i:s'), in UTC. */
996
+ declare function formatDateTime(date: Date): string;
997
+ declare function formatDate(date: Date): string;
998
+ /**
999
+ * Parses a stored date/time as UTC. Accepts Dates, epoch milliseconds, 'Y-m-d', 'Y-m-d H:i:s' and ISO strings
1000
+ * (the last two with or without a zone suffix; a missing zone means UTC).
1001
+ */
1002
+ declare function parseDateTime(value: unknown): Date;
1003
+ /** Normalizes one binding for the driver: booleans, dates, JSON and undefined. */
1004
+ declare function prepareValue(value: unknown, driver: DriverName): unknown;
1005
+
1006
+ /** `config('database')`, in Laravel's config/database.php shape. */
1007
+ interface DatabaseConfig {
1008
+ default: string;
1009
+ connections: Record<string, ConnectionConfig>;
1010
+ /** Laravel 11: { table: 'migrations' }. A plain string (older Laravel) is accepted too. */
1011
+ migrations?: {
1012
+ table?: string;
1013
+ } | string;
1014
+ }
1015
+ /**
1016
+ * The DatabaseManager contract: named connections from config('database'), created on first use and cached.
1017
+ * Everything a connection does is also available here and runs on the default connection, as with Laravel's DB facade.
1018
+ * Named DatabaseManagerImpl so it never shadows the DatabaseManager token when both are re-exported.
1019
+ */
1020
+ declare class DatabaseManagerImpl implements DatabaseManager {
1021
+ private readonly config;
1022
+ private readonly connections;
1023
+ private defaultName;
1024
+ /** Pass the config, or a function that reads it (the provider reads config('database') lazily). */
1025
+ constructor(config: DatabaseConfig | (() => DatabaseConfig));
1026
+ private settings;
1027
+ /** A connection by name (default: config('database.default')). */
1028
+ connection(name?: string): Connection;
1029
+ getDefaultConnection(): string;
1030
+ /** Overrides config('database.default'); undefined clears the override. */
1031
+ setDefaultConnection(name: string | undefined): void;
1032
+ /**
1033
+ * Runs `callback` with `name` as the default connection (Laravel's usingConnection()), then restores the previous
1034
+ * override, or none, so the default follows config('database.default') again. Without a name, just runs it.
1035
+ */
1036
+ usingConnection<T>(name: string | undefined, callback: () => Promise<T>): Promise<T>;
1037
+ /** The connections opened so far. */
1038
+ getConnections(): Record<string, Connection>;
1039
+ /** The migrations table name (config('database.migrations.table'), default 'migrations'). */
1040
+ migrationsTable(): string;
1041
+ /** Closes a connection's pool and forgets it; the next connection(name) opens a new one. */
1042
+ disconnect(name?: string): Promise<void>;
1043
+ /** Laravel's purge(): the same as disconnect() here. */
1044
+ purge(name?: string): Promise<void>;
1045
+ /** Closes every open connection (app shutdown, the end of a test). */
1046
+ disconnectAll(): Promise<void>;
1047
+ /** The default connection's schema builder; Schema.connection(name) switches connections through this manager. */
1048
+ getSchemaBuilder(): SchemaBuilder;
1049
+ /** A raw SQL fragment: DB.raw('count(*) as total'). */
1050
+ raw(value: string, bindings?: readonly unknown[]): Expression;
1051
+ getName(): string;
1052
+ getDriverName(): DriverName;
1053
+ kysely(): ReturnType<Connection['kysely']>;
1054
+ table<T = Row>(table: string | Expression): Builder$1<T>;
1055
+ query<T = Row>(): Builder$1<T>;
1056
+ select<T = Row>(query: string, bindings?: readonly unknown[]): Promise<T[]>;
1057
+ /** The first row of a raw select, or undefined. */
1058
+ selectOne<T = Row>(query: string, bindings?: readonly unknown[]): Promise<T | undefined>;
1059
+ /** Raw insert. Returns true, like Laravel's DB::insert(). */
1060
+ insert(query: string, bindings?: readonly unknown[]): Promise<boolean>;
1061
+ /** Raw update; returns the number of affected rows. */
1062
+ update(query: string, bindings?: readonly unknown[]): Promise<number>;
1063
+ /** Raw delete; returns the number of affected rows. */
1064
+ delete(query: string, bindings?: readonly unknown[]): Promise<number>;
1065
+ statement(query: string, bindings?: readonly unknown[]): Promise<void>;
1066
+ affectingStatement(query: string, bindings?: readonly unknown[]): Promise<number>;
1067
+ transaction<R>(fn: (connection: Connection) => Promise<R>): Promise<R>;
1068
+ beginTransaction(): Promise<void>;
1069
+ commit(): Promise<void>;
1070
+ rollBack(): Promise<void>;
1071
+ transactionLevel(): number;
1072
+ enableQueryLog(): void;
1073
+ disableQueryLog(): void;
1074
+ getQueryLog(): LoggedQuery[];
1075
+ flushQueryLog(): void;
1076
+ }
1077
+
1078
+ /**
1079
+ * The DB facade: DB.table('users').get(), DB.transaction(fn), DB.connection('pgsql'), DB.kysely().
1080
+ * DB.raw() works without an application (it only builds an Expression).
1081
+ */
1082
+ declare const DB: _orieljs_support.Facade<DatabaseManagerImpl, {
1083
+ raw: typeof raw;
1084
+ }>;
1085
+ /** The Schema facade's binding: the default connection's SchemaBuilder (DatabaseServiceProvider binds it). */
1086
+ declare const SchemaBuilderToken: Token<SchemaBuilder>;
1087
+ /** The Schema facade: Schema.create('posts', (t) => { … }), Schema.table(…), Schema.dropIfExists(…). */
1088
+ declare const Schema: _orieljs_support.Facade<SchemaBuilder, object>;
1089
+
1090
+ /**
1091
+ * A relation is the related model's query builder, constrained to the parent: post.comments() is a
1092
+ * Builder<Comment> with `where comments.post_id = ?`, so every builder method (where, orderBy, paginate, a local
1093
+ * scope, …) works on it. Subclasses add eager loading (addEagerConstraints/initRelation/match) and the existence
1094
+ * queries behind has()/whereHas()/withCount().
1095
+ */
1096
+ declare abstract class Relation<R extends Model = Model, P extends Model = Model, Result = unknown> extends Builder<R> {
1097
+ readonly parent: P;
1098
+ /** The name the relation is loaded under (set when resolved by name, for eager loading and associate()). */
1099
+ relationName: string | undefined;
1100
+ /** Laravel's Relation::morphMap(): { post: Post } stores 'post' instead of 'Post' in *_type columns. */
1101
+ static morphMap(map?: Record<string, typeof Model>, merge?: boolean): Record<string, typeof Model>;
1102
+ static getMorphedModel(alias: string): typeof Model | undefined;
1103
+ protected constructor(related: R, parent: P);
1104
+ getParent(): P;
1105
+ getRelated(): R;
1106
+ /** Subclasses call this last in their constructor: adds the per-parent constraints unless eager loading. */
1107
+ protected init(): void;
1108
+ /** The constraints for one parent: where comments.post_id = post.id. */
1109
+ abstract addConstraints(): void;
1110
+ /** The constraints for many parents: where comments.post_id in (…). */
1111
+ abstract addEagerConstraints(models: P[]): void;
1112
+ /** Sets the empty value (null or an empty collection) on every parent. */
1113
+ abstract initRelation(models: P[], relation: string): P[];
1114
+ /** Distributes the eagerly loaded results to their parents. */
1115
+ abstract match(models: P[], results: R[], relation: string): P[];
1116
+ /** The relation's value for this parent (a model, null or a collection). */
1117
+ abstract getResults(): Promise<Result>;
1118
+ /** The query of has()/whereHas(): related rows that belong to the outer query's current row. */
1119
+ abstract getRelationExistenceQuery(query: Builder<R>, parentQuery: Builder<P>, columns?: ColumnRef[]): Builder<R>;
1120
+ /** Runs the eager query. */
1121
+ getEager(): Promise<Collection<R>>;
1122
+ /** select count(*) … for withCount() and has('comments', '>=', 3). */
1123
+ getRelationExistenceCountQuery(query: Builder<R>, parentQuery: Builder<P>): Builder<R>;
1124
+ /** The distinct non-null values of `key` on the models (the eager whereIn list). */
1125
+ protected keysOf(models: Model[], key: string): unknown[];
1126
+ }
1127
+
1128
+ /** A global scope class (Laravel's Scope): its apply() adds constraints to every query of the model. */
1129
+ interface Scope {
1130
+ apply(builder: Builder<any>, model: Model): void;
1131
+ }
1132
+ type ScopeCallback = (builder: Builder<any>) => void;
1133
+ type GlobalScope = Scope | ScopeCallback;
1134
+
1135
+ /**
1136
+ * A model's attribute types. `oriel model:types` adds a phantom `$attributes?: { … }` member to each model through
1137
+ * declaration merging; without it every attribute is `unknown`.
1138
+ */
1139
+ type Attributes<M> = M extends {
1140
+ $attributes?: infer A;
1141
+ } ? (unknown extends A ? Row : NonNullable<A>) : Row;
1142
+ /**
1143
+ * The column names a builder of M accepts: the generated attribute names plus any qualified `table.column`.
1144
+ * Without generated types, any string.
1145
+ */
1146
+ type Column<M> = M extends {
1147
+ $attributes?: infer A;
1148
+ } ? unknown extends A ? string : (keyof NonNullable<A> & string) | `${string}.${string}` : string;
1149
+ /** A model class: constructible with no arguments, with Model's statics. */
1150
+ type ModelClass<M extends Model = Model> = (new () => M) & Omit<typeof Model, 'prototype'>;
1151
+ type AnyScope = (query: any, ...args: any[]) => unknown;
1152
+ /** 'scopePublished' → 'published'. */
1153
+ type ScopeName<K> = K extends `scope${infer Name}` ? Uncapitalize<Name> : never;
1154
+ /** The local scopes of a model class as builder methods: static scopeOfType(q, type) → query.ofType(type). */
1155
+ type Scopes<C extends typeof Model> = {
1156
+ [K in keyof C as ScopeName<K>]: C[K] extends (query: never, ...args: infer A) => unknown ? (...args: A) => ModelBuilder<C> : never;
1157
+ };
1158
+ /** Post.query(): the Eloquent builder of Post, plus Post's local scopes. */
1159
+ type ModelBuilder<C extends typeof Model> = Builder<InstanceType<C>> & Scopes<C>;
1160
+ /** The static scope proxy type used by generated types: Post.published(). */
1161
+ type ScopeStatic<C extends typeof Model, K extends keyof C> = C[K] extends AnyScope ? C[K] extends (query: never, ...args: infer A) => unknown ? (...args: A) => ModelBuilder<C> : never : never;
1162
+ /** The arguments where() accepts on a builder of M (column names are checked when types are generated). */
1163
+ type WhereArgs<M, Q> = [column: Column<M> | Expression, value: unknown] | [column: Column<M> | Expression, operator: Operator | string, value: unknown] | [conditions: Row] | [callback: (query: Q) => unknown];
1164
+ /** The names of a model's relation methods (methods returning a relation). */
1165
+ type RelationNames<M> = {
1166
+ [K in keyof M]: M[K] extends () => {
1167
+ getResults(): Promise<any>;
1168
+ } ? K : never;
1169
+ }[keyof M] & string;
1170
+ /** The loaded value of a relation: what its getResults() resolves to (a model or null, or a Collection). */
1171
+ type RelationValue<M, K extends keyof M> = M[K] extends () => {
1172
+ getResults(): Promise<infer T>;
1173
+ } ? T : never;
1174
+
1175
+ type AnyRelation = Relation<any, any, any>;
1176
+ /** A constraint on an eager load, withCount() or whereHas(): (query) => query.where(…). */
1177
+ type RelationConstraint = (query: AnyRelation) => unknown;
1178
+ /** with('author'), with(['author', 'comments.user']), with({ comments: (q) => q.latest() }), with('author:id,name'). */
1179
+ type EagerLoadSpec = string | string[] | Record<string, RelationConstraint>;
1180
+ type AnyFunction = (...args: unknown[]) => unknown;
1181
+ /**
1182
+ * Eloquent's builder: the query builder of one model class. Rows come back as hydrated models, global scopes are
1183
+ * applied when the query runs (grouped so an orWhere can't escape them), and unknown methods call the model's local
1184
+ * scopes. Everything the query builder does (pagination, chunk, lazy, …) returns models here.
1185
+ */
1186
+ declare class Builder<M extends Model = Model> extends Builder$1<M> {
1187
+ readonly model: M;
1188
+ protected scopes: Map<string, GlobalScope>;
1189
+ protected removedScopes: string[];
1190
+ protected eagerLoad: Map<string, RelationConstraint | undefined>;
1191
+ constructor(model: M);
1192
+ getModel(): M;
1193
+ /** The model class's static scope<Name> method for a builder method name, if any. */
1194
+ localScope(name: string): AnyFunction | undefined;
1195
+ /** Runs a scope; the wheres it adds are grouped when they contain an "or" (Laravel's callScope). */
1196
+ callScope(scope: (query: this) => unknown): this;
1197
+ withGlobalScope(name: string, scope: GlobalScope): this;
1198
+ /** Removes a global scope by name or Scope class. */
1199
+ withoutGlobalScope(scope: string | (abstract new (...args: never[]) => unknown)): this;
1200
+ /** Removes every global scope, or the given ones. */
1201
+ withoutGlobalScopes(scopes?: Array<string | (abstract new (...args: never[]) => unknown)>): this;
1202
+ removedScopeNames(): string[];
1203
+ /** A copy of this query with every global scope applied (Laravel's applyScopes()). */
1204
+ applyScopes(): this;
1205
+ /** Groups [0, count) and [count, …) separately when either contains an "or", so scopes combine with "and". */
1206
+ protected addNewWheresWithinGroup(count: number): void;
1207
+ private groupWhereSlice;
1208
+ where(column: Column<M> | Expression, value: unknown): this;
1209
+ where(column: Column<M> | Expression, operator: Operator | string, value: unknown): this;
1210
+ where(conditions: Row): this;
1211
+ where(callback: (query: this) => unknown): this;
1212
+ orWhere(column: Column<M> | Expression, value: unknown): this;
1213
+ orWhere(column: Column<M> | Expression, operator: Operator | string, value: unknown): this;
1214
+ orWhere(conditions: Row): this;
1215
+ orWhere(callback: (query: this) => unknown): this;
1216
+ whereIn(column: Column<M> | Expression, values: readonly unknown[] | Builder$1<unknown>): this;
1217
+ whereNotIn(column: Column<M> | Expression, values: readonly unknown[] | Builder$1<unknown>): this;
1218
+ whereNull(columns: Column<M> | Expression | Array<Column<M> | Expression>): this;
1219
+ whereNotNull(columns: Column<M> | Expression | Array<Column<M> | Expression>): this;
1220
+ whereBetween(column: Column<M> | Expression, values: readonly [unknown, unknown]): this;
1221
+ orderBy(column: Column<M> | Expression, direction?: Direction | Uppercase<Direction>): this;
1222
+ /** Newest first by the model's created_at column (or the given one). */
1223
+ latest(column?: Column<M> | Expression): this;
1224
+ oldest(column?: Column<M> | Expression): this;
1225
+ select(...columns: Array<Column<M> | Expression | Array<Column<M> | Expression>>): this;
1226
+ /** where key = id (or key in ids). */
1227
+ whereKey(id: unknown): this;
1228
+ whereKeyNot(id: unknown): this;
1229
+ /** Runs the query, hydrates models, fires their retrieved events and eager loads the with() relations. */
1230
+ runSelect(): Promise<M[]>;
1231
+ /**
1232
+ * Relations to load with the results, one query per relation (and per nesting level):
1233
+ * with('author'), with('comments.author'), with({ comments: (q) => q.where('approved', true) }), with('author:id,name').
1234
+ */
1235
+ with(...relations: EagerLoadSpec[]): this;
1236
+ /** Removes eager loads (including the model's default `with`). */
1237
+ without(...relations: string[]): this;
1238
+ getEagerLoads(): Map<string, RelationConstraint | undefined>;
1239
+ /** Loads every top-level with() relation onto the models (nested ones are passed down to each relation query). */
1240
+ eagerLoadRelations(models: M[]): Promise<M[]>;
1241
+ /** The relation instance for a name, without its per-parent constraints. */
1242
+ getRelation(name: string): AnyRelation;
1243
+ protected eagerLoadRelation(models: M[], name: string, constraint: RelationConstraint | undefined): Promise<void>;
1244
+ private addEagerLoad;
1245
+ private relationsNestedUnder;
1246
+ /**
1247
+ * Adds `<relation>_count` columns: withCount('comments'), withCount({ comments: (q) => q.where('approved', true) }),
1248
+ * withCount('comments as approved_count'). Global scopes of the related model (soft deletes) apply.
1249
+ */
1250
+ withCount(...relations: EagerLoadSpec[]): this;
1251
+ /**
1252
+ * Rows that have related rows: has('comments'), has('comments', '>=', 3), has('comments.author').
1253
+ * Uses `exists (…)` for the common "at least one"/"none" cases and a count subquery otherwise.
1254
+ */
1255
+ has(relation: string, operator?: string, count?: number, boolean?: 'and' | 'or', callback?: RelationConstraint): this;
1256
+ orHas(relation: string, operator?: string, count?: number): this;
1257
+ doesntHave(relation: string, boolean?: 'and' | 'or', callback?: RelationConstraint): this;
1258
+ orDoesntHave(relation: string): this;
1259
+ /** Rows with related rows matching the callback: whereHas('comments', (q) => q.where('approved', true)). */
1260
+ whereHas(relation: string, callback?: RelationConstraint, operator?: string, count?: number): this;
1261
+ orWhereHas(relation: string, callback?: RelationConstraint, operator?: string, count?: number): this;
1262
+ whereDoesntHave(relation: string, callback?: RelationConstraint): this;
1263
+ orWhereDoesntHave(relation: string, callback?: RelationConstraint): this;
1264
+ /** has('comments.author'): whereHas('comments', q => q.has('author')) */
1265
+ private hasNested;
1266
+ private normalizeRelationSpecs;
1267
+ /** Models from raw rows, marked as existing. */
1268
+ hydrate(rows: readonly Row[]): M[];
1269
+ aggregate(fn: 'count' | 'min' | 'max' | 'sum' | 'avg', column: ColumnRef): Promise<unknown>;
1270
+ exists(): Promise<boolean>;
1271
+ /** The column's values, through the model's casts and accessors. */
1272
+ pluck<V = unknown>(column: Column<M>): Promise<Collection<V>>;
1273
+ find(id: unknown): Promise<M | undefined>;
1274
+ findMany(ids: readonly unknown[]): Promise<Collection<M>>;
1275
+ /** find(), or ModelNotFoundError (a 404). With an array, every id must exist. */
1276
+ findOrFail(ids: readonly unknown[]): Promise<Collection<M>>;
1277
+ findOrFail(id: unknown): Promise<M>;
1278
+ findOr<R>(id: unknown, callback: () => R | Promise<R>): Promise<M | R>;
1279
+ firstOrFail(): Promise<M>;
1280
+ firstOr<R>(callback: () => R | Promise<R>): Promise<M | R>;
1281
+ firstWhere(column: Column<M> | Expression, operatorOrValue: unknown, value?: unknown): Promise<M | undefined>;
1282
+ /** A new, unsaved model of this query's class (mass assignment rules apply). */
1283
+ newModelInstance(attributes?: Row): M;
1284
+ make(attributes?: Row): M;
1285
+ create(attributes?: Row): Promise<M>;
1286
+ /** Creates without mass assignment protection. Never pass it request input. */
1287
+ forceCreate(attributes: Row): Promise<M>;
1288
+ /** The first match, or a new unsaved model with attributes + values. */
1289
+ firstOrNew(attributes: Row, values?: Row): Promise<M>;
1290
+ /** The first match, or a new saved model. A concurrent insert of the same unique key returns that row instead. */
1291
+ firstOrCreate(attributes: Row, values?: Row): Promise<M>;
1292
+ /** Tries to create; on a unique constraint violation, returns the existing row (Laravel's createOrFirst()). */
1293
+ createOrFirst(attributes: Row, values?: Row): Promise<M>;
1294
+ /** Updates the first match with values, or creates it. */
1295
+ updateOrCreate(attributes: Row, values?: Row): Promise<M>;
1296
+ /** Mass update (no model events); sets updated_at when the model uses timestamps. */
1297
+ update(values: Row): Promise<number>;
1298
+ /** Mass delete (no model events). With soft deletes this sets deleted_at on the matching rows instead. */
1299
+ delete(): Promise<number>;
1300
+ /** Deletes the matching rows for real, even with soft deletes. */
1301
+ forceDelete(): Promise<number>;
1302
+ /** Includes soft-deleted rows (withTrashed(false) is withoutTrashed()). */
1303
+ withTrashed(withTrashed?: boolean): this;
1304
+ /** Excludes soft-deleted rows explicitly. */
1305
+ withoutTrashed(): this;
1306
+ /** Only soft-deleted rows. */
1307
+ onlyTrashed(): this;
1308
+ /** Restores every matching row (deleted_at = null), trashed or not. */
1309
+ restore(): Promise<number>;
1310
+ protected addUpdatedAtColumn(values: Row): Row;
1311
+ toSql(): string;
1312
+ getBindings(): unknown[];
1313
+ clone(): Builder<M>;
1314
+ /** Nested where groups get a builder of the same model (without global scopes), so local scopes work inside them. */
1315
+ newQuery(): Builder$1<Row>;
1316
+ /** chunk() and lazy() order by the primary key when the query has no order. */
1317
+ protected enforceOrderBy(): void;
1318
+ protected defaultKeyName(): string;
1319
+ protected defaultPerPage(): number;
1320
+ }
1321
+
1322
+ /**
1323
+ * A custom cast (Laravel's CastsAttributes): get() turns the stored value into what the model exposes, set() turns
1324
+ * an assigned value back into what is stored.
1325
+ */
1326
+ interface CastsAttributes<TGet = unknown, TSet = TGet> {
1327
+ get(model: object, key: string, value: unknown, attributes: Row): TGet;
1328
+ set(model: object, key: string, value: TSet, attributes: Row): unknown;
1329
+ }
1330
+ /** A TypeScript enum object (string or numeric) used as a cast: casts = { status: PostStatus }. */
1331
+ type EnumLike = Record<string, string | number>;
1332
+ type BuiltInCast = 'int' | 'integer' | 'float' | 'double' | 'real' | 'string' | 'bool' | 'boolean' | 'array' | 'json' | 'object' | 'collection' | 'date' | 'datetime' | 'immutable_date' | 'immutable_datetime' | 'timestamp' | `decimal:${number}`;
1333
+ type CastDefinition = BuiltInCast | EnumLike | CastsAttributes | (new () => CastsAttributes);
1334
+ /** The values of a TypeScript enum. Numeric enums also map values back to names; those reverse entries are skipped. */
1335
+ declare function enumValues(cast: EnumLike): Array<string | number>;
1336
+ declare const isJsonCast: (cast: CastDefinition | undefined) => boolean;
1337
+ declare const isDateCast: (cast: CastDefinition | undefined) => boolean;
1338
+ /** Laravel's castAttribute(): the stored value → the value the model exposes. null stays null (except custom casts). */
1339
+ declare function castGet(model: object, key: string, cast: CastDefinition, value: unknown, attributes: Row, className: string): unknown;
1340
+ /** The value assigned to a cast attribute → the value stored in the model's attributes (and later bound). */
1341
+ declare function castSet(model: object, key: string, cast: CastDefinition, value: unknown, attributes: Row, className: string): unknown;
1342
+ /**
1343
+ * Laravel's originalIsEquivalent(): does the stored value still mean the same thing as the original?
1344
+ * Keeps save() from writing columns whose value only changed representation (1 vs true, '5' vs 5, same instant).
1345
+ */
1346
+ declare function isEquivalent(cast: CastDefinition | undefined, current: unknown, original: unknown, model: object, key: string, className: string): boolean;
1347
+
1348
+ declare const MANY: unique symbol;
1349
+ /** Type-level marker set by count(): make()/create() then return a Collection. */
1350
+ interface Many {
1351
+ readonly [MANY]: true;
1352
+ }
1353
+ /** What make()/create() return: a model, or a Collection after count(). */
1354
+ type FactoryResult<F, M> = F extends Many ? Collection<M> : M;
1355
+ /** What raw() returns: the attributes, or a list of them after count(). */
1356
+ type RawResult<F> = F extends Many ? Row[] : Row;
1357
+ /** Which model a state is being made for: its index in count() and the total. */
1358
+ interface StateContext {
1359
+ index: number;
1360
+ count: number;
1361
+ }
1362
+ type State = Row | ((attributes: Row, context: StateContext) => Row);
1363
+ type AnyFactory = Factory<any>;
1364
+ interface HasRelationship {
1365
+ factory: AnyFactory;
1366
+ relationship: string;
1367
+ pivot: Row;
1368
+ }
1369
+ interface ForRelationship {
1370
+ parent: AnyFactory | Model;
1371
+ relationship: string;
1372
+ resolved?: Model;
1373
+ }
1374
+ /** The builder state newInstance() copies and changes. */
1375
+ interface FactoryState<M extends Model> {
1376
+ countValue: number | undefined;
1377
+ states: State[];
1378
+ hasRelations: HasRelationship[];
1379
+ forRelations: ForRelationship[];
1380
+ afterMakingCallbacks: Array<(model: M) => unknown>;
1381
+ afterCreatingCallbacks: Array<(model: M) => unknown>;
1382
+ }
1383
+ /**
1384
+ * Laravel's model factories: `class UserFactory extends Factory<User> { model = User; definition() { … } }`,
1385
+ * then `await User.factory().count(3).create()`, `UserFactory.new().unverified().make()`.
1386
+ * Every builder method returns a new factory, so a base factory can be reused.
1387
+ */
1388
+ declare abstract class Factory<M extends Model = Model> {
1389
+ /** The model class this factory makes. */
1390
+ abstract model: new () => M;
1391
+ /** The default attributes. Values may be factories (created for their key) or (attributes) => value functions. */
1392
+ abstract definition(): Row;
1393
+ protected countValue: number | undefined;
1394
+ protected states: State[];
1395
+ protected hasRelations: HasRelationship[];
1396
+ protected forRelations: ForRelationship[];
1397
+ protected afterMakingCallbacks: Array<(model: M) => unknown>;
1398
+ protected afterCreatingCallbacks: Array<(model: M) => unknown>;
1399
+ /** A new factory with the given state (Laravel's Factory::new()). */
1400
+ static new<F extends AnyFactory>(this: new () => F, state?: State): F;
1401
+ /** Registers factory classes for Model.factory() (discoverFactories() does this for database/factories). */
1402
+ static register(...factories: Array<new () => AnyFactory>): void;
1403
+ /** The registered factory for a model class. */
1404
+ static forModel<M extends Model>(model: new () => M): Factory<M>;
1405
+ /** Hook for afterMaking()/afterCreating() registrations; runs in new(). */
1406
+ configure(): this;
1407
+ /** How many models make()/create() produce; they then return a Collection. */
1408
+ count(count: number): this & Many;
1409
+ /** Overrides attributes: state({ admin: true }) or state((attributes) => ({ … })). */
1410
+ state(state: State): this;
1411
+ /** Cycles through states per model: sequence({ role: 'admin' }, { role: 'user' }). */
1412
+ sequence(...states: State[]): this;
1413
+ /** deleted_at = now, for soft-deleting models. */
1414
+ trashed(): this;
1415
+ /** Creates related models for each created model: has(Post.factory().count(3)) (relationship default: 'posts'). */
1416
+ has(factory: AnyFactory, relationship?: string, pivot?: Row): this;
1417
+ /** Sets a belongsTo parent: for(User.factory()) or for(user) (relationship default: 'user'). Created once. */
1418
+ for(parent: AnyFactory | Model, relationship?: string): this;
1419
+ afterMaking(callback: (model: M) => unknown): this;
1420
+ afterCreating(callback: (model: M) => unknown): this;
1421
+ /** The attributes only, without a model (a Row, or a Row[] after count()). */
1422
+ raw(attributes?: Row): Promise<RawResult<this>>;
1423
+ /** Unsaved models (afterMaking callbacks run). */
1424
+ make(attributes?: Row): Promise<FactoryResult<this, M>>;
1425
+ /** Saved models, with their has() relations (afterCreating callbacks run). */
1426
+ create(attributes?: Row): Promise<FactoryResult<this, M>>;
1427
+ makeOne(attributes?: Row): Promise<M>;
1428
+ createOne(attributes?: Row): Promise<M>;
1429
+ /** One model per record (or `count` models). */
1430
+ createMany(records: number | Row[]): Promise<Collection<M>>;
1431
+ protected newInstance(changes: Partial<FactoryState<M>>): this;
1432
+ protected makeModels(attributes: Row): Promise<M[]>;
1433
+ /** definition() + states + overrides + for() parents, with factory and function values expanded. */
1434
+ protected attributesFor(overrides: Row, index: number): Promise<Row>;
1435
+ private parentAttributes;
1436
+ private createChildren;
1437
+ private relationOn;
1438
+ private result;
1439
+ }
1440
+ /** Imports every factory file in a directory and registers its exported Factory classes. */
1441
+ declare function discoverFactories(path: string): Promise<void>;
1442
+
1443
+ /** Laravel's model events. The -ing events of save, delete and restore can cancel by returning false. */
1444
+ declare const MODEL_EVENTS: readonly ["retrieved", "creating", "created", "updating", "updated", "saving", "saved", "deleting", "deleted", "restoring", "restored", "forceDeleting", "forceDeleted"];
1445
+ type ModelEvent = (typeof MODEL_EVENTS)[number];
1446
+ /** A listener receives the model. Returning false from a halting event cancels the operation. */
1447
+ type ModelListener<M> = (model: M) => unknown;
1448
+ /** 'eloquent.created: Post' (Laravel uses the fully qualified class name; Oriel uses the class name). */
1449
+ declare function modelEventName(event: string, className: string): string;
1450
+
1451
+ /** post.author(): this model (the child) holds the related model's key. */
1452
+ declare class BelongsTo<R extends Model, P extends Model = Model> extends Relation<R, P, R | null> {
1453
+ readonly foreignKey: string;
1454
+ readonly ownerKey: string;
1455
+ /**
1456
+ * @param foreignKey the column on the child ('user_id')
1457
+ * @param ownerKey the key on the related model it points at ('id')
1458
+ */
1459
+ constructor(related: R, child: P, foreignKey: string, ownerKey: string, relationName?: string);
1460
+ getChild(): P;
1461
+ getForeignKeyName(): string;
1462
+ getQualifiedForeignKeyName(): string;
1463
+ getOwnerKeyName(): string;
1464
+ getQualifiedOwnerKeyName(): string;
1465
+ addConstraints(): void;
1466
+ addEagerConstraints(models: P[]): void;
1467
+ getResults(): Promise<R | null>;
1468
+ initRelation(models: P[], relation: string): P[];
1469
+ match(models: P[], results: R[], relation: string): P[];
1470
+ /** Points the child at `model` (sets the foreign key and the loaded relation). Save the child afterwards. */
1471
+ associate(model: R | null): P;
1472
+ /** Clears the foreign key. Save the child afterwards. */
1473
+ dissociate(): P;
1474
+ getRelationExistenceQuery(query: Builder<R>, _parentQuery: Builder<P>, columns?: ColumnRef[]): Builder<R>;
1475
+ /** The loaded-relation name: the resolved name, else the related class in camelCase (author → pass it explicitly). */
1476
+ private relationKey;
1477
+ }
1478
+
1479
+ /** attach()/sync() accept ids, models, or { id: pivotAttributes }. */
1480
+ type PivotIds = unknown | readonly unknown[] | Record<string, Row>;
1481
+ interface SyncChanges {
1482
+ attached: unknown[];
1483
+ detached: unknown[];
1484
+ updated: unknown[];
1485
+ }
1486
+ /**
1487
+ * Many-to-many through a pivot table: post.tags() → belongsToMany(Tag) over post_tag (post_id, tag_id).
1488
+ * Each related model carries its pivot row as `tag.pivot` (withPivot() adds columns, withTimestamps() the timestamps).
1489
+ */
1490
+ declare class BelongsToMany<R extends Model, P extends Model = Model> extends Relation<R, P, Collection<R>> {
1491
+ readonly table: string;
1492
+ readonly foreignPivotKey: string;
1493
+ readonly relatedPivotKey: string;
1494
+ readonly parentKey: string;
1495
+ readonly relatedKey: string;
1496
+ protected pivotColumns: string[];
1497
+ protected pivotTimestamps: [string, string] | undefined;
1498
+ constructor(related: R, parent: P, table: string, foreignPivotKey: string, relatedPivotKey: string, parentKey: string, relatedKey: string);
1499
+ qualifyPivotColumn(column: string): string;
1500
+ getTable(): string;
1501
+ getForeignPivotKeyName(): string;
1502
+ getRelatedPivotKeyName(): string;
1503
+ getParentKey(): unknown;
1504
+ addConstraints(): void;
1505
+ addEagerConstraints(models: P[]): void;
1506
+ /** Extra pivot columns to load onto tag.pivot. */
1507
+ withPivot(...columns: Array<string | string[]>): this;
1508
+ /** The pivot table has created_at/updated_at: they are set on attach() and loaded onto tag.pivot. */
1509
+ withTimestamps(createdAt?: string, updatedAt?: string): this;
1510
+ wherePivot(column: string, operator: unknown, value?: unknown): this;
1511
+ wherePivotIn(column: string, values: readonly unknown[]): this;
1512
+ /** Selects the related columns plus the pivot columns (as pivot_*), then moves those onto each model's pivot. */
1513
+ runSelect(): Promise<R[]>;
1514
+ getResults(): Promise<Collection<R>>;
1515
+ initRelation(models: P[], relation: string): P[];
1516
+ match(models: P[], results: R[], relation: string): P[];
1517
+ getRelationExistenceQuery(query: Builder<R>, _parentQuery: Builder<P>, columns?: ColumnRef[]): Builder<R>;
1518
+ /** Inserts pivot rows for ids (or models, or { id: attributes }), with shared extra attributes. */
1519
+ attach(ids: PivotIds, attributes?: Row): Promise<void>;
1520
+ /** Deletes pivot rows for ids, or every pivot row of the parent. Returns how many were deleted. */
1521
+ detach(ids?: PivotIds): Promise<number>;
1522
+ /** Makes the pivot rows exactly ids: attaches the missing ones, detaches the others, updates given attributes. */
1523
+ sync(ids: PivotIds, detaching?: boolean): Promise<SyncChanges>;
1524
+ syncWithoutDetaching(ids: PivotIds): Promise<SyncChanges>;
1525
+ /** Attaches the ids that aren't attached and detaches the ones that are. */
1526
+ toggle(ids: PivotIds): Promise<{
1527
+ attached: unknown[];
1528
+ detached: unknown[];
1529
+ }>;
1530
+ /** Updates the pivot row of one related id. Returns the number of affected rows. */
1531
+ updateExistingPivot(id: unknown, attributes: Row): Promise<number>;
1532
+ /** Saves a new related model and attaches it. */
1533
+ create(attributes?: Row, pivotAttributes?: Row): Promise<R>;
1534
+ /** Saves a related model and attaches it. */
1535
+ save(model: R, pivotAttributes?: Row): Promise<R>;
1536
+ /** A plain query builder on the pivot table. */
1537
+ newPivotQuery(): Builder$1<Row>;
1538
+ private currentPivotIds;
1539
+ private pivotSelectColumns;
1540
+ private hydratePivot;
1541
+ private pivotRow;
1542
+ /** ids → Map(id → extra pivot attributes). Models become their related key. */
1543
+ private parseIds;
1544
+ private idOf;
1545
+ private isModel;
1546
+ /** Object keys are strings; numeric ones go back to numbers for integer keys. */
1547
+ private castKey;
1548
+ }
1549
+
1550
+ /** For morphOne/morphMany: the qualified type column and the parent's morph class stored in it. */
1551
+ interface MorphConstraint {
1552
+ type: string;
1553
+ value: string;
1554
+ }
1555
+ /**
1556
+ * The shared half of hasOne, hasMany, morphOne and morphMany: the related table holds the foreign key (and, for
1557
+ * the morph relations, the parent's type).
1558
+ */
1559
+ declare abstract class HasOneOrMany<R extends Model, P extends Model, Result> extends Relation<R, P, Result> {
1560
+ readonly foreignKey: string;
1561
+ readonly localKey: string;
1562
+ readonly morph?: MorphConstraint | undefined;
1563
+ /**
1564
+ * @param foreignKey the qualified foreign key on the related table ('comments.post_id')
1565
+ * @param localKey the key on the parent it points at ('id')
1566
+ * @param morph the type column and value, for morphOne/morphMany
1567
+ */
1568
+ constructor(related: R, parent: P, foreignKey: string, localKey: string, morph?: MorphConstraint | undefined);
1569
+ /** 'post_id' */
1570
+ getForeignKeyName(): string;
1571
+ getQualifiedForeignKeyName(): string;
1572
+ getParentKey(): unknown;
1573
+ getQualifiedParentKeyName(): string;
1574
+ /** 'commentable_type' for a morph relation. */
1575
+ getMorphType(): string | undefined;
1576
+ /** The parent's value in the type column, for a morph relation. */
1577
+ getMorphClass(): string | undefined;
1578
+ addConstraints(): void;
1579
+ addEagerConstraints(models: P[]): void;
1580
+ /** Related models grouped by their foreign key, as strings: bigint and integer keys compare equal. */
1581
+ protected buildDictionary(results: R[]): Map<string, R[]>;
1582
+ /** New related models get the parent's key (and type): post.comments().create({ body }) sets post_id. */
1583
+ newModelInstance(attributes?: Row): R;
1584
+ /** Sets the foreign key (and type) on an existing model and saves it. */
1585
+ save(model: R): Promise<R>;
1586
+ protected setForeignAttributes(model: R): R;
1587
+ saveMany(models: Iterable<R>): Promise<R[]>;
1588
+ createMany(records: Row[]): Promise<R[]>;
1589
+ getRelationExistenceQuery(query: Builder<R>, _parentQuery: Builder<P>, columns?: ColumnRef[]): Builder<R>;
1590
+ }
1591
+
1592
+ /** post.comments(): many related rows hold the parent's key. */
1593
+ declare class HasMany<R extends Model, P extends Model = Model> extends HasOneOrMany<R, P, Collection<R>> {
1594
+ getResults(): Promise<Collection<R>>;
1595
+ initRelation(models: P[], relation: string): P[];
1596
+ match(models: P[], results: R[], relation: string): P[];
1597
+ }
1598
+
1599
+ /**
1600
+ * Related rows reached through an intermediate model: country.posts() → hasManyThrough(Post, User):
1601
+ * posts join users on users.id = posts.user_id where users.country_id = countries.id.
1602
+ */
1603
+ declare class HasManyThrough<R extends Model, P extends Model = Model, T extends Model = Model> extends Relation<R, P, Collection<R>> {
1604
+ readonly throughParent: T;
1605
+ readonly firstKey: string;
1606
+ readonly secondKey: string;
1607
+ readonly localKey: string;
1608
+ readonly secondLocalKey: string;
1609
+ /** The through key of each loaded model (kept off its attributes, so it never reaches toJSON()). */
1610
+ private readonly throughKeys;
1611
+ /**
1612
+ * @param firstKey on the through table, pointing at the far parent ('users.country_id')
1613
+ * @param secondKey on the related table, pointing at the through model ('posts.user_id')
1614
+ * @param localKey on the far parent ('countries.id')
1615
+ * @param secondLocalKey on the through model ('users.id')
1616
+ */
1617
+ constructor(related: R, farParent: P, throughParent: T, firstKey: string, secondKey: string, localKey: string, secondLocalKey: string);
1618
+ /** users.country_id */
1619
+ getQualifiedFirstKeyName(): string;
1620
+ /** posts.user_id */
1621
+ getQualifiedForeignKeyName(): string;
1622
+ /** users.id */
1623
+ getQualifiedParentKeyName(): string;
1624
+ /** countries.id */
1625
+ getQualifiedLocalKeyName(): string;
1626
+ addConstraints(): void;
1627
+ addEagerConstraints(models: P[]): void;
1628
+ /** Selects the related columns plus the through key, then moves the key off the attributes. */
1629
+ runSelect(): Promise<R[]>;
1630
+ getResults(): Promise<Collection<R>>;
1631
+ getEager(): Promise<Collection<R>>;
1632
+ initRelation(models: P[], relation: string): P[];
1633
+ match(models: P[], results: R[], relation: string): P[];
1634
+ getRelationExistenceQuery(query: Builder<R>, _parentQuery: Builder<P>, columns?: ColumnRef[]): Builder<R>;
1635
+ }
1636
+
1637
+ /** user.profile(): one related row holds the parent's key. */
1638
+ declare class HasOne<R extends Model, P extends Model = Model> extends HasOneOrMany<R, P, R | null> {
1639
+ getResults(): Promise<R | null>;
1640
+ initRelation(models: P[], relation: string): P[];
1641
+ match(models: P[], results: R[], relation: string): P[];
1642
+ }
1643
+
1644
+ /** post.comments() → morphMany(Comment, 'commentable'): comments.commentable_id + commentable_type = 'Post'. */
1645
+ declare class MorphMany<R extends Model, P extends Model = Model> extends HasMany<R, P> {
1646
+ /**
1647
+ * @param morphType the qualified type column ('comments.commentable_type')
1648
+ * @param foreignKey the qualified id column ('comments.commentable_id')
1649
+ */
1650
+ constructor(related: R, parent: P, morphType: string, foreignKey: string, localKey: string);
1651
+ }
1652
+
1653
+ /** user.image() → morphOne(Image, 'imageable'): images.imageable_id + imageable_type = 'User'. */
1654
+ declare class MorphOne<R extends Model, P extends Model = Model> extends HasOne<R, P> {
1655
+ constructor(related: R, parent: P, morphType: string, foreignKey: string, localKey: string);
1656
+ }
1657
+
1658
+ /**
1659
+ * comment.commentable() → morphTo('commentable'): the parent's class comes from commentable_type (a morph map alias
1660
+ * or a class name) and its key from commentable_id. Eager loading runs one query per distinct type.
1661
+ */
1662
+ declare class MorphTo<R extends Model = Model, P extends Model = Model> extends BelongsTo<R, P> {
1663
+ readonly morphTypeColumn: string;
1664
+ readonly ownerKeyOverride: string | undefined;
1665
+ /** Parents grouped by type, then by id, while eager loading. */
1666
+ private dictionary;
1667
+ /** The stored type each eager result was loaded for (an alias or a class name), for match(). */
1668
+ private resultTypes;
1669
+ /**
1670
+ * @param related an instance of the current type's class (the child's own class when the type is empty)
1671
+ * @param morphType the type column on the child ('commentable_type')
1672
+ * @param ownerKey the key on the parent (default: each class's primary key)
1673
+ */
1674
+ constructor(related: R, child: P, foreignKey: string, morphTypeColumn: string, ownerKeyOverride: string | undefined, relationName: string);
1675
+ getMorphType(): string;
1676
+ addConstraints(): void;
1677
+ getResults(): Promise<R | null>;
1678
+ /** Groups the children by type and id; the queries run in getEager(). */
1679
+ addEagerConstraints(models: P[]): void;
1680
+ /** One query per type, with this relation's constraints and nested eager loads. */
1681
+ getEager(): Promise<Collection<R>>;
1682
+ match(models: P[], results: R[], relation: string): P[];
1683
+ /** Points the child at `model`: sets the id and the type columns and the loaded relation. */
1684
+ associate(model: R | null): P;
1685
+ getRelationExistenceQuery(): Builder<R>;
1686
+ }
1687
+
1688
+ type Instance<C extends typeof Model> = InstanceType<C>;
1689
+ type ScopeClass = abstract new (...args: never[]) => unknown;
1690
+ /** Laravel's date serialization: ISO 8601 in UTC with microseconds (2026-01-02T03:04:05.000000Z). */
1691
+ declare function serializeDate(date: Date): string;
1692
+ /**
1693
+ * Eloquent's Model: an Active Record over one table.
1694
+ *
1695
+ * Config lives in instance fields, as in Laravel: `protected fillable = ['title']`, `protected casts = {…}`,
1696
+ * `protected hidden = ['password']`, `protected table = 'posts'`. Attribute columns are never declared as class
1697
+ * fields (they would shadow the Proxy); their types come from `oriel model:types`, or from `declare title: string`.
1698
+ * `new Post()` takes no arguments: use Post.make(attrs), Post.create(attrs) or new Post().fill(attrs).
1699
+ */
1700
+ declare class Model implements ModelInstance {
1701
+ static CREATED_AT: string | null;
1702
+ static UPDATED_AT: string | null;
1703
+ static DELETED_AT: string;
1704
+ /** The table (default: the snake_case plural of the class name: BlogPost → blog_posts). */
1705
+ protected table: string | undefined;
1706
+ protected primaryKey: string;
1707
+ protected keyType: 'int' | 'string';
1708
+ incrementing: boolean;
1709
+ /** Attributes that fill()/create() may set. */
1710
+ protected fillable: string[];
1711
+ /** Attributes fill() never sets. ['*'] (the default) guards everything that isn't fillable. */
1712
+ protected guarded: string[];
1713
+ protected casts: Readonly<Record<string, CastDefinition>>;
1714
+ /** Left out of toArray()/toJSON(). */
1715
+ protected hidden: string[];
1716
+ /** When non-empty, only these are in toArray()/toJSON(). */
1717
+ protected visible: string[];
1718
+ /** Accessor-only attributes added to toArray()/toJSON(). */
1719
+ protected appends: string[];
1720
+ timestamps: boolean;
1721
+ /** Turns on soft deletes (Laravel's `use SoftDeletes`): deleted_at instead of a real delete. */
1722
+ protected softDeletes: boolean;
1723
+ /** The connection name (default: config('database.default')). */
1724
+ protected connection: string | undefined;
1725
+ protected perPage: number;
1726
+ /** Relations every query of this model eager loads (Laravel's $with). */
1727
+ protected with: string[];
1728
+ /** Relation counts every query of this model adds (Laravel's $withCount). */
1729
+ protected withCount: string[];
1730
+ exists: boolean;
1731
+ wasRecentlyCreated: boolean;
1732
+ protected forceDeleting: boolean;
1733
+ protected attributes: Row;
1734
+ protected original: Row;
1735
+ protected changes: Row;
1736
+ protected relations: Record<string, unknown>;
1737
+ /** Decoded json/array/object/collection values, so in-place changes are seen by save(). */
1738
+ protected castCache: Map<string, {
1739
+ raw: unknown;
1740
+ value: unknown;
1741
+ }>;
1742
+ constructor();
1743
+ /** Runs booting()/booted() once per class, the first time the class is instantiated. */
1744
+ static bootIfNotBooted(): void;
1745
+ /**
1746
+ * Framework hook: installs the static scope proxies (Post.published()) and, with `softDeletes = true`, the soft
1747
+ * delete scope. Overrides must call super.boot().
1748
+ */
1749
+ static boot(): void;
1750
+ /** Runs before boot(). */
1751
+ static booting(): void;
1752
+ /** Register global scopes and model event listeners here: static booted() { this.addGlobalScope(…) }. */
1753
+ static booted(): void;
1754
+ /**
1755
+ * Forgets which classes are booted, and their global scopes (Laravel's clearBootedModels()), so the next use boots
1756
+ * them again: booted() re-registers its scopes and event listeners against the current application. Every new
1757
+ * application does this (DatabaseServiceProvider.register()).
1758
+ */
1759
+ static clearBootedModels(): void;
1760
+ /** One cached instance per class, used by static methods to read config (table, key, casts, …). */
1761
+ static prototypeInstance<M extends Model>(this: new () => M): M;
1762
+ /** A new, unsaved model filled with attributes (mass assignment rules apply). */
1763
+ static make<M extends Model>(this: new () => M, attributes?: Row): M;
1764
+ /**
1765
+ * Adds a global scope to every query of this class: addGlobalScope('published', q => …),
1766
+ * addGlobalScope(new ActiveScope()) (named after its class) or addGlobalScope(q => …).
1767
+ */
1768
+ static addGlobalScope(scope: Scope | ScopeCallback): string;
1769
+ static addGlobalScope(name: string, scope: GlobalScope): string;
1770
+ static hasGlobalScope(scope: string | ScopeClass): boolean;
1771
+ static getGlobalScopes(): Map<string, GlobalScope>;
1772
+ /** Registers a listener for one of this model's events ('eloquent.<event>: <Class>'). Needs an EventDispatcher. */
1773
+ static registerModelEvent<C extends typeof Model>(this: C, event: ModelEvent, callback: ModelListener<InstanceType<C>>): void;
1774
+ static retrieved<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
1775
+ static creating<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
1776
+ static created<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
1777
+ static updating<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
1778
+ static updated<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
1779
+ static saving<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
1780
+ static saved<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
1781
+ static deleting<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
1782
+ static deleted<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
1783
+ static restoring<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
1784
+ static restored<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
1785
+ static forceDeleting<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
1786
+ static forceDeleted<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
1787
+ /**
1788
+ * Registers observers: every method named after a model event (created, updating, …) becomes a listener.
1789
+ * Observer classes are resolved from the container.
1790
+ */
1791
+ static observe(...observers: Array<object | (new () => object)>): void;
1792
+ /** Runs fn with model events off, for this async context only. */
1793
+ static withoutEvents<R>(fn: () => R): R;
1794
+ /** A new query of this model, with its global scopes. */
1795
+ static query<C extends typeof Model>(this: C): ModelBuilder<C>;
1796
+ static where<C extends typeof Model>(this: C, ...args: WhereArgs<Instance<C>, ModelBuilder<C>>): ModelBuilder<C>;
1797
+ static whereKey<C extends typeof Model>(this: C, id: unknown): ModelBuilder<C>;
1798
+ static whereIn<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, values: readonly unknown[]): ModelBuilder<C>;
1799
+ static whereNotIn<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, values: readonly unknown[]): ModelBuilder<C>;
1800
+ static whereNull<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression): ModelBuilder<C>;
1801
+ static whereNotNull<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression): ModelBuilder<C>;
1802
+ static whereBetween<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, values: readonly [unknown, unknown]): ModelBuilder<C>;
1803
+ static whereColumn<C extends typeof Model>(this: C, first: Column<Instance<C>>, operatorOrSecond: string, second?: Column<Instance<C>>): ModelBuilder<C>;
1804
+ static whereRaw<C extends typeof Model>(this: C, sql: string, bindings?: readonly unknown[]): ModelBuilder<C>;
1805
+ static select<C extends typeof Model>(this: C, ...columns: Array<Column<Instance<C>> | Expression>): ModelBuilder<C>;
1806
+ static orderBy<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, direction?: Direction): ModelBuilder<C>;
1807
+ static latest<C extends typeof Model>(this: C, column?: Column<Instance<C>>): ModelBuilder<C>;
1808
+ static oldest<C extends typeof Model>(this: C, column?: Column<Instance<C>>): ModelBuilder<C>;
1809
+ static inRandomOrder<C extends typeof Model>(this: C): ModelBuilder<C>;
1810
+ static limit<C extends typeof Model>(this: C, count: number): ModelBuilder<C>;
1811
+ static take<C extends typeof Model>(this: C, count: number): ModelBuilder<C>;
1812
+ static withoutGlobalScope<C extends typeof Model>(this: C, scope: string | ScopeClass): ModelBuilder<C>;
1813
+ static withoutGlobalScopes<C extends typeof Model>(this: C, scopes?: Array<string | ScopeClass>): ModelBuilder<C>;
1814
+ /** Eager loads relations: Post.with('author', 'comments.user').get(). */
1815
+ static with<C extends typeof Model>(this: C, ...relations: EagerLoadSpec[]): ModelBuilder<C>;
1816
+ static withCount<C extends typeof Model>(this: C, ...relations: EagerLoadSpec[]): ModelBuilder<C>;
1817
+ static has<C extends typeof Model>(this: C, relation: string, operator?: string, count?: number): ModelBuilder<C>;
1818
+ static whereHas<C extends typeof Model>(this: C, relation: string, callback?: RelationConstraint, operator?: string, count?: number): ModelBuilder<C>;
1819
+ static doesntHave<C extends typeof Model>(this: C, relation: string): ModelBuilder<C>;
1820
+ static whereDoesntHave<C extends typeof Model>(this: C, relation: string, callback?: RelationConstraint): ModelBuilder<C>;
1821
+ /** Soft deletes: include trashed rows. */
1822
+ static withTrashed<C extends typeof Model>(this: C): ModelBuilder<C>;
1823
+ /** Soft deletes: only trashed rows. */
1824
+ static onlyTrashed<C extends typeof Model>(this: C): ModelBuilder<C>;
1825
+ static withoutTrashed<C extends typeof Model>(this: C): ModelBuilder<C>;
1826
+ static all<C extends typeof Model>(this: C): Promise<Collection<Instance<C>>>;
1827
+ static find<C extends typeof Model>(this: C, id: unknown): Promise<Instance<C> | undefined>;
1828
+ static findOrFail<C extends typeof Model>(this: C, ids: readonly unknown[]): Promise<Collection<Instance<C>>>;
1829
+ static findOrFail<C extends typeof Model>(this: C, id: unknown): Promise<Instance<C>>;
1830
+ static findMany<C extends typeof Model>(this: C, ids: readonly unknown[]): Promise<Collection<Instance<C>>>;
1831
+ static first<C extends typeof Model>(this: C): Promise<Instance<C> | undefined>;
1832
+ static firstOrFail<C extends typeof Model>(this: C): Promise<Instance<C>>;
1833
+ static firstWhere<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, operatorOrValue: unknown, value?: unknown): Promise<Instance<C> | undefined>;
1834
+ static count(): Promise<number>;
1835
+ static exists(): Promise<boolean>;
1836
+ static pluck<C extends typeof Model, V = unknown>(this: C, column: Column<Instance<C>>): Promise<Collection<V>>;
1837
+ static paginate<C extends typeof Model>(this: C, perPage?: number, columns?: string[], pageName?: string, page?: number): Promise<LengthAwarePaginator<Instance<C>>>;
1838
+ static simplePaginate<C extends typeof Model>(this: C, perPage?: number, columns?: string[], pageName?: string, page?: number): Promise<Paginator<Instance<C>>>;
1839
+ static cursorPaginate<C extends typeof Model>(this: C, perPage?: number, columns?: string[], cursorName?: string, cursor?: Cursor | string): Promise<CursorPaginator<Instance<C>>>;
1840
+ static chunk<C extends typeof Model>(this: C, count: number, callback: (models: Collection<Instance<C>>, page: number) => unknown): Promise<boolean>;
1841
+ static chunkById<C extends typeof Model>(this: C, count: number, callback: (models: Collection<Instance<C>>, page: number) => unknown): Promise<boolean>;
1842
+ static each<C extends typeof Model>(this: C, callback: (model: Instance<C>, index: number) => unknown, count?: number): Promise<boolean>;
1843
+ static lazy<C extends typeof Model>(this: C, chunkSize?: number): LazyCollection<Instance<C>>;
1844
+ static lazyById<C extends typeof Model>(this: C, chunkSize?: number): LazyCollection<Instance<C>>;
1845
+ /** Creates and saves a model (mass assignment rules apply). */
1846
+ static create<C extends typeof Model>(this: C, attributes?: Row): Promise<Instance<C>>;
1847
+ static forceCreate<C extends typeof Model>(this: C, attributes: Row): Promise<Instance<C>>;
1848
+ static firstOrNew<C extends typeof Model>(this: C, attributes: Row, values?: Row): Promise<Instance<C>>;
1849
+ static firstOrCreate<C extends typeof Model>(this: C, attributes: Row, values?: Row): Promise<Instance<C>>;
1850
+ static updateOrCreate<C extends typeof Model>(this: C, attributes: Row, values?: Row): Promise<Instance<C>>;
1851
+ /**
1852
+ * The model's registered factory (database/factories/<Model>Factory.ts): await User.factory().create(),
1853
+ * await User.factory(3).create(). Use UserFactory.new() to reach the factory's own state methods with their types.
1854
+ */
1855
+ static factory<C extends typeof Model>(this: C): Factory<InstanceType<C>>;
1856
+ static factory<C extends typeof Model>(this: C, count: number, state?: State): Factory<InstanceType<C>> & Many;
1857
+ /** Deletes models by key, one by one, so model events fire. Returns how many were deleted. */
1858
+ static destroy(...ids: Array<unknown | unknown[]>): Promise<number>;
1859
+ /** Disables mass assignment protection everywhere until reguard(). */
1860
+ static unguard(state?: boolean): void;
1861
+ static reguard(): void;
1862
+ static isUnguarded(): boolean;
1863
+ /** Runs fn with mass assignment protection off, for this async context only (seeders, factories). */
1864
+ static unguarded<R>(fn: () => R): R;
1865
+ /** Sets the fillable attributes; the others are dropped, or throw MassAssignmentError on a totally guarded model. */
1866
+ fill(attributes: Row): this;
1867
+ /** Sets attributes with no mass assignment check. Never pass it request input. */
1868
+ forceFill(attributes: Row): this;
1869
+ isFillable(key: string): boolean;
1870
+ /** Guarded names match case-insensitively: SQLite and MySQL column names are case-insensitive. */
1871
+ isGuarded(key: string): boolean;
1872
+ totallyGuarded(): boolean;
1873
+ getFillable(): string[];
1874
+ getGuarded(): string[];
1875
+ /** An attribute through its accessor or cast; undefined when the model doesn't have it. */
1876
+ getAttribute<T = unknown>(key: string): T;
1877
+ /** The attribute's value after its accessor (get<Name>Attribute) or cast. */
1878
+ getAttributeValue(key: string): unknown;
1879
+ /** Sets an attribute through its mutator (set<Name>Attribute) or cast. */
1880
+ setAttribute(key: string, value: unknown): this;
1881
+ hasGetMutator(key: string): boolean;
1882
+ hasSetMutator(key: string): boolean;
1883
+ /** Every cast, including the implied ones: the incrementing key (int) and the timestamp columns (datetime). */
1884
+ getCasts(): Record<string, CastDefinition>;
1885
+ hasCast(key: string, types?: string[]): boolean;
1886
+ /** The stored attributes, with in-place changes to json casts written back. */
1887
+ getAttributes(): Row;
1888
+ /** Replaces the stored attributes as-is (no casts or mutators); sync = also make them the original. */
1889
+ setRawAttributes(attributes: Row, sync?: boolean): this;
1890
+ /** The original value (cast), or every original value. */
1891
+ getOriginal(): Row;
1892
+ getOriginal<T = unknown>(key: string): T;
1893
+ getRawOriginal(): Row;
1894
+ getRawOriginal<T = unknown>(key: string): T;
1895
+ syncOriginal(): this;
1896
+ syncOriginalAttributes(...keys: string[]): this;
1897
+ /** The attributes that changed since the model was loaded or saved, compared by meaning (casts), not representation. */
1898
+ getDirty(): Row;
1899
+ isDirty(...keys: Array<string | string[]>): boolean;
1900
+ isClean(...keys: Array<string | string[]>): boolean;
1901
+ /** The attributes the last save() changed. */
1902
+ getChanges(): Row;
1903
+ wasChanged(...keys: Array<string | string[]>): boolean;
1904
+ syncChanges(): this;
1905
+ /** The given attributes (through accessors and casts). */
1906
+ only(...keys: Array<string | string[]>): Row;
1907
+ /**
1908
+ * useCache = false skips the json-cast decode cache entirely (both reading and writing it): used by getOriginal(),
1909
+ * so a decoded original never aliases the live attribute's cached (and possibly in-place-mutated) object, even
1910
+ * when their raw stored strings are equal right after load/save.
1911
+ */
1912
+ protected castAttribute(key: string, value: unknown, useCache?: boolean): unknown;
1913
+ /** Writes json casts that were changed in place (post.meta.views++) back into the stored attributes. */
1914
+ protected mergeCachedCasts(): void;
1915
+ private mutatorFor;
1916
+ getKeyName(): string;
1917
+ getKeyType(): 'int' | 'string';
1918
+ getIncrementing(): boolean;
1919
+ getKey(): unknown;
1920
+ getTable(): string;
1921
+ getConnectionName(): string | undefined;
1922
+ getPerPage(): number;
1923
+ /** 'posts.title' for 'title'. Already-qualified columns are returned as-is. */
1924
+ qualifyColumn(column: string): string;
1925
+ getQualifiedKeyName(): string;
1926
+ /** The conventional foreign key pointing at this model: user_id for User. */
1927
+ getForeignKey(): string;
1928
+ getRouteKeyName(): string;
1929
+ getRouteKey(): unknown;
1930
+ /**
1931
+ * The model a route parameter value points at: where <field or route key> = value (global scopes apply, so a
1932
+ * soft-deleted row isn't found). A non-numeric value for an integer primary key finds nothing without a query.
1933
+ */
1934
+ resolveRouteBinding(value: string, field?: string): Promise<this | undefined>;
1935
+ /** Override to customize the binding query (Laravel's resolveRouteBindingQuery()). */
1936
+ resolveRouteBindingQuery(query: Builder<this>, value: string, field: string): Builder<this>;
1937
+ usesTimestamps(): boolean;
1938
+ usesSoftDeletes(): boolean;
1939
+ getCreatedAtColumn(): string | null;
1940
+ getUpdatedAtColumn(): string | null;
1941
+ getDeletedAtColumn(): string;
1942
+ /** The model's database connection, from the DatabaseManager binding. */
1943
+ getConnection(): Connection;
1944
+ setConnection(name: string | undefined): this;
1945
+ setTable(table: string): this;
1946
+ /** A new instance of the same class, connection and table (mass assignment rules apply to attributes). */
1947
+ newInstance(attributes?: Row, exists?: boolean): this;
1948
+ /** An existing model from a database row (no casts or mutators applied to the row). */
1949
+ newFromBuilder(attributes: Row): this;
1950
+ /** A query of this model with its global scopes and default eager loads. */
1951
+ newQuery(): Builder<this>;
1952
+ /** A query with the default eager loads (`with`, `withCount`) but no global scopes. */
1953
+ newQueryWithoutScopes(): Builder<this>;
1954
+ /** A query with the global scopes but no default eager loads. */
1955
+ newQueryWithoutRelationships(): Builder<this>;
1956
+ /** Adds this class's global scopes to a builder (relations use it for the related model's scopes). */
1957
+ registerGlobalScopes<B extends Builder<Model>>(builder: B): B;
1958
+ /**
1959
+ * Adds this class's default `with` and `withCount` to a builder (relations use it for the related model's
1960
+ * defaults). A default count that reaches the same class again while it is being added (a self-referencing
1961
+ * relation, or two models counting each other) is skipped there instead of recursing forever.
1962
+ */
1963
+ registerDefaultEagerLoads<B extends Builder<Model>>(builder: B): B;
1964
+ /** A bare builder for this model: no global scopes, no default eager loads. */
1965
+ newModelQuery(): Builder<this>;
1966
+ /**
1967
+ * Inserts the model, or updates its dirty attributes. Only changed columns are written; an unchanged model
1968
+ * runs no query at all. Returns false when a saving/creating/updating listener cancels.
1969
+ */
1970
+ save(): Promise<boolean>;
1971
+ /** Fills and saves an existing model. */
1972
+ update(attributes?: Row): Promise<boolean>;
1973
+ /**
1974
+ * Deletes the model's row, or sets deleted_at with soft deletes. Returns false for a model that isn't saved, or
1975
+ * when a deleting listener cancels.
1976
+ */
1977
+ delete(): Promise<boolean>;
1978
+ /** save() without model events. */
1979
+ saveQuietly(): Promise<boolean>;
1980
+ /** delete() without model events. */
1981
+ deleteQuietly(): Promise<boolean>;
1982
+ /** True when the model is soft deleted. Only for models with `softDeletes = true`. */
1983
+ trashed(): boolean;
1984
+ /** Clears deleted_at and saves. Fires restoring (can cancel) and restored. */
1985
+ restore(): Promise<boolean>;
1986
+ /** Deletes the row for real, even with soft deletes. Fires forceDeleting (can cancel) and forceDeleted. */
1987
+ forceDelete(): Promise<boolean>;
1988
+ isForceDeleting(): boolean;
1989
+ getQualifiedDeletedAtColumn(): string;
1990
+ private assertSoftDeletes;
1991
+ /** Reloads the attributes and the loaded relations from the database (including a soft-deleted row). */
1992
+ refresh(): Promise<this>;
1993
+ /** A fresh copy from the database, or undefined when the row is gone. */
1994
+ fresh(): Promise<this | undefined>;
1995
+ /** Updates updated_at (and saves). */
1996
+ touch(): Promise<boolean>;
1997
+ /** column = column + amount in the database, mirrored on the model without marking it dirty. */
1998
+ increment(column: string, amount?: number, extra?: Row): Promise<number>;
1999
+ decrement(column: string, amount?: number, extra?: Row): Promise<number>;
2000
+ /** Same table, connection and key. */
2001
+ is(other: Model | null | undefined): boolean;
2002
+ isNot(other: Model | null | undefined): boolean;
2003
+ /** The current time, to the second (the storage precision). */
2004
+ freshTimestamp(): Date;
2005
+ updateTimestamps(): void;
2006
+ protected performInsert(query: Builder<this>): Promise<boolean>;
2007
+ protected performUpdate(query: Builder<this>): Promise<boolean>;
2008
+ protected finishSave(): Promise<void>;
2009
+ protected performDeleteOnModel(): Promise<void>;
2010
+ /** deleted_at (and updated_at) = now, on this row only. The model still exists, as a trashed model. */
2011
+ protected runSoftDelete(): Promise<void>;
2012
+ /** where key = the key the row was loaded with (the original, in case the key itself changed). */
2013
+ protected setKeysForSaveQuery(query: Builder<this>): Builder<this>;
2014
+ protected incrementOrDecrement(column: string, amount: number, extra: Row): Promise<number>;
2015
+ /**
2016
+ * Dispatches 'eloquent.<event>: <Class>' with the model as payload. Halting events return false when a listener
2017
+ * returned false. A no-op without an EventDispatcher binding, or inside withoutEvents().
2018
+ */
2019
+ fireModelEvent(event: ModelEvent, halt?: boolean): Promise<boolean>;
2020
+ /** Whether any listener is registered for one of this model's events (retrieved is skipped when none is). */
2021
+ hasModelListeners(event: ModelEvent): boolean;
2022
+ /**
2023
+ * One related row holds this model's key: user.profile() → hasOne(Profile) (profiles.user_id = users.id).
2024
+ * @param foreignKey on the related table (default: this model's foreign key, e.g. user_id)
2025
+ * @param localKey on this model (default: the primary key)
2026
+ */
2027
+ hasOne<C extends typeof Model>(related: C, foreignKey?: string, localKey?: string): HasOne<InstanceType<C>, this> & Scopes<C>;
2028
+ /** Many related rows hold this model's key: post.comments() → hasMany(Comment) (comments.post_id = posts.id). */
2029
+ hasMany<C extends typeof Model>(related: C, foreignKey?: string, localKey?: string): HasMany<InstanceType<C>, this> & Scopes<C>;
2030
+ /**
2031
+ * This model holds the related model's key: post.author() → belongsTo(User, 'user_id').
2032
+ * @param foreignKey on this model (default: the related model's foreign key, e.g. user_id)
2033
+ * @param ownerKey on the related model (default: its primary key)
2034
+ * @param relation the loaded-relation name associate() sets (default: the resolved name, else the class in camelCase)
2035
+ */
2036
+ belongsTo<C extends typeof Model>(related: C, foreignKey?: string, ownerKey?: string, relation?: string): BelongsTo<InstanceType<C>, this> & Scopes<C>;
2037
+ /**
2038
+ * Many-to-many through a pivot table: post.tags() → belongsToMany(Tag) over post_tag (post_id, tag_id).
2039
+ * @param table default: the two singular snake names in alphabetical order (post_tag)
2040
+ * @param foreignPivotKey the pivot column pointing at this model (default: post_id)
2041
+ * @param relatedPivotKey the pivot column pointing at the related model (default: tag_id)
2042
+ */
2043
+ belongsToMany<C extends typeof Model>(related: C, table?: string, foreignPivotKey?: string, relatedPivotKey?: string, parentKey?: string, relatedKey?: string): BelongsToMany<InstanceType<C>, this> & Scopes<C>;
2044
+ /**
2045
+ * Related rows through an intermediate model: country.posts() → hasManyThrough(Post, User).
2046
+ * @param firstKey on the through table (default: this model's foreign key, country_id)
2047
+ * @param secondKey on the related table (default: the through model's foreign key, user_id)
2048
+ */
2049
+ hasManyThrough<C extends typeof Model, T extends typeof Model>(related: C, through: T, firstKey?: string, secondKey?: string, localKey?: string, secondLocalKey?: string): HasManyThrough<InstanceType<C>, this, InstanceType<T>> & Scopes<C>;
2050
+ /** A polymorphic one-to-one: user.image() → morphOne(Image, 'imageable') (images.imageable_id/_type). */
2051
+ morphOne<C extends typeof Model>(related: C, name: string, type?: string, id?: string, localKey?: string): MorphOne<InstanceType<C>, this> & Scopes<C>;
2052
+ /** A polymorphic one-to-many: post.comments() → morphMany(Comment, 'commentable'). */
2053
+ morphMany<C extends typeof Model>(related: C, name: string, type?: string, id?: string, localKey?: string): MorphMany<InstanceType<C>, this> & Scopes<C>;
2054
+ /**
2055
+ * The inverse of morphOne/morphMany: comment.commentable() → morphTo('commentable'). The name is required
2056
+ * (Laravel reads it from the calling method, which JavaScript can't do reliably).
2057
+ */
2058
+ morphTo<R extends Model = Model>(name: string, type?: string, id?: string, ownerKey?: string): MorphTo<R, this>;
2059
+ /** The value stored in *_type columns for this model: its morph map alias, or its class name. */
2060
+ getMorphClass(): string;
2061
+ /** The pivot row of a model loaded through belongsToMany (tag.pivot.getAttribute('created_at')). */
2062
+ get pivot(): Model | undefined;
2063
+ /** A related model instance on this model's connection when it has none of its own. */
2064
+ protected newRelatedInstance<C extends typeof Model>(related: C): InstanceType<C>;
2065
+ /** Calls the relation method `name` (post.comments()) and checks that it returns a relation. */
2066
+ getRelationInstance(name: string): Relation;
2067
+ /**
2068
+ * A loaded relation, typed from the relation method: post.getRelation('author') is User | null,
2069
+ * post.getRelation('comments') is Collection<Comment>. Throws RelationNotLoadedError when it isn't loaded
2070
+ * (JavaScript can't lazy-load synchronously: use with(), load() or post.comments().get()).
2071
+ */
2072
+ getRelation<K extends RelationNames<this>>(name: K): RelationValue<this, K>;
2073
+ /** Eager loads relations onto this model: await post.load('comments.author'). */
2074
+ load(...relations: EagerLoadSpec[]): Promise<this>;
2075
+ /** Loads only the relations that aren't loaded yet (nested paths are followed into loaded relations). */
2076
+ loadMissing(...relations: string[]): Promise<this>;
2077
+ /** Loads <relation>_count attributes: await post.loadCount('comments'). */
2078
+ loadCount(...relations: EagerLoadSpec[]): Promise<this>;
2079
+ /** Stores a loaded relation (eager loading and load() use this). */
2080
+ setRelation(name: string, value: unknown): this;
2081
+ relationLoaded(name: string): boolean;
2082
+ unsetRelation(name: string): this;
2083
+ getRelations(): Record<string, unknown>;
2084
+ getHidden(): string[];
2085
+ setHidden(hidden: string[]): this;
2086
+ getVisible(): string[];
2087
+ setVisible(visible: string[]): this;
2088
+ /** Hides attributes for this instance only. */
2089
+ makeHidden(...attributes: Array<string | string[]>): this;
2090
+ /** Un-hides attributes for this instance only. */
2091
+ makeVisible(...attributes: Array<string | string[]>): this;
2092
+ getAppends(): string[];
2093
+ setAppends(appends: string[]): this;
2094
+ /** Adds accessor-only attributes to the serialized form of this instance. */
2095
+ append(...attributes: Array<string | string[]>): this;
2096
+ /** Attributes (through accessors and casts, dates as ISO strings), appends and loaded relations, minus hidden ones. */
2097
+ toArray(): Row;
2098
+ toJSON(): Row;
2099
+ attributesToArray(): Row;
2100
+ /** Loaded relations under their snake_case names: a model → its array, a collection → an array of arrays. */
2101
+ relationsToArray(): Row;
2102
+ protected serializeValue(value: unknown): unknown;
2103
+ private isArrayableKey;
2104
+ private arrayable;
2105
+ }
2106
+ /** Eager loads relations onto models you already have (Laravel's $collection->load()). */
2107
+ declare function loadRelations<M extends Model>(models: Iterable<M>, ...relations: EagerLoadSpec[]): Promise<M[]>;
2108
+ /** A row of a belongsToMany pivot table, available as related.pivot (unguarded, no key, no timestamps by default). */
2109
+ declare class Pivot extends Model {
2110
+ protected guarded: string[];
2111
+ incrementing: boolean;
2112
+ timestamps: boolean;
2113
+ }
2114
+
2115
+ /**
2116
+ * The morph map: the value stored in `*_type` columns for each model class (Laravel's Relation::morphMap()).
2117
+ * Without an entry the class name is stored ('Post'). Returns the current map.
2118
+ */
2119
+ declare function morphMap(map?: Record<string, typeof Model>, merge?: boolean): Record<string, typeof Model>;
2120
+ /** The model class for a morph map alias, if mapped. */
2121
+ declare function getMorphedModel(alias: string): typeof Model | undefined;
2122
+ /** The morph map alias of a class, if mapped. */
2123
+ declare function getMorphAlias(model: typeof Model): string | undefined;
2124
+ /** The class for a stored morph type: the morph map, then the ClassRegistry (discovered models), then booted models. */
2125
+ declare function resolveMorphClass(type: string): typeof Model;
2126
+
2127
+ /**
2128
+ * Hides soft-deleted rows: where deleted_at is null. Registered for every model with `softDeletes = true`.
2129
+ * Builder.withTrashed()/onlyTrashed()/withoutTrashed() remove or replace it.
2130
+ */
2131
+ declare class SoftDeletingScope implements Scope {
2132
+ apply(builder: Builder<any>, model: Model): void;
2133
+ }
2134
+
2135
+ /**
2136
+ * A migration: `export default class extends Migration { async up() { await Schema.create(…) } async down() { … } }`.
2137
+ * Files live in database/migrations and run in file-name order. up() and down() are abstract (as in Laravel's
2138
+ * stub), so implementing them needs no `override` under noImplicitOverride.
2139
+ */
2140
+ declare abstract class Migration {
2141
+ /** The connection to run on (default: the default connection). */
2142
+ connection: string | undefined;
2143
+ /** Wrap up()/down() in a transaction where DDL is transactional (Postgres, SQLite; not MySQL), like Laravel. */
2144
+ withinTransaction: boolean;
2145
+ abstract up(): Promise<void> | void;
2146
+ abstract down(): Promise<void> | void;
2147
+ }
2148
+
2149
+ /** Laravel 11's migration.create stub: an anonymous class, the form the Migrator loads. */
2150
+ declare const MIGRATION_CREATE_STUB = "import { Migration, Schema } from '{{ importSource }}'\n\nexport default class extends Migration {\n async up() {\n await Schema.create('{{ table }}', (table) => {\n table.id()\n table.timestamps()\n })\n }\n\n async down() {\n await Schema.dropIfExists('{{ table }}')\n }\n}\n";
2151
+ /** Laravel 11's migration.update stub. */
2152
+ declare const MIGRATION_UPDATE_STUB = "import { Migration, Schema } from '{{ importSource }}'\n\nexport default class extends Migration {\n async up() {\n await Schema.table('{{ table }}', (table) => {\n //\n })\n }\n\n async down() {\n await Schema.table('{{ table }}', (table) => {\n //\n })\n }\n}\n";
2153
+ /** Laravel 11's blank migration stub. */
2154
+ declare const MIGRATION_STUB = "import { Migration } from '{{ importSource }}'\n\nexport default class extends Migration {\n async up() {\n //\n }\n\n async down() {\n //\n }\n}\n";
2155
+ /**
2156
+ * Laravel's TableGuesser: create_posts_table → ['posts', true], add_votes_to_users_table → ['users', false].
2157
+ * Returns undefined when the name says nothing about a table.
2158
+ */
2159
+ declare function guessTable(migration: string): {
2160
+ table: string;
2161
+ create: boolean;
2162
+ } | undefined;
2163
+ /** Laravel's date prefix, Y_m_d_His (UTC). */
2164
+ declare function migrationDatePrefix(date?: Date): string;
2165
+ interface CreateMigrationOptions {
2166
+ /** The table to create (--create). */
2167
+ create?: string;
2168
+ /** The table to change (--table). */
2169
+ table?: string;
2170
+ /** The package the migration imports Migration and Schema from (default '@orieljs/framework'). */
2171
+ importSource?: string;
2172
+ /** For tests: the timestamp of the file name. */
2173
+ date?: Date;
2174
+ }
2175
+ /** Laravel's MigrationCreator: writes <path>/<Y_m_d_His>_<name>.ts from the create, update or blank stub. */
2176
+ declare class MigrationCreator {
2177
+ /** Returns the path of the new file. */
2178
+ create(name: string, path: string, options?: CreateMigrationOptions): string;
2179
+ }
2180
+
2181
+ interface MigrationRecord {
2182
+ migration: string;
2183
+ batch: number;
2184
+ }
2185
+ /** The migrations table (id, migration, batch): which migration ran in which batch (Laravel's DatabaseMigrationRepository). */
2186
+ declare class MigrationRepository {
2187
+ protected readonly connection: Connection;
2188
+ readonly table: string;
2189
+ constructor(connection: Connection, table?: string);
2190
+ repositoryExists(): Promise<boolean>;
2191
+ createRepository(): Promise<void>;
2192
+ deleteRepository(): Promise<void>;
2193
+ /** Every migration that ran, oldest first. */
2194
+ getRan(): Promise<string[]>;
2195
+ /** The last `steps` migrations, newest first. */
2196
+ getMigrations(steps: number): Promise<MigrationRecord[]>;
2197
+ /** The migrations of one batch, newest first. */
2198
+ getMigrationsByBatch(batch: number): Promise<MigrationRecord[]>;
2199
+ /** The migrations of the last batch, newest first. */
2200
+ getLast(): Promise<MigrationRecord[]>;
2201
+ /** migration name → batch. */
2202
+ getMigrationBatches(): Promise<Record<string, number>>;
2203
+ log(migration: string, batch: number): Promise<void>;
2204
+ delete(migration: string): Promise<void>;
2205
+ getNextBatchNumber(): Promise<number>;
2206
+ getLastBatchNumber(): Promise<number>;
2207
+ private query;
2208
+ private records;
2209
+ }
2210
+
2211
+ interface MigrationStatus {
2212
+ name: string;
2213
+ ran: boolean;
2214
+ batch: number | undefined;
2215
+ }
2216
+ interface MigratorOptions {
2217
+ /** Run each migration in its own batch (migrate --step). */
2218
+ step?: boolean;
2219
+ }
2220
+ interface RollbackOptions {
2221
+ /** Roll back this many migrations instead of the last batch. */
2222
+ step?: number;
2223
+ /** Roll back one batch by number. */
2224
+ batch?: number;
2225
+ }
2226
+ /**
2227
+ * Runs database/migrations/*.ts in file-name order and records them in the migrations table
2228
+ * (Laravel's Migrator). Output lines go to `output`.
2229
+ */
2230
+ declare class Migrator {
2231
+ protected readonly manager: DatabaseManagerImpl;
2232
+ protected readonly output: (line: string) => void;
2233
+ private connectionName;
2234
+ constructor(manager: DatabaseManagerImpl, output?: (line: string) => void);
2235
+ /** Use another connection for the repository and for migrations that don't name one (--database). */
2236
+ setConnection(name: string | undefined): this;
2237
+ getConnection(): Connection;
2238
+ getRepository(): MigrationRepository;
2239
+ /** migration name (file name without extension) → absolute path, sorted by name across all paths. */
2240
+ getMigrationFiles(paths: readonly string[]): Map<string, string>;
2241
+ /** Creates the migrations table when it doesn't exist yet. */
2242
+ ensureRepository(): Promise<MigrationRepository>;
2243
+ /** Runs every pending migration in one new batch (or one batch each with step). Returns their names. */
2244
+ run(paths: readonly string[], options?: MigratorOptions): Promise<string[]>;
2245
+ /** Rolls back the last batch (or the last `step` migrations, or one batch). Returns the names rolled back. */
2246
+ rollback(paths: readonly string[], options?: RollbackOptions): Promise<string[]>;
2247
+ /** Rolls back every migration, newest first. */
2248
+ reset(paths: readonly string[]): Promise<string[]>;
2249
+ /** Drops every table, then runs every migration (migrate:fresh). */
2250
+ fresh(paths: readonly string[]): Promise<string[]>;
2251
+ /** Every migration file and every recorded migration, with its batch (all pending without a migrations table). */
2252
+ status(paths: readonly string[]): Promise<MigrationStatus[]>;
2253
+ /** Imports a migration file; its default export is a Migration class (or instance). */
2254
+ resolve(file: string): Promise<Migration>;
2255
+ private rollDown;
2256
+ /** Runs up/down on the migration's connection (made the default meanwhile), in a transaction where DDL allows it. */
2257
+ private runMigration;
2258
+ }
2259
+
2260
+ type SeederClass = new () => Seeder;
2261
+ /**
2262
+ * A database seeder (database/seeders/*.ts): run() inserts data, call() runs other seeders. Seeders run with mass
2263
+ * assignment protection off, as with Laravel's db:seed.
2264
+ */
2265
+ declare abstract class Seeder {
2266
+ protected output: (line: string) => void;
2267
+ abstract run(): Promise<void> | void;
2268
+ setOutput(output: (line: string) => void): this;
2269
+ /** Runs other seeders in order, printing their names. */
2270
+ call(...seeders: Array<SeederClass | SeederClass[]>): Promise<void>;
2271
+ /** Runs other seeders without output. */
2272
+ callSilent(...seeders: Array<SeederClass | SeederClass[]>): Promise<void>;
2273
+ /** Runs run() unguarded. */
2274
+ invoke(): Promise<void>;
2275
+ }
2276
+
2277
+ interface RegisteredModel {
2278
+ name: string;
2279
+ model: typeof Model;
2280
+ /** The file it was discovered in (used by model:types for the module path). */
2281
+ file?: string;
2282
+ }
2283
+ /**
2284
+ * The application's models, auto-discovered from app/Models: route model binding ({post} → Post), model:types,
2285
+ * and morphTo (through the ClassRegistry) look models up here by name.
2286
+ */
2287
+ declare class ModelRegistry {
2288
+ private readonly models;
2289
+ /** Registers a model class (booting it, so static scope proxies such as Post.published() exist). */
2290
+ register(model: typeof Model, file?: string): RegisteredModel;
2291
+ /** Imports every file under `directory` and registers each exported Model subclass. */
2292
+ discover(directory: string): Promise<RegisteredModel[]>;
2293
+ /** A model by class name or route parameter name: 'Post', 'post', 'blog_post' and 'blogPost' find BlogPost. */
2294
+ get(name: string): RegisteredModel | undefined;
2295
+ resolve(name: string): typeof Model | undefined;
2296
+ has(name: string): boolean;
2297
+ all(): RegisteredModel[];
2298
+ }
2299
+
2300
+ /** The parts of the application and database the commands need (resolved lazily, when a command runs). */
2301
+ interface DatabaseCommandContext {
2302
+ app: Pick<Application, 'basePath' | 'databasePath' | 'isProduction'>;
2303
+ manager(): DatabaseManagerImpl;
2304
+ /** The discovered models. When given, model:types works and migrate regenerates the types outside production. */
2305
+ models?(): Promise<ModelRegistry>;
2306
+ /** The package generated types import from (default '@orieljs/framework'). */
2307
+ typesImportSource?: string;
2308
+ /** The package make:migration's stubs import from (default '@orieljs/framework'). */
2309
+ stubsImportSource?: string;
2310
+ }
2311
+ /** Imports database/seeders/<Class>.ts and runs it (default export or the export named after the class). */
2312
+ declare function runSeeder(context: DatabaseCommandContext, className: string, output: (line: string) => void, database?: string): Promise<void>;
2313
+ /** Writes types/models.d.ts for the discovered models; returns the path relative to the base path. */
2314
+ declare function generateModelTypes(context: DatabaseCommandContext): Promise<string | undefined>;
2315
+ /** The migrate*, migrate:install, db:seed and make:migration commands (closure commands, PC1). */
2316
+ declare function registerMigrationCommands(kernel: ConsoleKernel, context: DatabaseCommandContext): void;
2317
+ /** model:types: regenerates types/models.d.ts from the database schema and the discovered models. */
2318
+ declare function registerModelTypesCommand(kernel: ConsoleKernel, context: DatabaseCommandContext): void;
2319
+
2320
+ interface TypeGeneratorOptions {
2321
+ /** Where the declarations go (the skeleton: types/models.d.ts). */
2322
+ outputFile: string;
2323
+ /** The package the generated file imports ScopeStatic from. */
2324
+ importSource?: string;
2325
+ }
2326
+ /**
2327
+ * Writes types/models.d.ts: for every model, the attribute types (from the database columns and the model's casts)
2328
+ * merged into the class by declaration merging, the phantom $attributes that Column<M> reads, accessor-only
2329
+ * attributes, and the static scope proxies (Post.published()).
2330
+ */
2331
+ declare class TypeGenerator {
2332
+ private readonly options;
2333
+ constructor(options: TypeGeneratorOptions);
2334
+ generate(models: readonly RegisteredModel[]): Promise<string>;
2335
+ /** Generates and writes the file; returns its path. */
2336
+ write(models: readonly RegisteredModel[]): Promise<string>;
2337
+ private modelBlock;
2338
+ /** '../app/Models/Post' for app/Models/Post.ts, relative to the output file. */
2339
+ private modulePath;
2340
+ private key;
2341
+ }
2342
+
2343
+ /** Thrown by fake().unique() when it can't find a new value (Laravel's OverflowException). */
2344
+ declare class FakerOverflowError extends DatabaseError {
2345
+ readonly name = "FakerOverflowError";
2346
+ }
2347
+ /**
2348
+ * A small built-in fake data generator for factories and tests (the subset of Faker that factories typically use).
2349
+ * Seedable for repeatable data: fake().seed(1234). For anything richer, use sequence() or plain JavaScript.
2350
+ */
2351
+ declare class Faker {
2352
+ private state;
2353
+ private uniqueProxy;
2354
+ private readonly seen;
2355
+ /** Makes the sequence repeatable. */
2356
+ seed(seed: number): this;
2357
+ /** A float in [0, 1) (mulberry32). */
2358
+ random(): number;
2359
+ /**
2360
+ * The same generator, but every call returns a value it hasn't returned before (per method). reset clears the
2361
+ * memory. Throws FakerOverflowError after 10000 tries.
2362
+ */
2363
+ unique(reset?: boolean): Faker;
2364
+ numberBetween(min?: number, max?: number): number;
2365
+ /** A random integer with up to `digits` digits (strict: exactly that many). */
2366
+ randomNumber(digits?: number, strict?: boolean): number;
2367
+ randomFloat(decimals?: number, min?: number, max?: number): number;
2368
+ randomDigit(): number;
2369
+ /** true with `chanceOfGettingTrue` percent. */
2370
+ boolean(chanceOfGettingTrue?: number): boolean;
2371
+ randomElement<T>(items: readonly T[]): T;
2372
+ /** `count` distinct items, in random order. */
2373
+ randomElements<T>(items: readonly T[], count?: number): T[];
2374
+ shuffle<T>(items: readonly T[]): T[];
2375
+ firstName(): string;
2376
+ lastName(): string;
2377
+ name(): string;
2378
+ userName(): string;
2379
+ /** An address at example.com/org/net, which never delivers mail. */
2380
+ safeEmail(): string;
2381
+ email(): string;
2382
+ word(): string;
2383
+ words(count?: number): string[];
2384
+ sentence(words?: number): string;
2385
+ sentences(count?: number): string[];
2386
+ paragraph(sentences?: number): string;
2387
+ paragraphs(count?: number): string[];
2388
+ /** Text of at most `maxChars` characters. */
2389
+ text(maxChars?: number): string;
2390
+ slug(words?: number): string;
2391
+ title(): string;
2392
+ url(): string;
2393
+ city(): string;
2394
+ country(): string;
2395
+ company(): string;
2396
+ phoneNumber(): string;
2397
+ uuid(): string;
2398
+ /** Replaces every # with a digit. */
2399
+ numerify(pattern?: string): string;
2400
+ /** Replaces every ? with a letter. */
2401
+ lexify(pattern?: string): string;
2402
+ /** numerify() and lexify() together. */
2403
+ bothify(pattern?: string): string;
2404
+ hexColor(): string;
2405
+ /** A date between two points ('-30 years', 'now', '+1 week', a Date). */
2406
+ dateTimeBetween(start?: Date | string, end?: Date | string): Date;
2407
+ /** A date before `max` (default now). */
2408
+ dateTime(max?: Date | string): Date;
2409
+ /** A Y-m-d date string before `max`. */
2410
+ date(max?: Date | string): string;
2411
+ private resolveDate;
2412
+ }
2413
+ /** The shared fake data generator (Laravel's fake() helper): fake().name(), fake().unique().safeEmail(). */
2414
+ declare function fake(): Faker;
2415
+
2416
+ /**
2417
+ * Route model binding for the router: {post} → Post (StudlyCase of the parameter, from the app/Models registry),
2418
+ * {post:slug} → Post where slug = value, Route.model('author', User) → resolveExplicit(User, …).
2419
+ * Named RouteModelResolverImpl so it never shadows the RouteModelResolver token.
2420
+ */
2421
+ declare class RouteModelResolverImpl implements RouteModelResolver {
2422
+ private readonly registry;
2423
+ constructor(registry: ModelRegistry);
2424
+ /** undefined when no model is called `parameter` (the router keeps the string); throws ModelNotFoundError (404) when the row is missing. */
2425
+ resolve(parameter: string, value: string, field?: string): Promise<unknown | undefined>;
2426
+ /** The model of `model` whose route key (or `field`) equals value; ModelNotFoundError (404) when there is none. */
2427
+ resolveExplicit(model: Class<unknown>, value: string, field?: string): Promise<unknown>;
2428
+ }
2429
+
2430
+ /** Laravel 11's config/database.php defaults (the app's config/database.ts wins, key by key). */
2431
+ declare function databaseConfigDefaults(app: Pick<Application, 'databasePath'>): DatabaseConfig & Record<string, unknown>;
2432
+ /** Points the paginators at the current request: ?page=, ?cursor=, the URL and the query string (Laravel's resolvers). */
2433
+ declare function usePaginationResolvers(): void;
2434
+ /**
2435
+ * Binds the database layer: the DatabaseManager (a root singleton owning the pools) behind the DB facade, the
2436
+ * Schema facade's SchemaBuilder, the ModelRegistry and the RouteModelResolver. At boot it discovers app/Models,
2437
+ * factories (console and tests), points pagination at the current request, and registers the migrate*, db:seed,
2438
+ * make:migration and model:types commands when a ConsoleKernel is bound. It also merges Laravel's database.redis
2439
+ * connections, which Cache, Queue and Session read.
2440
+ */
2441
+ declare class DatabaseServiceProvider extends ServiceProvider {
2442
+ register(): void;
2443
+ boot(): Promise<void>;
2444
+ private manager;
2445
+ }
2446
+
2447
+ export { AbstractPaginator, type Attributes, BelongsTo, BelongsToMany, Blueprint, type BlueprintCommand, Builder, type BuiltInCast, type BunDatabase, BunSqliteDatabase, type BunStatement, type CastDefinition, type CastsAttributes, type Column, type ColumnAttributes, ColumnDefinition, type ColumnInfo, type ColumnRef, type ColumnType, Connection, type ConnectionConfig, type CreateMigrationOptions, Cursor, CursorPaginator, type CursorPaginatorOptions, DB, type DatabaseCommandContext, type DatabaseConfig, DatabaseConfigError, DatabaseError, DatabaseManagerImpl, DatabaseServiceProvider, type Direction, type EagerLoadSpec, type EnumLike, Expression, Factory, type FactoryResult, Faker, FakerOverflowError, ForeignIdColumnDefinition, ForeignKeyDefinition, type GlobalScope, Grammar, HasMany, HasManyThrough, HasOne, HasOneOrMany, type Having, type IndexType, InvalidCastError, JoinClause, type JoinType, LengthAwarePaginator, type LoggedQuery, LogicError, MIGRATION_CREATE_STUB, MIGRATION_STUB, MIGRATION_UPDATE_STUB, MODEL_EVENTS, type Many, MassAssignmentError, Migration, MigrationCreator, type MigrationRecord, MigrationRepository, type MigrationStatus, Migrator, type MigratorOptions, Model, type ModelBuilder, type ModelClass, type ModelEvent, type ModelListener, ModelNotFoundError, ModelRegistry, type MorphConstraint, MorphMany, MorphOne, MorphTo, MySqlSchemaGrammar, OPERATORS, type Order, type PaginationLink, Paginator, type PaginatorOptions, Pivot, type PivotIds, PostgresSchemaGrammar, Builder$1 as QueryBuilder, QueryError, type RawResult, type ReferentialAction, type RegisteredModel, Relation, type RelationConstraint, type RelationNames, RelationNotFoundError, RelationNotLoadedError, type RelationValue, type RollbackOptions, RouteModelResolverImpl, Schema, SchemaBuilder, SchemaBuilderToken, SchemaGrammar, type Scope, type ScopeCallback, type ScopeStatic, type Scopes, Seeder, type SeederClass, type SelectColumn, SoftDeletingScope, SqliteSchemaGrammar, type State, type StateContext, type SyncChanges, TypeGenerator, type TypeGeneratorOptions, type Where, type WhereArgs, type WhereBoolean, buildQuery, castGet, castSet, columnKey, createDialect, databaseConfigDefaults, discoverFactories, enumValues, fake, formatDate, formatDateTime, generateModelTypes, getMorphAlias, getMorphedModel, guessTable, isBun, isDateCast, isEquivalent, isJsonCast, loadRelations, migrationDatePrefix, modelEventName, morphMap, mysqlPoolOptions, openSqlite, parseDateTime, prepareValue, raw, rawWithBindings, registerMigrationCommands, registerModelTypesCommand, resolveMorphClass, runSeeder, serializeDate, usePaginationResolvers };