@orieljs/database 0.1.0-alpha.15 → 0.1.0-alpha.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/dist/index.d.ts +2027 -1770
- package/dist/index.js +238 -135
- package/dist/index.js.map +1 -1
- package/package.json +6 -6
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../errors.ts","../runtime.ts","../Connectors/SqliteDatabase.ts","../Connectors/dialect.ts","../Query/Expression.ts","../Query/Builder.ts","../Pagination/AbstractPaginator.ts","../Pagination/CursorPaginator.ts","../Pagination/LengthAwarePaginator.ts","../Pagination/Paginator.ts","../Query/Grammar.ts","../Query/values.ts","../Connection.ts","../Schema/Builder.ts","../Schema/ColumnDefinition.ts","../Schema/ForeignKeyDefinition.ts","../Schema/Blueprint.ts","../Schema/Grammar.ts","../Schema/SqliteTableRebuild.ts","../DatabaseManager.ts","../facades.ts","../Eloquent/Model.ts","../Eloquent/Builder.ts","../Eloquent/Relations/constraints.ts","../Eloquent/SoftDeletingScope.ts","../Eloquent/casts.ts","../Eloquent/Collection.ts","../Eloquent/Factories/Factory.ts","../Eloquent/Relations/BelongsTo.ts","../Eloquent/Relations/morphMap.ts","../Eloquent/Relations/Relation.ts","../Eloquent/Relations/BelongsToMany.ts","../Eloquent/Relations/HasOneOrMany.ts","../Eloquent/Relations/MorphTo.ts","../Eloquent/events.ts","../Eloquent/Relations/HasMany.ts","../Eloquent/Relations/HasManyThrough.ts","../Eloquent/Relations/HasOne.ts","../Eloquent/Relations/MorphMany.ts","../Eloquent/Relations/MorphOne.ts","../Eloquent/HasUniqueStringIds.ts","../Eloquent/DatabaseNotification.ts","../Eloquent/HasDatabaseNotifications.ts","../Migrations/Migration.ts","../Migrations/MigrationCreator.ts","../Migrations/MigrationRepository.ts","../Migrations/Migrator.ts","../Seeder.ts","../Console/commands.ts","../Types/TypeGenerator.ts","../ModelRegistry.ts","../Eloquent/Factories/fake.ts","../RouteModelResolver.ts","../DatabaseServiceProvider.ts"],"sourcesContent":["import type { ModelNotFoundError as ModelNotFoundErrorContract, OrielError } from '@orieljs/contracts'\n\n/** Thrown by findOrFail()/firstOrFail() and route model binding. Renders as 404. */\nexport class ModelNotFoundError extends Error implements ModelNotFoundErrorContract {\n readonly kind = 'ModelNotFound' as const\n readonly status = 404\n override readonly name = 'ModelNotFoundError'\n\n constructor(\n readonly model: string,\n readonly ids: unknown[] = [],\n ) {\n super(`No query results for model [${model}]${ids.length ? ' ' + ids.map(String).join(', ') : '.'}`)\n }\n}\n\n/**\n * Base of every other Database error: a server error (bug or infrastructure failure). The exception handler reports\n * it and renders a 500, hiding the message unless app.debug is on.\n */\nexport abstract class DatabaseError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n}\n\n/** A failed SQL statement, with the SQL and connection in the message (Laravel's QueryException). */\nexport class QueryError extends DatabaseError {\n override readonly name = 'QueryError'\n\n constructor(\n readonly connectionName: string,\n readonly sql: string,\n readonly bindings: readonly unknown[],\n cause: unknown,\n ) {\n super(`${cause instanceof Error ? cause.message : String(cause)} (Connection: ${connectionName}, SQL: ${sql})`, { cause })\n }\n}\n\n/** Mass assignment on a model whose `guarded` is ['*'] (Laravel's MassAssignmentException). */\nexport class MassAssignmentError extends DatabaseError {\n override readonly name = 'MassAssignmentError'\n constructor(readonly model: string, readonly attribute: string) {\n super(`Add [${attribute}] to fillable property to allow mass assignment on [${model}].`)\n }\n}\n\nexport class RelationNotFoundError extends DatabaseError {\n override readonly name = 'RelationNotFoundError'\n constructor(readonly model: string, readonly relation: string) {\n super(`Call to undefined relationship [${relation}] on model [${model}].`)\n }\n}\n\nexport class RelationNotLoadedError extends DatabaseError {\n override readonly name = 'RelationNotLoadedError'\n constructor(readonly model: string, readonly relation: string) {\n super(\n `Relation [${relation}] is not loaded on model [${model}]. Eager load it with ${model}.with('${relation}') ` +\n `or await model.load('${relation}'), or query it with model.${relation}().get().`,\n )\n }\n}\n\nexport class InvalidCastError extends DatabaseError {\n override readonly name = 'InvalidCastError'\n constructor(readonly model: string, readonly column: string, readonly castType: string) {\n super(`Call to undefined cast [${castType}] on column [${column}] in model [${model}].`)\n }\n}\n\n/** Bad or missing database configuration (unknown connection, unsupported driver). */\nexport class DatabaseConfigError extends DatabaseError {\n override readonly name = 'DatabaseConfigError'\n}\n\n/** Thrown when an operation needs a feature the model hasn't enabled (e.g. restore() without soft deletes). */\nexport class LogicError extends DatabaseError {\n override readonly name = 'LogicError'\n}\n","/** True when running on Bun (bun:sqlite is used instead of better-sqlite3). */\nexport const isBun = (): boolean => typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined'\n","import type { SqliteDatabase, SqliteStatement } from 'kysely'\nimport { importOptional } from '@orieljs/support'\nimport { isBun } from '../runtime'\n\n/** The part of bun:sqlite's Statement this adapter uses. */\nexport interface BunStatement {\n readonly columnNames: string[]\n all(...parameters: unknown[]): unknown[]\n run(...parameters: unknown[]): { changes: number | bigint; lastInsertRowid: number | bigint }\n iterate(...parameters: unknown[]): IterableIterator<unknown>\n}\n\n/** The part of bun:sqlite's Database this adapter uses. */\nexport interface BunDatabase {\n prepare(sql: string): BunStatement\n close(): void\n}\n\n/** Adapts bun:sqlite to the better-sqlite3 shape Kysely's SqliteDialect expects. */\nexport class BunSqliteDatabase implements SqliteDatabase {\n constructor(private readonly database: BunDatabase) {}\n\n close(): void {\n this.database.close()\n }\n\n prepare(sql: string): SqliteStatement {\n const statement = this.database.prepare(sql)\n return {\n // A statement that returns columns (SELECT, or anything with RETURNING) is a reader.\n reader: statement.columnNames.length > 0,\n all: (parameters) => statement.all(...parameters),\n run: (parameters) => statement.run(...parameters),\n iterate: (parameters) => statement.iterate(...parameters),\n }\n }\n}\n\n/** Opens a SQLite database with bun:sqlite on Bun and better-sqlite3 on Node. */\nexport async function openSqlite(filename: string): Promise<SqliteDatabase> {\n if (isBun()) {\n // A variable specifier keeps bundlers, Vite and the dependency checker from trying to resolve bun:sqlite on Node.\n const specifier = 'bun:sqlite'\n const { Database } = (await import(/* @vite-ignore */ specifier)) as { Database: new (filename: string) => BunDatabase }\n const database = new Database(filename)\n // better-sqlite3 waits 5 seconds for a lock by default; bun:sqlite fails at once with SQLITE_BUSY.\n database.prepare('PRAGMA busy_timeout = 5000').run()\n return new BunSqliteDatabase(database)\n }\n const { default: Database } = await importOptional('better-sqlite3', 'The sqlite connection', () => import('better-sqlite3'))\n return new Database(filename)\n}\n","import { importOptional } from '@orieljs/support'\nimport { CompiledQuery, MysqlDialect, PostgresDialect, SqliteDialect, type Dialect } from 'kysely'\nimport type { DriverName } from '@orieljs/contracts'\nimport { DatabaseConfigError } from '../errors'\nimport { openSqlite } from './SqliteDatabase'\n\n/** One entry of `config('database.connections')`, in Laravel's config/database.php shape. */\nexport interface ConnectionConfig {\n driver: DriverName\n url?: string\n database?: string\n host?: string\n port?: string | number\n username?: string\n password?: string\n charset?: string\n collation?: string\n /** pgsql only. */\n search_path?: string\n /** sqlite only. Defaults to true, like Laravel's DB_FOREIGN_KEYS. */\n foreign_key_constraints?: boolean\n pool?: { max?: number }\n}\n\nconst PG_INT8 = 20\nconst PG_DATE = 1082\nconst PG_TIMESTAMP = 1114\nconst PG_TIMESTAMPTZ = 1184\n\n/**\n * The mysql2 pool options for a connection. When `url` is set its parts (host, port, user, password,\n * database) win over the individual keys, like Laravel; keys it leaves out fall back to the config.\n */\nexport function mysqlPoolOptions(config: ConnectionConfig): Record<string, unknown> {\n const options: Record<string, unknown> = {}\n if (config.url) {\n try {\n const url = new URL(config.url)\n const decoded = (value: string) => (value ? decodeURIComponent(value) : undefined)\n Object.assign(options, {\n host: url.hostname || undefined,\n port: url.port ? Number(url.port) : undefined,\n database: decoded(url.pathname.slice(1)),\n user: decoded(url.username),\n password: decoded(url.password),\n })\n // Query parameters are mysql2 options; like mysql2 itself, JSON-parse the value when it is JSON.\n for (const [key, value] of [...url.searchParams.entries()]) {\n try {\n options[key] = JSON.parse(value)\n } catch {\n options[key] = value\n }\n }\n } catch {\n throw new DatabaseConfigError('Invalid database url.')\n }\n }\n const fallbacks = {\n host: config.host,\n port: config.port === undefined || config.port === '' ? undefined : Number(config.port),\n database: config.database,\n user: config.username,\n password: config.password,\n charset: config.charset ?? 'utf8mb4',\n connectionLimit: config.pool?.max ?? 10,\n dateStrings: true,\n supportBigNumbers: true,\n timezone: 'Z',\n }\n for (const [key, value] of Object.entries(fallbacks)) options[key] ??= value\n return options\n}\n\n/** Builds the Kysely dialect for a connection. Driver modules are imported lazily, on the first query. */\nexport function createDialect(config: ConnectionConfig): Dialect {\n switch (config.driver) {\n case 'sqlite': {\n const foreignKeys = config.foreign_key_constraints ?? true\n return new SqliteDialect({\n database: () => openSqlite(config.database ?? ':memory:'),\n onCreateConnection: async (connection) => {\n await connection.executeQuery(CompiledQuery.raw(`PRAGMA foreign_keys = ${foreignKeys ? 'ON' : 'OFF'}`))\n },\n })\n }\n case 'pgsql':\n return new PostgresDialect({\n pool: async () => {\n const { default: pg } = await importOptional('pg', 'The pgsql connection', () => import('pg'))\n return new pg.Pool({\n connectionString: config.url,\n host: config.host,\n port: config.port === undefined ? undefined : Number(config.port),\n database: config.database,\n user: config.username,\n password: config.password,\n max: config.pool?.max ?? 10,\n types: {\n // Dates stay strings (casts parse them as UTC); bigint ids become numbers when they fit.\n getTypeParser: ((oid: number, format?: 'text' | 'binary') => {\n if (oid === PG_INT8) return (value: string) => (Number.isSafeInteger(Number(value)) ? Number(value) : value)\n if (oid === PG_DATE || oid === PG_TIMESTAMP || oid === PG_TIMESTAMPTZ) return (value: string) => value\n return pg.types.getTypeParser(oid, format)\n }) as typeof pg.types.getTypeParser,\n },\n })\n },\n onCreateConnection: async (connection) => {\n if (config.search_path) {\n await connection.executeQuery(CompiledQuery.raw(`set search_path to ${config.search_path}`))\n }\n },\n })\n case 'mysql':\n return new MysqlDialect({\n pool: async () => {\n const { createPool } = await importOptional('mysql2', 'The mysql connection', () => import('mysql2'))\n type PoolOptions = Parameters<typeof createPool>[0] & object\n return createPool(mysqlPoolOptions(config) as PoolOptions)\n },\n })\n default:\n throw new DatabaseConfigError(`Unsupported driver [${String((config as { driver: unknown }).driver)}].`)\n }\n}\n","import { sql, type RawBuilder } from 'kysely'\nimport { LogicError } from '../errors'\n\n/** A raw SQL fragment, never escaped: DB.raw('count(*) as total'). Use `?` placeholders for values. */\nexport class Expression {\n constructor(\n readonly value: string,\n readonly bindings: readonly unknown[] = [],\n ) {}\n\n toString(): string {\n return this.value\n }\n}\n\nexport const raw = (value: string, bindings: readonly unknown[] = []): Expression => new Expression(value, bindings)\n\n/**\n * Turns `select * from users where id = ?` + bindings into a Kysely RawBuilder, so each dialect gets its own\n * placeholders ($1 on Postgres). `?` inside quoted strings isn't special-cased: bind such values instead.\n */\nexport function rawWithBindings(query: string, bindings: readonly unknown[] = []): RawBuilder<unknown> {\n const fragments = query.split('?')\n if (fragments.length - 1 !== bindings.length) {\n throw new LogicError(`The query has ${fragments.length - 1} placeholders but ${bindings.length} bindings were given: ${query}`)\n }\n const strings = Object.assign([...fragments], { raw: [...fragments] }) as unknown as TemplateStringsArray\n return sql(strings, ...bindings)\n}\n","import { sql } from 'kysely'\nimport type { Operator, QueryBuilder, Row } from '@orieljs/contracts'\nimport { Collection, LazyCollection } from '@orieljs/collections'\nimport type { Connection } from '../Connection'\nimport { LogicError } from '../errors'\nimport { AbstractPaginator } from '../Pagination/AbstractPaginator'\nimport { Cursor, CursorPaginator } from '../Pagination/CursorPaginator'\nimport { LengthAwarePaginator } from '../Pagination/LengthAwarePaginator'\nimport { Paginator } from '../Pagination/Paginator'\nimport { Expression } from './Expression'\nimport { Grammar } from './Grammar'\n\n/** The row number column limitPerGroup() adds; it never reaches the rows a query returns. */\nexport const GROUP_ROW = 'oriel_row'\n\nexport type WhereBoolean = 'and' | 'or'\nexport type Direction = 'asc' | 'desc'\nexport type ColumnRef = string | Expression\n\nexport type Where =\n | { type: 'basic'; column: ColumnRef | Builder<unknown>; operator: string; value: unknown; boolean: WhereBoolean }\n | { type: 'in'; column: ColumnRef; values: readonly unknown[] | Builder<unknown>; not: boolean; boolean: WhereBoolean }\n | { type: 'null'; column: ColumnRef; not: boolean; boolean: WhereBoolean }\n | { type: 'between'; column: ColumnRef; values: readonly [unknown, unknown]; not: boolean; boolean: WhereBoolean }\n | { type: 'like'; column: ColumnRef; value: string; caseSensitive: boolean; not: boolean; boolean: WhereBoolean }\n | { type: 'column'; first: ColumnRef; operator: string; second: ColumnRef; boolean: WhereBoolean }\n | { type: 'nested'; query: Builder<unknown>; not: boolean; boolean: WhereBoolean }\n | { type: 'exists'; query: Builder<unknown>; not: boolean; boolean: WhereBoolean }\n | { type: 'raw'; sql: string; bindings: readonly unknown[]; boolean: WhereBoolean }\n | { type: 'date'; part: DatePart; column: ColumnRef; operator: string; value: unknown; boolean: WhereBoolean }\n\n/** The part of a date or time column a date where clause compares (whereDate() → 'date', whereYear() → 'year', …). */\nexport type DatePart = 'date' | 'time' | 'day' | 'month' | 'year'\n/** What a date where clause compares with: a Date (read in UTC), a string, a number, or DB.raw(). */\nexport type DateWhereValue = Date | string | number | Expression\n/** whereDate('published_at', '2026-01-05') or whereDate('published_at', '>=', new Date()). */\nexport type DateWhereArgs = [value: DateWhereValue] | [operator: string, value: DateWhereValue]\n\nexport type Having =\n | { column: ColumnRef; operator: string; value: unknown; boolean: WhereBoolean }\n | { raw: Expression; boolean: WhereBoolean }\n\nexport type Order = { column: ColumnRef; direction: Direction } | { raw: Expression }\n/** A column, an expression, or `(subquery) as alias` (`exists (subquery) as alias` with exists). */\nexport type SelectColumn = ColumnRef | { query: Builder<unknown>; as: string; exists?: boolean }\n\ntype NestedCallback<Q> = (query: Q) => unknown\n\n/** The value when()'s callback receives: the condition's type without its falsy members. */\nexport type Truthy<V> = Exclude<V, false | 0 | 0n | '' | null | undefined>\n\n/** Pages through a query lazily, one chunk per query (lazy()). */\nasync function* chunksOf<T>(query: Builder<T>, chunkSize: number): AsyncGenerator<T> {\n for (let page = 1; ; page++) {\n const results = await query.clone().forPage(page, chunkSize).runSelect()\n yield* results\n if (results.length < chunkSize) return\n }\n}\n\n/** Pages through a query lazily by key (lazyById()). */\nasync function* chunksById<T>(query: Builder<T>, chunkSize: number, column: string, alias: string): AsyncGenerator<T> {\n let lastId: unknown\n for (;;) {\n const results = await query.clone().forPageAfterId(chunkSize, lastId, column).runSelect()\n yield* results\n if (results.length < chunkSize) return\n lastId = keyOf(results.at(-1), alias)\n }\n}\n\n/** Reads the chunkById key from a row or a model. */\nfunction keyOf(item: unknown, alias: string): unknown {\n const value = (item as Record<string, unknown> | undefined)?.[alias]\n if (value === undefined || value === null) {\n throw new LogicError(`The chunkById operation was aborted because the [${alias}] column is not present in the query result.`)\n }\n return value\n}\n\nconst pad = (value: number, width = 2): string => String(value).padStart(width, '0')\n\n/**\n * Laravel's date where values: a Date becomes the compared part in UTC (the storage time zone), days and months are\n * zero-padded (sprintf('%02d')) so SQLite's strftime() text compares equal, and other numbers are sent as text (SQLite\n * binds a JavaScript number as a real, and cast(2026.0 as text) is '2026.0'). Expressions pass through.\n */\nfunction dateWhereValue(part: DatePart, value: DateWhereValue): unknown {\n if (value instanceof Expression) return value\n if (value instanceof Date) {\n if (part === 'date') return `${pad(value.getUTCFullYear(), 4)}-${pad(value.getUTCMonth() + 1)}-${pad(value.getUTCDate())}`\n if (part === 'time') return `${pad(value.getUTCHours())}:${pad(value.getUTCMinutes())}:${pad(value.getUTCSeconds())}`\n if (part === 'day') return pad(value.getUTCDate())\n if (part === 'month') return pad(value.getUTCMonth() + 1)\n return String(value.getUTCFullYear())\n }\n if (part === 'day' || part === 'month') return pad(Math.trunc(Number(value)) || 0)\n return typeof value === 'number' ? String(value) : value\n}\n\nconst isRow = (value: unknown): value is Row =>\n typeof value === 'object' && value !== null && !(value instanceof Expression) && !(value instanceof Builder) && !Array.isArray(value)\n\n/** The key a selected column comes back under: 'users.name' → 'name', 'name as n' → 'n'. */\nexport function columnKey(column: string): string {\n const alias = /\\s+as\\s+/i.exec(column)\n if (alias) return column.slice(alias.index + alias[0].length).trim()\n return column.split('.').pop()!.trim()\n}\n\n/**\n * Laravel's query builder: DB.table('users').where('votes', '>', 100).get().\n * Implements the QueryBuilder contract other components use (Queue, Cache, Session, Validation).\n */\nexport class Builder<T = Row> implements QueryBuilder<T> {\n readonly grammar: Grammar\n columns: SelectColumn[] = []\n distinctRows = false\n fromTable: string | Expression | undefined\n joins: JoinClause[] = []\n wheres: Where[] = []\n groups: ColumnRef[] = []\n havings: Having[] = []\n orders: Order[] = []\n limitValue: number | undefined\n offsetValue: number | undefined\n /** A limit and offset per value of `column` (each parent of an eager load), compiled as a window (limitPerGroup()). */\n groupLimit: { column: string; limit: number | undefined; offset: number | undefined } | undefined\n lockMode: 'update' | 'share' | undefined\n\n constructor(\n readonly connection: Connection,\n table?: string | Expression,\n ) {\n this.grammar = new Grammar(connection.getDriverName())\n this.fromTable = table\n }\n\n // ---------------------------------------------------------------- building\n\n from(table: string | Expression): this {\n this.fromTable = table\n return this\n }\n\n select(...columns: Array<ColumnRef | ColumnRef[]>): this {\n this.columns = columns.flat()\n return this\n }\n\n addSelect(...columns: Array<ColumnRef | ColumnRef[]>): this {\n this.columns.push(...columns.flat())\n return this\n }\n\n selectRaw(expression: string, bindings: readonly unknown[] = []): this {\n this.columns.push(new Expression(expression, bindings))\n return this\n }\n\n /** Adds `(subquery) as alias` to the select list. */\n selectSub(query: Builder<unknown>, as: string): this {\n if (!this.columns.length) this.columns.push('*')\n this.columns.push({ query, as })\n return this\n }\n\n distinct(): this {\n this.distinctRows = true\n return this\n }\n\n where(column: ColumnRef, value: unknown): this\n where(column: ColumnRef, operator: Operator | string, value: unknown): this\n where(conditions: Row): this\n where(callback: NestedCallback<Builder<T>>): this\n where(...args: unknown[]): this {\n return this.addWhere('and', args)\n }\n\n orWhere(column: ColumnRef, value: unknown): this\n orWhere(column: ColumnRef, operator: Operator | string, value: unknown): this\n orWhere(conditions: Row): this\n orWhere(callback: NestedCallback<Builder<T>>): this\n orWhere(...args: unknown[]): this {\n return this.addWhere('or', args)\n }\n\n /** where not (…): whereNot(q => q.where('a', 1).orWhere('b', 2)). */\n whereNot(callback: NestedCallback<Builder<T>>): this {\n return this.addNested(callback, 'and', true)\n }\n\n orWhereNot(callback: NestedCallback<Builder<T>>): this {\n return this.addNested(callback, 'or', true)\n }\n\n whereIn(column: ColumnRef, values: readonly unknown[] | Builder<unknown>): this {\n this.wheres.push({ type: 'in', column, values: Array.isArray(values) ? [...values] : values, not: false, boolean: 'and' })\n return this\n }\n\n orWhereIn(column: ColumnRef, values: readonly unknown[] | Builder<unknown>): this {\n this.wheres.push({ type: 'in', column, values: Array.isArray(values) ? [...values] : values, not: false, boolean: 'or' })\n return this\n }\n\n whereNotIn(column: ColumnRef, values: readonly unknown[] | Builder<unknown>): this {\n this.wheres.push({ type: 'in', column, values: Array.isArray(values) ? [...values] : values, not: true, boolean: 'and' })\n return this\n }\n\n orWhereNotIn(column: ColumnRef, values: readonly unknown[] | Builder<unknown>): this {\n this.wheres.push({ type: 'in', column, values: Array.isArray(values) ? [...values] : values, not: true, boolean: 'or' })\n return this\n }\n\n whereNull(columns: ColumnRef | ColumnRef[]): this {\n for (const column of [columns].flat()) this.wheres.push({ type: 'null', column, not: false, boolean: 'and' })\n return this\n }\n\n orWhereNull(column: ColumnRef): this {\n this.wheres.push({ type: 'null', column, not: false, boolean: 'or' })\n return this\n }\n\n whereNotNull(columns: ColumnRef | ColumnRef[]): this {\n for (const column of [columns].flat()) this.wheres.push({ type: 'null', column, not: true, boolean: 'and' })\n return this\n }\n\n orWhereNotNull(column: ColumnRef): this {\n this.wheres.push({ type: 'null', column, not: true, boolean: 'or' })\n return this\n }\n\n whereBetween(column: ColumnRef, values: readonly [unknown, unknown]): this {\n this.wheres.push({ type: 'between', column, values, not: false, boolean: 'and' })\n return this\n }\n\n orWhereBetween(column: ColumnRef, values: readonly [unknown, unknown]): this {\n this.wheres.push({ type: 'between', column, values, not: false, boolean: 'or' })\n return this\n }\n\n whereNotBetween(column: ColumnRef, values: readonly [unknown, unknown]): this {\n this.wheres.push({ type: 'between', column, values, not: true, boolean: 'and' })\n return this\n }\n\n /** Compares the date part of a column: whereDate('published_at', '2026-01-05'), whereDate('published_at', '<', new Date()). */\n whereDate(column: ColumnRef, ...args: DateWhereArgs): this {\n return this.addDateBasedWhere('date', column, args, 'and')\n }\n\n orWhereDate(column: ColumnRef, ...args: DateWhereArgs): this {\n return this.addDateBasedWhere('date', column, args, 'or')\n }\n\n /** Compares the time of day: whereTime('published_at', '>=', '09:00:00'). */\n whereTime(column: ColumnRef, ...args: DateWhereArgs): this {\n return this.addDateBasedWhere('time', column, args, 'and')\n }\n\n orWhereTime(column: ColumnRef, ...args: DateWhereArgs): this {\n return this.addDateBasedWhere('time', column, args, 'or')\n }\n\n /** Compares the day of the month: whereDay('published_at', 5). */\n whereDay(column: ColumnRef, ...args: DateWhereArgs): this {\n return this.addDateBasedWhere('day', column, args, 'and')\n }\n\n orWhereDay(column: ColumnRef, ...args: DateWhereArgs): this {\n return this.addDateBasedWhere('day', column, args, 'or')\n }\n\n /** Compares the month: whereMonth('published_at', 12). */\n whereMonth(column: ColumnRef, ...args: DateWhereArgs): this {\n return this.addDateBasedWhere('month', column, args, 'and')\n }\n\n orWhereMonth(column: ColumnRef, ...args: DateWhereArgs): this {\n return this.addDateBasedWhere('month', column, args, 'or')\n }\n\n /** Compares the year: whereYear('published_at', '>=', 2026). */\n whereYear(column: ColumnRef, ...args: DateWhereArgs): this {\n return this.addDateBasedWhere('year', column, args, 'and')\n }\n\n orWhereYear(column: ColumnRef, ...args: DateWhereArgs): this {\n return this.addDateBasedWhere('year', column, args, 'or')\n }\n\n /**\n * Laravel's whereLike(): the value is the pattern, `%` and `_` included (`whereLike('title', `%${term}%`)`).\n * Case-insensitive unless caseSensitive: ilike on Postgres, like on MySQL and SQLite (their like already ignores\n * case: MySQL through the column's collation, SQLite for ASCII letters). Case-sensitive is like on Postgres,\n * like binary on MySQL and glob on SQLite.\n */\n whereLike(column: ColumnRef, value: string, caseSensitive = false, boolean: WhereBoolean = 'and', not = false): this {\n this.wheres.push({ type: 'like', column, value, caseSensitive, not, boolean })\n return this\n }\n\n orWhereLike(column: ColumnRef, value: string, caseSensitive = false): this {\n return this.whereLike(column, value, caseSensitive, 'or')\n }\n\n whereNotLike(column: ColumnRef, value: string, caseSensitive = false, boolean: WhereBoolean = 'and'): this {\n return this.whereLike(column, value, caseSensitive, boolean, true)\n }\n\n orWhereNotLike(column: ColumnRef, value: string, caseSensitive = false): this {\n return this.whereNotLike(column, value, caseSensitive, 'or')\n }\n\n /** Compares two columns: whereColumn('updated_at', '>', 'created_at'). */\n whereColumn(first: ColumnRef, operatorOrSecond: string, second?: ColumnRef, boolean: WhereBoolean = 'and'): this {\n const [operator, other] = second === undefined ? ['=', operatorOrSecond] : [operatorOrSecond, second]\n this.grammar.operator(operator)\n this.wheres.push({ type: 'column', first, operator, second: other, boolean })\n return this\n }\n\n orWhereColumn(first: ColumnRef, operatorOrSecond: string, second?: ColumnRef): this {\n return this.whereColumn(first, operatorOrSecond, second, 'or')\n }\n\n whereRaw(sql: string, bindings: readonly unknown[] = [], boolean: WhereBoolean = 'and'): this {\n this.wheres.push({ type: 'raw', sql, bindings, boolean })\n return this\n }\n\n orWhereRaw(sql: string, bindings: readonly unknown[] = []): this {\n return this.whereRaw(sql, bindings, 'or')\n }\n\n whereExists(query: Builder<unknown> | NestedCallback<Builder<Row>>, boolean: WhereBoolean = 'and', not = false): this {\n const sub = query instanceof Builder ? query : this.subQuery(query)\n this.wheres.push({ type: 'exists', query: sub, not, boolean })\n return this\n }\n\n orWhereExists(query: Builder<unknown> | NestedCallback<Builder<Row>>): this {\n return this.whereExists(query, 'or')\n }\n\n whereNotExists(query: Builder<unknown> | NestedCallback<Builder<Row>>): this {\n return this.whereExists(query, 'and', true)\n }\n\n /** `(select …) <operator> value`: used by has('comments', '>=', 3). */\n whereSub(query: Builder<unknown>, operator: string, value: unknown, boolean: WhereBoolean = 'and'): this {\n this.grammar.operator(operator)\n this.wheres.push({ type: 'basic', column: query, operator, value, boolean })\n return this\n }\n\n /** Appends another builder's where clauses as one nested group. */\n addNestedWhereQuery(query: Builder<unknown>, boolean: WhereBoolean = 'and', not = false): this {\n if (query.wheres.length) this.wheres.push({ type: 'nested', query, not, boolean })\n return this\n }\n\n join(table: string | Expression, first: ColumnRef | ((join: JoinClause) => unknown), operator?: string, second?: ColumnRef, type: JoinType = 'inner'): this {\n const clause = new JoinClause(this, type, table)\n if (typeof first === 'function') first(clause)\n else clause.on(first, operator!, second)\n this.joins.push(clause)\n return this\n }\n\n leftJoin(table: string | Expression, first: ColumnRef | ((join: JoinClause) => unknown), operator?: string, second?: ColumnRef): this {\n return this.join(table, first, operator, second, 'left')\n }\n\n rightJoin(table: string | Expression, first: ColumnRef | ((join: JoinClause) => unknown), operator?: string, second?: ColumnRef): this {\n return this.join(table, first, operator, second, 'right')\n }\n\n crossJoin(table: string | Expression): this {\n this.joins.push(new JoinClause(this, 'cross', table))\n return this\n }\n\n groupBy(...columns: ColumnRef[]): this {\n this.groups.push(...columns)\n return this\n }\n\n having(column: ColumnRef, operatorOrValue: unknown, value?: unknown, boolean: WhereBoolean = 'and'): this {\n const [operator, operand] = value === undefined ? ['=', operatorOrValue] : [String(operatorOrValue), value]\n this.grammar.operator(operator)\n this.havings.push({ column, operator, value: operand, boolean })\n return this\n }\n\n havingRaw(sql: string, bindings: readonly unknown[] = [], boolean: WhereBoolean = 'and'): this {\n this.havings.push({ raw: new Expression(sql, bindings), boolean })\n return this\n }\n\n orderBy(column: ColumnRef, direction: Direction | Uppercase<Direction> = 'asc'): this {\n const normalized = direction.toLowerCase()\n if (normalized !== 'asc' && normalized !== 'desc') throw new LogicError('Order direction must be \"asc\" or \"desc\".')\n this.orders.push({ column, direction: normalized })\n return this\n }\n\n orderByDesc(column: ColumnRef): this {\n return this.orderBy(column, 'desc')\n }\n\n latest(column: ColumnRef = 'created_at'): this {\n return this.orderBy(column, 'desc')\n }\n\n oldest(column: ColumnRef = 'created_at'): this {\n return this.orderBy(column, 'asc')\n }\n\n inRandomOrder(): this {\n this.orders.push({ raw: this.grammar.compileRandom() })\n return this\n }\n\n orderByRaw(sql: string, bindings: readonly unknown[] = []): this {\n this.orders.push({ raw: new Expression(sql, bindings) })\n return this\n }\n\n /** Removes existing orders, optionally adding a new one. */\n reorder(column?: ColumnRef, direction: Direction = 'asc'): this {\n this.orders = []\n return column === undefined ? this : this.orderBy(column, direction)\n }\n\n limit(count: number): this {\n this.limitValue = count >= 0 ? Math.trunc(count) : undefined\n return this\n }\n\n take(count: number): this {\n return this.limit(count)\n }\n\n offset(count: number): this {\n this.offsetValue = Math.max(0, Math.trunc(count))\n return this\n }\n\n skip(count: number): this {\n return this.offset(count)\n }\n\n forPage(page: number, perPage = 15): this {\n return this.offset((Math.max(1, page) - 1) * perPage).limit(perPage)\n }\n\n lockForUpdate(): this {\n this.lockMode = 'update'\n return this\n }\n\n sharedLock(): this {\n this.lockMode = 'share'\n return this\n }\n\n /**\n * Laravel's when(): callback(query, value) runs when the value is truthy, otherwise(query, value) when it is falsy.\n * A function value is called with the query first and its result is the value. Truthiness is JavaScript's, so `'0'`\n * and `[]` are truthy: a `?active=0` filter applies, where Laravel would skip it. Returns the query; what the\n * callbacks return is ignored.\n *\n * @example\n * Post.query().when(request.query('q'), (query, q) => query.whereLike('title', `%${q}%`))\n */\n when<V>(value: (query: this) => V, callback: (query: this, value: Truthy<V>) => unknown, otherwise?: (query: this, value: V) => unknown): this\n when<V>(value: V, callback: (query: this, value: Truthy<V>) => unknown, otherwise?: (query: this, value: V) => unknown): this\n when(value: unknown, callback: (query: this, value: unknown) => unknown, otherwise?: (query: this, value: unknown) => unknown): this {\n const resolved = typeof value === 'function' ? (value as (query: this) => unknown)(this) : value\n if (resolved) callback(this, resolved)\n else otherwise?.(this, resolved)\n return this\n }\n\n /** Laravel's unless(): when() with the condition reversed. callback(query, value) runs when the value is falsy. */\n unless<V>(value: (query: this) => V, callback: (query: this, value: V) => unknown, otherwise?: (query: this, value: Truthy<V>) => unknown): this\n unless<V>(value: V, callback: (query: this, value: V) => unknown, otherwise?: (query: this, value: Truthy<V>) => unknown): this\n unless(value: unknown, callback: (query: this, value: unknown) => unknown, otherwise?: (query: this, value: unknown) => unknown): this {\n const resolved = typeof value === 'function' ? (value as (query: this) => unknown)(this) : value\n if (!resolved) callback(this, resolved)\n else otherwise?.(this, resolved)\n return this\n }\n\n tap(callback: (query: this) => unknown): this {\n callback(this)\n return this\n }\n\n // ---------------------------------------------------------------- reading\n\n async get(): Promise<Collection<T>> {\n return this.newCollection(await this.runSelect())\n }\n\n /** The collection get() and chunk() hand out (Eloquent's builder makes the model's collection). */\n protected newCollection(items: T[]): Collection<T> {\n return new Collection(items)\n }\n\n /** The raw rows, without a Collection around them. */\n async runSelect(): Promise<T[]> {\n const rows = (await this.connection.execute<T>(this.grammar.compileSelect(this))).rows\n if (this.groupLimit) for (const row of rows) delete (row as Row)[GROUP_ROW]\n return rows\n }\n\n /**\n * @internal Eager loading (Laravel 11's groupLimit()): the limit and offset set so far apply to each value of `column`,\n * the parent's key, instead of to the whole query. Compiled as row_number() over (partition by …).\n */\n limitPerGroup(column: string): this {\n if (this.limitValue === undefined && this.offsetValue === undefined) return this\n this.groupLimit = { column, limit: this.limitValue, offset: this.offsetValue }\n this.limitValue = undefined\n this.offsetValue = undefined\n return this\n }\n\n async first(): Promise<T | undefined> {\n const rows = await this.clone().limit(1).runSelect()\n return rows[0]\n }\n\n async find(id: unknown, keyName = 'id'): Promise<T | undefined> {\n return this.clone().where(keyName, '=', id).first()\n }\n\n async value<V = unknown>(column: string): Promise<V | undefined> {\n const row = (await this.clone().select(column).first()) as Row | undefined\n return row?.[columnKey(column)] as V | undefined\n }\n\n async pluck<V = unknown>(column: string): Promise<Collection<V>> {\n const rows = (await this.clone().select(column).runSelect()) as Row[]\n const key = columnKey(column)\n return new Collection(rows.map((row) => row[key] as V))\n }\n\n async count(column: ColumnRef = '*'): Promise<number> {\n return Number((await this.aggregate('count', column)) ?? 0)\n }\n\n async min<V = unknown>(column: ColumnRef): Promise<V | undefined> {\n return (await this.aggregate('min', column)) as V | undefined\n }\n\n async max<V = unknown>(column: ColumnRef): Promise<V | undefined> {\n return (await this.aggregate('max', column)) as V | undefined\n }\n\n async sum(column: ColumnRef): Promise<number> {\n return Number((await this.aggregate('sum', column)) ?? 0)\n }\n\n async avg(column: ColumnRef): Promise<number | undefined> {\n const result = await this.aggregate('avg', column)\n return result === null || result === undefined ? undefined : Number(result)\n }\n\n async aggregate(fn: 'count' | 'min' | 'max' | 'sum' | 'avg', column: ColumnRef): Promise<unknown> {\n const result = await this.connection.execute<{ aggregate: unknown }>(this.grammar.compileAggregate(this, fn, column))\n return result.rows[0]?.aggregate ?? undefined\n }\n\n async exists(): Promise<boolean> {\n const result = await this.connection.execute<{ exists: unknown }>(this.grammar.compileExists(this))\n const value = result.rows[0]?.exists\n return value === true || value === 1 || value === '1' || value === 't'\n }\n\n async doesntExist(): Promise<boolean> {\n return !(await this.exists())\n }\n\n // ---------------------------------------------------------------- writing\n\n async insert(values: Row | Row[]): Promise<void> {\n const rows = Array.isArray(values) ? values : [values]\n if (!rows.length) return\n await this.connection.execute(this.grammar.compileInsert(this, rows))\n }\n\n /** Inserts one row and returns its auto-increment id. */\n async insertGetId(values: Row, keyName = 'id'): Promise<number | string> {\n const result = await this.connection.execute<Row>(this.grammar.compileInsertGetId(this, values, keyName))\n if (this.connection.getDriverName() === 'pgsql') return result.rows[0]![keyName] as number | string\n return Number(result.insertId)\n }\n\n /** Inserts rows, skipping the ones that violate a unique constraint. Returns how many were inserted. */\n async insertOrIgnore(values: Row | Row[]): Promise<number> {\n const rows = Array.isArray(values) ? values : [values]\n if (!rows.length) return 0\n return Number((await this.connection.execute(this.grammar.compileInsertOrIgnore(this, rows))).numAffectedRows ?? 0)\n }\n\n async update(values: Row): Promise<number> {\n if (!Object.keys(values).length) return 0\n return Number((await this.connection.execute(this.grammar.compileUpdate(this, values))).numAffectedRows ?? 0)\n }\n\n /** Updates the row matching attributes, or inserts attributes + values. */\n async updateOrInsert(attributes: Row, values: Row = {}): Promise<boolean> {\n if (!(await this.clone().where(attributes).exists())) {\n await this.insert({ ...attributes, ...values })\n return true\n }\n if (!Object.keys(values).length) return true\n await this.clone().where(attributes).update(values)\n return true\n }\n\n /**\n * Inserts rows, updating `update` (default: every inserted column except uniqueBy) when a row already exists.\n * uniqueBy must be a primary key or unique index (Postgres and SQLite need it for ON CONFLICT).\n */\n async upsert(values: Row | Row[], uniqueBy: string[], update?: string[]): Promise<number> {\n const rows = Array.isArray(values) ? values : [values]\n if (!rows.length) return 0\n const columns = update ?? Object.keys(rows[0]!).filter((column) => !uniqueBy.includes(column))\n if (!columns.length) return this.insertOrIgnore(rows)\n return Number((await this.connection.execute(this.grammar.compileUpsert(this, rows, uniqueBy, columns))).numAffectedRows ?? 0)\n }\n\n async increment(column: string, amount = 1, extra: Row = {}): Promise<number> {\n return this.update({ ...extra, [column]: sql`${this.grammar.wrap(column)} + ${amount}` })\n }\n\n async decrement(column: string, amount = 1, extra: Row = {}): Promise<number> {\n return this.update({ ...extra, [column]: sql`${this.grammar.wrap(column)} - ${amount}` })\n }\n\n async delete(id?: unknown): Promise<number> {\n if (id !== undefined) this.where('id', '=', id)\n return Number((await this.connection.execute(this.grammar.compileDelete(this))).numAffectedRows ?? 0)\n }\n\n async truncate(): Promise<void> {\n for (const statement of this.grammar.compileTruncate(this)) await this.connection.execute(statement)\n if (this.connection.getDriverName() === 'sqlite') {\n const sequence = await this.connection.select(\"select name from sqlite_master where type = 'table' and name = 'sqlite_sequence'\")\n if (sequence.length) await this.connection.statement('delete from sqlite_sequence where name = ?', [String(this.requireTable())])\n }\n }\n\n // ---------------------------------------------------------------- pagination and chunking\n\n /**\n * Paginates with a total count (two queries: count, then the page). The page comes from ?page= on the current\n * request unless given: DB.table('users').orderBy('id').paginate(15).\n */\n async paginate(perPage?: number, columns: ColumnRef[] = ['*'], pageName = 'page', page?: number): Promise<LengthAwarePaginator<T>> {\n const size = perPage ?? this.defaultPerPage()\n const current = page ?? AbstractPaginator.resolveCurrentPage(pageName)\n const total = await this.clone().count()\n const items = total > 0 ? await this.clone().withColumns(columns).forPage(current, size).runSelect() : []\n return new LengthAwarePaginator(items, total, size, current, { path: AbstractPaginator.resolveCurrentPath(), pageName })\n }\n\n /** Paginates without a count: fetches perPage + 1 rows to know whether there is a next page. */\n async simplePaginate(perPage?: number, columns: ColumnRef[] = ['*'], pageName = 'page', page?: number): Promise<Paginator<T>> {\n const size = perPage ?? this.defaultPerPage()\n const current = page ?? AbstractPaginator.resolveCurrentPage(pageName)\n const items = await this.clone().withColumns(columns).offset((current - 1) * size).limit(size + 1).runSelect()\n return new Paginator(items, size, current, { path: AbstractPaginator.resolveCurrentPath(), pageName })\n }\n\n /**\n * Paginates by the ordered columns' values instead of an offset. Needs an orderBy (Eloquent adds the primary key);\n * the cursor comes from ?cursor= on the current request unless given.\n */\n async cursorPaginate(perPage?: number, columns: ColumnRef[] = ['*'], cursorName = 'cursor', cursor?: Cursor | string): Promise<CursorPaginator<T>> {\n const size = perPage ?? this.defaultPerPage()\n const current = cursor instanceof Cursor ? cursor : cursor === undefined ? CursorPaginator.resolveCurrentCursor(cursorName) : Cursor.fromEncoded(cursor)\n const query = this.clone().withColumns(columns)\n const orders = query.ordersForCursor(current?.pointsToPreviousItems() ?? false)\n if (current) query.whereCursor(current, orders, 0)\n const items = await query.limit(size + 1).runSelect()\n return new CursorPaginator(items, size, current, {\n path: AbstractPaginator.resolveCurrentPath(),\n cursorName,\n parameters: orders.map((order) => String(order.column)),\n })\n }\n\n /**\n * Runs the query page by page and passes each chunk to callback. Return false to stop. Needs an orderBy, so that\n * pages don't overlap. Don't update the ordered column inside the callback; use chunkById() for that.\n */\n async chunk(count: number, callback: (results: Collection<T>, page: number) => unknown): Promise<boolean> {\n this.enforceOrderBy()\n for (let page = 1; ; page++) {\n const results = await this.clone().forPage(page, count).runSelect()\n if (!results.length) return true\n if ((await callback(this.newCollection(results), page)) === false) return false\n if (results.length < count) return true\n }\n }\n\n /** Chunks by comparing the key (where id > last id), so it is safe to update or delete rows inside the callback. */\n async chunkById(\n count: number,\n callback: (results: Collection<T>, page: number) => unknown,\n column?: string,\n alias?: string,\n ): Promise<boolean> {\n const key = column ?? this.defaultKeyName()\n const aliasName = alias ?? columnKey(key)\n let lastId: unknown\n for (let page = 1; ; page++) {\n const results = await this.clone().forPageAfterId(count, lastId, key).runSelect()\n if (!results.length) return true\n if ((await callback(this.newCollection(results), page)) === false) return false\n if (results.length < count) return true\n lastId = keyOf(results.at(-1), aliasName)\n }\n }\n\n /** Calls callback for every row, fetching `count` rows per query. Return false to stop. */\n async each(callback: (item: T, index: number) => unknown, count = 1000): Promise<boolean> {\n return this.chunk(count, async (results) => {\n for (const [index, item] of results.all().entries()) {\n if ((await callback(item, index)) === false) return false\n }\n return true\n })\n }\n\n /** A LazyCollection that runs one query per chunk as it is iterated: for await (const user of query.lazy()). */\n lazy(chunkSize = 1000): LazyCollection<T> {\n if (chunkSize < 1) throw new LogicError('The chunk size should be at least 1')\n this.enforceOrderBy()\n const query = this.clone()\n return LazyCollection.make(() => chunksOf(query, chunkSize))\n }\n\n /** Like lazy(), but pages by key, so rows can be updated while iterating. */\n lazyById(chunkSize = 1000, column?: string, alias?: string): LazyCollection<T> {\n if (chunkSize < 1) throw new LogicError('The chunk size should be at least 1')\n const key = column ?? this.defaultKeyName()\n const query = this.clone()\n return LazyCollection.make(() => chunksById(query, chunkSize, key, alias ?? columnKey(key)))\n }\n\n /** where column > lastId order by column limit perPage (existing orders on the column are replaced). */\n forPageAfterId(perPage = 15, lastId?: unknown, column = 'id'): this {\n this.orders = this.orders.filter((order) => 'raw' in order || order.column !== column)\n if (lastId !== undefined && lastId !== null) this.where(column, '>', lastId)\n return this.orderBy(column, 'asc').limit(perPage)\n }\n\n /** chunk() and lazy() need a stable order. Eloquent orders by the primary key instead of throwing. */\n protected enforceOrderBy(): void {\n if (!this.orders.length) throw new LogicError('You must specify an orderBy clause when using this function.')\n }\n\n /** The key chunkById()/lazyById() use by default. Eloquent uses the model's key. */\n protected defaultKeyName(): string {\n return 'id'\n }\n\n /** The page size when none is given. Eloquent uses the model's perPage. */\n protected defaultPerPage(): number {\n return 15\n }\n\n /** Laravel's get($columns): only applies when no columns were selected yet. */\n private withColumns(columns: ColumnRef[]): this {\n if (!this.columns.length && !(columns.length === 1 && columns[0] === '*')) this.select(...columns)\n return this\n }\n\n /** The column orders cursor pagination compares on; reversed (in the query too) when paging backwards. */\n private ordersForCursor(reverse: boolean): Array<{ column: ColumnRef; direction: Direction }> {\n this.enforceOrderBy()\n if (this.orders.some((order) => 'raw' in order)) throw new LogicError('cursorPaginate() only supports column orders, not orderByRaw() or inRandomOrder().')\n const orders = this.orders as Array<{ column: ColumnRef; direction: Direction }>\n if (reverse) this.orders = orders.map((order) => ({ column: order.column, direction: order.direction === 'asc' ? 'desc' : 'asc' }))\n return this.orders as Array<{ column: ColumnRef; direction: Direction }>\n }\n\n /** (a > ?) or (a = ? and (b > ? or (b = ? and …))), Laravel's cursor conditions. */\n private whereCursor(cursor: Cursor, orders: Array<{ column: ColumnRef; direction: Direction }>, index: number): void {\n const { column, direction } = orders[index]!\n this.where((query) => {\n query.where(column, direction === 'asc' ? '>' : '<', cursor.parameter(String(column)))\n if (index < orders.length - 1) {\n query.orWhere((next) => {\n next.where(column, '=', cursor.parameter(String(column)))\n next.whereCursor(cursor, orders, index + 1)\n })\n }\n })\n }\n\n // ---------------------------------------------------------------- helpers\n\n /** The compiled SQL (placeholders included), for debugging and tests. */\n toSql(): string {\n return this.connection.compile(this.grammar.compileSelect(this)).sql\n }\n\n getBindings(): unknown[] {\n return [...this.connection.compile(this.grammar.compileSelect(this)).parameters]\n }\n\n clone(): Builder<T> {\n const copy = Object.create(Object.getPrototypeOf(this) as object) as Builder<T>\n Object.assign(copy, this)\n copy.columns = [...this.columns]\n copy.joins = [...this.joins]\n copy.wheres = [...this.wheres]\n copy.groups = [...this.groups]\n copy.havings = [...this.havings]\n copy.orders = [...this.orders]\n return copy\n }\n\n /** A fresh builder on the same connection and table (for nested where groups). */\n newQuery(): Builder<Row> {\n return new Builder<Row>(this.connection, this.fromTable)\n }\n\n requireTable(): string | Expression {\n if (this.fromTable === undefined) throw new LogicError('No table was given: use DB.table(name) or query.from(name).')\n return this.fromTable\n }\n\n private subQuery(callback: NestedCallback<Builder<Row>>): Builder<Row> {\n const query = new Builder<Row>(this.connection)\n callback(query)\n return query\n }\n\n private addNested(callback: NestedCallback<Builder<T>>, boolean: WhereBoolean, not = false): this {\n const query = this.newQuery() as unknown as Builder<T>\n callback(query)\n return this.addNestedWhereQuery(query as Builder<unknown>, boolean, not)\n }\n\n private addWhere(boolean: WhereBoolean, args: unknown[]): this {\n const [column, operatorOrValue, maybeValue] = args\n if (typeof column === 'function') return this.addNested(column as NestedCallback<Builder<T>>, boolean)\n if (isRow(column)) {\n return this.addNested((query) => {\n for (const [key, value] of Object.entries(column)) query.where(key, value)\n }, boolean)\n }\n const [operator, value] = args.length === 2 ? ['=', operatorOrValue] : [String(operatorOrValue).toLowerCase(), maybeValue]\n const ref = column as ColumnRef\n if (operator === 'in' || operator === 'not in') {\n this.wheres.push({ type: 'in', column: ref, values: value as unknown[], not: operator === 'not in', boolean })\n return this\n }\n if (value === null || value === undefined) {\n if (operator === '=') return this.pushNull(ref, false, boolean)\n if (operator === '!=' || operator === '<>') return this.pushNull(ref, true, boolean)\n }\n this.grammar.operator(operator)\n this.wheres.push({ type: 'basic', column: ref, operator, value, boolean })\n return this\n }\n\n /** Laravel's addDateBasedWhere(): one value means '='; the operator is checked against the whitelist. */\n private addDateBasedWhere(part: DatePart, column: ColumnRef, args: DateWhereArgs, boolean: WhereBoolean): this {\n const [operator, value] = args.length === 1 ? ['=', args[0]] : [args[0].toLowerCase(), args[1]]\n this.grammar.operator(operator)\n this.wheres.push({ type: 'date', part, column, operator, value: dateWhereValue(part, value), boolean })\n return this\n }\n\n private pushNull(column: ColumnRef, not: boolean, boolean: WhereBoolean): this {\n this.wheres.push({ type: 'null', column, not, boolean })\n return this\n }\n}\n\nexport type JoinType = 'inner' | 'left' | 'right' | 'cross'\n\n/** The `on …` part of a join. `where()` on a join binds a value; `on()` compares columns. */\nexport class JoinClause extends Builder<Row> {\n constructor(\n parent: Builder<unknown>,\n readonly joinType: JoinType,\n readonly table: string | Expression,\n ) {\n super(parent.connection)\n }\n\n on(first: ColumnRef, operator: string, second?: ColumnRef, boolean: WhereBoolean = 'and'): this {\n return this.whereColumn(first, operator, second, boolean)\n }\n\n orOn(first: ColumnRef, operator: string, second?: ColumnRef): this {\n return this.on(first, operator, second, 'or')\n }\n}\n","import { Collection } from '@orieljs/collections'\n\nexport interface PaginatorOptions {\n /** The base URL of the page links (default: the current request's URL, or '/'). */\n path?: string\n /** Extra query string values added to every link. */\n query?: Record<string, unknown>\n fragment?: string\n pageName?: string\n}\n\n/** Laravel's Arr::query(): nested values become key[0]=…, encoded as RFC 3986. */\nexport function buildQuery(values: Record<string, unknown>, prefix?: string): string {\n const parts: string[] = []\n for (const [key, value] of Object.entries(values)) {\n const name = prefix === undefined ? key : `${prefix}[${key}]`\n if (value === undefined || value === null) continue\n if (typeof value === 'object') {\n const nested = buildQuery(value as Record<string, unknown>, name)\n if (nested) parts.push(nested)\n } else {\n parts.push(`${encodeURIComponent(name)}=${encodeURIComponent(String(value))}`)\n }\n }\n return parts.join('&')\n}\n\nconst isArrayable = (value: unknown): value is { toArray(): unknown } =>\n typeof value === 'object' && value !== null && typeof (value as { toArray?: unknown }).toArray === 'function'\n\n/**\n * Shared paginator state and URL building (Laravel's AbstractPaginator).\n * The static resolvers read the current request; DatabaseServiceProvider points them at HttpRequest.\n */\nexport abstract class AbstractPaginator<T> implements Iterable<T> {\n static currentPathResolver: () => string = () => '/'\n static currentPageResolver: (pageName: string) => number = () => 1\n static queryStringResolver: () => Record<string, unknown> = () => ({})\n static currentCursorResolver: (cursorName: string) => unknown = () => undefined\n\n static resolveCurrentPath(): string {\n return AbstractPaginator.currentPathResolver()\n }\n\n static resolveCurrentPage(pageName = 'page'): number {\n const page = AbstractPaginator.currentPageResolver(pageName)\n return Number.isInteger(page) && page >= 1 ? page : 1\n }\n\n /** Restores the defaults (page 1, path '/'). Used by tests and when the provider is torn down. */\n static resetResolvers(): void {\n AbstractPaginator.currentPathResolver = () => '/'\n AbstractPaginator.currentPageResolver = () => 1\n AbstractPaginator.queryStringResolver = () => ({})\n AbstractPaginator.currentCursorResolver = () => undefined\n }\n\n protected collection: Collection<T>\n protected pathValue: string\n protected queryValues: Record<string, unknown>\n protected fragmentValue: string | undefined\n protected pageName: string\n /** The resolved page number: page-based paginators pass it in; cursor pagination never reads it. */\n protected readonly currentPageValue: number\n onEachSideCount = 3\n\n protected constructor(\n items: Iterable<T>,\n protected readonly perPageValue: number,\n options: PaginatorOptions,\n currentPage?: number,\n ) {\n this.collection = new Collection(items)\n const path = options.path ?? AbstractPaginator.resolveCurrentPath()\n this.pathValue = path !== '/' ? path.replace(/\\/+$/, '') : path\n this.queryValues = { ...(options.query ?? {}) }\n this.fragmentValue = options.fragment\n this.pageName = options.pageName ?? 'page'\n this.currentPageValue = currentPage !== undefined && Number.isInteger(currentPage) && currentPage >= 1\n ? currentPage\n : AbstractPaginator.resolveCurrentPage(this.pageName)\n }\n\n currentPage(): number {\n return this.currentPageValue\n }\n\n /** The 1-based position of the first item on this page, or null when the page is empty. */\n firstItem(): number | null {\n return this.count() > 0 ? (this.currentPageValue - 1) * this.perPageValue + 1 : null\n }\n\n lastItem(): number | null {\n const first = this.firstItem()\n return first === null ? null : first + this.count() - 1\n }\n\n onFirstPage(): boolean {\n return this.currentPageValue <= 1\n }\n\n previousPageUrl(): string | null {\n return this.currentPageValue > 1 ? this.url(this.currentPageValue - 1) : null\n }\n\n /** The URL for a page number: path?query&page=n#fragment. */\n url(page: number): string {\n const parameters = { ...this.queryValues, [this.pageName]: Math.max(1, page) }\n return this.pathValue + (this.pathValue.includes('?') ? '&' : '?') + buildQuery(parameters) + this.buildFragment()\n }\n\n protected buildFragment(): string {\n return this.fragmentValue ? `#${this.fragmentValue}` : ''\n }\n\n path(): string {\n return this.pathValue\n }\n\n withPath(path: string): this {\n this.pathValue = path\n return this\n }\n\n setPath(path: string): this {\n return this.withPath(path)\n }\n\n /** Adds values to every link's query string. */\n appends(key: string | Record<string, unknown>, value?: unknown): this {\n if (typeof key === 'string') this.queryValues[key] = value\n else Object.assign(this.queryValues, key)\n return this\n }\n\n /** Keeps the current request's query string on every link. */\n withQueryString(): this {\n return this.appends(AbstractPaginator.queryStringResolver())\n }\n\n fragment(fragment: string): this {\n this.fragmentValue = fragment\n return this\n }\n\n getPageName(): string {\n return this.pageName\n }\n\n setPageName(name: string): this {\n this.pageName = name\n return this\n }\n\n onEachSide(count: number): this {\n this.onEachSideCount = count\n return this\n }\n\n /** The items on this page, as an array (Laravel's items()). */\n items(): T[] {\n return this.collection.all()\n }\n\n getCollection(): Collection<T> {\n return this.collection\n }\n\n setCollection(items: Collection<T>): this {\n this.collection = items\n return this\n }\n\n /**\n * Transforms each item in place, typically for serialization, and returns this paginator typed with the new items:\n * `posts.through((post) => ({ id: post.id }))`. Each paginator narrows the return type to its own class.\n */\n through<U>(callback: (item: T, index: number) => U): AbstractPaginator<U> {\n this.collection = this.collection.map(callback) as unknown as Collection<T>\n return this as unknown as AbstractPaginator<U>\n }\n\n perPage(): number {\n return this.perPageValue\n }\n\n count(): number {\n return this.collection.count()\n }\n\n isEmpty(): boolean {\n return this.collection.isEmpty()\n }\n\n isNotEmpty(): boolean {\n return !this.collection.isEmpty()\n }\n\n [Symbol.iterator](): Iterator<T> {\n return this.collection[Symbol.iterator]()\n }\n\n protected itemsToArray(): unknown[] {\n return this.collection.all().map((item) => (isArrayable(item) ? item.toArray() : item))\n }\n\n abstract toArray(): Record<string, unknown>\n\n toJSON(): Record<string, unknown> {\n return this.toArray()\n }\n\n toJson(): string {\n return JSON.stringify(this.toArray())\n }\n}\n","import { Collection } from '@orieljs/collections'\nimport { LogicError } from '../errors'\nimport { AbstractPaginator, buildQuery, type PaginatorOptions } from './AbstractPaginator'\n\n/** A position in a cursor-paginated result: the ordered columns' values of an edge item, plus the direction. */\nexport class Cursor {\n constructor(\n protected readonly parameters: Record<string, unknown>,\n protected readonly pointsToNext = true,\n ) {}\n\n parameter(name: string): unknown {\n if (!Object.hasOwn(this.parameters, name)) throw new LogicError(`Unable to find parameter [${name}] in pagination item.`)\n return this.parameters[name]\n }\n\n pointsToNextItems(): boolean {\n return this.pointsToNext\n }\n\n pointsToPreviousItems(): boolean {\n return !this.pointsToNext\n }\n\n toArray(): Record<string, unknown> {\n return { ...this.parameters, _pointsToNextItems: this.pointsToNext }\n }\n\n /** URL-safe base64 of the JSON parameters (Laravel's format). */\n encode(): string {\n return Buffer.from(JSON.stringify(this.toArray())).toString('base64').replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n }\n\n /** Decodes a cursor from the query string. Anything malformed gives undefined (the first page). */\n static fromEncoded(encoded: unknown): Cursor | undefined {\n if (typeof encoded !== 'string' || encoded === '') return undefined\n try {\n const json: unknown = JSON.parse(Buffer.from(encoded.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'))\n if (typeof json !== 'object' || json === null || Array.isArray(json)) return undefined\n const { _pointsToNextItems: pointsToNext, ...parameters } = json as Record<string, unknown>\n if (typeof pointsToNext !== 'boolean') return undefined\n return new Cursor(parameters, pointsToNext)\n } catch {\n return undefined\n }\n }\n}\n\nexport interface CursorPaginatorOptions extends Omit<PaginatorOptions, 'pageName'> {\n cursorName?: string\n /** The ordered columns whose values make up each cursor. */\n parameters: string[]\n}\n\n/** The value of `column` on a row or a model (a model's raw stored value, so it binds exactly as stored). */\nfunction valueOf(item: unknown, column: string): unknown {\n const key = column.includes('.') ? column.slice(column.lastIndexOf('.') + 1) : column\n const source = item as { getAttributes?: () => Record<string, unknown> } & Record<string, unknown>\n const values = typeof source.getAttributes === 'function' ? source.getAttributes() : source\n if (Object.hasOwn(values, column)) return values[column]\n if (Object.hasOwn(values, key)) return values[key]\n throw new LogicError(`Unable to find parameter [${column}] in pagination item.`)\n}\n\n/**\n * cursorPaginate(): \"next\"/\"previous\" by the ordered columns' values instead of an offset, so it stays fast and\n * stable on large, changing tables (Laravel's CursorPaginator). JSON: data, path, per_page, next_cursor,\n * next_page_url, prev_cursor, prev_page_url.\n */\nexport class CursorPaginator<T> extends AbstractPaginator<T> {\n protected readonly hasMore: boolean\n protected readonly cursorName: string\n protected readonly parameters: string[]\n\n constructor(\n items: Iterable<T>,\n perPage: number,\n protected readonly cursorValue: Cursor | undefined,\n options: CursorPaginatorOptions,\n ) {\n super(items, perPage, options)\n this.cursorName = options.cursorName ?? 'cursor'\n this.parameters = options.parameters\n this.hasMore = this.collection.count() > perPage\n this.collection = this.collection.slice(0, perPage)\n // Previous pages are fetched in reverse order; flip them back.\n if (cursorValue?.pointsToPreviousItems()) this.collection = new Collection(this.collection.all().reverse())\n }\n\n /** The cursor in the current request's query string (?cursor=…), if any. */\n static resolveCurrentCursor(cursorName = 'cursor'): Cursor | undefined {\n return Cursor.fromEncoded(AbstractPaginator.currentCursorResolver(cursorName))\n }\n\n cursor(): Cursor | undefined {\n return this.cursorValue\n }\n\n getCursorName(): string {\n return this.cursorName\n }\n\n override through<U>(callback: (item: T, index: number) => U): CursorPaginator<U> {\n return super.through(callback) as CursorPaginator<U>\n }\n\n hasMorePages(): boolean {\n return (this.cursorValue === undefined && this.hasMore) ||\n (this.cursorValue !== undefined && this.cursorValue.pointsToNextItems() && this.hasMore) ||\n (this.cursorValue !== undefined && this.cursorValue.pointsToPreviousItems())\n }\n\n override onFirstPage(): boolean {\n return this.cursorValue === undefined || (this.cursorValue.pointsToPreviousItems() && !this.hasMore)\n }\n\n nextCursor(): Cursor | undefined {\n if ((this.cursorValue === undefined || this.cursorValue.pointsToNextItems()) && !this.hasMore) return undefined\n const last = this.collection.last()\n return last === undefined ? undefined : this.cursorFor(last, true)\n }\n\n previousCursor(): Cursor | undefined {\n if (this.onFirstPage()) return undefined\n const first = this.collection.first()\n return first === undefined ? undefined : this.cursorFor(first, false)\n }\n\n nextPageUrl(): string | null {\n const cursor = this.nextCursor()\n return cursor ? this.url(cursor) : null\n }\n\n override previousPageUrl(): string | null {\n const cursor = this.previousCursor()\n return cursor ? this.url(cursor) : null\n }\n\n /** The URL for a cursor: path?query&cursor=…#fragment. */\n override url(cursor: Cursor | number): string {\n const value = typeof cursor === 'number' ? undefined : cursor.encode()\n const parameters = { ...this.queryValues, [this.cursorName]: value }\n return this.pathValue + (this.pathValue.includes('?') ? '&' : '?') + buildQuery(parameters) + this.buildFragment()\n }\n\n protected cursorFor(item: T, pointsToNext: boolean): Cursor {\n return new Cursor(Object.fromEntries(this.parameters.map((column) => [column, valueOf(item, column)])), pointsToNext)\n }\n\n toArray(): Record<string, unknown> {\n return {\n data: this.itemsToArray(),\n path: this.path(),\n per_page: this.perPageValue,\n next_cursor: this.nextCursor()?.encode() ?? null,\n next_page_url: this.nextPageUrl(),\n prev_cursor: this.previousCursor()?.encode() ?? null,\n prev_page_url: this.previousPageUrl(),\n }\n }\n}\n","import { AbstractPaginator, type PaginatorOptions } from './AbstractPaginator'\n\nexport interface PaginationLink {\n url: string | null\n label: string\n active: boolean\n}\n\n/** Page number → URL, in page order. */\ntype UrlRange = Array<[number, string]>\n\n/**\n * paginate(): knows the total, so it can render every page link (Laravel's LengthAwarePaginator).\n * JSON: current_page, data, first_page_url, from, last_page, last_page_url, links, next_page_url, path, per_page,\n * prev_page_url, to, total.\n */\nexport class LengthAwarePaginator<T> extends AbstractPaginator<T> {\n protected readonly lastPageValue: number\n\n constructor(\n items: Iterable<T>,\n protected readonly totalValue: number,\n perPage: number,\n currentPage?: number,\n options: PaginatorOptions = {},\n ) {\n super(items, perPage, options, currentPage)\n this.lastPageValue = Math.max(Math.ceil(totalValue / perPage), 1)\n }\n\n total(): number {\n return this.totalValue\n }\n\n override through<U>(callback: (item: T, index: number) => U): LengthAwarePaginator<U> {\n return super.through(callback) as LengthAwarePaginator<U>\n }\n\n lastPage(): number {\n return this.lastPageValue\n }\n\n hasPages(): boolean {\n return this.currentPageValue !== 1 || this.hasMorePages()\n }\n\n hasMorePages(): boolean {\n return this.currentPageValue < this.lastPageValue\n }\n\n onLastPage(): boolean {\n return !this.hasMorePages()\n }\n\n nextPageUrl(): string | null {\n return this.hasMorePages() ? this.url(this.currentPageValue + 1) : null\n }\n\n /**\n * The page links Laravel renders: previous, the page window with '...' gaps, next. The labels are plain text\n * (\"« Previous\", \"Next »\"), not Laravel's `«` entities, so a page can print them as text.\n */\n linkCollection(): PaginationLink[] {\n const links: PaginationLink[] = [{ url: this.previousPageUrl(), label: '\\u00AB Previous', active: false }]\n for (const element of this.elements()) {\n if (element === '...') links.push({ url: null, label: '...', active: false })\n else for (const [page, url] of element) links.push({ url, label: String(page), active: page === this.currentPageValue })\n }\n links.push({ url: this.nextPageUrl(), label: 'Next \\u00BB', active: false })\n return links\n }\n\n /** Laravel's UrlWindow: the first pages, the slider around the current page and the last pages, with '...' between. */\n protected elements(): Array<UrlRange | '...'> {\n const window = this.urlWindow()\n const elements: Array<UrlRange | '...' | undefined> = [\n window.first,\n window.slider ? '...' : undefined,\n window.slider,\n window.last ? '...' : undefined,\n window.last,\n ]\n return elements.filter((element): element is UrlRange | '...' => element !== undefined && element.length > 0)\n }\n\n private urlWindow(): { first?: UrlRange; slider?: UrlRange; last?: UrlRange } {\n const onEachSide = this.onEachSideCount\n const last = this.lastPageValue\n const current = this.currentPageValue\n if (last < onEachSide * 2 + 8) return { first: this.range(1, last) }\n const window = onEachSide + 4\n if (!this.hasPages()) return {}\n if (current <= window) return { first: this.range(1, window + onEachSide), last: this.range(last - 1, last) }\n if (current > last - window) return { first: this.range(1, 2), last: this.range(last - (window + (onEachSide - 1)), last) }\n return {\n first: this.range(1, 2),\n slider: this.range(current - onEachSide, current + onEachSide),\n last: this.range(last - 1, last),\n }\n }\n\n private range(from: number, to: number): UrlRange {\n const pages: UrlRange = []\n for (let page = from; page <= to; page++) pages.push([page, this.url(page)])\n return pages\n }\n\n toArray(): Record<string, unknown> {\n return {\n current_page: this.currentPageValue,\n data: this.itemsToArray(),\n first_page_url: this.url(1),\n from: this.firstItem(),\n last_page: this.lastPageValue,\n last_page_url: this.url(this.lastPageValue),\n links: this.linkCollection(),\n next_page_url: this.nextPageUrl(),\n path: this.path(),\n per_page: this.perPageValue,\n prev_page_url: this.previousPageUrl(),\n to: this.lastItem(),\n total: this.totalValue,\n }\n }\n}\n","import { AbstractPaginator, type PaginatorOptions } from './AbstractPaginator'\n\n/**\n * simplePaginate(): no total, only \"is there a next page\". The query fetches perPage + 1 rows; the extra row only\n * sets hasMorePages() (Laravel's Paginator).\n */\nexport class Paginator<T> extends AbstractPaginator<T> {\n protected readonly hasMore: boolean\n\n constructor(items: Iterable<T>, perPage: number, currentPage?: number, options: PaginatorOptions = {}) {\n super(items, perPage, options, currentPage)\n this.hasMore = this.collection.count() > perPage\n this.collection = this.collection.slice(0, perPage)\n }\n\n hasMorePages(): boolean {\n return this.hasMore\n }\n\n override through<U>(callback: (item: T, index: number) => U): Paginator<U> {\n return super.through(callback) as Paginator<U>\n }\n\n hasPages(): boolean {\n return this.currentPageValue !== 1 || this.hasMore\n }\n\n onLastPage(): boolean {\n return !this.hasMore\n }\n\n nextPageUrl(): string | null {\n return this.hasMore ? this.url(this.currentPageValue + 1) : null\n }\n\n toArray(): Record<string, unknown> {\n return {\n current_page: this.currentPageValue,\n current_page_url: this.url(this.currentPageValue),\n data: this.itemsToArray(),\n first_page_url: this.url(1),\n from: this.firstItem(),\n next_page_url: this.nextPageUrl(),\n path: this.path(),\n per_page: this.perPageValue,\n prev_page_url: this.previousPageUrl(),\n to: this.lastItem(),\n }\n }\n}\n","import { sql, type RawBuilder } from 'kysely'\nimport type { DriverName, Row } from '@orieljs/contracts'\nimport { LogicError } from '../errors'\nimport { Expression, rawWithBindings } from './Expression'\nimport { prepareValue } from './values'\nimport { GROUP_ROW, type Builder, type Having, type JoinClause, type Where } from './Builder'\n\ntype Sql = RawBuilder<unknown>\n\n/** The operators accepted by where()/having(). Anything else is rejected: operators are written into the SQL. */\nexport const OPERATORS = new Set(['=', '<', '>', '<=', '>=', '<>', '!=', 'like', 'not like', 'ilike', 'not ilike'])\n\nconst EMPTY: Sql = sql.raw('')\nconst isSqlFragment = (value: unknown): value is Sql =>\n typeof value === 'object' && value !== null && typeof (value as Partial<Sql>).toOperationNode === 'function'\nconst join = (parts: Sql[], separator = ', '): Sql => sql.join(parts, sql.raw(separator))\n/** Joins non-empty clauses with single spaces. */\nconst clauses = (parts: Array<Sql | undefined>): Sql => join(parts.filter((part): part is Sql => part !== undefined), ' ')\n\n/**\n * A like pattern as a SQLite glob pattern (Laravel's SQLiteGrammar::prepareWhereLikeBinding): a literal * or ? is\n * bracketed first, then % becomes * and _ becomes ?.\n */\nfunction likeToGlob(pattern: string): string {\n return pattern.replaceAll('*', '[*]').replaceAll('?', '[?]').replaceAll('%', '*').replaceAll('_', '?')\n}\n\n/** SQLite's strftime() format for each date part (Laravel's SQLiteGrammar). */\nconst SQLITE_DATE_FORMATS = { date: '%Y-%m-%d', time: '%H:%M:%S', day: '%d', month: '%m', year: '%Y' } as const\n\n/**\n * Compiles a query builder's state into a Kysely `sql` template for one driver, like Laravel's Query\\Grammars.\n * Identifiers go through sql.id() (quoted per dialect); values are always bound parameters.\n */\nexport class Grammar {\n constructor(readonly driver: DriverName) {}\n\n /** 'users.name' → \"users\".\"name\", 'users.*' → \"users\".*, 'name as n' → \"name\" as \"n\". Expressions pass through raw. */\n wrap(value: string | Expression): Sql {\n if (value instanceof Expression) return rawWithBindings(value.value, value.bindings.map((v) => this.prepare(v)))\n const alias = /\\s+as\\s+/i.exec(value)\n if (alias) {\n const left = value.slice(0, alias.index)\n const right = value.slice(alias.index + alias[0].length)\n return sql`${this.wrap(left)} as ${sql.id(right.trim())}`\n }\n return join(\n value.split('.').map((segment) => (segment === '*' ? sql.raw('*') : sql.id(segment))),\n '.',\n )\n }\n\n wrapTable(table: string | Expression): Sql {\n return this.wrap(table)\n }\n\n prepare(value: unknown): unknown {\n return prepareValue(value, this.driver)\n }\n\n /** A bound value, the raw SQL of an Expression, or a Kysely sql fragment as-is. */\n parameter(value: unknown): Sql {\n if (value instanceof Expression) return this.wrap(value)\n if (isSqlFragment(value)) return value\n return sql`${this.prepare(value)}`\n }\n\n operator(operator: string): string {\n const normalized = operator.toLowerCase()\n if (!OPERATORS.has(normalized)) throw new LogicError(`Illegal operator [${operator}].`)\n if (this.driver !== 'pgsql' && normalized.endsWith('ilike')) return normalized.replace('ilike', 'like')\n return normalized\n }\n\n columnize(columns: ReadonlyArray<string | Expression>): Sql {\n return join(columns.map((column) => this.wrap(column)))\n }\n\n compileSelect(query: Builder<unknown>, extraColumn?: Sql): Sql {\n if (query.groupLimit && extraColumn === undefined) return this.compileGroupLimit(query)\n const list = query.columns.length\n ? query.columns.map((column) => (typeof column === 'object' && 'query' in column\n ? sql`${sql.raw(column.exists ? 'exists ' : '')}(${this.compileSelect(column.query)}) as ${sql.id(column.as)}`\n : this.wrap(column)))\n : [sql.raw('*')]\n const columns = join(extraColumn ? [...list, extraColumn] : list)\n return clauses([query.distinctRows ? sql`select distinct ${columns}` : sql`select ${columns}`, this.compileComponents(query)])\n }\n\n /**\n * Laravel 11's compileGroupLimit(): the query numbers its rows per `column` in its own order, and an outer query keeps\n * those inside the limit and offset, in row-number order. SQLite 3.25+, MySQL 8 and PostgreSQL have window functions.\n */\n compileGroupLimit(query: Builder<unknown>): Sql {\n const { column, limit, offset } = query.groupLimit!\n const inner = query.clone()\n inner.groupLimit = undefined\n inner.orders = []\n const order = this.compileOrders(query)\n const over = order ? sql`partition by ${this.wrap(column)} ${order}` : sql`partition by ${this.wrap(column)}`\n const row = sql.id(GROUP_ROW)\n const kept: Sql[] = []\n if (offset !== undefined && offset > 0) kept.push(sql`${row} > ${sql.lit(offset)}`)\n if (limit !== undefined) kept.push(sql`${row} <= ${sql.lit((offset ?? 0) + limit)}`)\n return clauses([\n sql`select * from (${this.compileSelect(inner, sql`row_number() over (${over}) as ${row}`)}) as ${sql.id('oriel_table')}`,\n kept.length ? sql`where ${join(kept, ' and ')}` : undefined,\n sql`order by ${row}`,\n ])\n }\n\n /** Everything after the select list: from, joins, where, group by, having, order by, limit/offset, lock. */\n compileComponents(query: Builder<unknown>): Sql {\n return clauses([\n query.fromTable === undefined ? undefined : sql`from ${this.wrapTable(query.fromTable)}`,\n ...query.joins.map((joinClause) => this.compileJoin(joinClause)),\n this.compileWheres(query.wheres, 'where'),\n query.groups.length ? sql`group by ${this.columnize(query.groups)}` : undefined,\n this.compileHavings(query.havings),\n this.compileOrders(query),\n this.compileLimitOffset(query.limitValue, query.offsetValue),\n this.compileLock(query.lockMode),\n ])\n }\n\n compileOrders(query: Builder<unknown>): Sql | undefined {\n if (!query.orders.length) return undefined\n return sql`order by ${join(query.orders.map((order) => ('raw' in order ? this.wrap(order.raw) : sql`${this.wrap(order.column)} ${sql.raw(order.direction)}`)))}`\n }\n\n compileWheres(wheres: readonly Where[], keyword?: 'where' | 'on'): Sql | undefined {\n if (!wheres.length) return undefined\n const body = join(wheres.map((where, i) => (i === 0 ? this.compileWhere(where) : sql`${sql.raw(where.boolean)} ${this.compileWhere(where)}`)), ' ')\n return keyword ? sql`${sql.raw(keyword)} ${body}` : body\n }\n\n compileWhere(where: Where): Sql {\n switch (where.type) {\n case 'basic': {\n const column = typeof where.column === 'object' && !(where.column instanceof Expression)\n ? sql`(${this.compileSelect(where.column)})`\n : this.wrap(where.column)\n const operator = this.operator(where.operator)\n // As Laravel's PostgresGrammar: a like comparison reads the column as text, so it works on numbers and dates too.\n if (this.driver === 'pgsql' && /like/i.test(operator)) return sql`${column}::text ${sql.raw(operator)} ${this.parameter(where.value)}`\n return sql`${column} ${sql.raw(operator)} ${this.parameter(where.value)}`\n }\n case 'in': {\n const keyword = sql.raw(where.not ? 'not in' : 'in')\n if (!Array.isArray(where.values)) return sql`${this.wrap(where.column)} ${keyword} (${this.compileSelect(where.values as Builder<unknown>)})`\n if (where.values.length === 0) return sql.raw(where.not ? '1 = 1' : '0 = 1')\n return sql`${this.wrap(where.column)} ${keyword} (${join(where.values.map((value) => this.parameter(value)))})`\n }\n case 'null':\n return sql`${this.wrap(where.column)} ${sql.raw(where.not ? 'is not null' : 'is null')}`\n case 'like':\n return this.compileWhereLike(where)\n case 'between':\n return sql`${this.wrap(where.column)} ${sql.raw(where.not ? 'not between' : 'between')} ${this.parameter(where.values[0])} and ${this.parameter(where.values[1])}`\n case 'column':\n return sql`${this.wrap(where.first)} ${sql.raw(this.operator(where.operator))} ${this.wrap(where.second)}`\n case 'nested':\n return sql`${sql.raw(where.not ? 'not ' : '')}(${this.compileWheres(where.query.wheres) ?? EMPTY})`\n case 'exists':\n return sql`${sql.raw(where.not ? 'not exists' : 'exists')} (${this.compileSelect(where.query)})`\n case 'raw':\n return rawWithBindings(where.sql, where.bindings.map((value) => this.prepare(value)))\n case 'date':\n return this.compileWhereDate(where)\n }\n }\n\n /**\n * whereDate(), whereTime(), whereDay(), whereMonth() and whereYear() per driver, as Laravel 12's grammars: MySQL's\n * date()/time()/day()/month()/year(), Postgres' ::date, ::time and extract(), SQLite's strftime() compared as text.\n */\n compileWhereDate(where: Extract<Where, { type: 'date' }>): Sql {\n const column = this.wrap(where.column)\n const operator = sql.raw(this.operator(where.operator))\n const value = this.parameter(where.value)\n if (this.driver === 'sqlite') return sql`strftime(${sql.lit(SQLITE_DATE_FORMATS[where.part])}, ${column}) ${operator} cast(${value} as text)`\n if (this.driver === 'pgsql') {\n if (where.part === 'date' || where.part === 'time') return sql`${column}::${sql.raw(where.part)} ${operator} ${value}`\n return sql`extract(${sql.raw(where.part)} from ${column}) ${operator} ${value}`\n }\n return sql`${sql.raw(where.part)}(${column}) ${operator} ${value}`\n }\n\n /**\n * whereLike() per driver, as Laravel 12's grammars: Postgres compares the column as text with ilike (like when\n * case-sensitive); MySQL uses like (like binary); SQLite uses like, or glob with the pattern translated.\n */\n compileWhereLike(where: Extract<Where, { type: 'like' }>): Sql {\n const not = where.not ? 'not ' : ''\n const column = this.wrap(where.column)\n if (this.driver === 'pgsql') return sql`${column}::text ${sql.raw(`${not}${where.caseSensitive ? 'like' : 'ilike'}`)} ${this.parameter(where.value)}`\n if (this.driver === 'mysql') return sql`${column} ${sql.raw(`${not}${where.caseSensitive ? 'like binary' : 'like'}`)} ${this.parameter(where.value)}`\n if (where.caseSensitive) return sql`${column} ${sql.raw(`${not}glob`)} ${this.parameter(likeToGlob(where.value))}`\n return sql`${column} ${sql.raw(`${not}like`)} ${this.parameter(where.value)}`\n }\n\n compileJoin(joinClause: JoinClause): Sql {\n if (joinClause.joinType === 'cross') return sql`cross join ${this.wrapTable(joinClause.table)}`\n return sql`${sql.raw(joinClause.joinType)} join ${this.wrapTable(joinClause.table)} ${this.compileWheres(joinClause.wheres, 'on') ?? EMPTY}`\n }\n\n compileHavings(havings: readonly Having[]): Sql | undefined {\n if (!havings.length) return undefined\n const parts = havings.map((having, i) => {\n const body = 'raw' in having\n ? this.wrap(having.raw)\n : sql`${this.wrap(having.column)} ${sql.raw(this.operator(having.operator))} ${this.parameter(having.value)}`\n return i === 0 ? body : sql`${sql.raw(having.boolean)} ${body}`\n })\n return sql`having ${join(parts, ' ')}`\n }\n\n compileLimitOffset(limit: number | undefined, offset: number | undefined): Sql | undefined {\n if (limit === undefined && offset === undefined) return undefined\n const parts: Sql[] = []\n if (limit !== undefined) parts.push(sql`limit ${sql.lit(limit)}`)\n // SQLite and MySQL can't OFFSET without a LIMIT.\n else if (this.driver === 'sqlite') parts.push(sql.raw('limit -1'))\n else if (this.driver === 'mysql') parts.push(sql.raw('limit 18446744073709551615'))\n if (offset !== undefined) parts.push(sql`offset ${sql.lit(offset)}`)\n return join(parts, ' ')\n }\n\n compileLock(mode: 'update' | 'share' | undefined): Sql | undefined {\n if (mode === undefined || this.driver === 'sqlite') return undefined\n if (mode === 'update') return sql.raw('for update')\n return sql.raw(this.driver === 'pgsql' ? 'for share' : 'lock in share mode')\n }\n\n /**\n * `select count(*) as aggregate …`. Orders, limit and offset are dropped. Grouped or distinct queries, and those with a\n * `having` (which may name a selected alias, withCount()'s `comments_count`), are wrapped, keeping their columns.\n */\n compileAggregate(query: Builder<unknown>, fn: string, column: string | Expression): Sql {\n const inner = query.clone()\n inner.orders = []\n inner.limitValue = undefined\n inner.offsetValue = undefined\n inner.lockMode = undefined\n const target = column === '*' ? sql.raw('*') : this.wrap(column)\n if (inner.groups.length || inner.distinctRows || inner.havings.length) {\n if (fn === 'count') return sql`select count(*) as ${sql.id('aggregate')} from (${this.compileSelect(inner)}) as ${sql.id('temp_table')}`\n if (column instanceof Expression) {\n throw new LogicError(`${fn}() can't target a raw expression over a distinct or grouped query: select it as an aliased column instead.`)\n }\n if (!inner.columns.length) inner.columns = [column]\n const unqualified = column.split('.').pop()!.trim()\n return sql`select ${sql.raw(fn)}(${sql.id(unqualified)}) as ${sql.id('aggregate')} from (${this.compileSelect(inner)}) as ${sql.id('temp_table')}`\n }\n return sql`select ${sql.raw(fn)}(${target}) as ${sql.id('aggregate')} ${this.compileComponents(inner)}`\n }\n\n compileExists(query: Builder<unknown>): Sql {\n return sql`select exists(${this.compileSelect(query)}) as ${sql.id('exists')}`\n }\n\n compileInsert(query: Builder<unknown>, rows: readonly Row[]): Sql {\n if (rows.every((row) => !Object.keys(row).length)) {\n const table = this.wrapTable(query.requireTable())\n return this.driver === 'mysql' ? sql`insert into ${table} () values ()` : sql`insert into ${table} default values`\n }\n return sql`insert ${this.compileInsertBody(query, rows)}`\n }\n\n compileInsertOrIgnore(query: Builder<unknown>, rows: readonly Row[]): Sql {\n const body = this.compileInsertBody(query, rows)\n if (this.driver === 'mysql') return sql`insert ignore ${body}`\n if (this.driver === 'sqlite') return sql`insert or ignore ${body}`\n return sql`insert ${body} on conflict do nothing`\n }\n\n /** `into \"table\" (\"a\", \"b\") values (?, ?), (?, ?)`. Columns are the union of every row's keys; a missing key binds null. */\n compileInsertBody(query: Builder<unknown>, rows: readonly Row[]): Sql {\n const columns = [...new Set(rows.flatMap((row) => Object.keys(row)))]\n const values = join(rows.map((row) => sql`(${join(columns.map((column) => this.parameter(row[column])))})`))\n return sql`into ${this.wrapTable(query.requireTable())} (${this.columnize(columns)}) values ${values}`\n }\n\n compileInsertGetId(query: Builder<unknown>, row: Row, keyName: string): Sql {\n const insert = this.compileInsert(query, [row])\n return this.driver === 'pgsql' ? sql`${insert} returning ${this.wrap(keyName)}` : insert\n }\n\n compileUpsert(query: Builder<unknown>, rows: readonly Row[], uniqueBy: readonly string[], update: readonly string[]): Sql {\n const insert = this.compileInsert(query, rows)\n if (this.driver === 'mysql') {\n const alias = 'laravel_upsert_alias'\n const sets = join(update.map((column) => sql`${this.wrap(column)} = ${sql.id(alias, column)}`))\n return sql`${insert} as ${sql.id(alias)} on duplicate key update ${sets}`\n }\n const sets = join(update.map((column) => sql`${this.wrap(column)} = ${sql.id('excluded', column)}`))\n return sql`${insert} on conflict (${this.columnize(uniqueBy)}) do update set ${sets}`\n }\n\n compileUpdate(query: Builder<unknown>, values: Row): Sql {\n this.assertSimpleMutation(query, 'update')\n const sets = join(Object.entries(values).map(([column, value]) => sql`${this.wrap(column.split('.').pop()!)} = ${this.parameter(value)}`))\n return clauses([\n sql`update ${this.wrapTable(query.requireTable())} set ${sets}`,\n this.compileWheres(query.wheres, 'where'),\n ...this.mysqlOrderAndLimit(query),\n ])\n }\n\n compileDelete(query: Builder<unknown>): Sql {\n this.assertSimpleMutation(query, 'delete')\n return clauses([\n sql`delete from ${this.wrapTable(query.requireTable())}`,\n this.compileWheres(query.wheres, 'where'),\n ...this.mysqlOrderAndLimit(query),\n ])\n }\n\n compileTruncate(query: Builder<unknown>): Sql[] {\n const table = this.wrapTable(query.requireTable())\n if (this.driver === 'pgsql') return [sql`truncate table ${table} restart identity cascade`]\n if (this.driver === 'mysql') return [sql`truncate table ${table}`]\n return [sql`delete from ${table}`]\n }\n\n compileRandom(): Expression {\n return new Expression(this.driver === 'mysql' ? 'RAND()' : 'random()')\n }\n\n private assertSimpleMutation(query: Builder<unknown>, action: string): void {\n if (query.joins.length || query.offsetValue !== undefined || (query.limitValue !== undefined && this.driver !== 'mysql')) {\n throw new LogicError(`${action}() with joins, offset or (except on MySQL) limit isn't supported. Select the keys first, then ${action} with whereIn().`)\n }\n }\n\n private mysqlOrderAndLimit(query: Builder<unknown>): Array<Sql | undefined> {\n if (this.driver !== 'mysql') return []\n return [\n this.compileOrders(query),\n query.limitValue === undefined ? undefined : sql`limit ${sql.lit(query.limitValue)}`,\n ]\n }\n}\n","import type { DriverName } from '@orieljs/contracts'\nimport { LogicError } from '../errors'\n\nconst pad = (n: number, width = 2) => String(n).padStart(width, '0')\n\n/** Laravel's storage format ('Y-m-d H:i:s'), in UTC. */\nexport function formatDateTime(date: Date): string {\n return (\n `${pad(date.getUTCFullYear(), 4)}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())} ` +\n `${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())}:${pad(date.getUTCSeconds())}`\n )\n}\n\nexport function formatDate(date: Date): string {\n return formatDateTime(date).slice(0, 10)\n}\n\n/**\n * Parses a stored date/time as UTC. Accepts Dates, epoch milliseconds, 'Y-m-d', 'Y-m-d H:i:s' and ISO strings\n * (the last two with or without a zone suffix; a missing zone means UTC).\n */\nexport function parseDateTime(value: unknown): Date {\n if (value instanceof Date) return new Date(value.getTime())\n if (typeof value === 'number') return new Date(value)\n const text = String(value).trim()\n const match = /^(\\d{4}-\\d{2}-\\d{2})(?:[ T](\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d+)?)?))?\\s*(Z|[+-]\\d{2}(?::?\\d{2})?)?$/i.exec(text)\n if (match) {\n const [, day, time = '00:00:00', zone] = match\n let offset = 'Z'\n if (zone && zone.toUpperCase() !== 'Z') offset = zone.length === 3 ? `${zone}:00` : zone.includes(':') ? zone : `${zone.slice(0, 3)}:${zone.slice(3)}`\n return new Date(`${day}T${time.length === 5 ? `${time}:00` : time}${offset}`)\n }\n const parsed = new Date(text)\n if (Number.isNaN(parsed.getTime())) throw new LogicError(`Unable to parse [${text}] as a date.`)\n return parsed\n}\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && Object.getPrototypeOf(value) === Object.prototype\n\n/** Normalizes one binding for the driver: booleans, dates, JSON and undefined. */\nexport function prepareValue(value: unknown, driver: DriverName): unknown {\n if (value === undefined) return null\n if (typeof value === 'boolean') return driver === 'pgsql' ? value : value ? 1 : 0\n if (value instanceof Date) return formatDateTime(value)\n if (Array.isArray(value) || isPlainObject(value)) return JSON.stringify(value)\n return value\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport { Kysely, sql, type CompiledQuery, type ControlledTransaction, type QueryResult, type RawBuilder } from 'kysely'\nimport type { DatabaseConnection, DriverName, Row } from '@orieljs/contracts'\nimport { createDialect, type ConnectionConfig } from './Connectors/dialect'\nimport { QueryError } from './errors'\nimport { Builder } from './Query/Builder'\nimport { Expression, rawWithBindings } from './Query/Expression'\nimport { prepareValue } from './Query/values'\nimport { SchemaBuilder } from './Schema/Builder'\n\n/** One open transaction level. Level 1 is the real transaction; deeper levels are savepoints named trans<level>. */\ninterface TransactionFrame {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n readonly trx: ControlledTransaction<any>\n readonly level: number\n /** An inner level's savepoint, named per frame. */\n readonly savepoint?: string\n /**\n * Inner transactions under one level take turns. Savepoints are a stack on one connection: rolling one back undoes\n * everything after it, a sibling's committed work included, so a sibling waits for the one before it to end.\n */\n turn: Promise<void>\n /** Hands the parent's turn to the next sibling, once this inner level has ended. */\n readonly endTurn?: () => void\n}\n\nexport interface LoggedQuery {\n query: string\n bindings: readonly unknown[]\n time: number\n}\n\n/**\n * A named database connection on Kysely.\n *\n * Transactions: `transaction(fn)` is bound to the async context that called it (AsyncLocalStorage), so a\n * transaction in one request never captures another request's queries. `beginTransaction()` instead pins the\n * transaction to the whole connection until `commit()`/`rollBack()`; that is what RefreshDatabase needs.\n * Nested levels use savepoints (trans2, trans3, …) either way.\n */\nexport class Connection implements DatabaseConnection {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n protected readonly db: Kysely<any>\n private readonly context = new AsyncLocalStorage<TransactionFrame>()\n private readonly pinned: TransactionFrame[] = []\n private savepoints = 0\n private loggingQueries = false\n private queryLog: LoggedQuery[] = []\n\n constructor(\n protected readonly name: string,\n protected readonly config: ConnectionConfig,\n ) {\n this.db = new Kysely({ dialect: createDialect(config) })\n }\n\n getName(): string {\n return this.name\n }\n\n getDriverName(): DriverName {\n return this.config.driver\n }\n\n getConfig(): ConnectionConfig {\n return this.config\n }\n\n /** A query builder for a table: connection.table('users').where('votes', '>', 100).get(). */\n table<T = Row>(table: string | Expression): Builder<T> {\n return new Builder<T>(this, table)\n }\n\n /** A query builder with no table yet (use from()). */\n query<T = Row>(): Builder<T> {\n return new Builder<T>(this)\n }\n\n /** Schema operations on this connection (Laravel's getSchemaBuilder()). */\n getSchemaBuilder(): SchemaBuilder {\n return new SchemaBuilder(this)\n }\n\n /** Raw Kysely access. Inside a transaction this is the transaction, so queries join it. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n kysely(): Kysely<any> {\n return this.current()?.trx ?? this.db\n }\n\n /** Normalizes a value for this driver (booleans, Dates, JSON). */\n prepareValue(value: unknown): unknown {\n return prepareValue(value, this.config.driver)\n }\n\n /** Compiles a Kysely raw builder against this connection's dialect. */\n compile(query: RawBuilder<unknown>): CompiledQuery {\n return query.compile(this.db)\n }\n\n /** Runs a compiled statement on the current executor (the transaction, when one is open). */\n async execute<T = Row>(query: RawBuilder<unknown> | CompiledQuery): Promise<QueryResult<T>> {\n const compiled = 'compile' in query ? this.compile(query) : query\n const started = performance.now()\n try {\n return await this.kysely().executeQuery<T>(compiled)\n } catch (error) {\n throw new QueryError(this.name, compiled.sql, compiled.parameters, error)\n } finally {\n if (this.loggingQueries) {\n this.queryLog.push({ query: compiled.sql, bindings: compiled.parameters, time: performance.now() - started })\n }\n }\n }\n\n /** Raw select with `?` placeholders. */\n async select<T = Row>(query: string, bindings: readonly unknown[] = []): Promise<T[]> {\n return (await this.execute<T>(this.raw(query, bindings))).rows\n }\n\n /** Raw statement with `?` placeholders. */\n async statement(query: string, bindings: readonly unknown[] = []): Promise<void> {\n await this.execute(this.raw(query, bindings))\n }\n\n /** Raw statement; returns the number of affected rows. */\n async affectingStatement(query: string, bindings: readonly unknown[] = []): Promise<number> {\n return Number((await this.execute(this.raw(query, bindings))).numAffectedRows ?? 0)\n }\n\n private raw(query: string, bindings: readonly unknown[]): RawBuilder<unknown> {\n return rawWithBindings(query, bindings.map((value) => this.prepareValue(value)))\n }\n\n /** Runs fn in a transaction (a savepoint when nested). Commits when fn resolves, rolls back and rethrows when it throws. */\n async transaction<R>(fn: (connection: this) => Promise<R>): Promise<R> {\n const frame = await this.open()\n let result: R\n try {\n result = await this.context.run(frame, () => fn(this))\n } catch (error) {\n await this.close(frame, 'rollback')\n throw error\n }\n await this.close(frame, 'commit')\n return result\n }\n\n /** Starts a transaction that stays open, for every async context, until commit()/rollBack(). */\n async beginTransaction(): Promise<void> {\n this.pinned.push(await this.open())\n }\n\n async commit(): Promise<void> {\n const frame = this.pinned.pop()\n if (frame) await this.close(frame, 'commit')\n }\n\n /** Rolls back the innermost level opened by beginTransaction(). Does nothing when none is open. */\n async rollBack(): Promise<void> {\n const frame = this.pinned.pop()\n if (frame) await this.close(frame, 'rollback')\n }\n\n transactionLevel(): number {\n return this.current()?.level ?? 0\n }\n\n enableQueryLog(): void {\n this.loggingQueries = true\n }\n\n disableQueryLog(): void {\n this.loggingQueries = false\n }\n\n getQueryLog(): LoggedQuery[] {\n return [...this.queryLog]\n }\n\n flushQueryLog(): void {\n this.queryLog = []\n }\n\n async disconnect(): Promise<void> {\n await this.db.destroy()\n }\n\n /** The innermost open level: the context's own transaction or a pinned one, whichever is deeper. */\n private current(): TransactionFrame | undefined {\n const own = this.context.getStore()\n const pinned = this.pinned.at(-1)\n if (!own) return pinned\n if (!pinned) return own\n return pinned.level > own.level ? pinned : own\n }\n\n private async open(): Promise<TransactionFrame> {\n const parent = this.current()\n if (!parent) return { trx: await this.db.startTransaction().execute(), level: 1, turn: Promise.resolve() }\n const previous = parent.turn\n let endTurn!: () => void\n parent.turn = new Promise<void>((resolve) => (endTurn = resolve))\n await previous\n const level = parent.level + 1\n const savepoint = `trans${level}_${++this.savepoints}`\n try {\n await sql.raw(`SAVEPOINT ${savepoint}`).execute(parent.trx)\n } catch (error) {\n endTurn()\n throw error\n }\n return { trx: parent.trx, level, savepoint, turn: Promise.resolve(), endTurn }\n }\n\n private async close(frame: TransactionFrame, action: 'commit' | 'rollback'): Promise<void> {\n try {\n if (frame.level === 1) {\n await (action === 'commit' ? frame.trx.commit() : frame.trx.rollback()).execute()\n } else if (action === 'commit') {\n await sql.raw(`RELEASE SAVEPOINT ${frame.savepoint}`).execute(frame.trx)\n } else {\n await sql.raw(`ROLLBACK TO SAVEPOINT ${frame.savepoint}`).execute(frame.trx)\n }\n } finally {\n frame.endTurn?.()\n }\n }\n}\n","import { sql, type RawBuilder } from 'kysely'\nimport type { Connection } from '../Connection'\nimport { LogicError } from '../errors'\nimport { Blueprint } from './Blueprint'\nimport { isTableRebuild, SchemaGrammar, SqliteSchemaGrammar, type ColumnInfo, type ForeignKeyInfo, type IndexInfo } from './Grammar'\nimport { rebuildSqliteTable } from './SqliteTableRebuild'\n\n/**\n * Laravel's Schema builder for one connection: Schema.create('posts', (t) => { t.id(); t.string('title') }).\n * Each blueprint compiles to one or more statements, run in order.\n */\nexport class SchemaBuilder {\n readonly grammar: SchemaGrammar\n\n constructor(\n protected readonly db: Connection,\n private readonly resolveConnection?: (name: string) => Connection,\n ) {\n this.grammar = SchemaGrammar.for(db.getDriverName(), db.getConfig())\n }\n\n getConnection(): Connection {\n return this.db\n }\n\n /** The schema builder of another connection: Schema.connection('pgsql').create(…). */\n connection(name: string): SchemaBuilder {\n if (!this.resolveConnection) throw new LogicError('This schema builder has no connection resolver.')\n return new SchemaBuilder(this.resolveConnection(name), this.resolveConnection)\n }\n\n async create(table: string, callback: (table: Blueprint) => void): Promise<void> {\n const blueprint = new Blueprint(table, true)\n callback(blueprint)\n await this.build(blueprint)\n }\n\n /** Changes an existing table: add columns, indexes and foreign keys, drop or rename columns. */\n async table(table: string, callback: (table: Blueprint) => void): Promise<void> {\n const blueprint = new Blueprint(table)\n callback(blueprint)\n await this.build(blueprint)\n }\n\n async drop(table: string): Promise<void> {\n await this.run([this.grammar.compileDrop(table)])\n }\n\n async dropIfExists(table: string): Promise<void> {\n await this.run([this.grammar.compileDropIfExists(table)])\n }\n\n async rename(from: string, to: string): Promise<void> {\n await this.run([this.grammar.compileRename(from, to)])\n }\n\n /**\n * Runs a blueprint's statements in order (inspect them with grammar.compile(blueprint)). On SQLite, a change to the\n * keys of an existing table rebuilds it from its live definition at its place in that order.\n */\n async build(blueprint: Blueprint): Promise<void> {\n for (const step of this.grammar.compileSteps(blueprint)) {\n if (isTableRebuild(step)) await rebuildSqliteTable(this.db, this.grammar as SqliteSchemaGrammar, step)\n else await this.db.execute(step)\n }\n }\n\n /** The table names of the connection's database (or current schema on Postgres). */\n async getTables(): Promise<string[]> {\n const rows = (await this.db.execute<{ name: string }>(this.grammar.compileTables())).rows\n return rows.map((row) => String(row.name))\n }\n\n async hasTable(table: string): Promise<boolean> {\n return (await this.getTables()).includes(table)\n }\n\n async getColumns(table: string): Promise<ColumnInfo[]> {\n const rows = (await this.db.execute<Record<string, unknown>>(this.grammar.compileColumns(table))).rows\n return this.grammar.normalizeColumns(rows)\n }\n\n async getColumnListing(table: string): Promise<string[]> {\n return (await this.getColumns(table)).map((column) => column.name)\n }\n\n /** Case-insensitive, like Laravel. */\n async hasColumn(table: string, column: string): Promise<boolean> {\n return this.hasColumns(table, [column])\n }\n\n async hasColumns(table: string, columns: string[]): Promise<boolean> {\n const existing = (await this.getColumnListing(table)).map((name) => name.toLowerCase())\n return columns.every((column) => existing.includes(column.toLowerCase()))\n }\n\n /** The table's indexes, its primary key included (Laravel's getIndexes()). */\n async getIndexes(table: string): Promise<IndexInfo[]> {\n const rows = (await this.db.execute<Record<string, unknown>>(this.grammar.compileIndexes(table))).rows\n return this.grammar.normalizeIndexes(rows)\n }\n\n async getIndexListing(table: string): Promise<string[]> {\n return (await this.getIndexes(table)).map((index) => index.name)\n }\n\n /**\n * Whether the table has an index with this name, or on exactly these columns (in order). `type` narrows it:\n * 'primary', 'unique', or an index method such as 'btree'.\n */\n async hasIndex(table: string, index: string | string[], type?: string): Promise<boolean> {\n const wanted = type?.toLowerCase()\n return (await this.getIndexes(table)).some((value) => {\n const typeMatches = wanted === undefined || (wanted === 'primary' && value.primary) || (wanted === 'unique' && value.unique) || wanted === value.type\n const indexMatches = typeof index === 'string'\n ? value.name === index\n : value.columns.length === index.length && value.columns.every((column, i) => column === index[i])\n return indexMatches && typeMatches\n })\n }\n\n /** The table's foreign keys (Laravel's getForeignKeys()). */\n async getForeignKeys(table: string): Promise<ForeignKeyInfo[]> {\n const rows = (await this.db.execute<Record<string, unknown>>(this.grammar.compileForeignKeys(table))).rows\n return this.grammar.normalizeForeignKeys(rows)\n }\n\n async enableForeignKeyConstraints(): Promise<void> {\n await this.run([this.grammar.compileEnableForeignKeyConstraints()])\n }\n\n async disableForeignKeyConstraints(): Promise<void> {\n await this.run([this.grammar.compileDisableForeignKeyConstraints()])\n }\n\n /**\n * Runs fn with foreign key checks off. On MySQL and Postgres the connection is pinned (a transaction) so the\n * setting and fn's statements share one pooled connection; SQLite has a single connection already.\n */\n async withoutForeignKeyConstraints<R>(fn: () => Promise<R>): Promise<R> {\n const run = async () => {\n await this.disableForeignKeyConstraints()\n try {\n return await fn()\n } finally {\n await this.enableForeignKeyConstraints()\n }\n }\n return this.db.getDriverName() === 'sqlite' ? run() : this.db.transaction(run)\n }\n\n /** Drops every table (migrate:fresh). */\n async dropAllTables(): Promise<void> {\n const tables = await this.getTables()\n if (!tables.length) return\n if (this.db.getDriverName() === 'pgsql') {\n await this.run([sql`drop table ${sql.join(tables.map((table) => sql.id(table)))} cascade`])\n return\n }\n await this.withoutForeignKeyConstraints(async () => {\n for (const table of tables) await this.run([this.grammar.compileDrop(table)])\n })\n }\n\n private async run(statements: Array<RawBuilder<unknown>>): Promise<void> {\n for (const statement of statements) await this.db.execute(statement)\n }\n}\n","import { Expression } from '../Query/Expression'\n\nexport type ColumnType =\n | 'bigInteger' | 'integer' | 'mediumInteger' | 'smallInteger' | 'tinyInteger'\n | 'string' | 'char' | 'text' | 'mediumText' | 'longText'\n | 'boolean' | 'date' | 'dateTime' | 'time' | 'timestamp'\n | 'decimal' | 'float' | 'double'\n | 'json' | 'jsonb' | 'uuid' | 'ulid' | 'binary' | 'enum'\n\n/** Everything a column definition can carry. Grammars read these; the fluent methods set them. */\nexport interface ColumnAttributes {\n type: ColumnType\n name: string\n length?: number\n total?: number\n places?: number\n precision?: number\n allowed?: readonly string[]\n autoIncrement?: boolean\n unsigned?: boolean\n nullable?: boolean\n default?: unknown\n primary?: boolean\n unique?: boolean | string\n index?: boolean | string\n comment?: string\n after?: string\n first?: boolean\n onUpdate?: Expression\n /** Set by change(): the column exists and is redefined, not added. */\n change?: boolean\n}\n\n/** A column in a Blueprint, with Laravel's fluent modifiers: t.string('email').nullable().unique(). */\nexport class ColumnDefinition {\n constructor(readonly attributes: ColumnAttributes) {}\n\n get name(): string {\n return this.attributes.name\n }\n\n /** Allows NULL (the default is NOT NULL). */\n nullable(value = true): this {\n this.attributes.nullable = value\n return this\n }\n\n /** A default value. Strings, numbers and booleans are quoted as literals; DB.raw() passes through unescaped. */\n default(value: unknown): this {\n this.attributes.default = value\n return this\n }\n\n unsigned(): this {\n this.attributes.unsigned = true\n return this\n }\n\n autoIncrement(): this {\n this.attributes.autoIncrement = true\n return this\n }\n\n primary(value = true): this {\n this.attributes.primary = value\n return this\n }\n\n /** Adds a unique index on this column, optionally with a name. */\n unique(name?: string): this {\n this.attributes.unique = name ?? true\n return this\n }\n\n /** Adds a plain index on this column, optionally with a name. */\n index(name?: string): this {\n this.attributes.index = name ?? true\n return this\n }\n\n /** Column comment (MySQL and Postgres; ignored on SQLite). */\n comment(text: string): this {\n this.attributes.comment = text\n return this\n }\n\n /** MySQL only: place the column after another one. Ignored elsewhere. */\n after(column: string): this {\n this.attributes.after = column\n return this\n }\n\n /** MySQL only: place the column first. Ignored elsewhere. */\n first(): this {\n this.attributes.first = true\n return this\n }\n\n /** default CURRENT_TIMESTAMP. */\n useCurrent(): this {\n this.attributes.default = new Expression('CURRENT_TIMESTAMP')\n return this\n }\n\n /**\n * Redefines an existing column (Laravel's change()): t.string('title', 500).nullable().change(). As in Laravel 11+,\n * the column becomes exactly this definition: a modifier it had and that isn't given again (nullable, default,\n * comment, …) is dropped. On SQLite the table is rebuilt.\n */\n change(): this {\n this.attributes.change = true\n return this\n }\n\n /** MySQL only: on update CURRENT_TIMESTAMP. */\n useCurrentOnUpdate(): this {\n this.attributes.onUpdate = new Expression('CURRENT_TIMESTAMP')\n return this\n }\n}\n","import { Str } from '@orieljs/support'\nimport { ColumnDefinition, type ColumnAttributes } from './ColumnDefinition'\n\nexport type ReferentialAction = 'cascade' | 'restrict' | 'set null' | 'no action' | 'set default'\n\n/** t.foreign('user_id').references('id').on('users').cascadeOnDelete() */\nexport class ForeignKeyDefinition {\n referencedColumns: string[] = ['id']\n referencedTable: string | undefined\n deleteAction: ReferentialAction | undefined\n updateAction: ReferentialAction | undefined\n\n constructor(\n readonly columns: string[],\n public indexName: string,\n ) {}\n\n references(columns: string | string[]): this {\n this.referencedColumns = [columns].flat()\n return this\n }\n\n on(table: string): this {\n this.referencedTable = table\n return this\n }\n\n onDelete(action: ReferentialAction): this {\n this.deleteAction = action\n return this\n }\n\n onUpdate(action: ReferentialAction): this {\n this.updateAction = action\n return this\n }\n\n cascadeOnDelete(): this {\n return this.onDelete('cascade')\n }\n\n restrictOnDelete(): this {\n return this.onDelete('restrict')\n }\n\n nullOnDelete(): this {\n return this.onDelete('set null')\n }\n\n noActionOnDelete(): this {\n return this.onDelete('no action')\n }\n\n cascadeOnUpdate(): this {\n return this.onUpdate('cascade')\n }\n\n restrictOnUpdate(): this {\n return this.onUpdate('restrict')\n }\n\n nullOnUpdate(): this {\n return this.onUpdate('set null')\n }\n\n noActionOnUpdate(): this {\n return this.onUpdate('no action')\n }\n\n /** Overrides the constraint name (default: {table}_{columns}_foreign). */\n name(name: string): this {\n this.indexName = name\n return this\n }\n}\n\n/** foreignId('user_id').constrained(): the column plus, on demand, its foreign key. */\nexport class ForeignIdColumnDefinition extends ColumnDefinition {\n constructor(\n attributes: ColumnAttributes,\n private readonly addForeign: (column: string) => ForeignKeyDefinition,\n ) {\n super(attributes)\n }\n\n /**\n * A foreign key to `table` (default: the column name without `_id`, pluralized: user_id → users) on `column`.\n * Chain cascadeOnDelete() etc. on the returned definition.\n */\n constrained(table?: string, column = 'id', indexName?: string): ForeignKeyDefinition {\n const foreign = this.addForeign(this.name).references(column).on(table ?? Str.plural(this.name.replace(/_id$/, '')))\n if (indexName) foreign.name(indexName)\n return foreign\n }\n\n /** A foreign key on this column to `column`; chain on('table'). */\n references(column: string): ForeignKeyDefinition {\n return this.addForeign(this.name).references(column)\n }\n}\n","import { ColumnDefinition, type ColumnAttributes, type ColumnType } from './ColumnDefinition'\nimport { ForeignIdColumnDefinition, ForeignKeyDefinition } from './ForeignKeyDefinition'\n\nexport type IndexType = 'primary' | 'unique' | 'index'\n\nexport type BlueprintCommand =\n | { name: 'create' }\n | { name: IndexType; columns: string[]; index: string }\n | { name: 'foreign'; foreign: ForeignKeyDefinition }\n | { name: 'dropColumn'; columns: string[] }\n | { name: 'renameColumn'; from: string; to: string }\n | { name: 'dropPrimary' | 'dropUnique' | 'dropIndex'; index: string }\n | { name: 'dropForeign'; index: string; columns?: string[] }\n | { name: 'rename'; to: string }\n | { name: 'drop' | 'dropIfExists' }\n\n/**\n * The table definition passed to Schema.create()/Schema.table() callbacks, with Laravel's column types and\n * commands. It only records; the schema grammar turns it into DDL for one driver.\n */\nexport class Blueprint {\n readonly columns: ColumnDefinition[] = []\n readonly commands: BlueprintCommand[] = []\n\n constructor(\n readonly table: string,\n readonly creating = false,\n ) {\n if (creating) this.commands.push({ name: 'create' })\n }\n\n // ---------------------------------------------------------------- columns\n\n addColumn(type: ColumnType, name: string, attributes: Partial<ColumnAttributes> = {}): ColumnDefinition {\n const column = new ColumnDefinition({ type, name, ...attributes })\n this.columns.push(column)\n return column\n }\n\n /** An auto-incrementing unsigned big integer primary key (Laravel's id()). */\n id(column = 'id'): ColumnDefinition {\n return this.bigIncrements(column)\n }\n\n increments(column: string): ColumnDefinition {\n return this.addColumn('integer', column, { autoIncrement: true, unsigned: true })\n }\n\n bigIncrements(column: string): ColumnDefinition {\n return this.addColumn('bigInteger', column, { autoIncrement: true, unsigned: true })\n }\n\n integer(column: string, autoIncrement = false, unsigned = false): ColumnDefinition {\n return this.addColumn('integer', column, { autoIncrement, unsigned })\n }\n\n bigInteger(column: string, autoIncrement = false, unsigned = false): ColumnDefinition {\n return this.addColumn('bigInteger', column, { autoIncrement, unsigned })\n }\n\n mediumInteger(column: string, autoIncrement = false, unsigned = false): ColumnDefinition {\n return this.addColumn('mediumInteger', column, { autoIncrement, unsigned })\n }\n\n smallInteger(column: string, autoIncrement = false, unsigned = false): ColumnDefinition {\n return this.addColumn('smallInteger', column, { autoIncrement, unsigned })\n }\n\n tinyInteger(column: string, autoIncrement = false, unsigned = false): ColumnDefinition {\n return this.addColumn('tinyInteger', column, { autoIncrement, unsigned })\n }\n\n unsignedInteger(column: string): ColumnDefinition {\n return this.integer(column, false, true)\n }\n\n unsignedBigInteger(column: string): ColumnDefinition {\n return this.bigInteger(column, false, true)\n }\n\n unsignedSmallInteger(column: string): ColumnDefinition {\n return this.smallInteger(column, false, true)\n }\n\n unsignedTinyInteger(column: string): ColumnDefinition {\n return this.tinyInteger(column, false, true)\n }\n\n /** An unsigned big integer meant for a foreign key: t.foreignId('user_id').constrained().cascadeOnDelete(). */\n foreignId(column: string): ForeignIdColumnDefinition {\n const definition = new ForeignIdColumnDefinition({ type: 'bigInteger', name: column, unsigned: true }, (name) => this.foreign(name))\n this.columns.push(definition)\n return definition\n }\n\n string(column: string, length = 255): ColumnDefinition {\n return this.addColumn('string', column, { length })\n }\n\n char(column: string, length = 255): ColumnDefinition {\n return this.addColumn('char', column, { length })\n }\n\n text(column: string): ColumnDefinition {\n return this.addColumn('text', column)\n }\n\n mediumText(column: string): ColumnDefinition {\n return this.addColumn('mediumText', column)\n }\n\n longText(column: string): ColumnDefinition {\n return this.addColumn('longText', column)\n }\n\n boolean(column: string): ColumnDefinition {\n return this.addColumn('boolean', column)\n }\n\n date(column: string): ColumnDefinition {\n return this.addColumn('date', column)\n }\n\n dateTime(column: string, precision = 0): ColumnDefinition {\n return this.addColumn('dateTime', column, { precision })\n }\n\n time(column: string, precision = 0): ColumnDefinition {\n return this.addColumn('time', column, { precision })\n }\n\n timestamp(column: string, precision = 0): ColumnDefinition {\n return this.addColumn('timestamp', column, { precision })\n }\n\n /** Nullable created_at and updated_at. */\n timestamps(precision = 0): void {\n this.timestamp('created_at', precision).nullable()\n this.timestamp('updated_at', precision).nullable()\n }\n\n nullableTimestamps(precision = 0): void {\n this.timestamps(precision)\n }\n\n /** A nullable deleted_at timestamp for soft deletes. */\n softDeletes(column = 'deleted_at', precision = 0): ColumnDefinition {\n return this.timestamp(column, precision).nullable()\n }\n\n decimal(column: string, total = 8, places = 2): ColumnDefinition {\n return this.addColumn('decimal', column, { total, places })\n }\n\n float(column: string, precision = 53): ColumnDefinition {\n return this.addColumn('float', column, { precision })\n }\n\n double(column: string): ColumnDefinition {\n return this.addColumn('double', column)\n }\n\n json(column: string): ColumnDefinition {\n return this.addColumn('json', column)\n }\n\n jsonb(column: string): ColumnDefinition {\n return this.addColumn('jsonb', column)\n }\n\n uuid(column = 'uuid'): ColumnDefinition {\n return this.addColumn('uuid', column)\n }\n\n ulid(column = 'ulid'): ColumnDefinition {\n return this.addColumn('ulid', column)\n }\n\n binary(column: string): ColumnDefinition {\n return this.addColumn('binary', column)\n }\n\n enum(column: string, allowed: readonly string[]): ColumnDefinition {\n return this.addColumn('enum', column, { allowed })\n }\n\n /** remember_token varchar(100) null. */\n rememberToken(): ColumnDefinition {\n return this.string('remember_token', 100).nullable()\n }\n\n /** {name}_type + {name}_id, indexed together: the columns of a polymorphic relation. */\n morphs(name: string, indexName?: string): void {\n this.string(`${name}_type`)\n this.unsignedBigInteger(`${name}_id`)\n this.index([`${name}_type`, `${name}_id`], indexName)\n }\n\n nullableMorphs(name: string, indexName?: string): void {\n this.string(`${name}_type`).nullable()\n this.unsignedBigInteger(`${name}_id`).nullable()\n this.index([`${name}_type`, `${name}_id`], indexName)\n }\n\n // ---------------------------------------------------------------- indexes and keys\n\n primary(columns: string | string[], name?: string): void {\n this.indexCommand('primary', columns, name)\n }\n\n unique(columns: string | string[], name?: string): void {\n this.indexCommand('unique', columns, name)\n }\n\n index(columns: string | string[], name?: string): void {\n this.indexCommand('index', columns, name)\n }\n\n /** t.foreign('user_id').references('id').on('users') */\n foreign(columns: string | string[], name?: string): ForeignKeyDefinition {\n const list = [columns].flat()\n const foreign = new ForeignKeyDefinition(list, name ?? this.createIndexName('foreign', list))\n this.commands.push({ name: 'foreign', foreign })\n return foreign\n }\n\n // ---------------------------------------------------------------- changes to an existing table\n\n dropColumn(...columns: Array<string | string[]>): void {\n this.commands.push({ name: 'dropColumn', columns: columns.flat() })\n }\n\n renameColumn(from: string, to: string): void {\n this.commands.push({ name: 'renameColumn', from, to })\n }\n\n dropPrimary(name?: string): void {\n this.commands.push({ name: 'dropPrimary', index: name ?? `${this.table}_pkey` })\n }\n\n /** By name, or by columns (the conventional {table}_{columns}_unique name). */\n dropUnique(index: string | string[]): void {\n this.commands.push({ name: 'dropUnique', index: this.indexNameFor('unique', index) })\n }\n\n dropIndex(index: string | string[]): void {\n this.commands.push({ name: 'dropIndex', index: this.indexNameFor('index', index) })\n }\n\n /** By name, or by columns (the conventional name; SQLite needs the columns, it doesn't keep foreign key names). */\n dropForeign(index: string | string[]): void {\n const columns = Array.isArray(index) ? [...index] : undefined\n this.commands.push({ name: 'dropForeign', index: this.indexNameFor('foreign', index), ...(columns ? { columns } : {}) })\n }\n\n /** Drops the foreign key on the column, then the column. */\n dropConstrainedForeignId(column: string): void {\n this.dropForeign([column])\n this.dropColumn(column)\n }\n\n dropTimestamps(): void {\n this.dropColumn('created_at', 'updated_at')\n }\n\n dropSoftDeletes(column = 'deleted_at'): void {\n this.dropColumn(column)\n }\n\n dropRememberToken(): void {\n this.dropColumn('remember_token')\n }\n\n dropMorphs(name: string, indexName?: string): void {\n this.dropIndex(indexName ?? this.createIndexName('index', [`${name}_type`, `${name}_id`]))\n this.dropColumn(`${name}_type`, `${name}_id`)\n }\n\n rename(to: string): void {\n this.commands.push({ name: 'rename', to })\n }\n\n drop(): void {\n this.commands.push({ name: 'drop' })\n }\n\n dropIfExists(): void {\n this.commands.push({ name: 'dropIfExists' })\n }\n\n // ---------------------------------------------------------------- helpers\n\n /** The columns this blueprint adds (not the ones change() redefines). */\n addedColumns(): ColumnDefinition[] {\n return this.columns.filter((column) => !column.attributes.change)\n }\n\n /** The existing columns change() redefines (on a table being created, every column is added instead). */\n changedColumns(): ColumnDefinition[] {\n return this.creating ? [] : this.columns.filter((column) => column.attributes.change === true)\n }\n\n /** Laravel's default index name: {table}_{columns}_{type}, lowercased, with - and . replaced by _. */\n createIndexName(type: IndexType | 'foreign', columns: string[]): string {\n return `${this.table}_${columns.join('_')}_${type}`.toLowerCase().replace(/[-.]/g, '_')\n }\n\n /** The index commands implied by column modifiers (t.string('email').unique()), in column order. */\n fluentIndexCommands(): BlueprintCommand[] {\n const commands: BlueprintCommand[] = []\n for (const column of this.columns) {\n for (const type of ['primary', 'unique', 'index'] as const) {\n const value = column.attributes[type]\n if (!value) continue\n const index = typeof value === 'string' ? value : this.createIndexName(type, [column.name])\n commands.push({ name: type, columns: [column.name], index })\n }\n }\n return commands\n }\n\n private indexCommand(type: IndexType, columns: string | string[], name?: string): void {\n const list = [columns].flat()\n this.commands.push({ name: type, columns: list, index: name ?? this.createIndexName(type, list) })\n }\n\n private indexNameFor(type: IndexType | 'foreign', index: string | string[]): string {\n return Array.isArray(index) ? this.createIndexName(type, index) : index\n }\n}\n","import { sql, type RawBuilder } from 'kysely'\nimport type { DriverName } from '@orieljs/contracts'\nimport type { ConnectionConfig } from '../Connectors/dialect'\nimport { LogicError } from '../errors'\nimport { Expression, rawWithBindings } from '../Query/Expression'\nimport type { Blueprint, BlueprintCommand } from './Blueprint'\nimport { ColumnDefinition } from './ColumnDefinition'\nimport type { ForeignKeyDefinition } from './ForeignKeyDefinition'\n\ntype Sql = RawBuilder<unknown>\n\n/** One column of an existing table, as reported by Schema.getColumns(). */\nexport interface ColumnInfo {\n name: string\n /** The base type, lowercased: 'varchar', 'bigint', 'int8', 'tinyint', 'timestamp', … (driver-specific). */\n type_name: string\n /** The full type, lowercased: 'varchar(255)', 'tinyint(1)', 'timestamp(0) without time zone', … */\n type: string\n nullable: boolean\n default: string | null\n auto_increment: boolean\n}\n\n/** One index of an existing table, as reported by Schema.getIndexes() (Laravel's shape). */\nexport interface IndexInfo {\n /** Lower-cased. The primary key is 'primary' on MySQL and on a SQLite rowid table, `{table}_pkey` on Postgres. */\n name: string\n columns: string[]\n /** The index method ('btree', 'hash', …) on Postgres and MySQL; null on SQLite. */\n type: string | null\n unique: boolean\n primary: boolean\n}\n\n/** One foreign key of an existing table, as reported by Schema.getForeignKeys() (Laravel's shape). */\nexport interface ForeignKeyInfo {\n /** The constraint name; null on SQLite, which doesn't keep it. */\n name: string | null\n columns: string[]\n foreign_schema: string\n foreign_table: string\n /** Empty when a SQLite key names only the table (it then points at that table's primary key). */\n foreign_columns: string[]\n /** 'cascade', 'restrict', 'set null', 'set default' or 'no action'. */\n on_update: string\n on_delete: string\n}\n\nconst list = (value: unknown): string[] => (value === null || value === undefined || value === '' ? [] : String(value).split(','))\n\n/**\n * A step a blueprint can't express as fixed SQL: on SQLite, rebuilding the table from its live definition plus these\n * key commands and changed columns. SchemaBuilder.build() runs it (Schema/SqliteTableRebuild.ts).\n */\nexport interface TableRebuild {\n readonly kind: 'rebuild'\n readonly table: string\n readonly commands: BlueprintCommand[]\n readonly changes: ColumnDefinition[]\n}\n\n/** One step of a compiled blueprint: a statement, or a table rebuild. */\nexport type SchemaStep = Sql | TableRebuild\n\nexport const isTableRebuild = (step: SchemaStep): step is TableRebuild => (step as Partial<TableRebuild>).kind === 'rebuild'\n\nconst join = (parts: Sql[], separator = ', '): Sql => sql.join(parts, sql.raw(separator))\nconst columnList = (columns: readonly string[]): Sql => join(columns.map((column) => sql.id(column)))\n\n/**\n * Turns a Blueprint into DDL for one driver (Laravel's Schema\\Grammars). Identifiers go through sql.id();\n * default values and comments are quoted literals (sql.lit); only DB.raw() defaults are written as-is.\n */\nexport abstract class SchemaGrammar {\n abstract readonly driver: DriverName\n\n constructor(protected readonly config: Partial<ConnectionConfig> = {}) {}\n\n static for(driver: DriverName, config: Partial<ConnectionConfig> = {}): SchemaGrammar {\n if (driver === 'pgsql') return new PostgresSchemaGrammar(config)\n if (driver === 'mysql') return new MySqlSchemaGrammar(config)\n return new SqliteSchemaGrammar(config)\n }\n\n /**\n * Every statement for the blueprint: create/add first, then commands in order, then indexes from column modifiers.\n * A blueprint that can only run against the live table (a SQLite rebuild) throws: run it with Schema.table().\n */\n compile(blueprint: Blueprint): Sql[] {\n const steps = this.compileSteps(blueprint)\n if (steps.some(isTableRebuild)) {\n throw new LogicError(`On SQLite, changing [${blueprint.table}] rebuilds the table from its live definition: run the blueprint with Schema.table().`)\n }\n return steps as Sql[]\n }\n\n /** compile() with table rebuilds as steps of their own; consecutive rebuilds of one run are merged into one. */\n compileSteps(blueprint: Blueprint): SchemaStep[] {\n const statements: SchemaStep[] = []\n const commands = [...blueprint.commands, ...blueprint.fluentIndexCommands()]\n const handled = new Set<BlueprintCommand>()\n if (blueprint.creating) {\n statements.push(this.compileCreate(blueprint, commands, handled))\n } else {\n if (blueprint.addedColumns().length) statements.push(...this.compileAdd(blueprint, commands, handled))\n for (const column of blueprint.changedColumns()) statements.push(...this.compileChange(blueprint, column))\n }\n for (const command of commands) {\n if (command.name === 'create' || handled.has(command)) continue\n statements.push(...this.compileCommand(blueprint, command))\n }\n if (blueprint.creating || blueprint.columns.length) statements.push(...this.compileComments(blueprint))\n return mergeRebuilds(statements)\n }\n\n protected compileCreate(blueprint: Blueprint, _commands: BlueprintCommand[], _handled: Set<BlueprintCommand>): Sql {\n return sql`create table ${sql.id(blueprint.table)} (${join(blueprint.columns.map((column) => this.columnDefinition(column)))})`\n }\n\n protected compileAdd(blueprint: Blueprint, _commands: BlueprintCommand[], _handled: Set<BlueprintCommand>): Sql[] {\n return blueprint.addedColumns().map((column) => sql`alter table ${sql.id(blueprint.table)} add column ${this.columnDefinition(column)}`)\n }\n\n /** Redefines an existing column (change()). */\n protected abstract compileChange(blueprint: Blueprint, column: ColumnDefinition): SchemaStep[]\n\n protected compileCommand(blueprint: Blueprint, command: BlueprintCommand): SchemaStep[] {\n const table = sql.id(blueprint.table)\n switch (command.name) {\n case 'primary':\n return [sql`alter table ${table} add primary key (${columnList(command.columns)})`]\n case 'unique':\n return [this.compileUnique(blueprint, command.index, command.columns)]\n case 'index':\n return [this.compileIndex(blueprint, command.index, command.columns)]\n case 'foreign':\n return [sql`alter table ${table} add constraint ${sql.id(command.foreign.indexName)} ${this.foreignKeyClause(command.foreign)}`]\n case 'dropColumn':\n return command.columns.map((column) => sql`alter table ${table} drop column ${sql.id(column)}`)\n case 'renameColumn':\n return [sql`alter table ${table} rename column ${sql.id(command.from)} to ${sql.id(command.to)}`]\n case 'dropPrimary':\n return [this.compileDropPrimary(blueprint, command.index)]\n case 'dropUnique':\n return [this.compileDropUnique(blueprint, command.index)]\n case 'dropIndex':\n return [this.compileDropIndex(blueprint, command.index)]\n case 'dropForeign':\n return [this.compileDropForeign(blueprint, command.index)]\n case 'rename':\n return [this.compileRename(blueprint.table, command.to)]\n case 'drop':\n return [this.compileDrop(blueprint.table)]\n case 'dropIfExists':\n return [this.compileDropIfExists(blueprint.table)]\n case 'create':\n return []\n }\n }\n\n compileRename(from: string, to: string): Sql {\n return sql`alter table ${sql.id(from)} rename to ${sql.id(to)}`\n }\n\n compileDrop(table: string): Sql {\n return sql`drop table ${sql.id(table)}`\n }\n\n compileDropIfExists(table: string): Sql {\n return sql`drop table if exists ${sql.id(table)}`\n }\n\n protected compileUnique(blueprint: Blueprint, index: string, columns: string[]): Sql {\n return sql`alter table ${sql.id(blueprint.table)} add constraint ${sql.id(index)} unique (${columnList(columns)})`\n }\n\n protected compileIndex(blueprint: Blueprint, index: string, columns: string[]): Sql {\n return sql`create index ${sql.id(index)} on ${sql.id(blueprint.table)} (${columnList(columns)})`\n }\n\n protected compileDropPrimary(blueprint: Blueprint, index: string): Sql {\n return sql`alter table ${sql.id(blueprint.table)} drop constraint ${sql.id(index)}`\n }\n\n protected compileDropUnique(blueprint: Blueprint, index: string): Sql {\n return sql`alter table ${sql.id(blueprint.table)} drop constraint ${sql.id(index)}`\n }\n\n protected compileDropIndex(_blueprint: Blueprint, index: string): Sql {\n return sql`drop index ${sql.id(index)}`\n }\n\n protected compileDropForeign(blueprint: Blueprint, index: string): Sql {\n return sql`alter table ${sql.id(blueprint.table)} drop constraint ${sql.id(index)}`\n }\n\n protected compileComments(_blueprint: Blueprint): Sql[] {\n return []\n }\n\n /** `foreign key (\"user_id\") references \"users\" (\"id\") on delete cascade` */\n protected foreignKeyClause(foreign: ForeignKeyDefinition): Sql {\n return sql`foreign key (${columnList(foreign.columns)}) ${this.referencesClause(foreign)}`\n }\n\n /** `references \"users\" (\"id\") on delete cascade on update …` */\n protected referencesClause(foreign: ForeignKeyDefinition): Sql {\n if (!foreign.referencedTable) {\n throw new LogicError(`Foreign key [${foreign.indexName}] has no referenced table: call on('table') or constrained().`)\n }\n const columns = foreign.referencedColumns.length ? sql` (${columnList(foreign.referencedColumns)})` : sql.raw('')\n const parts: Sql[] = [sql`references ${sql.id(foreign.referencedTable)}${columns}`]\n if (foreign.deleteAction) parts.push(sql.raw(`on delete ${foreign.deleteAction}`))\n if (foreign.updateAction) parts.push(sql.raw(`on update ${foreign.updateAction}`))\n return join(parts, ' ')\n }\n\n /** `\"name\" type modifiers` */\n columnDefinition(column: ColumnDefinition): Sql {\n return join([sql`${sql.id(column.name)} ${this.type(column)}`, ...this.modifiers(column)], '')\n }\n\n protected abstract type(column: ColumnDefinition): Sql\n protected abstract modifiers(column: ColumnDefinition): Sql[]\n\n /** Laravel's getDefaultValue(): raw expressions as-is, booleans as '1'/'0', everything else as a quoted literal. */\n protected defaultValue(value: unknown): Sql {\n if (value instanceof Expression) return rawWithBindings(value.value, value.bindings)\n if (typeof value === 'boolean') return sql.lit(value ? '1' : '0')\n return sql.lit(String(value))\n }\n\n protected nullable(column: ColumnDefinition): Sql {\n return sql.raw(column.attributes.nullable ? ' null' : ' not null')\n }\n\n protected default(column: ColumnDefinition): Sql | undefined {\n const value = column.attributes.default\n return value === undefined || value === null ? undefined : sql` default ${this.defaultValue(value)}`\n }\n\n protected enumCheck(column: ColumnDefinition, type: string): Sql {\n const allowed = join((column.attributes.allowed ?? []).map((value) => sql.lit(value)))\n return sql`${sql.raw(type)} check (${sql.id(column.name)} in (${allowed}))`\n }\n\n // ---------------------------------------------------------------- introspection\n\n abstract compileTables(): Sql\n abstract compileColumns(table: string): Sql\n abstract normalizeColumns(rows: Array<Record<string, unknown>>, tableSql?: string): ColumnInfo[]\n abstract compileIndexes(table: string): Sql\n abstract normalizeIndexes(rows: Array<Record<string, unknown>>): IndexInfo[]\n abstract compileForeignKeys(table: string): Sql\n abstract normalizeForeignKeys(rows: Array<Record<string, unknown>>): ForeignKeyInfo[]\n abstract compileEnableForeignKeyConstraints(): Sql\n abstract compileDisableForeignKeyConstraints(): Sql\n}\n\nconst present = (parts: Array<Sql | undefined>): Sql[] => parts.filter((part): part is Sql => part !== undefined)\n\n/** Folds each run of consecutive table rebuilds into one, as Laravel adds one 'alter' after each run of alter commands. */\nfunction mergeRebuilds(steps: SchemaStep[]): SchemaStep[] {\n const merged: SchemaStep[] = []\n for (const step of steps) {\n const previous = merged.at(-1)\n if (isTableRebuild(step) && previous !== undefined && isTableRebuild(previous)) {\n merged[merged.length - 1] = { ...previous, commands: [...previous.commands, ...step.commands], changes: [...previous.changes, ...step.changes] }\n } else {\n merged.push(step)\n }\n }\n return merged\n}\n\nexport class SqliteSchemaGrammar extends SchemaGrammar {\n readonly driver = 'sqlite' as const\n\n /** A new table's primary and foreign keys go inside create table (adding them later rebuilds the table). */\n protected override compileCreate(blueprint: Blueprint, commands: BlueprintCommand[], handled: Set<BlueprintCommand>): Sql {\n const parts = blueprint.columns.map((column) => this.columnDefinition(column))\n for (const command of commands) {\n if (command.name === 'primary') {\n parts.push(sql`primary key (${columnList(command.columns)})`)\n handled.add(command)\n } else if (command.name === 'foreign') {\n parts.push(this.foreignKeyClause(command.foreign))\n handled.add(command)\n }\n }\n return sql`create table ${sql.id(blueprint.table)} (${join(parts)})`\n }\n\n /** New columns may carry an inline `references` clause (the only foreign key SQLite can add later). */\n protected override compileAdd(blueprint: Blueprint, commands: BlueprintCommand[], handled: Set<BlueprintCommand>): Sql[] {\n return blueprint.addedColumns().map((column) => {\n const foreign = commands.find(\n (command): command is Extract<BlueprintCommand, { name: 'foreign' }> =>\n command.name === 'foreign' && command.foreign.columns.length === 1 && command.foreign.columns[0] === column.name,\n )\n let definition = this.columnDefinition(column)\n if (foreign) {\n definition = sql`${definition} ${this.referencesClause(foreign.foreign)}`\n handled.add(foreign)\n }\n return sql`alter table ${sql.id(blueprint.table)} add column ${definition}`\n })\n }\n\n /**\n * SQLite can't add or drop a primary or foreign key on an existing table: those commands rebuild the table (Laravel\n * 11+'s compileAlter), as a step SchemaBuilder.build() runs against the live table.\n */\n protected override compileCommand(blueprint: Blueprint, command: BlueprintCommand): SchemaStep[] {\n if (command.name === 'dropForeign' && !command.columns?.length) {\n throw new LogicError('This database driver does not support dropping foreign keys by name.')\n }\n if (command.name === 'primary' || command.name === 'foreign' || command.name === 'dropPrimary' || command.name === 'dropForeign') {\n return [{ kind: 'rebuild', table: blueprint.table, commands: [command], changes: [] }]\n }\n return super.compileCommand(blueprint, command)\n }\n\n /** SQLite can't alter a column: changing one rebuilds the table with the new definition. */\n protected compileChange(blueprint: Blueprint, column: ColumnDefinition): SchemaStep[] {\n return [{ kind: 'rebuild', table: blueprint.table, commands: [], changes: [column] }]\n }\n\n /** `foreign key (…) references … on delete …`, a table constraint of a rebuilt table. */\n compileForeignKeyConstraint(foreign: ForeignKeyDefinition): Sql {\n return this.foreignKeyClause(foreign)\n }\n\n protected override compileUnique(blueprint: Blueprint, index: string, columns: string[]): Sql {\n return sql`create unique index ${sql.id(index)} on ${sql.id(blueprint.table)} (${columnList(columns)})`\n }\n\n protected override compileDropUnique(_blueprint: Blueprint, index: string): Sql {\n return sql`drop index ${sql.id(index)}`\n }\n\n protected type(column: ColumnDefinition): Sql {\n const { type } = column.attributes\n switch (type) {\n case 'bigInteger': case 'integer': case 'mediumInteger': case 'smallInteger': case 'tinyInteger':\n return sql.raw('integer')\n case 'string': case 'char': case 'uuid': case 'ulid':\n return sql.raw('varchar')\n case 'text': case 'mediumText': case 'longText': case 'json': case 'jsonb':\n return sql.raw('text')\n case 'boolean':\n return sql.raw('tinyint(1)')\n case 'date':\n return sql.raw('date')\n case 'dateTime': case 'timestamp':\n return sql.raw('datetime')\n case 'time':\n return sql.raw('time')\n case 'decimal':\n return sql.raw('numeric')\n case 'float':\n return sql.raw('float')\n case 'double':\n return sql.raw('double')\n case 'binary':\n return sql.raw('blob')\n case 'enum':\n return this.enumCheck(column, 'varchar')\n }\n }\n\n protected modifiers(column: ColumnDefinition): Sql[] {\n const increment = column.attributes.autoIncrement ? sql.raw(' primary key autoincrement') : undefined\n return present([increment, column.attributes.nullable ? undefined : sql.raw(' not null'), this.default(column)])\n }\n\n compileTables(): Sql {\n return sql`select name from sqlite_master where type = 'table' and name not like 'sqlite_%' order by name`\n }\n\n compileColumns(table: string): Sql {\n return sql`select name, type, \"notnull\", dflt_value, pk, (select sql from sqlite_master where type = 'table' and name = ${table}) as table_sql from pragma_table_info(${table}) order by cid`\n }\n\n normalizeColumns(rows: Array<Record<string, unknown>>): ColumnInfo[] {\n return rows.map((row) => {\n const type = String(row.type).toLowerCase()\n const autoIncrement = Number(row.pk) === 1 && type === 'integer' && /autoincrement/i.test(String(row.table_sql ?? ''))\n return {\n name: String(row.name),\n type_name: type.replace(/\\(.*$/, '').trim(),\n type,\n nullable: Number(row.notnull) === 0 && !autoIncrement,\n default: row.dflt_value === null || row.dflt_value === undefined ? null : String(row.dflt_value),\n auto_increment: autoIncrement,\n }\n })\n }\n\n /** Laravel's query: the primary key from pragma_table_xinfo, then every index of pragma_index_list with its columns. */\n compileIndexes(table: string): Sql {\n return sql`select 'primary' as name, group_concat(col) as columns, 1 as \"unique\", 1 as \"primary\" from (select name as col from pragma_table_xinfo(${table}) where pk > 0 order by pk, cid) group by name\n union select name, group_concat(col) as columns, \"unique\", origin = 'pk' as \"primary\" from (select il.*, ii.name as col from pragma_index_list(${table}) il, pragma_index_info(il.name) ii order by il.seq, ii.seqno) group by name, \"unique\", \"primary\"`\n }\n\n /** A table whose primary key has its own index (not a rowid alias) lists it twice: the index entry is kept. */\n normalizeIndexes(rows: Array<Record<string, unknown>>): IndexInfo[] {\n const indexes = rows.map((row) => ({\n name: String(row.name).toLowerCase(),\n columns: list(row.columns),\n type: null,\n unique: Number(row.unique) === 1,\n primary: Number(row.primary) === 1,\n }))\n return indexes.filter((index) => index.primary).length > 1 ? indexes.filter((index) => index.name !== 'primary') : indexes\n }\n\n compileForeignKeys(table: string): Sql {\n return sql`select group_concat(\"from\") as columns, 'main' as foreign_schema, \"table\" as foreign_table, group_concat(\"to\") as foreign_columns, on_update, on_delete\n from (select * from pragma_foreign_key_list(${table}) order by id desc, seq) group by id, \"table\", on_update, on_delete`\n }\n\n normalizeForeignKeys(rows: Array<Record<string, unknown>>): ForeignKeyInfo[] {\n return rows.map((row) => ({\n name: null,\n columns: list(row.columns),\n foreign_schema: String(row.foreign_schema),\n foreign_table: String(row.foreign_table),\n foreign_columns: list(row.foreign_columns),\n on_update: String(row.on_update).toLowerCase(),\n on_delete: String(row.on_delete).toLowerCase(),\n }))\n }\n\n compileEnableForeignKeyConstraints(): Sql {\n return sql.raw('PRAGMA foreign_keys = ON')\n }\n\n compileDisableForeignKeyConstraints(): Sql {\n return sql.raw('PRAGMA foreign_keys = OFF')\n }\n}\n\n/** pg_constraint's confupdtype/confdeltype codes (Laravel's PostgresProcessor). */\nconst POSTGRES_ACTIONS: Record<string, string> = { a: 'no action', r: 'restrict', c: 'cascade', n: 'set null', d: 'set default' }\n\nexport class PostgresSchemaGrammar extends SchemaGrammar {\n readonly driver = 'pgsql' as const\n\n /** A changed column's comment is set again, or cleared (`is NULL`) when the new definition has none (Laravel 11+). */\n protected override compileComments(blueprint: Blueprint): Sql[] {\n const changed = new Set(blueprint.changedColumns())\n return blueprint.columns\n .filter((column) => column.attributes.comment !== undefined || changed.has(column))\n .map((column) => {\n const comment = column.attributes.comment\n return sql`comment on column ${sql.id(blueprint.table, column.name)} is ${comment === undefined ? sql.raw('NULL') : sql.lit(comment)}`\n })\n }\n\n /**\n * Laravel's compileChange(): `alter column` for the type, the nullability and the default, in one statement. A serial\n * type becomes its integer type (the sequence stays), and an auto-increment column keeps its default. No `using`\n * clause: a change Postgres can't cast implicitly fails, as in Laravel.\n */\n protected compileChange(blueprint: Blueprint, column: ColumnDefinition): SchemaStep[] {\n const name = sql.id(column.name)\n const { autoIncrement, nullable, default: value } = column.attributes\n const changes: Sql[] = [\n sql`type ${this.type(new ColumnDefinition({ ...column.attributes, autoIncrement: false }))}`,\n sql.raw(nullable ? 'drop not null' : 'set not null'),\n ]\n if (!autoIncrement) changes.push(value === undefined || value === null ? sql.raw('drop default') : sql`set default ${this.defaultValue(value)}`)\n return [sql`alter table ${sql.id(blueprint.table)} ${join(changes.map((change) => sql`alter column ${name} ${change}`))}`]\n }\n\n protected type(column: ColumnDefinition): Sql {\n const { type, autoIncrement, length, total, places, precision } = column.attributes\n switch (type) {\n case 'bigInteger':\n return sql.raw(autoIncrement ? 'bigserial' : 'bigint')\n case 'integer': case 'mediumInteger':\n return sql.raw(autoIncrement ? 'serial' : 'integer')\n case 'smallInteger': case 'tinyInteger':\n return sql.raw(autoIncrement ? 'smallserial' : 'smallint')\n case 'string':\n return sql.raw(`varchar(${length ?? 255})`)\n case 'char':\n return sql.raw(`char(${length ?? 255})`)\n case 'text': case 'mediumText': case 'longText':\n return sql.raw('text')\n case 'boolean':\n return sql.raw('boolean')\n case 'date':\n return sql.raw('date')\n case 'dateTime': case 'timestamp':\n return sql.raw(`timestamp(${precision ?? 0}) without time zone`)\n case 'time':\n return sql.raw(`time(${precision ?? 0}) without time zone`)\n case 'decimal':\n return sql.raw(`decimal(${total ?? 8}, ${places ?? 2})`)\n case 'float':\n return sql.raw(precision ? `float(${precision})` : 'real')\n case 'double':\n return sql.raw('double precision')\n case 'json':\n return sql.raw('json')\n case 'jsonb':\n return sql.raw('jsonb')\n case 'uuid':\n return sql.raw('uuid')\n case 'ulid':\n return sql.raw('char(26)')\n case 'binary':\n return sql.raw('bytea')\n case 'enum':\n return this.enumCheck(column, 'varchar(255)')\n }\n }\n\n protected modifiers(column: ColumnDefinition): Sql[] {\n return present([this.nullable(column), this.default(column), column.attributes.autoIncrement ? sql.raw(' primary key') : undefined])\n }\n\n compileTables(): Sql {\n return sql`select tablename as name from pg_tables where schemaname = current_schema() order by tablename`\n }\n\n compileColumns(table: string): Sql {\n return sql`select a.attname as name, t.typname as type_name, format_type(a.atttypid, a.atttypmod) as type, not a.attnotnull as nullable, pg_get_expr(d.adbin, d.adrelid) as ${sql.id('default')}\n from pg_attribute a\n join pg_class c on c.oid = a.attrelid\n join pg_namespace n on n.oid = c.relnamespace\n join pg_type t on t.oid = a.atttypid\n left join pg_attrdef d on d.adrelid = a.attrelid and d.adnum = a.attnum\n where c.relname = ${table} and n.nspname = current_schema() and a.attnum > 0 and not a.attisdropped\n order by a.attnum`\n }\n\n normalizeColumns(rows: Array<Record<string, unknown>>): ColumnInfo[] {\n return rows.map((row) => {\n const defaultValue = row.default === null || row.default === undefined ? null : String(row.default)\n return {\n name: String(row.name),\n type_name: String(row.type_name).toLowerCase(),\n type: String(row.type).toLowerCase(),\n nullable: row.nullable === true,\n default: defaultValue,\n auto_increment: defaultValue !== null && defaultValue.startsWith('nextval('),\n }\n })\n }\n\n compileIndexes(table: string): Sql {\n return sql`select ic.relname as name, string_agg(a.attname, ',' order by indseq.ord) as columns, am.amname as ${sql.id('type')}, i.indisunique as ${sql.id('unique')}, i.indisprimary as ${sql.id('primary')}\n from pg_index i\n join pg_class tc on tc.oid = i.indrelid\n join pg_namespace tn on tn.oid = tc.relnamespace\n join pg_class ic on ic.oid = i.indexrelid\n join pg_am am on am.oid = ic.relam\n join lateral unnest(i.indkey) with ordinality as indseq(num, ord) on true\n left join pg_attribute a on a.attrelid = i.indrelid and a.attnum = indseq.num\n where tc.relname = ${table} and tn.nspname = current_schema()\n group by ic.relname, am.amname, i.indisunique, i.indisprimary`\n }\n\n normalizeIndexes(rows: Array<Record<string, unknown>>): IndexInfo[] {\n return rows.map((row) => ({\n name: String(row.name).toLowerCase(),\n columns: list(row.columns),\n type: String(row.type).toLowerCase(),\n unique: row.unique === true,\n primary: row.primary === true,\n }))\n }\n\n compileForeignKeys(table: string): Sql {\n return sql`select c.conname as name, string_agg(la.attname, ',' order by conseq.ord) as columns, fn.nspname as foreign_schema, fc.relname as foreign_table,\n string_agg(fa.attname, ',' order by conseq.ord) as foreign_columns, c.confupdtype as on_update, c.confdeltype as on_delete\n from pg_constraint c\n join pg_class tc on c.conrelid = tc.oid\n join pg_namespace tn on tn.oid = tc.relnamespace\n join pg_class fc on c.confrelid = fc.oid\n join pg_namespace fn on fn.oid = fc.relnamespace\n join lateral unnest(c.conkey) with ordinality as conseq(num, ord) on true\n join pg_attribute la on la.attrelid = c.conrelid and la.attnum = conseq.num\n join pg_attribute fa on fa.attrelid = c.confrelid and fa.attnum = c.confkey[conseq.ord]\n where c.contype = 'f' and tc.relname = ${table} and tn.nspname = current_schema()\n group by c.conname, fn.nspname, fc.relname, c.confupdtype, c.confdeltype`\n }\n\n normalizeForeignKeys(rows: Array<Record<string, unknown>>): ForeignKeyInfo[] {\n return rows.map((row) => ({\n name: String(row.name),\n columns: list(row.columns),\n foreign_schema: String(row.foreign_schema),\n foreign_table: String(row.foreign_table),\n foreign_columns: list(row.foreign_columns),\n on_update: POSTGRES_ACTIONS[String(row.on_update).toLowerCase()] ?? 'no action',\n on_delete: POSTGRES_ACTIONS[String(row.on_delete).toLowerCase()] ?? 'no action',\n }))\n }\n\n compileEnableForeignKeyConstraints(): Sql {\n return sql.raw('SET CONSTRAINTS ALL IMMEDIATE')\n }\n\n compileDisableForeignKeyConstraints(): Sql {\n return sql.raw('SET CONSTRAINTS ALL DEFERRED')\n }\n}\n\nexport class MySqlSchemaGrammar extends SchemaGrammar {\n readonly driver = 'mysql' as const\n\n protected override compileCreate(blueprint: Blueprint, commands: BlueprintCommand[], handled: Set<BlueprintCommand>): Sql {\n const charset = this.config.charset ?? 'utf8mb4'\n const collation = this.config.collation ?? 'utf8mb4_unicode_ci'\n return sql`${super.compileCreate(blueprint, commands, handled)} default character set ${sql.raw(charset.replace(/[^\\w]/g, ''))} collate ${sql.lit(collation)}`\n }\n\n protected override compileAdd(blueprint: Blueprint): Sql[] {\n return blueprint.addedColumns().map((column) => sql`alter table ${sql.id(blueprint.table)} add ${this.columnDefinition(column)}`)\n }\n\n /** Laravel's compileChange(): `modify` with the column's whole new definition. */\n protected compileChange(blueprint: Blueprint, column: ColumnDefinition): SchemaStep[] {\n return [sql`alter table ${sql.id(blueprint.table)} modify ${this.columnDefinition(column)}`]\n }\n\n protected override compileUnique(blueprint: Blueprint, index: string, columns: string[]): Sql {\n return sql`alter table ${sql.id(blueprint.table)} add unique ${sql.id(index)}(${columnList(columns)})`\n }\n\n protected override compileIndex(blueprint: Blueprint, index: string, columns: string[]): Sql {\n return sql`alter table ${sql.id(blueprint.table)} add index ${sql.id(index)}(${columnList(columns)})`\n }\n\n protected override compileDropPrimary(blueprint: Blueprint): Sql {\n return sql`alter table ${sql.id(blueprint.table)} drop primary key`\n }\n\n protected override compileDropUnique(blueprint: Blueprint, index: string): Sql {\n return sql`alter table ${sql.id(blueprint.table)} drop index ${sql.id(index)}`\n }\n\n protected override compileDropIndex(blueprint: Blueprint, index: string): Sql {\n return sql`alter table ${sql.id(blueprint.table)} drop index ${sql.id(index)}`\n }\n\n protected override compileDropForeign(blueprint: Blueprint, index: string): Sql {\n return sql`alter table ${sql.id(blueprint.table)} drop foreign key ${sql.id(index)}`\n }\n\n protected type(column: ColumnDefinition): Sql {\n const { type, length, total, places, precision, allowed } = column.attributes\n switch (type) {\n case 'bigInteger':\n return sql.raw('bigint')\n case 'integer':\n return sql.raw('int')\n case 'mediumInteger':\n return sql.raw('mediumint')\n case 'smallInteger':\n return sql.raw('smallint')\n case 'tinyInteger':\n return sql.raw('tinyint')\n case 'string':\n return sql.raw(`varchar(${length ?? 255})`)\n case 'char':\n return sql.raw(`char(${length ?? 255})`)\n case 'text':\n return sql.raw('text')\n case 'mediumText':\n return sql.raw('mediumtext')\n case 'longText':\n return sql.raw('longtext')\n case 'boolean':\n return sql.raw('tinyint(1)')\n case 'date':\n return sql.raw('date')\n case 'dateTime':\n return sql.raw(precision ? `datetime(${precision})` : 'datetime')\n case 'timestamp':\n return sql.raw(precision ? `timestamp(${precision})` : 'timestamp')\n case 'time':\n return sql.raw(precision ? `time(${precision})` : 'time')\n case 'decimal':\n return sql.raw(`decimal(${total ?? 8}, ${places ?? 2})`)\n case 'float':\n return sql.raw(precision ? `float(${precision})` : 'float')\n case 'double':\n return sql.raw('double')\n case 'json': case 'jsonb':\n return sql.raw('json')\n case 'uuid':\n return sql.raw('char(36)')\n case 'ulid':\n return sql.raw('char(26)')\n case 'binary':\n return sql.raw('blob')\n case 'enum':\n return sql`enum(${join((allowed ?? []).map((value) => sql.lit(value)))})`\n }\n }\n\n protected modifiers(column: ColumnDefinition): Sql[] {\n const { unsigned, autoIncrement, onUpdate, comment, after, first, change, primary } = column.attributes\n // A changed auto-increment column already is the key (Laravel's modifyIncrement).\n const increment = change && !primary ? ' auto_increment' : ' auto_increment primary key'\n return present([\n unsigned ? sql.raw(' unsigned') : undefined,\n this.nullable(column),\n this.default(column),\n onUpdate ? sql` on update ${this.defaultValue(onUpdate)}` : undefined,\n autoIncrement ? sql.raw(increment) : undefined,\n comment === undefined ? undefined : sql` comment ${sql.lit(comment)}`,\n after === undefined ? undefined : sql` after ${sql.id(after)}`,\n first ? sql.raw(' first') : undefined,\n ])\n }\n\n compileTables(): Sql {\n return sql`select table_name as name from information_schema.tables where table_schema = database() and table_type = 'BASE TABLE' order by table_name`\n }\n\n compileColumns(table: string): Sql {\n return sql`select column_name as name, data_type as type_name, column_type as type, is_nullable = 'YES' as nullable, column_default as ${sql.id('default')}, extra like '%auto_increment%' as auto_increment\n from information_schema.columns where table_schema = database() and table_name = ${table} order by ordinal_position`\n }\n\n normalizeColumns(rows: Array<Record<string, unknown>>): ColumnInfo[] {\n return rows.map((row) => ({\n name: String(row.name),\n type_name: String(row.type_name).toLowerCase(),\n type: String(row.type).toLowerCase(),\n nullable: Number(row.nullable) === 1,\n default: row.default === null || row.default === undefined ? null : String(row.default),\n auto_increment: Number(row.auto_increment) === 1,\n }))\n }\n\n compileIndexes(table: string): Sql {\n return sql`select index_name as ${sql.id('name')}, group_concat(column_name order by seq_in_index) as ${sql.id('columns')}, index_type as ${sql.id('type')}, not non_unique as ${sql.id('unique')}\n from information_schema.statistics where table_schema = schema() and table_name = ${table}\n group by index_name, index_type, non_unique`\n }\n\n normalizeIndexes(rows: Array<Record<string, unknown>>): IndexInfo[] {\n return rows.map((row) => {\n const name = String(row.name).toLowerCase()\n return { name, columns: list(row.columns), type: String(row.type).toLowerCase(), unique: Number(row.unique) === 1, primary: name === 'primary' }\n })\n }\n\n compileForeignKeys(table: string): Sql {\n return sql`select kc.constraint_name as ${sql.id('name')}, group_concat(kc.column_name order by kc.ordinal_position) as ${sql.id('columns')},\n kc.referenced_table_schema as ${sql.id('foreign_schema')}, kc.referenced_table_name as ${sql.id('foreign_table')},\n group_concat(kc.referenced_column_name order by kc.ordinal_position) as ${sql.id('foreign_columns')}, rc.update_rule as ${sql.id('on_update')}, rc.delete_rule as ${sql.id('on_delete')}\n from information_schema.key_column_usage kc join information_schema.referential_constraints rc\n on kc.constraint_schema = rc.constraint_schema and kc.constraint_name = rc.constraint_name\n where kc.table_schema = schema() and kc.table_name = ${table} and kc.referenced_table_name is not null\n group by kc.constraint_name, kc.referenced_table_schema, kc.referenced_table_name, rc.update_rule, rc.delete_rule`\n }\n\n normalizeForeignKeys(rows: Array<Record<string, unknown>>): ForeignKeyInfo[] {\n return rows.map((row) => ({\n name: String(row.name),\n columns: list(row.columns),\n foreign_schema: String(row.foreign_schema),\n foreign_table: String(row.foreign_table),\n foreign_columns: list(row.foreign_columns),\n on_update: String(row.on_update).toLowerCase(),\n on_delete: String(row.on_delete).toLowerCase(),\n }))\n }\n\n compileEnableForeignKeyConstraints(): Sql {\n return sql.raw('SET FOREIGN_KEY_CHECKS=1')\n }\n\n compileDisableForeignKeyConstraints(): Sql {\n return sql.raw('SET FOREIGN_KEY_CHECKS=0')\n }\n}\n","import { sql, type RawBuilder } from 'kysely'\nimport type { Connection } from '../Connection'\nimport { LogicError } from '../errors'\nimport { ForeignKeyDefinition, type ReferentialAction } from './ForeignKeyDefinition'\nimport type { ForeignKeyInfo, SqliteSchemaGrammar, TableRebuild } from './Grammar'\n\ntype Sql = RawBuilder<unknown>\n\n/** A row of pragma_table_xinfo. */\ninterface LiveColumn {\n name: string\n type: string\n notnull: number\n dflt_value: string | null\n pk: number\n hidden: number\n}\n\nconst QUOTES: Record<string, string> = { \"'\": \"'\", '\"': '\"', '`': '`', '[': ']' }\nconst lower = (value: string): string => value.toLowerCase()\nconst join = (parts: Sql[], separator = ', '): Sql => sql.join(parts, sql.raw(separator))\nconst columnList = (columns: readonly string[]): Sql => join(columns.map((column) => sql.id(column)))\nconst sameColumns = (a: readonly string[], b: readonly string[]): boolean =>\n a.length === b.length && a.every((column, i) => lower(column) === lower(b[i]!))\n\n/** The text with quoted strings, quoted identifiers and comments blanked out (same length), so it can be searched. */\nfunction mask(text: string): string {\n let out = ''\n for (let i = 0; i < text.length; i++) {\n const char = text[i]!\n const closer = QUOTES[char]\n let end = -1\n if (closer !== undefined) {\n end = i + 1\n while (end < text.length && !(text[end] === closer && (closer === ']' || text[end + 1] !== closer))) end += text[end] === closer ? 2 : 1\n } else if (char === '-' && text[i + 1] === '-') {\n end = text.indexOf('\\n', i)\n if (end === -1) end = text.length - 1\n } else if (char === '/' && text[i + 1] === '*') {\n end = text.indexOf('*/', i + 2)\n end = end === -1 ? text.length - 1 : end + 1\n }\n if (end === -1) {\n out += char\n continue\n }\n out += ' '.repeat(Math.min(end, text.length - 1) - i + 1)\n i = end\n }\n return out\n}\n\n/** The index just past the parenthesis that closes the one at `open` (in masked text). */\nfunction closingParen(masked: string, open: number): number {\n let depth = 0\n for (let i = open; i < masked.length; i++) {\n if (masked[i] === '(') depth++\n else if (masked[i] === ')' && --depth === 0) return i + 1\n }\n return masked.length\n}\n\n/** The definitions inside a `create table` statement (top-level, comma-separated) and what follows its closing paren. */\nexport function splitCreateTable(statement: string): { definitions: string[]; options: string } {\n const masked = mask(statement)\n const open = masked.indexOf('(')\n if (open === -1) return { definitions: [], options: '' }\n const close = closingParen(masked, open) - 1\n const definitions: string[] = []\n let depth = 0\n let start = open + 1\n for (let i = open + 1; i < close; i++) {\n if (masked[i] === '(') depth++\n else if (masked[i] === ')') depth--\n else if (masked[i] === ',' && depth === 0) {\n definitions.push(statement.slice(start, i).trim())\n start = i + 1\n }\n }\n definitions.push(statement.slice(start, close).trim())\n return { definitions: definitions.filter((definition) => definition !== ''), options: statement.slice(close + 1) }\n}\n\n/** The column a definition declares (unquoted), or undefined for a table constraint. */\nfunction definedColumn(definition: string): string | undefined {\n const closer = QUOTES[definition[0] ?? '']\n if (closer !== undefined) {\n const end = definition.indexOf(closer, 1)\n return definition.slice(1, end === -1 ? undefined : end).replaceAll(`${closer}${closer}`, closer)\n }\n if (/^(constraint|primary|unique|check|foreign)\\b/i.test(definition)) return undefined\n return /^[^\\s(]+/.exec(definition)?.[0]\n}\n\n/** What a column definition carries that pragma_table_info doesn't report: check constraints, a collation, autoincrement. */\nfunction columnClauses(definition: string): { checks: string[]; collation: string | undefined; autoincrement: boolean } {\n const masked = mask(definition)\n const checks: string[] = []\n for (const match of masked.matchAll(/\\bcheck\\s*\\(/gi)) {\n const open = match.index + match[0].length - 1\n checks.push(definition.slice(open, closingParen(masked, open)))\n }\n const collate = /\\bcollate\\s+/i.exec(masked)\n let collation: string | undefined\n if (collate) {\n const rest = definition.slice(collate.index + collate[0].length)\n const closer = QUOTES[rest[0] ?? '']\n collation = closer === undefined ? /^\\w+/.exec(rest)?.[0] : rest.slice(0, rest.indexOf(closer, 1) + 1)\n }\n return { checks, collation, autoincrement: /\\bautoincrement\\b/i.test(masked) }\n}\n\n/** A table-level check constraint (`check (…)` or `constraint name check (…)`), kept as written. */\nconst isTableCheck = (definition: string): boolean => /^(constraint\\s+\\S+\\s+)?check\\b/i.test(mask(definition))\n\n/**\n * A column as a rebuilt table declares it: the live type, not null and default, plus its parsed clauses. The default is\n * wrapped in parentheses: pragma_table_xinfo reports `default (datetime('now'))` as `datetime('now')`.\n */\nfunction renderColumn(column: LiveColumn, definition: string | undefined, autoincrement: boolean): Sql {\n const clauses = definition === undefined ? { checks: [], collation: undefined } : columnClauses(definition)\n const parts: Sql[] = [sql.id(column.name)]\n if (column.type) parts.push(sql.raw(` ${column.type}`))\n if (autoincrement) parts.push(sql.raw(' primary key autoincrement'))\n if (Number(column.notnull) === 1) parts.push(sql.raw(' not null'))\n if (column.dflt_value !== null && column.dflt_value !== undefined) parts.push(sql.raw(` default (${column.dflt_value})`))\n if (clauses.collation) parts.push(sql.raw(` collate ${clauses.collation}`))\n for (const check of clauses.checks) parts.push(sql.raw(` check ${check}`))\n return join(parts, '')\n}\n\n/** A foreign key read back from pragma_foreign_key_list, as a definition the grammar can write again. */\nfunction foreignKeyDefinition(key: ForeignKeyInfo): ForeignKeyDefinition {\n const definition = new ForeignKeyDefinition(key.columns, '').references(key.foreign_columns).on(key.foreign_table)\n if (key.on_delete !== 'no action') definition.onDelete(key.on_delete as ReferentialAction)\n if (key.on_update !== 'no action') definition.onUpdate(key.on_update as ReferentialAction)\n return definition\n}\n\n/** Whether SQLite enforces foreign keys on this connection (PRAGMA foreign_keys). */\nexport async function sqliteForeignKeysEnabled(db: Connection): Promise<boolean> {\n const rows = await db.select<{ foreign_keys: number }>('PRAGMA foreign_keys')\n return Number(rows[0]?.foreign_keys) === 1\n}\n\n/**\n * Throws when rows break a foreign key (SQLite's foreign_key_check), of one table or of the whole database; a hint, if\n * given, follows the message.\n */\nexport async function assertSqliteForeignKeys(db: Connection, table?: string, hint?: string): Promise<void> {\n const statement = table === undefined ? sql.raw('PRAGMA foreign_key_check') : sql`PRAGMA foreign_key_check(${sql.id(table)})`\n const rows = (await db.execute<{ table: string; rowid: number | null; parent: string }>(statement)).rows\n if (!rows.length) return\n const shown = rows.slice(0, 5).map((row) => `[${row.table}] row ${row.rowid ?? '?'} points at no row of [${row.parent}]`)\n const more = rows.length > 5 ? `; and ${rows.length - 5} more` : ''\n throw new LogicError(`Foreign key check failed: ${shown.join('; ')}${more}.${hint === undefined ? '' : ` ${hint}`}`)\n}\n\n/** The tables whose foreign keys point at `table` (itself included). */\nasync function referencingTables(db: Connection, table: string): Promise<string[]> {\n const rows = await db.select<{ name: string }>(\n `select m.name as name from sqlite_master m, pragma_foreign_key_list(m.name) f where m.type = 'table' and lower(f.\"table\") = lower(?) group by m.name order by m.name`,\n [table],\n )\n return rows.map((row) => row.name)\n}\n\n/**\n * Rebuilds a SQLite table with changed keys or columns (Laravel 11+'s compileAlter): a new table from the live\n * definition, the step's changed columns and its commands, the rows copied, the old table dropped, the new one\n * renamed, then its indexes, unique constraints, triggers and auto-increment sequence restored. Afterwards the table\n * and every table that references it are checked: rows that break a foreign key, or a key that no longer matches the\n * referenced columns, throw, and the rebuild is rolled back.\n *\n * Dropping a table while SQLite enforces foreign keys runs the ON DELETE actions of every table that references it, and\n * SQLite ignores `PRAGMA foreign_keys` inside a transaction. So outside a transaction the rebuild turns foreign keys off\n * around itself; inside one (foreign keys on) it refuses a table that another table, or itself, references.\n */\nexport async function rebuildSqliteTable(db: Connection, grammar: SqliteSchemaGrammar, step: TableRebuild): Promise<void> {\n const enabled = await sqliteForeignKeysEnabled(db)\n if (enabled && db.transactionLevel() === 0) {\n await db.statement('PRAGMA foreign_keys = OFF')\n try {\n await db.transaction(() => rebuild(db, grammar, step))\n } finally {\n await db.statement('PRAGMA foreign_keys = ON')\n }\n return\n }\n if (enabled) {\n const referencing = await referencingTables(db, step.table)\n if (referencing.length) {\n const names = referencing.map((name) => `[${name}]`).join(', ')\n throw new LogicError(\n `SQLite can't rebuild [${step.table}] inside a transaction while foreign keys are on: ${names} ${referencing.length === 1 ? 'references' : 'reference'} it, ` +\n 'and dropping the old table would run their ON DELETE actions. Run the change outside the transaction, or with foreign keys off ' +\n '(the migrator turns them off around a migration that runs in a transaction).',\n )\n }\n }\n await db.transaction(() => rebuild(db, grammar, step))\n}\n\nasync function rebuild(db: Connection, grammar: SqliteSchemaGrammar, step: TableRebuild): Promise<void> {\n const { table } = step\n const [master] = await db.select<{ sql: string }>(\"select sql from sqlite_master where type = 'table' and name = ?\", [table])\n if (!master) throw new LogicError(`Table [${table}] doesn't exist.`)\n const columns = await db.select<LiveColumn>('select name, type, \"notnull\", dflt_value, pk, hidden from pragma_table_xinfo(?) order by cid', [table])\n if (columns.some((column) => Number(column.hidden) !== 0)) {\n throw new LogicError(`SQLite can't rebuild [${table}]: it has generated or hidden columns.`)\n }\n const { definitions, options } = splitCreateTable(master.sql)\n const declared = new Map<string, string>()\n for (const definition of definitions) {\n const name = definedColumn(definition)\n if (name !== undefined) declared.set(lower(name), definition)\n }\n const keyColumns = columns.filter((column) => Number(column.pk) > 0).sort((a, b) => Number(a.pk) - Number(b.pk))\n let autoincrement = keyColumns.length === 1 && columnClauses(declared.get(lower(keyColumns[0]!.name)) ?? '').autoincrement\n ? keyColumns[0]!.name\n : undefined\n let primary = keyColumns.map((column) => column.name)\n const foreign = grammar.normalizeForeignKeys((await db.execute<Record<string, unknown>>(grammar.compileForeignKeys(table))).rows).map(foreignKeyDefinition)\n\n for (const change of step.changes) {\n if (!columns.some((column) => lower(column.name) === lower(change.name))) throw new LogicError(`[${table}] has no column [${change.name}] to change.`)\n if (change.attributes.autoIncrement) {\n autoincrement = change.name\n primary = [change.name]\n } else if (autoincrement !== undefined && lower(autoincrement) === lower(change.name)) {\n autoincrement = undefined\n }\n }\n const changes = new Map(step.changes.map((change) => [lower(change.name), change]))\n\n for (const command of step.commands) {\n if (command.name === 'primary') {\n if (autoincrement !== undefined) {\n throw new LogicError(`[${table}] already has an auto-increment primary key [${autoincrement}]: drop it first with dropPrimary().`)\n }\n primary = [...command.columns]\n } else if (command.name === 'dropPrimary') {\n primary = []\n autoincrement = undefined\n } else if (command.name === 'foreign') {\n foreign.push(command.foreign)\n } else if (command.name === 'dropForeign') {\n const columnsOf = command.columns ?? []\n const index = foreign.findIndex((key) => sameColumns(key.columns, columnsOf))\n if (index === -1) throw new LogicError(`[${table}] has no foreign key on [${columnsOf.join(', ')}].`)\n foreign.splice(index, 1)\n }\n }\n\n const parts = columns.map((column) => {\n const change = changes.get(lower(column.name))\n return change ? grammar.columnDefinition(change) : renderColumn(column, declared.get(lower(column.name)), column.name === autoincrement)\n })\n if (autoincrement === undefined && primary.length) parts.push(sql`primary key (${columnList(primary)})`)\n for (const key of foreign) parts.push(grammar.compileForeignKeyConstraint(key))\n for (const definition of definitions) if (isTableCheck(definition)) parts.push(sql.raw(definition))\n\n const indexes = await db.select<{ sql: string }>(\"select sql from sqlite_master where type = 'index' and tbl_name = ? and sql is not null\", [table])\n const uniques = await db.select<{ columns: string }>(\n \"select group_concat(col) as columns from (select il.name as name, ii.name as col from pragma_index_list(?) il, pragma_index_info(il.name) ii where il.origin = 'u' order by il.seq, ii.seqno) group by name\",\n [table],\n )\n const triggers = await db.select<{ sql: string }>(\"select sql from sqlite_master where type = 'trigger' and tbl_name = ?\", [table])\n const hasSequence = (await db.select(\"select name from sqlite_master where type = 'table' and name = 'sqlite_sequence'\")).length > 0\n const sequence = hasSequence ? (await db.select<{ seq: number }>('select seq from sqlite_sequence where name = ?', [table]))[0]?.seq : undefined\n\n const temp = `__temp__${table}`\n const names = columns.map((column) => sql.id(column.name))\n const statements: Sql[] = [\n sql`create table ${sql.id(temp)} (${join(parts)})${sql.raw(options)}`,\n sql`insert into ${sql.id(temp)} (${join(names)}) select ${join(names)} from ${sql.id(table)}`,\n sql`drop table ${sql.id(table)}`,\n sql`alter table ${sql.id(temp)} rename to ${sql.id(table)}`,\n ...indexes.map((index) => sql.raw(index.sql)),\n ...uniques.map(({ columns: list }) => {\n const unique = list.split(',')\n return sql`create unique index ${sql.id(`${table}_${unique.join('_')}_unique`.toLowerCase())} on ${sql.id(table)} (${columnList(unique)})`\n }),\n ...triggers.map((trigger) => sql.raw(trigger.sql)),\n ]\n for (const statement of statements) await db.execute(statement)\n if (autoincrement !== undefined && sequence !== undefined) await restoreSequence(db, table, Number(sequence))\n await assertSqliteForeignKeys(db, table)\n for (const child of await referencingTables(db, table)) if (lower(child) !== lower(table)) await assertSqliteForeignKeys(db, child)\n}\n\n/** Keeps the auto-increment high-water mark: ids of deleted rows are never reused, as before the rebuild. */\nasync function restoreSequence(db: Connection, table: string, sequence: number): Promise<void> {\n const [current] = await db.select<{ seq: number }>('select seq from sqlite_sequence where name = ?', [table])\n if (!current) await db.statement('insert into sqlite_sequence (name, seq) values (?, ?)', [table, sequence])\n else if (Number(current.seq) < sequence) await db.statement('update sqlite_sequence set seq = ? where name = ?', [sequence, table])\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport type { DatabaseManager as DatabaseManagerContract, DriverName, Row } from '@orieljs/contracts'\nimport type { ConnectionConfig } from './Connectors/dialect'\nimport { Connection, type LoggedQuery } from './Connection'\nimport { DatabaseConfigError } from './errors'\nimport type { Builder } from './Query/Builder'\nimport { Expression } from './Query/Expression'\nimport { SchemaBuilder } from './Schema/Builder'\n\n/** `config('database')`, in Laravel's config/database.php shape. */\nexport interface DatabaseConfig {\n default: string\n connections: Record<string, ConnectionConfig>\n /** Laravel 11: { table: 'migrations' }. A plain string (older Laravel) is accepted too. */\n migrations?: { table?: string } | string\n}\n\n/**\n * The DatabaseManager contract: named connections from config('database'), created on first use and cached.\n * Everything a connection does is also available here and runs on the default connection, as with Laravel's DB facade.\n * Named DatabaseManagerImpl so it never shadows the DatabaseManager token when both are re-exported.\n */\nexport class DatabaseManagerImpl implements DatabaseManagerContract {\n private readonly connections = new Map<string, Connection>()\n private defaultName: string | undefined\n /** usingConnection()'s name, for its own async context only: requests running beside it keep theirs. */\n private readonly using = new AsyncLocalStorage<string>()\n\n /** Pass the config, or a function that reads it (the provider reads config('database') lazily). */\n constructor(private readonly config: DatabaseConfig | (() => DatabaseConfig)) {}\n\n private settings(): DatabaseConfig {\n return typeof this.config === 'function' ? this.config() : this.config\n }\n\n /** A connection by name (default: config('database.default')). */\n connection(name?: string): Connection {\n const key = name ?? this.getDefaultConnection()\n let connection = this.connections.get(key)\n if (!connection) {\n const config = this.settings().connections[key]\n if (!config) throw new DatabaseConfigError(`Database connection [${key}] not configured.`)\n connection = new Connection(key, config)\n this.connections.set(key, connection)\n }\n return connection\n }\n\n getDefaultConnection(): string {\n return this.using.getStore() ?? this.defaultName ?? this.settings().default\n }\n\n /** Overrides config('database.default'); undefined clears the override. */\n setDefaultConnection(name: string | undefined): void {\n this.defaultName = name\n }\n\n /**\n * Runs `callback` with `name` as the default connection (Laravel's usingConnection()), for the callback's own async\n * context only: other requests running meanwhile keep their default. Without a name, just runs it.\n */\n async usingConnection<T>(name: string | undefined, callback: () => Promise<T>): Promise<T> {\n if (!name) return callback()\n return this.using.run(name, callback)\n }\n\n /** The connections opened so far. */\n getConnections(): Record<string, Connection> {\n return Object.fromEntries(this.connections)\n }\n\n /** The migrations table name (config('database.migrations.table'), default 'migrations'). */\n migrationsTable(): string {\n const migrations = this.settings().migrations\n return (typeof migrations === 'string' ? migrations : migrations?.table) ?? 'migrations'\n }\n\n /** Closes a connection's pool and forgets it; the next connection(name) opens a new one. */\n async disconnect(name?: string): Promise<void> {\n const key = name ?? this.getDefaultConnection()\n const connection = this.connections.get(key)\n this.connections.delete(key)\n await connection?.disconnect()\n }\n\n /** Laravel's purge(): the same as disconnect() here. */\n purge(name?: string): Promise<void> {\n return this.disconnect(name)\n }\n\n /** Closes every open connection (app shutdown, the end of a test). */\n async disconnectAll(): Promise<void> {\n const open = [...this.connections.values()]\n this.connections.clear()\n await Promise.all(open.map((connection) => connection.disconnect()))\n }\n\n /** The default connection's schema builder; Schema.connection(name) switches connections through this manager. */\n getSchemaBuilder(): SchemaBuilder {\n return new SchemaBuilder(this.connection(), (name) => this.connection(name))\n }\n\n /** A raw SQL fragment: DB.raw('count(*) as total'). */\n raw(value: string, bindings: readonly unknown[] = []): Expression {\n return new Expression(value, bindings)\n }\n\n // ---------------------------------------------------------------- the default connection\n\n getName(): string {\n return this.connection().getName()\n }\n\n getDriverName(): DriverName {\n return this.connection().getDriverName()\n }\n\n kysely(): ReturnType<Connection['kysely']> {\n return this.connection().kysely()\n }\n\n table<T = Row>(table: string | Expression): Builder<T> {\n return this.connection().table<T>(table)\n }\n\n query<T = Row>(): Builder<T> {\n return this.connection().query<T>()\n }\n\n select<T = Row>(query: string, bindings?: readonly unknown[]): Promise<T[]> {\n return this.connection().select<T>(query, bindings)\n }\n\n /** The first row of a raw select, or undefined. */\n async selectOne<T = Row>(query: string, bindings?: readonly unknown[]): Promise<T | undefined> {\n return (await this.connection().select<T>(query, bindings))[0]\n }\n\n /** Raw insert. Returns true, like Laravel's DB::insert(). */\n async insert(query: string, bindings?: readonly unknown[]): Promise<boolean> {\n await this.connection().statement(query, bindings)\n return true\n }\n\n /** Raw update; returns the number of affected rows. */\n update(query: string, bindings?: readonly unknown[]): Promise<number> {\n return this.connection().affectingStatement(query, bindings)\n }\n\n /** Raw delete; returns the number of affected rows. */\n delete(query: string, bindings?: readonly unknown[]): Promise<number> {\n return this.connection().affectingStatement(query, bindings)\n }\n\n statement(query: string, bindings?: readonly unknown[]): Promise<void> {\n return this.connection().statement(query, bindings)\n }\n\n affectingStatement(query: string, bindings?: readonly unknown[]): Promise<number> {\n return this.connection().affectingStatement(query, bindings)\n }\n\n transaction<R>(fn: (connection: Connection) => Promise<R>): Promise<R> {\n return this.connection().transaction(fn)\n }\n\n beginTransaction(): Promise<void> {\n return this.connection().beginTransaction()\n }\n\n commit(): Promise<void> {\n return this.connection().commit()\n }\n\n rollBack(): Promise<void> {\n return this.connection().rollBack()\n }\n\n transactionLevel(): number {\n return this.connection().transactionLevel()\n }\n\n enableQueryLog(): void {\n this.connection().enableQueryLog()\n }\n\n disableQueryLog(): void {\n this.connection().disableQueryLog()\n }\n\n getQueryLog(): LoggedQuery[] {\n return this.connection().getQueryLog()\n }\n\n flushQueryLog(): void {\n this.connection().flushQueryLog()\n }\n}\n","import { DatabaseManager, token, type Token } from '@orieljs/contracts'\nimport { facade } from '@orieljs/support'\nimport type { DatabaseManagerImpl } from './DatabaseManager'\nimport { raw } from './Query/Expression'\nimport type { SchemaBuilder } from './Schema/Builder'\n\n/**\n * The DB facade: DB.table('users').get(), DB.transaction(fn), DB.connection('pgsql'), DB.kysely().\n * DB.raw() works without an application (it only builds an Expression).\n */\nexport const DB = facade(DatabaseManager as unknown as Token<DatabaseManagerImpl>, { raw } as { raw: typeof raw })\n\n/** The Schema facade's binding: the default connection's SchemaBuilder (DatabaseServiceProvider binds it). */\nexport const SchemaBuilderToken = token<SchemaBuilder>('Database.SchemaBuilder')\n\n/** The Schema facade: Schema.create('posts', (t) => { … }), Schema.table(…), Schema.dropIfExists(…). */\nexport const Schema = facade(SchemaBuilderToken)\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport { DatabaseManager, Hasher, type ModelInstance, type Row } from '@orieljs/contracts'\nimport { Collection, type LazyCollection } from '@orieljs/collections'\nimport { currentContainer, inject } from '@orieljs/container'\nimport { Str } from '@orieljs/support'\nimport { Connection } from '../Connection'\nimport { DatabaseConfigError, LogicError, MassAssignmentError, RelationNotFoundError, RelationNotLoadedError } from '../errors'\nimport type { CursorPaginator, Cursor } from '../Pagination/CursorPaginator'\nimport type { LengthAwarePaginator } from '../Pagination/LengthAwarePaginator'\nimport type { Paginator } from '../Pagination/Paginator'\nimport type { DateWhereArgs, Direction, Truthy } from '../Query/Builder'\nimport type { Expression } from '../Query/Expression'\nimport { Builder, type EagerLoadSpec, type RelationConstraint } from './Builder'\nimport { castGet, castSet, isEquivalent, isHashedCast, isJsonCast, type CastDefinition } from './casts'\nimport { EloquentCollection } from './Collection'\nimport { Factory, type Many, type State } from './Factories/Factory'\nimport {\n eventDispatcher, MODEL_EVENTS, modelEventName, modelEventsMuted, requireEventDispatcher, withoutModelEvents,\n type ModelEvent, type ModelListener,\n} from './events'\nimport { BelongsTo } from './Relations/BelongsTo'\nimport { BelongsToMany } from './Relations/BelongsToMany'\nimport { HasMany } from './Relations/HasMany'\nimport { HasManyThrough } from './Relations/HasManyThrough'\nimport { HasOne } from './Relations/HasOne'\nimport { MorphMany } from './Relations/MorphMany'\nimport { MorphOne } from './Relations/MorphOne'\nimport { MorphTo } from './Relations/MorphTo'\nimport { getMorphAlias, rememberModelClass, resolveMorphClass, setModelBaseClass } from './Relations/morphMap'\nimport { Relation } from './Relations/Relation'\nimport type { GlobalScope, Scope, ScopeCallback } from './Scope'\nimport { SoftDeletingScope } from './SoftDeletingScope'\nimport type { Column, ModelBuilder, RelationNames, RelationValue, Scopes, WhereArgs } from './types'\n\ntype AnyFunction = (...args: unknown[]) => unknown\n\n/**\n * Every model instance is a Proxy. Real members (fields, methods, getters, config such as `fillable`) are read and\n * written normally; any other property is an attribute: `post.title` → getAttribute('title') (accessors, casts),\n * `post.title = 'x'` → setAttribute('title', 'x') (mutators, casts).\n */\nconst handler: ProxyHandler<Model> = {\n get(target, key, receiver) {\n if (typeof key === 'symbol' || key in target) {\n const value: unknown = Reflect.get(target, key, receiver)\n if (relationGuard.enabled && typeof key === 'string' && typeof value === 'function' && !(key in Model.prototype) && !Object.hasOwn(target, key)) {\n return guardedMethod(target.constructor as typeof Model, key, value as AnyFunction)\n }\n return value\n }\n return (receiver as Model).getAttribute(key)\n },\n set(target, key, value, receiver) {\n if (typeof key === 'symbol' || key in target) return Reflect.set(target, key, value, receiver)\n ;(receiver as Model).setAttribute(key, value)\n return true\n },\n}\n\n/**\n * The relation guard: `post.author` is the relation method, so `post.author.name` is the function's name ('author')\n * and `post.author.email` is undefined, with no error. While the guard is on (outside production), a model's own\n * methods are handed out wrapped, and reading `name`, `length` or a property a function doesn't have from one warns\n * once per class, method and property. Calling, binding and comparing the methods are untouched.\n */\nconst relationGuard = { enabled: true, warned: new Set<string>() }\nconst guardedMethods = new WeakMap<AnyFunction, Map<typeof Model, AnyFunction>>()\n\nfunction guardedMethod(cls: typeof Model, key: string, method: AnyFunction): AnyFunction {\n let byClass = guardedMethods.get(method)\n if (!byClass) guardedMethods.set(method, (byClass = new Map()))\n let guarded = byClass.get(cls)\n if (!guarded) {\n guarded = new Proxy(method, {\n get(target, property, receiver) {\n if (typeof property === 'string' && (property === 'name' || property === 'length' || !(property in target))) {\n warnRelationPropertyAccess(cls.name, key, property)\n }\n // bind() reads name and length, and a proxied function's toString() prints [native code]: use the method itself.\n if (property === 'bind') return (thisArg: unknown, ...args: unknown[]) => Function.prototype.bind.call(target, thisArg, ...args)\n if (property === 'toString') return () => Function.prototype.toString.call(target)\n return Reflect.get(target, property, receiver)\n },\n })\n byClass.set(cls, guarded)\n }\n return guarded\n}\n\nfunction warnRelationPropertyAccess(model: string, method: string, property: string): void {\n const id = `${model}.${method}.${property}`\n if (relationGuard.warned.has(id)) return\n relationGuard.warned.add(id)\n console.warn(\n `[${model}] ${method} is a method, so ${method}.${property} reads the function, not an attribute of a related model. ` +\n `Read a loaded relation with getRelation('${method}') (after with('${method}') or load('${method}')), or query it with ` +\n `await ${method}().first().`,\n )\n}\n\nconst bootedModels = new Set<typeof Model>()\nconst prototypes = new Map<typeof Model, Model>()\nconst unguardedGlobally = { value: false }\n/** Model classes whose default withCount is being added (breaks recursion through their relations). */\nconst addingDefaultCounts = new Set<typeof Model>()\n/** The only keys a guarded-list model accepts from fill(): a plain column name, no spaces, dots or quoting tricks. */\nconst PLAIN_COLUMN = /^[A-Za-z_][A-Za-z0-9_]*$/\nconst unguardedScope = new AsyncLocalStorage<boolean>()\nconst globalScopes = new Map<typeof Model, Map<string, GlobalScope>>()\nlet anonymousScopes = 0\n\ntype Instance<C extends typeof Model> = InstanceType<C>\ntype ScopeClass = abstract new (...args: never[]) => unknown\n\n/** Post.published() for every static scopePublished() (installed when the class boots). */\nfunction installScopeProxies(cls: typeof Model): void {\n for (let current: unknown = cls; current && current !== Model; current = Object.getPrototypeOf(current)) {\n for (const key of Object.getOwnPropertyNames(current)) {\n if (!key.startsWith('scope') || key.length <= 5) continue\n if (typeof Reflect.get(current as object, key) !== 'function') continue\n const name = Str.lcfirst(key.slice(5))\n if (name in cls) continue\n Object.defineProperty(cls, name, {\n configurable: true,\n writable: true,\n value(this: typeof Model, ...args: unknown[]) {\n const query = this.query() as unknown as Record<string, (...a: unknown[]) => unknown>\n return query[name]!(...args)\n },\n })\n }\n }\n}\n\n/** A method defined on the model's class (never an attribute), e.g. getFullNameAttribute. */\nfunction methodOf(model: Model, name: string): AnyFunction | undefined {\n const value: unknown = Reflect.get(Object.getPrototypeOf(model) as object, name)\n return typeof value === 'function' ? (value as AnyFunction) : undefined\n}\n\n/** The application's Hasher, for the hashed cast. */\nfunction hasher(): Hasher {\n const container = currentContainer()\n if (!container?.bound(Hasher)) throw new LogicError('The hashed cast needs a Hasher: register HashingServiceProvider (or bind the Hasher contract).')\n return container.make(Hasher)\n}\n\n/** The models whose toArray() is running: a model met again inside it (a chaperone() cycle) gives its attributes only. */\nconst serializing = new WeakSet<Model>()\n\n/** Laravel's date serialization: ISO 8601 in UTC with microseconds (2026-01-02T03:04:05.000000Z). */\nexport function serializeDate(date: Date): string {\n return date.toISOString().replace(/\\.(\\d{3})Z$/, '.$1000Z')\n}\n\n/**\n * Eloquent's Model: an Active Record over one table.\n *\n * Config lives in instance fields, as in Laravel: `protected fillable = ['title']`, `protected casts = {…}`,\n * `protected hidden = ['password']`, `protected table = 'posts'`. Attribute columns are never declared as class\n * fields (they would shadow the Proxy); their types come from `oriel model:types`, or from `declare title: string`.\n * `new Post()` takes no arguments: use Post.make(attrs), Post.create(attrs) or new Post().fill(attrs).\n */\nexport class Model implements ModelInstance {\n static CREATED_AT: string | null = 'created_at'\n static UPDATED_AT: string | null = 'updated_at'\n static DELETED_AT = 'deleted_at'\n\n // ---------------------------------------------------------------- config (override in subclasses)\n\n /** The table (default: the snake_case plural of the class name: BlogPost → blog_posts). */\n protected table: string | undefined = undefined\n protected primaryKey = 'id'\n protected keyType: 'int' | 'string' = 'int'\n incrementing = true\n /** Attributes that fill()/create() may set. */\n protected fillable: string[] = []\n /** Attributes fill() never sets. ['*'] (the default) guards everything that isn't fillable. */\n protected guarded: string[] = ['*']\n protected casts: Readonly<Record<string, CastDefinition>> = {}\n /** Left out of toArray()/toJSON(). */\n protected hidden: string[] = []\n /** When non-empty, only these are in toArray()/toJSON(). */\n protected visible: string[] = []\n /** Accessor-only attributes added to toArray()/toJSON(). */\n protected appends: string[] = []\n timestamps = true\n /** Turns on soft deletes (Laravel's `use SoftDeletes`): deleted_at instead of a real delete. */\n protected softDeletes = false\n /** The connection name (default: config('database.default')). */\n protected connection: string | undefined = undefined\n protected perPage = 15\n /** Relations every query of this model eager loads (Laravel's $with). */\n protected with: string[] = []\n /** Relation counts every query of this model adds (Laravel's $withCount). */\n protected withCount: string[] = []\n\n // ---------------------------------------------------------------- state\n\n exists = false\n wasRecentlyCreated = false\n protected forceDeleting = false\n protected attributes: Row = {}\n protected original: Row = {}\n protected changes: Row = {}\n protected relations: Record<string, unknown> = {}\n /** Decoded json/array/object/collection values, so in-place changes are seen by save(). */\n protected castCache = new Map<string, { raw: unknown; value: unknown }>()\n /** Attributes with the hashed cast that were assigned a value since the last save; save() hashes them. */\n protected pendingHashes = new Set<string>()\n\n constructor() {\n ;(this.constructor as typeof Model).bootIfNotBooted()\n return new Proxy(this, handler)\n }\n\n // ---------------------------------------------------------------- booting\n\n /** Runs booting()/booted() once per class, the first time the class is instantiated. */\n static bootIfNotBooted(): void {\n if (bootedModels.has(this)) return\n bootedModels.add(this)\n rememberModelClass(this)\n this.booting()\n this.boot()\n this.booted()\n }\n\n /**\n * Framework hook: installs the static scope proxies (Post.published()) and, with `softDeletes = true`, the soft\n * delete scope. Overrides must call super.boot().\n */\n static boot(): void {\n installScopeProxies(this)\n if (this.prototypeInstance().usesSoftDeletes()) this.addGlobalScope(new SoftDeletingScope())\n }\n\n /** Runs before boot(). */\n static booting(): void {}\n\n /** Register global scopes and model event listeners here: static booted() { this.addGlobalScope(…) }. */\n static booted(): void {}\n\n /**\n * Forgets which classes are booted, and their global scopes (Laravel's clearBootedModels()), so the next use boots\n * them again: booted() re-registers its scopes and event listeners against the current application. Every new\n * application does this (DatabaseServiceProvider.register()).\n */\n static clearBootedModels(): void {\n bootedModels.clear()\n prototypes.clear()\n globalScopes.clear()\n }\n\n /** One cached instance per class, used by static methods to read config (table, key, casts, …). */\n static prototypeInstance<M extends Model>(this: new () => M): M {\n const cls = this as unknown as typeof Model\n let instance = prototypes.get(cls)\n if (!instance) {\n instance = new cls()\n prototypes.set(cls, instance)\n }\n return instance as M\n }\n\n /** A new, unsaved model filled with attributes (mass assignment rules apply). */\n static make<M extends Model>(this: new () => M, attributes: Row = {}): M {\n return new this().fill(attributes)\n }\n\n // ---------------------------------------------------------------- global scopes\n\n /**\n * Adds a global scope to every query of this class: addGlobalScope('published', q => …),\n * addGlobalScope(new ActiveScope()) (named after its class) or addGlobalScope(q => …).\n */\n static addGlobalScope(scope: Scope | ScopeCallback): string\n static addGlobalScope(name: string, scope: GlobalScope): string\n static addGlobalScope(nameOrScope: string | GlobalScope, implementation?: GlobalScope): string {\n let name: string\n let scope: GlobalScope\n if (typeof nameOrScope === 'string') {\n name = nameOrScope\n scope = implementation!\n } else {\n scope = nameOrScope\n name = typeof scope === 'function' ? `closure#${++anonymousScopes}` : scope.constructor.name\n }\n let scopes = globalScopes.get(this)\n if (!scopes) globalScopes.set(this, (scopes = new Map()))\n scopes.set(name, scope)\n return name\n }\n\n static hasGlobalScope(scope: string | ScopeClass): boolean {\n return globalScopes.get(this)?.has(typeof scope === 'string' ? scope : scope.name) ?? false\n }\n\n static getGlobalScopes(): Map<string, GlobalScope> {\n return new Map(globalScopes.get(this))\n }\n\n // ---------------------------------------------------------------- model events and observers\n\n /** Registers a listener for one of this model's events ('eloquent.<event>: <Class>'). Needs an EventDispatcher. */\n static registerModelEvent<C extends typeof Model>(this: C, event: ModelEvent, callback: ModelListener<InstanceType<C>>): void {\n requireEventDispatcher(this.name).listen(modelEventName(event, this.name), (model: unknown) => callback(model as InstanceType<C>))\n }\n\n static retrieved<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('retrieved', callback)\n }\n\n static creating<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('creating', callback)\n }\n\n static created<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('created', callback)\n }\n\n static updating<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('updating', callback)\n }\n\n static updated<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('updated', callback)\n }\n\n static saving<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('saving', callback)\n }\n\n static saved<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('saved', callback)\n }\n\n static deleting<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('deleting', callback)\n }\n\n static deleted<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('deleted', callback)\n }\n\n static restoring<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('restoring', callback)\n }\n\n static restored<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('restored', callback)\n }\n\n static forceDeleting<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('forceDeleting', callback)\n }\n\n static forceDeleted<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('forceDeleted', callback)\n }\n\n /**\n * Registers observers: every method named after a model event (created, updating, …) becomes a listener.\n * Observer classes are resolved from the container.\n */\n static observe(...observers: Array<object | (new () => object)>): void {\n const dispatcher = requireEventDispatcher(this.name)\n for (const entry of observers) {\n const observer = (typeof entry === 'function' ? (currentContainer()?.make(entry as new () => object) ?? new (entry as new () => object)()) : entry) as Record<string, unknown>\n for (const event of MODEL_EVENTS) {\n const method = observer[event]\n if (typeof method !== 'function') continue\n dispatcher.listen(modelEventName(event, this.name), (model: unknown) => (method as (m: unknown) => unknown).call(observer, model))\n }\n }\n }\n\n /**\n * Turns the relation guard on or off: while it is on, reading a property of a relation method as if it were the\n * related model (`post.author.name`) warns once with how to read the relation. DatabaseServiceProvider turns it on\n * outside production. Turning it on again forgets which warnings were given.\n */\n static warnOnRelationPropertyAccess(enabled = true): void {\n relationGuard.enabled = enabled\n if (enabled) relationGuard.warned.clear()\n }\n\n static warnsOnRelationPropertyAccess(): boolean {\n return relationGuard.enabled\n }\n\n /** Runs fn with model events off, for this async context only. */\n static withoutEvents<R>(fn: () => R): R {\n return withoutModelEvents(fn)\n }\n\n // ---------------------------------------------------------------- static query API (Post.where(…), Post.find(…))\n\n /** A new query of this model, with its global scopes. */\n static query<C extends typeof Model>(this: C): ModelBuilder<C> {\n return (this as typeof Model).prototypeInstance().newQuery() as unknown as ModelBuilder<C>\n }\n\n static where<C extends typeof Model>(this: C, ...args: WhereArgs<Instance<C>, ModelBuilder<C>>): ModelBuilder<C> {\n const query = this.query()\n return Reflect.apply(query.where, query, args) as ModelBuilder<C>\n }\n\n /** Post.when(request.query('q'), (query, q) => query.whereLike('title', `%${q}%`)): a new query, then when(). */\n static when<C extends typeof Model, V>(this: C, value: (query: ModelBuilder<C>) => V, callback: (query: ModelBuilder<C>, value: Truthy<V>) => unknown, otherwise?: (query: ModelBuilder<C>, value: V) => unknown): ModelBuilder<C>\n static when<C extends typeof Model, V>(this: C, value: V, callback: (query: ModelBuilder<C>, value: Truthy<V>) => unknown, otherwise?: (query: ModelBuilder<C>, value: V) => unknown): ModelBuilder<C>\n static when<C extends typeof Model>(this: C, ...args: unknown[]): ModelBuilder<C> {\n const query = this.query()\n return Reflect.apply(query.when, query, args) as ModelBuilder<C>\n }\n\n /** A new query, then unless(): the callback runs when the value is falsy. */\n static unless<C extends typeof Model, V>(this: C, value: (query: ModelBuilder<C>) => V, callback: (query: ModelBuilder<C>, value: V) => unknown, otherwise?: (query: ModelBuilder<C>, value: Truthy<V>) => unknown): ModelBuilder<C>\n static unless<C extends typeof Model, V>(this: C, value: V, callback: (query: ModelBuilder<C>, value: V) => unknown, otherwise?: (query: ModelBuilder<C>, value: Truthy<V>) => unknown): ModelBuilder<C>\n static unless<C extends typeof Model>(this: C, ...args: unknown[]): ModelBuilder<C> {\n const query = this.query()\n return Reflect.apply(query.unless, query, args) as ModelBuilder<C>\n }\n\n static whereKey<C extends typeof Model>(this: C, id: unknown): ModelBuilder<C> {\n return this.query().whereKey(id)\n }\n\n static whereIn<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, values: readonly unknown[]): ModelBuilder<C> {\n return this.query().whereIn(column, values)\n }\n\n static whereNotIn<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, values: readonly unknown[]): ModelBuilder<C> {\n return this.query().whereNotIn(column, values)\n }\n\n static whereNull<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression): ModelBuilder<C> {\n return this.query().whereNull(column)\n }\n\n static whereNotNull<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression): ModelBuilder<C> {\n return this.query().whereNotNull(column)\n }\n\n static whereBetween<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, values: readonly [unknown, unknown]): ModelBuilder<C> {\n return this.query().whereBetween(column, values)\n }\n\n /** Post.whereLike('title', `%${term}%`): case-insensitive unless caseSensitive (see the query builder's whereLike()). */\n static whereLike<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, value: string, caseSensitive = false): ModelBuilder<C> {\n return this.query().whereLike(column, value, caseSensitive)\n }\n\n static whereNotLike<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, value: string, caseSensitive = false): ModelBuilder<C> {\n return this.query().whereNotLike(column, value, caseSensitive)\n }\n\n /** Post.whereDate('published_at', '2026-01-05'), Post.whereDate('published_at', '<', new Date()). */\n static whereDate<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, ...args: DateWhereArgs): ModelBuilder<C> {\n return this.query().whereDate(column, ...args)\n }\n\n static whereTime<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, ...args: DateWhereArgs): ModelBuilder<C> {\n return this.query().whereTime(column, ...args)\n }\n\n static whereDay<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, ...args: DateWhereArgs): ModelBuilder<C> {\n return this.query().whereDay(column, ...args)\n }\n\n static whereMonth<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, ...args: DateWhereArgs): ModelBuilder<C> {\n return this.query().whereMonth(column, ...args)\n }\n\n static whereYear<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, ...args: DateWhereArgs): ModelBuilder<C> {\n return this.query().whereYear(column, ...args)\n }\n\n static whereColumn<C extends typeof Model>(this: C, first: Column<Instance<C>>, operatorOrSecond: string, second?: Column<Instance<C>>): ModelBuilder<C> {\n return this.query().whereColumn(first, operatorOrSecond, second)\n }\n\n static whereRaw<C extends typeof Model>(this: C, sql: string, bindings: readonly unknown[] = []): ModelBuilder<C> {\n return this.query().whereRaw(sql, bindings)\n }\n\n static select<C extends typeof Model>(this: C, ...columns: Array<Column<Instance<C>> | Expression>): ModelBuilder<C> {\n return this.query().select(...columns)\n }\n\n static orderBy<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, direction: Direction = 'asc'): ModelBuilder<C> {\n return this.query().orderBy(column, direction)\n }\n\n static latest<C extends typeof Model>(this: C, column?: Column<Instance<C>>): ModelBuilder<C> {\n return this.query().latest(column)\n }\n\n static oldest<C extends typeof Model>(this: C, column?: Column<Instance<C>>): ModelBuilder<C> {\n return this.query().oldest(column)\n }\n\n static inRandomOrder<C extends typeof Model>(this: C): ModelBuilder<C> {\n return this.query().inRandomOrder()\n }\n\n static limit<C extends typeof Model>(this: C, count: number): ModelBuilder<C> {\n return this.query().limit(count)\n }\n\n static take<C extends typeof Model>(this: C, count: number): ModelBuilder<C> {\n return this.query().take(count)\n }\n\n static withoutGlobalScope<C extends typeof Model>(this: C, scope: string | ScopeClass): ModelBuilder<C> {\n return this.query().withoutGlobalScope(scope)\n }\n\n static withoutGlobalScopes<C extends typeof Model>(this: C, scopes?: Array<string | ScopeClass>): ModelBuilder<C> {\n return this.query().withoutGlobalScopes(scopes)\n }\n\n /** Eager loads relations: Post.with('author', 'comments.user').get(). */\n static with<C extends typeof Model>(this: C, ...relations: EagerLoadSpec[]): ModelBuilder<C> {\n return this.query().with(...relations)\n }\n\n static withCount<C extends typeof Model>(this: C, ...relations: EagerLoadSpec[]): ModelBuilder<C> {\n return this.query().withCount(...relations)\n }\n\n /** Post.withSum('orders', 'price'): adds orders_sum_price. */\n static withSum<C extends typeof Model>(this: C, relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): ModelBuilder<C> {\n return this.query().withSum(relations, column)\n }\n\n static withAvg<C extends typeof Model>(this: C, relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): ModelBuilder<C> {\n return this.query().withAvg(relations, column)\n }\n\n static withMin<C extends typeof Model>(this: C, relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): ModelBuilder<C> {\n return this.query().withMin(relations, column)\n }\n\n static withMax<C extends typeof Model>(this: C, relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): ModelBuilder<C> {\n return this.query().withMax(relations, column)\n }\n\n static withExists<C extends typeof Model>(this: C, ...relations: EagerLoadSpec[]): ModelBuilder<C> {\n return this.query().withExists(...relations)\n }\n\n static withAggregate<C extends typeof Model>(this: C, relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression, fn?: string): ModelBuilder<C> {\n return this.query().withAggregate(relations, column, fn)\n }\n\n static has<C extends typeof Model>(this: C, relation: string, operator = '>=', count = 1): ModelBuilder<C> {\n return this.query().has(relation, operator, count)\n }\n\n static whereHas<C extends typeof Model>(this: C, relation: string, callback?: RelationConstraint, operator = '>=', count = 1): ModelBuilder<C> {\n return this.query().whereHas(relation, callback, operator, count)\n }\n\n static doesntHave<C extends typeof Model>(this: C, relation: string): ModelBuilder<C> {\n return this.query().doesntHave(relation)\n }\n\n static whereDoesntHave<C extends typeof Model>(this: C, relation: string, callback?: RelationConstraint): ModelBuilder<C> {\n return this.query().whereDoesntHave(relation, callback)\n }\n\n /** Soft deletes: include trashed rows. */\n static withTrashed<C extends typeof Model>(this: C): ModelBuilder<C> {\n return this.query().withTrashed()\n }\n\n /** Soft deletes: only trashed rows. */\n static onlyTrashed<C extends typeof Model>(this: C): ModelBuilder<C> {\n return this.query().onlyTrashed()\n }\n\n static withoutTrashed<C extends typeof Model>(this: C): ModelBuilder<C> {\n return this.query().withoutTrashed()\n }\n\n static all<C extends typeof Model>(this: C): Promise<EloquentCollection<Instance<C>>> {\n return this.query().get()\n }\n\n static find<C extends typeof Model>(this: C, ids: readonly unknown[]): Promise<EloquentCollection<Instance<C>>>\n static find<C extends typeof Model>(this: C, id: unknown): Promise<Instance<C> | undefined>\n static find<C extends typeof Model>(this: C, id: unknown): Promise<Instance<C> | undefined | EloquentCollection<Instance<C>>> {\n return this.query().find(id)\n }\n\n static findOrFail<C extends typeof Model>(this: C, ids: readonly unknown[]): Promise<EloquentCollection<Instance<C>>>\n static findOrFail<C extends typeof Model>(this: C, id: unknown): Promise<Instance<C>>\n static findOrFail<C extends typeof Model>(this: C, id: unknown): Promise<Instance<C> | EloquentCollection<Instance<C>>> {\n return this.query().findOrFail(id)\n }\n\n static findMany<C extends typeof Model>(this: C, ids: readonly unknown[]): Promise<EloquentCollection<Instance<C>>> {\n return this.query().findMany(ids)\n }\n\n static first<C extends typeof Model>(this: C): Promise<Instance<C> | undefined> {\n return this.query().first()\n }\n\n static firstOrFail<C extends typeof Model>(this: C): Promise<Instance<C>> {\n return this.query().firstOrFail()\n }\n\n static firstWhere<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, operatorOrValue: unknown, value?: unknown): Promise<Instance<C> | undefined> {\n return this.query().firstWhere(column, operatorOrValue, value)\n }\n\n static count(): Promise<number> {\n return this.query().count()\n }\n\n static exists(): Promise<boolean> {\n return this.query().exists()\n }\n\n static pluck<C extends typeof Model, V = unknown>(this: C, column: Column<Instance<C>>): Promise<Collection<V>> {\n return this.query().pluck<V>(column)\n }\n\n static paginate<C extends typeof Model>(this: C, perPage?: number, columns?: string[], pageName?: string, page?: number): Promise<LengthAwarePaginator<Instance<C>>> {\n return this.query().paginate(perPage, columns, pageName, page)\n }\n\n static simplePaginate<C extends typeof Model>(this: C, perPage?: number, columns?: string[], pageName?: string, page?: number): Promise<Paginator<Instance<C>>> {\n return this.query().simplePaginate(perPage, columns, pageName, page)\n }\n\n static cursorPaginate<C extends typeof Model>(this: C, perPage?: number, columns?: string[], cursorName?: string, cursor?: Cursor | string): Promise<CursorPaginator<Instance<C>>> {\n return this.query().cursorPaginate(perPage, columns, cursorName, cursor)\n }\n\n static chunk<C extends typeof Model>(this: C, count: number, callback: (models: EloquentCollection<Instance<C>>, page: number) => unknown): Promise<boolean> {\n return this.query().chunk(count, callback)\n }\n\n static chunkById<C extends typeof Model>(this: C, count: number, callback: (models: EloquentCollection<Instance<C>>, page: number) => unknown): Promise<boolean> {\n return this.query().chunkById(count, callback)\n }\n\n static each<C extends typeof Model>(this: C, callback: (model: Instance<C>, index: number) => unknown, count?: number): Promise<boolean> {\n return this.query().each(callback, count)\n }\n\n static lazy<C extends typeof Model>(this: C, chunkSize?: number): LazyCollection<Instance<C>> {\n return this.query().lazy(chunkSize)\n }\n\n static lazyById<C extends typeof Model>(this: C, chunkSize?: number): LazyCollection<Instance<C>> {\n return this.query().lazyById(chunkSize)\n }\n\n /** Creates and saves a model (mass assignment rules apply). */\n static create<C extends typeof Model>(this: C, attributes: Row = {}): Promise<Instance<C>> {\n return this.query().create(attributes)\n }\n\n static forceCreate<C extends typeof Model>(this: C, attributes: Row): Promise<Instance<C>> {\n return this.query().forceCreate(attributes)\n }\n\n static firstOrNew<C extends typeof Model>(this: C, attributes: Row, values: Row = {}): Promise<Instance<C>> {\n return this.query().firstOrNew(attributes, values)\n }\n\n static firstOrCreate<C extends typeof Model>(this: C, attributes: Row, values: Row = {}): Promise<Instance<C>> {\n return this.query().firstOrCreate(attributes, values)\n }\n\n static updateOrCreate<C extends typeof Model>(this: C, attributes: Row, values: Row = {}): Promise<Instance<C>> {\n return this.query().updateOrCreate(attributes, values)\n }\n\n /**\n * The model's registered factory (database/factories/<Model>Factory.ts): await User.factory().create(),\n * await User.factory(3).create(). Use UserFactory.new() to reach the factory's own state methods with their types.\n */\n static factory<C extends typeof Model>(this: C): Factory<InstanceType<C>>\n static factory<C extends typeof Model>(this: C, count: number, state?: State): Factory<InstanceType<C>> & Many\n static factory<C extends typeof Model>(this: C, count?: number, state?: State): Factory<InstanceType<C>> {\n let factory = Factory.forModel(this as unknown as new () => InstanceType<C>)\n if (count !== undefined) factory = factory.count(count)\n if (state) factory = factory.state(state)\n return factory\n }\n\n /** Deletes models by key, one by one, so model events fire. Returns how many were deleted. */\n static async destroy(...ids: Array<unknown | unknown[]>): Promise<number> {\n const keys = ids.flat()\n if (!keys.length) return 0\n let count = 0\n for (const model of await this.query().whereKey(keys).get()) if (await model.delete()) count++\n return count\n }\n\n // ---------------------------------------------------------------- mass assignment\n\n /** Disables mass assignment protection everywhere until reguard(). */\n static unguard(state = true): void {\n unguardedGlobally.value = state\n }\n\n static reguard(): void {\n unguardedGlobally.value = false\n }\n\n static isUnguarded(): boolean {\n return unguardedGlobally.value || unguardedScope.getStore() === true\n }\n\n /** Runs fn with mass assignment protection off, for this async context only (seeders, factories). */\n static unguarded<R>(fn: () => R): R {\n return unguardedScope.run(true, fn)\n }\n\n /** Sets the fillable attributes; the others are dropped, or throw MassAssignmentError on a totally guarded model. */\n fill(attributes: Row): this {\n const totallyGuarded = this.totallyGuarded()\n for (const [key, value] of Object.entries(attributes)) {\n if (this.isFillable(key)) this.setAttribute(key, value)\n else if (totallyGuarded) throw new MassAssignmentError(this.constructor.name, key)\n }\n return this\n }\n\n /** Sets attributes with no mass assignment check. Never pass it request input. */\n forceFill(attributes: Row): this {\n for (const [key, value] of Object.entries(attributes)) this.setAttribute(key, value)\n return this\n }\n\n isFillable(key: string): boolean {\n if (Model.isUnguarded()) return true\n if (this.fillable.includes(key)) return true\n if (this.fillable.length > 0 || this.isGuarded(key)) return false\n return PLAIN_COLUMN.test(key) && !key.startsWith('_')\n }\n\n /** Guarded names match case-insensitively: SQLite and MySQL column names are case-insensitive. */\n isGuarded(key: string): boolean {\n if (this.guarded.length === 0) return false\n const lower = key.toLowerCase()\n return this.guarded.some((guarded) => guarded === '*' || guarded.toLowerCase() === lower)\n }\n\n totallyGuarded(): boolean {\n return !Model.isUnguarded() && this.fillable.length === 0 && this.guarded.length === 1 && this.guarded[0] === '*'\n }\n\n getFillable(): string[] {\n return [...this.fillable]\n }\n\n getGuarded(): string[] {\n return [...this.guarded]\n }\n\n // ---------------------------------------------------------------- attributes\n\n /** An attribute through its accessor or cast; undefined when the model doesn't have it. */\n getAttribute<T = unknown>(key: string): T {\n if (!key) return undefined as T\n if (Object.hasOwn(this.attributes, key) || this.hasGetMutator(key) || this.hasCast(key)) return this.getAttributeValue(key) as T\n return undefined as T\n }\n\n /** The attribute's value after its accessor (get<Name>Attribute) or cast. */\n getAttributeValue(key: string): unknown {\n const value = this.attributes[key]\n const accessor = this.mutatorFor('get', key)\n if (accessor) return accessor.call(this, value)\n return this.castAttribute(key, value)\n }\n\n /** Sets an attribute through its mutator (set<Name>Attribute) or cast. */\n setAttribute(key: string, value: unknown): this {\n const mutator = this.mutatorFor('set', key)\n if (mutator) {\n mutator.call(this, value)\n return this\n }\n const cast = this.getCasts()[key]\n this.castCache.delete(key)\n this.attributes[key] = cast === undefined ? value : castSet(this, key, cast, value, this.attributes, this.constructor.name)\n if (isHashedCast(cast)) {\n if (value === null || value === undefined) this.pendingHashes.delete(key)\n else this.pendingHashes.add(key)\n }\n return this\n }\n\n hasGetMutator(key: string): boolean {\n return this.mutatorFor('get', key) !== undefined\n }\n\n hasSetMutator(key: string): boolean {\n return this.mutatorFor('set', key) !== undefined\n }\n\n /** Every cast, including the implied ones: the incrementing key (int) and the timestamp columns (datetime). */\n getCasts(): Record<string, CastDefinition> {\n const implied: Record<string, CastDefinition> = {}\n if (this.getIncrementing()) implied[this.getKeyName()] = this.getKeyType() === 'int' ? 'int' : 'string'\n if (this.usesTimestamps()) {\n const created = this.getCreatedAtColumn()\n const updated = this.getUpdatedAtColumn()\n if (created) implied[created] = 'datetime'\n if (updated) implied[updated] = 'datetime'\n }\n if (this.softDeletes) implied[this.getDeletedAtColumn()] = 'datetime'\n return { ...implied, ...this.casts }\n }\n\n /** Adds casts to this instance only (Laravel's mergeCasts()); withCasts() on a query does it for each result. */\n mergeCasts(casts: Readonly<Record<string, CastDefinition>>): this {\n this.casts = { ...this.casts, ...casts }\n return this\n }\n\n hasCast(key: string, types?: string[]): boolean {\n const cast = this.getCasts()[key]\n if (cast === undefined) return false\n return types === undefined || (typeof cast === 'string' && types.includes(cast))\n }\n\n /** The stored attributes, with in-place changes to json casts written back. */\n getAttributes(): Row {\n this.mergeCachedCasts()\n return { ...this.attributes }\n }\n\n /** Replaces the stored attributes as-is (no casts or mutators); sync = also make them the original. */\n setRawAttributes(attributes: Row, sync = false): this {\n this.attributes = { ...attributes }\n this.castCache.clear()\n this.pendingHashes.clear()\n if (sync) this.syncOriginal()\n return this\n }\n\n /** The original value (cast), or every original value. */\n getOriginal(): Row\n getOriginal<T = unknown>(key: string): T\n getOriginal(key?: string): unknown {\n if (key !== undefined) return this.castAttribute(key, this.original[key], false)\n return Object.fromEntries(Object.keys(this.original).map((name) => [name, this.castAttribute(name, this.original[name], false)]))\n }\n\n getRawOriginal(): Row\n getRawOriginal<T = unknown>(key: string): T\n getRawOriginal(key?: string): unknown {\n return key === undefined ? { ...this.original } : this.original[key]\n }\n\n syncOriginal(): this {\n this.original = this.getAttributes()\n return this\n }\n\n syncOriginalAttributes(...keys: string[]): this {\n const current = this.getAttributes()\n for (const key of keys) this.original[key] = current[key]\n return this\n }\n\n /** The attributes that changed since the model was loaded or saved, compared by meaning (casts), not representation. */\n getDirty(): Row {\n this.mergeCachedCasts()\n const casts = this.getCasts()\n const dirty: Row = {}\n for (const [key, value] of Object.entries(this.attributes)) {\n const unchanged = Object.hasOwn(this.original, key) &&\n isEquivalent(casts[key], value, this.original[key], this, key, this.constructor.name)\n if (!unchanged) dirty[key] = value\n }\n return dirty\n }\n\n isDirty(...keys: Array<string | string[]>): boolean {\n const dirty = this.getDirty()\n const names = keys.flat()\n return names.length ? names.some((key) => Object.hasOwn(dirty, key)) : Object.keys(dirty).length > 0\n }\n\n isClean(...keys: Array<string | string[]>): boolean {\n return !this.isDirty(...keys)\n }\n\n /** The attributes the last save() changed. */\n getChanges(): Row {\n return { ...this.changes }\n }\n\n wasChanged(...keys: Array<string | string[]>): boolean {\n const names = keys.flat()\n return names.length ? names.some((key) => Object.hasOwn(this.changes, key)) : Object.keys(this.changes).length > 0\n }\n\n syncChanges(): this {\n this.changes = this.getDirty()\n return this\n }\n\n /** The given attributes (through accessors and casts). */\n only(...keys: Array<string | string[]>): Row {\n return Object.fromEntries(keys.flat().map((key) => [key, this.getAttribute(key)]))\n }\n\n /**\n * useCache = false skips the json-cast decode cache entirely (both reading and writing it): used by getOriginal(),\n * so a decoded original never aliases the live attribute's cached (and possibly in-place-mutated) object, even\n * when their raw stored strings are equal right after load/save.\n */\n protected castAttribute(key: string, value: unknown, useCache = true): unknown {\n const cast = this.getCasts()[key]\n if (cast === undefined) return value\n if (useCache && isJsonCast(cast) && value !== null && value !== undefined) {\n const cached = this.castCache.get(key)\n if (cached && cached.raw === value) return cached.value\n const decoded = castGet(this, key, cast, value, this.attributes, this.constructor.name)\n if (value === this.attributes[key]) this.castCache.set(key, { raw: value, value: decoded })\n return decoded\n }\n return castGet(this, key, cast, value, this.attributes, this.constructor.name)\n }\n\n /** Writes json casts that were changed in place (post.meta.views++) back into the stored attributes. */\n protected mergeCachedCasts(): void {\n const casts = this.getCasts()\n for (const [key, entry] of this.castCache) {\n if (this.attributes[key] !== entry.raw) {\n this.castCache.delete(key)\n continue\n }\n const encoded = castSet(this, key, casts[key]!, entry.value, this.attributes, this.constructor.name)\n if (encoded !== entry.raw) {\n this.attributes[key] = encoded\n entry.raw = encoded\n }\n }\n }\n\n private mutatorFor(kind: 'get' | 'set', key: string): AnyFunction | undefined {\n return methodOf(this, `${kind}${Str.studly(key)}Attribute`)\n }\n\n // ---------------------------------------------------------------- keys, table and naming\n\n getKeyName(): string {\n return this.primaryKey\n }\n\n getKeyType(): 'int' | 'string' {\n return this.keyType\n }\n\n getIncrementing(): boolean {\n return this.incrementing\n }\n\n /** Whether new rows get unique string ids before `creating` (HasUuids, HasUlids). */\n usesUniqueIds(): boolean {\n return false\n }\n\n /** The columns that get a unique id (HasUuids and HasUlids: the primary key). */\n uniqueIds(): string[] {\n return []\n }\n\n /** A new unique id (HasUuids: a version 7 UUID; HasUlids: a lower-case ULID). */\n newUniqueId(): string | undefined {\n return undefined\n }\n\n /** Whether a value has the shape of this model's unique ids (HasUuids: a UUID). Any value passes by default. */\n isValidUniqueId(_value: unknown): boolean {\n return true\n }\n\n /** Fills each empty unique id column with newUniqueId() (Laravel's setUniqueIds()). */\n setUniqueIds(): void {\n for (const column of this.uniqueIds()) {\n const value = this.getAttribute(column)\n if (value === undefined || value === null || value === '') this.setAttribute(column, this.newUniqueId())\n }\n }\n\n getKey(): unknown {\n return this.getAttribute(this.getKeyName())\n }\n\n getTable(): string {\n return this.table ?? Str.snake(Str.plural(this.constructor.name))\n }\n\n getConnectionName(): string | undefined {\n return this.connection\n }\n\n getPerPage(): number {\n return this.perPage\n }\n\n /** 'posts.title' for 'title'. Already-qualified columns are returned as-is. */\n qualifyColumn(column: string): string {\n return column.includes('.') ? column : `${this.getTable()}.${column}`\n }\n\n getQualifiedKeyName(): string {\n return this.qualifyColumn(this.getKeyName())\n }\n\n /** The conventional foreign key pointing at this model: user_id for User. */\n getForeignKey(): string {\n return `${Str.snake(this.constructor.name)}_${this.getKeyName()}`\n }\n\n getRouteKeyName(): string {\n return this.getKeyName()\n }\n\n getRouteKey(): unknown {\n return this.getAttribute(this.getRouteKeyName())\n }\n\n /**\n * The model a route parameter value points at: where <field or route key> = value (global scopes apply, so a\n * soft-deleted row isn't found). A non-numeric value for an integer primary key, or a value that isn't a UUID\n * (ULID) for a unique id column, finds nothing without a query.\n */\n async resolveRouteBinding(value: string, field?: string): Promise<this | undefined> {\n const column = field ?? this.getRouteKeyName()\n if (column === this.getKeyName() && this.getKeyType() === 'int' && !/^-?\\d+$/.test(value)) return undefined\n if (this.uniqueIds().includes(column) && !this.isValidUniqueId(value)) return undefined\n return this.resolveRouteBindingQuery(this.newQuery(), value, column).first()\n }\n\n /** Override to customize the binding query (Laravel's resolveRouteBindingQuery()). */\n resolveRouteBindingQuery(query: Builder<this>, value: string, field: string): Builder<this> {\n return query.where(this.qualifyColumn(field) as Column<this>, value)\n }\n\n usesTimestamps(): boolean {\n return this.timestamps\n }\n\n usesSoftDeletes(): boolean {\n return this.softDeletes\n }\n\n getCreatedAtColumn(): string | null {\n return (this.constructor as typeof Model).CREATED_AT\n }\n\n getUpdatedAtColumn(): string | null {\n return (this.constructor as typeof Model).UPDATED_AT\n }\n\n getDeletedAtColumn(): string {\n return (this.constructor as typeof Model).DELETED_AT\n }\n\n // ---------------------------------------------------------------- connection and queries\n\n /** The model's database connection, from the DatabaseManager binding. */\n getConnection(): Connection {\n const connection = inject(DatabaseManager).connection(this.getConnectionName())\n if (!(connection instanceof Connection)) {\n throw new DatabaseConfigError('Models need the DatabaseManager from @orieljs/database. Is DatabaseServiceProvider registered?')\n }\n return connection\n }\n\n setConnection(name: string | undefined): this {\n this.connection = name\n return this\n }\n\n setTable(table: string): this {\n this.table = table\n return this\n }\n\n /** A new instance of the same class, connection and table (mass assignment rules apply to attributes). */\n newInstance(attributes: Row = {}, exists = false): this {\n const model = new (this.constructor as new () => this)()\n model.exists = exists\n model.setConnection(this.getConnectionName())\n model.setTable(this.getTable())\n return model.fill(attributes)\n }\n\n /** An existing model from a database row (no casts or mutators applied to the row). */\n newFromBuilder(attributes: Row): this {\n const model = this.newInstance({}, true)\n model.setRawAttributes(attributes, true)\n return model\n }\n\n /** A query of this model with its global scopes and default eager loads. */\n newQuery(): Builder<this> {\n return this.registerGlobalScopes(this.newQueryWithoutScopes())\n }\n\n /** A query with the default eager loads (`with`, `withCount`) but no global scopes. */\n newQueryWithoutScopes(): Builder<this> {\n return this.registerDefaultEagerLoads(this.newModelQuery())\n }\n\n /** A query with the global scopes but no default eager loads. */\n newQueryWithoutRelationships(): Builder<this> {\n return this.registerGlobalScopes(this.newModelQuery())\n }\n\n /** Adds this class's global scopes to a builder (relations use it for the related model's scopes). */\n registerGlobalScopes<B extends Builder<Model>>(builder: B): B {\n for (const [name, scope] of globalScopes.get(this.constructor as typeof Model) ?? []) builder.withGlobalScope(name, scope)\n return builder\n }\n\n /**\n * Adds this class's default `with` and `withCount` to a builder (relations use it for the related model's\n * defaults). A default count that reaches the same class again while it is being added (a self-referencing\n * relation, or two models counting each other) is skipped there instead of recursing forever.\n */\n registerDefaultEagerLoads<B extends Builder<Model>>(builder: B): B {\n if (this.with.length) builder.with(...this.with)\n const cls = this.constructor as typeof Model\n if (!this.withCount.length || addingDefaultCounts.has(cls)) return builder\n addingDefaultCounts.add(cls)\n try {\n builder.withCount(...this.withCount)\n } finally {\n addingDefaultCounts.delete(cls)\n }\n return builder\n }\n\n /** A bare builder for this model: no global scopes, no default eager loads. */\n newModelQuery(): Builder<this> {\n return new Builder<this>(this)\n }\n\n // ---------------------------------------------------------------- persistence\n\n /**\n * Inserts the model, or updates its dirty attributes. Only changed columns are written; an unchanged model\n * runs no query at all. Returns false when a saving/creating/updating listener cancels.\n */\n async save(): Promise<boolean> {\n const query = this.newModelQuery()\n await this.hashPendingAttributes()\n if ((await this.fireModelEvent('saving')) === false) return false\n let saved: boolean\n if (this.exists) saved = this.isDirty() ? await this.performUpdate(query) : true\n else saved = await this.performInsert(query)\n if (saved) await this.finishSave()\n return saved\n }\n\n /**\n * Laravel's hashed cast (castAttributeAsHashedString()), run when the model is saved because the Hasher is\n * asynchronous: each newly assigned value is hashed before the saving event, so every listener sees the hash, and\n * again just before the write (after the creating or updating event), so a value a listener assigns is hashed too.\n * A value that is already a hash is kept when it matches the configured algorithm and options, and refused\n * otherwise. Only strings and numbers are hashed (null stays null); any other value is refused.\n */\n protected async hashPendingAttributes(): Promise<void> {\n if (!this.pendingHashes.size) return\n const hashing = hasher()\n for (const key of this.pendingHashes) {\n const value = this.attributes[key]\n if (value === null || value === undefined) continue\n if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'bigint') {\n throw new LogicError(`The hashed cast on [${key}] needs a string, got ${Array.isArray(value) ? 'array' : typeof value}.`)\n }\n const text = String(value)\n if (hashing.info(text).algorithm === 'unknown') this.attributes[key] = await hashing.make(text)\n else if (hashing.needsRehash(text)) throw new LogicError(\"Could not verify the hashed value's configuration.\")\n }\n this.pendingHashes.clear()\n }\n\n /** Fills and saves an existing model. */\n async update(attributes: Row = {}): Promise<boolean> {\n if (!this.exists) return false\n return this.fill(attributes).save()\n }\n\n /**\n * Deletes the model's row, or sets deleted_at with soft deletes. Returns false for a model that isn't saved, or\n * when a deleting listener cancels.\n */\n async delete(): Promise<boolean> {\n if (!this.exists) return false\n if ((await this.fireModelEvent('deleting')) === false) return false\n await this.performDeleteOnModel()\n await this.fireModelEvent('deleted', false)\n return true\n }\n\n /** save() without model events. */\n saveQuietly(): Promise<boolean> {\n return withoutModelEvents(() => this.save())\n }\n\n /** delete() without model events. */\n deleteQuietly(): Promise<boolean> {\n return withoutModelEvents(() => this.delete())\n }\n\n // ---------------------------------------------------------------- soft deletes\n\n /** True when the model is soft deleted. Only for models with `softDeletes = true`. */\n trashed(): boolean {\n this.assertSoftDeletes('trashed')\n const value = this.getAttribute(this.getDeletedAtColumn())\n return value !== null && value !== undefined\n }\n\n /** Clears deleted_at and saves. Fires restoring (can cancel) and restored. */\n async restore(): Promise<boolean> {\n this.assertSoftDeletes('restore')\n if ((await this.fireModelEvent('restoring')) === false) return false\n this.setAttribute(this.getDeletedAtColumn(), null)\n this.exists = true\n const saved = await this.save()\n await this.fireModelEvent('restored', false)\n return saved\n }\n\n /** Deletes the row for real, even with soft deletes. Fires forceDeleting (can cancel) and forceDeleted. */\n async forceDelete(): Promise<boolean> {\n if (!this.usesSoftDeletes()) return this.delete()\n if ((await this.fireModelEvent('forceDeleting')) === false) return false\n this.forceDeleting = true\n try {\n const deleted = await this.delete()\n if (deleted) await this.fireModelEvent('forceDeleted', false)\n return deleted\n } finally {\n this.forceDeleting = false\n }\n }\n\n isForceDeleting(): boolean {\n return this.forceDeleting\n }\n\n getQualifiedDeletedAtColumn(): string {\n return this.qualifyColumn(this.getDeletedAtColumn())\n }\n\n private assertSoftDeletes(method: string): void {\n if (!this.usesSoftDeletes()) {\n throw new LogicError(`${method}() needs soft deletes: set \\`protected softDeletes = true\\` on [${this.constructor.name}].`)\n }\n }\n\n /** Reloads the attributes and the loaded relations from the database (including a soft-deleted row). */\n async refresh(): Promise<this> {\n if (!this.exists) return this\n const fresh = await this.newModelQuery().whereKey(this.getKey()).firstOrFail()\n this.setRawAttributes(fresh.getAttributes(), true)\n const loaded = Object.keys(this.relations)\n if (loaded.length) await this.load(loaded)\n return this\n }\n\n /** A fresh copy from the database, or undefined when the row is gone. */\n async fresh(): Promise<this | undefined> {\n if (!this.exists) return undefined\n return this.newModelQuery().whereKey(this.getKey()).first()\n }\n\n /** Updates updated_at (and saves). */\n async touch(): Promise<boolean> {\n if (!this.usesTimestamps()) return false\n this.updateTimestamps()\n return this.save()\n }\n\n /** column = column + amount in the database, mirrored on the model without marking it dirty. */\n async increment(column: string, amount = 1, extra: Row = {}): Promise<number> {\n return this.incrementOrDecrement(column, amount, extra)\n }\n\n async decrement(column: string, amount = 1, extra: Row = {}): Promise<number> {\n return this.incrementOrDecrement(column, -amount, extra)\n }\n\n /** Same table, connection and key. */\n is(other: Model | null | undefined): boolean {\n return !!other && other.getKey() === this.getKey() && other.getTable() === this.getTable() &&\n other.getConnectionName() === this.getConnectionName()\n }\n\n isNot(other: Model | null | undefined): boolean {\n return !this.is(other)\n }\n\n /** The current time, to the second (the storage precision). */\n freshTimestamp(): Date {\n const now = new Date()\n now.setMilliseconds(0)\n return now\n }\n\n updateTimestamps(): void {\n const time = this.freshTimestamp()\n const updated = this.getUpdatedAtColumn()\n const created = this.getCreatedAtColumn()\n if (updated && !this.isDirty(updated)) this.setAttribute(updated, time)\n if (!this.exists && created && !this.isDirty(created)) this.setAttribute(created, time)\n }\n\n protected async performInsert(query: Builder<this>): Promise<boolean> {\n if (this.usesUniqueIds()) this.setUniqueIds()\n if ((await this.fireModelEvent('creating')) === false) return false\n if (this.usesTimestamps()) this.updateTimestamps()\n await this.hashPendingAttributes()\n const attributes = this.getAttributes()\n if (this.getIncrementing()) {\n const id = await query.insertGetId(attributes, this.getKeyName())\n this.setAttribute(this.getKeyName(), id)\n } else {\n if (!Object.keys(attributes).length) return true\n await query.insert(attributes)\n }\n this.exists = true\n this.wasRecentlyCreated = true\n await this.fireModelEvent('created', false)\n return true\n }\n\n protected async performUpdate(query: Builder<this>): Promise<boolean> {\n if ((await this.fireModelEvent('updating')) === false) return false\n if (this.usesTimestamps()) this.updateTimestamps()\n await this.hashPendingAttributes()\n const dirty = this.getDirty()\n if (Object.keys(dirty).length) {\n await this.setKeysForSaveQuery(query).update(dirty)\n this.syncChanges()\n await this.fireModelEvent('updated', false)\n }\n return true\n }\n\n protected async finishSave(): Promise<void> {\n await this.fireModelEvent('saved', false)\n this.syncOriginal()\n }\n\n protected async performDeleteOnModel(): Promise<void> {\n if (this.usesSoftDeletes() && !this.forceDeleting) return this.runSoftDelete()\n await this.setKeysForSaveQuery(this.newModelQuery()).forceDelete()\n this.exists = false\n }\n\n /** deleted_at (and updated_at) = now, on this row only. The model still exists, as a trashed model. */\n protected async runSoftDelete(): Promise<void> {\n const time = this.freshTimestamp()\n const columns = [this.getDeletedAtColumn()]\n this.setAttribute(this.getDeletedAtColumn(), time)\n const updated = this.getUpdatedAtColumn()\n if (this.usesTimestamps() && updated) {\n this.setAttribute(updated, time)\n columns.push(updated)\n }\n const values = Object.fromEntries(columns.map((column) => [column, this.getAttributes()[column]]))\n await this.setKeysForSaveQuery(this.newModelQuery()).update(values)\n this.syncOriginalAttributes(...columns)\n }\n\n /** where key = the key the row was loaded with (the original, in case the key itself changed). */\n protected setKeysForSaveQuery(query: Builder<this>): Builder<this> {\n const key = Object.hasOwn(this.original, this.getKeyName()) ? this.original[this.getKeyName()] : this.getKey()\n if (key === undefined || key === null) throw new LogicError(`Model [${this.constructor.name}] has no primary key value.`)\n return query.where(this.getKeyName() as Column<this>, '=', key)\n }\n\n protected async incrementOrDecrement(column: string, amount: number, extra: Row): Promise<number> {\n // An unsaved model updates every row its global scopes allow (never trashed rows); a saved one updates its own row.\n if (!this.exists) return this.newQueryWithoutRelationships().increment(column, amount, extra)\n // As Laravel's: the model holds the new values first, so updating and updated listeners (observers) see them, and an\n // updating listener that returns false stops the write.\n this.forceFill({ ...extra, [column]: Number(this.getAttribute(column) ?? 0) + amount })\n if ((await this.fireModelEvent('updating')) === false) return 0\n const affected = await this.setKeysForSaveQuery(this.newModelQuery()).increment(column, amount, extra)\n this.syncChanges()\n await this.fireModelEvent('updated', false)\n this.syncOriginalAttributes(column, ...Object.keys(extra))\n return affected\n }\n\n /**\n * Dispatches 'eloquent.<event>: <Class>' with the model as payload. Halting events return false when a listener\n * returned false. A no-op without an EventDispatcher binding, or inside withoutEvents().\n */\n async fireModelEvent(event: ModelEvent, halt = true): Promise<boolean> {\n if (modelEventsMuted()) return true\n const dispatcher = eventDispatcher()\n if (!dispatcher) return true\n const name = modelEventName(event, this.constructor.name)\n if (halt) return (await dispatcher.until(name, [this])) !== false\n await dispatcher.dispatch(name, [this])\n return true\n }\n\n /** Whether any listener is registered for one of this model's events (retrieved is skipped when none is). */\n hasModelListeners(event: ModelEvent): boolean {\n return !modelEventsMuted() && (eventDispatcher()?.hasListeners(modelEventName(event, this.constructor.name)) ?? false)\n }\n\n // ---------------------------------------------------------------- relations\n\n /**\n * One related row holds this model's key: user.profile() → hasOne(Profile) (profiles.user_id = users.id).\n * @param foreignKey on the related table (default: this model's foreign key, e.g. user_id)\n * @param localKey on this model (default: the primary key)\n */\n hasOne<C extends typeof Model>(related: C, foreignKey?: string, localKey?: string): HasOne<InstanceType<C>, this> & Scopes<C> {\n const instance = this.newRelatedInstance(related)\n const relation = new HasOne(instance, this, instance.qualifyColumn(foreignKey ?? this.getForeignKey()), localKey ?? this.getKeyName())\n return relation as HasOne<InstanceType<C>, this> & Scopes<C>\n }\n\n /** Many related rows hold this model's key: post.comments() → hasMany(Comment) (comments.post_id = posts.id). */\n hasMany<C extends typeof Model>(related: C, foreignKey?: string, localKey?: string): HasMany<InstanceType<C>, this> & Scopes<C> {\n const instance = this.newRelatedInstance(related)\n const relation = new HasMany(instance, this, instance.qualifyColumn(foreignKey ?? this.getForeignKey()), localKey ?? this.getKeyName())\n return relation as HasMany<InstanceType<C>, this> & Scopes<C>\n }\n\n /**\n * This model holds the related model's key: post.author() → belongsTo(User, 'user_id').\n * @param foreignKey on this model (default: the related model's foreign key, e.g. user_id)\n * @param ownerKey on the related model (default: its primary key)\n * @param relation the loaded-relation name associate() sets (default: the resolved name, else the class in camelCase)\n */\n belongsTo<C extends typeof Model>(related: C, foreignKey?: string, ownerKey?: string, relation?: string): BelongsTo<InstanceType<C>, this> & Scopes<C> {\n const instance = this.newRelatedInstance(related)\n const belongsTo = new BelongsTo(instance, this, foreignKey ?? instance.getForeignKey(), ownerKey ?? instance.getKeyName(), relation)\n return belongsTo as BelongsTo<InstanceType<C>, this> & Scopes<C>\n }\n\n /**\n * Many-to-many through a pivot table: post.tags() → belongsToMany(Tag) over post_tag (post_id, tag_id).\n * @param table default: the two singular snake names in alphabetical order (post_tag)\n * @param foreignPivotKey the pivot column pointing at this model (default: post_id)\n * @param relatedPivotKey the pivot column pointing at the related model (default: tag_id)\n */\n belongsToMany<C extends typeof Model>(\n related: C,\n table?: string,\n foreignPivotKey?: string,\n relatedPivotKey?: string,\n parentKey?: string,\n relatedKey?: string,\n ): BelongsToMany<InstanceType<C>, this> & Scopes<C> {\n const instance = this.newRelatedInstance(related)\n const joining = table ?? [Str.snake(this.constructor.name), Str.snake(related.name)].sort().join('_').toLowerCase()\n const relation = new BelongsToMany(\n instance,\n this,\n joining,\n foreignPivotKey ?? this.getForeignKey(),\n relatedPivotKey ?? instance.getForeignKey(),\n parentKey ?? this.getKeyName(),\n relatedKey ?? instance.getKeyName(),\n )\n return relation as BelongsToMany<InstanceType<C>, this> & Scopes<C>\n }\n\n /**\n * Related rows through an intermediate model: country.posts() → hasManyThrough(Post, User).\n * @param firstKey on the through table (default: this model's foreign key, country_id)\n * @param secondKey on the related table (default: the through model's foreign key, user_id)\n */\n hasManyThrough<C extends typeof Model, T extends typeof Model>(\n related: C,\n through: T,\n firstKey?: string,\n secondKey?: string,\n localKey?: string,\n secondLocalKey?: string,\n ): HasManyThrough<InstanceType<C>, this, InstanceType<T>> & Scopes<C> {\n const instance = this.newRelatedInstance(related)\n const throughParent = this.newRelatedInstance(through)\n const relation = new HasManyThrough(\n instance,\n this,\n throughParent,\n firstKey ?? this.getForeignKey(),\n secondKey ?? throughParent.getForeignKey(),\n localKey ?? this.getKeyName(),\n secondLocalKey ?? throughParent.getKeyName(),\n )\n return relation as HasManyThrough<InstanceType<C>, this, InstanceType<T>> & Scopes<C>\n }\n\n /** A polymorphic one-to-one: user.image() → morphOne(Image, 'imageable') (images.imageable_id/_type). */\n morphOne<C extends typeof Model>(related: C, name: string, type?: string, id?: string, localKey?: string): MorphOne<InstanceType<C>, this> & Scopes<C> {\n const instance = this.newRelatedInstance(related)\n const relation = new MorphOne(instance, this, instance.qualifyColumn(type ?? `${name}_type`), instance.qualifyColumn(id ?? `${name}_id`), localKey ?? this.getKeyName())\n return relation as MorphOne<InstanceType<C>, this> & Scopes<C>\n }\n\n /** A polymorphic one-to-many: post.comments() → morphMany(Comment, 'commentable'). */\n morphMany<C extends typeof Model>(related: C, name: string, type?: string, id?: string, localKey?: string): MorphMany<InstanceType<C>, this> & Scopes<C> {\n const instance = this.newRelatedInstance(related)\n const relation = new MorphMany(instance, this, instance.qualifyColumn(type ?? `${name}_type`), instance.qualifyColumn(id ?? `${name}_id`), localKey ?? this.getKeyName())\n return relation as MorphMany<InstanceType<C>, this> & Scopes<C>\n }\n\n /**\n * The inverse of morphOne/morphMany: comment.commentable() → morphTo('commentable'). The name is required\n * (Laravel reads it from the calling method, which JavaScript can't do reliably).\n */\n morphTo<R extends Model = Model>(name: string, type?: string, id?: string, ownerKey?: string): MorphTo<R, this> {\n const typeColumn = type ?? `${name}_type`\n const value = this.getAttribute(typeColumn)\n const related = (value ? this.newRelatedInstance(resolveMorphClass(String(value))) : this.newInstance()) as unknown as R\n return new MorphTo<R, this>(related, this, id ?? `${name}_id`, typeColumn, ownerKey, name)\n }\n\n /** The value stored in *_type columns for this model: its morph map alias, or its class name. */\n getMorphClass(): string {\n const cls = this.constructor as typeof Model\n return getMorphAlias(cls) ?? cls.name\n }\n\n /** The pivot row of a model loaded through belongsToMany (tag.pivot.getAttribute('created_at')). */\n get pivot(): Model | undefined {\n return this.relations.pivot as Model | undefined\n }\n\n /** A related model instance on this model's connection when it has none of its own. */\n protected newRelatedInstance<C extends typeof Model>(related: C): InstanceType<C> {\n const instance = new related() as InstanceType<C>\n if (!instance.getConnectionName()) instance.setConnection(this.getConnectionName())\n return instance\n }\n\n /** Whether the model has a relation method called `name` (Laravel's isRelation()). */\n isRelation(name: string): boolean {\n return !(name in Model.prototype) && methodOf(this, name) !== undefined\n }\n\n /** Calls the relation method `name` (post.comments()) and checks that it returns a relation. */\n getRelationInstance(name: string): Relation {\n if (name in Model.prototype) throw new RelationNotFoundError(this.constructor.name, name)\n const method = methodOf(this, name)\n const relation = method?.call(this)\n if (!(relation instanceof Relation)) throw new RelationNotFoundError(this.constructor.name, name)\n relation.relationName = name\n return relation\n }\n\n /**\n * A loaded relation, typed from the relation method: post.getRelation('author') is User | null,\n * post.getRelation('comments') is EloquentCollection<Comment>. Throws RelationNotLoadedError when it isn't loaded\n * (JavaScript can't lazy-load synchronously: use with(), load() or post.comments().get()).\n */\n getRelation<K extends RelationNames<this>>(name: K): RelationValue<this, K> {\n if (!Object.hasOwn(this.relations, name)) throw new RelationNotLoadedError(this.constructor.name, name)\n return this.relations[name] as RelationValue<this, K>\n }\n\n /** Eager loads relations onto this model: await post.load('comments.author'). */\n async load(...relations: EagerLoadSpec[]): Promise<this> {\n await this.newCollection([this]).load(...relations)\n return this\n }\n\n /** Loads only the relations that aren't loaded yet (nested paths are followed into loaded relations). */\n async loadMissing(...relations: string[]): Promise<this> {\n await this.newCollection([this]).loadMissing(...relations)\n return this\n }\n\n /** Loads <relation>_count attributes: await post.loadCount('comments'). */\n async loadCount(...relations: EagerLoadSpec[]): Promise<this> {\n await this.newCollection([this]).loadCount(...relations)\n return this\n }\n\n /** Loads an aggregate of a relation as an attribute (Laravel's loadAggregate()): see withAggregate(). */\n async loadAggregate(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression, fn?: string): Promise<this> {\n await this.newCollection([this]).loadAggregate(relations, column, fn)\n return this\n }\n\n /** Loads <relation>_sum_<column>: await user.loadSum('orders', 'price'). */\n loadSum(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): Promise<this> {\n return this.loadAggregate(relations, column, 'sum')\n }\n\n loadAvg(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): Promise<this> {\n return this.loadAggregate(relations, column, 'avg')\n }\n\n loadMin(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): Promise<this> {\n return this.loadAggregate(relations, column, 'min')\n }\n\n loadMax(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): Promise<this> {\n return this.loadAggregate(relations, column, 'max')\n }\n\n /** Loads a boolean <relation>_exists. */\n loadExists(...relations: EagerLoadSpec[]): Promise<this> {\n return this.loadAggregate(relations, '*', 'exists')\n }\n\n /**\n * The collection queries of this model return (Laravel's newCollection()): an EloquentCollection. Override it to\n * return a subclass with your own methods.\n */\n newCollection<T extends Model>(this: T, models: T[] = []): EloquentCollection<T> {\n return new EloquentCollection(models)\n }\n\n // ---------------------------------------------------------------- relations storage\n\n /** Stores a loaded relation (eager loading and load() use this). */\n setRelation(name: string, value: unknown): this {\n this.relations[name] = value\n return this\n }\n\n relationLoaded(name: string): boolean {\n return Object.hasOwn(this.relations, name)\n }\n\n unsetRelation(name: string): this {\n delete this.relations[name]\n return this\n }\n\n getRelations(): Record<string, unknown> {\n return { ...this.relations }\n }\n\n // ---------------------------------------------------------------- serialization\n\n getHidden(): string[] {\n return [...this.hidden]\n }\n\n setHidden(hidden: string[]): this {\n this.hidden = [...hidden]\n return this\n }\n\n getVisible(): string[] {\n return [...this.visible]\n }\n\n setVisible(visible: string[]): this {\n this.visible = [...visible]\n return this\n }\n\n /** Hides attributes for this instance only. */\n makeHidden(...attributes: Array<string | string[]>): this {\n const names = attributes.flat()\n this.hidden = [...new Set([...this.hidden, ...names])]\n this.visible = this.visible.filter((name) => !names.includes(name))\n return this\n }\n\n /** Un-hides attributes for this instance only. */\n makeVisible(...attributes: Array<string | string[]>): this {\n const names = attributes.flat()\n this.hidden = this.hidden.filter((name) => !names.includes(name))\n if (this.visible.length) this.visible = [...new Set([...this.visible, ...names])]\n return this\n }\n\n getAppends(): string[] {\n return [...this.appends]\n }\n\n setAppends(appends: string[]): this {\n this.appends = [...appends]\n return this\n }\n\n /** Adds accessor-only attributes to the serialized form of this instance. */\n append(...attributes: Array<string | string[]>): this {\n this.appends = [...new Set([...this.appends, ...attributes.flat()])]\n return this\n }\n\n /**\n * Attributes (through accessors and casts, dates as ISO strings), appends and loaded relations, minus hidden ones.\n * A model met again while its own toArray() runs (a child chaperone() pointed back at it) gives its attributes only.\n */\n toArray(): Row {\n if (serializing.has(this)) return this.attributesToArray()\n serializing.add(this)\n try {\n return { ...this.attributesToArray(), ...this.relationsToArray() }\n } finally {\n serializing.delete(this)\n }\n }\n\n toJSON(): Row {\n return this.toArray()\n }\n\n attributesToArray(): Row {\n const casts = this.getCasts()\n const result: Row = {}\n for (const [key, raw] of Object.entries(this.arrayable(this.getAttributes()))) {\n const accessor = this.mutatorFor('get', key)\n if (accessor) result[key] = this.serializeValue(accessor.call(this, raw))\n else if (casts[key] !== undefined) result[key] = this.serializeValue(this.castAttribute(key, raw))\n else result[key] = raw\n }\n for (const key of this.appends) {\n if (this.isArrayableKey(key)) result[key] = this.serializeValue(this.getAttribute(key))\n }\n return result\n }\n\n /** Loaded relations under their snake_case names: a model → its array, a collection → an array of arrays. */\n relationsToArray(): Row {\n const result: Row = {}\n for (const [name, value] of Object.entries(this.relations)) {\n const key = Str.snake(name)\n if (!this.isArrayableKey(key)) continue\n if (value === null || value === undefined) result[key] = null\n else if (value instanceof Collection) result[key] = value.toArray()\n else if (typeof (value as { toArray?: unknown }).toArray === 'function') result[key] = (value as { toArray(): unknown }).toArray()\n else result[key] = value\n }\n return result\n }\n\n protected serializeValue(value: unknown): unknown {\n if (value instanceof Date) return serializeDate(value)\n if (value instanceof Collection) return value.toArray()\n return value\n }\n\n private isArrayableKey(key: string): boolean {\n if (this.visible.length && !this.visible.includes(key)) return false\n return !this.hidden.includes(key)\n }\n\n private arrayable(values: Row): Row {\n return Object.fromEntries(Object.entries(values).filter(([key]) => this.isArrayableKey(key)))\n }\n}\n\nsetModelBaseClass(Model)\n\n/** Eager loads relations onto models you already have (Laravel's $collection->load()). */\nexport async function loadRelations<M extends Model>(models: Iterable<M>, ...relations: EagerLoadSpec[]): Promise<M[]> {\n const list = [...models]\n if (!list.length) return list\n await list[0]!.newQueryWithoutRelationships().with(...relations).eagerLoadRelations(list)\n return list\n}\n\n/** A row of a belongsToMany pivot table, available as related.pivot (unguarded, no key, no timestamps by default). */\nexport class Pivot extends Model {\n protected override guarded: string[] = []\n override incrementing = false\n override timestamps = false\n}\n","import type { Operator, Row } from '@orieljs/contracts'\nimport { Collection } from '@orieljs/collections'\nimport { Str } from '@orieljs/support'\nimport { ModelNotFoundError, QueryError } from '../errors'\nimport { Builder as QueryBuilder, type ColumnRef, type DateWhereArgs, type Direction, type Where, type WhereBoolean } from '../Query/Builder'\nimport { Expression } from '../Query/Expression'\nimport { formatDateTime } from '../Query/values'\nimport type { CastDefinition } from './casts'\nimport type { EloquentCollection } from './Collection'\nimport type { Model } from './Model'\nimport { withoutRelationConstraints } from './Relations/constraints'\nimport type { Relation } from './Relations/Relation'\nimport type { GlobalScope } from './Scope'\nimport { SoftDeletingScope } from './SoftDeletingScope'\nimport type { Column } from './types'\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyRelation = Relation<any, any, any>\n/** A constraint on an eager load, withCount() or whereHas(): (query) => query.where(…). */\nexport type RelationConstraint = (query: AnyRelation) => unknown\n/** with('author'), with(['author', 'comments.user']), with({ comments: (q) => q.latest() }), with('author:id,name'). */\nexport type EagerLoadSpec = string | string[] | Record<string, RelationConstraint>\n\ntype AnyFunction = (...args: unknown[]) => unknown\n\n/** Unknown properties of an Eloquent builder resolve to the model's local scopes: query.published() → scopePublished. */\nconst handler: ProxyHandler<Builder<Model>> = {\n get(target, key, receiver) {\n if (typeof key === 'symbol' || key in target) return Reflect.get(target, key, receiver)\n const scope = target.localScope(key)\n if (!scope) return undefined\n return (...args: unknown[]) => (receiver as Builder<Model>).callScope((query) => scope.call(target.model.constructor, query, ...args))\n },\n}\n\n/** Unique-constraint violations on each driver (createOrFirst()). */\nfunction isUniqueViolation(error: unknown): boolean {\n const cause = (error instanceof QueryError ? error.cause : error) as { code?: unknown; errno?: unknown; message?: unknown } | undefined\n return cause?.code === '23505' || cause?.errno === 1062 || cause?.code === 'ER_DUP_ENTRY' ||\n /UNIQUE constraint failed/.test(String(cause?.message ?? ''))\n}\n\n/**\n * Eloquent's builder: the query builder of one model class. Rows come back as hydrated models, global scopes are\n * applied when the query runs (grouped so an orWhere can't escape them), and unknown methods call the model's local\n * scopes. Everything the query builder does (pagination, chunk, lazy, …) returns models here.\n */\nexport class Builder<M extends Model = Model> extends QueryBuilder<M> {\n readonly model: M\n protected scopes = new Map<string, GlobalScope>()\n protected removedScopes: string[] = []\n protected eagerLoad = new Map<string, RelationConstraint | undefined>()\n /** Casts for the selected columns (withCasts()), merged into every model this query hydrates. */\n protected selectCasts: Record<string, CastDefinition> = {}\n\n constructor(model: M) {\n super(model.getConnection(), model.getTable())\n this.model = model\n return new Proxy(this, handler as ProxyHandler<this>)\n }\n\n getModel(): M {\n return this.model\n }\n\n // ---------------------------------------------------------------- scopes\n\n /** The model class's static scope<Name> method for a builder method name, if any. */\n localScope(name: string): AnyFunction | undefined {\n const scope: unknown = Reflect.get(this.model.constructor, `scope${Str.studly(name)}`)\n return typeof scope === 'function' ? (scope as AnyFunction) : undefined\n }\n\n /** Runs a scope; the wheres it adds are grouped when they contain an \"or\" (Laravel's callScope). */\n callScope(scope: (query: this) => unknown): this {\n const before = this.wheres.length\n const result = scope(this)\n if (this.wheres.length > before) this.addNewWheresWithinGroup(before)\n return result === undefined || result === null ? this : (result as this)\n }\n\n withGlobalScope(name: string, scope: GlobalScope): this {\n this.scopes.set(name, scope)\n return this\n }\n\n /** Removes a global scope by name or Scope class. */\n withoutGlobalScope(scope: string | (abstract new (...args: never[]) => unknown)): this {\n const name = typeof scope === 'string' ? scope : scope.name\n this.removedScopes.push(name)\n this.scopes.delete(name)\n return this\n }\n\n /** Removes every global scope, or the given ones. */\n withoutGlobalScopes(scopes?: Array<string | (abstract new (...args: never[]) => unknown)>): this {\n if (!scopes) {\n this.removedScopes.push(...this.scopes.keys())\n this.scopes.clear()\n } else {\n for (const scope of scopes) this.withoutGlobalScope(scope)\n }\n return this\n }\n\n removedScopeNames(): string[] {\n return [...this.removedScopes]\n }\n\n /** A copy of this query with every global scope applied (Laravel's applyScopes()). */\n applyScopes(): this {\n if (!this.scopes.size) return this\n const query = this.clone() as this\n for (const scope of this.scopes.values()) {\n query.callScope((builder) => (typeof scope === 'function' ? scope(builder) : scope.apply(builder, this.model)))\n }\n query.scopes = new Map()\n return query\n }\n\n /** Groups [0, count) and [count, …) separately when either contains an \"or\", so scopes combine with \"and\". */\n protected addNewWheresWithinGroup(count: number): void {\n const all = this.wheres\n this.wheres = []\n this.groupWhereSlice(all.slice(0, count))\n this.groupWhereSlice(all.slice(count))\n }\n\n private groupWhereSlice(slice: Where[]): void {\n if (!slice.length) return\n if (slice.some((where) => where.boolean === 'or')) {\n const nested = new QueryBuilder<Row>(this.connection)\n nested.wheres = slice\n this.wheres.push({ type: 'nested', query: nested, not: false, boolean: slice[0]!.boolean })\n } else {\n this.wheres.push(...slice)\n }\n }\n\n // ---------------------------------------------------------------- typed constraints (Column<M> names)\n\n override where(column: Column<M> | Expression, value: unknown): this\n override where(column: Column<M> | Expression, operator: Operator | string, value: unknown): this\n override where(conditions: Row): this\n override where(callback: (query: this) => unknown): this\n override where(...args: unknown[]): this {\n return Reflect.apply(QueryBuilder.prototype.where, this, args) as this\n }\n\n override orWhere(column: Column<M> | Expression, value: unknown): this\n override orWhere(column: Column<M> | Expression, operator: Operator | string, value: unknown): this\n override orWhere(conditions: Row): this\n override orWhere(callback: (query: this) => unknown): this\n override orWhere(...args: unknown[]): this {\n return Reflect.apply(QueryBuilder.prototype.orWhere, this, args) as this\n }\n\n override whereIn(column: Column<M> | Expression, values: readonly unknown[] | QueryBuilder<unknown>): this {\n return super.whereIn(column, values)\n }\n\n override whereNotIn(column: Column<M> | Expression, values: readonly unknown[] | QueryBuilder<unknown>): this {\n return super.whereNotIn(column, values)\n }\n\n override whereNull(columns: Column<M> | Expression | Array<Column<M> | Expression>): this {\n return super.whereNull(columns)\n }\n\n override whereNotNull(columns: Column<M> | Expression | Array<Column<M> | Expression>): this {\n return super.whereNotNull(columns)\n }\n\n override whereBetween(column: Column<M> | Expression, values: readonly [unknown, unknown]): this {\n return super.whereBetween(column, values)\n }\n\n override whereDate(column: Column<M> | Expression, ...args: DateWhereArgs): this {\n return super.whereDate(column, ...args)\n }\n\n override orWhereDate(column: Column<M> | Expression, ...args: DateWhereArgs): this {\n return super.orWhereDate(column, ...args)\n }\n\n override whereTime(column: Column<M> | Expression, ...args: DateWhereArgs): this {\n return super.whereTime(column, ...args)\n }\n\n override orWhereTime(column: Column<M> | Expression, ...args: DateWhereArgs): this {\n return super.orWhereTime(column, ...args)\n }\n\n override whereDay(column: Column<M> | Expression, ...args: DateWhereArgs): this {\n return super.whereDay(column, ...args)\n }\n\n override orWhereDay(column: Column<M> | Expression, ...args: DateWhereArgs): this {\n return super.orWhereDay(column, ...args)\n }\n\n override whereMonth(column: Column<M> | Expression, ...args: DateWhereArgs): this {\n return super.whereMonth(column, ...args)\n }\n\n override orWhereMonth(column: Column<M> | Expression, ...args: DateWhereArgs): this {\n return super.orWhereMonth(column, ...args)\n }\n\n override whereYear(column: Column<M> | Expression, ...args: DateWhereArgs): this {\n return super.whereYear(column, ...args)\n }\n\n override orWhereYear(column: Column<M> | Expression, ...args: DateWhereArgs): this {\n return super.orWhereYear(column, ...args)\n }\n\n override whereLike(column: Column<M> | Expression, value: string, caseSensitive = false, boolean: WhereBoolean = 'and', not = false): this {\n return super.whereLike(column, value, caseSensitive, boolean, not)\n }\n\n override orWhereLike(column: Column<M> | Expression, value: string, caseSensitive = false): this {\n return super.orWhereLike(column, value, caseSensitive)\n }\n\n override whereNotLike(column: Column<M> | Expression, value: string, caseSensitive = false, boolean: WhereBoolean = 'and'): this {\n return super.whereNotLike(column, value, caseSensitive, boolean)\n }\n\n override orWhereNotLike(column: Column<M> | Expression, value: string, caseSensitive = false): this {\n return super.orWhereNotLike(column, value, caseSensitive)\n }\n\n override orderBy(column: Column<M> | Expression, direction: Direction | Uppercase<Direction> = 'asc'): this {\n return super.orderBy(column, direction)\n }\n\n /** Newest first by the model's created_at column (or the given one). */\n override latest(column?: Column<M> | Expression): this {\n return super.latest(column ?? this.model.getCreatedAtColumn() ?? 'created_at')\n }\n\n override oldest(column?: Column<M> | Expression): this {\n return super.oldest(column ?? this.model.getCreatedAtColumn() ?? 'created_at')\n }\n\n override select(...columns: Array<Column<M> | Expression | Array<Column<M> | Expression>>): this {\n return super.select(...columns)\n }\n\n /** where key = id (or key in ids). */\n whereKey(id: unknown): this {\n if (Array.isArray(id)) return super.whereIn(this.model.getQualifiedKeyName(), id)\n return super.where(this.model.getQualifiedKeyName(), '=', id)\n }\n\n whereKeyNot(id: unknown): this {\n if (Array.isArray(id)) return super.whereNotIn(this.model.getQualifiedKeyName(), id)\n return super.where(this.model.getQualifiedKeyName(), '!=', id)\n }\n\n // ---------------------------------------------------------------- reading\n\n /** The models, in the model's collection (an EloquentCollection). */\n override async get(): Promise<EloquentCollection<M>> {\n return (await super.get()) as EloquentCollection<M>\n }\n\n protected override newCollection(models: M[]): EloquentCollection<M> {\n return this.model.newCollection(models)\n }\n\n /** chunk() with each chunk in the model's collection. */\n override chunk(count: number, callback: (models: EloquentCollection<M>, page: number) => unknown): Promise<boolean> {\n return super.chunk(count, callback as (results: Collection<M>, page: number) => unknown)\n }\n\n override chunkById(count: number, callback: (models: EloquentCollection<M>, page: number) => unknown, column?: string, alias?: string): Promise<boolean> {\n return super.chunkById(count, callback as (results: Collection<M>, page: number) => unknown, column, alias)\n }\n\n /** Runs the query, hydrates models, fires their retrieved events and eager loads the with() relations. */\n override async runSelect(): Promise<M[]> {\n const query = this.applyScopes()\n const rows = (await QueryBuilder.prototype.runSelect.call(query)) as unknown as Row[]\n const models = query.hydrate(rows)\n if (models.length && this.model.hasModelListeners('retrieved')) {\n for (const model of models) await model.fireModelEvent('retrieved', false)\n }\n // The scoped copy's eager loads: a global scope may add with() relations of its own.\n if (models.length && query.eagerLoad.size) await query.eagerLoadRelations(models)\n return models\n }\n\n // ---------------------------------------------------------------- eager loading\n\n /**\n * Relations to load with the results, one query per relation (and per nesting level):\n * with('author'), with('comments.author'), with({ comments: (q) => q.where('approved', true) }), with('author:id,name').\n */\n with(...relations: EagerLoadSpec[]): this {\n for (const spec of relations) {\n if (typeof spec === 'string') this.addEagerLoad(spec, undefined)\n else if (Array.isArray(spec)) for (const name of spec) this.addEagerLoad(name, undefined)\n else for (const [name, constraint] of Object.entries(spec)) this.addEagerLoad(name, constraint)\n }\n return this\n }\n\n /** Removes eager loads (including the model's default `with`). */\n without(...relations: string[]): this {\n for (const name of relations) {\n for (const key of [...this.eagerLoad.keys()]) if (key === name || key.startsWith(`${name}.`)) this.eagerLoad.delete(key)\n }\n return this\n }\n\n getEagerLoads(): Map<string, RelationConstraint | undefined> {\n return new Map(this.eagerLoad)\n }\n\n /** Loads every top-level with() relation onto the models (nested ones are passed down to each relation query). */\n async eagerLoadRelations(models: M[]): Promise<M[]> {\n for (const [name, constraint] of this.eagerLoad) {\n if (!name.includes('.')) await this.eagerLoadRelation(models, name, constraint)\n }\n return models\n }\n\n /** The relation instance for a name, without its per-parent constraints. */\n getRelation(name: string): AnyRelation {\n return withoutRelationConstraints(() => this.model.newInstance().getRelationInstance(name))\n }\n\n protected async eagerLoadRelation(models: M[], name: string, constraint: RelationConstraint | undefined): Promise<void> {\n const relation = this.getRelation(name)\n relation.addEagerConstraints(models)\n constraint?.(relation)\n relation.limitEagerPerParent()\n const nested = this.relationsNestedUnder(name)\n if (Object.keys(nested).length) relation.with(nested)\n relation.initRelation(models, name)\n relation.match(models, (await relation.getEager()).all(), name)\n }\n\n private addEagerLoad(spec: string, constraint: RelationConstraint | undefined): void {\n const [path = '', columns] = spec.split(':')\n const name = path.trim()\n let callback = constraint\n if (columns) {\n const selected = columns.split(',').map((column) => column.trim())\n callback = (query) => {\n query.select(...selected)\n constraint?.(query)\n }\n }\n const segments = name.split('.')\n for (let i = 1; i < segments.length; i++) {\n const parent = segments.slice(0, i).join('.')\n if (!this.eagerLoad.has(parent)) this.eagerLoad.set(parent, undefined)\n }\n this.eagerLoad.set(name, callback)\n }\n\n private relationsNestedUnder(name: string): Record<string, RelationConstraint> {\n const nested: Record<string, RelationConstraint> = {}\n for (const [key, constraint] of this.eagerLoad) {\n if (key.startsWith(`${name}.`)) nested[key.slice(name.length + 1)] = constraint ?? (() => undefined)\n }\n return nested\n }\n\n // ---------------------------------------------------------------- relation counts and existence\n\n /**\n * Adds `<relation>_count` columns: withCount('comments'), withCount({ comments: (q) => q.where('approved', true) }),\n * withCount('comments as approved_count'). Global scopes of the related model (soft deletes) apply.\n */\n withCount(...relations: EagerLoadSpec[]): this {\n return this.withAggregate(relations, '*', 'count')\n }\n\n /** Adds `<relation>_sum_<column>`: withSum('orders', 'price'), withSum({ 'orders as paid': (q) => … }, 'price'). */\n withSum(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): this {\n return this.withAggregate(relations, column, 'sum')\n }\n\n /** Adds `<relation>_avg_<column>`. */\n withAvg(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): this {\n return this.withAggregate(relations, column, 'avg')\n }\n\n /** Adds `<relation>_min_<column>`. */\n withMin(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): this {\n return this.withAggregate(relations, column, 'min')\n }\n\n /** Adds `<relation>_max_<column>`. */\n withMax(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): this {\n return this.withAggregate(relations, column, 'max')\n }\n\n /** Adds a boolean `<relation>_exists`: withExists('comments'). */\n withExists(...relations: EagerLoadSpec[]): this {\n return this.withAggregate(relations, '*', 'exists')\n }\n\n /**\n * Laravel's withAggregate(): a correlated subquery per relation, `select <fn>(<related column>) … as <alias>`, the\n * alias being `<relation>_<fn>_<column>` unless the relation is named `'orders as alias'`. The relation's\n * constraint and the related model's global scopes apply; orderings are dropped. 'exists' selects\n * `exists (…)`, cast to a boolean. Without a function the column's first value is selected.\n */\n withAggregate(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression, fn?: string): this {\n const specs = this.normalizeRelationSpecs([relations].flat() as EagerLoadSpec[])\n if (!specs.length) return this\n if (!this.columns.length) this.columns = [`${this.model.getTable()}.*`]\n for (const [spec, constraint] of specs) {\n const [rawName = '', as] = spec.split(/\\s+as\\s+/i)\n const name = rawName.trim()\n const relation = this.getRelation(name)\n const query = relation.getRelationExistenceQuery(relation.getRelated().newQueryWithoutRelationships(), this)\n // Qualified after the existence query: on a self-referencing relation the related table has taken its alias.\n const target = column instanceof Expression\n ? column\n : new Expression(column === '*' ? '*' : this.connection.compile(this.grammar.wrap(query.getModel().qualifyColumn(column))).sql)\n const expression = fn && fn !== 'exists' ? new Expression(`${fn}(${target.value})`, target.bindings) : target\n query.select(expression)\n query.wheres.push(...relation.wheres)\n if (constraint) query.callScope((q) => constraint(q as unknown as AnyRelation))\n const scoped = query.applyScopes()\n scoped.orders = []\n if (scoped.columns.length > 1) scoped.columns = [scoped.columns[0]!]\n const columnName = (column instanceof Expression ? column.value : column).toLowerCase()\n const alias = as?.trim() ?? Str.snake(`${name} ${fn ?? ''} ${columnName}`.replace(/[^\\p{L}\\p{N}\\s_]/gu, ''))\n if (fn === 'exists') {\n this.columns.push({ query: scoped, as: alias, exists: true })\n this.withCasts({ [alias]: 'bool' })\n } else {\n this.selectSub(fn ? scoped : scoped.limit(1), alias)\n }\n }\n return this\n }\n\n /** Casts for selected columns, as if the model declared them: withCasts({ orders_sum_price: 'float' }). */\n withCasts(casts: Readonly<Record<string, CastDefinition>>): this {\n this.selectCasts = { ...this.selectCasts, ...casts }\n return this\n }\n\n /**\n * Rows that have related rows: has('comments'), has('comments', '>=', 3), has('comments.author').\n * Uses `exists (…)` for the common \"at least one\"/\"none\" cases and a count subquery otherwise.\n */\n has(relation: string, operator = '>=', count = 1, boolean: 'and' | 'or' = 'and', callback?: RelationConstraint): this {\n if (relation.includes('.')) return this.hasNested(relation, operator, count, boolean, callback)\n const instance = this.getRelation(relation)\n const useExists = (operator === '>=' || operator === '<') && count === 1\n const query = useExists\n ? instance.getRelationExistenceQuery(instance.getRelated().newQueryWithoutRelationships(), this)\n : instance.getRelationExistenceCountQuery(instance.getRelated().newQueryWithoutRelationships(), this)\n query.wheres.push(...instance.wheres)\n if (callback) query.callScope((q) => callback(q as unknown as AnyRelation))\n const scoped = query.applyScopes()\n if (useExists) return this.whereExists(scoped, boolean, operator === '<')\n return this.whereSub(scoped, operator, count, boolean)\n }\n\n orHas(relation: string, operator = '>=', count = 1): this {\n return this.has(relation, operator, count, 'or')\n }\n\n doesntHave(relation: string, boolean: 'and' | 'or' = 'and', callback?: RelationConstraint): this {\n return this.has(relation, '<', 1, boolean, callback)\n }\n\n orDoesntHave(relation: string): this {\n return this.doesntHave(relation, 'or')\n }\n\n /** Rows with related rows matching the callback: whereHas('comments', (q) => q.where('approved', true)). */\n whereHas(relation: string, callback?: RelationConstraint, operator = '>=', count = 1): this {\n return this.has(relation, operator, count, 'and', callback)\n }\n\n orWhereHas(relation: string, callback?: RelationConstraint, operator = '>=', count = 1): this {\n return this.has(relation, operator, count, 'or', callback)\n }\n\n whereDoesntHave(relation: string, callback?: RelationConstraint): this {\n return this.doesntHave(relation, 'and', callback)\n }\n\n orWhereDoesntHave(relation: string, callback?: RelationConstraint): this {\n return this.doesntHave(relation, 'or', callback)\n }\n\n /** has('comments.author'): whereHas('comments', q => q.has('author')) */\n private hasNested(relation: string, operator: string, count: number, boolean: 'and' | 'or', callback?: RelationConstraint): this {\n const [first = '', ...rest] = relation.split('.')\n return this.has(first, '>=', 1, boolean, (query) => {\n query.has(rest.join('.'), operator, count, 'and', callback)\n })\n }\n\n private normalizeRelationSpecs(relations: EagerLoadSpec[]): Array<[string, RelationConstraint | undefined]> {\n const specs: Array<[string, RelationConstraint | undefined]> = []\n for (const spec of relations) {\n if (typeof spec === 'string') specs.push([spec, undefined])\n else if (Array.isArray(spec)) for (const name of spec) specs.push([name, undefined])\n else specs.push(...Object.entries(spec))\n }\n return specs\n }\n\n /** Models from raw rows, marked as existing. */\n hydrate(rows: readonly Row[]): M[] {\n const casts = Object.keys(this.selectCasts).length ? this.selectCasts : undefined\n return rows.map((row) => {\n const model = this.model.newFromBuilder(row) as M\n return casts ? model.mergeCasts(casts) : model\n })\n }\n\n override async aggregate(fn: 'count' | 'min' | 'max' | 'sum' | 'avg', column: ColumnRef): Promise<unknown> {\n return QueryBuilder.prototype.aggregate.call(this.applyScopes(), fn, column)\n }\n\n override async exists(): Promise<boolean> {\n return QueryBuilder.prototype.exists.call(this.applyScopes())\n }\n\n /** The column's values, through the model's casts and accessors. */\n override async pluck<V = unknown>(column: Column<M>): Promise<Collection<V>> {\n const query = this.applyScopes().clone()\n const rows = (await QueryBuilder.prototype.runSelect.call(query.select(column))) as unknown as Row[]\n const key = column.includes('.') ? column.slice(column.lastIndexOf('.') + 1) : column\n return new Collection(rows.map((row) => this.model.newInstance().setRawAttributes({ [key]: row[key] }).getAttribute<V>(key)))\n }\n\n /** Whether `id` can't be one of the model's unique ids (not a UUID for HasUuids): it matches no row. */\n protected isMalformedKey(id: unknown): boolean {\n return this.model.uniqueIds().includes(this.model.getKeyName()) && !this.model.isValidUniqueId(id)\n }\n\n /**\n * A model by its key, or undefined; with an array of keys, the models found, as a collection (Laravel's find()). A\n * malformed unique id (HasUuids, HasUlids) finds nothing without a query, as route model binding does.\n */\n override find(ids: readonly unknown[]): Promise<EloquentCollection<M>>\n override find(id: unknown): Promise<M | undefined>\n override async find(id: unknown): Promise<M | undefined | EloquentCollection<M>> {\n if (Array.isArray(id)) return this.findMany(id)\n if (this.isMalformedKey(id)) return undefined\n return this.clone().whereKey(id).first()\n }\n\n async findMany(ids: readonly unknown[]): Promise<EloquentCollection<M>> {\n const keys = ids.filter((id) => !this.isMalformedKey(id))\n if (!keys.length) return this.model.newCollection<M>([])\n return this.clone().whereKey(keys).get()\n }\n\n /** find(), or ModelNotFoundError (a 404). With an array, every id must exist. */\n async findOrFail(ids: readonly unknown[]): Promise<EloquentCollection<M>>\n async findOrFail(id: unknown): Promise<M>\n async findOrFail(id: unknown): Promise<M | EloquentCollection<M>> {\n if (Array.isArray(id)) {\n const models = await this.findMany(id)\n if (models.count() !== new Set(id.map(String)).size) throw new ModelNotFoundError(this.model.constructor.name, id)\n return models\n }\n const model = await this.find(id)\n if (!model) throw new ModelNotFoundError(this.model.constructor.name, [id])\n return model\n }\n\n async findOr<R>(id: unknown, callback: () => R | Promise<R>): Promise<M | R> {\n return (await this.find(id)) ?? callback()\n }\n\n async firstOrFail(): Promise<M> {\n const model = await this.first()\n if (!model) throw new ModelNotFoundError(this.model.constructor.name)\n return model\n }\n\n async firstOr<R>(callback: () => R | Promise<R>): Promise<M | R> {\n return (await this.first()) ?? callback()\n }\n\n async firstWhere(column: Column<M> | Expression, operatorOrValue: unknown, value?: unknown): Promise<M | undefined> {\n const query = this.clone()\n return (value === undefined ? query.where(column, operatorOrValue) : query.where(column, String(operatorOrValue), value)).first()\n }\n\n // ---------------------------------------------------------------- creating and updating\n\n /** A new, unsaved model of this query's class (mass assignment rules apply). */\n newModelInstance(attributes: Row = {}): M {\n return this.model.newInstance(attributes) as M\n }\n\n make(attributes: Row = {}): M {\n return this.newModelInstance(attributes)\n }\n\n async create(attributes: Row = {}): Promise<M> {\n const model = this.newModelInstance(attributes)\n await model.save()\n return model\n }\n\n /** Creates without mass assignment protection. Never pass it request input. */\n async forceCreate(attributes: Row): Promise<M> {\n const model = this.newModelInstance().forceFill(attributes)\n await model.save()\n return model\n }\n\n /** The first match, or a new unsaved model with attributes + values. */\n async firstOrNew(attributes: Row, values: Row = {}): Promise<M> {\n return (await this.clone().where(attributes).first()) ?? this.newModelInstance({ ...attributes, ...values })\n }\n\n /** The first match, or a new saved model. A concurrent insert of the same unique key returns that row instead. */\n async firstOrCreate(attributes: Row, values: Row = {}): Promise<M> {\n return (await this.clone().where(attributes).first()) ?? this.createOrFirst(attributes, values)\n }\n\n /** Tries to create; on a unique constraint violation, returns the existing row (Laravel's createOrFirst()). */\n async createOrFirst(attributes: Row, values: Row = {}): Promise<M> {\n try {\n const connection = this.connection\n const create = () => this.create({ ...attributes, ...values })\n // A failed insert aborts a Postgres transaction, so run it in a savepoint when one is open.\n return connection.transactionLevel() > 0 ? await connection.transaction(create) : await create()\n } catch (error) {\n if (!isUniqueViolation(error)) throw error\n const existing = await this.clone().where(attributes).first()\n if (!existing) throw error\n return existing\n }\n }\n\n /** Updates the first match with values, or creates it. */\n async updateOrCreate(attributes: Row, values: Row = {}): Promise<M> {\n const model = await this.firstOrCreate(attributes, values)\n if (!model.wasRecentlyCreated) await model.fill(values).save()\n return model\n }\n\n /** Mass update (no model events); sets updated_at when the model uses timestamps. */\n override async update(values: Row): Promise<number> {\n return QueryBuilder.prototype.update.call(this.applyScopes(), this.addUpdatedAtColumn(values))\n }\n\n /** Mass delete (no model events). With soft deletes this sets deleted_at on the matching rows instead. */\n override async delete(): Promise<number> {\n if (this.model.usesSoftDeletes()) {\n return this.update({ [this.model.getDeletedAtColumn()]: formatDateTime(this.model.freshTimestamp()) })\n }\n return this.forceDelete()\n }\n\n /** Deletes the matching rows for real, even with soft deletes. */\n async forceDelete(): Promise<number> {\n return QueryBuilder.prototype.delete.call(this.applyScopes())\n }\n\n // ---------------------------------------------------------------- soft deletes\n\n /** Includes soft-deleted rows (withTrashed(false) is withoutTrashed()). */\n withTrashed(withTrashed = true): this {\n return withTrashed ? this.withoutGlobalScope(SoftDeletingScope) : this.withoutTrashed()\n }\n\n /** Excludes soft-deleted rows explicitly. */\n withoutTrashed(): this {\n return super.whereNull(this.model.getQualifiedDeletedAtColumn()).withoutGlobalScope(SoftDeletingScope)\n }\n\n /** Only soft-deleted rows. */\n onlyTrashed(): this {\n return super.whereNotNull(this.model.getQualifiedDeletedAtColumn()).withoutGlobalScope(SoftDeletingScope)\n }\n\n /** Restores every matching row (deleted_at = null), trashed or not. */\n async restore(): Promise<number> {\n return this.withTrashed().update({ [this.model.getDeletedAtColumn()]: null })\n }\n\n protected addUpdatedAtColumn(values: Row): Row {\n const column = this.model.getUpdatedAtColumn()\n if (!this.model.usesTimestamps() || !column || Object.hasOwn(values, column)) return values\n return { ...values, [column]: formatDateTime(this.model.freshTimestamp()) }\n }\n\n // ---------------------------------------------------------------- plumbing\n\n override toSql(): string {\n return QueryBuilder.prototype.toSql.call(this.applyScopes())\n }\n\n override getBindings(): unknown[] {\n return QueryBuilder.prototype.getBindings.call(this.applyScopes())\n }\n\n override clone(): Builder<M> {\n const copy = super.clone() as Builder<M>\n copy.scopes = new Map(this.scopes)\n copy.removedScopes = [...this.removedScopes]\n copy.eagerLoad = new Map(this.eagerLoad)\n copy.selectCasts = { ...this.selectCasts }\n return new Proxy(copy, handler as ProxyHandler<Builder<M>>)\n }\n\n /** Nested where groups get a builder of the same model (without global scopes), so local scopes work inside them. */\n override newQuery(): QueryBuilder<Row> {\n return this.model.newModelQuery() as unknown as QueryBuilder<Row>\n }\n\n /** chunk() and lazy() order by the primary key when the query has no order. */\n protected override enforceOrderBy(): void {\n if (!this.orders.length) this.orderBy(this.model.getQualifiedKeyName() as Column<M>, 'asc')\n }\n\n protected override defaultKeyName(): string {\n return this.model.getKeyName()\n }\n\n protected override defaultPerPage(): number {\n return this.model.getPerPage()\n }\n}\n","/**\n * While eager loading, relation methods are called only to learn the relation's shape, so their per-parent\n * constraints (where post_id = ?) must be skipped (Laravel's Relation::noConstraints()). Relation methods are\n * synchronous, so a counter is enough.\n */\nlet disabled = 0\n\nexport function withoutRelationConstraints<T>(fn: () => T): T {\n disabled++\n try {\n return fn()\n } finally {\n disabled--\n }\n}\n\nexport const relationConstraintsEnabled = (): boolean => disabled === 0\n","import type { Builder } from './Builder'\nimport type { Model } from './Model'\nimport type { Scope } from './Scope'\n\n/**\n * Hides soft-deleted rows: where deleted_at is null. Registered for every model with `softDeletes = true`.\n * Builder.withTrashed()/onlyTrashed()/withoutTrashed() remove or replace it.\n */\nexport class SoftDeletingScope implements Scope {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n apply(builder: Builder<any>, model: Model): void {\n builder.whereNull(model.getQualifiedDeletedAtColumn())\n }\n}\n","import { isDeepStrictEqual } from 'node:util'\nimport type { Row } from '@orieljs/contracts'\nimport { Collection } from '@orieljs/collections'\nimport { InvalidCastError, LogicError } from '../errors'\nimport { formatDate, formatDateTime, parseDateTime } from '../Query/values'\n\n/**\n * A custom cast (Laravel's CastsAttributes): get() turns the stored value into what the model exposes, set() turns\n * an assigned value back into what is stored.\n */\nexport interface CastsAttributes<TGet = unknown, TSet = TGet> {\n get(model: object, key: string, value: unknown, attributes: Row): TGet\n set(model: object, key: string, value: TSet, attributes: Row): unknown\n}\n\n/** A TypeScript enum object (string or numeric) used as a cast: casts = { status: PostStatus }. */\nexport type EnumLike = Record<string, string | number>\n\nexport type BuiltInCast =\n | 'int' | 'integer' | 'float' | 'double' | 'real' | 'string' | 'bool' | 'boolean'\n | 'array' | 'json' | 'object' | 'collection'\n | 'date' | 'datetime' | 'immutable_date' | 'immutable_datetime' | 'timestamp'\n | 'hashed'\n | `decimal:${number}`\n\nexport type CastDefinition = BuiltInCast | EnumLike | CastsAttributes | (new () => CastsAttributes)\n\nconst JSON_CASTS = new Set(['array', 'json', 'object', 'collection'])\nconst DATE_CASTS = new Set(['date', 'datetime', 'immutable_date', 'immutable_datetime'])\nconst PRIMITIVE_CASTS = new Set(['int', 'integer', 'float', 'double', 'real', 'string', 'bool', 'boolean', 'timestamp'])\n/** Laravel's hashed cast: the model hashes the assigned value when it is saved (Model.save()). */\nconst HASHED_CAST = 'hashed'\n\nconst isCustom = (cast: CastDefinition): cast is CastsAttributes =>\n typeof cast === 'object' && typeof (cast as Partial<CastsAttributes>).get === 'function' && typeof (cast as Partial<CastsAttributes>).set === 'function'\n\nconst isCustomClass = (cast: CastDefinition): cast is new () => CastsAttributes => typeof cast === 'function'\n\nconst isEnum = (cast: CastDefinition): cast is EnumLike => typeof cast === 'object' && !isCustom(cast)\n\n/** Builds the custom cast instance for a class-valued cast (cached per class). */\nconst instances = new WeakMap<new () => CastsAttributes, CastsAttributes>()\nfunction customCaster(cast: CastsAttributes | (new () => CastsAttributes)): CastsAttributes {\n if (!isCustomClass(cast)) return cast\n let instance = instances.get(cast)\n if (!instance) instances.set(cast, (instance = new cast()))\n return instance\n}\n\n/** The values of a TypeScript enum. Numeric enums also map values back to names; those reverse entries are skipped. */\nexport function enumValues(cast: EnumLike): Array<string | number> {\n return Object.entries(cast)\n .filter(([key]) => !/^\\d+$/.test(key))\n .map(([, value]) => value)\n}\n\nexport const isJsonCast = (cast: CastDefinition | undefined): boolean => typeof cast === 'string' && JSON_CASTS.has(cast)\nexport const isDateCast = (cast: CastDefinition | undefined): boolean => typeof cast === 'string' && DATE_CASTS.has(cast)\nexport const isHashedCast = (cast: CastDefinition | undefined): boolean => cast === HASHED_CAST\n/** A cast whose value is a class instance, so dirty checks and serialization go through custom logic. */\nexport const isCustomCast = (cast: CastDefinition | undefined): boolean => cast !== undefined && (isCustom(cast) || isCustomClass(cast))\n\nconst decimalPlaces = (cast: string): number | undefined => (cast.startsWith('decimal:') ? Number(cast.slice(8)) : undefined)\n\nconst isBuiltInCast = (cast: string): boolean =>\n JSON_CASTS.has(cast) || DATE_CASTS.has(cast) || PRIMITIVE_CASTS.has(cast) || cast === HASHED_CAST || /^decimal:\\d+$/.test(cast)\n\n/** Throws InvalidCastError for a cast string that isn't one of the built-in casts. */\nfunction assertBuiltInCast(cast: string, key: string, className: string): void {\n if (!isBuiltInCast(cast)) throw new InvalidCastError(className, key, cast)\n}\n\nconst toBoolean = (value: unknown): boolean => {\n if (typeof value === 'boolean') return value\n if (typeof value === 'number' || typeof value === 'bigint') return Number(value) !== 0\n const text = String(value).toLowerCase()\n return !(text === '' || text === '0' || text === 'f' || text === 'false')\n}\n\n/** Laravel's castAttribute(): the stored value → the value the model exposes. null stays null (except custom casts). */\nexport function castGet(model: object, key: string, cast: CastDefinition, value: unknown, attributes: Row, className: string): unknown {\n if (isCustom(cast) || isCustomClass(cast)) return customCaster(cast).get(model, key, value, attributes)\n if (typeof cast === 'string') assertBuiltInCast(cast, key, className)\n if (value === null || value === undefined) return value\n if (isEnum(cast)) {\n const allowed = enumValues(cast)\n const match = allowed.find((candidate) => candidate === value || String(candidate) === String(value))\n if (match === undefined) throw new LogicError(`\"${String(value)}\" is not a valid backing value for the cast of [${key}] on [${className}].`)\n return match\n }\n const places = decimalPlaces(cast)\n if (places !== undefined) return Number(value).toFixed(places)\n switch (cast) {\n case 'int': case 'integer':\n return Math.trunc(Number(value))\n case 'float': case 'double': case 'real':\n return Number(value)\n case 'string':\n return String(value)\n case 'bool': case 'boolean':\n return toBoolean(value)\n case 'array': case 'json': case 'object':\n // Postgres and MySQL drivers hand back json columns already parsed; copy them so the original stays intact.\n return typeof value === 'string' ? JSON.parse(value) : structuredClone(value)\n case 'collection':\n return new Collection((typeof value === 'string' ? JSON.parse(value) : structuredClone(value)) as unknown[])\n case 'date': case 'immutable_date': {\n const date = parseDateTime(value)\n date.setUTCHours(0, 0, 0, 0)\n return date\n }\n case 'datetime': case 'immutable_datetime':\n return parseDateTime(value)\n case 'timestamp':\n return Math.floor(parseDateTime(value).getTime() / 1000)\n }\n return value\n}\n\n/** The value assigned to a cast attribute → the value stored in the model's attributes (and later bound). */\nexport function castSet(model: object, key: string, cast: CastDefinition, value: unknown, attributes: Row, className: string): unknown {\n if (isCustom(cast) || isCustomClass(cast)) return customCaster(cast).set(model, key, value, attributes)\n if (typeof cast === 'string') assertBuiltInCast(cast, key, className)\n if (value === null || value === undefined) return null\n if (isEnum(cast)) return castGet(model, key, cast, value, attributes, className)\n if (typeof cast !== 'string') return value\n if (JSON_CASTS.has(cast)) return JSON.stringify(value instanceof Collection ? value.all() : value)\n if (cast === 'date' || cast === 'immutable_date') return formatDate(parseDateTime(value))\n if (cast === 'datetime' || cast === 'immutable_datetime') return formatDateTime(parseDateTime(value))\n if (cast === 'timestamp') return formatDateTime(typeof value === 'number' ? new Date(value * 1000) : parseDateTime(value))\n return value\n}\n\n/**\n * Laravel's originalIsEquivalent(): does the stored value still mean the same thing as the original?\n * Keeps save() from writing columns whose value only changed representation (1 vs true, '5' vs 5, same instant).\n */\nexport function isEquivalent(cast: CastDefinition | undefined, current: unknown, original: unknown, model: object, key: string, className: string): boolean {\n if (current === original) return true\n if (current === null || current === undefined || original === null || original === undefined) return false\n if (cast !== undefined) {\n if (isDateCast(cast) || cast === 'timestamp') {\n return parseDateTime(current).getTime() === parseDateTime(original).getTime()\n }\n if (typeof cast === 'string' && ['float', 'double', 'real'].includes(cast)) {\n return Math.abs(Number(current) - Number(original)) < Number.EPSILON * 4\n }\n const read = (value: unknown) => castGet(model, key, cast, value, {}, className)\n if (typeof cast === 'string' && (JSON_CASTS.has(cast) || PRIMITIVE_CASTS.has(cast) || cast.startsWith('decimal:'))) {\n const a = read(current)\n const b = read(original)\n return isDeepStrictEqual(a instanceof Collection ? a.all() : a, b instanceof Collection ? b.all() : b)\n }\n if (isEnum(cast)) return String(current) === String(original)\n }\n const numeric = (value: unknown) => (typeof value === 'number' || (typeof value === 'string' && value.trim() !== '' && !Number.isNaN(Number(value))))\n return numeric(current) && numeric(original) && Number(current) === Number(original)\n}\n","import { Collection, type Operator } from '@orieljs/collections'\nimport { LogicError, ModelNotFoundError } from '../errors'\nimport type { Expression } from '../Query/Expression'\nimport type { Builder, EagerLoadSpec } from './Builder'\nimport type { Model } from './Model'\nimport type { Column } from './types'\n\n/** Laravel's getDictionaryKey(): keys compare as text, so 1 and '1' are the same model. */\nconst dictionaryKey = (key: unknown): string => String(key)\n\nconst isModel = (value: unknown): value is Model =>\n typeof value === 'object' && value !== null && typeof (value as Partial<Model>).getKey === 'function' &&\n typeof (value as Partial<Model>).relationLoaded === 'function'\n\n/**\n * One model per key, in the models' order: a key keeps its first position and its last instance, as a PHP array\n * keyed by the model keys does (a plain object would list integer-like keys first, in ascending order).\n */\nfunction uniqueByKey<M extends Model>(models: readonly M[]): M[] {\n return [...new Map(models.map((model) => [dictionaryKey(model.getKey()), model])).values()]\n}\n\n/** The models a loaded relation holds: a collection's models, a model, or none. */\nfunction relatedModels(value: unknown): Model[] {\n if (value instanceof Collection) return (value.all() as unknown[]).filter(isModel)\n return isModel(value) ? [value] : []\n}\n\n/**\n * Laravel's Eloquent collection: what every query, relation and eager load of models returns. It is a support\n * Collection (methods that keep the items keep this class; map() and the other type-changing methods return a plain\n * Collection) with the model-aware methods: find() by key, load() and loadCount() for every model at once, fresh(),\n * modelKeys(), toQuery(), and diff()/intersect()/unique()/only()/except()/merge() that compare models by key.\n */\nexport class EloquentCollection<M extends Model = Model> extends Collection<M> {\n /** The model with this key (or this model's key), else the default; with several keys, those models. */\n find(key: readonly unknown[] | Collection<unknown>): this\n find(key: unknown): M | undefined\n find<D>(key: unknown, defaultValue: D): M | D\n find(key: unknown, defaultValue?: unknown): unknown {\n const value = isModel(key) ? key.getKey() : key instanceof Collection ? key.all() : key\n if (Array.isArray(value)) {\n const wanted = new Set(value.map(dictionaryKey))\n return this.filter((model) => wanted.has(dictionaryKey(model.getKey())))\n }\n return this.first((model) => dictionaryKey(model.getKey()) === dictionaryKey(value), defaultValue)\n }\n\n /** find(), or ModelNotFoundError naming the missing keys. */\n findOrFail(keys: readonly unknown[] | Collection<unknown>): this\n findOrFail(key: unknown): M\n findOrFail(key: unknown): M | this {\n const value = key instanceof Collection ? key.all() : key\n if (Array.isArray(value)) {\n const found = this.find(value)\n const keys = [...new Map(value.map((id) => [dictionaryKey(id), id])).values()]\n if (found.count() === keys.length) return found\n const present = new Set(found.modelKeys().map(dictionaryKey))\n throw new ModelNotFoundError(this.first()?.constructor.name ?? 'Model', keys.filter((id) => !present.has(dictionaryKey(id))))\n }\n const model = this.find(value)\n if (model !== undefined) return model\n throw new ModelNotFoundError(this.first()?.constructor.name ?? 'Model', [isModel(value) ? value.getKey() : value])\n }\n\n /** The primary keys, in order. */\n modelKeys(): unknown[] {\n return this.items.map((model) => model.getKey())\n }\n\n /** The models keyed by their primary key (as text). */\n getDictionary(items: Iterable<M> = this.items): Record<string, M> {\n const dictionary: Record<string, M> = {}\n for (const model of items) dictionary[dictionaryKey(model.getKey())] = model\n return dictionary\n }\n\n /** The same models in a plain Collection. */\n toBase(): Collection<M> {\n return new Collection(this.items)\n }\n\n /** Whether a model with this key (or this model) is in the collection; the other forms are Collection's. */\n override contains(key: keyof M & string, value: unknown): boolean\n override contains(key: (keyof M & string) | ((item: M) => unknown), operator: Operator, value: unknown): boolean\n override contains(callback: (item: M) => boolean): boolean\n override contains(value: unknown): boolean\n override contains(...args: unknown[]): boolean {\n if (args.length > 1 || typeof args[0] === 'function') return Reflect.apply(Collection.prototype.contains, this, args) as boolean\n const [key] = args\n if (isModel(key)) return this.items.some((model) => model.is(key))\n return this.items.some((model) => dictionaryKey(model.getKey()) === dictionaryKey(key))\n }\n\n /** Collection's containsStrict(): a model matches only itself (no key matching). */\n override containsStrict(key: keyof M & string, value: unknown): boolean\n override containsStrict(callback: (item: M) => boolean): boolean\n override containsStrict(value: unknown): boolean\n override containsStrict(...args: unknown[]): boolean {\n return Reflect.apply(Collection.prototype.contains, this, args) as boolean\n }\n\n /** Collection's doesntContainStrict(): a model matches only itself (no key matching). */\n override doesntContainStrict(key: keyof M & string, value: unknown): boolean\n override doesntContainStrict(callback: (item: M) => boolean): boolean\n override doesntContainStrict(value: unknown): boolean\n override doesntContainStrict(...args: unknown[]): boolean {\n return !(Reflect.apply(Collection.prototype.contains, this, args) as boolean)\n }\n\n /** Eager loads relations onto every model, one query per relation: await posts.load('author', 'comments.author'). */\n async load(...relations: EagerLoadSpec[]): Promise<this> {\n const first = this.first()\n if (!first || !relations.length) return this\n await first.newQueryWithoutRelationships().with(...relations).eagerLoadRelations(this.items)\n return this\n }\n\n /** Loads only the relations that aren't loaded yet; nested paths are followed into the loaded relations. */\n async loadMissing(...relations: string[]): Promise<this> {\n await loadMissingOn(this.items, relations)\n return this\n }\n\n /** Adds <relation>_count attributes to every model with one query: await posts.loadCount('comments'). */\n loadCount(...relations: EagerLoadSpec[]): Promise<this> {\n return this.loadAggregate(relations, '*', 'count')\n }\n\n /**\n * Laravel's loadAggregate(): withAggregate() for models already loaded, with one query for the whole collection.\n * The values become clean attributes (with their casts: loadExists() gives booleans).\n */\n async loadAggregate(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression, fn?: string): Promise<this> {\n const first = this.first()\n if (!first || ![relations].flat().length) return this\n const keyName = first.getKeyName()\n const rows = await first.newModelQuery().whereKey(this.modelKeys()).select(keyName as Column<M>).withAggregate(relations, column, fn).get()\n const byKey = new Map(rows.all().map((row) => [dictionaryKey(row.getKey()), row]))\n for (const model of this.items) {\n const row = byKey.get(dictionaryKey(model.getKey()))\n if (!row) continue\n const values = Object.fromEntries(Object.entries(row.getAttributes()).filter(([name]) => name !== keyName))\n const casts = Object.fromEntries(Object.entries(row.getCasts()).filter(([name]) => Object.hasOwn(values, name)))\n model.forceFill(values).syncOriginalAttributes(...Object.keys(values)).mergeCasts(casts)\n }\n return this\n }\n\n /** Adds <relation>_sum_<column> to every model: await users.loadSum('orders', 'price'). */\n loadSum(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): Promise<this> {\n return this.loadAggregate(relations, column, 'sum')\n }\n\n loadAvg(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): Promise<this> {\n return this.loadAggregate(relations, column, 'avg')\n }\n\n loadMin(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): Promise<this> {\n return this.loadAggregate(relations, column, 'min')\n }\n\n loadMax(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): Promise<this> {\n return this.loadAggregate(relations, column, 'max')\n }\n\n /** Adds a boolean <relation>_exists to every model. */\n loadExists(...relations: EagerLoadSpec[]): Promise<this> {\n return this.loadAggregate(relations, '*', 'exists')\n }\n\n /** The models as they are in the database now (without global scopes), with relations loaded; deleted ones drop out. */\n async fresh(...relations: EagerLoadSpec[]): Promise<this> {\n const first = this.first()\n if (!first) return this.newInstance()\n const fresh = this.getDictionary(await first.newQueryWithoutScopes().with(...relations).whereKey(this.modelKeys()).get())\n const models: M[] = []\n for (const model of this.items) {\n const found = model.exists ? fresh[dictionaryKey(model.getKey())] : undefined\n if (found) models.push(found)\n }\n return this.newInstance(models)\n }\n\n /** The models whose keys aren't in the given models. */\n override diff(items: Iterable<M>): this {\n const other = this.getDictionary(items)\n return this.filter((model) => !Object.hasOwn(other, dictionaryKey(model.getKey())))\n }\n\n /** The models whose keys are also in the given models. */\n override intersect(items: Iterable<M>): this {\n const other = this.getDictionary(items)\n return this.filter((model) => Object.hasOwn(other, dictionaryKey(model.getKey())))\n }\n\n /** One model per key (the last instance, at the first one's place); with a key or callback, Collection's unique(). */\n override unique(key?: (keyof M & string) | ((item: M) => unknown)): this {\n if (key !== undefined) return super.unique(key)\n return this.newInstance(uniqueByKey(this.items))\n }\n\n /** The models with these keys, in the collection's order. */\n override only(...keys: unknown[]): this {\n const wanted = new Set(keys.flat().map(dictionaryKey))\n return this.newInstance(uniqueByKey(this.items).filter((model) => wanted.has(dictionaryKey(model.getKey()))))\n }\n\n /** The models without these keys, in the collection's order. */\n override except(...keys: unknown[]): this {\n const unwanted = new Set(keys.flat().map(dictionaryKey))\n return this.newInstance(uniqueByKey(this.items).filter((model) => !unwanted.has(dictionaryKey(model.getKey()))))\n }\n\n /** Adds the given models, replacing the ones with the same key. */\n override merge(items: Iterable<M>): this {\n const dictionary = new Map(this.items.map((model) => [dictionaryKey(model.getKey()), model]))\n for (const model of items) dictionary.set(dictionaryKey(model.getKey()), model)\n return this.newInstance(dictionary.values())\n }\n\n makeHidden(...attributes: Array<string | string[]>): this {\n for (const model of this.items) model.makeHidden(...attributes)\n return this\n }\n\n makeVisible(...attributes: Array<string | string[]>): this {\n for (const model of this.items) model.makeVisible(...attributes)\n return this\n }\n\n setVisible(visible: string[]): this {\n for (const model of this.items) model.setVisible(visible)\n return this\n }\n\n setHidden(hidden: string[]): this {\n for (const model of this.items) model.setHidden(hidden)\n return this\n }\n\n append(...attributes: Array<string | string[]>): this {\n for (const model of this.items) model.append(...attributes)\n return this\n }\n\n /** A query of exactly these models (where key in …), for mass updates: await posts.toQuery().update({ … }). */\n toQuery(): Builder<M> {\n const first = this.first()\n if (!first) throw new LogicError('Unable to create query for empty collection.')\n if (this.items.some((model) => model.constructor !== first.constructor)) {\n throw new LogicError('Unable to create query for collection with mixed types.')\n }\n return first.newModelQuery().whereKey(this.modelKeys())\n }\n}\n\n/** loadMissing() for some models: loads each path's first relation where it is missing, then follows the rest. */\nasync function loadMissingOn(models: Model[], paths: string[]): Promise<void> {\n for (const path of paths) {\n const [head = '', ...rest] = path.split('.')\n const missing = models.filter((model) => !model.relationLoaded(head))\n if (missing.length) await missing[0]!.newQueryWithoutRelationships().with(path).eagerLoadRelations(missing)\n if (!rest.length) continue\n const related = models.flatMap((model) => relatedModels(model.getRelations()[head]))\n if (related.length) await loadMissingOn(related, [rest.join('.')])\n }\n}\n","import { existsSync, readdirSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport type { Row } from '@orieljs/contracts'\nimport { Collection } from '@orieljs/collections'\nimport { Str } from '@orieljs/support'\nimport { LogicError } from '../../errors'\nimport { formatDateTime } from '../../Query/values'\nimport { Model } from '../Model'\nimport { BelongsTo } from '../Relations/BelongsTo'\nimport { BelongsToMany } from '../Relations/BelongsToMany'\nimport { HasOneOrMany } from '../Relations/HasOneOrMany'\nimport { MorphTo } from '../Relations/MorphTo'\n\ndeclare const MANY: unique symbol\n/** Type-level marker set by count(): make()/create() then return a Collection. */\nexport interface Many {\n readonly [MANY]: true\n}\n/** What make()/create() return: a model, or a Collection after count(). */\nexport type FactoryResult<F, M> = F extends Many ? Collection<M> : M\n/** What raw() returns: the attributes, or a list of them after count(). */\nexport type RawResult<F> = F extends Many ? Row[] : Row\n\n/** Which model a state is being made for: its index in count() and the total. */\nexport interface StateContext {\n index: number\n count: number\n}\nexport type State = Row | ((attributes: Row, context: StateContext) => Row)\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyFactory = Factory<any>\n\n/**\n * What has() and for() need from a factory: its model, create(), createOne() and state(). A factory of any model,\n * counted or not, has them; Factory<any> itself would refuse a counted one, whose make(), create() and raw() return\n * lists.\n */\nexport interface RelatedFactory {\n readonly model: new () => Model\n create(attributes?: Row): Promise<unknown>\n createOne(attributes?: Row): Promise<Model>\n state(state: State): RelatedFactory\n}\n\n/**\n * A model's factory() typed as its own factory class (Laravel's `@use HasFactory<UserFactory>`): declare it in the\n * model, `declare static factory: HasFactory<UserFactory>` (with `import type`), and User.factory().unverified()\n * type-checks. The factory is still found at run time by name (database/factories/UserFactory.ts).\n */\nexport type HasFactory<F> = {\n (): F\n (count: number, state?: State): F & Many\n} & (typeof Model)['factory']\n\ninterface HasRelationship {\n factory: RelatedFactory\n relationship: string\n pivot: Row\n}\n\ninterface ForRelationship {\n parent: RelatedFactory | Model\n relationship: string\n}\n\n/** The for() parents one make()/create()/raw() call has resolved: shared by that call's models, made again by the next. */\ntype ResolvedParents = Map<ForRelationship, Model>\n\n/** The builder state newInstance() copies and changes. */\ninterface FactoryState<M extends Model> {\n countValue: number | undefined\n states: State[]\n hasRelations: HasRelationship[]\n forRelations: ForRelationship[]\n afterMakingCallbacks: Array<(model: M) => unknown>\n afterCreatingCallbacks: Array<(model: M) => unknown>\n}\n\nconst registry = new Map<typeof Model, new () => AnyFactory>()\n\n/**\n * Laravel's model factories: `class UserFactory extends Factory<User> { model = User; definition() { … } }`,\n * then `await User.factory().count(3).create()`, `UserFactory.new().unverified().make()`.\n * Every builder method returns a new factory, so a base factory can be reused.\n */\nexport abstract class Factory<M extends Model = Model> {\n /** The model class this factory makes. */\n abstract model: new () => M\n\n /** The default attributes. Values may be factories (created for their key) or (attributes) => value functions. */\n abstract definition(): Row\n\n protected countValue: number | undefined\n protected states: State[] = []\n protected hasRelations: HasRelationship[] = []\n protected forRelations: ForRelationship[] = []\n protected afterMakingCallbacks: Array<(model: M) => unknown> = []\n protected afterCreatingCallbacks: Array<(model: M) => unknown> = []\n\n /** A new factory with the given state (Laravel's Factory::new()). */\n static new<F extends AnyFactory>(this: new () => F, state?: State): F {\n const factory = new this().configure() as F\n return state ? factory.state(state) : factory\n }\n\n /** Registers factory classes for Model.factory() (discoverFactories() does this for database/factories). */\n static register(...factories: Array<new () => AnyFactory>): void {\n for (const factory of factories) registry.set(new factory().model as unknown as typeof Model, factory)\n }\n\n /** The registered factory for a model class. */\n static forModel<M extends Model>(model: new () => M): Factory<M> {\n const factory = registry.get(model as unknown as typeof Model)\n if (!factory) {\n throw new LogicError(`No factory registered for [${model.name}]. Add database/factories/${model.name}Factory.ts (default export) or call Factory.register().`)\n }\n return new factory().configure() as unknown as Factory<M>\n }\n\n /** Hook for afterMaking()/afterCreating() registrations; runs in new(). */\n configure(): this {\n return this\n }\n\n /** How many models make()/create() produce; they then return a Collection. */\n count(count: number): this & Many {\n return this.newInstance({ countValue: count }) as this & Many\n }\n\n /** Overrides attributes: state({ admin: true }) or state((attributes) => ({ … })). */\n state(state: State): this {\n return this.newInstance({ states: [...this.states, state] })\n }\n\n /** Cycles through states per model: sequence({ role: 'admin' }, { role: 'user' }). */\n sequence(...states: State[]): this {\n return this.state((attributes, context) => {\n const state = states[context.index % states.length]!\n return typeof state === 'function' ? state(attributes, context) : state\n })\n }\n\n /** deleted_at = now, for soft-deleting models. */\n trashed(): this {\n return this.state((_attributes) => ({ [new this.model().getDeletedAtColumn()]: formatDateTime(new Date()) }))\n }\n\n /** Creates related models for each created model: has(Post.factory().count(3)) (relationship default: 'posts'). */\n has(factory: RelatedFactory, relationship?: string, pivot: Row = {}): this {\n const name = relationship ?? Str.camel(Str.plural(new factory.model().constructor.name))\n return this.newInstance({ hasRelations: [...this.hasRelations, { factory, relationship: name, pivot }] })\n }\n\n /**\n * Sets a belongsTo parent: for(User.factory()) or for(user) (relationship default: 'user'). A factory parent is made\n * once per make()/create() call, for all of its models, and again by the next call, so a factory kept in a variable\n * never points at a parent an earlier test rolled back.\n */\n for(parent: RelatedFactory | Model, relationship?: string): this {\n const cls = parent instanceof Model ? parent.constructor : new parent.model().constructor\n return this.newInstance({ forRelations: [...this.forRelations, { parent, relationship: relationship ?? Str.camel(cls.name) }] })\n }\n\n afterMaking(callback: (model: M) => unknown): this {\n return this.newInstance({ afterMakingCallbacks: [...this.afterMakingCallbacks, callback] })\n }\n\n afterCreating(callback: (model: M) => unknown): this {\n return this.newInstance({ afterCreatingCallbacks: [...this.afterCreatingCallbacks, callback] })\n }\n\n /** The attributes only, without a model (a Row, or a Row[] after count()). */\n async raw(attributes: Row = {}): Promise<RawResult<this>> {\n const rows: Row[] = []\n const parents: ResolvedParents = new Map()\n for (let index = 0; index < (this.countValue ?? 1); index++) rows.push(await this.attributesFor(attributes, index, parents))\n return (this.countValue === undefined ? rows[0]! : rows) as RawResult<this>\n }\n\n /** Unsaved models (afterMaking callbacks run). */\n async make(attributes: Row = {}): Promise<FactoryResult<this, M>> {\n const models = await this.makeModels(attributes)\n return this.result(models)\n }\n\n /** Saved models, with their has() relations (afterCreating callbacks run). */\n async create(attributes: Row = {}): Promise<FactoryResult<this, M>> {\n const models = await this.makeModels(attributes)\n for (const model of models) {\n await model.save()\n await this.createChildren(model)\n for (const callback of this.afterCreatingCallbacks) await callback(model)\n }\n return this.result(models)\n }\n\n async makeOne(attributes: Row = {}): Promise<M> {\n return (await this.newInstance({ countValue: undefined }).makeModels(attributes))[0]!\n }\n\n async createOne(attributes: Row = {}): Promise<M> {\n return (await this.newInstance({ countValue: undefined }).create(attributes)) as M\n }\n\n /** One model per record (or `count` models). */\n async createMany(records: number | Row[]): Promise<Collection<M>> {\n const list = typeof records === 'number' ? Array.from({ length: records }, () => ({})) : records\n const created: M[] = []\n for (const record of list) created.push(await this.createOne(record))\n return new Collection(created)\n }\n\n protected newInstance(changes: Partial<FactoryState<M>>): this {\n const copy = Object.create(Object.getPrototypeOf(this) as object) as this\n Object.assign(copy, this, changes)\n return copy\n }\n\n protected async makeModels(attributes: Row): Promise<M[]> {\n const models: M[] = []\n const parents: ResolvedParents = new Map()\n for (let index = 0; index < (this.countValue ?? 1); index++) {\n const model = new this.model().forceFill(await this.attributesFor(attributes, index, parents))\n for (const callback of this.afterMakingCallbacks) await callback(model)\n models.push(model)\n }\n return models\n }\n\n /** definition() + states + overrides + for() parents, with factory and function values expanded. */\n protected async attributesFor(overrides: Row, index: number, parents: ResolvedParents = new Map()): Promise<Row> {\n const context: StateContext = { index, count: this.countValue ?? 1 }\n let attributes: Row = this.definition()\n for (const state of this.states) attributes = { ...attributes, ...(typeof state === 'function' ? state(attributes, context) : state) }\n attributes = { ...attributes, ...overrides }\n for (const parent of this.forRelations) Object.assign(attributes, await this.parentAttributes(parent, parents))\n const expanded: Row = {}\n for (const [key, value] of Object.entries(attributes)) {\n if (value instanceof Factory) expanded[key] = (await value.createOne()).getKey()\n else if (value instanceof Model) expanded[key] = value.getKey()\n else if (typeof value === 'function') expanded[key] = (value as (attributes: Row) => unknown)(attributes)\n else expanded[key] = value\n }\n return expanded\n }\n\n private async parentAttributes(parent: ForRelationship, parents: ResolvedParents): Promise<Row> {\n let resolved = parents.get(parent)\n if (resolved === undefined) {\n resolved = parent.parent instanceof Model ? parent.parent : ((await parent.parent.createOne()) as Model)\n parents.set(parent, resolved)\n }\n const relation = this.relationOn(new this.model(), parent.relationship)\n if (relation instanceof MorphTo) {\n return { [relation.getForeignKeyName()]: resolved.getKey(), [relation.getMorphType()]: resolved.getMorphClass() }\n }\n if (relation instanceof BelongsTo) return { [relation.getForeignKeyName()]: resolved.getAttribute(relation.getOwnerKeyName()) }\n throw new LogicError(`for() needs a belongsTo or morphTo relation; [${parent.relationship}] is neither.`)\n }\n\n private async createChildren(model: M): Promise<void> {\n for (const { factory, relationship, pivot } of this.hasRelations) {\n const relation = this.relationOn(model, relationship)\n if (relation instanceof BelongsToMany) {\n const related = await factory.create()\n await relation.attach(related instanceof Collection ? related.all() : (related as Model), pivot)\n } else if (relation instanceof HasOneOrMany) {\n const foreign: Row = { [relation.getForeignKeyName()]: relation.getParentKey() }\n if (relation.morph) foreign[relation.getMorphType()!] = relation.getMorphClass()\n await factory.state(foreign).create()\n } else {\n throw new LogicError(`has() needs a hasOne, hasMany, morphMany or belongsToMany relation; [${relationship}] is none of them.`)\n }\n }\n }\n\n private relationOn(model: Model, relationship: string) {\n return model.getRelationInstance(relationship)\n }\n\n private result(models: M[]): FactoryResult<this, M> {\n return (this.countValue === undefined ? models[0] : new Collection(models)) as FactoryResult<this, M>\n }\n}\n\n/** Imports every factory file in a directory and registers its exported Factory classes. */\nexport async function discoverFactories(path: string): Promise<void> {\n if (!existsSync(path)) return\n for (const file of readdirSync(path).sort()) {\n if (!/\\.(ts|js|mts|mjs)$/.test(file) || /\\.d\\.[mc]?ts$/.test(file)) continue\n const module = (await import(pathToFileURL(join(path, file)).href)) as Record<string, unknown>\n for (const exported of Object.values(module)) {\n if (typeof exported === 'function' && exported.prototype instanceof Factory) {\n Factory.register(exported as unknown as new () => AnyFactory)\n }\n }\n }\n}\n","import { Str } from '@orieljs/support'\nimport type { ColumnRef } from '../../Query/Builder'\nimport type { Builder } from '../Builder'\nimport type { Model } from '../Model'\nimport type { Column } from '../types'\nimport { Relation } from './Relation'\n\n/** post.author(): this model (the child) holds the related model's key. */\nexport class BelongsTo<R extends Model, P extends Model = Model> extends Relation<R, P, R | null> {\n /**\n * @param foreignKey the column on the child ('user_id')\n * @param ownerKey the key on the related model it points at ('id')\n */\n constructor(\n related: R,\n child: P,\n readonly foreignKey: string,\n readonly ownerKey: string,\n relationName?: string,\n ) {\n super(related, child)\n this.relationName = relationName\n this.init()\n }\n\n getChild(): P {\n return this.parent\n }\n\n getForeignKeyName(): string {\n return this.foreignKey\n }\n\n getQualifiedForeignKeyName(): string {\n return this.parent.qualifyColumn(this.foreignKey)\n }\n\n getOwnerKeyName(): string {\n return this.ownerKey\n }\n\n getQualifiedOwnerKeyName(): string {\n return this.model.qualifyColumn(this.ownerKey)\n }\n\n addConstraints(): void {\n this.where(this.getQualifiedOwnerKeyName() as Column<R>, '=', this.parent.getAttribute(this.foreignKey))\n }\n\n addEagerConstraints(models: P[]): void {\n this.whereIn(this.getQualifiedOwnerKeyName() as Column<R>, this.keysOf(models, this.foreignKey))\n }\n\n async getResults(): Promise<R | null> {\n const key = this.parent.getAttribute(this.foreignKey)\n if (key === null || key === undefined) return null\n return (await this.first()) ?? null\n }\n\n initRelation(models: P[], relation: string): P[] {\n for (const model of models) model.setRelation(relation, null)\n return models\n }\n\n match(models: P[], results: R[], relation: string): P[] {\n const owners = new Map(results.map((result) => [String(result.getAttribute(this.ownerKey)), result]))\n for (const model of models) model.setRelation(relation, owners.get(String(model.getAttribute(this.foreignKey))) ?? null)\n return models\n }\n\n /** Points the child at `model` (sets the foreign key and the loaded relation). Save the child afterwards. */\n associate(model: R | null): P {\n this.parent.setAttribute(this.foreignKey, model === null ? null : model.getAttribute(this.ownerKey))\n this.parent.setRelation(this.relationKey(), model)\n return this.parent\n }\n\n /** Clears the foreign key. Save the child afterwards. */\n dissociate(): P {\n return this.associate(null)\n }\n\n getRelationExistenceQuery(query: Builder<R>, _parentQuery: Builder<P>, columns: ColumnRef[] = ['*']): Builder<R> {\n this.aliasSelfTable(query)\n return query.select(...(columns as Array<Column<R>>)).whereColumn(this.getQualifiedForeignKeyName(), '=', this.getQualifiedOwnerKeyName())\n }\n\n /** The loaded-relation name: the resolved name, else the related class in camelCase (author → pass it explicitly). */\n private relationKey(): string {\n return this.relationName ?? Str.camel(this.model.constructor.name)\n }\n}\n","import { ClassRegistry } from '@orieljs/contracts'\nimport { currentContainer } from '@orieljs/container'\nimport { LogicError } from '../../errors'\nimport type { Model } from '../Model'\n\nconst aliases = new Map<string, typeof Model>()\nconst booted = new Map<string, typeof Model>()\n/** The Model base class, handed over by Model.ts once it is defined (importing it here would be a circular import). */\nlet modelBase: typeof Model | undefined\n\nexport function setModelBaseClass(base: typeof Model): void {\n modelBase = base\n}\n\n/**\n * The morph map: the value stored in `*_type` columns for each model class (Laravel's Relation::morphMap()).\n * Without an entry the class name is stored ('Post'). Returns the current map.\n */\nexport function morphMap(map?: Record<string, typeof Model>, merge = true): Record<string, typeof Model> {\n if (map) {\n if (!merge) aliases.clear()\n for (const [alias, model] of Object.entries(map)) aliases.set(alias, model)\n }\n return Object.fromEntries(aliases)\n}\n\n/** The model class for a morph map alias, if mapped. */\nexport function getMorphedModel(alias: string): typeof Model | undefined {\n return aliases.get(alias)\n}\n\n/** The morph map alias of a class, if mapped. */\nexport function getMorphAlias(model: typeof Model): string | undefined {\n for (const [alias, candidate] of aliases) if (candidate === model) return alias\n return undefined\n}\n\n/** Remembers a booted model class by name, so morphTo can find it without a morph map entry. */\nexport function rememberModelClass(model: typeof Model): void {\n booted.set(model.name, model)\n}\n\n/** The class for a stored morph type: the morph map, then the ClassRegistry (discovered models), then booted models. */\nexport function resolveMorphClass(type: string): typeof Model {\n const mapped = aliases.get(type)\n if (mapped) return mapped\n const container = currentContainer()\n if (container?.bound(ClassRegistry)) {\n const registry = container.make(ClassRegistry)\n if (registry.has(type)) {\n const cls = registry.resolve(type)\n if (!modelBase || !(cls.prototype instanceof modelBase)) throw new LogicError(`Class [${type}] is not a model, so it can't be the type of a morphTo relation.`)\n return cls as unknown as typeof Model\n }\n }\n const known = booted.get(type)\n if (known) return known\n throw new LogicError(`Class [${type}] not found for a morphTo relation. Add it to Relation.morphMap().`)\n}\n","import type { Collection } from '@orieljs/collections'\nimport type { ColumnRef } from '../../Query/Builder'\nimport { Expression } from '../../Query/Expression'\nimport { Builder } from '../Builder'\nimport type { Model } from '../Model'\nimport { relationConstraintsEnabled } from './constraints'\nimport { getMorphedModel, morphMap } from './morphMap'\n\n/**\n * A relation is the related model's query builder, constrained to the parent: post.comments() is a\n * Builder<Comment> with `where comments.post_id = ?`, so every builder method (where, orderBy, paginate, a local\n * scope, …) works on it. Subclasses add eager loading (addEagerConstraints/initRelation/match) and the existence\n * queries behind has()/whereHas()/withCount().\n */\n/** Counts the aliases self-referencing existence queries take (Laravel's getRelationCountHash()). */\nlet selfAliases = 0\n\nexport abstract class Relation<R extends Model = Model, P extends Model = Model, Result = unknown> extends Builder<R> {\n /** The name the relation is loaded under (set when resolved by name, for eager loading and associate()). */\n relationName: string | undefined\n\n /** Laravel's Relation::morphMap(): { post: Post } stores 'post' instead of 'Post' in *_type columns. */\n static morphMap(map?: Record<string, typeof Model>, merge = true): Record<string, typeof Model> {\n return morphMap(map, merge)\n }\n\n static getMorphedModel(alias: string): typeof Model | undefined {\n return getMorphedModel(alias)\n }\n\n protected constructor(\n related: R,\n readonly parent: P,\n ) {\n super(related)\n related.registerGlobalScopes(this)\n related.registerDefaultEagerLoads(this)\n }\n\n getParent(): P {\n return this.parent\n }\n\n getRelated(): R {\n return this.model\n }\n\n /**\n * When the related table is the parent's own (a category's children, a user's followers), the existence query reads it\n * under an alias, `oriel_reserved_<n>`, so its columns aren't the outer row's. The related model takes the alias as its\n * table, so its qualified columns (keys, soft deletes, a constraint's qualifyColumn()) follow. Returns the alias, or\n * undefined when the tables differ.\n */\n protected aliasSelfTable(query: Builder<R>): string | undefined {\n const table = query.getModel().getTable()\n if (table !== this.parent.getTable()) return undefined\n const alias = `oriel_reserved_${selfAliases++}`\n query.from(`${table} as ${alias}`)\n query.getModel().setTable(alias)\n return alias\n }\n\n /**\n * @internal After an eager load's constraint: a limit() or offset() set there applies to each parent, as in Laravel 11,\n * on the relations that know the column holding the parent's key.\n */\n limitEagerPerParent(): void {\n const column = this.eagerPartitionColumn()\n if (column !== undefined) this.limitPerGroup(column)\n }\n\n /** The column of the eager query holding each row's parent key; undefined where a per-parent limit makes no sense. */\n protected eagerPartitionColumn(): string | undefined {\n return undefined\n }\n\n /** Subclasses call this last in their constructor: adds the per-parent constraints unless eager loading. */\n protected init(): void {\n if (relationConstraintsEnabled()) this.addConstraints()\n }\n\n /** The constraints for one parent: where comments.post_id = post.id. */\n abstract addConstraints(): void\n\n /** The constraints for many parents: where comments.post_id in (…). */\n abstract addEagerConstraints(models: P[]): void\n\n /** Sets the empty value (null or an empty collection) on every parent. */\n abstract initRelation(models: P[], relation: string): P[]\n\n /** Distributes the eagerly loaded results to their parents. */\n abstract match(models: P[], results: R[], relation: string): P[]\n\n /** The relation's value for this parent (a model, null or a collection). */\n abstract getResults(): Promise<Result>\n\n /** The query of has()/whereHas(): related rows that belong to the outer query's current row. */\n abstract getRelationExistenceQuery(query: Builder<R>, parentQuery: Builder<P>, columns?: ColumnRef[]): Builder<R>\n\n /** Runs the eager query. */\n getEager(): Promise<Collection<R>> {\n return this.get()\n }\n\n /** select count(*) … for withCount() and has('comments', '>=', 3). */\n getRelationExistenceCountQuery(query: Builder<R>, parentQuery: Builder<P>): Builder<R> {\n return this.getRelationExistenceQuery(query, parentQuery, [new Expression('count(*)')])\n }\n\n /** The distinct non-null values of `key` on the models (the eager whereIn list). */\n protected keysOf(models: Model[], key: string): unknown[] {\n const seen = new Map<string, unknown>()\n for (const model of models) {\n const value = model.getAttribute(key)\n if (value !== null && value !== undefined) seen.set(String(value), value)\n }\n return [...seen.values()]\n }\n}\n","import type { Row } from '@orieljs/contracts'\nimport { Collection } from '@orieljs/collections'\nimport type { Builder as QueryBuilder, ColumnRef } from '../../Query/Builder'\nimport { formatDateTime } from '../../Query/values'\nimport { Builder } from '../Builder'\nimport type { EloquentCollection } from '../Collection'\nimport { Pivot, type Model } from '../Model'\nimport type { Column } from '../types'\nimport { Relation } from './Relation'\n\n/** attach()/sync() accept ids, models, or { id: pivotAttributes }. */\nexport type PivotIds = unknown | readonly unknown[] | Record<string, Row>\n\nexport interface SyncChanges {\n attached: unknown[]\n detached: unknown[]\n updated: unknown[]\n}\n\n/**\n * Many-to-many through a pivot table: post.tags() → belongsToMany(Tag) over post_tag (post_id, tag_id).\n * Each related model carries its pivot row as `tag.pivot` (withPivot() adds columns, withTimestamps() the timestamps).\n */\nexport class BelongsToMany<R extends Model, P extends Model = Model> extends Relation<R, P, EloquentCollection<R>> {\n protected pivotColumns: string[] = []\n protected pivotTimestamps: [string, string] | undefined\n\n constructor(\n related: R,\n parent: P,\n readonly table: string,\n readonly foreignPivotKey: string,\n readonly relatedPivotKey: string,\n readonly parentKey: string,\n readonly relatedKey: string,\n ) {\n super(related, parent)\n this.join(this.table, this.model.qualifyColumn(this.relatedKey), '=', this.qualifyPivotColumn(this.relatedPivotKey))\n this.init()\n }\n\n qualifyPivotColumn(column: string): string {\n return column.includes('.') ? column : `${this.table}.${column}`\n }\n\n getTable(): string {\n return this.table\n }\n\n getForeignPivotKeyName(): string {\n return this.foreignPivotKey\n }\n\n getRelatedPivotKeyName(): string {\n return this.relatedPivotKey\n }\n\n getParentKey(): unknown {\n return this.parent.getAttribute(this.parentKey)\n }\n\n addConstraints(): void {\n this.where(this.qualifyPivotColumn(this.foreignPivotKey) as Column<R>, '=', this.getParentKey())\n }\n\n addEagerConstraints(models: P[]): void {\n this.whereIn(this.qualifyPivotColumn(this.foreignPivotKey) as Column<R>, this.keysOf(models, this.parentKey))\n }\n\n /** Extra pivot columns to load onto tag.pivot. */\n withPivot(...columns: Array<string | string[]>): this {\n this.pivotColumns.push(...columns.flat())\n return this\n }\n\n /** The pivot table has created_at/updated_at: they are set on attach() and loaded onto tag.pivot. */\n withTimestamps(createdAt = 'created_at', updatedAt = 'updated_at'): this {\n this.pivotTimestamps = [createdAt, updatedAt]\n return this.withPivot(createdAt, updatedAt)\n }\n\n wherePivot(column: string, operator: unknown, value?: unknown): this {\n const qualified = this.qualifyPivotColumn(column) as Column<R>\n return value === undefined ? this.where(qualified, operator) : this.where(qualified, String(operator), value)\n }\n\n wherePivotIn(column: string, values: readonly unknown[]): this {\n return this.whereIn(this.qualifyPivotColumn(column) as Column<R>, values)\n }\n\n /** Selects the related columns plus the pivot columns (as pivot_*), then moves those onto each model's pivot. */\n override async runSelect(): Promise<R[]> {\n const query = this.clone() as this\n if (!query.columns.length) query.columns = [`${this.model.getTable()}.*`]\n query.columns.push(...this.pivotSelectColumns())\n const models = (await Builder.prototype.runSelect.call(query)) as R[]\n for (const model of models) this.hydratePivot(model)\n return models\n }\n\n async getResults(): Promise<EloquentCollection<R>> {\n const key = this.getParentKey()\n return key === null || key === undefined ? this.getRelated().newCollection<R>() : this.get()\n }\n\n initRelation(models: P[], relation: string): P[] {\n for (const model of models) model.setRelation(relation, this.getRelated().newCollection<R>())\n return models\n }\n\n match(models: P[], results: R[], relation: string): P[] {\n const dictionary = new Map<string, R[]>()\n for (const result of results) {\n const key = String(result.pivot?.getAttribute(this.foreignPivotKey))\n const group = dictionary.get(key)\n if (group) group.push(result)\n else dictionary.set(key, [result])\n }\n for (const model of models) model.setRelation(relation, this.getRelated().newCollection(dictionary.get(String(model.getAttribute(this.parentKey))) ?? []))\n return models\n }\n\n protected override eagerPartitionColumn(): string {\n return this.qualifyPivotColumn(this.foreignPivotKey)\n }\n\n getRelationExistenceQuery(query: Builder<R>, _parentQuery: Builder<P>, columns: ColumnRef[] = ['*']): Builder<R> {\n this.aliasSelfTable(query)\n return query\n .select(...(columns as Array<Column<R>>))\n .join(this.table, this.model.qualifyColumn(this.relatedKey), '=', this.qualifyPivotColumn(this.relatedPivotKey))\n .whereColumn(this.parent.qualifyColumn(this.parentKey), '=', this.qualifyPivotColumn(this.foreignPivotKey))\n }\n\n // ---------------------------------------------------------------- the pivot table\n\n /** Inserts pivot rows for ids (or models, or { id: attributes }), with shared extra attributes. */\n async attach(ids: PivotIds, attributes: Row = {}): Promise<void> {\n const rows = [...this.parseIds(ids)].map(([id, extra]) => this.pivotRow(id, { ...attributes, ...extra }, true))\n if (rows.length) await this.newPivotQuery().insert(rows)\n }\n\n /** Deletes pivot rows for ids, or every pivot row of the parent. Returns how many were deleted. */\n async detach(ids?: PivotIds): Promise<number> {\n const query = this.newPivotQuery().where(this.foreignPivotKey, '=', this.getParentKey())\n if (ids !== undefined) {\n const list = [...this.parseIds(ids).keys()]\n if (!list.length) return 0\n query.whereIn(this.relatedPivotKey, list)\n }\n return query.delete()\n }\n\n /** Makes the pivot rows exactly ids: attaches the missing ones, detaches the others, updates given attributes. */\n async sync(ids: PivotIds, detaching = true): Promise<SyncChanges> {\n const changes: SyncChanges = { attached: [], detached: [], updated: [] }\n const wanted = this.parseIds(ids)\n const current = await this.currentPivotIds()\n const wantedKeys = new Set([...wanted.keys()].map(String))\n if (detaching) {\n const detach = current.filter((id) => !wantedKeys.has(String(id)))\n if (detach.length) {\n await this.detach(detach)\n changes.detached.push(...detach)\n }\n }\n const currentKeys = new Set(current.map(String))\n for (const [id, attributes] of wanted) {\n if (!currentKeys.has(String(id))) {\n await this.attach(id, attributes)\n changes.attached.push(id)\n } else if (Object.keys(attributes).length && (await this.updateExistingPivot(id, attributes)) > 0) {\n changes.updated.push(id)\n }\n }\n return changes\n }\n\n syncWithoutDetaching(ids: PivotIds): Promise<SyncChanges> {\n return this.sync(ids, false)\n }\n\n /** Attaches the ids that aren't attached and detaches the ones that are. */\n async toggle(ids: PivotIds): Promise<{ attached: unknown[]; detached: unknown[] }> {\n const current = new Set((await this.currentPivotIds()).map(String))\n const attached: unknown[] = []\n const detached: unknown[] = []\n for (const [id, attributes] of this.parseIds(ids)) {\n if (current.has(String(id))) {\n await this.detach(id)\n detached.push(id)\n } else {\n await this.attach(id, attributes)\n attached.push(id)\n }\n }\n return { attached, detached }\n }\n\n /** Updates the pivot row of one related id. Returns the number of affected rows. */\n async updateExistingPivot(id: unknown, attributes: Row): Promise<number> {\n const values = { ...attributes }\n if (this.pivotTimestamps) values[this.pivotTimestamps[1]] = formatDateTime(this.parent.freshTimestamp())\n return this.newPivotQuery()\n .where(this.foreignPivotKey, '=', this.getParentKey())\n .where(this.relatedPivotKey, '=', this.idOf(id))\n .update(values)\n }\n\n /** Saves a new related model and attaches it. */\n override async create(attributes: Row = {}, pivotAttributes: Row = {}): Promise<R> {\n const model = this.model.newInstance(attributes) as R\n await model.save()\n await this.attach(model, pivotAttributes)\n return model\n }\n\n /** Saves a related model and attaches it. */\n async save(model: R, pivotAttributes: Row = {}): Promise<R> {\n await model.save()\n await this.attach(model, pivotAttributes)\n return model\n }\n\n /** A plain query builder on the pivot table. */\n newPivotQuery(): QueryBuilder<Row> {\n return this.connection.table(this.table)\n }\n\n private async currentPivotIds(): Promise<unknown[]> {\n return (await this.newPivotQuery().where(this.foreignPivotKey, '=', this.getParentKey()).pluck(this.relatedPivotKey)).all()\n }\n\n private pivotSelectColumns(): string[] {\n const columns = [...new Set([this.foreignPivotKey, this.relatedPivotKey, ...this.pivotColumns])]\n return columns.map((column) => `${this.table}.${column} as pivot_${column}`)\n }\n\n private hydratePivot(model: R): void {\n const attributes = model.getAttributes()\n const pivotValues: Row = {}\n const own: Row = {}\n for (const [key, value] of Object.entries(attributes)) {\n if (key.startsWith('pivot_')) pivotValues[key.slice(6)] = value\n else own[key] = value\n }\n model.setRawAttributes(own, true)\n const pivot = new Pivot().setTable(this.table)\n pivot.timestamps = this.pivotTimestamps !== undefined\n pivot.setRawAttributes(pivotValues, true)\n pivot.exists = true\n model.setRelation('pivot', pivot)\n }\n\n private pivotRow(id: unknown, attributes: Row, creating: boolean): Row {\n const row: Row = { ...attributes, [this.foreignPivotKey]: this.getParentKey(), [this.relatedPivotKey]: this.idOf(id) }\n if (this.pivotTimestamps && creating) {\n const now = formatDateTime(this.parent.freshTimestamp())\n row[this.pivotTimestamps[0]] ??= now\n row[this.pivotTimestamps[1]] ??= now\n }\n return row\n }\n\n /** ids → Map(id → extra pivot attributes). Models become their related key. */\n private parseIds(ids: PivotIds): Map<unknown, Row> {\n const parsed = new Map<unknown, Row>()\n if (ids instanceof Collection) ids = ids.all()\n if (Array.isArray(ids)) {\n for (const id of ids) parsed.set(this.idOf(id), {})\n } else if (ids !== null && typeof ids === 'object' && !this.isModel(ids)) {\n for (const [id, attributes] of Object.entries(ids as Record<string, Row>)) parsed.set(this.castKey(id), attributes)\n } else {\n parsed.set(this.idOf(ids), {})\n }\n return parsed\n }\n\n private idOf(id: unknown): unknown {\n return this.isModel(id) ? id.getAttribute(this.relatedKey) : id\n }\n\n private isModel(value: unknown): value is Model {\n return typeof value === 'object' && value !== null && typeof (value as Model).getAttribute === 'function' && typeof (value as Model).getTable === 'function'\n }\n\n /** Object keys are strings; numeric ones go back to numbers for integer keys. */\n private castKey(id: string): unknown {\n return this.model.getKeyType() === 'int' && /^\\d+$/.test(id) ? Number(id) : id\n }\n}\n","import type { Row } from '@orieljs/contracts'\nimport { Str } from '@orieljs/support'\nimport { RelationNotFoundError } from '../../errors'\nimport type { ColumnRef } from '../../Query/Builder'\nimport type { Builder } from '../Builder'\nimport type { Model } from '../Model'\nimport type { Column } from '../types'\nimport { Relation } from './Relation'\n\n/** For morphOne/morphMany: the qualified type column and the parent's morph class stored in it. */\nexport interface MorphConstraint {\n type: string\n value: string\n}\n\n/**\n * The shared half of hasOne, hasMany, morphOne and morphMany: the related table holds the foreign key (and, for\n * the morph relations, the parent's type).\n */\nexport abstract class HasOneOrMany<R extends Model, P extends Model, Result> extends Relation<R, P, Result> {\n /** The relation on each related model that chaperone() points back at the parent. */\n protected inverseRelationship: string | undefined\n /**\n * @param foreignKey the qualified foreign key on the related table ('comments.post_id')\n * @param localKey the key on the parent it points at ('id')\n * @param morph the type column and value, for morphOne/morphMany\n */\n constructor(\n related: R,\n parent: P,\n readonly foreignKey: string,\n readonly localKey: string,\n readonly morph?: MorphConstraint,\n ) {\n super(related, parent)\n this.init()\n }\n\n /** 'post_id' */\n getForeignKeyName(): string {\n return this.foreignKey.slice(this.foreignKey.lastIndexOf('.') + 1)\n }\n\n getQualifiedForeignKeyName(): string {\n return this.foreignKey\n }\n\n getParentKey(): unknown {\n return this.parent.getAttribute(this.localKey)\n }\n\n getQualifiedParentKeyName(): string {\n return this.parent.qualifyColumn(this.localKey)\n }\n\n /** 'commentable_type' for a morph relation. */\n getMorphType(): string | undefined {\n return this.morph?.type.slice(this.morph.type.lastIndexOf('.') + 1)\n }\n\n /** The parent's value in the type column, for a morph relation. */\n getMorphClass(): string | undefined {\n return this.morph?.value\n }\n\n /**\n * Laravel's chaperone(): every related model this relation loads, eagerly or lazily, or makes, gets the parent as\n * its `relation` (guessed when not given: post_id → post, the parent's class, owner), so reading it needs no query:\n * `comments() { return this.hasMany(Comment).chaperone() }`.\n */\n chaperone(relation?: string): this {\n const name = relation ?? this.guessInverseRelation()\n if (name === undefined || !this.model.isRelation(name)) throw new RelationNotFoundError(this.model.constructor.name, name ?? 'null')\n this.inverseRelationship = name\n return this\n }\n\n /** Laravel's inverse(): chaperone() under its other name. */\n inverse(relation?: string): this {\n return this.chaperone(relation)\n }\n\n withoutChaperone(): this {\n this.inverseRelationship = undefined\n return this\n }\n\n withoutInverse(): this {\n return this.withoutChaperone()\n }\n\n getInverseRelationship(): string | undefined {\n return this.inverseRelationship\n }\n\n /** The first of the possible names that is a relation of the related model. */\n protected guessInverseRelation(): string | undefined {\n return this.getPossibleInverseRelations().find((name) => this.model.isRelation(name))\n }\n\n /** Laravel's candidates: the morph name, the foreign key without the parent's key, the parent's class, owner, parent. */\n protected getPossibleInverseRelations(): string[] {\n const key = this.parent.getKeyName()\n const names = [\n this.morph ? Str.beforeLast(this.getMorphType()!, '_type') : '',\n Str.camel(Str.beforeLast(this.getForeignKeyName(), key)),\n Str.camel(Str.beforeLast(this.parent.getForeignKey(), key)),\n Str.camel(this.parent.constructor.name),\n 'owner',\n this.parent.constructor === this.model.constructor ? 'parent' : '',\n ]\n return [...new Set(names.filter((name) => name !== ''))]\n }\n\n /** Sets the parent on a related model, when chaperone() named the relation. */\n protected applyInverseRelationToModel<M extends R | null | undefined>(model: M, parent: P = this.parent): M {\n if (model && this.inverseRelationship !== undefined) model.setRelation(this.inverseRelationship, parent)\n return model\n }\n\n protected applyInverseRelationToMany(models: R[], parent: P = this.parent): R[] {\n for (const model of models) this.applyInverseRelationToModel(model, parent)\n return models\n }\n\n /** The relation query's rows (get(), first(), paginate(), …), pointing back at the parent with chaperone(). */\n override async runSelect(): Promise<R[]> {\n return this.applyInverseRelationToMany(await super.runSelect())\n }\n\n addConstraints(): void {\n this.where(this.foreignKey as Column<R>, '=', this.getParentKey())\n this.whereNotNull(this.foreignKey as Column<R>)\n if (this.morph) this.where(this.morph.type as Column<R>, '=', this.morph.value)\n }\n\n addEagerConstraints(models: P[]): void {\n this.whereIn(this.foreignKey as Column<R>, this.keysOf(models, this.localKey))\n if (this.morph) this.where(this.morph.type as Column<R>, '=', this.morph.value)\n }\n\n /** Related models grouped by their foreign key, as strings: bigint and integer keys compare equal. */\n protected buildDictionary(results: R[]): Map<string, R[]> {\n const dictionary = new Map<string, R[]>()\n const key = this.getForeignKeyName()\n for (const result of results) {\n const value = String(result.getAttribute(key))\n const group = dictionary.get(value)\n if (group) group.push(result)\n else dictionary.set(value, [result])\n }\n return dictionary\n }\n\n /** New related models get the parent's key (and type): post.comments().create({ body }) sets post_id. */\n override newModelInstance(attributes: Row = {}): R {\n return this.setForeignAttributes(super.newModelInstance(attributes))\n }\n\n /** Sets the foreign key (and type) on an existing model and saves it. */\n async save(model: R): Promise<R> {\n await this.setForeignAttributes(model).save()\n return model\n }\n\n protected setForeignAttributes(model: R): R {\n model.setAttribute(this.getForeignKeyName(), this.getParentKey())\n if (this.morph) model.setAttribute(this.getMorphType()!, this.morph.value)\n return this.applyInverseRelationToModel(model)\n }\n\n async saveMany(models: Iterable<R>): Promise<R[]> {\n const saved: R[] = []\n for (const model of models) saved.push(await this.save(model))\n return saved\n }\n\n async createMany(records: Row[]): Promise<R[]> {\n const created: R[] = []\n for (const record of records) created.push(await this.create(record))\n return created\n }\n\n protected override eagerPartitionColumn(): string {\n return this.foreignKey\n }\n\n getRelationExistenceQuery(query: Builder<R>, _parentQuery: Builder<P>, columns: ColumnRef[] = ['*']): Builder<R> {\n const alias = this.aliasSelfTable(query)\n const foreignKey = alias === undefined ? this.foreignKey : `${alias}.${this.getForeignKeyName()}`\n query.select(...(columns as Array<Column<R>>)).whereColumn(this.getQualifiedParentKeyName(), '=', foreignKey)\n if (this.morph) {\n const type = alias === undefined ? this.morph.type : `${alias}.${this.morph.type.slice(this.morph.type.lastIndexOf('.') + 1)}`\n query.where(type as Column<R>, '=', this.morph.value)\n }\n return query\n }\n}\n","import { Collection } from '@orieljs/collections'\nimport { LogicError } from '../../errors'\nimport type { Builder } from '../Builder'\nimport type { Model } from '../Model'\nimport { BelongsTo } from './BelongsTo'\nimport { resolveMorphClass } from './morphMap'\n\n/**\n * comment.commentable() → morphTo('commentable'): the parent's class comes from commentable_type (a morph map alias\n * or a class name) and its key from commentable_id. Eager loading runs one query per distinct type.\n */\nexport class MorphTo<R extends Model = Model, P extends Model = Model> extends BelongsTo<R, P> {\n /** Parents grouped by type, then by id, while eager loading. */\n private dictionary = new Map<string, Map<string, P[]>>()\n /** The stored type each eager result was loaded for (an alias or a class name), for match(). */\n private resultTypes = new WeakMap<Model, string>()\n\n /**\n * @param related an instance of the current type's class (the child's own class when the type is empty)\n * @param morphType the type column on the child ('commentable_type')\n * @param ownerKey the key on the parent (default: each class's primary key)\n */\n constructor(related: R, child: P, foreignKey: string, readonly morphTypeColumn: string, readonly ownerKeyOverride: string | undefined, relationName: string) {\n super(related, child, foreignKey, ownerKeyOverride ?? related.getKeyName(), relationName)\n // Without a type, `related` is only the child's own class standing in for the real ones: its default with and\n // withCount belong to the child, not to the parents getEager() loads (each type's query adds its own defaults).\n if (!child.getAttribute(morphTypeColumn)) {\n this.eagerLoad.clear()\n this.columns = []\n }\n }\n\n getMorphType(): string {\n return this.morphTypeColumn\n }\n\n override addConstraints(): void {\n if (this.parent.getAttribute(this.morphTypeColumn)) super.addConstraints()\n }\n\n override async getResults(): Promise<R | null> {\n if (!this.parent.getAttribute(this.morphTypeColumn)) return null\n return super.getResults()\n }\n\n /** Groups the children by type and id; the queries run in getEager(). */\n override addEagerConstraints(models: P[]): void {\n this.dictionary = new Map()\n for (const model of models) {\n const type = model.getAttribute(this.morphTypeColumn)\n const id = model.getAttribute(this.foreignKey)\n if (!type || id === null || id === undefined) continue\n const byId = this.dictionary.get(String(type)) ?? new Map<string, P[]>()\n const group = byId.get(String(id))\n if (group) group.push(model)\n else byId.set(String(id), [model])\n this.dictionary.set(String(type), byId)\n }\n }\n\n /** One query per type, with this relation's constraints and nested eager loads. */\n override async getEager(): Promise<Collection<R>> {\n const results: R[] = []\n for (const [type, byId] of this.dictionary) {\n const cls = resolveMorphClass(type)\n const instance = cls.prototypeInstance()\n const ownerKey = this.ownerKeyOverride ?? instance.getKeyName()\n const query = cls.query()\n for (const [name, constraint] of this.getEagerLoads()) query.with(constraint ? { [name]: constraint } : name)\n query.wheres.push(...this.wheres)\n const ids = [...byId.values()].map((models) => models[0]!.getAttribute(this.foreignKey))\n for (const result of (await query.whereIn(instance.qualifyColumn(ownerKey), ids).get()).all() as unknown as R[]) {\n this.resultTypes.set(result, type)\n results.push(result)\n }\n }\n return new Collection(results)\n }\n\n override match(models: P[], results: R[], relation: string): P[] {\n for (const result of results) {\n const byId = this.dictionary.get(this.resultTypes.get(result) ?? result.getMorphClass())\n const ownerKey = this.ownerKeyOverride ?? result.getKeyName()\n for (const model of byId?.get(String(result.getAttribute(ownerKey))) ?? []) model.setRelation(relation, result)\n }\n return models\n }\n\n /** Points the child at `model`: sets the id and the type columns and the loaded relation. */\n override associate(model: R | null): P {\n this.parent.setAttribute(this.foreignKey, model === null ? null : model.getAttribute(this.ownerKeyOverride ?? model.getKeyName()))\n this.parent.setAttribute(this.morphTypeColumn, model === null ? null : model.getMorphClass())\n this.parent.setRelation(this.relationName ?? this.morphTypeColumn.replace(/_type$/, ''), model)\n return this.parent\n }\n\n override getRelationExistenceQuery(): Builder<R> {\n throw new LogicError('has()/whereHas() on a morphTo relation needs the possible types, which Oriel v1 does not support.')\n }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport { EventDispatcher } from '@orieljs/contracts'\nimport { currentContainer } from '@orieljs/container'\nimport { LogicError } from '../errors'\n\n/** Laravel's model events. The -ing events of save, delete and restore can cancel by returning false. */\nexport const MODEL_EVENTS = [\n 'retrieved', 'creating', 'created', 'updating', 'updated', 'saving', 'saved',\n 'deleting', 'deleted', 'restoring', 'restored', 'forceDeleting', 'forceDeleted',\n] as const\nexport type ModelEvent = (typeof MODEL_EVENTS)[number]\n\n/** A listener receives the model. Returning false from a halting event cancels the operation. */\nexport type ModelListener<M> = (model: M) => unknown\n\nconst muted = new AsyncLocalStorage<boolean>()\n\n/** 'eloquent.created: Post' (Laravel uses the fully qualified class name; Oriel uses the class name). */\nexport function modelEventName(event: string, className: string): string {\n return `eloquent.${event}: ${className}`\n}\n\n/** The EventDispatcher of the current container, when one is bound. Firing without one is a no-op. */\nexport function eventDispatcher(): EventDispatcher | undefined {\n const container = currentContainer()\n return container?.bound(EventDispatcher) ? container.make(EventDispatcher) : undefined\n}\n\n/** The dispatcher for registering listeners: required, because silently dropping an observer would hide a bug. */\nexport function requireEventDispatcher(className: string): EventDispatcher {\n const dispatcher = eventDispatcher()\n if (!dispatcher) {\n throw new LogicError(`Registering model events on [${className}] needs an EventDispatcher. Is EventServiceProvider registered?`)\n }\n return dispatcher\n}\n\n/** Runs fn with model events off, for this async context only (Model.withoutEvents, saveQuietly). */\nexport function withoutModelEvents<R>(fn: () => R): R {\n return muted.run(true, fn)\n}\n\nexport function modelEventsMuted(): boolean {\n return muted.getStore() === true\n}\n","import type { EloquentCollection } from '../Collection'\nimport type { Model } from '../Model'\nimport { HasOneOrMany } from './HasOneOrMany'\n\n/** post.comments(): many related rows hold the parent's key. */\nexport class HasMany<R extends Model, P extends Model = Model> extends HasOneOrMany<R, P, EloquentCollection<R>> {\n async getResults(): Promise<EloquentCollection<R>> {\n const key = this.getParentKey()\n return key === null || key === undefined ? this.getRelated().newCollection<R>() : this.get()\n }\n\n initRelation(models: P[], relation: string): P[] {\n for (const model of models) model.setRelation(relation, this.getRelated().newCollection<R>())\n return models\n }\n\n match(models: P[], results: R[], relation: string): P[] {\n const dictionary = this.buildDictionary(results)\n for (const model of models) {\n const children = this.applyInverseRelationToMany(dictionary.get(String(model.getAttribute(this.localKey))) ?? [], model)\n model.setRelation(relation, this.getRelated().newCollection(children))\n }\n return models\n }\n}\n","import type { Row } from '@orieljs/contracts'\nimport type { ColumnRef } from '../../Query/Builder'\nimport { Builder } from '../Builder'\nimport type { EloquentCollection } from '../Collection'\nimport type { Model } from '../Model'\nimport type { Column } from '../types'\nimport { Relation } from './Relation'\n\nconst THROUGH_KEY = 'laravel_through_key'\n\n/**\n * Related rows reached through an intermediate model: country.posts() → hasManyThrough(Post, User):\n * posts join users on users.id = posts.user_id where users.country_id = countries.id.\n */\nexport class HasManyThrough<R extends Model, P extends Model = Model, T extends Model = Model> extends Relation<R, P, EloquentCollection<R>> {\n /** The through key of each loaded model (kept off its attributes, so it never reaches toJSON()). */\n private readonly throughKeys = new WeakMap<Model, unknown>()\n\n /**\n * @param firstKey on the through table, pointing at the far parent ('users.country_id')\n * @param secondKey on the related table, pointing at the through model ('posts.user_id')\n * @param localKey on the far parent ('countries.id')\n * @param secondLocalKey on the through model ('users.id')\n */\n constructor(\n related: R,\n farParent: P,\n readonly throughParent: T,\n readonly firstKey: string,\n readonly secondKey: string,\n readonly localKey: string,\n readonly secondLocalKey: string,\n ) {\n super(related, farParent)\n this.join(this.throughParent.getTable(), this.getQualifiedParentKeyName(), '=', this.getQualifiedForeignKeyName())\n if (this.throughParent.usesSoftDeletes()) {\n this.withGlobalScope('SoftDeletableHasManyThrough', (query) => query.whereNull(this.throughParent.getQualifiedDeletedAtColumn()))\n }\n this.init()\n }\n\n /** users.country_id */\n getQualifiedFirstKeyName(): string {\n return this.throughParent.qualifyColumn(this.firstKey)\n }\n\n /** posts.user_id */\n getQualifiedForeignKeyName(): string {\n return this.model.qualifyColumn(this.secondKey)\n }\n\n /** users.id */\n getQualifiedParentKeyName(): string {\n return this.throughParent.qualifyColumn(this.secondLocalKey)\n }\n\n /** countries.id */\n getQualifiedLocalKeyName(): string {\n return this.parent.qualifyColumn(this.localKey)\n }\n\n addConstraints(): void {\n this.where(this.getQualifiedFirstKeyName() as Column<R>, '=', this.parent.getAttribute(this.localKey))\n }\n\n addEagerConstraints(models: P[]): void {\n this.whereIn(this.getQualifiedFirstKeyName() as Column<R>, this.keysOf(models, this.localKey))\n }\n\n /** Selects the related columns plus the through key, then moves the key off the attributes. */\n override async runSelect(): Promise<R[]> {\n const query = this.clone() as this\n if (!query.columns.length) query.columns = [`${this.model.getTable()}.*`]\n query.columns.push(`${this.getQualifiedFirstKeyName()} as ${THROUGH_KEY}`)\n const models = (await Builder.prototype.runSelect.call(query)) as R[]\n for (const model of models) {\n const { [THROUGH_KEY]: key, ...attributes } = model.getAttributes() as Row\n this.throughKeys.set(model, key)\n model.setRawAttributes(attributes, true)\n }\n return models\n }\n\n async getResults(): Promise<EloquentCollection<R>> {\n const key = this.parent.getAttribute(this.localKey)\n return key === null || key === undefined ? this.getRelated().newCollection<R>() : this.get()\n }\n\n override async getEager(): Promise<EloquentCollection<R>> {\n return this.get()\n }\n\n initRelation(models: P[], relation: string): P[] {\n for (const model of models) model.setRelation(relation, this.getRelated().newCollection<R>())\n return models\n }\n\n match(models: P[], results: R[], relation: string): P[] {\n const dictionary = new Map<string, R[]>()\n for (const result of results) {\n const key = String(this.throughKeys.get(result))\n const group = dictionary.get(key)\n if (group) group.push(result)\n else dictionary.set(key, [result])\n }\n for (const model of models) model.setRelation(relation, this.getRelated().newCollection(dictionary.get(String(model.getAttribute(this.localKey))) ?? []))\n return models\n }\n\n getRelationExistenceQuery(query: Builder<R>, _parentQuery: Builder<P>, columns: ColumnRef[] = ['*']): Builder<R> {\n query\n .select(...(columns as Array<Column<R>>))\n .join(this.throughParent.getTable(), this.getQualifiedParentKeyName(), '=', this.getQualifiedForeignKeyName())\n .whereColumn(this.getQualifiedLocalKeyName(), '=', this.getQualifiedFirstKeyName())\n if (this.throughParent.usesSoftDeletes()) query.whereNull(this.throughParent.getQualifiedDeletedAtColumn() as Column<R>)\n return query\n }\n}\n","import type { Model } from '../Model'\nimport { HasOneOrMany } from './HasOneOrMany'\n\n/** user.profile(): one related row holds the parent's key. */\nexport class HasOne<R extends Model, P extends Model = Model> extends HasOneOrMany<R, P, R | null> {\n async getResults(): Promise<R | null> {\n const key = this.getParentKey()\n if (key === null || key === undefined) return null\n return (await this.first()) ?? null\n }\n\n initRelation(models: P[], relation: string): P[] {\n for (const model of models) model.setRelation(relation, null)\n return models\n }\n\n match(models: P[], results: R[], relation: string): P[] {\n const dictionary = this.buildDictionary(results)\n for (const model of models) {\n model.setRelation(relation, this.applyInverseRelationToModel(dictionary.get(String(model.getAttribute(this.localKey)))?.[0] ?? null, model))\n }\n return models\n }\n}\n","import type { Model } from '../Model'\nimport { HasMany } from './HasMany'\n\n/** post.comments() → morphMany(Comment, 'commentable'): comments.commentable_id + commentable_type = 'Post'. */\nexport class MorphMany<R extends Model, P extends Model = Model> extends HasMany<R, P> {\n /**\n * @param morphType the qualified type column ('comments.commentable_type')\n * @param foreignKey the qualified id column ('comments.commentable_id')\n */\n constructor(related: R, parent: P, morphType: string, foreignKey: string, localKey: string) {\n super(related, parent, foreignKey, localKey, { type: morphType, value: parent.getMorphClass() })\n }\n}\n","import type { Model } from '../Model'\nimport { HasOne } from './HasOne'\n\n/** user.image() → morphOne(Image, 'imageable'): images.imageable_id + imageable_type = 'User'. */\nexport class MorphOne<R extends Model, P extends Model = Model> extends HasOne<R, P> {\n constructor(related: R, parent: P, morphType: string, foreignKey: string, localKey: string) {\n super(related, parent, foreignKey, localKey, { type: morphType, value: parent.getMorphClass() })\n }\n}\n","import { Str } from '@orieljs/support'\nimport type { ModelConstructor } from './HasDatabaseNotifications'\n\n/**\n * Laravel's HasUniqueStringIds, shared by HasUuids and HasUlids: the primary key is a string the model fills on\n * insert, and a value of the wrong shape finds nothing without a query (route model binding, find(), findOrFail()).\n */\nfunction uniqueStringIds<TBase extends ModelConstructor>(Base: TBase, generate: () => string, valid: (value: unknown) => boolean): TBase {\n return class WithUniqueStringIds extends Base {\n override usesUniqueIds(): boolean {\n return true\n }\n\n override uniqueIds(): string[] {\n return [this.getKeyName()]\n }\n\n override newUniqueId(): string {\n return generate()\n }\n\n override isValidUniqueId(value: unknown): boolean {\n return valid(value)\n }\n\n override getKeyType(): 'int' | 'string' {\n return this.uniqueIds().includes(this.getKeyName()) ? 'string' : super.getKeyType()\n }\n\n override getIncrementing(): boolean {\n return this.uniqueIds().includes(this.getKeyName()) ? false : super.getIncrementing()\n }\n }\n}\n\n/** Laravel's HasUuids: `class Post extends HasUuids(Model) {}` keys new rows with a version 7 UUID. */\nexport function HasUuids<TBase extends ModelConstructor>(Base: TBase): TBase {\n return uniqueStringIds(Base, () => Str.uuid7(), Str.isUuid)\n}\n\n/** Laravel's HasUlids: `class Post extends HasUlids(Model) {}` keys new rows with a lower-case ULID. */\nexport function HasUlids<TBase extends ModelConstructor>(Base: TBase): TBase {\n return uniqueStringIds(Base, () => Str.ulid().toLowerCase(), Str.isUlid)\n}\n","import type { DatabaseNotification as DatabaseNotificationContract } from '@orieljs/contracts'\nimport type { Builder } from './Builder'\nimport type { CastDefinition } from './casts'\nimport { EloquentCollection } from './Collection'\nimport { HasUuids } from './HasUniqueStringIds'\nimport { Model } from './Model'\nimport { MorphMany } from './Relations/MorphMany'\nimport type { MorphTo } from './Relations/MorphTo'\n\n/**\n * Laravel's DatabaseNotification: one row of the `notifications` table, which the database channel writes. A UUID\n * string key (HasUuids: a malformed id finds nothing without a query, so it is a 404), `data` as an array cast and\n * `read_at` as a datetime. `user.notifications()` returns these, newest first.\n */\nexport class DatabaseNotification extends HasUuids(Model) implements DatabaseNotificationContract {\n protected override table: string | undefined = 'notifications'\n protected override keyType: 'int' | 'string' = 'string'\n override incrementing = false\n protected override guarded: string[] = []\n protected override casts: Readonly<Record<string, CastDefinition>> = { data: 'array', read_at: 'datetime' }\n\n declare $attributes?: {\n id: string\n type: string\n notifiable_type: string\n notifiable_id: number | string\n data: Record<string, unknown>\n read_at: Date | null\n created_at: Date | null\n updated_at: Date | null\n }\n\n declare readonly id: string\n declare readonly type: string\n declare readonly notifiable_type: string\n declare readonly notifiable_id: number | string\n declare readonly data: Record<string, unknown>\n declare read_at: Date | null\n declare readonly created_at: Date | null\n declare readonly updated_at: Date | null\n\n /** The model the notification was sent to. */\n notifiable<R extends Model = Model>(): MorphTo<R, this> {\n return this.morphTo<R>('notifiable')\n }\n\n /** Sets read_at to now and saves, unless it is already read. */\n async markAsRead(): Promise<void> {\n if (this.unread()) await this.forceFill({ read_at: this.freshTimestamp() }).save()\n }\n\n /** Clears read_at and saves, unless it is already unread. */\n async markAsUnread(): Promise<void> {\n if (this.read()) await this.forceFill({ read_at: null }).save()\n }\n\n read(): boolean {\n return this.read_at !== null && this.read_at !== undefined\n }\n\n unread(): boolean {\n return !this.read()\n }\n\n /** Queries of notifications return a DatabaseNotificationCollection (markAsRead() on all of them). */\n override newCollection<T extends Model>(this: T, models: T[] = []): EloquentCollection<T> {\n return new DatabaseNotificationCollection(models as unknown as DatabaseNotification[]) as unknown as EloquentCollection<T>\n }\n\n /** `query.read()`: only read notifications. */\n static scopeRead(query: Builder<DatabaseNotification>): Builder<DatabaseNotification> {\n return query.whereNotNull('read_at')\n }\n\n /** `query.unread()`: only unread notifications. */\n static scopeUnread(query: Builder<DatabaseNotification>): Builder<DatabaseNotification> {\n return query.whereNull('read_at')\n }\n}\n\n/** Laravel's DatabaseNotificationCollection: what `await user.notifications().get()` returns. */\nexport class DatabaseNotificationCollection extends EloquentCollection<DatabaseNotification> {\n /** Marks every notification as read (one save each, as in Laravel). */\n async markAsRead(): Promise<void> {\n for (const notification of this.all()) await notification.markAsRead()\n }\n\n /** Marks every notification as unread. */\n async markAsUnread(): Promise<void> {\n for (const notification of this.all()) await notification.markAsUnread()\n }\n}\n\n/**\n * The relation `notifications()`, `readNotifications()` and `unreadNotifications()` return: a morphMany over\n * DatabaseNotification whose results (get(), the loaded relation, eager loads) are DatabaseNotificationCollections.\n * Every builder method works on it: paginate(), count(), update({ read_at }), where(), …\n */\nexport class DatabaseNotificationsRelation<P extends Model = Model> extends MorphMany<DatabaseNotification, P> {\n override async get(): Promise<DatabaseNotificationCollection> {\n return new DatabaseNotificationCollection(await this.runSelect())\n }\n\n override async getResults(): Promise<DatabaseNotificationCollection> {\n const key = this.getParentKey()\n return key === null || key === undefined ? new DatabaseNotificationCollection() : this.get()\n }\n\n override initRelation(models: P[], relation: string): P[] {\n for (const model of models) model.setRelation(relation, new DatabaseNotificationCollection())\n return models\n }\n\n override match(models: P[], results: DatabaseNotification[], relation: string): P[] {\n const dictionary = this.buildDictionary(results)\n for (const model of models) {\n model.setRelation(relation, new DatabaseNotificationCollection(dictionary.get(String(model.getAttribute(this.localKey))) ?? []))\n }\n return models\n }\n}\n","import { DatabaseNotification, DatabaseNotificationsRelation } from './DatabaseNotification'\nimport type { Model } from './Model'\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ModelConstructor = new (...args: any[]) => Model\n\n/** What HasDatabaseNotifications adds to a model. */\nexport interface HasDatabaseNotificationsModel extends Model {\n /** The model's notifications, newest first: morphMany(DatabaseNotification, 'notifiable').latest(). */\n notifications(): DatabaseNotificationsRelation<this>\n /** The read ones (read_at set). */\n readNotifications(): DatabaseNotificationsRelation<this>\n /** The unread ones (read_at null). */\n unreadNotifications(): DatabaseNotificationsRelation<this>\n}\n\n/**\n * Laravel's HasDatabaseNotifications: the notifications the database channel stored for this model, as queries.\n * `class User extends HasDatabaseNotifications(Model) {}`; apps get it through `Notifiable`.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function HasDatabaseNotifications<TBase extends ModelConstructor>(Base: TBase): TBase & (new (...args: any[]) => HasDatabaseNotificationsModel) {\n class WithDatabaseNotifications extends Base implements HasDatabaseNotificationsModel {\n notifications(): DatabaseNotificationsRelation<this> {\n const related = this.newRelatedInstance(DatabaseNotification)\n return new DatabaseNotificationsRelation<this>(\n related,\n this,\n related.qualifyColumn('notifiable_type'),\n related.qualifyColumn('notifiable_id'),\n this.getKeyName(),\n ).latest()\n }\n\n readNotifications(): DatabaseNotificationsRelation<this> {\n return this.notifications().whereNotNull('read_at')\n }\n\n unreadNotifications(): DatabaseNotificationsRelation<this> {\n return this.notifications().whereNull('read_at')\n }\n }\n return WithDatabaseNotifications\n}\n","/**\n * A migration: `export default class extends Migration { async up() { await Schema.create(…) } async down() { … } }`.\n * Files live in database/migrations and run in file-name order. up() and down() are abstract (as in Laravel's\n * stub), so implementing them needs no `override` under noImplicitOverride.\n */\nexport abstract class Migration {\n /** The connection to run on (default: the default connection). */\n connection: string | undefined = undefined\n\n /** Wrap up()/down() in a transaction where DDL is transactional (Postgres, SQLite; not MySQL), like Laravel. */\n withinTransaction = true\n\n abstract up(): Promise<void> | void\n\n abstract down(): Promise<void> | void\n}\n","import { existsSync, mkdirSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { Str } from '@orieljs/support'\nimport { LogicError } from '../errors'\n\n/** Laravel 11's migration.create stub: an anonymous class, the form the Migrator loads. */\nexport 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`\n\n/** Laravel 11's migration.update stub. */\nexport 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`\n\n/** Laravel 11's blank migration stub. */\nexport 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`\n\n/**\n * Laravel's TableGuesser: create_posts_table → ['posts', true], add_votes_to_users_table → ['users', false].\n * Returns undefined when the name says nothing about a table.\n */\nexport function guessTable(migration: string): { table: string; create: boolean } | undefined {\n const create = /^create_(\\w+?)(?:_table)?$/.exec(migration)\n if (create) return { table: create[1]!, create: true }\n const change = /_(?:to|from|in)_(\\w+?)(?:_table)?$/.exec(migration)\n if (change) return { table: change[1]!, create: false }\n return undefined\n}\n\n/** Laravel's date prefix, Y_m_d_His (UTC). */\nexport function migrationDatePrefix(date: Date = new Date()): string {\n const pad = (value: number) => String(value).padStart(2, '0')\n return (\n `${date.getUTCFullYear()}_${pad(date.getUTCMonth() + 1)}_${pad(date.getUTCDate())}_` +\n `${pad(date.getUTCHours())}${pad(date.getUTCMinutes())}${pad(date.getUTCSeconds())}`\n )\n}\n\nexport interface CreateMigrationOptions {\n /** The table to create (--create). */\n create?: string\n /** The table to change (--table). */\n table?: string\n /** The package the migration imports Migration and Schema from (default '@orieljs/framework'). */\n importSource?: string\n /** For tests: the timestamp of the file name. */\n date?: Date\n}\n\n/** Laravel's MigrationCreator: writes <path>/<Y_m_d_His>_<name>.ts from the create, update or blank stub. */\nexport class MigrationCreator {\n /** Returns the path of the new file. */\n create(name: string, path: string, options: CreateMigrationOptions = {}): string {\n const snake = Str.snake(name.trim())\n let table = options.table ?? options.create\n let create = options.create !== undefined\n if (table === undefined) {\n const guessed = guessTable(snake)\n if (guessed) ({ table, create } = guessed)\n }\n const stub = table === undefined ? MIGRATION_STUB : create ? MIGRATION_CREATE_STUB : MIGRATION_UPDATE_STUB\n const file = join(path, `${migrationDatePrefix(options.date)}_${snake}.ts`)\n if (existsSync(file)) throw new LogicError(`Migration [${file}] already exists.`)\n mkdirSync(path, { recursive: true })\n writeFileSync(\n file,\n stub.replaceAll('{{ importSource }}', options.importSource ?? '@orieljs/framework').replaceAll('{{ table }}', table ?? ''),\n )\n return file\n }\n}\n","import type { Connection } from '../Connection'\n\nexport interface MigrationRecord {\n migration: string\n batch: number\n}\n\n/** The migrations table (id, migration, batch): which migration ran in which batch (Laravel's DatabaseMigrationRepository). */\nexport class MigrationRepository {\n constructor(\n protected readonly connection: Connection,\n readonly table = 'migrations',\n ) {}\n\n async repositoryExists(): Promise<boolean> {\n return this.connection.getSchemaBuilder().hasTable(this.table)\n }\n\n async createRepository(): Promise<void> {\n await this.connection.getSchemaBuilder().create(this.table, (table) => {\n table.increments('id')\n table.string('migration')\n table.integer('batch')\n })\n }\n\n async deleteRepository(): Promise<void> {\n await this.connection.getSchemaBuilder().dropIfExists(this.table)\n }\n\n /** Every migration that ran, oldest first. */\n async getRan(): Promise<string[]> {\n return (await this.query().orderBy('batch').orderBy('migration').pluck<string>('migration')).all()\n }\n\n /** The last `steps` migrations, newest first. */\n async getMigrations(steps: number): Promise<MigrationRecord[]> {\n return this.records(this.query().where('batch', '>=', 1).orderBy('batch', 'desc').orderBy('migration', 'desc').limit(steps))\n }\n\n /** The migrations of one batch, newest first. */\n async getMigrationsByBatch(batch: number): Promise<MigrationRecord[]> {\n return this.records(this.query().where('batch', batch).orderBy('migration', 'desc'))\n }\n\n /** The migrations of the last batch, newest first. */\n async getLast(): Promise<MigrationRecord[]> {\n return this.getMigrationsByBatch(await this.getLastBatchNumber())\n }\n\n /** migration name → batch. */\n async getMigrationBatches(): Promise<Record<string, number>> {\n const rows = await this.records(this.query().orderBy('batch').orderBy('migration'))\n return Object.fromEntries(rows.map((row) => [row.migration, row.batch]))\n }\n\n async log(migration: string, batch: number): Promise<void> {\n await this.query().insert({ migration, batch })\n }\n\n async delete(migration: string): Promise<void> {\n await this.query().where('migration', migration).delete()\n }\n\n async getNextBatchNumber(): Promise<number> {\n return (await this.getLastBatchNumber()) + 1\n }\n\n async getLastBatchNumber(): Promise<number> {\n return Number((await this.query().max('batch')) ?? 0)\n }\n\n private query() {\n return this.connection.table<MigrationRecord>(this.table)\n }\n\n private async records(query: ReturnType<MigrationRepository['query']>): Promise<MigrationRecord[]> {\n return (await query.get()).all().map((row) => ({ migration: String(row.migration), batch: Number(row.batch) }))\n }\n}\n","import { existsSync, readdirSync } from 'node:fs'\nimport { basename, extname, join } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport type { Connection } from '../Connection'\nimport type { DatabaseManagerImpl } from '../DatabaseManager'\nimport { LogicError } from '../errors'\nimport { assertSqliteForeignKeys, sqliteForeignKeysEnabled } from '../Schema/SqliteTableRebuild'\nimport { Migration } from './Migration'\nimport { MigrationRepository } from './MigrationRepository'\n\n/** Why a SQLite migration's foreign key check can fail where the same changes pass with foreign keys on. */\nconst SQLITE_MIGRATION_HINT =\n \"SQLite runs a migration with foreign keys off, so ON DELETE and ON UPDATE actions don't run in it: change the child rows first, or set withinTransaction = false.\"\n\nconst MIGRATION_FILE = /^(?!.*\\.d\\.[mc]?ts$).+\\.(ts|js|mts|mjs)$/\n\nexport interface MigrationStatus {\n name: string\n ran: boolean\n batch: number | undefined\n}\n\nexport interface MigratorOptions {\n /** Run each migration in its own batch (migrate --step). */\n step?: boolean\n}\n\nexport interface RollbackOptions {\n /** Roll back this many migrations instead of the last batch. */\n step?: number\n /** Roll back one batch by number. */\n batch?: number\n}\n\n/**\n * Runs database/migrations/*.ts in file-name order and records them in the migrations table\n * (Laravel's Migrator). Output lines go to `output`.\n */\nexport class Migrator {\n private connectionName: string | undefined\n\n constructor(\n protected readonly manager: DatabaseManagerImpl,\n protected readonly output: (line: string) => void = () => undefined,\n ) {}\n\n /** Use another connection for the repository and for migrations that don't name one (--database). */\n setConnection(name: string | undefined): this {\n this.connectionName = name\n return this\n }\n\n getConnection(): Connection {\n return this.manager.connection(this.connectionName)\n }\n\n getRepository(): MigrationRepository {\n return new MigrationRepository(this.getConnection(), this.manager.migrationsTable())\n }\n\n /** migration name (file name without extension) → absolute path, sorted by name across all paths. */\n getMigrationFiles(paths: readonly string[]): Map<string, string> {\n const files: Array<[string, string]> = []\n for (const path of paths) {\n if (!existsSync(path)) continue\n for (const file of readdirSync(path)) {\n if (MIGRATION_FILE.test(file)) files.push([basename(file, extname(file)), join(path, file)])\n }\n }\n return new Map(files.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))\n }\n\n /** Creates the migrations table when it doesn't exist yet. */\n async ensureRepository(): Promise<MigrationRepository> {\n const repository = this.getRepository()\n if (!(await repository.repositoryExists())) await repository.createRepository()\n return repository\n }\n\n /** Runs every pending migration in one new batch (or one batch each with step). Returns their names. */\n async run(paths: readonly string[], options: MigratorOptions = {}): Promise<string[]> {\n const repository = await this.ensureRepository()\n const ran = new Set(await repository.getRan())\n const pending = [...this.getMigrationFiles(paths)].filter(([name]) => !ran.has(name))\n if (!pending.length) {\n this.output('Nothing to migrate.')\n return []\n }\n let batch = await repository.getNextBatchNumber()\n this.output('Running migrations.')\n for (const [name, file] of pending) {\n await this.runMigration(await this.resolve(file), 'up')\n await repository.log(name, batch)\n this.output(` ${name} DONE`)\n if (options.step) batch++\n }\n return pending.map(([name]) => name)\n }\n\n /** Rolls back the last batch (or the last `step` migrations, or one batch). Returns the names rolled back. */\n async rollback(paths: readonly string[], options: RollbackOptions = {}): Promise<string[]> {\n const repository = await this.ensureRepository()\n const records = options.step\n ? await repository.getMigrations(options.step)\n : options.batch\n ? await repository.getMigrationsByBatch(options.batch)\n : await repository.getLast()\n if (!records.length) {\n this.output('Nothing to rollback.')\n return []\n }\n this.output('Rolling back migrations.')\n return this.rollDown(paths, records.map((record) => record.migration), repository)\n }\n\n /** Rolls back every migration, newest first. */\n async reset(paths: readonly string[]): Promise<string[]> {\n const repository = await this.ensureRepository()\n const ran = (await repository.getRan()).reverse()\n if (!ran.length) {\n this.output('Nothing to rollback.')\n return []\n }\n this.output('Rolling back migrations.')\n return this.rollDown(paths, ran, repository)\n }\n\n /** Drops every table, then runs every migration (migrate:fresh). */\n async fresh(paths: readonly string[]): Promise<string[]> {\n await this.getConnection().getSchemaBuilder().dropAllTables()\n this.output('Dropping all tables DONE')\n return this.run(paths)\n }\n\n /** Every migration file and every recorded migration, with its batch (all pending without a migrations table). */\n async status(paths: readonly string[]): Promise<MigrationStatus[]> {\n const repository = this.getRepository()\n const batches = (await repository.repositoryExists()) ? await repository.getMigrationBatches() : {}\n const names = new Set([...this.getMigrationFiles(paths).keys(), ...Object.keys(batches)])\n return [...names].sort().map((name) => ({ name, ran: name in batches, batch: batches[name] }))\n }\n\n /** Imports a migration file; its default export is a Migration class (or instance). */\n async resolve(file: string): Promise<Migration> {\n const module = (await import(pathToFileURL(file).href)) as { default?: unknown }\n const exported = module.default\n const migration = typeof exported === 'function' ? new (exported as new () => unknown)() : exported\n if (!(migration instanceof Migration)) {\n throw new LogicError(`Migration [${basename(file)}] must default-export a class extending Migration.`)\n }\n return migration\n }\n\n private async rollDown(paths: readonly string[], names: string[], repository: MigrationRepository): Promise<string[]> {\n const files = this.getMigrationFiles(paths)\n const rolledBack: string[] = []\n for (const name of names) {\n const file = files.get(name)\n if (!file) {\n this.output(` ${name} Migration not found`)\n continue\n }\n await this.runMigration(await this.resolve(file), 'down')\n await repository.delete(name)\n this.output(` ${name} DONE`)\n rolledBack.push(name)\n }\n return rolledBack\n }\n\n /** Runs up/down on the migration's connection (made the default meanwhile), in a transaction where DDL allows it. */\n private async runMigration(migration: Migration, method: 'up' | 'down'): Promise<void> {\n const name = migration.connection ?? this.connectionName\n await this.manager.usingConnection(name, async () => {\n const connection = this.manager.connection(name)\n const run = async () => {\n await migration[method]()\n }\n if (connection.getDriverName() === 'sqlite') await this.runOnSqlite(connection, migration, run)\n else if (migration.withinTransaction && connection.getDriverName() !== 'mysql') await connection.transaction(run)\n else await run()\n })\n }\n\n /**\n * SQLite's order for a migration in a transaction: foreign keys off before the transaction (SQLite ignores the pragma\n * inside one, and a table rebuild would otherwise run the ON DELETE actions of the tables that reference it), the\n * migration, a foreign key check before the commit (rows that break a key fail the migration), then foreign keys back\n * on. A migration outside a transaction runs with foreign keys as they are, so its ON DELETE and ON UPDATE actions\n * run; a table rebuild in it turns them off around itself and checks the table.\n */\n private async runOnSqlite(connection: Connection, migration: Migration, run: () => Promise<void>): Promise<void> {\n if (!migration.withinTransaction) return run()\n const toggle = connection.transactionLevel() === 0 && (await sqliteForeignKeysEnabled(connection))\n if (toggle) await connection.statement('PRAGMA foreign_keys = OFF')\n try {\n await connection.transaction(async () => {\n await run()\n if (toggle) await assertSqliteForeignKeys(connection, undefined, SQLITE_MIGRATION_HINT)\n })\n } finally {\n if (toggle) await connection.statement('PRAGMA foreign_keys = ON')\n }\n }\n}\n","import { Model } from './Eloquent/Model'\n\nexport type SeederClass = new () => Seeder\n\n/**\n * A database seeder (database/seeders/*.ts): run() inserts data, call() runs other seeders. Seeders run with mass\n * assignment protection off, as with Laravel's db:seed.\n */\nexport abstract class Seeder {\n protected output: (line: string) => void = () => undefined\n\n abstract run(): Promise<void> | void\n\n setOutput(output: (line: string) => void): this {\n this.output = output\n return this\n }\n\n /** Runs other seeders in order, printing their names. */\n async call(...seeders: Array<SeederClass | SeederClass[]>): Promise<void> {\n for (const seeder of seeders.flat()) {\n this.output(` ${seeder.name} RUNNING`)\n await new seeder().setOutput(this.output).invoke()\n this.output(` ${seeder.name} DONE`)\n }\n }\n\n /** Runs other seeders without output. */\n async callSilent(...seeders: Array<SeederClass | SeederClass[]>): Promise<void> {\n for (const seeder of seeders.flat()) await new seeder().invoke()\n }\n\n /** Runs run() unguarded. */\n async invoke(): Promise<void> {\n await Model.unguarded(() => this.run())\n }\n}\n","import { existsSync } from 'node:fs'\nimport { isAbsolute, join, relative } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport type { Application, CommandContext, ConsoleKernel } from '@orieljs/contracts'\nimport type { DatabaseManagerImpl } from '../DatabaseManager'\nimport { LogicError } from '../errors'\nimport { MigrationCreator } from '../Migrations/MigrationCreator'\nimport { Migrator } from '../Migrations/Migrator'\nimport type { ModelRegistry } from '../ModelRegistry'\nimport { Seeder } from '../Seeder'\nimport { TypeGenerator } from '../Types/TypeGenerator'\n\n/** The parts of the application and database the commands need (resolved lazily, when a command runs). */\nexport interface DatabaseCommandContext {\n app: Pick<Application, 'basePath' | 'databasePath' | 'isProduction'>\n manager(): DatabaseManagerImpl\n /** The discovered models. When given, model:types works and migrate regenerates the types outside production. */\n models?(): Promise<ModelRegistry>\n /** The package generated types import from (default '@orieljs/framework'). */\n typesImportSource?: string\n /** The package make:migration's stubs import from (default '@orieljs/framework'). */\n stubsImportSource?: string\n}\n\ntype Handler = (command: CommandContext) => Promise<number>\n\nconst text = (value: unknown): string | undefined => (typeof value === 'string' && value !== '' ? value : undefined)\nconst list = (value: unknown): string[] => (Array.isArray(value) ? value.map(String) : text(value) ? [String(value)] : [])\nconst integer = (value: unknown): number => {\n const number = Number(value ?? 0)\n return Number.isInteger(number) && number > 0 ? number : 0\n}\n\n/** A closure command with Laravel's description (shown by `oriel list`). */\nfunction define(kernel: ConsoleKernel, signature: string, description: string, handler: Handler): void {\n kernel\n .command(signature, async function (this: CommandContext) {\n return handler(this)\n })\n .purpose(description)\n}\n\n/** Laravel's ConfirmableTrait without the prompt: in production the command needs --force. */\nfunction confirmToProceed(context: DatabaseCommandContext, command: CommandContext): boolean {\n if (!context.app.isProduction() || command.option('force') === true) return true\n command.error('Application in production. Use --force to run this command.')\n return false\n}\n\n/** --path values (relative to the base path), or database/migrations. */\nfunction migrationPaths(context: DatabaseCommandContext, command: CommandContext): string[] {\n const paths = list(command.option('path'))\n if (!paths.length) return [context.app.databasePath('migrations')]\n return paths.map((path) => (isAbsolute(path) ? path : context.app.basePath(path)))\n}\n\nfunction migrator(context: DatabaseCommandContext, command: CommandContext): Migrator {\n return new Migrator(context.manager(), (line) => command.line(line)).setConnection(text(command.option('database')))\n}\n\n/** Imports database/seeders/<Class>.ts and runs it (default export or the export named after the class). */\nexport async function runSeeder(context: DatabaseCommandContext, className: string, output: (line: string) => void, database?: string): Promise<void> {\n const name = className.split('\\\\').pop()!\n const file = ['ts', 'js', 'mts', 'mjs'].map((extension) => context.app.databasePath(join('seeders', `${name}.${extension}`))).find(existsSync)\n if (!file) throw new LogicError(`Seeder [${name}] not found in ${context.app.databasePath('seeders')}.`)\n const module = (await import(pathToFileURL(file).href)) as Record<string, unknown>\n const exported = module.default ?? module[name]\n const seeder = typeof exported === 'function' ? new (exported as new () => unknown)() : exported\n if (!(seeder instanceof Seeder)) throw new LogicError(`Seeder [${name}] must export a class extending Seeder.`)\n await context.manager().usingConnection(database, () => seeder.setOutput(output).invoke())\n}\n\n/** Writes types/models.d.ts for the discovered models; returns the path relative to the base path. */\nexport async function generateModelTypes(context: DatabaseCommandContext): Promise<string | undefined> {\n if (!context.models) return undefined\n const outputFile = context.app.basePath(join('types', 'models.d.ts'))\n await new TypeGenerator({ outputFile, importSource: context.typesImportSource }).write((await context.models()).all())\n return relative(context.app.basePath(), outputFile)\n}\n\n/** After migrate, migrate:fresh and migrate:refresh: regenerates the model types, for apps that keep them (types/). */\nasync function writeModelTypes(context: DatabaseCommandContext, command: CommandContext): Promise<void> {\n if (context.app.isProduction() || !existsSync(context.app.basePath('types'))) return\n const written = await generateModelTypes(context)\n if (written) command.line(`Model types written to ${written}.`)\n}\n\n/** Laravel's needsSeeding(): --seed, or a --seeder class on its own. */\nasync function seedIfRequested(context: DatabaseCommandContext, command: CommandContext): Promise<void> {\n const seeder = text(command.option('seeder'))\n if (command.option('seed') !== true && seeder === undefined) return\n command.info('Seeding database.')\n await runSeeder(context, seeder ?? 'DatabaseSeeder', (line) => command.line(line), text(command.option('database')))\n}\n\n/** The migrate*, migrate:install, db:seed and make:migration commands (closure commands, PC1). */\nexport function registerMigrationCommands(kernel: ConsoleKernel, context: DatabaseCommandContext): void {\n define(kernel, 'migrate {--database=} {--force} {--path=*} {--seed} {--seeder=} {--step}', 'Run the database migrations', async (command) => {\n if (!confirmToProceed(context, command)) return 1\n await migrator(context, command).run(migrationPaths(context, command), { step: command.option('step') === true })\n await seedIfRequested(context, command)\n await writeModelTypes(context, command)\n return 0\n })\n\n define(kernel, 'migrate:install {--database=}', 'Create the migration repository', async (command) => {\n const repository = migrator(context, command).getRepository()\n if (!(await repository.repositoryExists())) await repository.createRepository()\n command.info('Migration table created successfully.')\n return 0\n })\n\n define(kernel, 'migrate:rollback {--database=} {--force} {--path=*} {--step=0} {--batch=0}', 'Rollback the last database migration', async (command) => {\n if (!confirmToProceed(context, command)) return 1\n await migrator(context, command).rollback(migrationPaths(context, command), {\n step: integer(command.option('step')),\n batch: integer(command.option('batch')),\n })\n return 0\n })\n\n define(kernel, 'migrate:reset {--database=} {--force} {--path=*}', 'Rollback all database migrations', async (command) => {\n if (!confirmToProceed(context, command)) return 1\n await migrator(context, command).reset(migrationPaths(context, command))\n return 0\n })\n\n define(kernel, 'migrate:refresh {--database=} {--force} {--path=*} {--seed} {--seeder=} {--step=0}', 'Reset and re-run all migrations', async (command) => {\n if (!confirmToProceed(context, command)) return 1\n const instance = migrator(context, command)\n const paths = migrationPaths(context, command)\n const step = integer(command.option('step'))\n if (step) await instance.rollback(paths, { step })\n else await instance.reset(paths)\n await instance.run(paths)\n await seedIfRequested(context, command)\n await writeModelTypes(context, command)\n return 0\n })\n\n define(kernel, 'migrate:fresh {--database=} {--force} {--path=*} {--seed} {--seeder=}', 'Drop all tables and re-run all migrations', async (command) => {\n if (!confirmToProceed(context, command)) return 1\n await migrator(context, command).fresh(migrationPaths(context, command))\n await seedIfRequested(context, command)\n await writeModelTypes(context, command)\n return 0\n })\n\n define(kernel, 'migrate:status {--database=} {--path=*}', 'Show the status of each migration', async (command) => {\n const instance = migrator(context, command)\n if (!(await instance.getRepository().repositoryExists())) {\n command.error('Migration table not found.')\n return 1\n }\n for (const status of await instance.status(migrationPaths(context, command))) {\n command.line(status.ran ? ` ${status.name} [${status.batch}] Ran` : ` ${status.name} Pending`)\n }\n return 0\n })\n\n define(kernel, 'db:seed {class?} {--class=DatabaseSeeder} {--database=} {--force}', 'Seed the database with records', async (command) => {\n if (!confirmToProceed(context, command)) return 1\n command.info('Seeding database.')\n const className = text(command.argument('class')) ?? text(command.option('class')) ?? 'DatabaseSeeder'\n await runSeeder(context, className, (line) => command.line(line), text(command.option('database')))\n return 0\n })\n\n const makeMigration =\n 'make:migration {name : The name of the migration} {--create= : The table to be created} ' +\n '{--table= : The table to migrate} {--path= : The location where the migration file should be created}'\n define(kernel, makeMigration, 'Create a new migration file', async (command) => {\n const name = text(command.argument('name'))\n if (name === undefined) {\n command.error('Not enough arguments (missing: \"name\").')\n return 1\n }\n const path = text(command.option('path'))\n const directory = path === undefined ? context.app.databasePath('migrations') : isAbsolute(path) ? path : context.app.basePath(path)\n const file = new MigrationCreator().create(name, directory, {\n create: text(command.option('create')),\n table: text(command.option('table')),\n importSource: context.stubsImportSource,\n })\n command.info(`Migration [${relative(context.app.basePath(), file)}] created successfully.`)\n return 0\n })\n}\n\n/** model:types: regenerates types/models.d.ts from the database schema and the discovered models. */\nexport function registerModelTypesCommand(kernel: ConsoleKernel, context: DatabaseCommandContext): void {\n define(kernel, 'model:types', \"Generate TypeScript types for the application's models\", async (command) => {\n const written = await generateModelTypes(context)\n if (!written) {\n command.error('No models registry is available: is DatabaseServiceProvider registered?')\n return 1\n }\n command.info(`Model types written to ${written}.`)\n return 0\n })\n}\n","import { mkdir, writeFile } from 'node:fs/promises'\nimport { dirname, relative, sep } from 'node:path'\nimport { Str } from '@orieljs/support'\nimport { enumValues, type CastDefinition } from '../Eloquent/casts'\nimport { Model } from '../Eloquent/Model'\nimport type { RegisteredModel } from '../ModelRegistry'\nimport type { ColumnInfo } from '../Schema/Grammar'\n\nexport interface TypeGeneratorOptions {\n /** Where the declarations go (the skeleton: types/models.d.ts). */\n outputFile: string\n /** The package the generated file imports ScopeStatic from. */\n importSource?: string\n}\n\nconst INTEGER = new Set(['int', 'integer', 'int2', 'int4', 'int8', 'bigint', 'smallint', 'mediumint', 'tinyint', 'serial', 'bigserial', 'smallserial', 'year'])\nconst FLOAT = new Set(['float', 'float4', 'float8', 'double', 'double precision', 'real'])\nconst BOOLEAN = new Set(['bool', 'boolean'])\nconst JSON_TYPES = new Set(['json', 'jsonb'])\nconst BINARY = new Set(['blob', 'bytea', 'binary', 'varbinary', 'longblob', 'mediumblob', 'tinyblob'])\n\n/** The TypeScript type for a cast, or undefined when the column type decides. */\nfunction castType(cast: CastDefinition | undefined): string | undefined {\n if (cast === undefined) return undefined\n if (typeof cast === 'string') {\n if (['int', 'integer', 'float', 'double', 'real', 'timestamp'].includes(cast)) return 'number'\n if (cast === 'string' || cast === 'hashed' || cast.startsWith('decimal:')) return 'string'\n if (cast === 'bool' || cast === 'boolean') return 'boolean'\n if (['date', 'datetime', 'immutable_date', 'immutable_datetime'].includes(cast)) return 'Date'\n return 'unknown'\n }\n if (typeof cast === 'object' && typeof (cast as { get?: unknown }).get !== 'function') {\n const literal = (value: string | number) => (typeof value === 'number' ? String(value) : `'${value.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`)\n return enumValues(cast as Record<string, string | number>).map(literal).join(' | ') || 'never'\n }\n return 'unknown'\n}\n\n/** The TypeScript type for a database column type (what the drivers hand back without a cast). */\nfunction columnType(column: ColumnInfo): string {\n const name = column.type_name.toLowerCase()\n if (INTEGER.has(name)) return 'number'\n if (FLOAT.has(name)) return 'number'\n if (BOOLEAN.has(name)) return 'boolean'\n if (JSON_TYPES.has(name)) return 'unknown'\n if (BINARY.has(name)) return 'Buffer'\n return 'string'\n}\n\n/** The get<Name>Attribute accessors on a model class, as [attribute, method] pairs. */\nfunction accessors(model: typeof Model): Array<[string, string]> {\n const found = new Map<string, string>()\n for (let proto: object | null = model.prototype; proto && proto !== Model.prototype; proto = Object.getPrototypeOf(proto) as object | null) {\n for (const key of Object.getOwnPropertyNames(proto)) {\n const match = /^get(.+)Attribute$/.exec(key)\n if (match && typeof Reflect.get(proto, key) === 'function' && !found.has(Str.snake(match[1]!))) found.set(Str.snake(match[1]!), key)\n }\n }\n return [...found]\n}\n\n/** The static scope<Name> methods of a model class, as [builder method, static method] pairs. */\nfunction scopes(model: typeof Model): Array<[string, string]> {\n const found = new Map<string, string>()\n for (let current: unknown = model; current && current !== Model; current = Object.getPrototypeOf(current)) {\n for (const key of Object.getOwnPropertyNames(current)) {\n if (key.startsWith('scope') && key.length > 5 && typeof Reflect.get(current as object, key) === 'function') {\n const name = Str.lcfirst(key.slice(5))\n if (!found.has(name)) found.set(name, key)\n }\n }\n }\n return [...found]\n}\n\n/**\n * Writes types/models.d.ts: for every model, the attribute types (from the database columns and the model's casts)\n * merged into the class by declaration merging, the phantom $attributes that Column<M> reads, accessor-only\n * attributes, and the static scope proxies (Post.published()).\n */\nexport class TypeGenerator {\n constructor(private readonly options: TypeGeneratorOptions) {}\n\n async generate(models: readonly RegisteredModel[]): Promise<string> {\n const blocks: string[] = []\n for (const entry of [...models].sort((a, b) => a.name.localeCompare(b.name))) {\n if (!entry.file) continue\n const block = await this.modelBlock(entry)\n if (block) blocks.push(block)\n }\n const importSource = this.options.importSource ?? '@orieljs/framework'\n return [\n '// Generated by `oriel model:types`. Do not edit: run `oriel model:types` (or `oriel migrate`) again.',\n // Built by concatenation so tools that scan source for imports don't mistake this template for one.\n 'import type { ScopeStatic } from ' + `'${importSource}'`,\n '',\n ...blocks,\n ].join('\\n')\n }\n\n /** Generates and writes the file; returns its path. */\n async write(models: readonly RegisteredModel[]): Promise<string> {\n await mkdir(dirname(this.options.outputFile), { recursive: true })\n await writeFile(this.options.outputFile, await this.generate(models))\n return this.options.outputFile\n }\n\n private async modelBlock({ name, model, file }: RegisteredModel): Promise<string | undefined> {\n const instance = model.prototypeInstance()\n const columns = await instance.getConnection().getSchemaBuilder().getColumns(instance.getTable())\n if (!columns.length) return undefined\n const casts = instance.getCasts()\n const attributes = columns.map((column) => {\n const type = castType(casts[column.name]) ?? columnType(column)\n return [column.name, column.nullable && type !== 'unknown' ? `${type} | null` : type] as const\n })\n const members = attributes.filter(([column]) => !(column in instance))\n const extra = accessors(model).filter(([attribute]) => !columns.some((column) => column.name === attribute) && !(attribute in instance))\n const statics = scopes(model).filter(([method]) => !(method in Model))\n // The columns toJSON() leaves out: page prop types (Inertia) don't offer them.\n const hidden = instance.getHidden().filter((column) => columns.some(({ name: columnName }) => columnName === column))\n const lines = [\n 'declare module ' + `'${this.modulePath(file!)}' {`,\n ` interface ${name} {`,\n ' $attributes?: {',\n ...attributes.map(([column, type]) => ` ${this.key(column)}: ${type}`),\n ' }',\n ...(hidden.length ? [` $hidden?: ${hidden.map((column) => `'${column}'`).join(' | ')}`] : []),\n ...members.map(([column, type]) => ` ${this.key(column)}: ${type}`),\n ...extra.map(([attribute, method]) => ` ${this.key(attribute)}: ReturnType<${name}['${method}']>`),\n ' }',\n ]\n if (statics.length) {\n lines.push(` namespace ${name} {`, ...statics.map(([method, key]) => ` const ${method}: ScopeStatic<typeof ${name}, '${key}'>`), ' }')\n }\n lines.push('}', '')\n return lines.join('\\n')\n }\n\n /** '../app/Models/Post' for app/Models/Post.ts, relative to the output file. */\n private modulePath(file: string): string {\n const path = relative(dirname(this.options.outputFile), file).split(sep).join('/').replace(/\\.(ts|js|mts|mjs)$/, '')\n return path.startsWith('.') ? path : `./${path}`\n }\n\n private key(name: string): string {\n return /^[A-Za-z_$][\\w$]*$/.test(name) ? name : JSON.stringify(name)\n }\n}\n","import { existsSync, readdirSync, statSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { Str } from '@orieljs/support'\nimport { Model } from './Eloquent/Model'\n\nexport interface RegisteredModel {\n name: string\n model: typeof Model\n /** The file it was discovered in (used by model:types for the module path). */\n file?: string\n}\n\nconst MODEL_FILE = /^(?!.*\\.d\\.[mc]?ts$).+\\.(ts|js|mts|mjs)$/\n\n/**\n * The application's models, auto-discovered from app/Models: route model binding ({post} → Post), model:types,\n * and morphTo (through the ClassRegistry) look models up here by name.\n */\nexport class ModelRegistry {\n private readonly models = new Map<string, RegisteredModel>()\n\n /** Registers a model class (booting it, so static scope proxies such as Post.published() exist). */\n register(model: typeof Model, file?: string): RegisteredModel {\n const entry: RegisteredModel = { name: model.name, model, file }\n this.models.set(model.name, entry)\n model.bootIfNotBooted()\n return entry\n }\n\n /** Imports every file under `directory` and registers each exported Model subclass. */\n async discover(directory: string): Promise<RegisteredModel[]> {\n const found: RegisteredModel[] = []\n for (const file of listFiles(directory)) {\n const module = (await import(pathToFileURL(file).href)) as Record<string, unknown>\n for (const exported of Object.values(module)) {\n if (typeof exported === 'function' && exported.prototype instanceof Model && !this.models.has(exported.name)) {\n found.push(this.register(exported as typeof Model, file))\n }\n }\n }\n return found\n }\n\n /** A model by class name or route parameter name: 'Post', 'post', 'blog_post' and 'blogPost' find BlogPost. */\n get(name: string): RegisteredModel | undefined {\n return this.models.get(name) ?? this.models.get(Str.studly(name))\n }\n\n resolve(name: string): typeof Model | undefined {\n return this.get(name)?.model\n }\n\n has(name: string): boolean {\n return this.get(name) !== undefined\n }\n\n all(): RegisteredModel[] {\n return [...this.models.values()]\n }\n}\n\nfunction listFiles(directory: string): string[] {\n if (!existsSync(directory)) return []\n const files: string[] = []\n for (const entry of readdirSync(directory).sort()) {\n const path = join(directory, entry)\n if (statSync(path).isDirectory()) files.push(...listFiles(path))\n else if (MODEL_FILE.test(entry)) files.push(path)\n }\n return files\n}\n","import { randomUUID } from 'node:crypto'\nimport { DatabaseError, LogicError } from '../../errors'\n\nconst FIRST_NAMES = [\n 'Taylor', 'Abigail', 'Dayle', 'Mohamed', 'Jess', 'Nuno', 'James', 'Tim', 'Joe', 'Dries', 'Ana', 'Maria', 'Sofia',\n 'Liam', 'Noah', 'Emma', 'Olivia', 'Ava', 'Mia', 'Lucas', 'Hugo', 'Lea', 'Ines', 'Yuki', 'Aarav', 'Zara', 'Omar',\n 'Chloe', 'Ethan', 'Grace', 'Isaac', 'Julia', 'Kai', 'Leo', 'Nora', 'Owen', 'Priya', 'Quinn', 'Ruby', 'Sam',\n]\nconst LAST_NAMES = [\n 'Otwell', 'Smith', 'Johnson', 'Brown', 'Garcia', 'Miller', 'Davis', 'Martin', 'Lopez', 'Wilson', 'Anderson',\n 'Thomas', 'Moore', 'Jackson', 'White', 'Harris', 'Clark', 'Lewis', 'Walker', 'Hall', 'Young', 'King', 'Wright',\n 'Scott', 'Green', 'Baker', 'Adams', 'Nelson', 'Hill', 'Campbell', 'Mitchell', 'Roberts', 'Carter', 'Phillips',\n]\nconst WORDS = [\n 'lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur', 'adipiscing', 'elit', 'sed', 'do', 'eiusmod', 'tempor',\n 'incididunt', 'ut', 'labore', 'et', 'dolore', 'magna', 'aliqua', 'enim', 'ad', 'minim', 'veniam', 'quis', 'nostrud',\n 'exercitation', 'ullamco', 'laboris', 'nisi', 'aliquip', 'ex', 'ea', 'commodo', 'consequat', 'duis', 'aute',\n 'irure', 'in', 'reprehenderit', 'voluptate', 'velit', 'esse', 'cillum', 'fugiat', 'nulla', 'pariatur', 'excepteur',\n 'sint', 'occaecat', 'cupidatat', 'non', 'proident', 'sunt', 'culpa', 'qui', 'officia', 'deserunt', 'mollit', 'anim',\n]\nconst DOMAINS = ['example.com', 'example.org', 'example.net']\nconst CITIES = ['Springfield', 'Riverside', 'Fairview', 'Madison', 'Georgetown', 'Clinton', 'Salem', 'Franklin', 'Greenville', 'Bristol']\nconst COUNTRIES = ['France', 'Japan', 'Brazil', 'Canada', 'India', 'Kenya', 'Spain', 'Norway', 'Chile', 'Vietnam']\nconst COMPANY_SUFFIXES = ['Inc', 'LLC', 'Group', 'Ltd', 'and Sons']\n\n/** Thrown by fake().unique() when it can't find a new value (Laravel's OverflowException). */\nexport class FakerOverflowError extends DatabaseError {\n override readonly name = 'FakerOverflowError'\n}\n\nconst DURATION = /^([+-]?\\d+)\\s*(second|minute|hour|day|week|month|year)s?$/i\nconst UNIT_MS: Record<string, number> = {\n second: 1000, minute: 60_000, hour: 3_600_000, day: 86_400_000, week: 604_800_000, month: 2_629_800_000, year: 31_557_600_000,\n}\n\n/**\n * A small built-in fake data generator for factories and tests (the subset of Faker that factories typically use).\n * Seedable for repeatable data: fake().seed(1234). For anything richer, use sequence() or plain JavaScript.\n */\nexport class Faker {\n private state = Math.floor(Math.random() * 2 ** 32)\n private uniqueProxy: Faker | undefined\n private readonly seen = new Map<string, Set<unknown>>()\n\n /** Makes the sequence repeatable. */\n seed(seed: number): this {\n this.state = seed >>> 0\n return this\n }\n\n /** A float in [0, 1) (mulberry32). */\n random(): number {\n this.state = (this.state + 0x6d2b79f5) >>> 0\n let t = this.state\n t = Math.imul(t ^ (t >>> 15), t | 1)\n t ^= t + Math.imul(t ^ (t >>> 7), t | 61)\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296\n }\n\n /**\n * The same generator, but every call returns a value it hasn't returned before (per method). reset clears the\n * memory. Throws FakerOverflowError after 10000 tries.\n */\n unique(reset = false): Faker {\n if (reset) this.seen.clear()\n this.uniqueProxy ??= new Proxy(this, {\n get: (target, key, receiver) => {\n const value: unknown = Reflect.get(target, key, receiver)\n if (typeof value !== 'function' || typeof key === 'symbol' || key === 'unique' || key === 'seed' || key === 'random') return value\n return (...args: unknown[]) => {\n const seen = target.seen.get(key) ?? new Set<unknown>()\n target.seen.set(key, seen)\n for (let i = 0; i < 10_000; i++) {\n const candidate: unknown = (value as (...a: unknown[]) => unknown).apply(target, args)\n const fingerprint = typeof candidate === 'object' ? JSON.stringify(candidate) : candidate\n if (!seen.has(fingerprint)) {\n seen.add(fingerprint)\n return candidate\n }\n }\n throw new FakerOverflowError('Maximum retries of 10000 reached without finding a unique value')\n }\n },\n })\n return this.uniqueProxy\n }\n\n numberBetween(min = 0, max = 2147483647): number {\n return Math.floor(this.random() * (max - min + 1)) + min\n }\n\n /** A random integer with up to `digits` digits (strict: exactly that many). */\n randomNumber(digits = 9, strict = false): number {\n const max = 10 ** digits - 1\n return strict ? this.numberBetween(10 ** (digits - 1), max) : this.numberBetween(0, max)\n }\n\n randomFloat(decimals = 2, min = 0, max = 1000): number {\n return Number((this.random() * (max - min) + min).toFixed(decimals))\n }\n\n randomDigit(): number {\n return this.numberBetween(0, 9)\n }\n\n /** true with `chanceOfGettingTrue` percent. */\n boolean(chanceOfGettingTrue = 50): boolean {\n return this.random() * 100 < chanceOfGettingTrue\n }\n\n randomElement<T>(items: readonly T[]): T {\n if (!items.length) throw new LogicError('randomElement() needs at least one item.')\n return items[this.numberBetween(0, items.length - 1)]!\n }\n\n /** `count` distinct items, in random order. */\n randomElements<T>(items: readonly T[], count = 1): T[] {\n const pool = [...items]\n const picked: T[] = []\n while (picked.length < count && pool.length) picked.push(pool.splice(this.numberBetween(0, pool.length - 1), 1)[0]!)\n return picked\n }\n\n shuffle<T>(items: readonly T[]): T[] {\n return this.randomElements(items, items.length)\n }\n\n firstName(): string {\n return this.randomElement(FIRST_NAMES)\n }\n\n lastName(): string {\n return this.randomElement(LAST_NAMES)\n }\n\n name(): string {\n return `${this.firstName()} ${this.lastName()}`\n }\n\n userName(): string {\n return `${this.firstName().toLowerCase()}.${this.lastName().toLowerCase()}${this.numberBetween(1, 999)}`\n }\n\n /** An address at example.com/org/net, which never delivers mail. */\n safeEmail(): string {\n return `${this.userName()}@${this.randomElement(DOMAINS)}`\n }\n\n email(): string {\n return this.safeEmail()\n }\n\n word(): string {\n return this.randomElement(WORDS)\n }\n\n words(count = 3): string[] {\n return Array.from({ length: count }, () => this.word())\n }\n\n sentence(words = 6): string {\n const text = this.words(Math.max(1, words)).join(' ')\n return `${text.charAt(0).toUpperCase()}${text.slice(1)}.`\n }\n\n sentences(count = 3): string[] {\n return Array.from({ length: count }, () => this.sentence(this.numberBetween(4, 10)))\n }\n\n paragraph(sentences = 3): string {\n return this.sentences(sentences).join(' ')\n }\n\n paragraphs(count = 3): string[] {\n return Array.from({ length: count }, () => this.paragraph())\n }\n\n /** Text of at most `maxChars` characters. */\n text(maxChars = 200): string {\n let text = ''\n while (text.length < maxChars) text = text ? `${text} ${this.sentence()}` : this.sentence()\n return text.slice(0, maxChars).trimEnd()\n }\n\n slug(words = 3): string {\n return this.words(words).join('-')\n }\n\n title(): string {\n return this.sentence(this.numberBetween(2, 5)).slice(0, -1)\n }\n\n url(): string {\n return `https://${this.randomElement(DOMAINS)}/${this.slug()}`\n }\n\n city(): string {\n return this.randomElement(CITIES)\n }\n\n country(): string {\n return this.randomElement(COUNTRIES)\n }\n\n company(): string {\n return `${this.lastName()} ${this.randomElement(COMPANY_SUFFIXES)}`\n }\n\n phoneNumber(): string {\n return this.numerify('+1-###-###-####')\n }\n\n uuid(): string {\n return randomUUID()\n }\n\n /** Replaces every # with a digit. */\n numerify(pattern = '###'): string {\n return pattern.replace(/#/g, () => String(this.randomDigit()))\n }\n\n /** Replaces every ? with a letter. */\n lexify(pattern = '????'): string {\n return pattern.replace(/\\?/g, () => String.fromCharCode(97 + this.numberBetween(0, 25)))\n }\n\n /** numerify() and lexify() together. */\n bothify(pattern = '## ??'): string {\n return this.lexify(this.numerify(pattern))\n }\n\n hexColor(): string {\n return `#${this.numberBetween(0, 0xffffff).toString(16).padStart(6, '0')}`\n }\n\n /** A date between two points ('-30 years', 'now', '+1 week', a Date). */\n dateTimeBetween(start: Date | string = '-30 years', end: Date | string = 'now'): Date {\n const from = this.resolveDate(start).getTime()\n const to = this.resolveDate(end).getTime()\n return new Date(Math.floor(from + this.random() * (to - from)))\n }\n\n /** A date before `max` (default now). */\n dateTime(max: Date | string = 'now'): Date {\n return this.dateTimeBetween(new Date(0), max)\n }\n\n /** A Y-m-d date string before `max`. */\n date(max: Date | string = 'now'): string {\n return this.dateTime(max).toISOString().slice(0, 10)\n }\n\n private resolveDate(value: Date | string): Date {\n if (value instanceof Date) return value\n if (value === 'now') return new Date()\n const match = DURATION.exec(value.trim())\n if (match) return new Date(Date.now() + Number(match[1]) * UNIT_MS[match[2]!.toLowerCase()]!)\n const parsed = new Date(value)\n if (Number.isNaN(parsed.getTime())) throw new LogicError(`Unable to parse [${value}] as a date.`)\n return parsed\n }\n}\n\nlet shared: Faker | undefined\n\n/** The shared fake data generator (Laravel's fake() helper): fake().name(), fake().unique().safeEmail(). */\nexport function fake(): Faker {\n return (shared ??= new Faker())\n}\n","import type { Class, RouteModelResolver } from '@orieljs/contracts'\nimport { Model } from './Eloquent/Model'\nimport { LogicError, ModelNotFoundError } from './errors'\nimport type { ModelRegistry } from './ModelRegistry'\n\n/**\n * Route model binding for the router: {post} → Post (StudlyCase of the parameter, from the app/Models registry),\n * {post:slug} → Post where slug = value, Route.model('author', User) → resolveExplicit(User, …).\n * Named RouteModelResolverImpl so it never shadows the RouteModelResolver token.\n */\nexport class RouteModelResolverImpl implements RouteModelResolver {\n constructor(private readonly registry: ModelRegistry) {}\n\n /** undefined when no model is called `parameter` (the router keeps the string); throws ModelNotFoundError (404) when the row is missing. */\n async resolve(parameter: string, value: string, field?: string): Promise<unknown | undefined> {\n const model = this.registry.resolve(parameter)\n if (!model) return undefined\n return this.resolveExplicit(model, value, field)\n }\n\n /** The model of `model` whose route key (or `field`) equals value; ModelNotFoundError (404) when there is none. */\n async resolveExplicit(model: Class<unknown>, value: string, field?: string): Promise<unknown> {\n if (!(model.prototype instanceof Model)) throw new LogicError(`Route model binding needs a Model class; [${model.name}] isn't one.`)\n const cls = model as unknown as typeof Model\n const found = await cls.prototypeInstance().resolveRouteBinding(value, field)\n if (!found) throw new ModelNotFoundError(cls.name, [value])\n return found\n }\n}\n","import {\n Application,\n ClassRegistry,\n ConfigRepository,\n ConsoleKernel,\n DatabaseManager,\n HttpRequest,\n PaginationState,\n RouteModelResolver,\n} from '@orieljs/contracts'\nimport { BindingResolutionError, currentContainer } from '@orieljs/container'\nimport { ServiceProvider } from '@orieljs/support'\nimport { registerMigrationCommands, registerModelTypesCommand, type DatabaseCommandContext } from './Console/commands'\nimport { DatabaseManagerImpl, type DatabaseConfig } from './DatabaseManager'\nimport { discoverFactories } from './Eloquent/Factories/Factory'\nimport { Model } from './Eloquent/Model'\nimport { SchemaBuilderToken } from './facades'\nimport { ModelRegistry } from './ModelRegistry'\nimport { AbstractPaginator } from './Pagination/AbstractPaginator'\nimport { RouteModelResolverImpl } from './RouteModelResolver'\n\nconst env = (key: string, fallback?: string): string | undefined => {\n const value = process.env[key]\n return value === undefined || value === '' ? fallback : value\n}\n\n/** Laravel 11's config/database.php defaults (the app's config/database.ts wins, key by key). */\nexport function databaseConfigDefaults(app: Pick<Application, 'databasePath'>): DatabaseConfig & Record<string, unknown> {\n return {\n default: env('DB_CONNECTION', 'sqlite')!,\n connections: {\n sqlite: {\n driver: 'sqlite',\n url: env('DB_URL'),\n database: env('DB_DATABASE', app.databasePath('database.sqlite')),\n foreign_key_constraints: env('DB_FOREIGN_KEYS', 'true') !== 'false',\n },\n mysql: {\n driver: 'mysql',\n url: env('DB_URL'),\n host: env('DB_HOST', '127.0.0.1'),\n port: env('DB_PORT', '3306'),\n database: env('DB_DATABASE', 'laravel'),\n username: env('DB_USERNAME', 'root'),\n password: env('DB_PASSWORD', ''),\n charset: env('DB_CHARSET', 'utf8mb4'),\n collation: env('DB_COLLATION', 'utf8mb4_unicode_ci'),\n },\n pgsql: {\n driver: 'pgsql',\n url: env('DB_URL'),\n host: env('DB_HOST', '127.0.0.1'),\n port: env('DB_PORT', '5432'),\n database: env('DB_DATABASE', 'laravel'),\n username: env('DB_USERNAME', 'root'),\n password: env('DB_PASSWORD', ''),\n charset: env('DB_CHARSET', 'utf8'),\n search_path: 'public',\n },\n },\n migrations: { table: 'migrations', update_date_on_publish: true } as DatabaseConfig['migrations'],\n // Laravel keeps the Redis connections here; Cache, Queue and Session resolve database.redis.<connection>.\n redis: {\n client: 'ioredis',\n default: { url: env('REDIS_URL'), host: '127.0.0.1', port: 6379, password: undefined, db: 0 },\n cache: { url: env('REDIS_URL'), host: '127.0.0.1', port: 6379, password: undefined, db: 1 },\n },\n }\n}\n\n/** The current request, when the current container is a request scope with one. */\nfunction currentRequest(): HttpRequest | undefined {\n const container = currentContainer()\n if (!container?.bound(HttpRequest)) return undefined\n try {\n return container.make(HttpRequest)\n } catch {\n return undefined // scoped binding resolved outside a request scope (R13)\n }\n}\n\n/**\n * The PaginationState of the current container, when it resolves (Live binds one for the application, which answers\n * while a WithPagination component mounts, runs an update's hooks and actions, or renders).\n */\nfunction paginationState(): PaginationState | undefined {\n const container = currentContainer()\n if (!container?.bound(PaginationState)) return undefined\n try {\n return container.make(PaginationState)\n } catch (error) {\n if (error instanceof BindingResolutionError) return undefined // a scoped binding resolved outside a request scope\n throw error\n }\n}\n\n/**\n * Points the paginators at the current request: ?page=, ?cursor=, the URL and the query string (Laravel's resolvers).\n * A bound PaginationState is asked first for the page and the path (Livewire's WithPagination replaces Laravel's\n * resolvers the same way); what it leaves undefined comes from the request.\n */\nexport function usePaginationResolvers(): void {\n AbstractPaginator.currentPathResolver = () => paginationState()?.currentPath() ?? currentRequest()?.url() ?? '/'\n AbstractPaginator.currentPageResolver = (pageName) => {\n const state = paginationState()?.currentPage(pageName)\n if (state !== undefined) return state\n const page = Number(currentRequest()?.input(pageName))\n return Number.isInteger(page) && page >= 1 ? page : 1\n }\n AbstractPaginator.queryStringResolver = () => (currentRequest()?.query<Record<string, unknown>>() ?? {})\n AbstractPaginator.currentCursorResolver = (cursorName) => currentRequest()?.input(cursorName)\n}\n\n/**\n * Binds the database layer: the DatabaseManager (a root singleton owning the pools) behind the DB facade, the\n * Schema facade's SchemaBuilder, the ModelRegistry and the RouteModelResolver. At boot it discovers app/Models,\n * factories (console and tests), points pagination at the current request, and registers the migrate*, db:seed,\n * make:migration and model:types commands when a ConsoleKernel is bound. It also merges Laravel's database.redis\n * connections, which Cache, Queue and Session read.\n */\nexport class DatabaseServiceProvider extends ServiceProvider {\n override register(): void {\n // Models booted by an earlier application (tests make one per test) boot again, so the listeners that\n // static booted() registers reach this application's EventDispatcher.\n Model.clearBootedModels()\n this.mergeConfigFrom(databaseConfigDefaults(this.app), 'database')\n this.app.singleton(DatabaseManager, () => new DatabaseManagerImpl(() => this.app.make(ConfigRepository).get<DatabaseConfig>('database')))\n // At the end of the process: close every connection's pool (never builds a manager to do it).\n this.app.onShutdown(async () => {\n if (this.app.resolved(DatabaseManager)) await this.app.make(DatabaseManager).disconnectAll()\n })\n this.app.singleton(ModelRegistry)\n this.app.singleton(RouteModelResolver, () => new RouteModelResolverImpl(this.app.make(ModelRegistry)))\n this.app.bind(SchemaBuilderToken, () => this.manager().getSchemaBuilder())\n }\n\n override async boot(): Promise<void> {\n // post.author.name reads the relation method's name: warn about it while developing.\n Model.warnOnRelationPropertyAccess(!this.app.isProduction())\n usePaginationResolvers()\n const registry = this.app.make(ModelRegistry)\n const classes = this.app.bound(ClassRegistry) ? this.app.make(ClassRegistry) : undefined\n for (const entry of await registry.discover(this.app.appPath('Models'))) {\n // Queue and Live serialize models as class name + key.\n if (classes && !classes.has(entry.name)) classes.register(entry.model, entry.name)\n }\n if (this.app.runningInConsole() || this.app.runningUnitTests()) await discoverFactories(this.app.databasePath('factories'))\n if (this.app.bound(ConsoleKernel)) {\n const kernel = this.app.make(ConsoleKernel)\n const context: DatabaseCommandContext = { app: this.app, manager: () => this.manager(), models: async () => registry }\n registerMigrationCommands(kernel, context)\n registerModelTypesCommand(kernel, context)\n }\n }\n\n private manager(): DatabaseManagerImpl {\n return this.app.make(DatabaseManager) as DatabaseManagerImpl\n }\n}\n"],"mappings":";AAGO,IAAM,qBAAN,cAAiC,MAA4C;AAAA,EAKlF,YACW,OACA,MAAiB,CAAC,GAC3B;AACA,UAAM,+BAA+B,KAAK,IAAI,IAAI,SAAS,MAAM,IAAI,IAAI,MAAM,EAAE,KAAK,IAAI,IAAI,GAAG,EAAE;AAH1F;AACA;AAAA,EAGX;AAAA,EAJW;AAAA,EACA;AAAA,EANF,OAAO;AAAA,EACP,SAAS;AAAA,EACA,OAAO;AAQ3B;AAMO,IAAe,gBAAf,cAAqC,MAA4B;AAAA,EAC7D,OAAO;AAAA,EACP,SAAS;AACpB;AAGO,IAAM,aAAN,cAAyB,cAAc;AAAA,EAG5C,YACW,gBACAA,MACA,UACT,OACA;AACA,UAAM,GAAG,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,iBAAiB,cAAc,UAAUA,IAAG,KAAK,EAAE,MAAM,CAAC;AALhH;AACA,eAAAA;AACA;AAAA,EAIX;AAAA,EANW;AAAA,EACA;AAAA,EACA;AAAA,EALO,OAAO;AAU3B;AAGO,IAAM,sBAAN,cAAkC,cAAc;AAAA,EAErD,YAAqB,OAAwB,WAAmB;AAC9D,UAAM,QAAQ,SAAS,uDAAuD,KAAK,IAAI;AADpE;AAAwB;AAAA,EAE7C;AAAA,EAFqB;AAAA,EAAwB;AAAA,EAD3B,OAAO;AAI3B;AAEO,IAAM,wBAAN,cAAoC,cAAc;AAAA,EAEvD,YAAqB,OAAwB,UAAkB;AAC7D,UAAM,mCAAmC,QAAQ,eAAe,KAAK,IAAI;A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nF;AACA,QAAI,KAAK,IAAI,iBAAiB,KAAK,KAAK,IAAI,iBAAiB,EAAG,OAAM,kBAAkB,KAAK,IAAI,aAAa,WAAW,CAAC;AAC1H,QAAI,KAAK,IAAI,MAAM,aAAa,GAAG;AACjC,YAAM,SAAS,KAAK,IAAI,KAAK,aAAa;AAC1C,YAAM,UAAkC,EAAE,KAAK,KAAK,KAAK,SAAS,MAAM,KAAK,QAAQ,GAAG,QAAQ,YAAYA,UAAS;AACrH,gCAA0B,QAAQ,OAAO;AACzC,gCAA0B,QAAQ,OAAO;AAAA,IAC3C;AAAA,EACF;AAAA,EAEQ,UAA+B;AACrC,WAAO,KAAK,IAAI,KAAKD,gBAAe;AAAA,EACtC;AACF;","names":["sql","castType","sql","Database","importOptional","importOptional","sql","Collection","Collection","Collection","sql","text","sql","list","sets","pad","sql","Collection","value","sql","sql","text","list","sql","join","sql","sql","join","sql","columnList","text","clauses","list","sql","sql","AsyncLocalStorage","AsyncLocalStorage","AsyncLocalStorage","DatabaseManager","Collection","currentContainer","Str","Collection","Str","Builder","Str","scopes","Collection","Collection","text","Collection","Collection","Collection","present","join","Collection","Str","Str","registry","Builder","Str","Collection","Builder","list","Collection","Str","Str","Collection","Collection","Str","list","Collection","join","AsyncLocalStorage","currentContainer","AsyncLocalStorage","currentContainer","Builder","handler","AsyncLocalStorage","Str","currentContainer","scopes","sql","lower","DatabaseManager","Builder","text","raw","Collection","list","Str","existsSync","join","Str","pad","Str","join","existsSync","existsSync","readdirSync","join","pathToFileURL","existsSync","readdirSync","join","pathToFileURL","existsSync","join","relative","pathToFileURL","Str","Str","list","handler","join","existsSync","pathToFileURL","relative","existsSync","readdirSync","join","pathToFileURL","Str","pathToFileURL","Str","existsSync","readdirSync","join","text","registry","ClassRegistry","DatabaseManager","currentContainer","currentContainer","DatabaseManager","registry","ClassRegistry"]}
|
|
1
|
+
{"version":3,"sources":["../errors.ts","../runtime.ts","../Connectors/SqliteDatabase.ts","../Connectors/dialect.ts","../Query/Expression.ts","../Query/Builder.ts","../Pagination/AbstractPaginator.ts","../Pagination/CursorPaginator.ts","../Pagination/LengthAwarePaginator.ts","../Pagination/Paginator.ts","../Query/Grammar.ts","../Query/values.ts","../Connection.ts","../Schema/Builder.ts","../Schema/ColumnDefinition.ts","../Schema/ForeignKeyDefinition.ts","../Schema/Blueprint.ts","../Schema/Grammar.ts","../Schema/SqliteTableRebuild.ts","../DatabaseManager.ts","../facades.ts","../Eloquent/Model.ts","../Eloquent/Builder.ts","../Eloquent/Relations/constraints.ts","../Eloquent/SoftDeletingScope.ts","../Eloquent/casts.ts","../Eloquent/Collection.ts","../Eloquent/Factories/Factory.ts","../Eloquent/Relations/BelongsTo.ts","../Eloquent/Relations/morphMap.ts","../Eloquent/Relations/Relation.ts","../Eloquent/Relations/BelongsToMany.ts","../Eloquent/Relations/HasOneOrMany.ts","../Eloquent/Relations/MorphTo.ts","../Eloquent/events.ts","../Eloquent/Relations/HasMany.ts","../Eloquent/Relations/HasManyThrough.ts","../Eloquent/Relations/HasOne.ts","../Eloquent/Relations/MorphMany.ts","../Eloquent/Relations/MorphOne.ts","../Eloquent/HasUniqueStringIds.ts","../Eloquent/DatabaseNotification.ts","../Eloquent/HasDatabaseNotifications.ts","../Migrations/Migration.ts","../Migrations/MigrationCreator.ts","../Migrations/MigrationRepository.ts","../Migrations/Migrator.ts","../Seeder.ts","../Console/commands.ts","../Types/TypeGenerator.ts","../ModelRegistry.ts","../Eloquent/Factories/fake.ts","../RouteModelResolver.ts","../DatabaseServiceProvider.ts"],"sourcesContent":["import type { ModelNotFoundError as ModelNotFoundErrorContract, OrielError } from '@orieljs/contracts'\n\n/** Thrown by findOrFail()/firstOrFail() and route model binding. Renders as 404. */\nexport class ModelNotFoundError extends Error implements ModelNotFoundErrorContract {\n readonly kind = 'ModelNotFound' as const\n readonly status = 404\n override readonly name = 'ModelNotFoundError'\n\n constructor(\n readonly model: string,\n readonly ids: unknown[] = [],\n ) {\n super(`No query results for model [${model}]${ids.length ? ' ' + ids.map(String).join(', ') : '.'}`)\n }\n}\n\n/**\n * Base of every other Database error: a server error (bug or infrastructure failure). The exception handler reports\n * it and renders a 500, hiding the message unless app.debug is on.\n */\nexport abstract class DatabaseError extends Error implements OrielError {\n readonly kind = 'Server' as const\n readonly status = 500\n}\n\n/** A failed SQL statement, with the SQL and connection in the message (Laravel's QueryException). */\nexport class QueryError extends DatabaseError {\n override readonly name = 'QueryError'\n\n constructor(\n readonly connectionName: string,\n readonly sql: string,\n readonly bindings: readonly unknown[],\n cause: unknown,\n ) {\n super(`${cause instanceof Error ? cause.message : String(cause)} (Connection: ${connectionName}, SQL: ${sql})`, { cause })\n }\n}\n\n/** Mass assignment on a model whose `guarded` is ['*'] (Laravel's MassAssignmentException). */\nexport class MassAssignmentError extends DatabaseError {\n override readonly name = 'MassAssignmentError'\n constructor(readonly model: string, readonly attribute: string) {\n super(`Add [${attribute}] to fillable property to allow mass assignment on [${model}].`)\n }\n}\n\nexport class RelationNotFoundError extends DatabaseError {\n override readonly name = 'RelationNotFoundError'\n constructor(readonly model: string, readonly relation: string) {\n super(`Call to undefined relationship [${relation}] on model [${model}].`)\n }\n}\n\nexport class RelationNotLoadedError extends DatabaseError {\n override readonly name = 'RelationNotLoadedError'\n constructor(readonly model: string, readonly relation: string) {\n super(\n `Relation [${relation}] is not loaded on model [${model}]. Eager load it with ${model}.with('${relation}') ` +\n `or await model.load('${relation}'), or query it with model.${relation}().get().`,\n )\n }\n}\n\nexport class InvalidCastError extends DatabaseError {\n override readonly name = 'InvalidCastError'\n constructor(readonly model: string, readonly column: string, readonly castType: string) {\n super(`Call to undefined cast [${castType}] on column [${column}] in model [${model}].`)\n }\n}\n\n/** Bad or missing database configuration (unknown connection, unsupported driver). */\nexport class DatabaseConfigError extends DatabaseError {\n override readonly name = 'DatabaseConfigError'\n}\n\n/** Thrown when an operation needs a feature the model hasn't enabled (e.g. restore() without soft deletes). */\nexport class LogicError extends DatabaseError {\n override readonly name = 'LogicError'\n}\n","/** True when running on Bun (bun:sqlite is used instead of better-sqlite3). */\nexport const isBun = (): boolean => typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined'\n","import type { SqliteDatabase, SqliteStatement } from 'kysely'\nimport { importOptional } from '@orieljs/support'\nimport { isBun } from '../runtime'\n\n/** The part of bun:sqlite's Statement this adapter uses. */\nexport interface BunStatement {\n readonly columnNames: string[]\n all(...parameters: unknown[]): unknown[]\n run(...parameters: unknown[]): { changes: number | bigint; lastInsertRowid: number | bigint }\n iterate(...parameters: unknown[]): IterableIterator<unknown>\n}\n\n/** The part of bun:sqlite's Database this adapter uses. */\nexport interface BunDatabase {\n prepare(sql: string): BunStatement\n close(): void\n}\n\n/** Adapts bun:sqlite to the better-sqlite3 shape Kysely's SqliteDialect expects. */\nexport class BunSqliteDatabase implements SqliteDatabase {\n constructor(private readonly database: BunDatabase) {}\n\n close(): void {\n this.database.close()\n }\n\n prepare(sql: string): SqliteStatement {\n const statement = this.database.prepare(sql)\n return {\n // A statement that returns columns (SELECT, or anything with RETURNING) is a reader.\n reader: statement.columnNames.length > 0,\n all: (parameters) => statement.all(...parameters),\n run: (parameters) => statement.run(...parameters),\n iterate: (parameters) => statement.iterate(...parameters),\n }\n }\n}\n\n/** Opens a SQLite database with bun:sqlite on Bun and better-sqlite3 on Node. */\nexport async function openSqlite(filename: string): Promise<SqliteDatabase> {\n if (isBun()) {\n // A variable specifier keeps bundlers, Vite and the dependency checker from trying to resolve bun:sqlite on Node.\n const specifier = 'bun:sqlite'\n const { Database } = (await import(/* @vite-ignore */ specifier)) as { Database: new (filename: string) => BunDatabase }\n const database = new Database(filename)\n // better-sqlite3 waits 5 seconds for a lock by default; bun:sqlite fails at once with SQLITE_BUSY.\n database.prepare('PRAGMA busy_timeout = 5000').run()\n return new BunSqliteDatabase(database)\n }\n const { default: Database } = await importOptional('better-sqlite3', 'The sqlite connection', () => import('better-sqlite3'))\n return new Database(filename)\n}\n","import { importOptional } from '@orieljs/support'\nimport { CompiledQuery, MysqlDialect, PostgresDialect, SqliteDialect, type Dialect } from 'kysely'\nimport type { DriverName } from '@orieljs/contracts'\nimport { DatabaseConfigError } from '../errors'\nimport { openSqlite } from './SqliteDatabase'\n\n/** One entry of `config('database.connections')`, in Laravel's config/database.php shape. */\nexport interface ConnectionConfig {\n driver: DriverName\n url?: string\n database?: string\n host?: string\n port?: string | number\n username?: string\n password?: string\n charset?: string\n collation?: string\n /** pgsql only. */\n search_path?: string\n /** sqlite only. Defaults to true, like Laravel's DB_FOREIGN_KEYS. */\n foreign_key_constraints?: boolean\n pool?: { max?: number }\n}\n\nconst PG_INT8 = 20\nconst PG_DATE = 1082\nconst PG_TIMESTAMP = 1114\nconst PG_TIMESTAMPTZ = 1184\n\n/**\n * The mysql2 pool options for a connection. When `url` is set its parts (host, port, user, password,\n * database) win over the individual keys, like Laravel; keys it leaves out fall back to the config.\n */\nexport function mysqlPoolOptions(config: ConnectionConfig): Record<string, unknown> {\n const options: Record<string, unknown> = {}\n if (config.url) {\n try {\n const url = new URL(config.url)\n const decoded = (value: string) => (value ? decodeURIComponent(value) : undefined)\n Object.assign(options, {\n host: url.hostname || undefined,\n port: url.port ? Number(url.port) : undefined,\n database: decoded(url.pathname.slice(1)),\n user: decoded(url.username),\n password: decoded(url.password),\n })\n // Query parameters are mysql2 options; like mysql2 itself, JSON-parse the value when it is JSON.\n for (const [key, value] of [...url.searchParams.entries()]) {\n try {\n options[key] = JSON.parse(value)\n } catch {\n options[key] = value\n }\n }\n } catch {\n throw new DatabaseConfigError('Invalid database url.')\n }\n }\n const fallbacks = {\n host: config.host,\n port: config.port === undefined || config.port === '' ? undefined : Number(config.port),\n database: config.database,\n user: config.username,\n password: config.password,\n charset: config.charset ?? 'utf8mb4',\n connectionLimit: config.pool?.max ?? 10,\n dateStrings: true,\n supportBigNumbers: true,\n timezone: 'Z',\n }\n for (const [key, value] of Object.entries(fallbacks)) options[key] ??= value\n return options\n}\n\n/** Builds the Kysely dialect for a connection. Driver modules are imported lazily, on the first query. */\nexport function createDialect(config: ConnectionConfig): Dialect {\n switch (config.driver) {\n case 'sqlite': {\n const foreignKeys = config.foreign_key_constraints ?? true\n return new SqliteDialect({\n database: () => openSqlite(config.database ?? ':memory:'),\n onCreateConnection: async (connection) => {\n await connection.executeQuery(CompiledQuery.raw(`PRAGMA foreign_keys = ${foreignKeys ? 'ON' : 'OFF'}`))\n },\n })\n }\n case 'pgsql':\n return new PostgresDialect({\n pool: async () => {\n const { default: pg } = await importOptional('pg', 'The pgsql connection', () => import('pg'))\n return new pg.Pool({\n connectionString: config.url,\n host: config.host,\n port: config.port === undefined ? undefined : Number(config.port),\n database: config.database,\n user: config.username,\n password: config.password,\n max: config.pool?.max ?? 10,\n types: {\n // Dates stay strings (casts parse them as UTC); bigint ids become numbers when they fit.\n getTypeParser: ((oid: number, format?: 'text' | 'binary') => {\n if (oid === PG_INT8) return (value: string) => (Number.isSafeInteger(Number(value)) ? Number(value) : value)\n if (oid === PG_DATE || oid === PG_TIMESTAMP || oid === PG_TIMESTAMPTZ) return (value: string) => value\n return pg.types.getTypeParser(oid, format)\n }) as typeof pg.types.getTypeParser,\n },\n })\n },\n onCreateConnection: async (connection) => {\n if (config.search_path) {\n await connection.executeQuery(CompiledQuery.raw(`set search_path to ${config.search_path}`))\n }\n },\n })\n case 'mysql':\n return new MysqlDialect({\n pool: async () => {\n const { createPool } = await importOptional('mysql2', 'The mysql connection', () => import('mysql2'))\n type PoolOptions = Parameters<typeof createPool>[0] & object\n return createPool(mysqlPoolOptions(config) as PoolOptions)\n },\n })\n default:\n throw new DatabaseConfigError(`Unsupported driver [${String((config as { driver: unknown }).driver)}].`)\n }\n}\n","import { sql, type RawBuilder } from 'kysely'\nimport { LogicError } from '../errors'\n\n/** A raw SQL fragment, never escaped: DB.raw('count(*) as total'). Use `?` placeholders for values. */\nexport class Expression {\n constructor(\n readonly value: string,\n readonly bindings: readonly unknown[] = [],\n ) {}\n\n toString(): string {\n return this.value\n }\n}\n\nexport const raw = (value: string, bindings: readonly unknown[] = []): Expression => new Expression(value, bindings)\n\n/**\n * Turns `select * from users where id = ?` + bindings into a Kysely RawBuilder, so each dialect gets its own\n * placeholders ($1 on Postgres). `?` inside quoted strings isn't special-cased: bind such values instead.\n */\nexport function rawWithBindings(query: string, bindings: readonly unknown[] = []): RawBuilder<unknown> {\n const fragments = query.split('?')\n if (fragments.length - 1 !== bindings.length) {\n throw new LogicError(`The query has ${fragments.length - 1} placeholders but ${bindings.length} bindings were given: ${query}`)\n }\n const strings = Object.assign([...fragments], { raw: [...fragments] }) as unknown as TemplateStringsArray\n return sql(strings, ...bindings)\n}\n","import { sql } from 'kysely'\nimport type { Operator, QueryBuilder, Row } from '@orieljs/contracts'\nimport { Collection, LazyCollection } from '@orieljs/collections'\nimport type { Connection } from '../Connection'\nimport { LogicError } from '../errors'\nimport { AbstractPaginator } from '../Pagination/AbstractPaginator'\nimport { Cursor, CursorPaginator } from '../Pagination/CursorPaginator'\nimport { LengthAwarePaginator } from '../Pagination/LengthAwarePaginator'\nimport { Paginator } from '../Pagination/Paginator'\nimport { Expression } from './Expression'\nimport { Grammar } from './Grammar'\n\n/** The row number column limitPerGroup() adds; it never reaches the rows a query returns. */\nexport const GROUP_ROW = 'oriel_row'\n\nexport type WhereBoolean = 'and' | 'or'\nexport type Direction = 'asc' | 'desc'\nexport type ColumnRef = string | Expression\n\nexport type Where =\n | { type: 'basic'; column: ColumnRef | Builder<unknown>; operator: string; value: unknown; boolean: WhereBoolean }\n | { type: 'in'; column: ColumnRef; values: readonly unknown[] | Builder<unknown>; not: boolean; boolean: WhereBoolean }\n | { type: 'null'; column: ColumnRef; not: boolean; boolean: WhereBoolean }\n | { type: 'between'; column: ColumnRef; values: readonly [unknown, unknown]; not: boolean; boolean: WhereBoolean }\n | { type: 'like'; column: ColumnRef; value: string; caseSensitive: boolean; not: boolean; boolean: WhereBoolean }\n | { type: 'column'; first: ColumnRef; operator: string; second: ColumnRef; boolean: WhereBoolean }\n | { type: 'nested'; query: Builder<unknown>; not: boolean; boolean: WhereBoolean }\n | { type: 'exists'; query: Builder<unknown>; not: boolean; boolean: WhereBoolean }\n | { type: 'raw'; sql: string; bindings: readonly unknown[]; boolean: WhereBoolean }\n | { type: 'date'; part: DatePart; column: ColumnRef; operator: string; value: unknown; boolean: WhereBoolean }\n\n/** The part of a date or time column a date where clause compares (whereDate() → 'date', whereYear() → 'year', …). */\nexport type DatePart = 'date' | 'time' | 'day' | 'month' | 'year'\n/** What a date where clause compares with: a Date (read in UTC), a string, a number, or DB.raw(). */\nexport type DateWhereValue = Date | string | number | Expression\n/** whereDate('published_at', '2026-01-05') or whereDate('published_at', '>=', new Date()). */\nexport type DateWhereArgs = [value: DateWhereValue] | [operator: string, value: DateWhereValue]\n\nexport type Having =\n | { column: ColumnRef; operator: string; value: unknown; boolean: WhereBoolean }\n | { raw: Expression; boolean: WhereBoolean }\n\nexport type Order = { column: ColumnRef; direction: Direction } | { raw: Expression }\n/** A column, an expression, or `(subquery) as alias` (`exists (subquery) as alias` with exists). */\nexport type SelectColumn = ColumnRef | { query: Builder<unknown>; as: string; exists?: boolean }\n\ntype NestedCallback<Q> = (query: Q) => unknown\n\n/** The value when()'s callback receives: the condition's type without its falsy members. */\nexport type Truthy<V> = Exclude<V, false | 0 | 0n | '' | null | undefined>\n\n/** Pages through a query lazily, one chunk per query (lazy()). */\nasync function* chunksOf<T>(query: Builder<T>, chunkSize: number): AsyncGenerator<T> {\n for (let page = 1; ; page++) {\n const results = await query.clone().forPage(page, chunkSize).runSelect()\n yield* results\n if (results.length < chunkSize) return\n }\n}\n\n/** Pages through a query lazily by key (lazyById()). */\nasync function* chunksById<T>(query: Builder<T>, chunkSize: number, column: string, alias: string): AsyncGenerator<T> {\n let lastId: unknown\n for (;;) {\n const results = await query.clone().forPageAfterId(chunkSize, lastId, column).runSelect()\n yield* results\n if (results.length < chunkSize) return\n lastId = keyOf(results.at(-1), alias)\n }\n}\n\n/** Reads the chunkById key from a row or a model. */\nfunction keyOf(item: unknown, alias: string): unknown {\n const value = (item as Record<string, unknown> | undefined)?.[alias]\n if (value === undefined || value === null) {\n throw new LogicError(`The chunkById operation was aborted because the [${alias}] column is not present in the query result.`)\n }\n return value\n}\n\nconst pad = (value: number, width = 2): string => String(value).padStart(width, '0')\n\n/**\n * Laravel's date where values: a Date becomes the compared part in UTC (the storage time zone), days and months are\n * zero-padded (sprintf('%02d')) so SQLite's strftime() text compares equal, and other numbers are sent as text (SQLite\n * binds a JavaScript number as a real, and cast(2026.0 as text) is '2026.0'). Expressions pass through.\n */\nfunction dateWhereValue(part: DatePart, value: DateWhereValue): unknown {\n if (value instanceof Expression) return value\n if (value instanceof Date) {\n if (part === 'date') return `${pad(value.getUTCFullYear(), 4)}-${pad(value.getUTCMonth() + 1)}-${pad(value.getUTCDate())}`\n if (part === 'time') return `${pad(value.getUTCHours())}:${pad(value.getUTCMinutes())}:${pad(value.getUTCSeconds())}`\n if (part === 'day') return pad(value.getUTCDate())\n if (part === 'month') return pad(value.getUTCMonth() + 1)\n return String(value.getUTCFullYear())\n }\n if (part === 'day' || part === 'month') return pad(Math.trunc(Number(value)) || 0)\n return typeof value === 'number' ? String(value) : value\n}\n\nconst isRow = (value: unknown): value is Row =>\n typeof value === 'object' && value !== null && !(value instanceof Expression) && !(value instanceof Builder) && !Array.isArray(value)\n\n/** The key a selected column comes back under: 'users.name' → 'name', 'name as n' → 'n'. */\nexport function columnKey(column: string): string {\n const alias = /\\s+as\\s+/i.exec(column)\n if (alias) return column.slice(alias.index + alias[0].length).trim()\n return column.split('.').pop()!.trim()\n}\n\n/**\n * Laravel's query builder: DB.table('users').where('votes', '>', 100).get().\n * Implements the QueryBuilder contract other components use (Queue, Cache, Session, Validation).\n */\nexport class Builder<T = Row> implements QueryBuilder<T> {\n readonly grammar: Grammar\n columns: SelectColumn[] = []\n distinctRows = false\n fromTable: string | Expression | undefined\n joins: JoinClause[] = []\n wheres: Where[] = []\n groups: ColumnRef[] = []\n havings: Having[] = []\n orders: Order[] = []\n limitValue: number | undefined\n offsetValue: number | undefined\n /** A limit and offset per value of `column` (each parent of an eager load), compiled as a window (limitPerGroup()). */\n groupLimit: { column: string; limit: number | undefined; offset: number | undefined } | undefined\n lockMode: 'update' | 'share' | undefined\n\n constructor(\n readonly connection: Connection,\n table?: string | Expression,\n ) {\n this.grammar = new Grammar(connection.getDriverName())\n this.fromTable = table\n }\n\n // ---------------------------------------------------------------- building\n\n from(table: string | Expression): this {\n this.fromTable = table\n return this\n }\n\n select(...columns: Array<ColumnRef | ColumnRef[]>): this {\n this.columns = columns.flat()\n return this\n }\n\n addSelect(...columns: Array<ColumnRef | ColumnRef[]>): this {\n this.columns.push(...columns.flat())\n return this\n }\n\n selectRaw(expression: string, bindings: readonly unknown[] = []): this {\n this.columns.push(new Expression(expression, bindings))\n return this\n }\n\n /** Adds `(subquery) as alias` to the select list. */\n selectSub(query: Builder<unknown>, as: string): this {\n if (!this.columns.length) this.columns.push('*')\n this.columns.push({ query, as })\n return this\n }\n\n distinct(): this {\n this.distinctRows = true\n return this\n }\n\n where(column: ColumnRef, value: unknown): this\n where(column: ColumnRef, operator: Operator | string, value: unknown): this\n where(conditions: Row): this\n where(callback: NestedCallback<Builder<T>>): this\n where(...args: unknown[]): this {\n return this.addWhere('and', args)\n }\n\n orWhere(column: ColumnRef, value: unknown): this\n orWhere(column: ColumnRef, operator: Operator | string, value: unknown): this\n orWhere(conditions: Row): this\n orWhere(callback: NestedCallback<Builder<T>>): this\n orWhere(...args: unknown[]): this {\n return this.addWhere('or', args)\n }\n\n /** where not (…): whereNot(q => q.where('a', 1).orWhere('b', 2)). */\n whereNot(callback: NestedCallback<Builder<T>>): this {\n return this.addNested(callback, 'and', true)\n }\n\n orWhereNot(callback: NestedCallback<Builder<T>>): this {\n return this.addNested(callback, 'or', true)\n }\n\n whereIn(column: ColumnRef, values: readonly unknown[] | Builder<unknown>): this {\n this.wheres.push({ type: 'in', column, values: Array.isArray(values) ? [...values] : values, not: false, boolean: 'and' })\n return this\n }\n\n orWhereIn(column: ColumnRef, values: readonly unknown[] | Builder<unknown>): this {\n this.wheres.push({ type: 'in', column, values: Array.isArray(values) ? [...values] : values, not: false, boolean: 'or' })\n return this\n }\n\n whereNotIn(column: ColumnRef, values: readonly unknown[] | Builder<unknown>): this {\n this.wheres.push({ type: 'in', column, values: Array.isArray(values) ? [...values] : values, not: true, boolean: 'and' })\n return this\n }\n\n orWhereNotIn(column: ColumnRef, values: readonly unknown[] | Builder<unknown>): this {\n this.wheres.push({ type: 'in', column, values: Array.isArray(values) ? [...values] : values, not: true, boolean: 'or' })\n return this\n }\n\n whereNull(columns: ColumnRef | ColumnRef[]): this {\n for (const column of [columns].flat()) this.wheres.push({ type: 'null', column, not: false, boolean: 'and' })\n return this\n }\n\n orWhereNull(column: ColumnRef): this {\n this.wheres.push({ type: 'null', column, not: false, boolean: 'or' })\n return this\n }\n\n whereNotNull(columns: ColumnRef | ColumnRef[]): this {\n for (const column of [columns].flat()) this.wheres.push({ type: 'null', column, not: true, boolean: 'and' })\n return this\n }\n\n orWhereNotNull(column: ColumnRef): this {\n this.wheres.push({ type: 'null', column, not: true, boolean: 'or' })\n return this\n }\n\n whereBetween(column: ColumnRef, values: readonly [unknown, unknown]): this {\n this.wheres.push({ type: 'between', column, values, not: false, boolean: 'and' })\n return this\n }\n\n orWhereBetween(column: ColumnRef, values: readonly [unknown, unknown]): this {\n this.wheres.push({ type: 'between', column, values, not: false, boolean: 'or' })\n return this\n }\n\n whereNotBetween(column: ColumnRef, values: readonly [unknown, unknown]): this {\n this.wheres.push({ type: 'between', column, values, not: true, boolean: 'and' })\n return this\n }\n\n /** Compares the date part of a column: whereDate('published_at', '2026-01-05'), whereDate('published_at', '<', new Date()). */\n whereDate(column: ColumnRef, ...args: DateWhereArgs): this {\n return this.addDateBasedWhere('date', column, args, 'and')\n }\n\n orWhereDate(column: ColumnRef, ...args: DateWhereArgs): this {\n return this.addDateBasedWhere('date', column, args, 'or')\n }\n\n /** Compares the time of day: whereTime('published_at', '>=', '09:00:00'). */\n whereTime(column: ColumnRef, ...args: DateWhereArgs): this {\n return this.addDateBasedWhere('time', column, args, 'and')\n }\n\n orWhereTime(column: ColumnRef, ...args: DateWhereArgs): this {\n return this.addDateBasedWhere('time', column, args, 'or')\n }\n\n /** Compares the day of the month: whereDay('published_at', 5). */\n whereDay(column: ColumnRef, ...args: DateWhereArgs): this {\n return this.addDateBasedWhere('day', column, args, 'and')\n }\n\n orWhereDay(column: ColumnRef, ...args: DateWhereArgs): this {\n return this.addDateBasedWhere('day', column, args, 'or')\n }\n\n /** Compares the month: whereMonth('published_at', 12). */\n whereMonth(column: ColumnRef, ...args: DateWhereArgs): this {\n return this.addDateBasedWhere('month', column, args, 'and')\n }\n\n orWhereMonth(column: ColumnRef, ...args: DateWhereArgs): this {\n return this.addDateBasedWhere('month', column, args, 'or')\n }\n\n /** Compares the year: whereYear('published_at', '>=', 2026). */\n whereYear(column: ColumnRef, ...args: DateWhereArgs): this {\n return this.addDateBasedWhere('year', column, args, 'and')\n }\n\n orWhereYear(column: ColumnRef, ...args: DateWhereArgs): this {\n return this.addDateBasedWhere('year', column, args, 'or')\n }\n\n /**\n * Laravel's whereLike(): the value is the pattern, `%` and `_` included (`whereLike('title', `%${term}%`)`).\n * Case-insensitive unless caseSensitive: ilike on Postgres, like on MySQL and SQLite (their like already ignores\n * case: MySQL through the column's collation, SQLite for ASCII letters). Case-sensitive is like on Postgres,\n * like binary on MySQL and glob on SQLite.\n */\n whereLike(column: ColumnRef, value: string, caseSensitive = false, boolean: WhereBoolean = 'and', not = false): this {\n this.wheres.push({ type: 'like', column, value, caseSensitive, not, boolean })\n return this\n }\n\n orWhereLike(column: ColumnRef, value: string, caseSensitive = false): this {\n return this.whereLike(column, value, caseSensitive, 'or')\n }\n\n whereNotLike(column: ColumnRef, value: string, caseSensitive = false, boolean: WhereBoolean = 'and'): this {\n return this.whereLike(column, value, caseSensitive, boolean, true)\n }\n\n orWhereNotLike(column: ColumnRef, value: string, caseSensitive = false): this {\n return this.whereNotLike(column, value, caseSensitive, 'or')\n }\n\n /** Compares two columns: whereColumn('updated_at', '>', 'created_at'). */\n whereColumn(first: ColumnRef, operatorOrSecond: string, second?: ColumnRef, boolean: WhereBoolean = 'and'): this {\n const [operator, other] = second === undefined ? ['=', operatorOrSecond] : [operatorOrSecond, second]\n this.grammar.operator(operator)\n this.wheres.push({ type: 'column', first, operator, second: other, boolean })\n return this\n }\n\n orWhereColumn(first: ColumnRef, operatorOrSecond: string, second?: ColumnRef): this {\n return this.whereColumn(first, operatorOrSecond, second, 'or')\n }\n\n whereRaw(sql: string, bindings: readonly unknown[] = [], boolean: WhereBoolean = 'and'): this {\n this.wheres.push({ type: 'raw', sql, bindings, boolean })\n return this\n }\n\n orWhereRaw(sql: string, bindings: readonly unknown[] = []): this {\n return this.whereRaw(sql, bindings, 'or')\n }\n\n whereExists(query: Builder<unknown> | NestedCallback<Builder<Row>>, boolean: WhereBoolean = 'and', not = false): this {\n const sub = query instanceof Builder ? query : this.subQuery(query)\n this.wheres.push({ type: 'exists', query: sub, not, boolean })\n return this\n }\n\n orWhereExists(query: Builder<unknown> | NestedCallback<Builder<Row>>): this {\n return this.whereExists(query, 'or')\n }\n\n whereNotExists(query: Builder<unknown> | NestedCallback<Builder<Row>>): this {\n return this.whereExists(query, 'and', true)\n }\n\n /** `(select …) <operator> value`: used by has('comments', '>=', 3). */\n whereSub(query: Builder<unknown>, operator: string, value: unknown, boolean: WhereBoolean = 'and'): this {\n this.grammar.operator(operator)\n this.wheres.push({ type: 'basic', column: query, operator, value, boolean })\n return this\n }\n\n /** Appends another builder's where clauses as one nested group. */\n addNestedWhereQuery(query: Builder<unknown>, boolean: WhereBoolean = 'and', not = false): this {\n if (query.wheres.length) this.wheres.push({ type: 'nested', query, not, boolean })\n return this\n }\n\n join(table: string | Expression, first: ColumnRef | ((join: JoinClause) => unknown), operator?: string, second?: ColumnRef, type: JoinType = 'inner'): this {\n const clause = new JoinClause(this, type, table)\n if (typeof first === 'function') first(clause)\n else clause.on(first, operator!, second)\n this.joins.push(clause)\n return this\n }\n\n leftJoin(table: string | Expression, first: ColumnRef | ((join: JoinClause) => unknown), operator?: string, second?: ColumnRef): this {\n return this.join(table, first, operator, second, 'left')\n }\n\n rightJoin(table: string | Expression, first: ColumnRef | ((join: JoinClause) => unknown), operator?: string, second?: ColumnRef): this {\n return this.join(table, first, operator, second, 'right')\n }\n\n crossJoin(table: string | Expression): this {\n this.joins.push(new JoinClause(this, 'cross', table))\n return this\n }\n\n groupBy(...columns: ColumnRef[]): this {\n this.groups.push(...columns)\n return this\n }\n\n having(column: ColumnRef, operatorOrValue: unknown, value?: unknown, boolean: WhereBoolean = 'and'): this {\n const [operator, operand] = value === undefined ? ['=', operatorOrValue] : [String(operatorOrValue), value]\n this.grammar.operator(operator)\n this.havings.push({ column, operator, value: operand, boolean })\n return this\n }\n\n havingRaw(sql: string, bindings: readonly unknown[] = [], boolean: WhereBoolean = 'and'): this {\n this.havings.push({ raw: new Expression(sql, bindings), boolean })\n return this\n }\n\n orderBy(column: ColumnRef, direction: Direction | Uppercase<Direction> = 'asc'): this {\n const normalized = direction.toLowerCase()\n if (normalized !== 'asc' && normalized !== 'desc') throw new LogicError('Order direction must be \"asc\" or \"desc\".')\n this.orders.push({ column, direction: normalized })\n return this\n }\n\n orderByDesc(column: ColumnRef): this {\n return this.orderBy(column, 'desc')\n }\n\n latest(column: ColumnRef = 'created_at'): this {\n return this.orderBy(column, 'desc')\n }\n\n oldest(column: ColumnRef = 'created_at'): this {\n return this.orderBy(column, 'asc')\n }\n\n inRandomOrder(): this {\n this.orders.push({ raw: this.grammar.compileRandom() })\n return this\n }\n\n orderByRaw(sql: string, bindings: readonly unknown[] = []): this {\n this.orders.push({ raw: new Expression(sql, bindings) })\n return this\n }\n\n /** Removes existing orders, optionally adding a new one. */\n reorder(column?: ColumnRef, direction: Direction = 'asc'): this {\n this.orders = []\n return column === undefined ? this : this.orderBy(column, direction)\n }\n\n limit(count: number): this {\n this.limitValue = count >= 0 ? Math.trunc(count) : undefined\n return this\n }\n\n take(count: number): this {\n return this.limit(count)\n }\n\n offset(count: number): this {\n this.offsetValue = Math.max(0, Math.trunc(count))\n return this\n }\n\n skip(count: number): this {\n return this.offset(count)\n }\n\n forPage(page: number, perPage = 15): this {\n return this.offset((Math.max(1, page) - 1) * perPage).limit(perPage)\n }\n\n lockForUpdate(): this {\n this.lockMode = 'update'\n return this\n }\n\n sharedLock(): this {\n this.lockMode = 'share'\n return this\n }\n\n /**\n * Laravel's when(): callback(query, value) runs when the value is truthy, otherwise(query, value) when it is falsy.\n * A function value is called with the query first and its result is the value. Truthiness is JavaScript's, so `'0'`\n * and `[]` are truthy: a `?active=0` filter applies, where Laravel would skip it. Returns the query; what the\n * callbacks return is ignored.\n *\n * @example\n * Post.query().when(request.query('q'), (query, q) => query.whereLike('title', `%${q}%`))\n */\n when<V>(value: (query: this) => V, callback: (query: this, value: Truthy<V>) => unknown, otherwise?: (query: this, value: V) => unknown): this\n when<V>(value: V, callback: (query: this, value: Truthy<V>) => unknown, otherwise?: (query: this, value: V) => unknown): this\n when(value: unknown, callback: (query: this, value: unknown) => unknown, otherwise?: (query: this, value: unknown) => unknown): this {\n const resolved = typeof value === 'function' ? (value as (query: this) => unknown)(this) : value\n if (resolved) callback(this, resolved)\n else otherwise?.(this, resolved)\n return this\n }\n\n /** Laravel's unless(): when() with the condition reversed. callback(query, value) runs when the value is falsy. */\n unless<V>(value: (query: this) => V, callback: (query: this, value: V) => unknown, otherwise?: (query: this, value: Truthy<V>) => unknown): this\n unless<V>(value: V, callback: (query: this, value: V) => unknown, otherwise?: (query: this, value: Truthy<V>) => unknown): this\n unless(value: unknown, callback: (query: this, value: unknown) => unknown, otherwise?: (query: this, value: unknown) => unknown): this {\n const resolved = typeof value === 'function' ? (value as (query: this) => unknown)(this) : value\n if (!resolved) callback(this, resolved)\n else otherwise?.(this, resolved)\n return this\n }\n\n tap(callback: (query: this) => unknown): this {\n callback(this)\n return this\n }\n\n // ---------------------------------------------------------------- reading\n\n async get(): Promise<Collection<T>> {\n return this.newCollection(await this.runSelect())\n }\n\n /** The collection get() and chunk() hand out (Eloquent's builder makes the model's collection). */\n protected newCollection(items: T[]): Collection<T> {\n return new Collection(items)\n }\n\n /** The raw rows, without a Collection around them. */\n async runSelect(): Promise<T[]> {\n const rows = (await this.connection.execute<T>(this.grammar.compileSelect(this))).rows\n if (this.groupLimit) for (const row of rows) delete (row as Row)[GROUP_ROW]\n return rows\n }\n\n /**\n * @internal Eager loading (Laravel 11's groupLimit()): the limit and offset set so far apply to each value of `column`,\n * the parent's key, instead of to the whole query. Compiled as row_number() over (partition by …).\n */\n limitPerGroup(column: string): this {\n if (this.limitValue === undefined && this.offsetValue === undefined) return this\n this.groupLimit = { column, limit: this.limitValue, offset: this.offsetValue }\n this.limitValue = undefined\n this.offsetValue = undefined\n return this\n }\n\n async first(): Promise<T | undefined> {\n const rows = await this.clone().limit(1).runSelect()\n return rows[0]\n }\n\n async find(id: unknown, keyName = 'id'): Promise<T | undefined> {\n return this.clone().where(keyName, '=', id).first()\n }\n\n async value<V = unknown>(column: string): Promise<V | undefined> {\n const row = (await this.clone().select(column).first()) as Row | undefined\n return row?.[columnKey(column)] as V | undefined\n }\n\n async pluck<V = unknown>(column: string): Promise<Collection<V>> {\n const rows = (await this.clone().select(column).runSelect()) as Row[]\n const key = columnKey(column)\n return new Collection(rows.map((row) => row[key] as V))\n }\n\n async count(column: ColumnRef = '*'): Promise<number> {\n return Number((await this.aggregate('count', column)) ?? 0)\n }\n\n async min<V = unknown>(column: ColumnRef): Promise<V | undefined> {\n return (await this.aggregate('min', column)) as V | undefined\n }\n\n async max<V = unknown>(column: ColumnRef): Promise<V | undefined> {\n return (await this.aggregate('max', column)) as V | undefined\n }\n\n async sum(column: ColumnRef): Promise<number> {\n return Number((await this.aggregate('sum', column)) ?? 0)\n }\n\n async avg(column: ColumnRef): Promise<number | undefined> {\n const result = await this.aggregate('avg', column)\n return result === null || result === undefined ? undefined : Number(result)\n }\n\n async aggregate(fn: 'count' | 'min' | 'max' | 'sum' | 'avg', column: ColumnRef): Promise<unknown> {\n const result = await this.connection.execute<{ aggregate: unknown }>(this.grammar.compileAggregate(this, fn, column))\n return result.rows[0]?.aggregate ?? undefined\n }\n\n async exists(): Promise<boolean> {\n const result = await this.connection.execute<{ exists: unknown }>(this.grammar.compileExists(this))\n const value = result.rows[0]?.exists\n return value === true || value === 1 || value === '1' || value === 't'\n }\n\n async doesntExist(): Promise<boolean> {\n return !(await this.exists())\n }\n\n // ---------------------------------------------------------------- writing\n\n async insert(values: Row | Row[]): Promise<void> {\n const rows = Array.isArray(values) ? values : [values]\n if (!rows.length) return\n await this.connection.execute(this.grammar.compileInsert(this, rows))\n }\n\n /** Inserts one row and returns its auto-increment id. */\n async insertGetId(values: Row, keyName = 'id'): Promise<number | string> {\n const result = await this.connection.execute<Row>(this.grammar.compileInsertGetId(this, values, keyName))\n if (this.connection.getDriverName() === 'pgsql') return result.rows[0]![keyName] as number | string\n return Number(result.insertId)\n }\n\n /** Inserts rows, skipping the ones that violate a unique constraint. Returns how many were inserted. */\n async insertOrIgnore(values: Row | Row[]): Promise<number> {\n const rows = Array.isArray(values) ? values : [values]\n if (!rows.length) return 0\n return Number((await this.connection.execute(this.grammar.compileInsertOrIgnore(this, rows))).numAffectedRows ?? 0)\n }\n\n async update(values: Row): Promise<number> {\n if (!Object.keys(values).length) return 0\n return Number((await this.connection.execute(this.grammar.compileUpdate(this, values))).numAffectedRows ?? 0)\n }\n\n /** Updates the row matching attributes, or inserts attributes + values. */\n async updateOrInsert(attributes: Row, values: Row = {}): Promise<boolean> {\n if (!(await this.clone().where(attributes).exists())) {\n await this.insert({ ...attributes, ...values })\n return true\n }\n if (!Object.keys(values).length) return true\n await this.clone().where(attributes).update(values)\n return true\n }\n\n /**\n * Inserts rows, updating `update` (default: every inserted column except uniqueBy) when a row already exists.\n * uniqueBy must be a primary key or unique index (Postgres and SQLite need it for ON CONFLICT).\n */\n async upsert(values: Row | Row[], uniqueBy: string[], update?: string[]): Promise<number> {\n const rows = Array.isArray(values) ? values : [values]\n if (!rows.length) return 0\n const columns = update ?? Object.keys(rows[0]!).filter((column) => !uniqueBy.includes(column))\n if (!columns.length) return this.insertOrIgnore(rows)\n return Number((await this.connection.execute(this.grammar.compileUpsert(this, rows, uniqueBy, columns))).numAffectedRows ?? 0)\n }\n\n async increment(column: string, amount = 1, extra: Row = {}): Promise<number> {\n return this.update({ ...extra, [column]: sql`${this.grammar.wrap(column)} + ${amount}` })\n }\n\n async decrement(column: string, amount = 1, extra: Row = {}): Promise<number> {\n return this.update({ ...extra, [column]: sql`${this.grammar.wrap(column)} - ${amount}` })\n }\n\n async delete(id?: unknown): Promise<number> {\n if (id !== undefined) this.where('id', '=', id)\n return Number((await this.connection.execute(this.grammar.compileDelete(this))).numAffectedRows ?? 0)\n }\n\n async truncate(): Promise<void> {\n for (const statement of this.grammar.compileTruncate(this)) await this.connection.execute(statement)\n if (this.connection.getDriverName() === 'sqlite') {\n const sequence = await this.connection.select(\"select name from sqlite_master where type = 'table' and name = 'sqlite_sequence'\")\n if (sequence.length) await this.connection.statement('delete from sqlite_sequence where name = ?', [String(this.requireTable())])\n }\n }\n\n // ---------------------------------------------------------------- pagination and chunking\n\n /**\n * Paginates with a total count (two queries: count, then the page). The page comes from ?page= on the current\n * request unless given: DB.table('users').orderBy('id').paginate(15).\n */\n async paginate(perPage?: number, columns: ColumnRef[] = ['*'], pageName = 'page', page?: number): Promise<LengthAwarePaginator<T>> {\n const size = perPage ?? this.defaultPerPage()\n const current = page ?? AbstractPaginator.resolveCurrentPage(pageName)\n const total = await this.clone().count()\n const items = total > 0 ? await this.clone().withColumns(columns).forPage(current, size).runSelect() : []\n return new LengthAwarePaginator(this.newCollection(items), total, size, current, { path: AbstractPaginator.resolveCurrentPath(), pageName })\n }\n\n /** Paginates without a count: fetches perPage + 1 rows to know whether there is a next page. */\n async simplePaginate(perPage?: number, columns: ColumnRef[] = ['*'], pageName = 'page', page?: number): Promise<Paginator<T>> {\n const size = perPage ?? this.defaultPerPage()\n const current = page ?? AbstractPaginator.resolveCurrentPage(pageName)\n const items = await this.clone().withColumns(columns).offset((current - 1) * size).limit(size + 1).runSelect()\n return new Paginator(this.newCollection(items), size, current, { path: AbstractPaginator.resolveCurrentPath(), pageName })\n }\n\n /**\n * Paginates by the ordered columns' values instead of an offset. Needs an orderBy (Eloquent adds the primary key);\n * the cursor comes from ?cursor= on the current request unless given.\n */\n async cursorPaginate(perPage?: number, columns: ColumnRef[] = ['*'], cursorName = 'cursor', cursor?: Cursor | string): Promise<CursorPaginator<T>> {\n const size = perPage ?? this.defaultPerPage()\n const current = cursor instanceof Cursor ? cursor : cursor === undefined ? CursorPaginator.resolveCurrentCursor(cursorName) : Cursor.fromEncoded(cursor)\n const query = this.clone().withColumns(columns)\n const orders = query.ordersForCursor(current?.pointsToPreviousItems() ?? false)\n if (current) query.whereCursor(current, orders, 0)\n const items = await query.limit(size + 1).runSelect()\n return new CursorPaginator(this.newCollection(items), size, current, {\n path: AbstractPaginator.resolveCurrentPath(),\n cursorName,\n parameters: orders.map((order) => String(order.column)),\n })\n }\n\n /**\n * Runs the query page by page and passes each chunk to callback. Return false to stop. Needs an orderBy, so that\n * pages don't overlap. Don't update the ordered column inside the callback; use chunkById() for that.\n */\n async chunk(count: number, callback: (results: Collection<T>, page: number) => unknown): Promise<boolean> {\n this.enforceOrderBy()\n for (let page = 1; ; page++) {\n const results = await this.clone().forPage(page, count).runSelect()\n if (!results.length) return true\n if ((await callback(this.newCollection(results), page)) === false) return false\n if (results.length < count) return true\n }\n }\n\n /** Chunks by comparing the key (where id > last id), so it is safe to update or delete rows inside the callback. */\n async chunkById(\n count: number,\n callback: (results: Collection<T>, page: number) => unknown,\n column?: string,\n alias?: string,\n ): Promise<boolean> {\n const key = column ?? this.defaultKeyName()\n const aliasName = alias ?? columnKey(key)\n let lastId: unknown\n for (let page = 1; ; page++) {\n const results = await this.clone().forPageAfterId(count, lastId, key).runSelect()\n if (!results.length) return true\n if ((await callback(this.newCollection(results), page)) === false) return false\n if (results.length < count) return true\n lastId = keyOf(results.at(-1), aliasName)\n }\n }\n\n /** Calls callback for every row, fetching `count` rows per query. Return false to stop. */\n async each(callback: (item: T, index: number) => unknown, count = 1000): Promise<boolean> {\n return this.chunk(count, async (results) => {\n for (const [index, item] of results.all().entries()) {\n if ((await callback(item, index)) === false) return false\n }\n return true\n })\n }\n\n /** A LazyCollection that runs one query per chunk as it is iterated: for await (const user of query.lazy()). */\n lazy(chunkSize = 1000): LazyCollection<T> {\n if (chunkSize < 1) throw new LogicError('The chunk size should be at least 1')\n this.enforceOrderBy()\n const query = this.clone()\n return LazyCollection.make(() => chunksOf(query, chunkSize))\n }\n\n /** Like lazy(), but pages by key, so rows can be updated while iterating. */\n lazyById(chunkSize = 1000, column?: string, alias?: string): LazyCollection<T> {\n if (chunkSize < 1) throw new LogicError('The chunk size should be at least 1')\n const key = column ?? this.defaultKeyName()\n const query = this.clone()\n return LazyCollection.make(() => chunksById(query, chunkSize, key, alias ?? columnKey(key)))\n }\n\n /** where column > lastId order by column limit perPage (existing orders on the column are replaced). */\n forPageAfterId(perPage = 15, lastId?: unknown, column = 'id'): this {\n this.orders = this.orders.filter((order) => 'raw' in order || order.column !== column)\n if (lastId !== undefined && lastId !== null) this.where(column, '>', lastId)\n return this.orderBy(column, 'asc').limit(perPage)\n }\n\n /** chunk() and lazy() need a stable order. Eloquent orders by the primary key instead of throwing. */\n protected enforceOrderBy(): void {\n if (!this.orders.length) throw new LogicError('You must specify an orderBy clause when using this function.')\n }\n\n /** The key chunkById()/lazyById() use by default. Eloquent uses the model's key. */\n protected defaultKeyName(): string {\n return 'id'\n }\n\n /** The page size when none is given. Eloquent uses the model's perPage. */\n protected defaultPerPage(): number {\n return 15\n }\n\n /** Laravel's get($columns): only applies when no columns were selected yet. */\n private withColumns(columns: ColumnRef[]): this {\n if (!this.columns.length && !(columns.length === 1 && columns[0] === '*')) this.select(...columns)\n return this\n }\n\n /** The column orders cursor pagination compares on; reversed (in the query too) when paging backwards. */\n private ordersForCursor(reverse: boolean): Array<{ column: ColumnRef; direction: Direction }> {\n this.enforceOrderBy()\n if (this.orders.some((order) => 'raw' in order)) throw new LogicError('cursorPaginate() only supports column orders, not orderByRaw() or inRandomOrder().')\n const orders = this.orders as Array<{ column: ColumnRef; direction: Direction }>\n if (reverse) this.orders = orders.map((order) => ({ column: order.column, direction: order.direction === 'asc' ? 'desc' : 'asc' }))\n return this.orders as Array<{ column: ColumnRef; direction: Direction }>\n }\n\n /** (a > ?) or (a = ? and (b > ? or (b = ? and …))), Laravel's cursor conditions. */\n private whereCursor(cursor: Cursor, orders: Array<{ column: ColumnRef; direction: Direction }>, index: number): void {\n const { column, direction } = orders[index]!\n this.where((query) => {\n query.where(column, direction === 'asc' ? '>' : '<', cursor.parameter(String(column)))\n if (index < orders.length - 1) {\n query.orWhere((next) => {\n next.where(column, '=', cursor.parameter(String(column)))\n next.whereCursor(cursor, orders, index + 1)\n })\n }\n })\n }\n\n // ---------------------------------------------------------------- helpers\n\n /** The compiled SQL (placeholders included), for debugging and tests. */\n toSql(): string {\n return this.connection.compile(this.grammar.compileSelect(this)).sql\n }\n\n getBindings(): unknown[] {\n return [...this.connection.compile(this.grammar.compileSelect(this)).parameters]\n }\n\n clone(): Builder<T> {\n const copy = Object.create(Object.getPrototypeOf(this) as object) as Builder<T>\n Object.assign(copy, this)\n copy.columns = [...this.columns]\n copy.joins = [...this.joins]\n copy.wheres = [...this.wheres]\n copy.groups = [...this.groups]\n copy.havings = [...this.havings]\n copy.orders = [...this.orders]\n return copy\n }\n\n /** A fresh builder on the same connection and table (for nested where groups). */\n newQuery(): Builder<Row> {\n return new Builder<Row>(this.connection, this.fromTable)\n }\n\n requireTable(): string | Expression {\n if (this.fromTable === undefined) throw new LogicError('No table was given: use DB.table(name) or query.from(name).')\n return this.fromTable\n }\n\n private subQuery(callback: NestedCallback<Builder<Row>>): Builder<Row> {\n const query = new Builder<Row>(this.connection)\n callback(query)\n return query\n }\n\n private addNested(callback: NestedCallback<Builder<T>>, boolean: WhereBoolean, not = false): this {\n const query = this.newQuery() as unknown as Builder<T>\n callback(query)\n return this.addNestedWhereQuery(query as Builder<unknown>, boolean, not)\n }\n\n private addWhere(boolean: WhereBoolean, args: unknown[]): this {\n const [column, operatorOrValue, maybeValue] = args\n if (typeof column === 'function') return this.addNested(column as NestedCallback<Builder<T>>, boolean)\n if (isRow(column)) {\n return this.addNested((query) => {\n for (const [key, value] of Object.entries(column)) query.where(key, value)\n }, boolean)\n }\n const [operator, value] = args.length === 2 ? ['=', operatorOrValue] : [String(operatorOrValue).toLowerCase(), maybeValue]\n const ref = column as ColumnRef\n if (operator === 'in' || operator === 'not in') {\n this.wheres.push({ type: 'in', column: ref, values: value as unknown[], not: operator === 'not in', boolean })\n return this\n }\n if (value === null || value === undefined) {\n if (operator === '=') return this.pushNull(ref, false, boolean)\n if (operator === '!=' || operator === '<>') return this.pushNull(ref, true, boolean)\n }\n this.grammar.operator(operator)\n this.wheres.push({ type: 'basic', column: ref, operator, value, boolean })\n return this\n }\n\n /** Laravel's addDateBasedWhere(): one value means '='; the operator is checked against the whitelist. */\n private addDateBasedWhere(part: DatePart, column: ColumnRef, args: DateWhereArgs, boolean: WhereBoolean): this {\n const [operator, value] = args.length === 1 ? ['=', args[0]] : [args[0].toLowerCase(), args[1]]\n this.grammar.operator(operator)\n this.wheres.push({ type: 'date', part, column, operator, value: dateWhereValue(part, value), boolean })\n return this\n }\n\n private pushNull(column: ColumnRef, not: boolean, boolean: WhereBoolean): this {\n this.wheres.push({ type: 'null', column, not, boolean })\n return this\n }\n}\n\nexport type JoinType = 'inner' | 'left' | 'right' | 'cross'\n\n/** The `on …` part of a join. `where()` on a join binds a value; `on()` compares columns. */\nexport class JoinClause extends Builder<Row> {\n constructor(\n parent: Builder<unknown>,\n readonly joinType: JoinType,\n readonly table: string | Expression,\n ) {\n super(parent.connection)\n }\n\n on(first: ColumnRef, operator: string, second?: ColumnRef, boolean: WhereBoolean = 'and'): this {\n return this.whereColumn(first, operator, second, boolean)\n }\n\n orOn(first: ColumnRef, operator: string, second?: ColumnRef): this {\n return this.on(first, operator, second, 'or')\n }\n}\n","import { Collection } from '@orieljs/collections'\nimport type { EloquentCollection } from '../Eloquent/Collection'\nimport type { Model } from '../Eloquent/Model'\n\n/** What a paginator's getCollection() holds: the models' Eloquent collection, else a Collection. */\nexport type PageCollection<T> = [T] extends [Model] ? EloquentCollection<T> : Collection<T>\n\nexport interface PaginatorOptions {\n /** The base URL of the page links (default: the current request's URL, or '/'). */\n path?: string\n /** Extra query string values added to every link. */\n query?: Record<string, unknown>\n fragment?: string\n pageName?: string\n}\n\n/** Laravel's Arr::query(): nested values become key[0]=…, encoded as RFC 3986. */\nexport function buildQuery(values: Record<string, unknown>, prefix?: string): string {\n const parts: string[] = []\n for (const [key, value] of Object.entries(values)) {\n const name = prefix === undefined ? key : `${prefix}[${key}]`\n if (value === undefined || value === null) continue\n if (typeof value === 'object') {\n const nested = buildQuery(value as Record<string, unknown>, name)\n if (nested) parts.push(nested)\n } else {\n parts.push(`${encodeURIComponent(name)}=${encodeURIComponent(String(value))}`)\n }\n }\n return parts.join('&')\n}\n\n/** Models, as far as a paginator can tell without importing Model (Eloquent imports the paginators). */\nconst isModelLike = (value: unknown): boolean =>\n typeof value === 'object' && value !== null && typeof (value as { getKey?: unknown }).getKey === 'function' && typeof (value as { getAttributes?: unknown }).getAttributes === 'function'\n\nconst isArrayable = (value: unknown): value is { toArray(): unknown } =>\n typeof value === 'object' && value !== null && typeof (value as { toArray?: unknown }).toArray === 'function'\n\n/**\n * Shared paginator state and URL building (Laravel's AbstractPaginator).\n * The static resolvers read the current request; DatabaseServiceProvider points them at HttpRequest.\n */\nexport abstract class AbstractPaginator<T> implements Iterable<T> {\n static currentPathResolver: () => string = () => '/'\n static currentPageResolver: (pageName: string) => number = () => 1\n static queryStringResolver: () => Record<string, unknown> = () => ({})\n static currentCursorResolver: (cursorName: string) => unknown = () => undefined\n\n static resolveCurrentPath(): string {\n return AbstractPaginator.currentPathResolver()\n }\n\n static resolveCurrentPage(pageName = 'page'): number {\n const page = AbstractPaginator.currentPageResolver(pageName)\n return Number.isInteger(page) && page >= 1 ? page : 1\n }\n\n /** Restores the defaults (page 1, path '/'). Used by tests and when the provider is torn down. */\n static resetResolvers(): void {\n AbstractPaginator.currentPathResolver = () => '/'\n AbstractPaginator.currentPageResolver = () => 1\n AbstractPaginator.queryStringResolver = () => ({})\n AbstractPaginator.currentCursorResolver = () => undefined\n }\n\n protected collection: Collection<T>\n protected pathValue: string\n protected queryValues: Record<string, unknown>\n protected fragmentValue: string | undefined\n protected pageName: string\n /** The resolved page number: page-based paginators pass it in; cursor pagination never reads it. */\n protected readonly currentPageValue: number\n onEachSideCount = 3\n\n protected constructor(\n items: Iterable<T>,\n protected readonly perPageValue: number,\n options: PaginatorOptions,\n currentPage?: number,\n ) {\n // An Eloquent query hands over its models' collection, kept as it is (slice() and reverse() keep its class).\n this.collection = items instanceof Collection ? (items as Collection<T>) : new Collection(items)\n const path = options.path ?? AbstractPaginator.resolveCurrentPath()\n this.pathValue = path !== '/' ? path.replace(/\\/+$/, '') : path\n this.queryValues = { ...(options.query ?? {}) }\n this.fragmentValue = options.fragment\n this.pageName = options.pageName ?? 'page'\n this.currentPageValue = currentPage !== undefined && Number.isInteger(currentPage) && currentPage >= 1\n ? currentPage\n : AbstractPaginator.resolveCurrentPage(this.pageName)\n }\n\n currentPage(): number {\n return this.currentPageValue\n }\n\n /** The 1-based position of the first item on this page, or null when the page is empty. */\n firstItem(): number | null {\n return this.count() > 0 ? (this.currentPageValue - 1) * this.perPageValue + 1 : null\n }\n\n lastItem(): number | null {\n const first = this.firstItem()\n return first === null ? null : first + this.count() - 1\n }\n\n onFirstPage(): boolean {\n return this.currentPageValue <= 1\n }\n\n previousPageUrl(): string | null {\n return this.currentPageValue > 1 ? this.url(this.currentPageValue - 1) : null\n }\n\n /** The URL for a page number: path?query&page=n#fragment. */\n url(page: number): string {\n const parameters = { ...this.queryValues, [this.pageName]: Math.max(1, page) }\n return this.pathValue + (this.pathValue.includes('?') ? '&' : '?') + buildQuery(parameters) + this.buildFragment()\n }\n\n protected buildFragment(): string {\n return this.fragmentValue ? `#${this.fragmentValue}` : ''\n }\n\n path(): string {\n return this.pathValue\n }\n\n withPath(path: string): this {\n this.pathValue = path\n return this\n }\n\n setPath(path: string): this {\n return this.withPath(path)\n }\n\n /** Adds values to every link's query string. */\n appends(key: string | Record<string, unknown>, value?: unknown): this {\n if (typeof key === 'string') this.queryValues[key] = value\n else Object.assign(this.queryValues, key)\n return this\n }\n\n /** Keeps the current request's query string on every link. */\n withQueryString(): this {\n return this.appends(AbstractPaginator.queryStringResolver())\n }\n\n fragment(fragment: string): this {\n this.fragmentValue = fragment\n return this\n }\n\n getPageName(): string {\n return this.pageName\n }\n\n setPageName(name: string): this {\n this.pageName = name\n return this\n }\n\n onEachSide(count: number): this {\n this.onEachSideCount = count\n return this\n }\n\n /** The items on this page, as an array (Laravel's items()). */\n items(): T[] {\n return this.collection.all()\n }\n\n /** The items on this page: an Eloquent query's in its models' Eloquent collection, as Laravel's. */\n getCollection(): PageCollection<T> {\n return this.collection as PageCollection<T>\n }\n\n setCollection(items: Collection<T>): this {\n this.collection = items\n return this\n }\n\n /**\n * Transforms each item in place, typically for serialization, and returns this paginator typed with the new items:\n * `posts.through((post) => ({ id: post.id }))`. Each paginator narrows the return type to its own class.\n */\n through<U>(callback: (item: T, index: number) => U): AbstractPaginator<U> {\n // As Laravel's Eloquent map(): models stay in their Eloquent collection, anything else goes in a plain one.\n const mapped = this.collection.all().map(callback)\n const eloquent = typeof (this.collection as { modelKeys?: unknown }).modelKeys === 'function' && mapped.every(isModelLike)\n this.collection = (eloquent ? new (this.collection.constructor as new (items: U[]) => Collection<U>)(mapped) : new Collection(mapped)) as unknown as Collection<T>\n return this as unknown as AbstractPaginator<U>\n }\n\n perPage(): number {\n return this.perPageValue\n }\n\n count(): number {\n return this.collection.count()\n }\n\n isEmpty(): boolean {\n return this.collection.isEmpty()\n }\n\n isNotEmpty(): boolean {\n return !this.collection.isEmpty()\n }\n\n [Symbol.iterator](): Iterator<T> {\n return this.collection[Symbol.iterator]()\n }\n\n protected itemsToArray(): unknown[] {\n return this.collection.all().map((item) => (isArrayable(item) ? item.toArray() : item))\n }\n\n abstract toArray(): Record<string, unknown>\n\n toJSON(): Record<string, unknown> {\n return this.toArray()\n }\n\n toJson(): string {\n return JSON.stringify(this.toArray())\n }\n}\n","import { LogicError } from '../errors'\nimport { AbstractPaginator, buildQuery, type PaginatorOptions } from './AbstractPaginator'\n\n/** A position in a cursor-paginated result: the ordered columns' values of an edge item, plus the direction. */\nexport class Cursor {\n constructor(\n protected readonly parameters: Record<string, unknown>,\n protected readonly pointsToNext = true,\n ) {}\n\n parameter(name: string): unknown {\n if (!Object.hasOwn(this.parameters, name)) throw new LogicError(`Unable to find parameter [${name}] in pagination item.`)\n return this.parameters[name]\n }\n\n pointsToNextItems(): boolean {\n return this.pointsToNext\n }\n\n pointsToPreviousItems(): boolean {\n return !this.pointsToNext\n }\n\n toArray(): Record<string, unknown> {\n return { ...this.parameters, _pointsToNextItems: this.pointsToNext }\n }\n\n /** URL-safe base64 of the JSON parameters (Laravel's format). */\n encode(): string {\n return Buffer.from(JSON.stringify(this.toArray())).toString('base64').replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n }\n\n /** Decodes a cursor from the query string. Anything malformed gives undefined (the first page). */\n static fromEncoded(encoded: unknown): Cursor | undefined {\n if (typeof encoded !== 'string' || encoded === '') return undefined\n try {\n const json: unknown = JSON.parse(Buffer.from(encoded.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'))\n if (typeof json !== 'object' || json === null || Array.isArray(json)) return undefined\n const { _pointsToNextItems: pointsToNext, ...parameters } = json as Record<string, unknown>\n if (typeof pointsToNext !== 'boolean') return undefined\n return new Cursor(parameters, pointsToNext)\n } catch {\n return undefined\n }\n }\n}\n\nexport interface CursorPaginatorOptions extends Omit<PaginatorOptions, 'pageName'> {\n cursorName?: string\n /** The ordered columns whose values make up each cursor. */\n parameters: string[]\n}\n\n/** The value of `column` on a row or a model (a model's raw stored value, so it binds exactly as stored). */\nfunction valueOf(item: unknown, column: string): unknown {\n const key = column.includes('.') ? column.slice(column.lastIndexOf('.') + 1) : column\n const source = item as { getAttributes?: () => Record<string, unknown> } & Record<string, unknown>\n const values = typeof source.getAttributes === 'function' ? source.getAttributes() : source\n if (Object.hasOwn(values, column)) return values[column]\n if (Object.hasOwn(values, key)) return values[key]\n throw new LogicError(`Unable to find parameter [${column}] in pagination item.`)\n}\n\n/**\n * cursorPaginate(): \"next\"/\"previous\" by the ordered columns' values instead of an offset, so it stays fast and\n * stable on large, changing tables (Laravel's CursorPaginator). JSON: data, path, per_page, next_cursor,\n * next_page_url, prev_cursor, prev_page_url.\n */\nexport class CursorPaginator<T> extends AbstractPaginator<T> {\n protected readonly hasMore: boolean\n protected readonly cursorName: string\n protected readonly parameters: string[]\n\n constructor(\n items: Iterable<T>,\n perPage: number,\n protected readonly cursorValue: Cursor | undefined,\n options: CursorPaginatorOptions,\n ) {\n super(items, perPage, options)\n this.cursorName = options.cursorName ?? 'cursor'\n this.parameters = options.parameters\n this.hasMore = this.collection.count() > perPage\n this.collection = this.collection.slice(0, perPage)\n // Previous pages are fetched in reverse order; flip them back.\n if (cursorValue?.pointsToPreviousItems()) this.collection = this.collection.reverse()\n }\n\n /** The cursor in the current request's query string (?cursor=…), if any. */\n static resolveCurrentCursor(cursorName = 'cursor'): Cursor | undefined {\n return Cursor.fromEncoded(AbstractPaginator.currentCursorResolver(cursorName))\n }\n\n cursor(): Cursor | undefined {\n return this.cursorValue\n }\n\n getCursorName(): string {\n return this.cursorName\n }\n\n override through<U>(callback: (item: T, index: number) => U): CursorPaginator<U> {\n return super.through(callback) as CursorPaginator<U>\n }\n\n hasMorePages(): boolean {\n return (this.cursorValue === undefined && this.hasMore) ||\n (this.cursorValue !== undefined && this.cursorValue.pointsToNextItems() && this.hasMore) ||\n (this.cursorValue !== undefined && this.cursorValue.pointsToPreviousItems())\n }\n\n override onFirstPage(): boolean {\n return this.cursorValue === undefined || (this.cursorValue.pointsToPreviousItems() && !this.hasMore)\n }\n\n nextCursor(): Cursor | undefined {\n if ((this.cursorValue === undefined || this.cursorValue.pointsToNextItems()) && !this.hasMore) return undefined\n const last = this.collection.last()\n return last === undefined ? undefined : this.cursorFor(last, true)\n }\n\n previousCursor(): Cursor | undefined {\n if (this.onFirstPage()) return undefined\n const first = this.collection.first()\n return first === undefined ? undefined : this.cursorFor(first, false)\n }\n\n nextPageUrl(): string | null {\n const cursor = this.nextCursor()\n return cursor ? this.url(cursor) : null\n }\n\n override previousPageUrl(): string | null {\n const cursor = this.previousCursor()\n return cursor ? this.url(cursor) : null\n }\n\n /** The URL for a cursor: path?query&cursor=…#fragment. */\n override url(cursor: Cursor | number): string {\n const value = typeof cursor === 'number' ? undefined : cursor.encode()\n const parameters = { ...this.queryValues, [this.cursorName]: value }\n return this.pathValue + (this.pathValue.includes('?') ? '&' : '?') + buildQuery(parameters) + this.buildFragment()\n }\n\n protected cursorFor(item: T, pointsToNext: boolean): Cursor {\n return new Cursor(Object.fromEntries(this.parameters.map((column) => [column, valueOf(item, column)])), pointsToNext)\n }\n\n toArray(): Record<string, unknown> {\n return {\n data: this.itemsToArray(),\n path: this.path(),\n per_page: this.perPageValue,\n next_cursor: this.nextCursor()?.encode() ?? null,\n next_page_url: this.nextPageUrl(),\n prev_cursor: this.previousCursor()?.encode() ?? null,\n prev_page_url: this.previousPageUrl(),\n }\n }\n}\n","import { AbstractPaginator, type PaginatorOptions } from './AbstractPaginator'\n\nexport interface PaginationLink {\n url: string | null\n label: string\n active: boolean\n}\n\n/** Page number → URL, in page order. */\ntype UrlRange = Array<[number, string]>\n\n/**\n * paginate(): knows the total, so it can render every page link (Laravel's LengthAwarePaginator).\n * JSON: current_page, data, first_page_url, from, last_page, last_page_url, links, next_page_url, path, per_page,\n * prev_page_url, to, total.\n */\nexport class LengthAwarePaginator<T> extends AbstractPaginator<T> {\n protected readonly lastPageValue: number\n\n constructor(\n items: Iterable<T>,\n protected readonly totalValue: number,\n perPage: number,\n currentPage?: number,\n options: PaginatorOptions = {},\n ) {\n super(items, perPage, options, currentPage)\n this.lastPageValue = Math.max(Math.ceil(totalValue / perPage), 1)\n }\n\n total(): number {\n return this.totalValue\n }\n\n override through<U>(callback: (item: T, index: number) => U): LengthAwarePaginator<U> {\n return super.through(callback) as LengthAwarePaginator<U>\n }\n\n lastPage(): number {\n return this.lastPageValue\n }\n\n hasPages(): boolean {\n return this.currentPageValue !== 1 || this.hasMorePages()\n }\n\n hasMorePages(): boolean {\n return this.currentPageValue < this.lastPageValue\n }\n\n onLastPage(): boolean {\n return !this.hasMorePages()\n }\n\n nextPageUrl(): string | null {\n return this.hasMorePages() ? this.url(this.currentPageValue + 1) : null\n }\n\n /**\n * The page links Laravel renders: previous, the page window with '...' gaps, next. The labels are plain text\n * (\"« Previous\", \"Next »\"), not Laravel's `«` entities, so a page can print them as text.\n */\n linkCollection(): PaginationLink[] {\n const links: PaginationLink[] = [{ url: this.previousPageUrl(), label: '\\u00AB Previous', active: false }]\n for (const element of this.elements()) {\n if (element === '...') links.push({ url: null, label: '...', active: false })\n else for (const [page, url] of element) links.push({ url, label: String(page), active: page === this.currentPageValue })\n }\n links.push({ url: this.nextPageUrl(), label: 'Next \\u00BB', active: false })\n return links\n }\n\n /** Laravel's UrlWindow: the first pages, the slider around the current page and the last pages, with '...' between. */\n protected elements(): Array<UrlRange | '...'> {\n const window = this.urlWindow()\n const elements: Array<UrlRange | '...' | undefined> = [\n window.first,\n window.slider ? '...' : undefined,\n window.slider,\n window.last ? '...' : undefined,\n window.last,\n ]\n return elements.filter((element): element is UrlRange | '...' => element !== undefined && element.length > 0)\n }\n\n private urlWindow(): { first?: UrlRange; slider?: UrlRange; last?: UrlRange } {\n const onEachSide = this.onEachSideCount\n const last = this.lastPageValue\n const current = this.currentPageValue\n if (last < onEachSide * 2 + 8) return { first: this.range(1, last) }\n const window = onEachSide + 4\n if (!this.hasPages()) return {}\n if (current <= window) return { first: this.range(1, window + onEachSide), last: this.range(last - 1, last) }\n if (current > last - window) return { first: this.range(1, 2), last: this.range(last - (window + (onEachSide - 1)), last) }\n return {\n first: this.range(1, 2),\n slider: this.range(current - onEachSide, current + onEachSide),\n last: this.range(last - 1, last),\n }\n }\n\n private range(from: number, to: number): UrlRange {\n const pages: UrlRange = []\n for (let page = from; page <= to; page++) pages.push([page, this.url(page)])\n return pages\n }\n\n toArray(): Record<string, unknown> {\n return {\n current_page: this.currentPageValue,\n data: this.itemsToArray(),\n first_page_url: this.url(1),\n from: this.firstItem(),\n last_page: this.lastPageValue,\n last_page_url: this.url(this.lastPageValue),\n links: this.linkCollection(),\n next_page_url: this.nextPageUrl(),\n path: this.path(),\n per_page: this.perPageValue,\n prev_page_url: this.previousPageUrl(),\n to: this.lastItem(),\n total: this.totalValue,\n }\n }\n}\n","import { AbstractPaginator, type PaginatorOptions } from './AbstractPaginator'\n\n/**\n * simplePaginate(): no total, only \"is there a next page\". The query fetches perPage + 1 rows; the extra row only\n * sets hasMorePages() (Laravel's Paginator).\n */\nexport class Paginator<T> extends AbstractPaginator<T> {\n protected readonly hasMore: boolean\n\n constructor(items: Iterable<T>, perPage: number, currentPage?: number, options: PaginatorOptions = {}) {\n super(items, perPage, options, currentPage)\n this.hasMore = this.collection.count() > perPage\n this.collection = this.collection.slice(0, perPage)\n }\n\n hasMorePages(): boolean {\n return this.hasMore\n }\n\n override through<U>(callback: (item: T, index: number) => U): Paginator<U> {\n return super.through(callback) as Paginator<U>\n }\n\n hasPages(): boolean {\n return this.currentPageValue !== 1 || this.hasMore\n }\n\n onLastPage(): boolean {\n return !this.hasMore\n }\n\n nextPageUrl(): string | null {\n return this.hasMore ? this.url(this.currentPageValue + 1) : null\n }\n\n toArray(): Record<string, unknown> {\n return {\n current_page: this.currentPageValue,\n current_page_url: this.url(this.currentPageValue),\n data: this.itemsToArray(),\n first_page_url: this.url(1),\n from: this.firstItem(),\n next_page_url: this.nextPageUrl(),\n path: this.path(),\n per_page: this.perPageValue,\n prev_page_url: this.previousPageUrl(),\n to: this.lastItem(),\n }\n }\n}\n","import { sql, type RawBuilder } from 'kysely'\nimport type { DriverName, Row } from '@orieljs/contracts'\nimport { LogicError } from '../errors'\nimport { Expression, rawWithBindings } from './Expression'\nimport { prepareValue } from './values'\nimport { GROUP_ROW, type Builder, type Having, type JoinClause, type Where } from './Builder'\n\ntype Sql = RawBuilder<unknown>\n\n/** The operators accepted by where()/having(). Anything else is rejected: operators are written into the SQL. */\nexport const OPERATORS = new Set(['=', '<', '>', '<=', '>=', '<>', '!=', 'like', 'not like', 'ilike', 'not ilike'])\n\nconst EMPTY: Sql = sql.raw('')\nconst isSqlFragment = (value: unknown): value is Sql =>\n typeof value === 'object' && value !== null && typeof (value as Partial<Sql>).toOperationNode === 'function'\nconst join = (parts: Sql[], separator = ', '): Sql => sql.join(parts, sql.raw(separator))\n/** Joins non-empty clauses with single spaces. */\nconst clauses = (parts: Array<Sql | undefined>): Sql => join(parts.filter((part): part is Sql => part !== undefined), ' ')\n\n/**\n * A like pattern as a SQLite glob pattern (Laravel's SQLiteGrammar::prepareWhereLikeBinding): a literal * or ? is\n * bracketed first, then % becomes * and _ becomes ?.\n */\nfunction likeToGlob(pattern: string): string {\n return pattern.replaceAll('*', '[*]').replaceAll('?', '[?]').replaceAll('%', '*').replaceAll('_', '?')\n}\n\n/** SQLite's strftime() format for each date part (Laravel's SQLiteGrammar). */\nconst SQLITE_DATE_FORMATS = { date: '%Y-%m-%d', time: '%H:%M:%S', day: '%d', month: '%m', year: '%Y' } as const\n\n/**\n * Compiles a query builder's state into a Kysely `sql` template for one driver, like Laravel's Query\\Grammars.\n * Identifiers go through sql.id() (quoted per dialect); values are always bound parameters.\n */\nexport class Grammar {\n constructor(readonly driver: DriverName) {}\n\n /** 'users.name' → \"users\".\"name\", 'users.*' → \"users\".*, 'name as n' → \"name\" as \"n\". Expressions pass through raw. */\n wrap(value: string | Expression): Sql {\n if (value instanceof Expression) return rawWithBindings(value.value, value.bindings.map((v) => this.prepare(v)))\n const alias = /\\s+as\\s+/i.exec(value)\n if (alias) {\n const left = value.slice(0, alias.index)\n const right = value.slice(alias.index + alias[0].length)\n return sql`${this.wrap(left)} as ${sql.id(right.trim())}`\n }\n return join(\n value.split('.').map((segment) => (segment === '*' ? sql.raw('*') : sql.id(segment))),\n '.',\n )\n }\n\n wrapTable(table: string | Expression): Sql {\n return this.wrap(table)\n }\n\n prepare(value: unknown): unknown {\n return prepareValue(value, this.driver)\n }\n\n /** A bound value, the raw SQL of an Expression, or a Kysely sql fragment as-is. */\n parameter(value: unknown): Sql {\n if (value instanceof Expression) return this.wrap(value)\n if (isSqlFragment(value)) return value\n return sql`${this.prepare(value)}`\n }\n\n operator(operator: string): string {\n const normalized = operator.toLowerCase()\n if (!OPERATORS.has(normalized)) throw new LogicError(`Illegal operator [${operator}].`)\n if (this.driver !== 'pgsql' && normalized.endsWith('ilike')) return normalized.replace('ilike', 'like')\n return normalized\n }\n\n columnize(columns: ReadonlyArray<string | Expression>): Sql {\n return join(columns.map((column) => this.wrap(column)))\n }\n\n compileSelect(query: Builder<unknown>, extraColumn?: Sql): Sql {\n if (query.groupLimit && extraColumn === undefined) return this.compileGroupLimit(query)\n const list = query.columns.length\n ? query.columns.map((column) => (typeof column === 'object' && 'query' in column\n ? sql`${sql.raw(column.exists ? 'exists ' : '')}(${this.compileSelect(column.query)}) as ${sql.id(column.as)}`\n : this.wrap(column)))\n : [sql.raw('*')]\n const columns = join(extraColumn ? [...list, extraColumn] : list)\n return clauses([query.distinctRows ? sql`select distinct ${columns}` : sql`select ${columns}`, this.compileComponents(query)])\n }\n\n /**\n * Laravel 11's compileGroupLimit(): the query numbers its rows per `column` in its own order, and an outer query keeps\n * those inside the limit and offset, in row-number order. SQLite 3.25+, MySQL 8 and PostgreSQL have window functions.\n */\n compileGroupLimit(query: Builder<unknown>): Sql {\n const { column, limit, offset } = query.groupLimit!\n const inner = query.clone()\n inner.groupLimit = undefined\n inner.orders = []\n const order = this.compileOrders(query)\n const over = order ? sql`partition by ${this.wrap(column)} ${order}` : sql`partition by ${this.wrap(column)}`\n const row = sql.id(GROUP_ROW)\n const kept: Sql[] = []\n if (offset !== undefined && offset > 0) kept.push(sql`${row} > ${sql.lit(offset)}`)\n if (limit !== undefined) kept.push(sql`${row} <= ${sql.lit((offset ?? 0) + limit)}`)\n return clauses([\n sql`select * from (${this.compileSelect(inner, sql`row_number() over (${over}) as ${row}`)}) as ${sql.id('oriel_table')}`,\n kept.length ? sql`where ${join(kept, ' and ')}` : undefined,\n sql`order by ${row}`,\n ])\n }\n\n /** Everything after the select list: from, joins, where, group by, having, order by, limit/offset, lock. */\n compileComponents(query: Builder<unknown>): Sql {\n return clauses([\n query.fromTable === undefined ? undefined : sql`from ${this.wrapTable(query.fromTable)}`,\n ...query.joins.map((joinClause) => this.compileJoin(joinClause)),\n this.compileWheres(query.wheres, 'where'),\n query.groups.length ? sql`group by ${this.columnize(query.groups)}` : undefined,\n this.compileHavings(query.havings),\n this.compileOrders(query),\n this.compileLimitOffset(query.limitValue, query.offsetValue),\n this.compileLock(query.lockMode),\n ])\n }\n\n compileOrders(query: Builder<unknown>): Sql | undefined {\n if (!query.orders.length) return undefined\n return sql`order by ${join(query.orders.map((order) => ('raw' in order ? this.wrap(order.raw) : sql`${this.wrap(order.column)} ${sql.raw(order.direction)}`)))}`\n }\n\n compileWheres(wheres: readonly Where[], keyword?: 'where' | 'on'): Sql | undefined {\n if (!wheres.length) return undefined\n const body = join(wheres.map((where, i) => (i === 0 ? this.compileWhere(where) : sql`${sql.raw(where.boolean)} ${this.compileWhere(where)}`)), ' ')\n return keyword ? sql`${sql.raw(keyword)} ${body}` : body\n }\n\n compileWhere(where: Where): Sql {\n switch (where.type) {\n case 'basic': {\n const column = typeof where.column === 'object' && !(where.column instanceof Expression)\n ? sql`(${this.compileSelect(where.column)})`\n : this.wrap(where.column)\n const operator = this.operator(where.operator)\n // As Laravel's PostgresGrammar: a like comparison reads the column as text, so it works on numbers and dates too.\n if (this.driver === 'pgsql' && /like/i.test(operator)) return sql`${column}::text ${sql.raw(operator)} ${this.parameter(where.value)}`\n return sql`${column} ${sql.raw(operator)} ${this.parameter(where.value)}`\n }\n case 'in': {\n const keyword = sql.raw(where.not ? 'not in' : 'in')\n if (!Array.isArray(where.values)) return sql`${this.wrap(where.column)} ${keyword} (${this.compileSelect(where.values as Builder<unknown>)})`\n if (where.values.length === 0) return sql.raw(where.not ? '1 = 1' : '0 = 1')\n return sql`${this.wrap(where.column)} ${keyword} (${join(where.values.map((value) => this.parameter(value)))})`\n }\n case 'null':\n return sql`${this.wrap(where.column)} ${sql.raw(where.not ? 'is not null' : 'is null')}`\n case 'like':\n return this.compileWhereLike(where)\n case 'between':\n return sql`${this.wrap(where.column)} ${sql.raw(where.not ? 'not between' : 'between')} ${this.parameter(where.values[0])} and ${this.parameter(where.values[1])}`\n case 'column':\n return sql`${this.wrap(where.first)} ${sql.raw(this.operator(where.operator))} ${this.wrap(where.second)}`\n case 'nested':\n return sql`${sql.raw(where.not ? 'not ' : '')}(${this.compileWheres(where.query.wheres) ?? EMPTY})`\n case 'exists':\n return sql`${sql.raw(where.not ? 'not exists' : 'exists')} (${this.compileSelect(where.query)})`\n case 'raw':\n return rawWithBindings(where.sql, where.bindings.map((value) => this.prepare(value)))\n case 'date':\n return this.compileWhereDate(where)\n }\n }\n\n /**\n * whereDate(), whereTime(), whereDay(), whereMonth() and whereYear() per driver, as Laravel 12's grammars: MySQL's\n * date()/time()/day()/month()/year(), Postgres' ::date, ::time and extract(), SQLite's strftime() compared as text.\n */\n compileWhereDate(where: Extract<Where, { type: 'date' }>): Sql {\n const column = this.wrap(where.column)\n const operator = sql.raw(this.operator(where.operator))\n const value = this.parameter(where.value)\n if (this.driver === 'sqlite') return sql`strftime(${sql.lit(SQLITE_DATE_FORMATS[where.part])}, ${column}) ${operator} cast(${value} as text)`\n if (this.driver === 'pgsql') {\n if (where.part === 'date' || where.part === 'time') return sql`${column}::${sql.raw(where.part)} ${operator} ${value}`\n return sql`extract(${sql.raw(where.part)} from ${column}) ${operator} ${value}`\n }\n return sql`${sql.raw(where.part)}(${column}) ${operator} ${value}`\n }\n\n /**\n * whereLike() per driver, as Laravel 12's grammars: Postgres compares the column as text with ilike (like when\n * case-sensitive); MySQL uses like (like binary); SQLite uses like, or glob with the pattern translated.\n */\n compileWhereLike(where: Extract<Where, { type: 'like' }>): Sql {\n const not = where.not ? 'not ' : ''\n const column = this.wrap(where.column)\n if (this.driver === 'pgsql') return sql`${column}::text ${sql.raw(`${not}${where.caseSensitive ? 'like' : 'ilike'}`)} ${this.parameter(where.value)}`\n if (this.driver === 'mysql') return sql`${column} ${sql.raw(`${not}${where.caseSensitive ? 'like binary' : 'like'}`)} ${this.parameter(where.value)}`\n if (where.caseSensitive) return sql`${column} ${sql.raw(`${not}glob`)} ${this.parameter(likeToGlob(where.value))}`\n return sql`${column} ${sql.raw(`${not}like`)} ${this.parameter(where.value)}`\n }\n\n compileJoin(joinClause: JoinClause): Sql {\n if (joinClause.joinType === 'cross') return sql`cross join ${this.wrapTable(joinClause.table)}`\n return sql`${sql.raw(joinClause.joinType)} join ${this.wrapTable(joinClause.table)} ${this.compileWheres(joinClause.wheres, 'on') ?? EMPTY}`\n }\n\n compileHavings(havings: readonly Having[]): Sql | undefined {\n if (!havings.length) return undefined\n const parts = havings.map((having, i) => {\n const body = 'raw' in having\n ? this.wrap(having.raw)\n : sql`${this.wrap(having.column)} ${sql.raw(this.operator(having.operator))} ${this.parameter(having.value)}`\n return i === 0 ? body : sql`${sql.raw(having.boolean)} ${body}`\n })\n return sql`having ${join(parts, ' ')}`\n }\n\n compileLimitOffset(limit: number | undefined, offset: number | undefined): Sql | undefined {\n if (limit === undefined && offset === undefined) return undefined\n const parts: Sql[] = []\n if (limit !== undefined) parts.push(sql`limit ${sql.lit(limit)}`)\n // SQLite and MySQL can't OFFSET without a LIMIT.\n else if (this.driver === 'sqlite') parts.push(sql.raw('limit -1'))\n else if (this.driver === 'mysql') parts.push(sql.raw('limit 18446744073709551615'))\n if (offset !== undefined) parts.push(sql`offset ${sql.lit(offset)}`)\n return join(parts, ' ')\n }\n\n compileLock(mode: 'update' | 'share' | undefined): Sql | undefined {\n if (mode === undefined || this.driver === 'sqlite') return undefined\n if (mode === 'update') return sql.raw('for update')\n return sql.raw(this.driver === 'pgsql' ? 'for share' : 'lock in share mode')\n }\n\n /**\n * `select count(*) as aggregate …`. Orders, limit and offset are dropped. Grouped or distinct queries, and those with a\n * `having` (which may name a selected alias, withCount()'s `comments_count`), are wrapped, keeping their columns.\n */\n compileAggregate(query: Builder<unknown>, fn: string, column: string | Expression): Sql {\n const inner = query.clone()\n inner.orders = []\n inner.limitValue = undefined\n inner.offsetValue = undefined\n inner.lockMode = undefined\n const target = column === '*' ? sql.raw('*') : this.wrap(column)\n if (inner.groups.length || inner.distinctRows || inner.havings.length) {\n if (fn === 'count') return sql`select count(*) as ${sql.id('aggregate')} from (${this.compileSelect(inner)}) as ${sql.id('temp_table')}`\n if (column instanceof Expression) {\n throw new LogicError(`${fn}() can't target a raw expression over a distinct or grouped query: select it as an aliased column instead.`)\n }\n if (!inner.columns.length) inner.columns = [column]\n const unqualified = column.split('.').pop()!.trim()\n return sql`select ${sql.raw(fn)}(${sql.id(unqualified)}) as ${sql.id('aggregate')} from (${this.compileSelect(inner)}) as ${sql.id('temp_table')}`\n }\n return sql`select ${sql.raw(fn)}(${target}) as ${sql.id('aggregate')} ${this.compileComponents(inner)}`\n }\n\n compileExists(query: Builder<unknown>): Sql {\n return sql`select exists(${this.compileSelect(query)}) as ${sql.id('exists')}`\n }\n\n compileInsert(query: Builder<unknown>, rows: readonly Row[]): Sql {\n if (rows.every((row) => !Object.keys(row).length)) {\n const table = this.wrapTable(query.requireTable())\n return this.driver === 'mysql' ? sql`insert into ${table} () values ()` : sql`insert into ${table} default values`\n }\n return sql`insert ${this.compileInsertBody(query, rows)}`\n }\n\n compileInsertOrIgnore(query: Builder<unknown>, rows: readonly Row[]): Sql {\n const body = this.compileInsertBody(query, rows)\n if (this.driver === 'mysql') return sql`insert ignore ${body}`\n if (this.driver === 'sqlite') return sql`insert or ignore ${body}`\n return sql`insert ${body} on conflict do nothing`\n }\n\n /** `into \"table\" (\"a\", \"b\") values (?, ?), (?, ?)`. Columns are the union of every row's keys; a missing key binds null. */\n compileInsertBody(query: Builder<unknown>, rows: readonly Row[]): Sql {\n const columns = [...new Set(rows.flatMap((row) => Object.keys(row)))]\n const values = join(rows.map((row) => sql`(${join(columns.map((column) => this.parameter(row[column])))})`))\n return sql`into ${this.wrapTable(query.requireTable())} (${this.columnize(columns)}) values ${values}`\n }\n\n compileInsertGetId(query: Builder<unknown>, row: Row, keyName: string): Sql {\n const insert = this.compileInsert(query, [row])\n return this.driver === 'pgsql' ? sql`${insert} returning ${this.wrap(keyName)}` : insert\n }\n\n compileUpsert(query: Builder<unknown>, rows: readonly Row[], uniqueBy: readonly string[], update: readonly string[]): Sql {\n const insert = this.compileInsert(query, rows)\n if (this.driver === 'mysql') {\n const alias = 'laravel_upsert_alias'\n const sets = join(update.map((column) => sql`${this.wrap(column)} = ${sql.id(alias, column)}`))\n return sql`${insert} as ${sql.id(alias)} on duplicate key update ${sets}`\n }\n const sets = join(update.map((column) => sql`${this.wrap(column)} = ${sql.id('excluded', column)}`))\n return sql`${insert} on conflict (${this.columnize(uniqueBy)}) do update set ${sets}`\n }\n\n compileUpdate(query: Builder<unknown>, values: Row): Sql {\n this.assertSimpleMutation(query, 'update')\n const sets = join(Object.entries(values).map(([column, value]) => sql`${this.wrap(column.split('.').pop()!)} = ${this.parameter(value)}`))\n return clauses([\n sql`update ${this.wrapTable(query.requireTable())} set ${sets}`,\n this.compileWheres(query.wheres, 'where'),\n ...this.mysqlOrderAndLimit(query),\n ])\n }\n\n compileDelete(query: Builder<unknown>): Sql {\n this.assertSimpleMutation(query, 'delete')\n return clauses([\n sql`delete from ${this.wrapTable(query.requireTable())}`,\n this.compileWheres(query.wheres, 'where'),\n ...this.mysqlOrderAndLimit(query),\n ])\n }\n\n compileTruncate(query: Builder<unknown>): Sql[] {\n const table = this.wrapTable(query.requireTable())\n if (this.driver === 'pgsql') return [sql`truncate table ${table} restart identity cascade`]\n if (this.driver === 'mysql') return [sql`truncate table ${table}`]\n return [sql`delete from ${table}`]\n }\n\n compileRandom(): Expression {\n return new Expression(this.driver === 'mysql' ? 'RAND()' : 'random()')\n }\n\n private assertSimpleMutation(query: Builder<unknown>, action: string): void {\n if (query.joins.length || query.offsetValue !== undefined || (query.limitValue !== undefined && this.driver !== 'mysql')) {\n throw new LogicError(`${action}() with joins, offset or (except on MySQL) limit isn't supported. Select the keys first, then ${action} with whereIn().`)\n }\n }\n\n private mysqlOrderAndLimit(query: Builder<unknown>): Array<Sql | undefined> {\n if (this.driver !== 'mysql') return []\n return [\n this.compileOrders(query),\n query.limitValue === undefined ? undefined : sql`limit ${sql.lit(query.limitValue)}`,\n ]\n }\n}\n","import type { DriverName } from '@orieljs/contracts'\nimport { LogicError } from '../errors'\n\nconst pad = (n: number, width = 2) => String(n).padStart(width, '0')\n\n/** Laravel's storage format ('Y-m-d H:i:s'), in UTC. */\nexport function formatDateTime(date: Date): string {\n return (\n `${pad(date.getUTCFullYear(), 4)}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())} ` +\n `${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())}:${pad(date.getUTCSeconds())}`\n )\n}\n\nexport function formatDate(date: Date): string {\n return formatDateTime(date).slice(0, 10)\n}\n\n/**\n * Parses a stored date/time as UTC. Accepts Dates, epoch milliseconds, 'Y-m-d', 'Y-m-d H:i:s' and ISO strings\n * (the last two with or without a zone suffix; a missing zone means UTC).\n */\nexport function parseDateTime(value: unknown): Date {\n if (value instanceof Date) return new Date(value.getTime())\n if (typeof value === 'number') return new Date(value)\n const text = String(value).trim()\n const match = /^(\\d{4}-\\d{2}-\\d{2})(?:[ T](\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d+)?)?))?\\s*(Z|[+-]\\d{2}(?::?\\d{2})?)?$/i.exec(text)\n if (match) {\n const [, day, time = '00:00:00', zone] = match\n let offset = 'Z'\n if (zone && zone.toUpperCase() !== 'Z') offset = zone.length === 3 ? `${zone}:00` : zone.includes(':') ? zone : `${zone.slice(0, 3)}:${zone.slice(3)}`\n return new Date(`${day}T${time.length === 5 ? `${time}:00` : time}${offset}`)\n }\n const parsed = new Date(text)\n if (Number.isNaN(parsed.getTime())) throw new LogicError(`Unable to parse [${text}] as a date.`)\n return parsed\n}\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && Object.getPrototypeOf(value) === Object.prototype\n\n/** Normalizes one binding for the driver: booleans, dates, JSON and undefined. */\nexport function prepareValue(value: unknown, driver: DriverName): unknown {\n if (value === undefined) return null\n if (typeof value === 'boolean') return driver === 'pgsql' ? value : value ? 1 : 0\n if (value instanceof Date) return formatDateTime(value)\n if (Array.isArray(value) || isPlainObject(value)) return JSON.stringify(value)\n return value\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport { Kysely, sql, type CompiledQuery, type ControlledTransaction, type QueryResult, type RawBuilder } from 'kysely'\nimport type { DatabaseConnection, DriverName, Row } from '@orieljs/contracts'\nimport { createDialect, type ConnectionConfig } from './Connectors/dialect'\nimport { QueryError } from './errors'\nimport { Builder } from './Query/Builder'\nimport { Expression, rawWithBindings } from './Query/Expression'\nimport { prepareValue } from './Query/values'\nimport { SchemaBuilder } from './Schema/Builder'\n\n/** One open transaction level. Level 1 is the real transaction; deeper levels are savepoints named trans<level>. */\ninterface TransactionFrame {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n readonly trx: ControlledTransaction<any>\n readonly level: number\n /** An inner level's savepoint, named per frame. */\n readonly savepoint?: string\n /**\n * Inner transactions under one level take turns. Savepoints are a stack on one connection: rolling one back undoes\n * everything after it, a sibling's committed work included, so a sibling waits for the one before it to end.\n */\n turn: Promise<void>\n /** Hands the parent's turn to the next sibling, once this inner level has ended. */\n readonly endTurn?: () => void\n /** The level this one is nested in. */\n readonly parent?: TransactionFrame\n /** Opened by beginTransaction(): open for every async context until commit() or rollBack(). */\n pinned?: boolean\n /** The testing traits' transaction (Laravel's callbacksShouldIgnore()): it holds no afterCommit() callbacks. */\n ignoresCallbacks?: boolean\n /** afterCommit() callbacks, run once the outermost transaction(fn) commits; dropped on rollback. */\n readonly callbacks: Array<() => unknown>\n /** afterCommit()'s onRollBack callbacks, run if this level (or, once it commits, the one it's nested in) rolls back. */\n readonly rollbacks: Array<() => unknown>\n /** How the level ended, once it has: a callback added later still follows it. */\n ended?: 'commit' | 'rollback'\n}\n\n/** Whether afterCommit() callbacks wait in this level: any but the testing traits' transaction. */\nfunction holdsCallbacks(frame: TransactionFrame | undefined): frame is TransactionFrame {\n return frame !== undefined && frame.ignoresCallbacks !== true\n}\n\nexport interface LoggedQuery {\n query: string\n bindings: readonly unknown[]\n time: number\n}\n\n/**\n * A named database connection on Kysely.\n *\n * Transactions: `transaction(fn)` is bound to the async context that called it (AsyncLocalStorage), so a\n * transaction in one request never captures another request's queries. `beginTransaction()` instead pins the\n * transaction to the whole connection until `commit()`/`rollBack()`; that is what RefreshDatabase needs.\n * Nested levels use savepoints (trans2, trans3, …) either way.\n */\nexport class Connection implements DatabaseConnection {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n protected readonly db: Kysely<any>\n private readonly context = new AsyncLocalStorage<TransactionFrame>()\n private readonly pinned: TransactionFrame[] = []\n private savepoints = 0\n private loggingQueries = false\n private queryLog: LoggedQuery[] = []\n\n constructor(\n protected readonly name: string,\n protected readonly config: ConnectionConfig,\n ) {\n this.db = new Kysely({ dialect: createDialect(config) })\n }\n\n getName(): string {\n return this.name\n }\n\n getDriverName(): DriverName {\n return this.config.driver\n }\n\n getConfig(): ConnectionConfig {\n return this.config\n }\n\n /** A query builder for a table: connection.table('users').where('votes', '>', 100).get(). */\n table<T = Row>(table: string | Expression): Builder<T> {\n return new Builder<T>(this, table)\n }\n\n /** A query builder with no table yet (use from()). */\n query<T = Row>(): Builder<T> {\n return new Builder<T>(this)\n }\n\n /** Schema operations on this connection (Laravel's getSchemaBuilder()). */\n getSchemaBuilder(): SchemaBuilder {\n return new SchemaBuilder(this)\n }\n\n /** Raw Kysely access. Inside a transaction this is the transaction, so queries join it. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n kysely(): Kysely<any> {\n return this.current()?.trx ?? this.db\n }\n\n /** Normalizes a value for this driver (booleans, Dates, JSON). */\n prepareValue(value: unknown): unknown {\n return prepareValue(value, this.config.driver)\n }\n\n /** Compiles a Kysely raw builder against this connection's dialect. */\n compile(query: RawBuilder<unknown>): CompiledQuery {\n return query.compile(this.db)\n }\n\n /** Runs a compiled statement on the current executor (the transaction, when one is open). */\n async execute<T = Row>(query: RawBuilder<unknown> | CompiledQuery): Promise<QueryResult<T>> {\n const compiled = 'compile' in query ? this.compile(query) : query\n const started = performance.now()\n try {\n return await this.kysely().executeQuery<T>(compiled)\n } catch (error) {\n throw new QueryError(this.name, compiled.sql, compiled.parameters, error)\n } finally {\n if (this.loggingQueries) {\n this.queryLog.push({ query: compiled.sql, bindings: compiled.parameters, time: performance.now() - started })\n }\n }\n }\n\n /** Raw select with `?` placeholders. */\n async select<T = Row>(query: string, bindings: readonly unknown[] = []): Promise<T[]> {\n return (await this.execute<T>(this.raw(query, bindings))).rows\n }\n\n /** Raw statement with `?` placeholders. */\n async statement(query: string, bindings: readonly unknown[] = []): Promise<void> {\n await this.execute(this.raw(query, bindings))\n }\n\n /** Raw statement; returns the number of affected rows. */\n async affectingStatement(query: string, bindings: readonly unknown[] = []): Promise<number> {\n return Number((await this.execute(this.raw(query, bindings))).numAffectedRows ?? 0)\n }\n\n private raw(query: string, bindings: readonly unknown[]): RawBuilder<unknown> {\n return rawWithBindings(query, bindings.map((value) => this.prepareValue(value)))\n }\n\n /** Runs fn in a transaction (a savepoint when nested). Commits when fn resolves, rolls back and rethrows when it throws. */\n async transaction<R>(fn: (connection: this) => Promise<R>): Promise<R> {\n const frame = await this.open()\n let result: R\n try {\n result = await this.context.run(frame, () => fn(this))\n } catch (error) {\n try {\n await this.close(frame, 'rollback')\n } finally {\n await this.rolledBack(frame)\n }\n throw error\n }\n try {\n await this.close(frame, 'commit')\n } catch (error) {\n await this.rolledBack(frame)\n throw error\n }\n await this.committed(frame)\n return result\n }\n\n /** A committed level hands its callbacks to the transaction(fn) it's nested in, or runs them, outside its context. */\n private async committed(frame: TransactionFrame): Promise<void> {\n frame.ended = 'commit'\n if (holdsCallbacks(frame.parent)) {\n frame.parent.callbacks.push(...frame.callbacks.splice(0))\n frame.parent.rollbacks.push(...frame.rollbacks.splice(0))\n return\n }\n frame.rollbacks.length = 0\n for (const callback of frame.callbacks.splice(0)) await this.context.exit(() => callback())\n }\n\n /** A level that rolled back drops its callbacks and runs its onRollBack ones, outside its context. */\n private async rolledBack(frame: TransactionFrame): Promise<void> {\n frame.ended = 'rollback'\n frame.callbacks.length = 0\n for (const callback of frame.rollbacks.splice(0)) await this.runQuietly(callback)\n }\n\n /** An onRollBack callback's failure must not hide the error that rolled the transaction back. */\n private async runQuietly(callback: () => unknown): Promise<void> {\n try {\n await this.context.exit(() => callback())\n } catch {\n // The transaction's own error is the one its caller gets.\n }\n }\n\n /** Starts a transaction that stays open, for every async context, until commit()/rollBack(). */\n async beginTransaction(): Promise<void> {\n const frame = await this.open()\n frame.pinned = true\n this.pinned.push(frame)\n }\n\n /**\n * @internal RefreshDatabase's and DatabaseTransactions': the level beginTransaction() just opened holds no\n * afterCommit() callbacks, so they run as they would without the test's transaction (Laravel's\n * callbacksShouldIgnore()), and a test's own transaction(fn) or beginTransaction() runs them at its commit.\n */\n ignoreAfterCommitAtCurrentLevel(): void {\n const frame = this.pinned.at(-1)\n if (frame) frame.ignoresCallbacks = true\n }\n\n /**\n * Laravel's DB::afterCommit(): runs the callback once the transaction open here commits, the outermost one when\n * they're nested, and drops it if that level rolls back: a transaction(fn) open in this async context, or a level\n * beginTransaction() opened. Outside one, or in only the testing traits' transaction, it runs at once.\n * `onRollBack` runs instead when the level that holds the callback rolls back. A callback added once its level has\n * ended (by work nobody awaited) follows it: held by the level it was committed into, run if the commit is done,\n * dropped if it rolled back.\n */\n async afterCommit(callback: () => unknown, onRollBack?: () => unknown): Promise<void> {\n let frame = this.context.getStore() ?? this.pinned.at(-1)\n while (frame?.ended === 'commit') frame = holdsCallbacks(frame.parent) ? frame.parent : undefined\n if (!holdsCallbacks(frame)) {\n await callback()\n return\n }\n if (frame.ended === 'rollback') {\n if (onRollBack !== undefined) await this.runQuietly(onRollBack)\n return\n }\n frame.callbacks.push(callback)\n if (onRollBack !== undefined) frame.rollbacks.push(onRollBack)\n }\n\n /** @internal Whether a transaction is open here that afterCommit() would wait for. */\n inTransactionContext(): boolean {\n return holdsCallbacks(this.context.getStore() ?? this.pinned.at(-1))\n }\n\n /** Commits the innermost level opened by beginTransaction(), then runs (or hands up) its afterCommit() callbacks. */\n async commit(): Promise<void> {\n const frame = this.pinned.pop()\n if (!frame) return\n try {\n await this.close(frame, 'commit')\n } catch (error) {\n await this.rolledBack(frame)\n throw error\n }\n await this.committed(frame)\n }\n\n /** Rolls back the innermost level opened by beginTransaction(), dropping its afterCommit() callbacks. */\n async rollBack(): Promise<void> {\n const frame = this.pinned.pop()\n if (!frame) return\n try {\n await this.close(frame, 'rollback')\n } finally {\n await this.rolledBack(frame)\n }\n }\n\n transactionLevel(): number {\n return this.current()?.level ?? 0\n }\n\n enableQueryLog(): void {\n this.loggingQueries = true\n }\n\n disableQueryLog(): void {\n this.loggingQueries = false\n }\n\n getQueryLog(): LoggedQuery[] {\n return [...this.queryLog]\n }\n\n flushQueryLog(): void {\n this.queryLog = []\n }\n\n async disconnect(): Promise<void> {\n await this.db.destroy()\n }\n\n /** The innermost open level: the context's own transaction or a pinned one, whichever is deeper. */\n private current(): TransactionFrame | undefined {\n const own = this.context.getStore()\n const pinned = this.pinned.at(-1)\n if (!own) return pinned\n if (!pinned) return own\n return pinned.level > own.level ? pinned : own\n }\n\n private async open(): Promise<TransactionFrame> {\n const parent = this.current()\n if (!parent) return { trx: await this.db.startTransaction().execute(), level: 1, turn: Promise.resolve(), callbacks: [], rollbacks: [] }\n const previous = parent.turn\n let endTurn!: () => void\n parent.turn = new Promise<void>((resolve) => (endTurn = resolve))\n await previous\n const level = parent.level + 1\n const savepoint = `trans${level}_${++this.savepoints}`\n try {\n await sql.raw(`SAVEPOINT ${savepoint}`).execute(parent.trx)\n } catch (error) {\n endTurn()\n throw error\n }\n return { trx: parent.trx, level, savepoint, turn: Promise.resolve(), endTurn, parent, callbacks: [], rollbacks: [] }\n }\n\n private async close(frame: TransactionFrame, action: 'commit' | 'rollback'): Promise<void> {\n try {\n if (frame.level === 1) {\n await (action === 'commit' ? frame.trx.commit() : frame.trx.rollback()).execute()\n } else if (action === 'commit') {\n await sql.raw(`RELEASE SAVEPOINT ${frame.savepoint}`).execute(frame.trx)\n } else {\n await sql.raw(`ROLLBACK TO SAVEPOINT ${frame.savepoint}`).execute(frame.trx)\n }\n } finally {\n frame.endTurn?.()\n }\n }\n}\n","import { sql, type RawBuilder } from 'kysely'\nimport type { Connection } from '../Connection'\nimport { LogicError } from '../errors'\nimport { Blueprint } from './Blueprint'\nimport { isTableRebuild, SchemaGrammar, SqliteSchemaGrammar, type ColumnInfo, type ForeignKeyInfo, type IndexInfo } from './Grammar'\nimport { rebuildSqliteTable } from './SqliteTableRebuild'\n\n/**\n * Laravel's Schema builder for one connection: Schema.create('posts', (t) => { t.id(); t.string('title') }).\n * Each blueprint compiles to one or more statements, run in order.\n */\nexport class SchemaBuilder {\n readonly grammar: SchemaGrammar\n\n constructor(\n protected readonly db: Connection,\n private readonly resolveConnection?: (name: string) => Connection,\n ) {\n this.grammar = SchemaGrammar.for(db.getDriverName(), db.getConfig())\n }\n\n getConnection(): Connection {\n return this.db\n }\n\n /** The schema builder of another connection: Schema.connection('pgsql').create(…). */\n connection(name: string): SchemaBuilder {\n if (!this.resolveConnection) throw new LogicError('This schema builder has no connection resolver.')\n return new SchemaBuilder(this.resolveConnection(name), this.resolveConnection)\n }\n\n async create(table: string, callback: (table: Blueprint) => void): Promise<void> {\n const blueprint = new Blueprint(table, true)\n callback(blueprint)\n await this.build(blueprint)\n }\n\n /** Changes an existing table: add columns, indexes and foreign keys, drop or rename columns. */\n async table(table: string, callback: (table: Blueprint) => void): Promise<void> {\n const blueprint = new Blueprint(table)\n callback(blueprint)\n await this.build(blueprint)\n }\n\n async drop(table: string): Promise<void> {\n await this.run([this.grammar.compileDrop(table)])\n }\n\n async dropIfExists(table: string): Promise<void> {\n await this.run([this.grammar.compileDropIfExists(table)])\n }\n\n async rename(from: string, to: string): Promise<void> {\n await this.run([this.grammar.compileRename(from, to)])\n }\n\n /**\n * Runs a blueprint's statements in order (inspect them with grammar.compile(blueprint)). On SQLite, a change to the\n * keys of an existing table rebuilds it from its live definition at its place in that order.\n */\n async build(blueprint: Blueprint): Promise<void> {\n for (const step of this.grammar.compileSteps(blueprint)) {\n if (isTableRebuild(step)) await rebuildSqliteTable(this.db, this.grammar as SqliteSchemaGrammar, step)\n else await this.db.execute(step)\n }\n }\n\n /** The table names of the connection's database (or current schema on Postgres). */\n async getTables(): Promise<string[]> {\n const rows = (await this.db.execute<{ name: string }>(this.grammar.compileTables())).rows\n return rows.map((row) => String(row.name))\n }\n\n async hasTable(table: string): Promise<boolean> {\n return (await this.getTables()).includes(table)\n }\n\n async getColumns(table: string): Promise<ColumnInfo[]> {\n const rows = (await this.db.execute<Record<string, unknown>>(this.grammar.compileColumns(table))).rows\n return this.grammar.normalizeColumns(rows)\n }\n\n async getColumnListing(table: string): Promise<string[]> {\n return (await this.getColumns(table)).map((column) => column.name)\n }\n\n /** Case-insensitive, like Laravel. */\n async hasColumn(table: string, column: string): Promise<boolean> {\n return this.hasColumns(table, [column])\n }\n\n async hasColumns(table: string, columns: string[]): Promise<boolean> {\n const existing = (await this.getColumnListing(table)).map((name) => name.toLowerCase())\n return columns.every((column) => existing.includes(column.toLowerCase()))\n }\n\n /** The table's indexes, its primary key included (Laravel's getIndexes()). */\n async getIndexes(table: string): Promise<IndexInfo[]> {\n const rows = (await this.db.execute<Record<string, unknown>>(this.grammar.compileIndexes(table))).rows\n return this.grammar.normalizeIndexes(rows)\n }\n\n async getIndexListing(table: string): Promise<string[]> {\n return (await this.getIndexes(table)).map((index) => index.name)\n }\n\n /**\n * Whether the table has an index with this name, or on exactly these columns (in order). `type` narrows it:\n * 'primary', 'unique', or an index method such as 'btree'.\n */\n async hasIndex(table: string, index: string | string[], type?: string): Promise<boolean> {\n const wanted = type?.toLowerCase()\n return (await this.getIndexes(table)).some((value) => {\n const typeMatches = wanted === undefined || (wanted === 'primary' && value.primary) || (wanted === 'unique' && value.unique) || wanted === value.type\n const indexMatches = typeof index === 'string'\n ? value.name === index\n : value.columns.length === index.length && value.columns.every((column, i) => column === index[i])\n return indexMatches && typeMatches\n })\n }\n\n /** The table's foreign keys (Laravel's getForeignKeys()). */\n async getForeignKeys(table: string): Promise<ForeignKeyInfo[]> {\n const rows = (await this.db.execute<Record<string, unknown>>(this.grammar.compileForeignKeys(table))).rows\n return this.grammar.normalizeForeignKeys(rows)\n }\n\n async enableForeignKeyConstraints(): Promise<void> {\n await this.run([this.grammar.compileEnableForeignKeyConstraints()])\n }\n\n async disableForeignKeyConstraints(): Promise<void> {\n await this.run([this.grammar.compileDisableForeignKeyConstraints()])\n }\n\n /**\n * Runs fn with foreign key checks off. On MySQL and Postgres the connection is pinned (a transaction) so the\n * setting and fn's statements share one pooled connection; SQLite has a single connection already.\n */\n async withoutForeignKeyConstraints<R>(fn: () => Promise<R>): Promise<R> {\n const run = async () => {\n await this.disableForeignKeyConstraints()\n try {\n return await fn()\n } finally {\n await this.enableForeignKeyConstraints()\n }\n }\n return this.db.getDriverName() === 'sqlite' ? run() : this.db.transaction(run)\n }\n\n /** Drops every table (migrate:fresh). */\n async dropAllTables(): Promise<void> {\n const tables = await this.getTables()\n if (!tables.length) return\n if (this.db.getDriverName() === 'pgsql') {\n await this.run([sql`drop table ${sql.join(tables.map((table) => sql.id(table)))} cascade`])\n return\n }\n await this.withoutForeignKeyConstraints(async () => {\n for (const table of tables) await this.run([this.grammar.compileDrop(table)])\n })\n }\n\n private async run(statements: Array<RawBuilder<unknown>>): Promise<void> {\n for (const statement of statements) await this.db.execute(statement)\n }\n}\n","import { Expression } from '../Query/Expression'\n\nexport type ColumnType =\n | 'bigInteger' | 'integer' | 'mediumInteger' | 'smallInteger' | 'tinyInteger'\n | 'string' | 'char' | 'text' | 'mediumText' | 'longText'\n | 'boolean' | 'date' | 'dateTime' | 'time' | 'timestamp'\n | 'decimal' | 'float' | 'double'\n | 'json' | 'jsonb' | 'uuid' | 'ulid' | 'binary' | 'enum'\n\n/** Everything a column definition can carry. Grammars read these; the fluent methods set them. */\nexport interface ColumnAttributes {\n type: ColumnType\n name: string\n length?: number\n total?: number\n places?: number\n precision?: number\n allowed?: readonly string[]\n autoIncrement?: boolean\n unsigned?: boolean\n nullable?: boolean\n default?: unknown\n primary?: boolean\n unique?: boolean | string\n index?: boolean | string\n comment?: string\n after?: string\n first?: boolean\n onUpdate?: Expression\n /** Set by change(): the column exists and is redefined, not added. */\n change?: boolean\n}\n\n/** A column in a Blueprint, with Laravel's fluent modifiers: t.string('email').nullable().unique(). */\nexport class ColumnDefinition {\n constructor(readonly attributes: ColumnAttributes) {}\n\n get name(): string {\n return this.attributes.name\n }\n\n /** Allows NULL (the default is NOT NULL). */\n nullable(value = true): this {\n this.attributes.nullable = value\n return this\n }\n\n /** A default value. Strings, numbers and booleans are quoted as literals; DB.raw() passes through unescaped. */\n default(value: unknown): this {\n this.attributes.default = value\n return this\n }\n\n unsigned(): this {\n this.attributes.unsigned = true\n return this\n }\n\n autoIncrement(): this {\n this.attributes.autoIncrement = true\n return this\n }\n\n primary(value = true): this {\n this.attributes.primary = value\n return this\n }\n\n /** Adds a unique index on this column, optionally with a name. */\n unique(name?: string): this {\n this.attributes.unique = name ?? true\n return this\n }\n\n /** Adds a plain index on this column, optionally with a name. */\n index(name?: string): this {\n this.attributes.index = name ?? true\n return this\n }\n\n /** Column comment (MySQL and Postgres; ignored on SQLite). */\n comment(text: string): this {\n this.attributes.comment = text\n return this\n }\n\n /** MySQL only: place the column after another one. Ignored elsewhere. */\n after(column: string): this {\n this.attributes.after = column\n return this\n }\n\n /** MySQL only: place the column first. Ignored elsewhere. */\n first(): this {\n this.attributes.first = true\n return this\n }\n\n /** default CURRENT_TIMESTAMP. */\n useCurrent(): this {\n this.attributes.default = new Expression('CURRENT_TIMESTAMP')\n return this\n }\n\n /**\n * Redefines an existing column (Laravel's change()): t.string('title', 500).nullable().change(). As in Laravel 11+,\n * the column becomes exactly this definition: a modifier it had and that isn't given again (nullable, default,\n * comment, …) is dropped. On SQLite the table is rebuilt.\n */\n change(): this {\n this.attributes.change = true\n return this\n }\n\n /** MySQL only: on update CURRENT_TIMESTAMP. */\n useCurrentOnUpdate(): this {\n this.attributes.onUpdate = new Expression('CURRENT_TIMESTAMP')\n return this\n }\n}\n","import { Str } from '@orieljs/support'\nimport { ColumnDefinition, type ColumnAttributes } from './ColumnDefinition'\n\nexport type ReferentialAction = 'cascade' | 'restrict' | 'set null' | 'no action' | 'set default'\n\n/** t.foreign('user_id').references('id').on('users').cascadeOnDelete() */\nexport class ForeignKeyDefinition {\n referencedColumns: string[] = ['id']\n referencedTable: string | undefined\n deleteAction: ReferentialAction | undefined\n updateAction: ReferentialAction | undefined\n\n constructor(\n readonly columns: string[],\n public indexName: string,\n ) {}\n\n references(columns: string | string[]): this {\n this.referencedColumns = [columns].flat()\n return this\n }\n\n on(table: string): this {\n this.referencedTable = table\n return this\n }\n\n onDelete(action: ReferentialAction): this {\n this.deleteAction = action\n return this\n }\n\n onUpdate(action: ReferentialAction): this {\n this.updateAction = action\n return this\n }\n\n cascadeOnDelete(): this {\n return this.onDelete('cascade')\n }\n\n restrictOnDelete(): this {\n return this.onDelete('restrict')\n }\n\n nullOnDelete(): this {\n return this.onDelete('set null')\n }\n\n noActionOnDelete(): this {\n return this.onDelete('no action')\n }\n\n cascadeOnUpdate(): this {\n return this.onUpdate('cascade')\n }\n\n restrictOnUpdate(): this {\n return this.onUpdate('restrict')\n }\n\n nullOnUpdate(): this {\n return this.onUpdate('set null')\n }\n\n noActionOnUpdate(): this {\n return this.onUpdate('no action')\n }\n\n /** Overrides the constraint name (default: {table}_{columns}_foreign). */\n name(name: string): this {\n this.indexName = name\n return this\n }\n}\n\n/** foreignId('user_id').constrained(): the column plus, on demand, its foreign key. */\nexport class ForeignIdColumnDefinition extends ColumnDefinition {\n constructor(\n attributes: ColumnAttributes,\n private readonly addForeign: (column: string) => ForeignKeyDefinition,\n ) {\n super(attributes)\n }\n\n /**\n * A foreign key to `table` (default: the column name without `_id`, pluralized: user_id → users) on `column`.\n * Chain cascadeOnDelete() etc. on the returned definition.\n */\n constrained(table?: string, column = 'id', indexName?: string): ForeignKeyDefinition {\n const foreign = this.addForeign(this.name).references(column).on(table ?? Str.plural(this.name.replace(/_id$/, '')))\n if (indexName) foreign.name(indexName)\n return foreign\n }\n\n /** A foreign key on this column to `column`; chain on('table'). */\n references(column: string): ForeignKeyDefinition {\n return this.addForeign(this.name).references(column)\n }\n}\n","import { ColumnDefinition, type ColumnAttributes, type ColumnType } from './ColumnDefinition'\nimport { ForeignIdColumnDefinition, ForeignKeyDefinition } from './ForeignKeyDefinition'\n\nexport type IndexType = 'primary' | 'unique' | 'index'\n\nexport type BlueprintCommand =\n | { name: 'create' }\n | { name: IndexType; columns: string[]; index: string }\n | { name: 'foreign'; foreign: ForeignKeyDefinition }\n | { name: 'dropColumn'; columns: string[] }\n | { name: 'renameColumn'; from: string; to: string }\n | { name: 'dropPrimary' | 'dropUnique' | 'dropIndex'; index: string }\n | { name: 'dropForeign'; index: string; columns?: string[] }\n | { name: 'rename'; to: string }\n | { name: 'drop' | 'dropIfExists' }\n\n/**\n * The table definition passed to Schema.create()/Schema.table() callbacks, with Laravel's column types and\n * commands. It only records; the schema grammar turns it into DDL for one driver.\n */\nexport class Blueprint {\n readonly columns: ColumnDefinition[] = []\n readonly commands: BlueprintCommand[] = []\n\n constructor(\n readonly table: string,\n readonly creating = false,\n ) {\n if (creating) this.commands.push({ name: 'create' })\n }\n\n // ---------------------------------------------------------------- columns\n\n addColumn(type: ColumnType, name: string, attributes: Partial<ColumnAttributes> = {}): ColumnDefinition {\n const column = new ColumnDefinition({ type, name, ...attributes })\n this.columns.push(column)\n return column\n }\n\n /** An auto-incrementing unsigned big integer primary key (Laravel's id()). */\n id(column = 'id'): ColumnDefinition {\n return this.bigIncrements(column)\n }\n\n increments(column: string): ColumnDefinition {\n return this.addColumn('integer', column, { autoIncrement: true, unsigned: true })\n }\n\n bigIncrements(column: string): ColumnDefinition {\n return this.addColumn('bigInteger', column, { autoIncrement: true, unsigned: true })\n }\n\n integer(column: string, autoIncrement = false, unsigned = false): ColumnDefinition {\n return this.addColumn('integer', column, { autoIncrement, unsigned })\n }\n\n bigInteger(column: string, autoIncrement = false, unsigned = false): ColumnDefinition {\n return this.addColumn('bigInteger', column, { autoIncrement, unsigned })\n }\n\n mediumInteger(column: string, autoIncrement = false, unsigned = false): ColumnDefinition {\n return this.addColumn('mediumInteger', column, { autoIncrement, unsigned })\n }\n\n smallInteger(column: string, autoIncrement = false, unsigned = false): ColumnDefinition {\n return this.addColumn('smallInteger', column, { autoIncrement, unsigned })\n }\n\n tinyInteger(column: string, autoIncrement = false, unsigned = false): ColumnDefinition {\n return this.addColumn('tinyInteger', column, { autoIncrement, unsigned })\n }\n\n unsignedInteger(column: string): ColumnDefinition {\n return this.integer(column, false, true)\n }\n\n unsignedBigInteger(column: string): ColumnDefinition {\n return this.bigInteger(column, false, true)\n }\n\n unsignedSmallInteger(column: string): ColumnDefinition {\n return this.smallInteger(column, false, true)\n }\n\n unsignedTinyInteger(column: string): ColumnDefinition {\n return this.tinyInteger(column, false, true)\n }\n\n /** An unsigned big integer meant for a foreign key: t.foreignId('user_id').constrained().cascadeOnDelete(). */\n foreignId(column: string): ForeignIdColumnDefinition {\n const definition = new ForeignIdColumnDefinition({ type: 'bigInteger', name: column, unsigned: true }, (name) => this.foreign(name))\n this.columns.push(definition)\n return definition\n }\n\n string(column: string, length = 255): ColumnDefinition {\n return this.addColumn('string', column, { length })\n }\n\n char(column: string, length = 255): ColumnDefinition {\n return this.addColumn('char', column, { length })\n }\n\n text(column: string): ColumnDefinition {\n return this.addColumn('text', column)\n }\n\n mediumText(column: string): ColumnDefinition {\n return this.addColumn('mediumText', column)\n }\n\n longText(column: string): ColumnDefinition {\n return this.addColumn('longText', column)\n }\n\n boolean(column: string): ColumnDefinition {\n return this.addColumn('boolean', column)\n }\n\n date(column: string): ColumnDefinition {\n return this.addColumn('date', column)\n }\n\n dateTime(column: string, precision = 0): ColumnDefinition {\n return this.addColumn('dateTime', column, { precision })\n }\n\n time(column: string, precision = 0): ColumnDefinition {\n return this.addColumn('time', column, { precision })\n }\n\n timestamp(column: string, precision = 0): ColumnDefinition {\n return this.addColumn('timestamp', column, { precision })\n }\n\n /** Nullable created_at and updated_at. */\n timestamps(precision = 0): void {\n this.timestamp('created_at', precision).nullable()\n this.timestamp('updated_at', precision).nullable()\n }\n\n nullableTimestamps(precision = 0): void {\n this.timestamps(precision)\n }\n\n /** A nullable deleted_at timestamp for soft deletes. */\n softDeletes(column = 'deleted_at', precision = 0): ColumnDefinition {\n return this.timestamp(column, precision).nullable()\n }\n\n decimal(column: string, total = 8, places = 2): ColumnDefinition {\n return this.addColumn('decimal', column, { total, places })\n }\n\n float(column: string, precision = 53): ColumnDefinition {\n return this.addColumn('float', column, { precision })\n }\n\n double(column: string): ColumnDefinition {\n return this.addColumn('double', column)\n }\n\n json(column: string): ColumnDefinition {\n return this.addColumn('json', column)\n }\n\n jsonb(column: string): ColumnDefinition {\n return this.addColumn('jsonb', column)\n }\n\n uuid(column = 'uuid'): ColumnDefinition {\n return this.addColumn('uuid', column)\n }\n\n ulid(column = 'ulid'): ColumnDefinition {\n return this.addColumn('ulid', column)\n }\n\n binary(column: string): ColumnDefinition {\n return this.addColumn('binary', column)\n }\n\n enum(column: string, allowed: readonly string[]): ColumnDefinition {\n return this.addColumn('enum', column, { allowed })\n }\n\n /** remember_token varchar(100) null. */\n rememberToken(): ColumnDefinition {\n return this.string('remember_token', 100).nullable()\n }\n\n /** {name}_type + {name}_id, indexed together: the columns of a polymorphic relation. */\n morphs(name: string, indexName?: string): void {\n this.string(`${name}_type`)\n this.unsignedBigInteger(`${name}_id`)\n this.index([`${name}_type`, `${name}_id`], indexName)\n }\n\n nullableMorphs(name: string, indexName?: string): void {\n this.string(`${name}_type`).nullable()\n this.unsignedBigInteger(`${name}_id`).nullable()\n this.index([`${name}_type`, `${name}_id`], indexName)\n }\n\n // ---------------------------------------------------------------- indexes and keys\n\n primary(columns: string | string[], name?: string): void {\n this.indexCommand('primary', columns, name)\n }\n\n unique(columns: string | string[], name?: string): void {\n this.indexCommand('unique', columns, name)\n }\n\n index(columns: string | string[], name?: string): void {\n this.indexCommand('index', columns, name)\n }\n\n /** t.foreign('user_id').references('id').on('users') */\n foreign(columns: string | string[], name?: string): ForeignKeyDefinition {\n const list = [columns].flat()\n const foreign = new ForeignKeyDefinition(list, name ?? this.createIndexName('foreign', list))\n this.commands.push({ name: 'foreign', foreign })\n return foreign\n }\n\n // ---------------------------------------------------------------- changes to an existing table\n\n dropColumn(...columns: Array<string | string[]>): void {\n this.commands.push({ name: 'dropColumn', columns: columns.flat() })\n }\n\n renameColumn(from: string, to: string): void {\n this.commands.push({ name: 'renameColumn', from, to })\n }\n\n dropPrimary(name?: string): void {\n this.commands.push({ name: 'dropPrimary', index: name ?? `${this.table}_pkey` })\n }\n\n /** By name, or by columns (the conventional {table}_{columns}_unique name). */\n dropUnique(index: string | string[]): void {\n this.commands.push({ name: 'dropUnique', index: this.indexNameFor('unique', index) })\n }\n\n dropIndex(index: string | string[]): void {\n this.commands.push({ name: 'dropIndex', index: this.indexNameFor('index', index) })\n }\n\n /** By name, or by columns (the conventional name; SQLite needs the columns, it doesn't keep foreign key names). */\n dropForeign(index: string | string[]): void {\n const columns = Array.isArray(index) ? [...index] : undefined\n this.commands.push({ name: 'dropForeign', index: this.indexNameFor('foreign', index), ...(columns ? { columns } : {}) })\n }\n\n /** Drops the foreign key on the column, then the column. */\n dropConstrainedForeignId(column: string): void {\n this.dropForeign([column])\n this.dropColumn(column)\n }\n\n dropTimestamps(): void {\n this.dropColumn('created_at', 'updated_at')\n }\n\n dropSoftDeletes(column = 'deleted_at'): void {\n this.dropColumn(column)\n }\n\n dropRememberToken(): void {\n this.dropColumn('remember_token')\n }\n\n dropMorphs(name: string, indexName?: string): void {\n this.dropIndex(indexName ?? this.createIndexName('index', [`${name}_type`, `${name}_id`]))\n this.dropColumn(`${name}_type`, `${name}_id`)\n }\n\n rename(to: string): void {\n this.commands.push({ name: 'rename', to })\n }\n\n drop(): void {\n this.commands.push({ name: 'drop' })\n }\n\n dropIfExists(): void {\n this.commands.push({ name: 'dropIfExists' })\n }\n\n // ---------------------------------------------------------------- helpers\n\n /** The columns this blueprint adds (not the ones change() redefines). */\n addedColumns(): ColumnDefinition[] {\n return this.columns.filter((column) => !column.attributes.change)\n }\n\n /** The existing columns change() redefines (on a table being created, every column is added instead). */\n changedColumns(): ColumnDefinition[] {\n return this.creating ? [] : this.columns.filter((column) => column.attributes.change === true)\n }\n\n /** Laravel's default index name: {table}_{columns}_{type}, lowercased, with - and . replaced by _. */\n createIndexName(type: IndexType | 'foreign', columns: string[]): string {\n return `${this.table}_${columns.join('_')}_${type}`.toLowerCase().replace(/[-.]/g, '_')\n }\n\n /** The index commands implied by column modifiers (t.string('email').unique()), in column order. */\n fluentIndexCommands(): BlueprintCommand[] {\n const commands: BlueprintCommand[] = []\n for (const column of this.columns) {\n for (const type of ['primary', 'unique', 'index'] as const) {\n const value = column.attributes[type]\n if (!value) continue\n const index = typeof value === 'string' ? value : this.createIndexName(type, [column.name])\n commands.push({ name: type, columns: [column.name], index })\n }\n }\n return commands\n }\n\n private indexCommand(type: IndexType, columns: string | string[], name?: string): void {\n const list = [columns].flat()\n this.commands.push({ name: type, columns: list, index: name ?? this.createIndexName(type, list) })\n }\n\n private indexNameFor(type: IndexType | 'foreign', index: string | string[]): string {\n return Array.isArray(index) ? this.createIndexName(type, index) : index\n }\n}\n","import { sql, type RawBuilder } from 'kysely'\nimport type { DriverName } from '@orieljs/contracts'\nimport type { ConnectionConfig } from '../Connectors/dialect'\nimport { LogicError } from '../errors'\nimport { Expression, rawWithBindings } from '../Query/Expression'\nimport type { Blueprint, BlueprintCommand } from './Blueprint'\nimport { ColumnDefinition } from './ColumnDefinition'\nimport type { ForeignKeyDefinition } from './ForeignKeyDefinition'\n\ntype Sql = RawBuilder<unknown>\n\n/** One column of an existing table, as reported by Schema.getColumns(). */\nexport interface ColumnInfo {\n name: string\n /** The base type, lowercased: 'varchar', 'bigint', 'int8', 'tinyint', 'timestamp', … (driver-specific). */\n type_name: string\n /** The full type, lowercased: 'varchar(255)', 'tinyint(1)', 'timestamp(0) without time zone', … */\n type: string\n nullable: boolean\n default: string | null\n auto_increment: boolean\n}\n\n/** One index of an existing table, as reported by Schema.getIndexes() (Laravel's shape). */\nexport interface IndexInfo {\n /** Lower-cased. The primary key is 'primary' on MySQL and on a SQLite rowid table, `{table}_pkey` on Postgres. */\n name: string\n columns: string[]\n /** The index method ('btree', 'hash', …) on Postgres and MySQL; null on SQLite. */\n type: string | null\n unique: boolean\n primary: boolean\n}\n\n/** One foreign key of an existing table, as reported by Schema.getForeignKeys() (Laravel's shape). */\nexport interface ForeignKeyInfo {\n /** The constraint name; null on SQLite, which doesn't keep it. */\n name: string | null\n columns: string[]\n foreign_schema: string\n foreign_table: string\n /** Empty when a SQLite key names only the table (it then points at that table's primary key). */\n foreign_columns: string[]\n /** 'cascade', 'restrict', 'set null', 'set default' or 'no action'. */\n on_update: string\n on_delete: string\n}\n\nconst list = (value: unknown): string[] => (value === null || value === undefined || value === '' ? [] : String(value).split(','))\n\n/**\n * A step a blueprint can't express as fixed SQL: on SQLite, rebuilding the table from its live definition plus these\n * key commands and changed columns. SchemaBuilder.build() runs it (Schema/SqliteTableRebuild.ts).\n */\nexport interface TableRebuild {\n readonly kind: 'rebuild'\n readonly table: string\n readonly commands: BlueprintCommand[]\n readonly changes: ColumnDefinition[]\n}\n\n/** One step of a compiled blueprint: a statement, or a table rebuild. */\nexport type SchemaStep = Sql | TableRebuild\n\nexport const isTableRebuild = (step: SchemaStep): step is TableRebuild => (step as Partial<TableRebuild>).kind === 'rebuild'\n\nconst join = (parts: Sql[], separator = ', '): Sql => sql.join(parts, sql.raw(separator))\nconst columnList = (columns: readonly string[]): Sql => join(columns.map((column) => sql.id(column)))\n\n/**\n * Turns a Blueprint into DDL for one driver (Laravel's Schema\\Grammars). Identifiers go through sql.id();\n * default values and comments are quoted literals (sql.lit); only DB.raw() defaults are written as-is.\n */\nexport abstract class SchemaGrammar {\n abstract readonly driver: DriverName\n\n constructor(protected readonly config: Partial<ConnectionConfig> = {}) {}\n\n static for(driver: DriverName, config: Partial<ConnectionConfig> = {}): SchemaGrammar {\n if (driver === 'pgsql') return new PostgresSchemaGrammar(config)\n if (driver === 'mysql') return new MySqlSchemaGrammar(config)\n return new SqliteSchemaGrammar(config)\n }\n\n /**\n * Every statement for the blueprint: create/add first, then commands in order, then indexes from column modifiers.\n * A blueprint that can only run against the live table (a SQLite rebuild) throws: run it with Schema.table().\n */\n compile(blueprint: Blueprint): Sql[] {\n const steps = this.compileSteps(blueprint)\n if (steps.some(isTableRebuild)) {\n throw new LogicError(`On SQLite, changing [${blueprint.table}] rebuilds the table from its live definition: run the blueprint with Schema.table().`)\n }\n return steps as Sql[]\n }\n\n /** compile() with table rebuilds as steps of their own; consecutive rebuilds of one run are merged into one. */\n compileSteps(blueprint: Blueprint): SchemaStep[] {\n const statements: SchemaStep[] = []\n const commands = [...blueprint.commands, ...blueprint.fluentIndexCommands()]\n const handled = new Set<BlueprintCommand>()\n if (blueprint.creating) {\n statements.push(this.compileCreate(blueprint, commands, handled))\n } else {\n if (blueprint.addedColumns().length) statements.push(...this.compileAdd(blueprint, commands, handled))\n for (const column of blueprint.changedColumns()) statements.push(...this.compileChange(blueprint, column))\n }\n for (const command of commands) {\n if (command.name === 'create' || handled.has(command)) continue\n statements.push(...this.compileCommand(blueprint, command))\n }\n if (blueprint.creating || blueprint.columns.length) statements.push(...this.compileComments(blueprint))\n return mergeRebuilds(statements)\n }\n\n protected compileCreate(blueprint: Blueprint, _commands: BlueprintCommand[], _handled: Set<BlueprintCommand>): Sql {\n return sql`create table ${sql.id(blueprint.table)} (${join(blueprint.columns.map((column) => this.columnDefinition(column)))})`\n }\n\n protected compileAdd(blueprint: Blueprint, _commands: BlueprintCommand[], _handled: Set<BlueprintCommand>): Sql[] {\n return blueprint.addedColumns().map((column) => sql`alter table ${sql.id(blueprint.table)} add column ${this.columnDefinition(column)}`)\n }\n\n /** Redefines an existing column (change()). */\n protected abstract compileChange(blueprint: Blueprint, column: ColumnDefinition): SchemaStep[]\n\n protected compileCommand(blueprint: Blueprint, command: BlueprintCommand): SchemaStep[] {\n const table = sql.id(blueprint.table)\n switch (command.name) {\n case 'primary':\n return [sql`alter table ${table} add primary key (${columnList(command.columns)})`]\n case 'unique':\n return [this.compileUnique(blueprint, command.index, command.columns)]\n case 'index':\n return [this.compileIndex(blueprint, command.index, command.columns)]\n case 'foreign':\n return [sql`alter table ${table} add constraint ${sql.id(command.foreign.indexName)} ${this.foreignKeyClause(command.foreign)}`]\n case 'dropColumn':\n return command.columns.map((column) => sql`alter table ${table} drop column ${sql.id(column)}`)\n case 'renameColumn':\n return [sql`alter table ${table} rename column ${sql.id(command.from)} to ${sql.id(command.to)}`]\n case 'dropPrimary':\n return [this.compileDropPrimary(blueprint, command.index)]\n case 'dropUnique':\n return [this.compileDropUnique(blueprint, command.index)]\n case 'dropIndex':\n return [this.compileDropIndex(blueprint, command.index)]\n case 'dropForeign':\n return [this.compileDropForeign(blueprint, command.index)]\n case 'rename':\n return [this.compileRename(blueprint.table, command.to)]\n case 'drop':\n return [this.compileDrop(blueprint.table)]\n case 'dropIfExists':\n return [this.compileDropIfExists(blueprint.table)]\n case 'create':\n return []\n }\n }\n\n compileRename(from: string, to: string): Sql {\n return sql`alter table ${sql.id(from)} rename to ${sql.id(to)}`\n }\n\n compileDrop(table: string): Sql {\n return sql`drop table ${sql.id(table)}`\n }\n\n compileDropIfExists(table: string): Sql {\n return sql`drop table if exists ${sql.id(table)}`\n }\n\n protected compileUnique(blueprint: Blueprint, index: string, columns: string[]): Sql {\n return sql`alter table ${sql.id(blueprint.table)} add constraint ${sql.id(index)} unique (${columnList(columns)})`\n }\n\n protected compileIndex(blueprint: Blueprint, index: string, columns: string[]): Sql {\n return sql`create index ${sql.id(index)} on ${sql.id(blueprint.table)} (${columnList(columns)})`\n }\n\n protected compileDropPrimary(blueprint: Blueprint, index: string): Sql {\n return sql`alter table ${sql.id(blueprint.table)} drop constraint ${sql.id(index)}`\n }\n\n protected compileDropUnique(blueprint: Blueprint, index: string): Sql {\n return sql`alter table ${sql.id(blueprint.table)} drop constraint ${sql.id(index)}`\n }\n\n protected compileDropIndex(_blueprint: Blueprint, index: string): Sql {\n return sql`drop index ${sql.id(index)}`\n }\n\n protected compileDropForeign(blueprint: Blueprint, index: string): Sql {\n return sql`alter table ${sql.id(blueprint.table)} drop constraint ${sql.id(index)}`\n }\n\n protected compileComments(_blueprint: Blueprint): Sql[] {\n return []\n }\n\n /** `foreign key (\"user_id\") references \"users\" (\"id\") on delete cascade` */\n protected foreignKeyClause(foreign: ForeignKeyDefinition): Sql {\n return sql`foreign key (${columnList(foreign.columns)}) ${this.referencesClause(foreign)}`\n }\n\n /** `references \"users\" (\"id\") on delete cascade on update …` */\n protected referencesClause(foreign: ForeignKeyDefinition): Sql {\n if (!foreign.referencedTable) {\n throw new LogicError(`Foreign key [${foreign.indexName}] has no referenced table: call on('table') or constrained().`)\n }\n const columns = foreign.referencedColumns.length ? sql` (${columnList(foreign.referencedColumns)})` : sql.raw('')\n const parts: Sql[] = [sql`references ${sql.id(foreign.referencedTable)}${columns}`]\n if (foreign.deleteAction) parts.push(sql.raw(`on delete ${foreign.deleteAction}`))\n if (foreign.updateAction) parts.push(sql.raw(`on update ${foreign.updateAction}`))\n return join(parts, ' ')\n }\n\n /** `\"name\" type modifiers` */\n columnDefinition(column: ColumnDefinition): Sql {\n return join([sql`${sql.id(column.name)} ${this.type(column)}`, ...this.modifiers(column)], '')\n }\n\n protected abstract type(column: ColumnDefinition): Sql\n protected abstract modifiers(column: ColumnDefinition): Sql[]\n\n /** Laravel's getDefaultValue(): raw expressions as-is, booleans as '1'/'0', everything else as a quoted literal. */\n protected defaultValue(value: unknown): Sql {\n if (value instanceof Expression) return rawWithBindings(value.value, value.bindings)\n if (typeof value === 'boolean') return sql.lit(value ? '1' : '0')\n return sql.lit(String(value))\n }\n\n protected nullable(column: ColumnDefinition): Sql {\n return sql.raw(column.attributes.nullable ? ' null' : ' not null')\n }\n\n protected default(column: ColumnDefinition): Sql | undefined {\n const value = column.attributes.default\n return value === undefined || value === null ? undefined : sql` default ${this.defaultValue(value)}`\n }\n\n protected enumCheck(column: ColumnDefinition, type: string): Sql {\n const allowed = join((column.attributes.allowed ?? []).map((value) => sql.lit(value)))\n return sql`${sql.raw(type)} check (${sql.id(column.name)} in (${allowed}))`\n }\n\n // ---------------------------------------------------------------- introspection\n\n abstract compileTables(): Sql\n abstract compileColumns(table: string): Sql\n abstract normalizeColumns(rows: Array<Record<string, unknown>>, tableSql?: string): ColumnInfo[]\n abstract compileIndexes(table: string): Sql\n abstract normalizeIndexes(rows: Array<Record<string, unknown>>): IndexInfo[]\n abstract compileForeignKeys(table: string): Sql\n abstract normalizeForeignKeys(rows: Array<Record<string, unknown>>): ForeignKeyInfo[]\n abstract compileEnableForeignKeyConstraints(): Sql\n abstract compileDisableForeignKeyConstraints(): Sql\n}\n\nconst present = (parts: Array<Sql | undefined>): Sql[] => parts.filter((part): part is Sql => part !== undefined)\n\n/** Folds each run of consecutive table rebuilds into one, as Laravel adds one 'alter' after each run of alter commands. */\nfunction mergeRebuilds(steps: SchemaStep[]): SchemaStep[] {\n const merged: SchemaStep[] = []\n for (const step of steps) {\n const previous = merged.at(-1)\n if (isTableRebuild(step) && previous !== undefined && isTableRebuild(previous)) {\n merged[merged.length - 1] = { ...previous, commands: [...previous.commands, ...step.commands], changes: [...previous.changes, ...step.changes] }\n } else {\n merged.push(step)\n }\n }\n return merged\n}\n\nexport class SqliteSchemaGrammar extends SchemaGrammar {\n readonly driver = 'sqlite' as const\n\n /** A new table's primary and foreign keys go inside create table (adding them later rebuilds the table). */\n protected override compileCreate(blueprint: Blueprint, commands: BlueprintCommand[], handled: Set<BlueprintCommand>): Sql {\n const parts = blueprint.columns.map((column) => this.columnDefinition(column))\n for (const command of commands) {\n if (command.name === 'primary') {\n parts.push(sql`primary key (${columnList(command.columns)})`)\n handled.add(command)\n } else if (command.name === 'foreign') {\n parts.push(this.foreignKeyClause(command.foreign))\n handled.add(command)\n }\n }\n return sql`create table ${sql.id(blueprint.table)} (${join(parts)})`\n }\n\n /** New columns may carry an inline `references` clause (the only foreign key SQLite can add later). */\n protected override compileAdd(blueprint: Blueprint, commands: BlueprintCommand[], handled: Set<BlueprintCommand>): Sql[] {\n return blueprint.addedColumns().map((column) => {\n const foreign = commands.find(\n (command): command is Extract<BlueprintCommand, { name: 'foreign' }> =>\n command.name === 'foreign' && command.foreign.columns.length === 1 && command.foreign.columns[0] === column.name,\n )\n let definition = this.columnDefinition(column)\n if (foreign) {\n definition = sql`${definition} ${this.referencesClause(foreign.foreign)}`\n handled.add(foreign)\n }\n return sql`alter table ${sql.id(blueprint.table)} add column ${definition}`\n })\n }\n\n /**\n * SQLite can't add or drop a primary or foreign key on an existing table: those commands rebuild the table (Laravel\n * 11+'s compileAlter), as a step SchemaBuilder.build() runs against the live table.\n */\n protected override compileCommand(blueprint: Blueprint, command: BlueprintCommand): SchemaStep[] {\n if (command.name === 'dropForeign' && !command.columns?.length) {\n throw new LogicError('This database driver does not support dropping foreign keys by name.')\n }\n if (command.name === 'primary' || command.name === 'foreign' || command.name === 'dropPrimary' || command.name === 'dropForeign') {\n return [{ kind: 'rebuild', table: blueprint.table, commands: [command], changes: [] }]\n }\n return super.compileCommand(blueprint, command)\n }\n\n /** SQLite can't alter a column: changing one rebuilds the table with the new definition. */\n protected compileChange(blueprint: Blueprint, column: ColumnDefinition): SchemaStep[] {\n return [{ kind: 'rebuild', table: blueprint.table, commands: [], changes: [column] }]\n }\n\n /** `foreign key (…) references … on delete …`, a table constraint of a rebuilt table. */\n compileForeignKeyConstraint(foreign: ForeignKeyDefinition): Sql {\n return this.foreignKeyClause(foreign)\n }\n\n protected override compileUnique(blueprint: Blueprint, index: string, columns: string[]): Sql {\n return sql`create unique index ${sql.id(index)} on ${sql.id(blueprint.table)} (${columnList(columns)})`\n }\n\n protected override compileDropUnique(_blueprint: Blueprint, index: string): Sql {\n return sql`drop index ${sql.id(index)}`\n }\n\n protected type(column: ColumnDefinition): Sql {\n const { type } = column.attributes\n switch (type) {\n case 'bigInteger': case 'integer': case 'mediumInteger': case 'smallInteger': case 'tinyInteger':\n return sql.raw('integer')\n case 'string': case 'char': case 'uuid': case 'ulid':\n return sql.raw('varchar')\n case 'text': case 'mediumText': case 'longText': case 'json': case 'jsonb':\n return sql.raw('text')\n case 'boolean':\n return sql.raw('tinyint(1)')\n case 'date':\n return sql.raw('date')\n case 'dateTime': case 'timestamp':\n return sql.raw('datetime')\n case 'time':\n return sql.raw('time')\n case 'decimal':\n return sql.raw('numeric')\n case 'float':\n return sql.raw('float')\n case 'double':\n return sql.raw('double')\n case 'binary':\n return sql.raw('blob')\n case 'enum':\n return this.enumCheck(column, 'varchar')\n }\n }\n\n protected modifiers(column: ColumnDefinition): Sql[] {\n const increment = column.attributes.autoIncrement ? sql.raw(' primary key autoincrement') : undefined\n return present([increment, column.attributes.nullable ? undefined : sql.raw(' not null'), this.default(column)])\n }\n\n compileTables(): Sql {\n return sql`select name from sqlite_master where type = 'table' and name not like 'sqlite_%' order by name`\n }\n\n compileColumns(table: string): Sql {\n return sql`select name, type, \"notnull\", dflt_value, pk, (select sql from sqlite_master where type = 'table' and name = ${table}) as table_sql from pragma_table_info(${table}) order by cid`\n }\n\n normalizeColumns(rows: Array<Record<string, unknown>>): ColumnInfo[] {\n return rows.map((row) => {\n const type = String(row.type).toLowerCase()\n const autoIncrement = Number(row.pk) === 1 && type === 'integer' && /autoincrement/i.test(String(row.table_sql ?? ''))\n return {\n name: String(row.name),\n type_name: type.replace(/\\(.*$/, '').trim(),\n type,\n nullable: Number(row.notnull) === 0 && !autoIncrement,\n default: row.dflt_value === null || row.dflt_value === undefined ? null : String(row.dflt_value),\n auto_increment: autoIncrement,\n }\n })\n }\n\n /** Laravel's query: the primary key from pragma_table_xinfo, then every index of pragma_index_list with its columns. */\n compileIndexes(table: string): Sql {\n return sql`select 'primary' as name, group_concat(col) as columns, 1 as \"unique\", 1 as \"primary\" from (select name as col from pragma_table_xinfo(${table}) where pk > 0 order by pk, cid) group by name\n union select name, group_concat(col) as columns, \"unique\", origin = 'pk' as \"primary\" from (select il.*, ii.name as col from pragma_index_list(${table}) il, pragma_index_info(il.name) ii order by il.seq, ii.seqno) group by name, \"unique\", \"primary\"`\n }\n\n /** A table whose primary key has its own index (not a rowid alias) lists it twice: the index entry is kept. */\n normalizeIndexes(rows: Array<Record<string, unknown>>): IndexInfo[] {\n const indexes = rows.map((row) => ({\n name: String(row.name).toLowerCase(),\n columns: list(row.columns),\n type: null,\n unique: Number(row.unique) === 1,\n primary: Number(row.primary) === 1,\n }))\n return indexes.filter((index) => index.primary).length > 1 ? indexes.filter((index) => index.name !== 'primary') : indexes\n }\n\n compileForeignKeys(table: string): Sql {\n return sql`select group_concat(\"from\") as columns, 'main' as foreign_schema, \"table\" as foreign_table, group_concat(\"to\") as foreign_columns, on_update, on_delete\n from (select * from pragma_foreign_key_list(${table}) order by id desc, seq) group by id, \"table\", on_update, on_delete`\n }\n\n normalizeForeignKeys(rows: Array<Record<string, unknown>>): ForeignKeyInfo[] {\n return rows.map((row) => ({\n name: null,\n columns: list(row.columns),\n foreign_schema: String(row.foreign_schema),\n foreign_table: String(row.foreign_table),\n foreign_columns: list(row.foreign_columns),\n on_update: String(row.on_update).toLowerCase(),\n on_delete: String(row.on_delete).toLowerCase(),\n }))\n }\n\n compileEnableForeignKeyConstraints(): Sql {\n return sql.raw('PRAGMA foreign_keys = ON')\n }\n\n compileDisableForeignKeyConstraints(): Sql {\n return sql.raw('PRAGMA foreign_keys = OFF')\n }\n}\n\n/** pg_constraint's confupdtype/confdeltype codes (Laravel's PostgresProcessor). */\nconst POSTGRES_ACTIONS: Record<string, string> = { a: 'no action', r: 'restrict', c: 'cascade', n: 'set null', d: 'set default' }\n\nexport class PostgresSchemaGrammar extends SchemaGrammar {\n readonly driver = 'pgsql' as const\n\n /** A changed column's comment is set again, or cleared (`is NULL`) when the new definition has none (Laravel 11+). */\n protected override compileComments(blueprint: Blueprint): Sql[] {\n const changed = new Set(blueprint.changedColumns())\n return blueprint.columns\n .filter((column) => column.attributes.comment !== undefined || changed.has(column))\n .map((column) => {\n const comment = column.attributes.comment\n return sql`comment on column ${sql.id(blueprint.table, column.name)} is ${comment === undefined ? sql.raw('NULL') : sql.lit(comment)}`\n })\n }\n\n /**\n * Laravel's compileChange(): `alter column` for the type, the nullability and the default, in one statement. A serial\n * type becomes its integer type (the sequence stays), and an auto-increment column keeps its default. No `using`\n * clause: a change Postgres can't cast implicitly fails, as in Laravel.\n */\n protected compileChange(blueprint: Blueprint, column: ColumnDefinition): SchemaStep[] {\n const name = sql.id(column.name)\n const { autoIncrement, nullable, default: value } = column.attributes\n const changes: Sql[] = [\n sql`type ${this.type(new ColumnDefinition({ ...column.attributes, autoIncrement: false }))}`,\n sql.raw(nullable ? 'drop not null' : 'set not null'),\n ]\n if (!autoIncrement) changes.push(value === undefined || value === null ? sql.raw('drop default') : sql`set default ${this.defaultValue(value)}`)\n return [sql`alter table ${sql.id(blueprint.table)} ${join(changes.map((change) => sql`alter column ${name} ${change}`))}`]\n }\n\n protected type(column: ColumnDefinition): Sql {\n const { type, autoIncrement, length, total, places, precision } = column.attributes\n switch (type) {\n case 'bigInteger':\n return sql.raw(autoIncrement ? 'bigserial' : 'bigint')\n case 'integer': case 'mediumInteger':\n return sql.raw(autoIncrement ? 'serial' : 'integer')\n case 'smallInteger': case 'tinyInteger':\n return sql.raw(autoIncrement ? 'smallserial' : 'smallint')\n case 'string':\n return sql.raw(`varchar(${length ?? 255})`)\n case 'char':\n return sql.raw(`char(${length ?? 255})`)\n case 'text': case 'mediumText': case 'longText':\n return sql.raw('text')\n case 'boolean':\n return sql.raw('boolean')\n case 'date':\n return sql.raw('date')\n case 'dateTime': case 'timestamp':\n return sql.raw(`timestamp(${precision ?? 0}) without time zone`)\n case 'time':\n return sql.raw(`time(${precision ?? 0}) without time zone`)\n case 'decimal':\n return sql.raw(`decimal(${total ?? 8}, ${places ?? 2})`)\n case 'float':\n return sql.raw(precision ? `float(${precision})` : 'real')\n case 'double':\n return sql.raw('double precision')\n case 'json':\n return sql.raw('json')\n case 'jsonb':\n return sql.raw('jsonb')\n case 'uuid':\n return sql.raw('uuid')\n case 'ulid':\n return sql.raw('char(26)')\n case 'binary':\n return sql.raw('bytea')\n case 'enum':\n return this.enumCheck(column, 'varchar(255)')\n }\n }\n\n protected modifiers(column: ColumnDefinition): Sql[] {\n return present([this.nullable(column), this.default(column), column.attributes.autoIncrement ? sql.raw(' primary key') : undefined])\n }\n\n compileTables(): Sql {\n return sql`select tablename as name from pg_tables where schemaname = current_schema() order by tablename`\n }\n\n compileColumns(table: string): Sql {\n return sql`select a.attname as name, t.typname as type_name, format_type(a.atttypid, a.atttypmod) as type, not a.attnotnull as nullable, pg_get_expr(d.adbin, d.adrelid) as ${sql.id('default')}\n from pg_attribute a\n join pg_class c on c.oid = a.attrelid\n join pg_namespace n on n.oid = c.relnamespace\n join pg_type t on t.oid = a.atttypid\n left join pg_attrdef d on d.adrelid = a.attrelid and d.adnum = a.attnum\n where c.relname = ${table} and n.nspname = current_schema() and a.attnum > 0 and not a.attisdropped\n order by a.attnum`\n }\n\n normalizeColumns(rows: Array<Record<string, unknown>>): ColumnInfo[] {\n return rows.map((row) => {\n const defaultValue = row.default === null || row.default === undefined ? null : String(row.default)\n return {\n name: String(row.name),\n type_name: String(row.type_name).toLowerCase(),\n type: String(row.type).toLowerCase(),\n nullable: row.nullable === true,\n default: defaultValue,\n auto_increment: defaultValue !== null && defaultValue.startsWith('nextval('),\n }\n })\n }\n\n compileIndexes(table: string): Sql {\n return sql`select ic.relname as name, string_agg(a.attname, ',' order by indseq.ord) as columns, am.amname as ${sql.id('type')}, i.indisunique as ${sql.id('unique')}, i.indisprimary as ${sql.id('primary')}\n from pg_index i\n join pg_class tc on tc.oid = i.indrelid\n join pg_namespace tn on tn.oid = tc.relnamespace\n join pg_class ic on ic.oid = i.indexrelid\n join pg_am am on am.oid = ic.relam\n join lateral unnest(i.indkey) with ordinality as indseq(num, ord) on true\n left join pg_attribute a on a.attrelid = i.indrelid and a.attnum = indseq.num\n where tc.relname = ${table} and tn.nspname = current_schema()\n group by ic.relname, am.amname, i.indisunique, i.indisprimary`\n }\n\n normalizeIndexes(rows: Array<Record<string, unknown>>): IndexInfo[] {\n return rows.map((row) => ({\n name: String(row.name).toLowerCase(),\n columns: list(row.columns),\n type: String(row.type).toLowerCase(),\n unique: row.unique === true,\n primary: row.primary === true,\n }))\n }\n\n compileForeignKeys(table: string): Sql {\n return sql`select c.conname as name, string_agg(la.attname, ',' order by conseq.ord) as columns, fn.nspname as foreign_schema, fc.relname as foreign_table,\n string_agg(fa.attname, ',' order by conseq.ord) as foreign_columns, c.confupdtype as on_update, c.confdeltype as on_delete\n from pg_constraint c\n join pg_class tc on c.conrelid = tc.oid\n join pg_namespace tn on tn.oid = tc.relnamespace\n join pg_class fc on c.confrelid = fc.oid\n join pg_namespace fn on fn.oid = fc.relnamespace\n join lateral unnest(c.conkey) with ordinality as conseq(num, ord) on true\n join pg_attribute la on la.attrelid = c.conrelid and la.attnum = conseq.num\n join pg_attribute fa on fa.attrelid = c.confrelid and fa.attnum = c.confkey[conseq.ord]\n where c.contype = 'f' and tc.relname = ${table} and tn.nspname = current_schema()\n group by c.conname, fn.nspname, fc.relname, c.confupdtype, c.confdeltype`\n }\n\n normalizeForeignKeys(rows: Array<Record<string, unknown>>): ForeignKeyInfo[] {\n return rows.map((row) => ({\n name: String(row.name),\n columns: list(row.columns),\n foreign_schema: String(row.foreign_schema),\n foreign_table: String(row.foreign_table),\n foreign_columns: list(row.foreign_columns),\n on_update: POSTGRES_ACTIONS[String(row.on_update).toLowerCase()] ?? 'no action',\n on_delete: POSTGRES_ACTIONS[String(row.on_delete).toLowerCase()] ?? 'no action',\n }))\n }\n\n compileEnableForeignKeyConstraints(): Sql {\n return sql.raw('SET CONSTRAINTS ALL IMMEDIATE')\n }\n\n compileDisableForeignKeyConstraints(): Sql {\n return sql.raw('SET CONSTRAINTS ALL DEFERRED')\n }\n}\n\nexport class MySqlSchemaGrammar extends SchemaGrammar {\n readonly driver = 'mysql' as const\n\n protected override compileCreate(blueprint: Blueprint, commands: BlueprintCommand[], handled: Set<BlueprintCommand>): Sql {\n const charset = this.config.charset ?? 'utf8mb4'\n const collation = this.config.collation ?? 'utf8mb4_unicode_ci'\n return sql`${super.compileCreate(blueprint, commands, handled)} default character set ${sql.raw(charset.replace(/[^\\w]/g, ''))} collate ${sql.lit(collation)}`\n }\n\n protected override compileAdd(blueprint: Blueprint): Sql[] {\n return blueprint.addedColumns().map((column) => sql`alter table ${sql.id(blueprint.table)} add ${this.columnDefinition(column)}`)\n }\n\n /** Laravel's compileChange(): `modify` with the column's whole new definition. */\n protected compileChange(blueprint: Blueprint, column: ColumnDefinition): SchemaStep[] {\n return [sql`alter table ${sql.id(blueprint.table)} modify ${this.columnDefinition(column)}`]\n }\n\n protected override compileUnique(blueprint: Blueprint, index: string, columns: string[]): Sql {\n return sql`alter table ${sql.id(blueprint.table)} add unique ${sql.id(index)}(${columnList(columns)})`\n }\n\n protected override compileIndex(blueprint: Blueprint, index: string, columns: string[]): Sql {\n return sql`alter table ${sql.id(blueprint.table)} add index ${sql.id(index)}(${columnList(columns)})`\n }\n\n protected override compileDropPrimary(blueprint: Blueprint): Sql {\n return sql`alter table ${sql.id(blueprint.table)} drop primary key`\n }\n\n protected override compileDropUnique(blueprint: Blueprint, index: string): Sql {\n return sql`alter table ${sql.id(blueprint.table)} drop index ${sql.id(index)}`\n }\n\n protected override compileDropIndex(blueprint: Blueprint, index: string): Sql {\n return sql`alter table ${sql.id(blueprint.table)} drop index ${sql.id(index)}`\n }\n\n protected override compileDropForeign(blueprint: Blueprint, index: string): Sql {\n return sql`alter table ${sql.id(blueprint.table)} drop foreign key ${sql.id(index)}`\n }\n\n protected type(column: ColumnDefinition): Sql {\n const { type, length, total, places, precision, allowed } = column.attributes\n switch (type) {\n case 'bigInteger':\n return sql.raw('bigint')\n case 'integer':\n return sql.raw('int')\n case 'mediumInteger':\n return sql.raw('mediumint')\n case 'smallInteger':\n return sql.raw('smallint')\n case 'tinyInteger':\n return sql.raw('tinyint')\n case 'string':\n return sql.raw(`varchar(${length ?? 255})`)\n case 'char':\n return sql.raw(`char(${length ?? 255})`)\n case 'text':\n return sql.raw('text')\n case 'mediumText':\n return sql.raw('mediumtext')\n case 'longText':\n return sql.raw('longtext')\n case 'boolean':\n return sql.raw('tinyint(1)')\n case 'date':\n return sql.raw('date')\n case 'dateTime':\n return sql.raw(precision ? `datetime(${precision})` : 'datetime')\n case 'timestamp':\n return sql.raw(precision ? `timestamp(${precision})` : 'timestamp')\n case 'time':\n return sql.raw(precision ? `time(${precision})` : 'time')\n case 'decimal':\n return sql.raw(`decimal(${total ?? 8}, ${places ?? 2})`)\n case 'float':\n return sql.raw(precision ? `float(${precision})` : 'float')\n case 'double':\n return sql.raw('double')\n case 'json': case 'jsonb':\n return sql.raw('json')\n case 'uuid':\n return sql.raw('char(36)')\n case 'ulid':\n return sql.raw('char(26)')\n case 'binary':\n return sql.raw('blob')\n case 'enum':\n return sql`enum(${join((allowed ?? []).map((value) => sql.lit(value)))})`\n }\n }\n\n protected modifiers(column: ColumnDefinition): Sql[] {\n const { unsigned, autoIncrement, onUpdate, comment, after, first, change, primary } = column.attributes\n // A changed auto-increment column already is the key (Laravel's modifyIncrement).\n const increment = change && !primary ? ' auto_increment' : ' auto_increment primary key'\n return present([\n unsigned ? sql.raw(' unsigned') : undefined,\n this.nullable(column),\n this.default(column),\n onUpdate ? sql` on update ${this.defaultValue(onUpdate)}` : undefined,\n autoIncrement ? sql.raw(increment) : undefined,\n comment === undefined ? undefined : sql` comment ${sql.lit(comment)}`,\n after === undefined ? undefined : sql` after ${sql.id(after)}`,\n first ? sql.raw(' first') : undefined,\n ])\n }\n\n compileTables(): Sql {\n return sql`select table_name as name from information_schema.tables where table_schema = database() and table_type = 'BASE TABLE' order by table_name`\n }\n\n compileColumns(table: string): Sql {\n return sql`select column_name as name, data_type as type_name, column_type as type, is_nullable = 'YES' as nullable, column_default as ${sql.id('default')}, extra like '%auto_increment%' as auto_increment\n from information_schema.columns where table_schema = database() and table_name = ${table} order by ordinal_position`\n }\n\n normalizeColumns(rows: Array<Record<string, unknown>>): ColumnInfo[] {\n return rows.map((row) => ({\n name: String(row.name),\n type_name: String(row.type_name).toLowerCase(),\n type: String(row.type).toLowerCase(),\n nullable: Number(row.nullable) === 1,\n default: row.default === null || row.default === undefined ? null : String(row.default),\n auto_increment: Number(row.auto_increment) === 1,\n }))\n }\n\n compileIndexes(table: string): Sql {\n return sql`select index_name as ${sql.id('name')}, group_concat(column_name order by seq_in_index) as ${sql.id('columns')}, index_type as ${sql.id('type')}, not non_unique as ${sql.id('unique')}\n from information_schema.statistics where table_schema = schema() and table_name = ${table}\n group by index_name, index_type, non_unique`\n }\n\n normalizeIndexes(rows: Array<Record<string, unknown>>): IndexInfo[] {\n return rows.map((row) => {\n const name = String(row.name).toLowerCase()\n return { name, columns: list(row.columns), type: String(row.type).toLowerCase(), unique: Number(row.unique) === 1, primary: name === 'primary' }\n })\n }\n\n compileForeignKeys(table: string): Sql {\n return sql`select kc.constraint_name as ${sql.id('name')}, group_concat(kc.column_name order by kc.ordinal_position) as ${sql.id('columns')},\n kc.referenced_table_schema as ${sql.id('foreign_schema')}, kc.referenced_table_name as ${sql.id('foreign_table')},\n group_concat(kc.referenced_column_name order by kc.ordinal_position) as ${sql.id('foreign_columns')}, rc.update_rule as ${sql.id('on_update')}, rc.delete_rule as ${sql.id('on_delete')}\n from information_schema.key_column_usage kc join information_schema.referential_constraints rc\n on kc.constraint_schema = rc.constraint_schema and kc.constraint_name = rc.constraint_name\n where kc.table_schema = schema() and kc.table_name = ${table} and kc.referenced_table_name is not null\n group by kc.constraint_name, kc.referenced_table_schema, kc.referenced_table_name, rc.update_rule, rc.delete_rule`\n }\n\n normalizeForeignKeys(rows: Array<Record<string, unknown>>): ForeignKeyInfo[] {\n return rows.map((row) => ({\n name: String(row.name),\n columns: list(row.columns),\n foreign_schema: String(row.foreign_schema),\n foreign_table: String(row.foreign_table),\n foreign_columns: list(row.foreign_columns),\n on_update: String(row.on_update).toLowerCase(),\n on_delete: String(row.on_delete).toLowerCase(),\n }))\n }\n\n compileEnableForeignKeyConstraints(): Sql {\n return sql.raw('SET FOREIGN_KEY_CHECKS=1')\n }\n\n compileDisableForeignKeyConstraints(): Sql {\n return sql.raw('SET FOREIGN_KEY_CHECKS=0')\n }\n}\n","import { sql, type RawBuilder } from 'kysely'\nimport type { Connection } from '../Connection'\nimport { LogicError } from '../errors'\nimport { ForeignKeyDefinition, type ReferentialAction } from './ForeignKeyDefinition'\nimport type { ForeignKeyInfo, SqliteSchemaGrammar, TableRebuild } from './Grammar'\n\ntype Sql = RawBuilder<unknown>\n\n/** A row of pragma_table_xinfo. */\ninterface LiveColumn {\n name: string\n type: string\n notnull: number\n dflt_value: string | null\n pk: number\n hidden: number\n}\n\nconst QUOTES: Record<string, string> = { \"'\": \"'\", '\"': '\"', '`': '`', '[': ']' }\nconst lower = (value: string): string => value.toLowerCase()\nconst join = (parts: Sql[], separator = ', '): Sql => sql.join(parts, sql.raw(separator))\nconst columnList = (columns: readonly string[]): Sql => join(columns.map((column) => sql.id(column)))\nconst sameColumns = (a: readonly string[], b: readonly string[]): boolean =>\n a.length === b.length && a.every((column, i) => lower(column) === lower(b[i]!))\n\n/** The text with quoted strings, quoted identifiers and comments blanked out (same length), so it can be searched. */\nfunction mask(text: string): string {\n let out = ''\n for (let i = 0; i < text.length; i++) {\n const char = text[i]!\n const closer = QUOTES[char]\n let end = -1\n if (closer !== undefined) {\n end = i + 1\n while (end < text.length && !(text[end] === closer && (closer === ']' || text[end + 1] !== closer))) end += text[end] === closer ? 2 : 1\n } else if (char === '-' && text[i + 1] === '-') {\n end = text.indexOf('\\n', i)\n if (end === -1) end = text.length - 1\n } else if (char === '/' && text[i + 1] === '*') {\n end = text.indexOf('*/', i + 2)\n end = end === -1 ? text.length - 1 : end + 1\n }\n if (end === -1) {\n out += char\n continue\n }\n out += ' '.repeat(Math.min(end, text.length - 1) - i + 1)\n i = end\n }\n return out\n}\n\n/** The index just past the parenthesis that closes the one at `open` (in masked text). */\nfunction closingParen(masked: string, open: number): number {\n let depth = 0\n for (let i = open; i < masked.length; i++) {\n if (masked[i] === '(') depth++\n else if (masked[i] === ')' && --depth === 0) return i + 1\n }\n return masked.length\n}\n\n/** The definitions inside a `create table` statement (top-level, comma-separated) and what follows its closing paren. */\nexport function splitCreateTable(statement: string): { definitions: string[]; options: string } {\n const masked = mask(statement)\n const open = masked.indexOf('(')\n if (open === -1) return { definitions: [], options: '' }\n const close = closingParen(masked, open) - 1\n const definitions: string[] = []\n let depth = 0\n let start = open + 1\n for (let i = open + 1; i < close; i++) {\n if (masked[i] === '(') depth++\n else if (masked[i] === ')') depth--\n else if (masked[i] === ',' && depth === 0) {\n definitions.push(statement.slice(start, i).trim())\n start = i + 1\n }\n }\n definitions.push(statement.slice(start, close).trim())\n return { definitions: definitions.filter((definition) => definition !== ''), options: statement.slice(close + 1) }\n}\n\n/** The column a definition declares (unquoted), or undefined for a table constraint. */\nfunction definedColumn(definition: string): string | undefined {\n const closer = QUOTES[definition[0] ?? '']\n if (closer !== undefined) {\n const end = definition.indexOf(closer, 1)\n return definition.slice(1, end === -1 ? undefined : end).replaceAll(`${closer}${closer}`, closer)\n }\n if (/^(constraint|primary|unique|check|foreign)\\b/i.test(definition)) return undefined\n return /^[^\\s(]+/.exec(definition)?.[0]\n}\n\n/** What a column definition carries that pragma_table_info doesn't report: check constraints, a collation, autoincrement. */\nfunction columnClauses(definition: string): { checks: string[]; collation: string | undefined; autoincrement: boolean } {\n const masked = mask(definition)\n const checks: string[] = []\n for (const match of masked.matchAll(/\\bcheck\\s*\\(/gi)) {\n const open = match.index + match[0].length - 1\n checks.push(definition.slice(open, closingParen(masked, open)))\n }\n const collate = /\\bcollate\\s+/i.exec(masked)\n let collation: string | undefined\n if (collate) {\n const rest = definition.slice(collate.index + collate[0].length)\n const closer = QUOTES[rest[0] ?? '']\n collation = closer === undefined ? /^\\w+/.exec(rest)?.[0] : rest.slice(0, rest.indexOf(closer, 1) + 1)\n }\n return { checks, collation, autoincrement: /\\bautoincrement\\b/i.test(masked) }\n}\n\n/** A table-level check constraint (`check (…)` or `constraint name check (…)`), kept as written. */\nconst isTableCheck = (definition: string): boolean => /^(constraint\\s+\\S+\\s+)?check\\b/i.test(mask(definition))\n\n/**\n * A column as a rebuilt table declares it: the live type, not null and default, plus its parsed clauses. The default is\n * wrapped in parentheses: pragma_table_xinfo reports `default (datetime('now'))` as `datetime('now')`.\n */\nfunction renderColumn(column: LiveColumn, definition: string | undefined, autoincrement: boolean): Sql {\n const clauses = definition === undefined ? { checks: [], collation: undefined } : columnClauses(definition)\n const parts: Sql[] = [sql.id(column.name)]\n if (column.type) parts.push(sql.raw(` ${column.type}`))\n if (autoincrement) parts.push(sql.raw(' primary key autoincrement'))\n if (Number(column.notnull) === 1) parts.push(sql.raw(' not null'))\n if (column.dflt_value !== null && column.dflt_value !== undefined) parts.push(sql.raw(` default (${column.dflt_value})`))\n if (clauses.collation) parts.push(sql.raw(` collate ${clauses.collation}`))\n for (const check of clauses.checks) parts.push(sql.raw(` check ${check}`))\n return join(parts, '')\n}\n\n/** A foreign key read back from pragma_foreign_key_list, as a definition the grammar can write again. */\nfunction foreignKeyDefinition(key: ForeignKeyInfo): ForeignKeyDefinition {\n const definition = new ForeignKeyDefinition(key.columns, '').references(key.foreign_columns).on(key.foreign_table)\n if (key.on_delete !== 'no action') definition.onDelete(key.on_delete as ReferentialAction)\n if (key.on_update !== 'no action') definition.onUpdate(key.on_update as ReferentialAction)\n return definition\n}\n\n/** Whether SQLite enforces foreign keys on this connection (PRAGMA foreign_keys). */\nexport async function sqliteForeignKeysEnabled(db: Connection): Promise<boolean> {\n const rows = await db.select<{ foreign_keys: number }>('PRAGMA foreign_keys')\n return Number(rows[0]?.foreign_keys) === 1\n}\n\n/**\n * Throws when rows break a foreign key (SQLite's foreign_key_check), of one table or of the whole database; a hint, if\n * given, follows the message.\n */\nexport async function assertSqliteForeignKeys(db: Connection, table?: string, hint?: string): Promise<void> {\n const statement = table === undefined ? sql.raw('PRAGMA foreign_key_check') : sql`PRAGMA foreign_key_check(${sql.id(table)})`\n const rows = (await db.execute<{ table: string; rowid: number | null; parent: string }>(statement)).rows\n if (!rows.length) return\n const shown = rows.slice(0, 5).map((row) => `[${row.table}] row ${row.rowid ?? '?'} points at no row of [${row.parent}]`)\n const more = rows.length > 5 ? `; and ${rows.length - 5} more` : ''\n throw new LogicError(`Foreign key check failed: ${shown.join('; ')}${more}.${hint === undefined ? '' : ` ${hint}`}`)\n}\n\n/** The tables whose foreign keys point at `table` (itself included). */\nasync function referencingTables(db: Connection, table: string): Promise<string[]> {\n const rows = await db.select<{ name: string }>(\n `select m.name as name from sqlite_master m, pragma_foreign_key_list(m.name) f where m.type = 'table' and lower(f.\"table\") = lower(?) group by m.name order by m.name`,\n [table],\n )\n return rows.map((row) => row.name)\n}\n\n/**\n * Rebuilds a SQLite table with changed keys or columns (Laravel 11+'s compileAlter): a new table from the live\n * definition, the step's changed columns and its commands, the rows copied, the old table dropped, the new one\n * renamed, then its indexes, unique constraints, triggers and auto-increment sequence restored. Afterwards the table\n * and every table that references it are checked: rows that break a foreign key, or a key that no longer matches the\n * referenced columns, throw, and the rebuild is rolled back.\n *\n * Dropping a table while SQLite enforces foreign keys runs the ON DELETE actions of every table that references it, and\n * SQLite ignores `PRAGMA foreign_keys` inside a transaction. So outside a transaction the rebuild turns foreign keys off\n * around itself; inside one (foreign keys on) it refuses a table that another table, or itself, references.\n */\nexport async function rebuildSqliteTable(db: Connection, grammar: SqliteSchemaGrammar, step: TableRebuild): Promise<void> {\n const enabled = await sqliteForeignKeysEnabled(db)\n if (enabled && db.transactionLevel() === 0) {\n await db.statement('PRAGMA foreign_keys = OFF')\n try {\n await db.transaction(() => rebuild(db, grammar, step))\n } finally {\n await db.statement('PRAGMA foreign_keys = ON')\n }\n return\n }\n if (enabled) {\n const referencing = await referencingTables(db, step.table)\n if (referencing.length) {\n const names = referencing.map((name) => `[${name}]`).join(', ')\n throw new LogicError(\n `SQLite can't rebuild [${step.table}] inside a transaction while foreign keys are on: ${names} ${referencing.length === 1 ? 'references' : 'reference'} it, ` +\n 'and dropping the old table would run their ON DELETE actions. Run the change outside the transaction, or with foreign keys off ' +\n '(the migrator turns them off around a migration that runs in a transaction).',\n )\n }\n }\n await db.transaction(() => rebuild(db, grammar, step))\n}\n\nasync function rebuild(db: Connection, grammar: SqliteSchemaGrammar, step: TableRebuild): Promise<void> {\n const { table } = step\n const [master] = await db.select<{ sql: string }>(\"select sql from sqlite_master where type = 'table' and name = ?\", [table])\n if (!master) throw new LogicError(`Table [${table}] doesn't exist.`)\n const columns = await db.select<LiveColumn>('select name, type, \"notnull\", dflt_value, pk, hidden from pragma_table_xinfo(?) order by cid', [table])\n if (columns.some((column) => Number(column.hidden) !== 0)) {\n throw new LogicError(`SQLite can't rebuild [${table}]: it has generated or hidden columns.`)\n }\n const { definitions, options } = splitCreateTable(master.sql)\n const declared = new Map<string, string>()\n for (const definition of definitions) {\n const name = definedColumn(definition)\n if (name !== undefined) declared.set(lower(name), definition)\n }\n const keyColumns = columns.filter((column) => Number(column.pk) > 0).sort((a, b) => Number(a.pk) - Number(b.pk))\n let autoincrement = keyColumns.length === 1 && columnClauses(declared.get(lower(keyColumns[0]!.name)) ?? '').autoincrement\n ? keyColumns[0]!.name\n : undefined\n let primary = keyColumns.map((column) => column.name)\n const foreign = grammar.normalizeForeignKeys((await db.execute<Record<string, unknown>>(grammar.compileForeignKeys(table))).rows).map(foreignKeyDefinition)\n\n for (const change of step.changes) {\n if (!columns.some((column) => lower(column.name) === lower(change.name))) throw new LogicError(`[${table}] has no column [${change.name}] to change.`)\n if (change.attributes.autoIncrement) {\n autoincrement = change.name\n primary = [change.name]\n } else if (autoincrement !== undefined && lower(autoincrement) === lower(change.name)) {\n autoincrement = undefined\n }\n }\n const changes = new Map(step.changes.map((change) => [lower(change.name), change]))\n\n for (const command of step.commands) {\n if (command.name === 'primary') {\n if (autoincrement !== undefined) {\n throw new LogicError(`[${table}] already has an auto-increment primary key [${autoincrement}]: drop it first with dropPrimary().`)\n }\n primary = [...command.columns]\n } else if (command.name === 'dropPrimary') {\n primary = []\n autoincrement = undefined\n } else if (command.name === 'foreign') {\n foreign.push(command.foreign)\n } else if (command.name === 'dropForeign') {\n const columnsOf = command.columns ?? []\n const index = foreign.findIndex((key) => sameColumns(key.columns, columnsOf))\n if (index === -1) throw new LogicError(`[${table}] has no foreign key on [${columnsOf.join(', ')}].`)\n foreign.splice(index, 1)\n }\n }\n\n const parts = columns.map((column) => {\n const change = changes.get(lower(column.name))\n return change ? grammar.columnDefinition(change) : renderColumn(column, declared.get(lower(column.name)), column.name === autoincrement)\n })\n if (autoincrement === undefined && primary.length) parts.push(sql`primary key (${columnList(primary)})`)\n for (const key of foreign) parts.push(grammar.compileForeignKeyConstraint(key))\n for (const definition of definitions) if (isTableCheck(definition)) parts.push(sql.raw(definition))\n\n const indexes = await db.select<{ sql: string }>(\"select sql from sqlite_master where type = 'index' and tbl_name = ? and sql is not null\", [table])\n const uniques = await db.select<{ columns: string }>(\n \"select group_concat(col) as columns from (select il.name as name, ii.name as col from pragma_index_list(?) il, pragma_index_info(il.name) ii where il.origin = 'u' order by il.seq, ii.seqno) group by name\",\n [table],\n )\n const triggers = await db.select<{ sql: string }>(\"select sql from sqlite_master where type = 'trigger' and tbl_name = ?\", [table])\n const hasSequence = (await db.select(\"select name from sqlite_master where type = 'table' and name = 'sqlite_sequence'\")).length > 0\n const sequence = hasSequence ? (await db.select<{ seq: number }>('select seq from sqlite_sequence where name = ?', [table]))[0]?.seq : undefined\n\n const temp = `__temp__${table}`\n const names = columns.map((column) => sql.id(column.name))\n const statements: Sql[] = [\n sql`create table ${sql.id(temp)} (${join(parts)})${sql.raw(options)}`,\n sql`insert into ${sql.id(temp)} (${join(names)}) select ${join(names)} from ${sql.id(table)}`,\n sql`drop table ${sql.id(table)}`,\n sql`alter table ${sql.id(temp)} rename to ${sql.id(table)}`,\n ...indexes.map((index) => sql.raw(index.sql)),\n ...uniques.map(({ columns: list }) => {\n const unique = list.split(',')\n return sql`create unique index ${sql.id(`${table}_${unique.join('_')}_unique`.toLowerCase())} on ${sql.id(table)} (${columnList(unique)})`\n }),\n ...triggers.map((trigger) => sql.raw(trigger.sql)),\n ]\n for (const statement of statements) await db.execute(statement)\n if (autoincrement !== undefined && sequence !== undefined) await restoreSequence(db, table, Number(sequence))\n await assertSqliteForeignKeys(db, table)\n for (const child of await referencingTables(db, table)) if (lower(child) !== lower(table)) await assertSqliteForeignKeys(db, child)\n}\n\n/** Keeps the auto-increment high-water mark: ids of deleted rows are never reused, as before the rebuild. */\nasync function restoreSequence(db: Connection, table: string, sequence: number): Promise<void> {\n const [current] = await db.select<{ seq: number }>('select seq from sqlite_sequence where name = ?', [table])\n if (!current) await db.statement('insert into sqlite_sequence (name, seq) values (?, ?)', [table, sequence])\n else if (Number(current.seq) < sequence) await db.statement('update sqlite_sequence set seq = ? where name = ?', [sequence, table])\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport type { DatabaseManager as DatabaseManagerContract, DriverName, Row } from '@orieljs/contracts'\nimport type { ConnectionConfig } from './Connectors/dialect'\nimport { Connection, type LoggedQuery } from './Connection'\nimport { DatabaseConfigError } from './errors'\nimport type { Builder } from './Query/Builder'\nimport { Expression } from './Query/Expression'\nimport { SchemaBuilder } from './Schema/Builder'\n\n/** `config('database')`, in Laravel's config/database.php shape. */\nexport interface DatabaseConfig {\n default: string\n connections: Record<string, ConnectionConfig>\n /** Laravel 11: { table: 'migrations' }. A plain string (older Laravel) is accepted too. */\n migrations?: { table?: string } | string\n}\n\n/**\n * The DatabaseManager contract: named connections from config('database'), created on first use and cached.\n * Everything a connection does is also available here and runs on the default connection, as with Laravel's DB facade.\n * Named DatabaseManagerImpl so it never shadows the DatabaseManager token when both are re-exported.\n */\nexport class DatabaseManagerImpl implements DatabaseManagerContract {\n private readonly connections = new Map<string, Connection>()\n private defaultName: string | undefined\n /** usingConnection()'s name, for its own async context only: requests running beside it keep theirs. */\n private readonly using = new AsyncLocalStorage<string>()\n\n /** Pass the config, or a function that reads it (the provider reads config('database') lazily). */\n constructor(private readonly config: DatabaseConfig | (() => DatabaseConfig)) {}\n\n private settings(): DatabaseConfig {\n return typeof this.config === 'function' ? this.config() : this.config\n }\n\n /** A connection by name (default: config('database.default')). */\n connection(name?: string): Connection {\n const key = name ?? this.getDefaultConnection()\n let connection = this.connections.get(key)\n if (!connection) {\n const config = this.settings().connections[key]\n if (!config) throw new DatabaseConfigError(`Database connection [${key}] not configured.`)\n connection = new Connection(key, config)\n this.connections.set(key, connection)\n }\n return connection\n }\n\n getDefaultConnection(): string {\n return this.using.getStore() ?? this.defaultName ?? this.settings().default\n }\n\n /** Overrides config('database.default'); undefined clears the override. */\n setDefaultConnection(name: string | undefined): void {\n this.defaultName = name\n }\n\n /**\n * Runs `callback` with `name` as the default connection (Laravel's usingConnection()), for the callback's own async\n * context only: other requests running meanwhile keep their default. Without a name, just runs it.\n */\n async usingConnection<T>(name: string | undefined, callback: () => Promise<T>): Promise<T> {\n if (!name) return callback()\n return this.using.run(name, callback)\n }\n\n /** The connections opened so far. */\n getConnections(): Record<string, Connection> {\n return Object.fromEntries(this.connections)\n }\n\n /** The migrations table name (config('database.migrations.table'), default 'migrations'). */\n migrationsTable(): string {\n const migrations = this.settings().migrations\n return (typeof migrations === 'string' ? migrations : migrations?.table) ?? 'migrations'\n }\n\n /** Closes a connection's pool and forgets it; the next connection(name) opens a new one. */\n async disconnect(name?: string): Promise<void> {\n const key = name ?? this.getDefaultConnection()\n const connection = this.connections.get(key)\n this.connections.delete(key)\n await connection?.disconnect()\n }\n\n /** Laravel's purge(): the same as disconnect() here. */\n purge(name?: string): Promise<void> {\n return this.disconnect(name)\n }\n\n /** Closes every open connection (app shutdown, the end of a test). */\n async disconnectAll(): Promise<void> {\n const open = [...this.connections.values()]\n this.connections.clear()\n await Promise.all(open.map((connection) => connection.disconnect()))\n }\n\n /** The default connection's schema builder; Schema.connection(name) switches connections through this manager. */\n getSchemaBuilder(): SchemaBuilder {\n return new SchemaBuilder(this.connection(), (name) => this.connection(name))\n }\n\n /** A raw SQL fragment: DB.raw('count(*) as total'). */\n raw(value: string, bindings: readonly unknown[] = []): Expression {\n return new Expression(value, bindings)\n }\n\n // ---------------------------------------------------------------- the default connection\n\n getName(): string {\n return this.connection().getName()\n }\n\n getDriverName(): DriverName {\n return this.connection().getDriverName()\n }\n\n kysely(): ReturnType<Connection['kysely']> {\n return this.connection().kysely()\n }\n\n table<T = Row>(table: string | Expression): Builder<T> {\n return this.connection().table<T>(table)\n }\n\n query<T = Row>(): Builder<T> {\n return this.connection().query<T>()\n }\n\n select<T = Row>(query: string, bindings?: readonly unknown[]): Promise<T[]> {\n return this.connection().select<T>(query, bindings)\n }\n\n /** The first row of a raw select, or undefined. */\n async selectOne<T = Row>(query: string, bindings?: readonly unknown[]): Promise<T | undefined> {\n return (await this.connection().select<T>(query, bindings))[0]\n }\n\n /** Raw insert. Returns true, like Laravel's DB::insert(). */\n async insert(query: string, bindings?: readonly unknown[]): Promise<boolean> {\n await this.connection().statement(query, bindings)\n return true\n }\n\n /** Raw update; returns the number of affected rows. */\n update(query: string, bindings?: readonly unknown[]): Promise<number> {\n return this.connection().affectingStatement(query, bindings)\n }\n\n /** Raw delete; returns the number of affected rows. */\n delete(query: string, bindings?: readonly unknown[]): Promise<number> {\n return this.connection().affectingStatement(query, bindings)\n }\n\n statement(query: string, bindings?: readonly unknown[]): Promise<void> {\n return this.connection().statement(query, bindings)\n }\n\n affectingStatement(query: string, bindings?: readonly unknown[]): Promise<number> {\n return this.connection().affectingStatement(query, bindings)\n }\n\n transaction<R>(fn: (connection: Connection) => Promise<R>): Promise<R> {\n return this.connection().transaction(fn)\n }\n\n beginTransaction(): Promise<void> {\n return this.connection().beginTransaction()\n }\n\n /**\n * Laravel's DB::afterCommit(): waits for the transaction(fn) open in this async context, on the default connection\n * first, then on any other opened one; runs at once outside one. It opens no connection: one with a transaction is\n * open already.\n */\n async afterCommit(callback: () => unknown, onRollBack?: () => unknown): Promise<void> {\n const preferred = this.connections.get(this.getDefaultConnection())\n const opened = [...(preferred === undefined ? [] : [preferred]), ...this.connections.values()]\n const open = opened.find((connection) => connection.inTransactionContext())\n if (open === undefined) await callback()\n else await open.afterCommit(callback, onRollBack)\n }\n\n commit(): Promise<void> {\n return this.connection().commit()\n }\n\n rollBack(): Promise<void> {\n return this.connection().rollBack()\n }\n\n transactionLevel(): number {\n return this.connection().transactionLevel()\n }\n\n enableQueryLog(): void {\n this.connection().enableQueryLog()\n }\n\n disableQueryLog(): void {\n this.connection().disableQueryLog()\n }\n\n getQueryLog(): LoggedQuery[] {\n return this.connection().getQueryLog()\n }\n\n flushQueryLog(): void {\n this.connection().flushQueryLog()\n }\n}\n","import { DatabaseManager, token, type Token } from '@orieljs/contracts'\nimport { facade } from '@orieljs/support'\nimport type { DatabaseManagerImpl } from './DatabaseManager'\nimport { raw } from './Query/Expression'\nimport type { SchemaBuilder } from './Schema/Builder'\n\n/**\n * The DB facade: DB.table('users').get(), DB.transaction(fn), DB.connection('pgsql'), DB.kysely().\n * DB.raw() works without an application (it only builds an Expression).\n */\nexport const DB = facade(DatabaseManager as unknown as Token<DatabaseManagerImpl>, { raw } as { raw: typeof raw })\n\n/** The Schema facade's binding: the default connection's SchemaBuilder (DatabaseServiceProvider binds it). */\nexport const SchemaBuilderToken = token<SchemaBuilder>('Database.SchemaBuilder')\n\n/** The Schema facade: Schema.create('posts', (t) => { … }), Schema.table(…), Schema.dropIfExists(…). */\nexport const Schema = facade(SchemaBuilderToken)\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport { DatabaseManager, Hasher, type ModelInstance, type Row } from '@orieljs/contracts'\nimport { Collection, type LazyCollection } from '@orieljs/collections'\nimport { currentContainer, inject } from '@orieljs/container'\nimport { serializeDate, Str } from '@orieljs/support'\nimport { Connection } from '../Connection'\nimport { DatabaseConfigError, LogicError, MassAssignmentError, RelationNotFoundError, RelationNotLoadedError } from '../errors'\nimport type { CursorPaginator, Cursor } from '../Pagination/CursorPaginator'\nimport type { LengthAwarePaginator } from '../Pagination/LengthAwarePaginator'\nimport type { Paginator } from '../Pagination/Paginator'\nimport type { DateWhereArgs, Direction, Truthy } from '../Query/Builder'\nimport type { Expression } from '../Query/Expression'\nimport { Builder, type EagerLoadSpec, type RelationConstraint } from './Builder'\nimport { castGet, castSet, isEquivalent, isHashedCast, isJsonCast, type CastDefinition } from './casts'\nimport { EloquentCollection } from './Collection'\nimport { Factory, type Many, type State } from './Factories/Factory'\nimport {\n eventDispatcher, MODEL_EVENTS, modelEventName, modelEventsMuted, requireEventDispatcher, withoutModelEvents,\n type ModelEvent, type ModelListener,\n} from './events'\nimport { BelongsTo } from './Relations/BelongsTo'\nimport { BelongsToMany } from './Relations/BelongsToMany'\nimport { HasMany } from './Relations/HasMany'\nimport { HasManyThrough } from './Relations/HasManyThrough'\nimport { HasOne } from './Relations/HasOne'\nimport { MorphMany } from './Relations/MorphMany'\nimport { MorphOne } from './Relations/MorphOne'\nimport { MorphTo } from './Relations/MorphTo'\nimport { getMorphAlias, rememberModelClass, resolveMorphClass, setModelBaseClass } from './Relations/morphMap'\nimport { Relation } from './Relations/Relation'\nimport type { GlobalScope, Scope, ScopeCallback } from './Scope'\nimport { SoftDeletingScope } from './SoftDeletingScope'\nimport type { AggregateSpecs, Aggregates, Column, EagerLoads, LoadedTree, LooseSpec, ModelBuilder, WithLoaded, ModelKey, RelationNames, RelationPath, RelationPathArg, RelationValue, Scopes, WhereArgs, WriteAttributes } from './types'\n\ntype AnyFunction = (...args: unknown[]) => unknown\n\n/**\n * Every model instance is a Proxy. Real members (fields, methods, getters, config such as `fillable`) are read and\n * written normally; any other property is an attribute: `post.title` → getAttribute('title') (accessors, casts),\n * `post.title = 'x'` → setAttribute('title', 'x') (mutators, casts).\n */\nconst handler: ProxyHandler<Model> = {\n get(target, key, receiver) {\n if (typeof key === 'symbol' || key in target) {\n const value: unknown = Reflect.get(target, key, receiver)\n if (relationGuard.enabled && typeof key === 'string' && typeof value === 'function' && !(key in Model.prototype) && !Object.hasOwn(target, key)) {\n return guardedMethod(target.constructor as typeof Model, key, value as AnyFunction)\n }\n return value\n }\n return (receiver as Model).getAttribute(key)\n },\n set(target, key, value, receiver) {\n if (typeof key === 'symbol' || key in target) return Reflect.set(target, key, value, receiver)\n ;(receiver as Model).setAttribute(key, value)\n return true\n },\n}\n\n/**\n * The relation guard: `post.author` is the relation method, so `post.author.name` is the function's name ('author')\n * and `post.author.email` is undefined, with no error. While the guard is on (outside production), a model's own\n * methods are handed out wrapped, and reading `name`, `length` or a property a function doesn't have from one warns\n * once per class, method and property. Calling, binding and comparing the methods are untouched.\n */\nconst relationGuard = { enabled: true, warned: new Set<string>() }\nconst guardedMethods = new WeakMap<AnyFunction, Map<typeof Model, AnyFunction>>()\n\nfunction guardedMethod(cls: typeof Model, key: string, method: AnyFunction): AnyFunction {\n let byClass = guardedMethods.get(method)\n if (!byClass) guardedMethods.set(method, (byClass = new Map()))\n let guarded = byClass.get(cls)\n if (!guarded) {\n guarded = new Proxy(method, {\n get(target, property, receiver) {\n if (typeof property === 'string' && (property === 'name' || property === 'length' || !(property in target))) {\n warnRelationPropertyAccess(cls.name, key, property)\n }\n // bind() reads name and length, and a proxied function's toString() prints [native code]: use the method itself.\n if (property === 'bind') return (thisArg: unknown, ...args: unknown[]) => Function.prototype.bind.call(target, thisArg, ...args)\n if (property === 'toString') return () => Function.prototype.toString.call(target)\n return Reflect.get(target, property, receiver)\n },\n })\n byClass.set(cls, guarded)\n }\n return guarded\n}\n\nfunction warnRelationPropertyAccess(model: string, method: string, property: string): void {\n const id = `${model}.${method}.${property}`\n if (relationGuard.warned.has(id)) return\n relationGuard.warned.add(id)\n console.warn(\n `[${model}] ${method} is a method, so ${method}.${property} reads the function, not an attribute of a related model. ` +\n `Read a loaded relation with getRelation('${method}') (after with('${method}') or load('${method}')), or query it with ` +\n `await ${method}().first().`,\n )\n}\n\nconst bootedModels = new Set<typeof Model>()\nconst prototypes = new Map<typeof Model, Model>()\nconst unguardedGlobally = { value: false }\n/** Model classes whose default withCount is being added (breaks recursion through their relations). */\nconst addingDefaultCounts = new Set<typeof Model>()\n/** The only keys a guarded-list model accepts from fill(): a plain column name, no spaces, dots or quoting tricks. */\nconst PLAIN_COLUMN = /^[A-Za-z_][A-Za-z0-9_]*$/\nconst unguardedScope = new AsyncLocalStorage<boolean>()\nconst globalScopes = new Map<typeof Model, Map<string, GlobalScope>>()\nlet anonymousScopes = 0\n\ntype Instance<C extends typeof Model> = InstanceType<C>\ntype ScopeClass = abstract new (...args: never[]) => unknown\n\n/** Post.published() for every static scopePublished() (installed when the class boots). */\nfunction installScopeProxies(cls: typeof Model): void {\n for (let current: unknown = cls; current && current !== Model; current = Object.getPrototypeOf(current)) {\n for (const key of Object.getOwnPropertyNames(current)) {\n if (!key.startsWith('scope') || key.length <= 5) continue\n if (typeof Reflect.get(current as object, key) !== 'function') continue\n const name = Str.lcfirst(key.slice(5))\n if (name in cls) continue\n Object.defineProperty(cls, name, {\n configurable: true,\n writable: true,\n value(this: typeof Model, ...args: unknown[]) {\n const query = this.query() as unknown as Record<string, (...a: unknown[]) => unknown>\n return query[name]!(...args)\n },\n })\n }\n }\n}\n\n/** A method defined on the model's class (never an attribute), e.g. getFullNameAttribute. */\nfunction methodOf(model: Model, name: string): AnyFunction | undefined {\n const value: unknown = Reflect.get(Object.getPrototypeOf(model) as object, name)\n return typeof value === 'function' ? (value as AnyFunction) : undefined\n}\n\n/** The application's Hasher, for the hashed cast. */\nfunction hasher(): Hasher {\n const container = currentContainer()\n if (!container?.bound(Hasher)) throw new LogicError('The hashed cast needs a Hasher: register HashingServiceProvider (or bind the Hasher contract).')\n return container.make(Hasher)\n}\n\n/** The models whose toArray() is running: a model met again inside it (a chaperone() cycle) gives its attributes only. */\nconst serializing = new WeakSet<Model>()\n\nexport { serializeDate }\n\n/**\n * Eloquent's Model: an Active Record over one table.\n *\n * Config lives in instance fields, as in Laravel: `protected fillable = ['title']`, `protected casts = {…}`,\n * `protected hidden = ['password']`, `protected table = 'posts'`. Attribute columns are never declared as class\n * fields (they would shadow the Proxy); their types come from `oriel model:types`, or from `declare title: string`.\n * `new Post()` takes no arguments: use Post.make(attrs), Post.create(attrs) or new Post().fill(attrs).\n */\nexport class Model implements ModelInstance {\n static CREATED_AT: string | null = 'created_at'\n static UPDATED_AT: string | null = 'updated_at'\n static DELETED_AT = 'deleted_at'\n\n // ---------------------------------------------------------------- config (override in subclasses)\n\n /** The table (default: the snake_case plural of the class name: BlogPost → blog_posts). */\n protected table: string | undefined = undefined\n protected primaryKey = 'id'\n protected keyType: 'int' | 'string' = 'int'\n incrementing = true\n /** Attributes that fill()/create() may set. */\n protected fillable: string[] = []\n /** Attributes fill() never sets. ['*'] (the default) guards everything that isn't fillable. */\n protected guarded: string[] = ['*']\n protected casts: Readonly<Record<string, CastDefinition>> = {}\n /** Left out of toArray()/toJSON(). */\n protected hidden: string[] = []\n /** When non-empty, only these are in toArray()/toJSON(). */\n protected visible: string[] = []\n /** Accessor-only attributes added to toArray()/toJSON(). */\n protected appends: string[] = []\n timestamps = true\n /** Turns on soft deletes (Laravel's `use SoftDeletes`): deleted_at instead of a real delete. */\n protected softDeletes = false\n /** The connection name (default: config('database.default')). */\n protected connection: string | undefined = undefined\n protected perPage = 15\n /** Relations every query of this model eager loads (Laravel's $with). */\n protected with: string[] = []\n /** Relation counts every query of this model adds (Laravel's $withCount). */\n protected withCount: string[] = []\n\n // ---------------------------------------------------------------- state\n\n exists = false\n wasRecentlyCreated = false\n protected forceDeleting = false\n protected attributes: Row = {}\n protected original: Row = {}\n protected changes: Row = {}\n protected relations: Record<string, unknown> = {}\n /** Decoded json/array/object/collection values, so in-place changes are seen by save(). */\n protected castCache = new Map<string, { raw: unknown; value: unknown }>()\n /** Attributes with the hashed cast that were assigned a value since the last save; save() hashes them. */\n protected pendingHashes = new Set<string>()\n\n constructor() {\n ;(this.constructor as typeof Model).bootIfNotBooted()\n return new Proxy(this, handler)\n }\n\n // ---------------------------------------------------------------- booting\n\n /** Runs booting()/booted() once per class, the first time the class is instantiated. */\n static bootIfNotBooted(): void {\n if (bootedModels.has(this)) return\n bootedModels.add(this)\n rememberModelClass(this)\n this.booting()\n this.boot()\n this.booted()\n }\n\n /**\n * Framework hook: installs the static scope proxies (Post.published()) and, with `softDeletes = true`, the soft\n * delete scope. Overrides must call super.boot().\n */\n static boot(): void {\n installScopeProxies(this)\n if (this.prototypeInstance().usesSoftDeletes()) this.addGlobalScope(new SoftDeletingScope())\n }\n\n /** Runs before boot(). */\n static booting(): void {}\n\n /** Register global scopes and model event listeners here: static booted() { this.addGlobalScope(…) }. */\n static booted(): void {}\n\n /**\n * Forgets which classes are booted, and their global scopes (Laravel's clearBootedModels()), so the next use boots\n * them again: booted() re-registers its scopes and event listeners against the current application. Every new\n * application does this (DatabaseServiceProvider.register()).\n */\n static clearBootedModels(): void {\n bootedModels.clear()\n prototypes.clear()\n globalScopes.clear()\n }\n\n /** One cached instance per class, used by static methods to read config (table, key, casts, …). */\n static prototypeInstance<M extends Model>(this: new () => M): M {\n const cls = this as unknown as typeof Model\n let instance = prototypes.get(cls)\n if (!instance) {\n instance = new cls()\n prototypes.set(cls, instance)\n }\n return instance as M\n }\n\n /** A new, unsaved model filled with attributes (mass assignment rules apply). */\n static make<M extends Model, const T extends object = Row>(this: new () => M, attributes?: T & WriteAttributes<M, T>): M {\n return new this().fill((attributes ?? {}) as Row)\n }\n\n // ---------------------------------------------------------------- global scopes\n\n /**\n * Adds a global scope to every query of this class: addGlobalScope('published', q => …),\n * addGlobalScope(new ActiveScope()) (named after its class) or addGlobalScope(q => …).\n */\n static addGlobalScope(scope: Scope | ScopeCallback): string\n static addGlobalScope(name: string, scope: GlobalScope): string\n static addGlobalScope(nameOrScope: string | GlobalScope, implementation?: GlobalScope): string {\n let name: string\n let scope: GlobalScope\n if (typeof nameOrScope === 'string') {\n name = nameOrScope\n scope = implementation!\n } else {\n scope = nameOrScope\n name = typeof scope === 'function' ? `closure#${++anonymousScopes}` : scope.constructor.name\n }\n let scopes = globalScopes.get(this)\n if (!scopes) globalScopes.set(this, (scopes = new Map()))\n scopes.set(name, scope)\n return name\n }\n\n static hasGlobalScope(scope: string | ScopeClass): boolean {\n return globalScopes.get(this)?.has(typeof scope === 'string' ? scope : scope.name) ?? false\n }\n\n static getGlobalScopes(): Map<string, GlobalScope> {\n return new Map(globalScopes.get(this))\n }\n\n // ---------------------------------------------------------------- model events and observers\n\n /** Registers a listener for one of this model's events ('eloquent.<event>: <Class>'). Needs an EventDispatcher. */\n static registerModelEvent<C extends typeof Model>(this: C, event: ModelEvent, callback: ModelListener<InstanceType<C>>): void {\n requireEventDispatcher(this.name).listen(modelEventName(event, this.name), (model: unknown) => callback(model as InstanceType<C>))\n }\n\n static retrieved<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('retrieved', callback)\n }\n\n static creating<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('creating', callback)\n }\n\n static created<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('created', callback)\n }\n\n static updating<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('updating', callback)\n }\n\n static updated<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('updated', callback)\n }\n\n static saving<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('saving', callback)\n }\n\n static saved<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('saved', callback)\n }\n\n static deleting<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('deleting', callback)\n }\n\n static deleted<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('deleted', callback)\n }\n\n static restoring<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('restoring', callback)\n }\n\n static restored<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('restored', callback)\n }\n\n static forceDeleting<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('forceDeleting', callback)\n }\n\n static forceDeleted<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void {\n this.registerModelEvent('forceDeleted', callback)\n }\n\n /**\n * Registers observers: every method named after a model event (created, updating, …) becomes a listener.\n * Observer classes are resolved from the container.\n */\n static observe(...observers: Array<object | (new () => object)>): void {\n const dispatcher = requireEventDispatcher(this.name)\n for (const entry of observers) {\n const observer = (typeof entry === 'function' ? (currentContainer()?.make(entry as new () => object) ?? new (entry as new () => object)()) : entry) as Record<string, unknown>\n for (const event of MODEL_EVENTS) {\n const method = observer[event]\n if (typeof method !== 'function') continue\n dispatcher.listen(modelEventName(event, this.name), (model: unknown) => (method as (m: unknown) => unknown).call(observer, model))\n }\n }\n }\n\n /**\n * Turns the relation guard on or off: while it is on, reading a property of a relation method as if it were the\n * related model (`post.author.name`) warns once with how to read the relation. DatabaseServiceProvider turns it on\n * outside production. Turning it on again forgets which warnings were given.\n */\n static warnOnRelationPropertyAccess(enabled = true): void {\n relationGuard.enabled = enabled\n if (enabled) relationGuard.warned.clear()\n }\n\n static warnsOnRelationPropertyAccess(): boolean {\n return relationGuard.enabled\n }\n\n /** Runs fn with model events off, for this async context only. */\n static withoutEvents<R>(fn: () => R): R {\n return withoutModelEvents(fn)\n }\n\n // ---------------------------------------------------------------- static query API (Post.where(…), Post.find(…))\n\n /** A new query of this model, with its global scopes. */\n static query<C extends typeof Model>(this: C): ModelBuilder<C> {\n return (this as typeof Model).prototypeInstance().newQuery() as unknown as ModelBuilder<C>\n }\n\n static where<C extends typeof Model>(this: C, ...args: WhereArgs<Instance<C>, ModelBuilder<C>>): ModelBuilder<C> {\n const query = this.query()\n return Reflect.apply(query.where, query, args) as ModelBuilder<C>\n }\n\n /** Post.when(request.query('q'), (query, q) => query.whereLike('title', `%${q}%`)): a new query, then when(). */\n static when<C extends typeof Model, V>(this: C, value: (query: ModelBuilder<C>) => V, callback: (query: ModelBuilder<C>, value: Truthy<V>) => unknown, otherwise?: (query: ModelBuilder<C>, value: V) => unknown): ModelBuilder<C>\n static when<C extends typeof Model, V>(this: C, value: V, callback: (query: ModelBuilder<C>, value: Truthy<V>) => unknown, otherwise?: (query: ModelBuilder<C>, value: V) => unknown): ModelBuilder<C>\n static when<C extends typeof Model>(this: C, ...args: unknown[]): ModelBuilder<C> {\n const query = this.query()\n return Reflect.apply(query.when, query, args) as ModelBuilder<C>\n }\n\n /** A new query, then unless(): the callback runs when the value is falsy. */\n static unless<C extends typeof Model, V>(this: C, value: (query: ModelBuilder<C>) => V, callback: (query: ModelBuilder<C>, value: V) => unknown, otherwise?: (query: ModelBuilder<C>, value: Truthy<V>) => unknown): ModelBuilder<C>\n static unless<C extends typeof Model, V>(this: C, value: V, callback: (query: ModelBuilder<C>, value: V) => unknown, otherwise?: (query: ModelBuilder<C>, value: Truthy<V>) => unknown): ModelBuilder<C>\n static unless<C extends typeof Model>(this: C, ...args: unknown[]): ModelBuilder<C> {\n const query = this.query()\n return Reflect.apply(query.unless, query, args) as ModelBuilder<C>\n }\n\n static whereKey<C extends typeof Model>(this: C, id: unknown): ModelBuilder<C> {\n return this.query().whereKey(id)\n }\n\n static whereIn<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, values: readonly unknown[]): ModelBuilder<C> {\n return this.query().whereIn(column, values)\n }\n\n static whereNotIn<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, values: readonly unknown[]): ModelBuilder<C> {\n return this.query().whereNotIn(column, values)\n }\n\n static whereNull<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression): ModelBuilder<C> {\n return this.query().whereNull(column)\n }\n\n static whereNotNull<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression): ModelBuilder<C> {\n return this.query().whereNotNull(column)\n }\n\n static whereBetween<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, values: readonly [unknown, unknown]): ModelBuilder<C> {\n return this.query().whereBetween(column, values)\n }\n\n /** Post.whereLike('title', `%${term}%`): case-insensitive unless caseSensitive (see the query builder's whereLike()). */\n static whereLike<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, value: string, caseSensitive = false): ModelBuilder<C> {\n return this.query().whereLike(column, value, caseSensitive)\n }\n\n static whereNotLike<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, value: string, caseSensitive = false): ModelBuilder<C> {\n return this.query().whereNotLike(column, value, caseSensitive)\n }\n\n /** Post.whereDate('published_at', '2026-01-05'), Post.whereDate('published_at', '<', new Date()). */\n static whereDate<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, ...args: DateWhereArgs): ModelBuilder<C> {\n return this.query().whereDate(column, ...args)\n }\n\n static whereTime<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, ...args: DateWhereArgs): ModelBuilder<C> {\n return this.query().whereTime(column, ...args)\n }\n\n static whereDay<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, ...args: DateWhereArgs): ModelBuilder<C> {\n return this.query().whereDay(column, ...args)\n }\n\n static whereMonth<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, ...args: DateWhereArgs): ModelBuilder<C> {\n return this.query().whereMonth(column, ...args)\n }\n\n static whereYear<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, ...args: DateWhereArgs): ModelBuilder<C> {\n return this.query().whereYear(column, ...args)\n }\n\n static whereColumn<C extends typeof Model>(this: C, first: Column<Instance<C>>, operatorOrSecond: string, second?: Column<Instance<C>>): ModelBuilder<C> {\n return this.query().whereColumn(first, operatorOrSecond, second)\n }\n\n static whereRaw<C extends typeof Model>(this: C, sql: string, bindings: readonly unknown[] = []): ModelBuilder<C> {\n return this.query().whereRaw(sql, bindings)\n }\n\n static select<C extends typeof Model>(this: C, ...columns: Array<Column<Instance<C>> | Expression>): ModelBuilder<C> {\n return this.query().select(...columns)\n }\n\n static orderBy<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, direction: Direction = 'asc'): ModelBuilder<C> {\n return this.query().orderBy(column, direction)\n }\n\n static latest<C extends typeof Model>(this: C, column?: Column<Instance<C>>): ModelBuilder<C> {\n return this.query().latest(column)\n }\n\n static oldest<C extends typeof Model>(this: C, column?: Column<Instance<C>>): ModelBuilder<C> {\n return this.query().oldest(column)\n }\n\n static inRandomOrder<C extends typeof Model>(this: C): ModelBuilder<C> {\n return this.query().inRandomOrder()\n }\n\n static limit<C extends typeof Model>(this: C, count: number): ModelBuilder<C> {\n return this.query().limit(count)\n }\n\n static take<C extends typeof Model>(this: C, count: number): ModelBuilder<C> {\n return this.query().take(count)\n }\n\n static withoutGlobalScope<C extends typeof Model>(this: C, scope: string | ScopeClass): ModelBuilder<C> {\n return this.query().withoutGlobalScope(scope)\n }\n\n static withoutGlobalScopes<C extends typeof Model>(this: C, scopes?: Array<string | ScopeClass>): ModelBuilder<C> {\n return this.query().withoutGlobalScopes(scopes)\n }\n\n /** Eager loads relations: Post.with('author', 'comments.user').get(). */\n static with<C extends typeof Model, const S extends readonly LooseSpec[]>(\n this: C,\n ...relations: EagerLoads<Instance<C>, S>\n ): ModelBuilder<C, WithLoaded<Instance<C>, LoadedTree<S>>> & ModelBuilder<C> {\n return this.query().with(...(relations as readonly LooseSpec[] as never[])) as never\n }\n\n static withCount<C extends typeof Model, const S extends readonly LooseSpec[]>(this: C, ...relations: Aggregates<Instance<C>, S>): ModelBuilder<C> {\n return this.query().withCount(...relations)\n }\n\n /** Post.withSum('orders', 'price'): adds orders_sum_price. */\n static withSum<C extends typeof Model, const S extends LooseSpec | readonly LooseSpec[]>(this: C, relations: AggregateSpecs<Instance<C>, S>, column: string | Expression): ModelBuilder<C> {\n return this.query().withSum(relations, column)\n }\n\n static withAvg<C extends typeof Model, const S extends LooseSpec | readonly LooseSpec[]>(this: C, relations: AggregateSpecs<Instance<C>, S>, column: string | Expression): ModelBuilder<C> {\n return this.query().withAvg(relations, column)\n }\n\n static withMin<C extends typeof Model, const S extends LooseSpec | readonly LooseSpec[]>(this: C, relations: AggregateSpecs<Instance<C>, S>, column: string | Expression): ModelBuilder<C> {\n return this.query().withMin(relations, column)\n }\n\n static withMax<C extends typeof Model, const S extends LooseSpec | readonly LooseSpec[]>(this: C, relations: AggregateSpecs<Instance<C>, S>, column: string | Expression): ModelBuilder<C> {\n return this.query().withMax(relations, column)\n }\n\n static withExists<C extends typeof Model, const S extends readonly LooseSpec[]>(this: C, ...relations: Aggregates<Instance<C>, S>): ModelBuilder<C> {\n return this.query().withExists(...relations)\n }\n\n static withAggregate<C extends typeof Model, const S extends LooseSpec | readonly LooseSpec[]>(this: C, relations: AggregateSpecs<Instance<C>, S>, column: string | Expression, fn?: string): ModelBuilder<C> {\n return this.query().withAggregate(relations, column, fn)\n }\n\n static has<C extends typeof Model, const N extends RelationPath<Instance<C>> | (string & {})>(this: C, relation: RelationPathArg<Instance<C>, N>, operator = '>=', count = 1): ModelBuilder<C> {\n return this.query().has(relation, operator, count)\n }\n\n static whereHas<C extends typeof Model, const N extends RelationPath<Instance<C>> | (string & {})>(this: C, relation: RelationPathArg<Instance<C>, N>, callback?: RelationConstraint, operator = '>=', count = 1): ModelBuilder<C> {\n return this.query().whereHas(relation, callback, operator, count)\n }\n\n static doesntHave<C extends typeof Model, const N extends RelationPath<Instance<C>> | (string & {})>(this: C, relation: RelationPathArg<Instance<C>, N>): ModelBuilder<C> {\n return this.query().doesntHave(relation)\n }\n\n static whereDoesntHave<C extends typeof Model, const N extends RelationPath<Instance<C>> | (string & {})>(this: C, relation: RelationPathArg<Instance<C>, N>, callback?: RelationConstraint): ModelBuilder<C> {\n return this.query().whereDoesntHave(relation, callback)\n }\n\n /** Soft deletes: include trashed rows. */\n static withTrashed<C extends typeof Model>(this: C): ModelBuilder<C> {\n return this.query().withTrashed()\n }\n\n /** Soft deletes: only trashed rows. */\n static onlyTrashed<C extends typeof Model>(this: C): ModelBuilder<C> {\n return this.query().onlyTrashed()\n }\n\n static withoutTrashed<C extends typeof Model>(this: C): ModelBuilder<C> {\n return this.query().withoutTrashed()\n }\n\n static all<C extends typeof Model>(this: C): Promise<EloquentCollection<Instance<C>>> {\n return this.query().get()\n }\n\n static find<C extends typeof Model>(this: C, ids: readonly unknown[]): Promise<EloquentCollection<Instance<C>>>\n static find<C extends typeof Model>(this: C, id: ModelKey | null | undefined): Promise<Instance<C> | undefined>\n /** A key typed `unknown` may be an array at run time (`?id[]=1`): a model or a collection. */\n static find<C extends typeof Model>(this: C, id: unknown): Promise<Instance<C> | EloquentCollection<Instance<C>> | undefined>\n static find<C extends typeof Model>(this: C, id: unknown): Promise<Instance<C> | undefined | EloquentCollection<Instance<C>>> {\n return this.query().find(id)\n }\n\n static findOrFail<C extends typeof Model>(this: C, ids: readonly unknown[]): Promise<EloquentCollection<Instance<C>>>\n static findOrFail<C extends typeof Model>(this: C, id: ModelKey | null | undefined): Promise<Instance<C>>\n static findOrFail<C extends typeof Model>(this: C, id: unknown): Promise<Instance<C> | EloquentCollection<Instance<C>>>\n static findOrFail<C extends typeof Model>(this: C, id: unknown): Promise<Instance<C> | EloquentCollection<Instance<C>>> {\n return this.query().findOrFail(id)\n }\n\n static findMany<C extends typeof Model>(this: C, ids: readonly unknown[]): Promise<EloquentCollection<Instance<C>>> {\n return this.query().findMany(ids)\n }\n\n static first<C extends typeof Model>(this: C): Promise<Instance<C> | undefined> {\n return this.query().first()\n }\n\n static firstOrFail<C extends typeof Model>(this: C): Promise<Instance<C>> {\n return this.query().firstOrFail()\n }\n\n static firstWhere<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, operatorOrValue: unknown, value?: unknown): Promise<Instance<C> | undefined> {\n return this.query().firstWhere(column, operatorOrValue, value)\n }\n\n static count(): Promise<number> {\n return this.query().count()\n }\n\n static exists(): Promise<boolean> {\n return this.query().exists()\n }\n\n static pluck<C extends typeof Model, V = unknown>(this: C, column: Column<Instance<C>>): Promise<Collection<V>> {\n return this.query().pluck<V>(column)\n }\n\n static paginate<C extends typeof Model>(this: C, perPage?: number, columns?: string[], pageName?: string, page?: number): Promise<LengthAwarePaginator<Instance<C>>> {\n return this.query().paginate(perPage, columns, pageName, page)\n }\n\n static simplePaginate<C extends typeof Model>(this: C, perPage?: number, columns?: string[], pageName?: string, page?: number): Promise<Paginator<Instance<C>>> {\n return this.query().simplePaginate(perPage, columns, pageName, page)\n }\n\n static cursorPaginate<C extends typeof Model>(this: C, perPage?: number, columns?: string[], cursorName?: string, cursor?: Cursor | string): Promise<CursorPaginator<Instance<C>>> {\n return this.query().cursorPaginate(perPage, columns, cursorName, cursor)\n }\n\n static chunk<C extends typeof Model>(this: C, count: number, callback: (models: EloquentCollection<Instance<C>>, page: number) => unknown): Promise<boolean> {\n return this.query().chunk(count, callback)\n }\n\n static chunkById<C extends typeof Model>(this: C, count: number, callback: (models: EloquentCollection<Instance<C>>, page: number) => unknown): Promise<boolean> {\n return this.query().chunkById(count, callback)\n }\n\n static each<C extends typeof Model>(this: C, callback: (model: Instance<C>, index: number) => unknown, count?: number): Promise<boolean> {\n return this.query().each(callback, count)\n }\n\n static lazy<C extends typeof Model>(this: C, chunkSize?: number): LazyCollection<Instance<C>> {\n return this.query().lazy(chunkSize)\n }\n\n static lazyById<C extends typeof Model>(this: C, chunkSize?: number): LazyCollection<Instance<C>> {\n return this.query().lazyById(chunkSize)\n }\n\n /** Creates and saves a model (mass assignment rules apply). */\n static create<C extends typeof Model, const T extends object = Row>(this: C, attributes?: T & WriteAttributes<Instance<C>, T>): Promise<Instance<C>> {\n return this.query().create((attributes ?? {}) as Row)\n }\n\n static forceCreate<C extends typeof Model, const T extends object = Row>(this: C, attributes: T & WriteAttributes<Instance<C>, T>): Promise<Instance<C>> {\n return this.query().forceCreate(attributes as Row)\n }\n\n static firstOrNew<C extends typeof Model, const A extends object = Row, const V extends object = Row>(\n this: C,\n attributes: A & WriteAttributes<Instance<C>, A>,\n values?: V & WriteAttributes<Instance<C>, V>,\n ): Promise<Instance<C>> {\n return this.query().firstOrNew(attributes as Row, (values ?? {}) as Row)\n }\n\n static firstOrCreate<C extends typeof Model, const A extends object = Row, const V extends object = Row>(\n this: C,\n attributes: A & WriteAttributes<Instance<C>, A>,\n values?: V & WriteAttributes<Instance<C>, V>,\n ): Promise<Instance<C>> {\n return this.query().firstOrCreate(attributes as Row, (values ?? {}) as Row)\n }\n\n static updateOrCreate<C extends typeof Model, const A extends object = Row, const V extends object = Row>(\n this: C,\n attributes: A & WriteAttributes<Instance<C>, A>,\n values?: V & WriteAttributes<Instance<C>, V>,\n ): Promise<Instance<C>> {\n return this.query().updateOrCreate(attributes as Row, (values ?? {}) as Row)\n }\n\n /**\n * The model's registered factory (database/factories/<Model>Factory.ts): await User.factory().create(),\n * await User.factory(3).create(). Use UserFactory.new() to reach the factory's own state methods with their types.\n */\n static factory<C extends typeof Model>(this: C): Factory<InstanceType<C>>\n static factory<C extends typeof Model>(this: C, count: number, state?: State): Factory<InstanceType<C>> & Many\n static factory<C extends typeof Model>(this: C, count?: number, state?: State): Factory<InstanceType<C>> {\n let factory = Factory.forModel(this as unknown as new () => InstanceType<C>)\n if (count !== undefined) factory = factory.count(count)\n if (state) factory = factory.state(state)\n return factory\n }\n\n /** Deletes models by key, one by one, so model events fire. Returns how many were deleted. */\n static async destroy(...ids: Array<unknown | unknown[]>): Promise<number> {\n const keys = ids.flat()\n if (!keys.length) return 0\n let count = 0\n for (const model of await this.query().whereKey(keys).get()) if (await model.delete()) count++\n return count\n }\n\n // ---------------------------------------------------------------- mass assignment\n\n /** Disables mass assignment protection everywhere until reguard(). */\n static unguard(state = true): void {\n unguardedGlobally.value = state\n }\n\n static reguard(): void {\n unguardedGlobally.value = false\n }\n\n static isUnguarded(): boolean {\n return unguardedGlobally.value || unguardedScope.getStore() === true\n }\n\n /** Runs fn with mass assignment protection off, for this async context only (seeders, factories). */\n static unguarded<R>(fn: () => R): R {\n return unguardedScope.run(true, fn)\n }\n\n /** Sets the fillable attributes; the others are dropped, or throw MassAssignmentError on a totally guarded model. */\n fill<Self extends Model, const T extends object = Row, Concrete extends Model = Model>(this: Self & { readonly $self?: Concrete }, attributes: T & WriteAttributes<Concrete, T>): this {\n const totallyGuarded = this.totallyGuarded()\n for (const [key, value] of Object.entries(attributes as Row)) {\n if (this.isFillable(key)) this.setAttribute(key, value)\n else if (totallyGuarded) throw new MassAssignmentError(this.constructor.name, key)\n }\n // `this` is the receiver, typed with its $self for the checks above; the method returns it as itself.\n return this as never\n }\n\n /** Sets attributes with no mass assignment check. Never pass it request input. */\n forceFill<Self extends Model, const T extends object = Row, Concrete extends Model = Model>(this: Self & { readonly $self?: Concrete }, attributes: T & WriteAttributes<Concrete, T>): this {\n for (const [key, value] of Object.entries(attributes as Row)) this.setAttribute(key, value)\n return this as never\n }\n\n isFillable(key: string): boolean {\n if (Model.isUnguarded()) return true\n if (this.fillable.includes(key)) return true\n if (this.fillable.length > 0 || this.isGuarded(key)) return false\n return PLAIN_COLUMN.test(key) && !key.startsWith('_')\n }\n\n /** Guarded names match case-insensitively: SQLite and MySQL column names are case-insensitive. */\n isGuarded(key: string): boolean {\n if (this.guarded.length === 0) return false\n const lower = key.toLowerCase()\n return this.guarded.some((guarded) => guarded === '*' || guarded.toLowerCase() === lower)\n }\n\n totallyGuarded(): boolean {\n return !Model.isUnguarded() && this.fillable.length === 0 && this.guarded.length === 1 && this.guarded[0] === '*'\n }\n\n getFillable(): string[] {\n return [...this.fillable]\n }\n\n getGuarded(): string[] {\n return [...this.guarded]\n }\n\n // ---------------------------------------------------------------- attributes\n\n /** An attribute through its accessor or cast; undefined when the model doesn't have it. */\n getAttribute<T = unknown>(key: string): T {\n if (!key) return undefined as T\n if (Object.hasOwn(this.attributes, key) || this.hasGetMutator(key) || this.hasCast(key)) return this.getAttributeValue(key) as T\n return undefined as T\n }\n\n /** The attribute's value after its accessor (get<Name>Attribute) or cast. */\n getAttributeValue(key: string): unknown {\n const value = this.attributes[key]\n const accessor = this.mutatorFor('get', key)\n if (accessor) return accessor.call(this, value)\n return this.castAttribute(key, value)\n }\n\n /** Sets an attribute through its mutator (set<Name>Attribute) or cast. */\n setAttribute(key: string, value: unknown): this {\n const mutator = this.mutatorFor('set', key)\n if (mutator) {\n mutator.call(this, value)\n return this\n }\n const cast = this.getCasts()[key]\n this.castCache.delete(key)\n this.attributes[key] = cast === undefined ? value : castSet(this, key, cast, value, this.attributes, this.constructor.name)\n if (isHashedCast(cast)) {\n if (value === null || value === undefined) this.pendingHashes.delete(key)\n else this.pendingHashes.add(key)\n }\n return this\n }\n\n hasGetMutator(key: string): boolean {\n return this.mutatorFor('get', key) !== undefined\n }\n\n hasSetMutator(key: string): boolean {\n return this.mutatorFor('set', key) !== undefined\n }\n\n /** Every cast, including the implied ones: the incrementing key (int) and the timestamp columns (datetime). */\n getCasts(): Record<string, CastDefinition> {\n const implied: Record<string, CastDefinition> = {}\n if (this.getIncrementing()) implied[this.getKeyName()] = this.getKeyType() === 'int' ? 'int' : 'string'\n if (this.usesTimestamps()) {\n const created = this.getCreatedAtColumn()\n const updated = this.getUpdatedAtColumn()\n if (created) implied[created] = 'datetime'\n if (updated) implied[updated] = 'datetime'\n }\n if (this.softDeletes) implied[this.getDeletedAtColumn()] = 'datetime'\n return { ...implied, ...this.casts }\n }\n\n /** Adds casts to this instance only (Laravel's mergeCasts()); withCasts() on a query does it for each result. */\n mergeCasts(casts: Readonly<Record<string, CastDefinition>>): this {\n this.casts = { ...this.casts, ...casts }\n return this\n }\n\n hasCast(key: string, types?: string[]): boolean {\n const cast = this.getCasts()[key]\n if (cast === undefined) return false\n return types === undefined || (typeof cast === 'string' && types.includes(cast))\n }\n\n /** The stored attributes, with in-place changes to json casts written back. */\n getAttributes(): Row {\n this.mergeCachedCasts()\n return { ...this.attributes }\n }\n\n /** Replaces the stored attributes as-is (no casts or mutators); sync = also make them the original. */\n setRawAttributes(attributes: Row, sync = false): this {\n this.attributes = { ...attributes }\n this.castCache.clear()\n this.pendingHashes.clear()\n if (sync) this.syncOriginal()\n return this\n }\n\n /** The original value (cast), or every original value. */\n getOriginal(): Row\n getOriginal<T = unknown>(key: string): T\n getOriginal(key?: string): unknown {\n if (key !== undefined) return this.castAttribute(key, this.original[key], false)\n return Object.fromEntries(Object.keys(this.original).map((name) => [name, this.castAttribute(name, this.original[name], false)]))\n }\n\n getRawOriginal(): Row\n getRawOriginal<T = unknown>(key: string): T\n getRawOriginal(key?: string): unknown {\n return key === undefined ? { ...this.original } : this.original[key]\n }\n\n syncOriginal(): this {\n this.original = this.getAttributes()\n return this\n }\n\n syncOriginalAttributes(...keys: string[]): this {\n const current = this.getAttributes()\n for (const key of keys) this.original[key] = current[key]\n return this\n }\n\n /** The attributes that changed since the model was loaded or saved, compared by meaning (casts), not representation. */\n getDirty(): Row {\n this.mergeCachedCasts()\n const casts = this.getCasts()\n const dirty: Row = {}\n for (const [key, value] of Object.entries(this.attributes)) {\n const unchanged = Object.hasOwn(this.original, key) &&\n isEquivalent(casts[key], value, this.original[key], this, key, this.constructor.name)\n if (!unchanged) dirty[key] = value\n }\n return dirty\n }\n\n isDirty(...keys: Array<string | string[]>): boolean {\n const dirty = this.getDirty()\n const names = keys.flat()\n return names.length ? names.some((key) => Object.hasOwn(dirty, key)) : Object.keys(dirty).length > 0\n }\n\n isClean(...keys: Array<string | string[]>): boolean {\n return !this.isDirty(...keys)\n }\n\n /** The attributes the last save() changed. */\n getChanges(): Row {\n return { ...this.changes }\n }\n\n wasChanged(...keys: Array<string | string[]>): boolean {\n const names = keys.flat()\n return names.length ? names.some((key) => Object.hasOwn(this.changes, key)) : Object.keys(this.changes).length > 0\n }\n\n syncChanges(): this {\n this.changes = this.getDirty()\n return this\n }\n\n /** The given attributes (through accessors and casts). */\n only(...keys: Array<string | string[]>): Row {\n return Object.fromEntries(keys.flat().map((key) => [key, this.getAttribute(key)]))\n }\n\n /**\n * useCache = false skips the json-cast decode cache entirely (both reading and writing it): used by getOriginal(),\n * so a decoded original never aliases the live attribute's cached (and possibly in-place-mutated) object, even\n * when their raw stored strings are equal right after load/save.\n */\n protected castAttribute(key: string, value: unknown, useCache = true): unknown {\n const cast = this.getCasts()[key]\n if (cast === undefined) return value\n if (useCache && isJsonCast(cast) && value !== null && value !== undefined) {\n const cached = this.castCache.get(key)\n if (cached && cached.raw === value) return cached.value\n const decoded = castGet(this, key, cast, value, this.attributes, this.constructor.name)\n if (value === this.attributes[key]) this.castCache.set(key, { raw: value, value: decoded })\n return decoded\n }\n return castGet(this, key, cast, value, this.attributes, this.constructor.name)\n }\n\n /** Writes json casts that were changed in place (post.meta.views++) back into the stored attributes. */\n protected mergeCachedCasts(): void {\n const casts = this.getCasts()\n for (const [key, entry] of this.castCache) {\n if (this.attributes[key] !== entry.raw) {\n this.castCache.delete(key)\n continue\n }\n const encoded = castSet(this, key, casts[key]!, entry.value, this.attributes, this.constructor.name)\n if (encoded !== entry.raw) {\n this.attributes[key] = encoded\n entry.raw = encoded\n }\n }\n }\n\n private mutatorFor(kind: 'get' | 'set', key: string): AnyFunction | undefined {\n return methodOf(this, `${kind}${Str.studly(key)}Attribute`)\n }\n\n // ---------------------------------------------------------------- keys, table and naming\n\n getKeyName(): string {\n return this.primaryKey\n }\n\n getKeyType(): 'int' | 'string' {\n return this.keyType\n }\n\n getIncrementing(): boolean {\n return this.incrementing\n }\n\n /** Whether new rows get unique string ids before `creating` (HasUuids, HasUlids). */\n usesUniqueIds(): boolean {\n return false\n }\n\n /** The columns that get a unique id (HasUuids and HasUlids: the primary key). */\n uniqueIds(): string[] {\n return []\n }\n\n /** A new unique id (HasUuids: a version 7 UUID; HasUlids: a lower-case ULID). */\n newUniqueId(): string | undefined {\n return undefined\n }\n\n /** Whether a value has the shape of this model's unique ids (HasUuids: a UUID). Any value passes by default. */\n isValidUniqueId(_value: unknown): boolean {\n return true\n }\n\n /** Fills each empty unique id column with newUniqueId() (Laravel's setUniqueIds()). */\n setUniqueIds(): void {\n for (const column of this.uniqueIds()) {\n const value = this.getAttribute(column)\n if (value === undefined || value === null || value === '') this.setAttribute(column, this.newUniqueId())\n }\n }\n\n /** The primary key's value: a string, a number or a bigint, or nothing on a model not yet saved. */\n getKey(): ModelKey | null | undefined {\n return this.getAttribute(this.getKeyName()) as ModelKey | null | undefined\n }\n\n getTable(): string {\n return this.table ?? Str.snake(Str.plural(this.constructor.name))\n }\n\n getConnectionName(): string | undefined {\n return this.connection\n }\n\n getPerPage(): number {\n return this.perPage\n }\n\n /** 'posts.title' for 'title'. Already-qualified columns are returned as-is. */\n qualifyColumn(column: string): string {\n return column.includes('.') ? column : `${this.getTable()}.${column}`\n }\n\n getQualifiedKeyName(): string {\n return this.qualifyColumn(this.getKeyName())\n }\n\n /** The conventional foreign key pointing at this model: user_id for User. */\n getForeignKey(): string {\n return `${Str.snake(this.constructor.name)}_${this.getKeyName()}`\n }\n\n getRouteKeyName(): string {\n return this.getKeyName()\n }\n\n getRouteKey(): unknown {\n return this.getAttribute(this.getRouteKeyName())\n }\n\n /**\n * The model a route parameter value points at: where <field or route key> = value (global scopes apply, so a\n * soft-deleted row isn't found). A non-numeric value for an integer primary key, or a value that isn't a UUID\n * (ULID) for a unique id column, finds nothing without a query.\n */\n async resolveRouteBinding(value: string, field?: string): Promise<this | undefined> {\n const column = field ?? this.getRouteKeyName()\n if (column === this.getKeyName() && this.getKeyType() === 'int' && !/^-?\\d+$/.test(value)) return undefined\n if (this.uniqueIds().includes(column) && !this.isValidUniqueId(value)) return undefined\n return this.resolveRouteBindingQuery(this.newQuery(), value, column).first()\n }\n\n /** Override to customize the binding query (Laravel's resolveRouteBindingQuery()). */\n resolveRouteBindingQuery(query: Builder<this>, value: string, field: string): Builder<this> {\n return query.where(this.qualifyColumn(field) as Column<this>, value)\n }\n\n usesTimestamps(): boolean {\n return this.timestamps\n }\n\n usesSoftDeletes(): boolean {\n return this.softDeletes\n }\n\n getCreatedAtColumn(): string | null {\n return (this.constructor as typeof Model).CREATED_AT\n }\n\n getUpdatedAtColumn(): string | null {\n return (this.constructor as typeof Model).UPDATED_AT\n }\n\n getDeletedAtColumn(): string {\n return (this.constructor as typeof Model).DELETED_AT\n }\n\n // ---------------------------------------------------------------- connection and queries\n\n /** The model's database connection, from the DatabaseManager binding. */\n getConnection(): Connection {\n const connection = inject(DatabaseManager).connection(this.getConnectionName())\n if (!(connection instanceof Connection)) {\n throw new DatabaseConfigError('Models need the DatabaseManager from @orieljs/database. Is DatabaseServiceProvider registered?')\n }\n return connection\n }\n\n setConnection(name: string | undefined): this {\n this.connection = name\n return this\n }\n\n setTable(table: string): this {\n this.table = table\n return this\n }\n\n /** A new instance of the same class, connection and table (mass assignment rules apply to attributes). */\n newInstance(attributes: Row = {}, exists = false): this {\n const model = new (this.constructor as new () => this)()\n model.exists = exists\n model.setConnection(this.getConnectionName())\n model.setTable(this.getTable())\n return model.fill(attributes)\n }\n\n /** An existing model from a database row (no casts or mutators applied to the row). */\n newFromBuilder(attributes: Row): this {\n const model = this.newInstance({}, true)\n model.setRawAttributes(attributes, true)\n return model\n }\n\n /** A query of this model with its global scopes and default eager loads. */\n newQuery(): Builder<this> {\n return this.registerGlobalScopes(this.newQueryWithoutScopes())\n }\n\n /** A query with the default eager loads (`with`, `withCount`) but no global scopes. */\n newQueryWithoutScopes(): Builder<this> {\n return this.registerDefaultEagerLoads(this.newModelQuery())\n }\n\n /** A query with the global scopes but no default eager loads. */\n newQueryWithoutRelationships(): Builder<this> {\n return this.registerGlobalScopes(this.newModelQuery())\n }\n\n /** Adds this class's global scopes to a builder (relations use it for the related model's scopes). */\n registerGlobalScopes<B extends Builder<Model>>(builder: B): B {\n for (const [name, scope] of globalScopes.get(this.constructor as typeof Model) ?? []) builder.withGlobalScope(name, scope)\n return builder\n }\n\n /**\n * Adds this class's default `with` and `withCount` to a builder (relations use it for the related model's\n * defaults). A default count that reaches the same class again while it is being added (a self-referencing\n * relation, or two models counting each other) is skipped there instead of recursing forever.\n */\n registerDefaultEagerLoads<B extends Builder<Model>>(builder: B): B {\n if (this.with.length) builder.with(...this.with)\n const cls = this.constructor as typeof Model\n if (!this.withCount.length || addingDefaultCounts.has(cls)) return builder\n addingDefaultCounts.add(cls)\n try {\n builder.withCount(...this.withCount)\n } finally {\n addingDefaultCounts.delete(cls)\n }\n return builder\n }\n\n /** A bare builder for this model: no global scopes, no default eager loads. */\n newModelQuery(): Builder<this> {\n return new Builder<this>(this)\n }\n\n // ---------------------------------------------------------------- persistence\n\n /**\n * Inserts the model, or updates its dirty attributes. Only changed columns are written; an unchanged model\n * runs no query at all. Returns false when a saving/creating/updating listener cancels.\n */\n async save(): Promise<boolean> {\n const query = this.newModelQuery()\n await this.hashPendingAttributes()\n if ((await this.fireModelEvent('saving')) === false) return false\n let saved: boolean\n if (this.exists) saved = this.isDirty() ? await this.performUpdate(query) : true\n else saved = await this.performInsert(query)\n if (saved) await this.finishSave()\n return saved\n }\n\n /**\n * Laravel's hashed cast (castAttributeAsHashedString()), run when the model is saved because the Hasher is\n * asynchronous: each newly assigned value is hashed before the saving event, so every listener sees the hash, and\n * again just before the write (after the creating or updating event), so a value a listener assigns is hashed too.\n * A value that is already a hash is kept when it matches the configured algorithm and options, and refused\n * otherwise. Only strings and numbers are hashed (null stays null); any other value is refused.\n */\n protected async hashPendingAttributes(): Promise<void> {\n if (!this.pendingHashes.size) return\n const hashing = hasher()\n for (const key of this.pendingHashes) {\n const value = this.attributes[key]\n if (value === null || value === undefined) continue\n if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'bigint') {\n throw new LogicError(`The hashed cast on [${key}] needs a string, got ${Array.isArray(value) ? 'array' : typeof value}.`)\n }\n const text = String(value)\n if (hashing.info(text).algorithm === 'unknown') this.attributes[key] = await hashing.make(text)\n else if (hashing.needsRehash(text)) throw new LogicError(\"Could not verify the hashed value's configuration.\")\n }\n this.pendingHashes.clear()\n }\n\n /** Fills and saves an existing model. */\n async update<Self extends Model, const T extends object = Row, Concrete extends Model = Model>(this: Self & { readonly $self?: Concrete }, attributes?: T & WriteAttributes<Concrete, T>): Promise<boolean> {\n if (!this.exists) return false\n return this.fill((attributes ?? {}) as Row).save()\n }\n\n /**\n * Deletes the model's row, or sets deleted_at with soft deletes. Returns false for a model that isn't saved, or\n * when a deleting listener cancels.\n */\n async delete(): Promise<boolean> {\n if (!this.exists) return false\n if ((await this.fireModelEvent('deleting')) === false) return false\n await this.performDeleteOnModel()\n await this.fireModelEvent('deleted', false)\n return true\n }\n\n /** save() without model events. */\n saveQuietly(): Promise<boolean> {\n return withoutModelEvents(() => this.save())\n }\n\n /** delete() without model events. */\n deleteQuietly(): Promise<boolean> {\n return withoutModelEvents(() => this.delete())\n }\n\n // ---------------------------------------------------------------- soft deletes\n\n /** True when the model is soft deleted. Only for models with `softDeletes = true`. */\n trashed(): boolean {\n this.assertSoftDeletes('trashed')\n const value = this.getAttribute(this.getDeletedAtColumn())\n return value !== null && value !== undefined\n }\n\n /** Clears deleted_at and saves. Fires restoring (can cancel) and restored. */\n async restore(): Promise<boolean> {\n this.assertSoftDeletes('restore')\n if ((await this.fireModelEvent('restoring')) === false) return false\n this.setAttribute(this.getDeletedAtColumn(), null)\n this.exists = true\n const saved = await this.save()\n await this.fireModelEvent('restored', false)\n return saved\n }\n\n /** Deletes the row for real, even with soft deletes. Fires forceDeleting (can cancel) and forceDeleted. */\n async forceDelete(): Promise<boolean> {\n if (!this.usesSoftDeletes()) return this.delete()\n if ((await this.fireModelEvent('forceDeleting')) === false) return false\n this.forceDeleting = true\n try {\n const deleted = await this.delete()\n if (deleted) await this.fireModelEvent('forceDeleted', false)\n return deleted\n } finally {\n this.forceDeleting = false\n }\n }\n\n isForceDeleting(): boolean {\n return this.forceDeleting\n }\n\n getQualifiedDeletedAtColumn(): string {\n return this.qualifyColumn(this.getDeletedAtColumn())\n }\n\n private assertSoftDeletes(method: string): void {\n if (!this.usesSoftDeletes()) {\n throw new LogicError(`${method}() needs soft deletes: set \\`protected softDeletes = true\\` on [${this.constructor.name}].`)\n }\n }\n\n /** Reloads the attributes and the loaded relations from the database (including a soft-deleted row). */\n async refresh(): Promise<this> {\n if (!this.exists) return this\n const fresh = await this.newModelQuery().whereKey(this.getKey()).firstOrFail()\n this.setRawAttributes(fresh.getAttributes(), true)\n const loaded = Object.keys(this.relations)\n if (loaded.length) await this.load(loaded)\n return this\n }\n\n /** A fresh copy from the database, or undefined when the row is gone. */\n async fresh(): Promise<this | undefined> {\n if (!this.exists) return undefined\n return this.newModelQuery().whereKey(this.getKey()).first()\n }\n\n /** Updates updated_at (and saves). */\n async touch(): Promise<boolean> {\n if (!this.usesTimestamps()) return false\n this.updateTimestamps()\n return this.save()\n }\n\n /** column = column + amount in the database, mirrored on the model without marking it dirty. */\n async increment(column: string, amount = 1, extra: Row = {}): Promise<number> {\n return this.incrementOrDecrement(column, amount, extra)\n }\n\n async decrement(column: string, amount = 1, extra: Row = {}): Promise<number> {\n return this.incrementOrDecrement(column, -amount, extra)\n }\n\n /** Same table, connection and key. */\n is(other: Model | null | undefined): boolean {\n return !!other && other.getKey() === this.getKey() && other.getTable() === this.getTable() &&\n other.getConnectionName() === this.getConnectionName()\n }\n\n isNot(other: Model | null | undefined): boolean {\n return !this.is(other)\n }\n\n /** The current time, to the second (the storage precision). */\n freshTimestamp(): Date {\n const now = new Date()\n now.setMilliseconds(0)\n return now\n }\n\n updateTimestamps(): void {\n const time = this.freshTimestamp()\n const updated = this.getUpdatedAtColumn()\n const created = this.getCreatedAtColumn()\n if (updated && !this.isDirty(updated)) this.setAttribute(updated, time)\n if (!this.exists && created && !this.isDirty(created)) this.setAttribute(created, time)\n }\n\n protected async performInsert(query: Builder<this>): Promise<boolean> {\n if (this.usesUniqueIds()) this.setUniqueIds()\n if ((await this.fireModelEvent('creating')) === false) return false\n if (this.usesTimestamps()) this.updateTimestamps()\n await this.hashPendingAttributes()\n const attributes = this.getAttributes()\n if (this.getIncrementing()) {\n const id = await query.insertGetId(attributes, this.getKeyName())\n this.setAttribute(this.getKeyName(), id)\n } else {\n if (!Object.keys(attributes).length) return true\n await query.insert(attributes)\n }\n this.exists = true\n this.wasRecentlyCreated = true\n await this.fireModelEvent('created', false)\n return true\n }\n\n protected async performUpdate(query: Builder<this>): Promise<boolean> {\n if ((await this.fireModelEvent('updating')) === false) return false\n if (this.usesTimestamps()) this.updateTimestamps()\n await this.hashPendingAttributes()\n const dirty = this.getDirty()\n if (Object.keys(dirty).length) {\n await this.setKeysForSaveQuery(query).update(dirty)\n this.syncChanges()\n await this.fireModelEvent('updated', false)\n }\n return true\n }\n\n protected async finishSave(): Promise<void> {\n await this.fireModelEvent('saved', false)\n this.syncOriginal()\n }\n\n protected async performDeleteOnModel(): Promise<void> {\n if (this.usesSoftDeletes() && !this.forceDeleting) return this.runSoftDelete()\n await this.setKeysForSaveQuery(this.newModelQuery()).forceDelete()\n this.exists = false\n }\n\n /** deleted_at (and updated_at) = now, on this row only. The model still exists, as a trashed model. */\n protected async runSoftDelete(): Promise<void> {\n const time = this.freshTimestamp()\n const columns = [this.getDeletedAtColumn()]\n this.setAttribute(this.getDeletedAtColumn(), time)\n const updated = this.getUpdatedAtColumn()\n if (this.usesTimestamps() && updated) {\n this.setAttribute(updated, time)\n columns.push(updated)\n }\n const values = Object.fromEntries(columns.map((column) => [column, this.getAttributes()[column]]))\n await this.setKeysForSaveQuery(this.newModelQuery()).update(values)\n this.syncOriginalAttributes(...columns)\n }\n\n /** where key = the key the row was loaded with (the original, in case the key itself changed). */\n protected setKeysForSaveQuery(query: Builder<this>): Builder<this> {\n const key = Object.hasOwn(this.original, this.getKeyName()) ? this.original[this.getKeyName()] : this.getKey()\n if (key === undefined || key === null) throw new LogicError(`Model [${this.constructor.name}] has no primary key value.`)\n return query.where(this.getKeyName() as Column<this>, '=', key)\n }\n\n protected async incrementOrDecrement(column: string, amount: number, extra: Row): Promise<number> {\n // An unsaved model updates every row its global scopes allow (never trashed rows); a saved one updates its own row.\n if (!this.exists) return this.newQueryWithoutRelationships().increment(column, amount, extra)\n // As Laravel's: the model holds the new values first, so updating and updated listeners (observers) see them, and an\n // updating listener that returns false stops the write.\n this.forceFill({ ...extra, [column]: Number(this.getAttribute(column) ?? 0) + amount })\n if ((await this.fireModelEvent('updating')) === false) return 0\n const affected = await this.setKeysForSaveQuery(this.newModelQuery()).increment(column, amount, extra)\n this.syncChanges()\n await this.fireModelEvent('updated', false)\n this.syncOriginalAttributes(column, ...Object.keys(extra))\n return affected\n }\n\n /**\n * Dispatches 'eloquent.<event>: <Class>' with the model as payload. Halting events return false when a listener\n * returned false. A no-op without an EventDispatcher binding, or inside withoutEvents().\n */\n async fireModelEvent(event: ModelEvent, halt = true): Promise<boolean> {\n if (modelEventsMuted()) return true\n const dispatcher = eventDispatcher()\n if (!dispatcher) return true\n const name = modelEventName(event, this.constructor.name)\n if (halt) return (await dispatcher.until(name, [this])) !== false\n await dispatcher.dispatch(name, [this])\n return true\n }\n\n /** Whether any listener is registered for one of this model's events (retrieved is skipped when none is). */\n hasModelListeners(event: ModelEvent): boolean {\n return !modelEventsMuted() && (eventDispatcher()?.hasListeners(modelEventName(event, this.constructor.name)) ?? false)\n }\n\n // ---------------------------------------------------------------- relations\n\n /**\n * One related row holds this model's key: user.profile() → hasOne(Profile) (profiles.user_id = users.id).\n * @param foreignKey on the related table (default: this model's foreign key, e.g. user_id)\n * @param localKey on this model (default: the primary key)\n */\n hasOne<C extends typeof Model>(related: C, foreignKey?: string, localKey?: string): HasOne<InstanceType<C>, this> & Scopes<C> {\n const instance = this.newRelatedInstance(related)\n const relation = new HasOne(instance, this, instance.qualifyColumn(foreignKey ?? this.getForeignKey()), localKey ?? this.getKeyName())\n return relation as HasOne<InstanceType<C>, this> & Scopes<C>\n }\n\n /** Many related rows hold this model's key: post.comments() → hasMany(Comment) (comments.post_id = posts.id). */\n hasMany<C extends typeof Model>(related: C, foreignKey?: string, localKey?: string): HasMany<InstanceType<C>, this> & Scopes<C> {\n const instance = this.newRelatedInstance(related)\n const relation = new HasMany(instance, this, instance.qualifyColumn(foreignKey ?? this.getForeignKey()), localKey ?? this.getKeyName())\n return relation as HasMany<InstanceType<C>, this> & Scopes<C>\n }\n\n /**\n * This model holds the related model's key: post.author() → belongsTo(User, 'user_id').\n * @param foreignKey on this model (default: the related model's foreign key, e.g. user_id)\n * @param ownerKey on the related model (default: its primary key)\n * @param relation the loaded-relation name associate() sets (default: the resolved name, else the class in camelCase)\n */\n belongsTo<C extends typeof Model>(related: C, foreignKey?: string, ownerKey?: string, relation?: string): BelongsTo<InstanceType<C>, this> & Scopes<C> {\n const instance = this.newRelatedInstance(related)\n const belongsTo = new BelongsTo(instance, this, foreignKey ?? instance.getForeignKey(), ownerKey ?? instance.getKeyName(), relation)\n return belongsTo as BelongsTo<InstanceType<C>, this> & Scopes<C>\n }\n\n /**\n * Many-to-many through a pivot table: post.tags() → belongsToMany(Tag) over post_tag (post_id, tag_id).\n * @param table default: the two singular snake names in alphabetical order (post_tag)\n * @param foreignPivotKey the pivot column pointing at this model (default: post_id)\n * @param relatedPivotKey the pivot column pointing at the related model (default: tag_id)\n */\n belongsToMany<C extends typeof Model>(\n related: C,\n table?: string,\n foreignPivotKey?: string,\n relatedPivotKey?: string,\n parentKey?: string,\n relatedKey?: string,\n ): BelongsToMany<InstanceType<C>, this> & Scopes<C> {\n const instance = this.newRelatedInstance(related)\n const joining = table ?? [Str.snake(this.constructor.name), Str.snake(related.name)].sort().join('_').toLowerCase()\n const relation = new BelongsToMany(\n instance,\n this,\n joining,\n foreignPivotKey ?? this.getForeignKey(),\n relatedPivotKey ?? instance.getForeignKey(),\n parentKey ?? this.getKeyName(),\n relatedKey ?? instance.getKeyName(),\n )\n return relation as BelongsToMany<InstanceType<C>, this> & Scopes<C>\n }\n\n /**\n * Related rows through an intermediate model: country.posts() → hasManyThrough(Post, User).\n * @param firstKey on the through table (default: this model's foreign key, country_id)\n * @param secondKey on the related table (default: the through model's foreign key, user_id)\n */\n hasManyThrough<C extends typeof Model, T extends typeof Model>(\n related: C,\n through: T,\n firstKey?: string,\n secondKey?: string,\n localKey?: string,\n secondLocalKey?: string,\n ): HasManyThrough<InstanceType<C>, this, InstanceType<T>> & Scopes<C> {\n const instance = this.newRelatedInstance(related)\n const throughParent = this.newRelatedInstance(through)\n const relation = new HasManyThrough(\n instance,\n this,\n throughParent,\n firstKey ?? this.getForeignKey(),\n secondKey ?? throughParent.getForeignKey(),\n localKey ?? this.getKeyName(),\n secondLocalKey ?? throughParent.getKeyName(),\n )\n return relation as HasManyThrough<InstanceType<C>, this, InstanceType<T>> & Scopes<C>\n }\n\n /** A polymorphic one-to-one: user.image() → morphOne(Image, 'imageable') (images.imageable_id/_type). */\n morphOne<C extends typeof Model>(related: C, name: string, type?: string, id?: string, localKey?: string): MorphOne<InstanceType<C>, this> & Scopes<C> {\n const instance = this.newRelatedInstance(related)\n const relation = new MorphOne(instance, this, instance.qualifyColumn(type ?? `${name}_type`), instance.qualifyColumn(id ?? `${name}_id`), localKey ?? this.getKeyName())\n return relation as MorphOne<InstanceType<C>, this> & Scopes<C>\n }\n\n /** A polymorphic one-to-many: post.comments() → morphMany(Comment, 'commentable'). */\n morphMany<C extends typeof Model>(related: C, name: string, type?: string, id?: string, localKey?: string): MorphMany<InstanceType<C>, this> & Scopes<C> {\n const instance = this.newRelatedInstance(related)\n const relation = new MorphMany(instance, this, instance.qualifyColumn(type ?? `${name}_type`), instance.qualifyColumn(id ?? `${name}_id`), localKey ?? this.getKeyName())\n return relation as MorphMany<InstanceType<C>, this> & Scopes<C>\n }\n\n /**\n * The inverse of morphOne/morphMany: comment.commentable() → morphTo('commentable'). The name is required\n * (Laravel reads it from the calling method, which JavaScript can't do reliably).\n */\n morphTo<R extends Model = Model>(name: string, type?: string, id?: string, ownerKey?: string): MorphTo<R, this> {\n const typeColumn = type ?? `${name}_type`\n const value = this.getAttribute(typeColumn)\n const related = (value ? this.newRelatedInstance(resolveMorphClass(String(value))) : this.newInstance()) as unknown as R\n return new MorphTo<R, this>(related, this, id ?? `${name}_id`, typeColumn, ownerKey, name)\n }\n\n /** The value stored in *_type columns for this model: its morph map alias, or its class name. */\n getMorphClass(): string {\n const cls = this.constructor as typeof Model\n return getMorphAlias(cls) ?? cls.name\n }\n\n /** The pivot row of a model loaded through belongsToMany (tag.pivot.getAttribute('created_at')). */\n get pivot(): Model | undefined {\n return this.relations.pivot as Model | undefined\n }\n\n /** A related model instance on this model's connection when it has none of its own. */\n protected newRelatedInstance<C extends typeof Model>(related: C): InstanceType<C> {\n const instance = new related() as InstanceType<C>\n if (!instance.getConnectionName()) instance.setConnection(this.getConnectionName())\n return instance\n }\n\n /** Whether the model has a relation method called `name` (Laravel's isRelation()). */\n isRelation(name: string): boolean {\n return !(name in Model.prototype) && methodOf(this, name) !== undefined\n }\n\n /** Calls the relation method `name` (post.comments()) and checks that it returns a relation. */\n getRelationInstance(name: string): Relation {\n if (name in Model.prototype) throw new RelationNotFoundError(this.constructor.name, name)\n const method = methodOf(this, name)\n const relation = method?.call(this)\n if (!(relation instanceof Relation)) throw new RelationNotFoundError(this.constructor.name, name)\n relation.relationName = name\n return relation\n }\n\n /**\n * A loaded relation, typed from the relation method: post.getRelation('author') is User | null,\n * post.getRelation('comments') is EloquentCollection<Comment>. Throws RelationNotLoadedError when it isn't loaded\n * (JavaScript can't lazy-load synchronously: use with(), load() or post.comments().get()).\n */\n getRelation<K extends RelationNames<this>>(name: K): RelationValue<this, K> {\n if (!Object.hasOwn(this.relations, name)) throw new RelationNotLoadedError(this.constructor.name, name)\n return this.relations[name] as RelationValue<this, K>\n }\n\n /** Eager loads relations onto this model: await post.load('comments.author'). */\n async load<Self extends Model, const S extends readonly LooseSpec[], Concrete extends Model = Model>(this: Self & { readonly $self?: Concrete }, ...relations: EagerLoads<Concrete, S>): Promise<WithLoaded<Self, LoadedTree<S>>> {\n await this.newCollection([this]).load(...(relations as readonly LooseSpec[] as never[]))\n return this as WithLoaded<Self, LoadedTree<S>>\n }\n\n /** Loads only the relations that aren't loaded yet (nested paths are followed into loaded relations). */\n async loadMissing<Self extends Model, const S extends readonly string[], Concrete extends Model = Model>(this: Self & { readonly $self?: Concrete }, ...relations: EagerLoads<Concrete, S>): Promise<WithLoaded<Self, LoadedTree<S>>> {\n await this.newCollection([this]).loadMissing(...(relations as readonly string[] as never[]))\n return this as WithLoaded<Self, LoadedTree<S>>\n }\n\n /** Loads <relation>_count attributes: await post.loadCount('comments'). */\n async loadCount<Self extends Model, const S extends readonly LooseSpec[], Concrete extends Model = Model>(this: Self & { readonly $self?: Concrete }, ...relations: Aggregates<Concrete, S>): Promise<Self> {\n await this.newCollection([this]).loadCount(...(relations as readonly LooseSpec[] as never[]))\n return this\n }\n\n /** Loads an aggregate of a relation as an attribute (Laravel's loadAggregate()): see withAggregate(). */\n async loadAggregate<Self extends Model, const S extends LooseSpec | readonly LooseSpec[], Concrete extends Model = Model>(this: Self & { readonly $self?: Concrete }, relations: AggregateSpecs<Concrete, S>, column: string | Expression, fn?: string): Promise<Self> {\n await this.newCollection([this]).loadAggregate(relations as never, column, fn)\n return this\n }\n\n /** Loads <relation>_sum_<column>: await user.loadSum('orders', 'price'). */\n loadSum<Self extends Model, const S extends LooseSpec | readonly LooseSpec[], Concrete extends Model = Model>(this: Self & { readonly $self?: Concrete }, relations: AggregateSpecs<Concrete, S>, column: string | Expression): Promise<Self> {\n return this.loadAggregate(relations as never, column, 'sum')\n }\n\n loadAvg<Self extends Model, const S extends LooseSpec | readonly LooseSpec[], Concrete extends Model = Model>(this: Self & { readonly $self?: Concrete }, relations: AggregateSpecs<Concrete, S>, column: string | Expression): Promise<Self> {\n return this.loadAggregate(relations as never, column, 'avg')\n }\n\n loadMin<Self extends Model, const S extends LooseSpec | readonly LooseSpec[], Concrete extends Model = Model>(this: Self & { readonly $self?: Concrete }, relations: AggregateSpecs<Concrete, S>, column: string | Expression): Promise<Self> {\n return this.loadAggregate(relations as never, column, 'min')\n }\n\n loadMax<Self extends Model, const S extends LooseSpec | readonly LooseSpec[], Concrete extends Model = Model>(this: Self & { readonly $self?: Concrete }, relations: AggregateSpecs<Concrete, S>, column: string | Expression): Promise<Self> {\n return this.loadAggregate(relations as never, column, 'max')\n }\n\n /** Loads a boolean <relation>_exists. */\n loadExists<Self extends Model, const S extends readonly LooseSpec[], Concrete extends Model = Model>(this: Self & { readonly $self?: Concrete }, ...relations: Aggregates<Concrete, S>): Promise<Self> {\n return this.loadAggregate(relations as never, '*', 'exists')\n }\n\n /**\n * The collection queries of this model return (Laravel's newCollection()): an EloquentCollection. Override it to\n * return a subclass with your own methods.\n */\n newCollection<T extends Model>(this: T, models: T[] = []): EloquentCollection<T> {\n return new EloquentCollection(models)\n }\n\n // ---------------------------------------------------------------- relations storage\n\n /** Stores a loaded relation (eager loading and load() use this). */\n setRelation(name: string, value: unknown): this {\n this.relations[name] = value\n return this\n }\n\n relationLoaded(name: string): boolean {\n return Object.hasOwn(this.relations, name)\n }\n\n unsetRelation(name: string): this {\n delete this.relations[name]\n return this\n }\n\n getRelations(): Record<string, unknown> {\n return { ...this.relations }\n }\n\n // ---------------------------------------------------------------- serialization\n\n getHidden(): string[] {\n return [...this.hidden]\n }\n\n setHidden(hidden: string[]): this {\n this.hidden = [...hidden]\n return this\n }\n\n getVisible(): string[] {\n return [...this.visible]\n }\n\n setVisible(visible: string[]): this {\n this.visible = [...visible]\n return this\n }\n\n /** Hides attributes for this instance only. */\n makeHidden(...attributes: Array<string | string[]>): this {\n const names = attributes.flat()\n this.hidden = [...new Set([...this.hidden, ...names])]\n this.visible = this.visible.filter((name) => !names.includes(name))\n return this\n }\n\n /** Un-hides attributes for this instance only. */\n makeVisible(...attributes: Array<string | string[]>): this {\n const names = attributes.flat()\n this.hidden = this.hidden.filter((name) => !names.includes(name))\n if (this.visible.length) this.visible = [...new Set([...this.visible, ...names])]\n return this\n }\n\n getAppends(): string[] {\n return [...this.appends]\n }\n\n setAppends(appends: string[]): this {\n this.appends = [...appends]\n return this\n }\n\n /** Adds accessor-only attributes to the serialized form of this instance. */\n append(...attributes: Array<string | string[]>): this {\n this.appends = [...new Set([...this.appends, ...attributes.flat()])]\n return this\n }\n\n /**\n * Attributes (through accessors and casts, dates as ISO strings), appends and loaded relations, minus hidden ones.\n * A model met again while its own toArray() runs (a child chaperone() pointed back at it) gives its attributes only.\n */\n toArray(): Row {\n if (serializing.has(this)) return this.attributesToArray()\n serializing.add(this)\n try {\n return { ...this.attributesToArray(), ...this.relationsToArray() }\n } finally {\n serializing.delete(this)\n }\n }\n\n toJSON(): Row {\n return this.toArray()\n }\n\n attributesToArray(): Row {\n const casts = this.getCasts()\n const result: Row = {}\n for (const [key, raw] of Object.entries(this.arrayable(this.getAttributes()))) {\n const accessor = this.mutatorFor('get', key)\n if (accessor) result[key] = this.serializeValue(accessor.call(this, raw))\n else if (casts[key] !== undefined) result[key] = this.serializeValue(this.castAttribute(key, raw))\n else result[key] = raw\n }\n for (const key of this.appends) {\n if (this.isArrayableKey(key)) result[key] = this.serializeValue(this.getAttribute(key))\n }\n return result\n }\n\n /** Loaded relations under their snake_case names: a model → its array, a collection → an array of arrays. */\n relationsToArray(): Row {\n const result: Row = {}\n for (const [name, value] of Object.entries(this.relations)) {\n const key = Str.snake(name)\n if (!this.isArrayableKey(key)) continue\n if (value === null || value === undefined) result[key] = null\n else if (value instanceof Collection) result[key] = value.toArray()\n else if (typeof (value as { toArray?: unknown }).toArray === 'function') result[key] = (value as { toArray(): unknown }).toArray()\n else result[key] = value\n }\n return result\n }\n\n protected serializeValue(value: unknown): unknown {\n if (value instanceof Date) return serializeDate(value)\n if (value instanceof Collection) return value.toArray()\n return value\n }\n\n private isArrayableKey(key: string): boolean {\n if (this.visible.length && !this.visible.includes(key)) return false\n return !this.hidden.includes(key)\n }\n\n private arrayable(values: Row): Row {\n return Object.fromEntries(Object.entries(values).filter(([key]) => this.isArrayableKey(key)))\n }\n}\n\nsetModelBaseClass(Model)\n\n/** Eager loads relations onto models you already have (Laravel's $collection->load()). */\nexport async function loadRelations<M extends Model>(models: Iterable<M>, ...relations: EagerLoadSpec[]): Promise<M[]> {\n const list = [...models]\n if (!list.length) return list\n await list[0]!.newQueryWithoutRelationships().with(...relations).eagerLoadRelations(list)\n return list\n}\n\n/** A row of a belongsToMany pivot table, available as related.pivot (unguarded, no key, no timestamps by default). */\nexport class Pivot extends Model {\n protected override guarded: string[] = []\n override incrementing = false\n override timestamps = false\n}\n","import type { Operator, Row } from '@orieljs/contracts'\nimport { Collection } from '@orieljs/collections'\nimport { Str } from '@orieljs/support'\nimport { ModelNotFoundError, QueryError } from '../errors'\nimport { Builder as QueryBuilder, type ColumnRef, type DateWhereArgs, type Direction, type Where, type WhereBoolean } from '../Query/Builder'\nimport { Expression } from '../Query/Expression'\nimport { formatDateTime } from '../Query/values'\nimport type { CastDefinition } from './casts'\nimport type { EloquentCollection } from './Collection'\nimport type { Model } from './Model'\nimport { withoutRelationConstraints } from './Relations/constraints'\nimport type { Relation } from './Relations/Relation'\nimport type { GlobalScope } from './Scope'\nimport type { Aggregates, AggregateSpecs, EagerLoads, LoadedBuilder, LoadedTree, LooseSpec, ModelKey, RelationPath, RelationPathArg, UntypedModel, WithLoaded, WriteAttributes } from './types'\nimport { SoftDeletingScope } from './SoftDeletingScope'\nimport type { Column } from './types'\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyRelation = Relation<any, any, any>\n/** A constraint on an eager load, withCount() or whereHas(): (query) => query.where(…). */\nexport type RelationConstraint = (query: AnyRelation) => unknown\nexport type { EagerLoadSpec } from './types'\n\ntype AnyFunction = (...args: unknown[]) => unknown\n\n/** Unknown properties of an Eloquent builder resolve to the model's local scopes: query.published() → scopePublished. */\nconst handler: ProxyHandler<Builder<Model>> = {\n get(target, key, receiver) {\n if (typeof key === 'symbol' || key in target) return Reflect.get(target, key, receiver)\n const scope = target.localScope(key)\n if (!scope) return undefined\n return (...args: unknown[]) => (receiver as Builder<Model>).callScope((query) => scope.call(target.model.constructor, query, ...args))\n },\n}\n\n/** Unique-constraint violations on each driver (createOrFirst()). */\nfunction isUniqueViolation(error: unknown): boolean {\n const cause = (error instanceof QueryError ? error.cause : error) as { code?: unknown; errno?: unknown; message?: unknown } | undefined\n return cause?.code === '23505' || cause?.errno === 1062 || cause?.code === 'ER_DUP_ENTRY' ||\n /UNIQUE constraint failed/.test(String(cause?.message ?? ''))\n}\n\n/**\n * Eloquent's builder: the query builder of one model class. Rows come back as hydrated models, global scopes are\n * applied when the query runs (grouped so an orWhere can't escape them), and unknown methods call the model's local\n * scopes. Everything the query builder does (pagination, chunk, lazy, …) returns models here.\n */\nexport class Builder<M extends Model = Model> extends QueryBuilder<M> {\n readonly model: M\n protected scopes = new Map<string, GlobalScope>()\n protected removedScopes: string[] = []\n protected eagerLoad = new Map<string, RelationConstraint | undefined>()\n /** Casts for the selected columns (withCasts()), merged into every model this query hydrates. */\n protected selectCasts: Record<string, CastDefinition> = {}\n\n constructor(model: M) {\n super(model.getConnection(), model.getTable())\n this.model = model\n return new Proxy(this, handler as ProxyHandler<this>)\n }\n\n getModel(): M {\n return this.model\n }\n\n // ---------------------------------------------------------------- scopes\n\n /** The model class's static scope<Name> method for a builder method name, if any. */\n localScope(name: string): AnyFunction | undefined {\n const scope: unknown = Reflect.get(this.model.constructor, `scope${Str.studly(name)}`)\n return typeof scope === 'function' ? (scope as AnyFunction) : undefined\n }\n\n /** Runs a scope; the wheres it adds are grouped when they contain an \"or\" (Laravel's callScope). */\n callScope(scope: (query: this) => unknown): this {\n const before = this.wheres.length\n const result = scope(this)\n if (this.wheres.length > before) this.addNewWheresWithinGroup(before)\n return result === undefined || result === null ? this : (result as this)\n }\n\n withGlobalScope(name: string, scope: GlobalScope): this {\n this.scopes.set(name, scope)\n return this\n }\n\n /** Removes a global scope by name or Scope class. */\n withoutGlobalScope(scope: string | (abstract new (...args: never[]) => unknown)): this {\n const name = typeof scope === 'string' ? scope : scope.name\n this.removedScopes.push(name)\n this.scopes.delete(name)\n return this\n }\n\n /** Removes every global scope, or the given ones. */\n withoutGlobalScopes(scopes?: Array<string | (abstract new (...args: never[]) => unknown)>): this {\n if (!scopes) {\n this.removedScopes.push(...this.scopes.keys())\n this.scopes.clear()\n } else {\n for (const scope of scopes) this.withoutGlobalScope(scope)\n }\n return this\n }\n\n removedScopeNames(): string[] {\n return [...this.removedScopes]\n }\n\n /** A copy of this query with every global scope applied (Laravel's applyScopes()). */\n applyScopes(): this {\n if (!this.scopes.size) return this\n const query = this.clone() as this\n for (const scope of this.scopes.values()) {\n query.callScope((builder) => (typeof scope === 'function' ? scope(builder) : scope.apply(builder, this.model)))\n }\n query.scopes = new Map()\n return query\n }\n\n /** Groups [0, count) and [count, …) separately when either contains an \"or\", so scopes combine with \"and\". */\n protected addNewWheresWithinGroup(count: number): void {\n const all = this.wheres\n this.wheres = []\n this.groupWhereSlice(all.slice(0, count))\n this.groupWhereSlice(all.slice(count))\n }\n\n private groupWhereSlice(slice: Where[]): void {\n if (!slice.length) return\n if (slice.some((where) => where.boolean === 'or')) {\n const nested = new QueryBuilder<Row>(this.connection)\n nested.wheres = slice\n this.wheres.push({ type: 'nested', query: nested, not: false, boolean: slice[0]!.boolean })\n } else {\n this.wheres.push(...slice)\n }\n }\n\n // ---------------------------------------------------------------- typed constraints (Column<M> names)\n\n override where(column: Column<M> | Expression, value: unknown): this\n override where(column: Column<M> | Expression, operator: Operator | string, value: unknown): this\n override where(conditions: Row): this\n override where(callback: (query: this) => unknown): this\n override where(...args: unknown[]): this {\n return Reflect.apply(QueryBuilder.prototype.where, this, args) as this\n }\n\n override orWhere(column: Column<M> | Expression, value: unknown): this\n override orWhere(column: Column<M> | Expression, operator: Operator | string, value: unknown): this\n override orWhere(conditions: Row): this\n override orWhere(callback: (query: this) => unknown): this\n override orWhere(...args: unknown[]): this {\n return Reflect.apply(QueryBuilder.prototype.orWhere, this, args) as this\n }\n\n override whereIn(column: Column<M> | Expression, values: readonly unknown[] | QueryBuilder<unknown>): this {\n return super.whereIn(column, values)\n }\n\n override whereNotIn(column: Column<M> | Expression, values: readonly unknown[] | QueryBuilder<unknown>): this {\n return super.whereNotIn(column, values)\n }\n\n override whereNull(columns: Column<M> | Expression | Array<Column<M> | Expression>): this {\n return super.whereNull(columns)\n }\n\n override whereNotNull(columns: Column<M> | Expression | Array<Column<M> | Expression>): this {\n return super.whereNotNull(columns)\n }\n\n override whereBetween(column: Column<M> | Expression, values: readonly [unknown, unknown]): this {\n return super.whereBetween(column, values)\n }\n\n override whereDate(column: Column<M> | Expression, ...args: DateWhereArgs): this {\n return super.whereDate(column, ...args)\n }\n\n override orWhereDate(column: Column<M> | Expression, ...args: DateWhereArgs): this {\n return super.orWhereDate(column, ...args)\n }\n\n override whereTime(column: Column<M> | Expression, ...args: DateWhereArgs): this {\n return super.whereTime(column, ...args)\n }\n\n override orWhereTime(column: Column<M> | Expression, ...args: DateWhereArgs): this {\n return super.orWhereTime(column, ...args)\n }\n\n override whereDay(column: Column<M> | Expression, ...args: DateWhereArgs): this {\n return super.whereDay(column, ...args)\n }\n\n override orWhereDay(column: Column<M> | Expression, ...args: DateWhereArgs): this {\n return super.orWhereDay(column, ...args)\n }\n\n override whereMonth(column: Column<M> | Expression, ...args: DateWhereArgs): this {\n return super.whereMonth(column, ...args)\n }\n\n override orWhereMonth(column: Column<M> | Expression, ...args: DateWhereArgs): this {\n return super.orWhereMonth(column, ...args)\n }\n\n override whereYear(column: Column<M> | Expression, ...args: DateWhereArgs): this {\n return super.whereYear(column, ...args)\n }\n\n override orWhereYear(column: Column<M> | Expression, ...args: DateWhereArgs): this {\n return super.orWhereYear(column, ...args)\n }\n\n override whereLike(column: Column<M> | Expression, value: string, caseSensitive = false, boolean: WhereBoolean = 'and', not = false): this {\n return super.whereLike(column, value, caseSensitive, boolean, not)\n }\n\n override orWhereLike(column: Column<M> | Expression, value: string, caseSensitive = false): this {\n return super.orWhereLike(column, value, caseSensitive)\n }\n\n override whereNotLike(column: Column<M> | Expression, value: string, caseSensitive = false, boolean: WhereBoolean = 'and'): this {\n return super.whereNotLike(column, value, caseSensitive, boolean)\n }\n\n override orWhereNotLike(column: Column<M> | Expression, value: string, caseSensitive = false): this {\n return super.orWhereNotLike(column, value, caseSensitive)\n }\n\n override orderBy(column: Column<M> | Expression, direction: Direction | Uppercase<Direction> = 'asc'): this {\n return super.orderBy(column, direction)\n }\n\n /** Newest first by the model's created_at column (or the given one). */\n override latest(column?: Column<M> | Expression): this {\n return super.latest(column ?? this.model.getCreatedAtColumn() ?? 'created_at')\n }\n\n override oldest(column?: Column<M> | Expression): this {\n return super.oldest(column ?? this.model.getCreatedAtColumn() ?? 'created_at')\n }\n\n override select(...columns: Array<Column<M> | Expression | Array<Column<M> | Expression>>): this {\n return super.select(...columns)\n }\n\n /** where key = id (or key in ids). */\n whereKey(id: unknown): this {\n if (Array.isArray(id)) return super.whereIn(this.model.getQualifiedKeyName(), id)\n return super.where(this.model.getQualifiedKeyName(), '=', id)\n }\n\n whereKeyNot(id: unknown): this {\n if (Array.isArray(id)) return super.whereNotIn(this.model.getQualifiedKeyName(), id)\n return super.where(this.model.getQualifiedKeyName(), '!=', id)\n }\n\n // ---------------------------------------------------------------- reading\n\n /** The models, in the model's collection (an EloquentCollection). */\n override async get(): Promise<EloquentCollection<M>> {\n return (await super.get()) as EloquentCollection<M>\n }\n\n protected override newCollection(models: M[]): EloquentCollection<M> {\n return this.model.newCollection(models)\n }\n\n /** chunk() with each chunk in the model's collection. */\n override chunk(count: number, callback: (models: EloquentCollection<M>, page: number) => unknown): Promise<boolean> {\n return super.chunk(count, callback as (results: Collection<M>, page: number) => unknown)\n }\n\n override chunkById(count: number, callback: (models: EloquentCollection<M>, page: number) => unknown, column?: string, alias?: string): Promise<boolean> {\n return super.chunkById(count, callback as (results: Collection<M>, page: number) => unknown, column, alias)\n }\n\n /** Runs the query, hydrates models, fires their retrieved events and eager loads the with() relations. */\n override async runSelect(): Promise<M[]> {\n const query = this.applyScopes()\n const rows = (await QueryBuilder.prototype.runSelect.call(query)) as unknown as Row[]\n const models = query.hydrate(rows)\n if (models.length && this.model.hasModelListeners('retrieved')) {\n for (const model of models) await model.fireModelEvent('retrieved', false)\n }\n // The scoped copy's eager loads: a global scope may add with() relations of its own.\n if (models.length && query.eagerLoad.size) await query.eagerLoadRelations(models)\n return models\n }\n\n // ---------------------------------------------------------------- eager loading\n\n /**\n * Relations to load with the results, one query per relation (and per nesting level):\n * with('author'), with('comments.author'), with({ comments: (q) => q.where('approved', true) }), with('author:id,name').\n */\n with<const S extends readonly LooseSpec[]>(...relations: EagerLoads<M, S>): LoadedBuilder<this, WithLoaded<M, LoadedTree<S>>>\n with(this: Builder<UntypedModel>, ...relations: LooseSpec[]): this\n with(...relations: LooseSpec[]): this {\n for (const spec of relations as readonly LooseSpec[]) {\n if (typeof spec === 'string') this.addEagerLoad(spec, undefined)\n else if (Array.isArray(spec)) for (const name of spec) this.addEagerLoad(name, undefined)\n else for (const [name, constraint] of Object.entries(spec)) this.addEagerLoad(name, constraint)\n }\n return this as never\n }\n\n /** Removes eager loads (including the model's default `with`). */\n without<const S extends readonly string[]>(...relations: S & { [I in keyof S]: RelationPathArg<M, S[I]> }): this\n without(this: Builder<UntypedModel>, ...relations: string[]): this\n without(...relations: string[]): this {\n for (const name of relations as readonly string[]) {\n for (const key of [...this.eagerLoad.keys()]) if (key === name || key.startsWith(`${name}.`)) this.eagerLoad.delete(key)\n }\n return this\n }\n\n getEagerLoads(): Map<string, RelationConstraint | undefined> {\n return new Map(this.eagerLoad)\n }\n\n /** Loads every top-level with() relation onto the models (nested ones are passed down to each relation query). */\n async eagerLoadRelations(models: M[]): Promise<M[]> {\n for (const [name, constraint] of this.eagerLoad) {\n if (!name.includes('.')) await this.eagerLoadRelation(models, name, constraint)\n }\n return models\n }\n\n /** The relation instance for a name, without its per-parent constraints. */\n getRelation(name: string): AnyRelation {\n return withoutRelationConstraints(() => this.model.newInstance().getRelationInstance(name))\n }\n\n protected async eagerLoadRelation(models: M[], name: string, constraint: RelationConstraint | undefined): Promise<void> {\n const relation = this.getRelation(name)\n relation.addEagerConstraints(models)\n constraint?.(relation)\n relation.limitEagerPerParent()\n const nested = this.relationsNestedUnder(name)\n if (Object.keys(nested).length) relation.with(nested)\n relation.initRelation(models, name)\n relation.match(models, (await relation.getEager()).all(), name)\n }\n\n private addEagerLoad(spec: string, constraint: RelationConstraint | undefined): void {\n const [path = '', columns] = spec.split(':')\n const name = path.trim()\n let callback = constraint\n if (columns) {\n const selected = columns.split(',').map((column) => column.trim())\n callback = (query) => {\n query.select(...selected)\n constraint?.(query)\n }\n }\n const segments = name.split('.')\n for (let i = 1; i < segments.length; i++) {\n const parent = segments.slice(0, i).join('.')\n if (!this.eagerLoad.has(parent)) this.eagerLoad.set(parent, undefined)\n }\n this.eagerLoad.set(name, callback)\n }\n\n private relationsNestedUnder(name: string): Record<string, RelationConstraint> {\n const nested: Record<string, RelationConstraint> = {}\n for (const [key, constraint] of this.eagerLoad) {\n if (key.startsWith(`${name}.`)) nested[key.slice(name.length + 1)] = constraint ?? (() => undefined)\n }\n return nested\n }\n\n // ---------------------------------------------------------------- relation counts and existence\n\n /**\n * Adds `<relation>_count` columns: withCount('comments'), withCount({ comments: (q) => q.where('approved', true) }),\n * withCount('comments as approved_count'). Global scopes of the related model (soft deletes) apply.\n */\n withCount<const S extends readonly LooseSpec[]>(...relations: Aggregates<M, S>): this\n withCount(this: Builder<UntypedModel>, ...relations: LooseSpec[]): this\n withCount(...relations: LooseSpec[]): this {\n return this.withAggregate(relations as readonly LooseSpec[] as never, '*', 'count')\n }\n\n /** Adds `<relation>_sum_<column>`: withSum('orders', 'price'), withSum({ 'orders as paid': (q) => … }, 'price'). */\n withSum<const S extends LooseSpec | readonly LooseSpec[]>(relations: AggregateSpecs<M, S>, column: string | Expression): this\n withSum(this: Builder<UntypedModel>, relations: LooseSpec | readonly LooseSpec[], column: string | Expression): this\n withSum(relations: LooseSpec | readonly LooseSpec[], column: string | Expression): this {\n return this.withAggregate(relations as never, column, 'sum')\n }\n\n /** Adds `<relation>_avg_<column>`. */\n withAvg<const S extends LooseSpec | readonly LooseSpec[]>(relations: AggregateSpecs<M, S>, column: string | Expression): this\n withAvg(this: Builder<UntypedModel>, relations: LooseSpec | readonly LooseSpec[], column: string | Expression): this\n withAvg(relations: LooseSpec | readonly LooseSpec[], column: string | Expression): this {\n return this.withAggregate(relations as never, column, 'avg')\n }\n\n /** Adds `<relation>_min_<column>`. */\n withMin<const S extends LooseSpec | readonly LooseSpec[]>(relations: AggregateSpecs<M, S>, column: string | Expression): this\n withMin(this: Builder<UntypedModel>, relations: LooseSpec | readonly LooseSpec[], column: string | Expression): this\n withMin(relations: LooseSpec | readonly LooseSpec[], column: string | Expression): this {\n return this.withAggregate(relations as never, column, 'min')\n }\n\n /** Adds `<relation>_max_<column>`. */\n withMax<const S extends LooseSpec | readonly LooseSpec[]>(relations: AggregateSpecs<M, S>, column: string | Expression): this\n withMax(this: Builder<UntypedModel>, relations: LooseSpec | readonly LooseSpec[], column: string | Expression): this\n withMax(relations: LooseSpec | readonly LooseSpec[], column: string | Expression): this {\n return this.withAggregate(relations as never, column, 'max')\n }\n\n /** Adds a boolean `<relation>_exists`: withExists('comments'). */\n withExists<const S extends readonly LooseSpec[]>(...relations: Aggregates<M, S>): this\n withExists(this: Builder<UntypedModel>, ...relations: LooseSpec[]): this\n withExists(...relations: LooseSpec[]): this {\n return this.withAggregate(relations as readonly LooseSpec[] as never, '*', 'exists')\n }\n\n /**\n * Laravel's withAggregate(): a correlated subquery per relation, `select <fn>(<related column>) … as <alias>`, the\n * alias being `<relation>_<fn>_<column>` unless the relation is named `'orders as alias'`. The relation's\n * constraint and the related model's global scopes apply; orderings are dropped. 'exists' selects\n * `exists (…)`, cast to a boolean. Without a function the column's first value is selected.\n */\n withAggregate<const S extends LooseSpec | readonly LooseSpec[]>(relations: AggregateSpecs<M, S>, column: string | Expression, fn?: string): this\n withAggregate(this: Builder<UntypedModel>, relations: LooseSpec | readonly LooseSpec[], column: string | Expression, fn?: string): this\n withAggregate(relations: LooseSpec | readonly LooseSpec[], column: string | Expression, fn?: string): this {\n const specs = this.normalizeRelationSpecs([relations as LooseSpec | readonly LooseSpec[]].flat() as LooseSpec[])\n if (!specs.length) return this\n if (!this.columns.length) this.columns = [`${this.model.getTable()}.*`]\n for (const [spec, constraint] of specs) {\n const [rawName = '', as] = spec.split(/\\s+as\\s+/i)\n const name = rawName.trim()\n const relation = this.getRelation(name)\n const query = relation.getRelationExistenceQuery(relation.getRelated().newQueryWithoutRelationships(), this)\n // Qualified after the existence query: on a self-referencing relation the related table has taken its alias.\n const target = column instanceof Expression\n ? column\n : new Expression(column === '*' ? '*' : this.connection.compile(this.grammar.wrap(query.getModel().qualifyColumn(column))).sql)\n const expression = fn && fn !== 'exists' ? new Expression(`${fn}(${target.value})`, target.bindings) : target\n query.select(expression)\n query.wheres.push(...relation.wheres)\n if (constraint) query.callScope((q) => constraint(q as unknown as AnyRelation))\n const scoped = query.applyScopes()\n scoped.orders = []\n if (scoped.columns.length > 1) scoped.columns = [scoped.columns[0]!]\n const columnName = (column instanceof Expression ? column.value : column).toLowerCase()\n const alias = as?.trim() ?? Str.snake(`${name} ${fn ?? ''} ${columnName}`.replace(/[^\\p{L}\\p{N}\\s_]/gu, ''))\n if (fn === 'exists') {\n this.columns.push({ query: scoped, as: alias, exists: true })\n this.withCasts({ [alias]: 'bool' })\n } else {\n this.selectSub(fn ? scoped : scoped.limit(1), alias)\n }\n }\n return this\n }\n\n /** Casts for selected columns, as if the model declared them: withCasts({ orders_sum_price: 'float' }). */\n withCasts(casts: Readonly<Record<string, CastDefinition>>): this {\n this.selectCasts = { ...this.selectCasts, ...casts }\n return this\n }\n\n /**\n * Rows that have related rows: has('comments'), has('comments', '>=', 3), has('comments.author').\n * Uses `exists (…)` for the common \"at least one\"/\"none\" cases and a count subquery otherwise.\n */\n has<const N extends RelationPath<M> | (string & {})>(relation: RelationPathArg<M, N>, operator?: string, count?: number, boolean?: 'and' | 'or', callback?: RelationConstraint): this\n has(this: Builder<UntypedModel>, relation: string, operator?: string, count?: number, boolean?: 'and' | 'or', callback?: RelationConstraint): this\n has(relation: string, operator = '>=', count = 1, boolean: 'and' | 'or' = 'and', callback?: RelationConstraint): this {\n const name = relation as string\n if (name.includes('.')) return this.hasNested(name, operator, count, boolean, callback)\n const instance = this.getRelation(name)\n const useExists = (operator === '>=' || operator === '<') && count === 1\n const query = useExists\n ? instance.getRelationExistenceQuery(instance.getRelated().newQueryWithoutRelationships(), this)\n : instance.getRelationExistenceCountQuery(instance.getRelated().newQueryWithoutRelationships(), this)\n query.wheres.push(...instance.wheres)\n if (callback) query.callScope((q) => callback(q as unknown as AnyRelation))\n const scoped = query.applyScopes()\n if (useExists) return this.whereExists(scoped, boolean, operator === '<')\n return this.whereSub(scoped, operator, count, boolean)\n }\n\n orHas<const N extends RelationPath<M> | (string & {})>(relation: RelationPathArg<M, N>, operator?: string, count?: number): this\n orHas(this: Builder<UntypedModel>, relation: string, operator?: string, count?: number): this\n orHas(relation: string, operator = '>=', count = 1): this {\n return this.has(relation as string, operator, count, 'or')\n }\n\n doesntHave<const N extends RelationPath<M> | (string & {})>(relation: RelationPathArg<M, N>, boolean?: 'and' | 'or', callback?: RelationConstraint): this\n doesntHave(this: Builder<UntypedModel>, relation: string, boolean?: 'and' | 'or', callback?: RelationConstraint): this\n doesntHave(relation: string, boolean: 'and' | 'or' = 'and', callback?: RelationConstraint): this {\n return this.has(relation as string, '<', 1, boolean, callback)\n }\n\n orDoesntHave<const N extends RelationPath<M> | (string & {})>(relation: RelationPathArg<M, N>): this\n orDoesntHave(this: Builder<UntypedModel>, relation: string): this\n orDoesntHave(relation: string): this {\n return this.doesntHave(relation as string, 'or')\n }\n\n /** Rows with related rows matching the callback: whereHas('comments', (q) => q.where('approved', true)). */\n whereHas<const N extends RelationPath<M> | (string & {})>(relation: RelationPathArg<M, N>, callback?: RelationConstraint, operator?: string, count?: number): this\n whereHas(this: Builder<UntypedModel>, relation: string, callback?: RelationConstraint, operator?: string, count?: number): this\n whereHas(relation: string, callback?: RelationConstraint, operator = '>=', count = 1): this {\n return this.has(relation as string, operator, count, 'and', callback)\n }\n\n orWhereHas<const N extends RelationPath<M> | (string & {})>(relation: RelationPathArg<M, N>, callback?: RelationConstraint, operator?: string, count?: number): this\n orWhereHas(this: Builder<UntypedModel>, relation: string, callback?: RelationConstraint, operator?: string, count?: number): this\n orWhereHas(relation: string, callback?: RelationConstraint, operator = '>=', count = 1): this {\n return this.has(relation as string, operator, count, 'or', callback)\n }\n\n whereDoesntHave<const N extends RelationPath<M> | (string & {})>(relation: RelationPathArg<M, N>, callback?: RelationConstraint): this\n whereDoesntHave(this: Builder<UntypedModel>, relation: string, callback?: RelationConstraint): this\n whereDoesntHave(relation: string, callback?: RelationConstraint): this {\n return this.doesntHave(relation as string, 'and', callback)\n }\n\n orWhereDoesntHave<const N extends RelationPath<M> | (string & {})>(relation: RelationPathArg<M, N>, callback?: RelationConstraint): this\n orWhereDoesntHave(this: Builder<UntypedModel>, relation: string, callback?: RelationConstraint): this\n orWhereDoesntHave(relation: string, callback?: RelationConstraint): this {\n return this.doesntHave(relation as string, 'or', callback)\n }\n\n /** has('comments.author'): whereHas('comments', q => q.has('author')) */\n private hasNested(relation: string, operator: string, count: number, boolean: 'and' | 'or', callback?: RelationConstraint): this {\n const [first = '', ...rest] = relation.split('.')\n return this.has(first, '>=', 1, boolean, (query) => {\n query.has(rest.join('.'), operator, count, 'and', callback)\n })\n }\n\n private normalizeRelationSpecs(relations: readonly LooseSpec[]): Array<[string, RelationConstraint | undefined]> {\n const specs: Array<[string, RelationConstraint | undefined]> = []\n for (const spec of relations) {\n if (typeof spec === 'string') specs.push([spec, undefined])\n else if (Array.isArray(spec)) for (const name of spec) specs.push([name, undefined])\n else specs.push(...Object.entries(spec))\n }\n return specs\n }\n\n /** Models from raw rows, marked as existing. */\n hydrate(rows: readonly Row[]): M[] {\n const casts = Object.keys(this.selectCasts).length ? this.selectCasts : undefined\n return rows.map((row) => {\n const model = this.model.newFromBuilder(row) as M\n return casts ? model.mergeCasts(casts) : model\n })\n }\n\n override async aggregate(fn: 'count' | 'min' | 'max' | 'sum' | 'avg', column: ColumnRef): Promise<unknown> {\n return QueryBuilder.prototype.aggregate.call(this.applyScopes(), fn, column)\n }\n\n override async exists(): Promise<boolean> {\n return QueryBuilder.prototype.exists.call(this.applyScopes())\n }\n\n /** The column's values, through the model's casts and accessors. */\n override async pluck<V = unknown>(column: Column<M>): Promise<Collection<V>> {\n const query = this.applyScopes().clone()\n const rows = (await QueryBuilder.prototype.runSelect.call(query.select(column))) as unknown as Row[]\n const key = column.includes('.') ? column.slice(column.lastIndexOf('.') + 1) : column\n return new Collection(rows.map((row) => this.model.newInstance().setRawAttributes({ [key]: row[key] }).getAttribute<V>(key)))\n }\n\n /** Whether `id` can't be one of the model's unique ids (not a UUID for HasUuids): it matches no row. */\n protected isMalformedKey(id: unknown): boolean {\n return this.model.uniqueIds().includes(this.model.getKeyName()) && !this.model.isValidUniqueId(id)\n }\n\n /**\n * A model by its key, or undefined; with an array of keys, the models found, as a collection (Laravel's find()). A\n * malformed unique id (HasUuids, HasUlids) finds nothing without a query, as route model binding does. A key typed\n * `unknown` (a request input) may be an array at run time, so its result is a model or a collection.\n */\n override find(ids: readonly unknown[]): Promise<EloquentCollection<M>>\n override find(id: ModelKey | null | undefined): Promise<M | undefined>\n override find(id: unknown): Promise<M | EloquentCollection<M> | undefined>\n override async find(id: unknown): Promise<M | undefined | EloquentCollection<M>> {\n if (Array.isArray(id)) return this.findMany(id)\n if (this.isMalformedKey(id)) return undefined\n return this.clone().whereKey(id).first()\n }\n\n async findMany(ids: readonly unknown[]): Promise<EloquentCollection<M>> {\n const keys = ids.filter((id) => !this.isMalformedKey(id))\n if (!keys.length) return this.model.newCollection<M>([])\n return this.clone().whereKey(keys).get()\n }\n\n /** find(), or ModelNotFoundError (a 404). With an array, every id must exist. */\n async findOrFail(ids: readonly unknown[]): Promise<EloquentCollection<M>>\n async findOrFail(id: ModelKey | null | undefined): Promise<M>\n async findOrFail(id: unknown): Promise<M | EloquentCollection<M>>\n async findOrFail(id: unknown): Promise<M | EloquentCollection<M>> {\n if (Array.isArray(id)) {\n const models = await this.findMany(id)\n if (models.count() !== new Set(id.map(String)).size) throw new ModelNotFoundError(this.model.constructor.name, id)\n return models\n }\n const model = await this.find(id as ModelKey)\n if (!model) throw new ModelNotFoundError(this.model.constructor.name, [id])\n return model\n }\n\n async findOr<R>(ids: readonly unknown[], callback: () => R | Promise<R>): Promise<EloquentCollection<M> | R>\n async findOr<R>(id: ModelKey | null | undefined, callback: () => R | Promise<R>): Promise<M | R>\n async findOr<R>(id: unknown, callback: () => R | Promise<R>): Promise<M | EloquentCollection<M> | R>\n async findOr<R>(id: unknown, callback: () => R | Promise<R>): Promise<M | EloquentCollection<M> | R> {\n return (await this.find(id)) ?? callback()\n }\n\n async firstOrFail(): Promise<M> {\n const model = await this.first()\n if (!model) throw new ModelNotFoundError(this.model.constructor.name)\n return model\n }\n\n async firstOr<R>(callback: () => R | Promise<R>): Promise<M | R> {\n return (await this.first()) ?? callback()\n }\n\n async firstWhere(column: Column<M> | Expression, operatorOrValue: unknown, value?: unknown): Promise<M | undefined> {\n const query = this.clone()\n return (value === undefined ? query.where(column, operatorOrValue) : query.where(column, String(operatorOrValue), value)).first()\n }\n\n // ---------------------------------------------------------------- creating and updating\n\n /** A new, unsaved model of this query's class (mass assignment rules apply). */\n newModelInstance(attributes: Row = {}): M {\n return this.model.newInstance(attributes) as M\n }\n\n /** With generated types, `attributes` is checked (WriteAttributes): each key a column or a set mutator's, each value its type. */\n make<const T extends object = Row>(attributes?: T & WriteAttributes<M, T>): M\n make(this: Builder<UntypedModel>, attributes?: Row): M\n make(attributes?: Row): M {\n return this.newModelInstance((attributes ?? {}) as Row)\n }\n\n create<const T extends object = Row>(attributes?: T & WriteAttributes<M, T>): Promise<M>\n create(this: Builder<UntypedModel>, attributes?: Row): Promise<M>\n async create(attributes?: Row): Promise<M> {\n const model = this.newModelInstance((attributes ?? {}) as Row)\n await model.save()\n return model\n }\n\n /** Creates without mass assignment protection. Never pass it request input. */\n forceCreate<const T extends object = Row>(attributes: T & WriteAttributes<M, T>): Promise<M>\n forceCreate(this: Builder<UntypedModel>, attributes: Row): Promise<M>\n async forceCreate(attributes: Row): Promise<M> {\n const model = this.newModelInstance().forceFill(attributes as Row)\n await model.save()\n return model\n }\n\n /** The first match, or a new unsaved model with attributes + values. */\n firstOrNew<const A extends object = Row, const V extends object = Row>(attributes: A & WriteAttributes<M, A>, values?: V & WriteAttributes<M, V>): Promise<M>\n firstOrNew(this: Builder<UntypedModel>, attributes: Row, values?: Row): Promise<M>\n async firstOrNew(attributes: Row, values?: Row): Promise<M> {\n const where = attributes as Row\n return (await this.clone().where(where).first()) ?? this.newModelInstance({ ...where, ...((values ?? {}) as Row) })\n }\n\n /** The first match, or a new saved model. A concurrent insert of the same unique key returns that row instead. */\n firstOrCreate<const A extends object = Row, const V extends object = Row>(attributes: A & WriteAttributes<M, A>, values?: V & WriteAttributes<M, V>): Promise<M>\n firstOrCreate(this: Builder<UntypedModel>, attributes: Row, values?: Row): Promise<M>\n async firstOrCreate(attributes: Row, values?: Row): Promise<M> {\n return (await this.clone().where(attributes as Row).first()) ?? this.createOrFirst(attributes as Row, (values ?? {}) as Row)\n }\n\n /** Tries to create; on a unique constraint violation, returns the existing row (Laravel's createOrFirst()). */\n createOrFirst<const A extends object = Row, const V extends object = Row>(attributes: A & WriteAttributes<M, A>, values?: V & WriteAttributes<M, V>): Promise<M>\n createOrFirst(this: Builder<UntypedModel>, attributes: Row, values?: Row): Promise<M>\n async createOrFirst(attributes: Row, values?: Row): Promise<M> {\n const where = attributes as Row\n const extra = (values ?? {}) as Row\n try {\n const connection = this.connection\n const create = () => this.create({ ...where, ...extra } as Row)\n // A failed insert aborts a Postgres transaction, so run it in a savepoint when one is open.\n return connection.transactionLevel() > 0 ? await connection.transaction(create) : await create()\n } catch (error) {\n if (!isUniqueViolation(error)) throw error\n const existing = await this.clone().where(where).first()\n if (!existing) throw error\n return existing\n }\n }\n\n /** Updates the first match with values, or creates it. */\n updateOrCreate<const A extends object = Row, const V extends object = Row>(attributes: A & WriteAttributes<M, A>, values?: V & WriteAttributes<M, V>): Promise<M>\n updateOrCreate(this: Builder<UntypedModel>, attributes: Row, values?: Row): Promise<M>\n async updateOrCreate(attributes: Row, values?: Row): Promise<M> {\n const extra = (values ?? {}) as Row\n const model = await this.firstOrCreate(attributes as Row, extra)\n if (!model.wasRecentlyCreated) await model.fill(extra).save()\n return model\n }\n\n /** Mass update (no model events); sets updated_at when the model uses timestamps. */\n override update<const T extends object = Row>(values: T & WriteAttributes<M, T>): Promise<number>\n override update(this: Builder<UntypedModel>, values: Row): Promise<number>\n override async update(values: Row): Promise<number> {\n return QueryBuilder.prototype.update.call(this.applyScopes(), this.addUpdatedAtColumn(values as Row))\n }\n\n /** Mass delete (no model events). With soft deletes this sets deleted_at on the matching rows instead. */\n override async delete(): Promise<number> {\n if (this.model.usesSoftDeletes()) {\n return this.update({ [this.model.getDeletedAtColumn()]: formatDateTime(this.model.freshTimestamp()) })\n }\n return this.forceDelete()\n }\n\n /** Deletes the matching rows for real, even with soft deletes. */\n async forceDelete(): Promise<number> {\n return QueryBuilder.prototype.delete.call(this.applyScopes())\n }\n\n // ---------------------------------------------------------------- soft deletes\n\n /** Includes soft-deleted rows (withTrashed(false) is withoutTrashed()). */\n withTrashed(withTrashed = true): this {\n return withTrashed ? this.withoutGlobalScope(SoftDeletingScope) : this.withoutTrashed()\n }\n\n /** Excludes soft-deleted rows explicitly. */\n withoutTrashed(): this {\n return super.whereNull(this.model.getQualifiedDeletedAtColumn()).withoutGlobalScope(SoftDeletingScope)\n }\n\n /** Only soft-deleted rows. */\n onlyTrashed(): this {\n return super.whereNotNull(this.model.getQualifiedDeletedAtColumn()).withoutGlobalScope(SoftDeletingScope)\n }\n\n /** Restores every matching row (deleted_at = null), trashed or not. */\n async restore(): Promise<number> {\n return this.withTrashed().update({ [this.model.getDeletedAtColumn()]: null })\n }\n\n protected addUpdatedAtColumn(values: Row): Row {\n const column = this.model.getUpdatedAtColumn()\n if (!this.model.usesTimestamps() || !column || Object.hasOwn(values, column)) return values\n return { ...values, [column]: formatDateTime(this.model.freshTimestamp()) }\n }\n\n // ---------------------------------------------------------------- plumbing\n\n override toSql(): string {\n return QueryBuilder.prototype.toSql.call(this.applyScopes())\n }\n\n override getBindings(): unknown[] {\n return QueryBuilder.prototype.getBindings.call(this.applyScopes())\n }\n\n override clone(): Builder<M> {\n const copy = super.clone() as Builder<M>\n copy.scopes = new Map(this.scopes)\n copy.removedScopes = [...this.removedScopes]\n copy.eagerLoad = new Map(this.eagerLoad)\n copy.selectCasts = { ...this.selectCasts }\n return new Proxy(copy, handler as ProxyHandler<Builder<M>>)\n }\n\n /** Nested where groups get a builder of the same model (without global scopes), so local scopes work inside them. */\n override newQuery(): QueryBuilder<Row> {\n return this.model.newModelQuery() as unknown as QueryBuilder<Row>\n }\n\n /** chunk() and lazy() order by the primary key when the query has no order. */\n protected override enforceOrderBy(): void {\n if (!this.orders.length) this.orderBy(this.model.getQualifiedKeyName() as Column<M>, 'asc')\n }\n\n protected override defaultKeyName(): string {\n return this.model.getKeyName()\n }\n\n protected override defaultPerPage(): number {\n return this.model.getPerPage()\n }\n}\n","/**\n * While eager loading, relation methods are called only to learn the relation's shape, so their per-parent\n * constraints (where post_id = ?) must be skipped (Laravel's Relation::noConstraints()). Relation methods are\n * synchronous, so a counter is enough.\n */\nlet disabled = 0\n\nexport function withoutRelationConstraints<T>(fn: () => T): T {\n disabled++\n try {\n return fn()\n } finally {\n disabled--\n }\n}\n\nexport const relationConstraintsEnabled = (): boolean => disabled === 0\n","import type { Builder } from './Builder'\nimport type { Model } from './Model'\nimport type { Scope } from './Scope'\n\n/**\n * Hides soft-deleted rows: where deleted_at is null. Registered for every model with `softDeletes = true`.\n * Builder.withTrashed()/onlyTrashed()/withoutTrashed() remove or replace it.\n */\nexport class SoftDeletingScope implements Scope {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n apply(builder: Builder<any>, model: Model): void {\n builder.whereNull(model.getQualifiedDeletedAtColumn())\n }\n}\n","import { isDeepStrictEqual } from 'node:util'\nimport type { Row } from '@orieljs/contracts'\nimport { Collection } from '@orieljs/collections'\nimport { InvalidCastError, LogicError } from '../errors'\nimport { formatDate, formatDateTime, parseDateTime } from '../Query/values'\n\n/**\n * A custom cast (Laravel's CastsAttributes): get() turns the stored value into what the model exposes, set() turns\n * an assigned value back into what is stored.\n */\nexport interface CastsAttributes<TGet = unknown, TSet = TGet> {\n get(model: object, key: string, value: unknown, attributes: Row): TGet\n set(model: object, key: string, value: TSet, attributes: Row): unknown\n}\n\n/** A TypeScript enum object (string or numeric) used as a cast: casts = { status: PostStatus }. */\nexport type EnumLike = Record<string, string | number>\n\nexport type BuiltInCast =\n | 'int' | 'integer' | 'float' | 'double' | 'real' | 'string' | 'bool' | 'boolean'\n | 'array' | 'json' | 'object' | 'collection'\n | 'date' | 'datetime' | 'immutable_date' | 'immutable_datetime' | 'timestamp'\n | 'hashed'\n | `decimal:${number}`\n\nexport type CastDefinition = BuiltInCast | EnumLike | CastsAttributes | (new () => CastsAttributes)\n\nconst JSON_CASTS = new Set(['array', 'json', 'object', 'collection'])\nconst DATE_CASTS = new Set(['date', 'datetime', 'immutable_date', 'immutable_datetime'])\nconst PRIMITIVE_CASTS = new Set(['int', 'integer', 'float', 'double', 'real', 'string', 'bool', 'boolean', 'timestamp'])\n/** Laravel's hashed cast: the model hashes the assigned value when it is saved (Model.save()). */\nconst HASHED_CAST = 'hashed'\n\nconst isCustom = (cast: CastDefinition): cast is CastsAttributes =>\n typeof cast === 'object' && typeof (cast as Partial<CastsAttributes>).get === 'function' && typeof (cast as Partial<CastsAttributes>).set === 'function'\n\nconst isCustomClass = (cast: CastDefinition): cast is new () => CastsAttributes => typeof cast === 'function'\n\nconst isEnum = (cast: CastDefinition): cast is EnumLike => typeof cast === 'object' && !isCustom(cast)\n\n/** Builds the custom cast instance for a class-valued cast (cached per class). */\nconst instances = new WeakMap<new () => CastsAttributes, CastsAttributes>()\nfunction customCaster(cast: CastsAttributes | (new () => CastsAttributes)): CastsAttributes {\n if (!isCustomClass(cast)) return cast\n let instance = instances.get(cast)\n if (!instance) instances.set(cast, (instance = new cast()))\n return instance\n}\n\n/** The values of a TypeScript enum. Numeric enums also map values back to names; those reverse entries are skipped. */\nexport function enumValues(cast: EnumLike): Array<string | number> {\n return Object.entries(cast)\n .filter(([key]) => !/^\\d+$/.test(key))\n .map(([, value]) => value)\n}\n\nexport const isJsonCast = (cast: CastDefinition | undefined): boolean => typeof cast === 'string' && JSON_CASTS.has(cast)\nexport const isDateCast = (cast: CastDefinition | undefined): boolean => typeof cast === 'string' && DATE_CASTS.has(cast)\nexport const isHashedCast = (cast: CastDefinition | undefined): boolean => cast === HASHED_CAST\n/** A cast whose value is a class instance, so dirty checks and serialization go through custom logic. */\nexport const isCustomCast = (cast: CastDefinition | undefined): boolean => cast !== undefined && (isCustom(cast) || isCustomClass(cast))\n\nconst decimalPlaces = (cast: string): number | undefined => (cast.startsWith('decimal:') ? Number(cast.slice(8)) : undefined)\n\nconst isBuiltInCast = (cast: string): boolean =>\n JSON_CASTS.has(cast) || DATE_CASTS.has(cast) || PRIMITIVE_CASTS.has(cast) || cast === HASHED_CAST || /^decimal:\\d+$/.test(cast)\n\n/** Throws InvalidCastError for a cast string that isn't one of the built-in casts. */\nfunction assertBuiltInCast(cast: string, key: string, className: string): void {\n if (!isBuiltInCast(cast)) throw new InvalidCastError(className, key, cast)\n}\n\nconst toBoolean = (value: unknown): boolean => {\n if (typeof value === 'boolean') return value\n if (typeof value === 'number' || typeof value === 'bigint') return Number(value) !== 0\n const text = String(value).toLowerCase()\n return !(text === '' || text === '0' || text === 'f' || text === 'false')\n}\n\n/** Laravel's castAttribute(): the stored value → the value the model exposes. null stays null (except custom casts). */\nexport function castGet(model: object, key: string, cast: CastDefinition, value: unknown, attributes: Row, className: string): unknown {\n if (isCustom(cast) || isCustomClass(cast)) return customCaster(cast).get(model, key, value, attributes)\n if (typeof cast === 'string') assertBuiltInCast(cast, key, className)\n if (value === null || value === undefined) return value\n if (isEnum(cast)) {\n const allowed = enumValues(cast)\n const match = allowed.find((candidate) => candidate === value || String(candidate) === String(value))\n if (match === undefined) throw new LogicError(`\"${String(value)}\" is not a valid backing value for the cast of [${key}] on [${className}].`)\n return match\n }\n const places = decimalPlaces(cast)\n if (places !== undefined) return Number(value).toFixed(places)\n switch (cast) {\n case 'int': case 'integer':\n return Math.trunc(Number(value))\n case 'float': case 'double': case 'real':\n return Number(value)\n case 'string':\n return String(value)\n case 'bool': case 'boolean':\n return toBoolean(value)\n case 'array': case 'json': case 'object':\n // Postgres and MySQL drivers hand back json columns already parsed; copy them so the original stays intact.\n return typeof value === 'string' ? JSON.parse(value) : structuredClone(value)\n case 'collection':\n return new Collection((typeof value === 'string' ? JSON.parse(value) : structuredClone(value)) as unknown[])\n case 'date': case 'immutable_date': {\n const date = parseDateTime(value)\n date.setUTCHours(0, 0, 0, 0)\n return date\n }\n case 'datetime': case 'immutable_datetime':\n return parseDateTime(value)\n case 'timestamp':\n return Math.floor(parseDateTime(value).getTime() / 1000)\n }\n return value\n}\n\n/** The value assigned to a cast attribute → the value stored in the model's attributes (and later bound). */\nexport function castSet(model: object, key: string, cast: CastDefinition, value: unknown, attributes: Row, className: string): unknown {\n if (isCustom(cast) || isCustomClass(cast)) return customCaster(cast).set(model, key, value, attributes)\n if (typeof cast === 'string') assertBuiltInCast(cast, key, className)\n if (value === null || value === undefined) return null\n if (isEnum(cast)) return castGet(model, key, cast, value, attributes, className)\n if (typeof cast !== 'string') return value\n if (JSON_CASTS.has(cast)) return JSON.stringify(value instanceof Collection ? value.all() : value)\n if (cast === 'date' || cast === 'immutable_date') return formatDate(parseDateTime(value))\n if (cast === 'datetime' || cast === 'immutable_datetime') return formatDateTime(parseDateTime(value))\n if (cast === 'timestamp') return formatDateTime(typeof value === 'number' ? new Date(value * 1000) : parseDateTime(value))\n return value\n}\n\n/**\n * Laravel's originalIsEquivalent(): does the stored value still mean the same thing as the original?\n * Keeps save() from writing columns whose value only changed representation (1 vs true, '5' vs 5, same instant).\n */\nexport function isEquivalent(cast: CastDefinition | undefined, current: unknown, original: unknown, model: object, key: string, className: string): boolean {\n if (current === original) return true\n if (current === null || current === undefined || original === null || original === undefined) return false\n if (cast !== undefined) {\n if (isDateCast(cast) || cast === 'timestamp') {\n return parseDateTime(current).getTime() === parseDateTime(original).getTime()\n }\n if (typeof cast === 'string' && ['float', 'double', 'real'].includes(cast)) {\n return Math.abs(Number(current) - Number(original)) < Number.EPSILON * 4\n }\n const read = (value: unknown) => castGet(model, key, cast, value, {}, className)\n if (typeof cast === 'string' && (JSON_CASTS.has(cast) || PRIMITIVE_CASTS.has(cast) || cast.startsWith('decimal:'))) {\n const a = read(current)\n const b = read(original)\n return isDeepStrictEqual(a instanceof Collection ? a.all() : a, b instanceof Collection ? b.all() : b)\n }\n if (isEnum(cast)) return String(current) === String(original)\n }\n const numeric = (value: unknown) => (typeof value === 'number' || (typeof value === 'string' && value.trim() !== '' && !Number.isNaN(Number(value))))\n return numeric(current) && numeric(original) && Number(current) === Number(original)\n}\n","import { Collection, type Operator } from '@orieljs/collections'\nimport { LogicError, ModelNotFoundError } from '../errors'\nimport type { Expression } from '../Query/Expression'\nimport type { Builder, EagerLoadSpec } from './Builder'\nimport type { Model } from './Model'\nimport type { Aggregates, AggregateSpecs, Column, EagerLoads, LoadedTree, LooseSpec, ModelKey, UntypedModel, WithLoaded } from './types'\n\n/** Laravel's getDictionaryKey(): keys compare as text, so 1 and '1' are the same model. */\nconst dictionaryKey = (key: unknown): string => String(key)\n\nconst isModel = (value: unknown): value is Model =>\n typeof value === 'object' && value !== null && typeof (value as Partial<Model>).getKey === 'function' &&\n typeof (value as Partial<Model>).relationLoaded === 'function'\n\n/**\n * One model per key, in the models' order: a key keeps its first position and its last instance, as a PHP array\n * keyed by the model keys does (a plain object would list integer-like keys first, in ascending order).\n */\nfunction uniqueByKey<M extends Model>(models: readonly M[]): M[] {\n return [...new Map(models.map((model) => [dictionaryKey(model.getKey()), model])).values()]\n}\n\n/** The models a loaded relation holds: a collection's models, a model, or none. */\nfunction relatedModels(value: unknown): Model[] {\n if (value instanceof Collection) return (value.all() as unknown[]).filter(isModel)\n return isModel(value) ? [value] : []\n}\n\n/**\n * Laravel's Eloquent collection: what every query, relation and eager load of models returns. It is a support\n * Collection (methods that keep the items keep this class; map() and the other type-changing methods return a plain\n * Collection) with the model-aware methods: find() by key, load() and loadCount() for every model at once, fresh(),\n * modelKeys(), toQuery(), and diff()/intersect()/unique()/only()/except()/merge() that compare models by key.\n */\nexport class EloquentCollection<M extends Model = Model> extends Collection<M> {\n /** The model with this key (or this model's key), else the default; with several keys, those models. */\n find(key: readonly unknown[] | Collection<unknown>): this\n find(key: ModelKey | Model | null | undefined): M | undefined\n find<D>(key: ModelKey | Model | null | undefined, defaultValue: D): M | D\n /** A key typed `unknown` may be a list at run time: a model or this collection's kind. */\n find(key: unknown): M | this | undefined\n find<D>(key: unknown, defaultValue: D): M | this | D\n find(key: unknown, defaultValue?: unknown): unknown {\n const value = isModel(key) ? key.getKey() : key instanceof Collection ? key.all() : key\n if (Array.isArray(value)) {\n const wanted = new Set(value.map(dictionaryKey))\n return this.filter((model) => wanted.has(dictionaryKey(model.getKey())))\n }\n return this.first((model) => dictionaryKey(model.getKey()) === dictionaryKey(value), defaultValue)\n }\n\n /** find(), or ModelNotFoundError naming the missing keys. */\n findOrFail(keys: readonly unknown[] | Collection<unknown>): this\n findOrFail(key: ModelKey | Model | null | undefined): M\n findOrFail(key: unknown): M | this\n findOrFail(key: unknown): M | this {\n const value = key instanceof Collection ? key.all() : key\n if (Array.isArray(value)) {\n const found = this.find(value)\n const keys = [...new Map(value.map((id) => [dictionaryKey(id), id])).values()]\n if (found.count() === keys.length) return found\n const present = new Set(found.modelKeys().map(dictionaryKey))\n throw new ModelNotFoundError(this.first()?.constructor.name ?? 'Model', keys.filter((id) => !present.has(dictionaryKey(id))))\n }\n const model = this.find(value)\n if (model !== undefined) return model\n throw new ModelNotFoundError(this.first()?.constructor.name ?? 'Model', [isModel(value) ? value.getKey() : value])\n }\n\n /** The primary keys, in order. */\n modelKeys(): unknown[] {\n return this.items.map((model) => model.getKey())\n }\n\n /** The models keyed by their primary key (as text). */\n getDictionary(items: Iterable<M> = this.items): Record<string, M> {\n const dictionary: Record<string, M> = {}\n for (const model of items) dictionary[dictionaryKey(model.getKey())] = model\n return dictionary\n }\n\n /** The same models in a plain Collection. */\n toBase(): Collection<M> {\n return new Collection(this.items)\n }\n\n /** Whether a model with this key (or this model) is in the collection; the other forms are Collection's. */\n override contains(key: keyof M & string, value: unknown): boolean\n override contains(key: (keyof M & string) | ((item: M) => unknown), operator: Operator, value: unknown): boolean\n override contains(callback: (item: M) => boolean): boolean\n override contains(value: unknown): boolean\n override contains(...args: unknown[]): boolean {\n if (args.length > 1 || typeof args[0] === 'function') return Reflect.apply(Collection.prototype.contains, this, args) as boolean\n const [key] = args\n if (isModel(key)) return this.items.some((model) => model.is(key))\n return this.items.some((model) => dictionaryKey(model.getKey()) === dictionaryKey(key))\n }\n\n /** Collection's containsStrict(): a model matches only itself (no key matching). */\n override containsStrict(key: keyof M & string, value: unknown): boolean\n override containsStrict(callback: (item: M) => boolean): boolean\n override containsStrict(value: unknown): boolean\n override containsStrict(...args: unknown[]): boolean {\n return Reflect.apply(Collection.prototype.contains, this, args) as boolean\n }\n\n /** Collection's doesntContainStrict(): a model matches only itself (no key matching). */\n override doesntContainStrict(key: keyof M & string, value: unknown): boolean\n override doesntContainStrict(callback: (item: M) => boolean): boolean\n override doesntContainStrict(value: unknown): boolean\n override doesntContainStrict(...args: unknown[]): boolean {\n return !(Reflect.apply(Collection.prototype.contains, this, args) as boolean)\n }\n\n /** Eager loads relations onto every model, one query per relation: await posts.load('author', 'comments.author'). */\n load<const S extends readonly LooseSpec[]>(...relations: EagerLoads<M, S>): Promise<EloquentCollection<WithLoaded<M, LoadedTree<S>>> & this>\n load(this: EloquentCollection<UntypedModel>, ...relations: LooseSpec[]): Promise<this>\n async load(...relations: LooseSpec[]): Promise<this> {\n const first = this.first()\n if (!first || !relations.length) return this as never\n await first.newQueryWithoutRelationships().with(...(relations as readonly LooseSpec[] as never[])).eagerLoadRelations(this.items)\n return this as never\n }\n\n /** Loads only the relations that aren't loaded yet; nested paths are followed into the loaded relations. */\n loadMissing<const S extends readonly string[]>(...relations: EagerLoads<M, S>): Promise<EloquentCollection<WithLoaded<M, LoadedTree<S>>> & this>\n loadMissing(this: EloquentCollection<UntypedModel>, ...relations: string[]): Promise<this>\n async loadMissing(...relations: string[]): Promise<this> {\n await loadMissingOn(this.items, [...(relations as readonly string[])])\n return this as never\n }\n\n /** Adds <relation>_count attributes to every model with one query: await posts.loadCount('comments'). */\n loadCount<const S extends readonly LooseSpec[]>(...relations: Aggregates<M, S>): Promise<this>\n loadCount(this: EloquentCollection<UntypedModel>, ...relations: LooseSpec[]): Promise<this>\n loadCount(...relations: LooseSpec[]): Promise<this> {\n return this.loadAggregate(relations as never, '*', 'count')\n }\n\n /**\n * Laravel's loadAggregate(): withAggregate() for models already loaded, with one query for the whole collection.\n * The values become clean attributes (with their casts: loadExists() gives booleans).\n */\n loadAggregate<const S extends LooseSpec | readonly LooseSpec[]>(relations: AggregateSpecs<M, S>, column: string | Expression, fn?: string): Promise<this>\n loadAggregate(this: EloquentCollection<UntypedModel>, relations: LooseSpec | readonly LooseSpec[], column: string | Expression, fn?: string): Promise<this>\n async loadAggregate(relations: LooseSpec | readonly LooseSpec[], column: string | Expression, fn?: string): Promise<this> {\n const first = this.first()\n if (!first || ![relations].flat().length) return this\n const keyName = first.getKeyName()\n const rows = await first.newModelQuery().whereKey(this.modelKeys()).select(keyName as Column<M>).withAggregate(relations, column, fn).get()\n const byKey = new Map(rows.all().map((row) => [dictionaryKey(row.getKey()), row]))\n for (const model of this.items) {\n const row = byKey.get(dictionaryKey(model.getKey()))\n if (!row) continue\n const values = Object.fromEntries(Object.entries(row.getAttributes()).filter(([name]) => name !== keyName))\n const casts = Object.fromEntries(Object.entries(row.getCasts()).filter(([name]) => Object.hasOwn(values, name)))\n model.forceFill(values).syncOriginalAttributes(...Object.keys(values)).mergeCasts(casts)\n }\n return this\n }\n\n /** Adds <relation>_sum_<column> to every model: await users.loadSum('orders', 'price'). */\n loadSum<const S extends LooseSpec | readonly LooseSpec[]>(relations: AggregateSpecs<M, S>, column: string | Expression): Promise<this>\n loadSum(this: EloquentCollection<UntypedModel>, relations: LooseSpec | readonly LooseSpec[], column: string | Expression): Promise<this>\n loadSum(relations: LooseSpec | readonly LooseSpec[], column: string | Expression): Promise<this> {\n return this.loadAggregate(relations as never, column, 'sum')\n }\n\n loadAvg<const S extends LooseSpec | readonly LooseSpec[]>(relations: AggregateSpecs<M, S>, column: string | Expression): Promise<this>\n loadAvg(this: EloquentCollection<UntypedModel>, relations: LooseSpec | readonly LooseSpec[], column: string | Expression): Promise<this>\n loadAvg(relations: LooseSpec | readonly LooseSpec[], column: string | Expression): Promise<this> {\n return this.loadAggregate(relations as never, column, 'avg')\n }\n\n loadMin<const S extends LooseSpec | readonly LooseSpec[]>(relations: AggregateSpecs<M, S>, column: string | Expression): Promise<this>\n loadMin(this: EloquentCollection<UntypedModel>, relations: LooseSpec | readonly LooseSpec[], column: string | Expression): Promise<this>\n loadMin(relations: LooseSpec | readonly LooseSpec[], column: string | Expression): Promise<this> {\n return this.loadAggregate(relations as never, column, 'min')\n }\n\n loadMax<const S extends LooseSpec | readonly LooseSpec[]>(relations: AggregateSpecs<M, S>, column: string | Expression): Promise<this>\n loadMax(this: EloquentCollection<UntypedModel>, relations: LooseSpec | readonly LooseSpec[], column: string | Expression): Promise<this>\n loadMax(relations: LooseSpec | readonly LooseSpec[], column: string | Expression): Promise<this> {\n return this.loadAggregate(relations as never, column, 'max')\n }\n\n /** Adds a boolean <relation>_exists to every model. */\n loadExists<const S extends readonly LooseSpec[]>(...relations: Aggregates<M, S>): Promise<this>\n loadExists(this: EloquentCollection<UntypedModel>, ...relations: LooseSpec[]): Promise<this>\n loadExists(...relations: LooseSpec[]): Promise<this> {\n return this.loadAggregate(relations as never, '*', 'exists')\n }\n\n /** The models as they are in the database now (without global scopes), with relations loaded; deleted ones drop out. */\n async fresh(...relations: EagerLoadSpec[]): Promise<this> {\n const first = this.first()\n if (!first) return this.newInstance()\n const fresh = this.getDictionary(await first.newQueryWithoutScopes().with(...relations).whereKey(this.modelKeys()).get())\n const models: M[] = []\n for (const model of this.items) {\n const found = model.exists ? fresh[dictionaryKey(model.getKey())] : undefined\n if (found) models.push(found)\n }\n return this.newInstance(models)\n }\n\n /** The models whose keys aren't in the given models. */\n override diff(items: Iterable<M>): this {\n const other = this.getDictionary(items)\n return this.filter((model) => !Object.hasOwn(other, dictionaryKey(model.getKey())))\n }\n\n /** The models whose keys are also in the given models. */\n override intersect(items: Iterable<M>): this {\n const other = this.getDictionary(items)\n return this.filter((model) => Object.hasOwn(other, dictionaryKey(model.getKey())))\n }\n\n /** One model per key (the last instance, at the first one's place); with a key or callback, Collection's unique(). */\n override unique(key?: (keyof M & string) | ((item: M) => unknown)): this {\n if (key !== undefined) return super.unique(key)\n return this.newInstance(uniqueByKey(this.items))\n }\n\n /** The models with these keys, in the collection's order. */\n override only(...keys: unknown[]): this {\n const wanted = new Set(keys.flat().map(dictionaryKey))\n return this.newInstance(uniqueByKey(this.items).filter((model) => wanted.has(dictionaryKey(model.getKey()))))\n }\n\n /** The models without these keys, in the collection's order. */\n override except(...keys: unknown[]): this {\n const unwanted = new Set(keys.flat().map(dictionaryKey))\n return this.newInstance(uniqueByKey(this.items).filter((model) => !unwanted.has(dictionaryKey(model.getKey()))))\n }\n\n /** Adds the given models, replacing the ones with the same key. */\n override merge(items: Iterable<M>): this {\n const dictionary = new Map(this.items.map((model) => [dictionaryKey(model.getKey()), model]))\n for (const model of items) dictionary.set(dictionaryKey(model.getKey()), model)\n return this.newInstance(dictionary.values())\n }\n\n makeHidden(...attributes: Array<string | string[]>): this {\n for (const model of this.items) model.makeHidden(...attributes)\n return this\n }\n\n makeVisible(...attributes: Array<string | string[]>): this {\n for (const model of this.items) model.makeVisible(...attributes)\n return this\n }\n\n setVisible(visible: string[]): this {\n for (const model of this.items) model.setVisible(visible)\n return this\n }\n\n setHidden(hidden: string[]): this {\n for (const model of this.items) model.setHidden(hidden)\n return this\n }\n\n append(...attributes: Array<string | string[]>): this {\n for (const model of this.items) model.append(...attributes)\n return this\n }\n\n /** A query of exactly these models (where key in …), for mass updates: await posts.toQuery().update({ … }). */\n toQuery(): Builder<M> {\n const first = this.first()\n if (!first) throw new LogicError('Unable to create query for empty collection.')\n if (this.items.some((model) => model.constructor !== first.constructor)) {\n throw new LogicError('Unable to create query for collection with mixed types.')\n }\n return first.newModelQuery().whereKey(this.modelKeys())\n }\n}\n\n/** loadMissing() for some models: loads each path's first relation where it is missing, then follows the rest. */\nasync function loadMissingOn(models: Model[], paths: string[]): Promise<void> {\n for (const path of paths) {\n const [head = '', ...rest] = path.split('.')\n const missing = models.filter((model) => !model.relationLoaded(head))\n if (missing.length) await missing[0]!.newQueryWithoutRelationships().with(path).eagerLoadRelations(missing)\n if (!rest.length) continue\n const related = models.flatMap((model) => relatedModels(model.getRelations()[head]))\n if (related.length) await loadMissingOn(related, [rest.join('.')])\n }\n}\n","import { existsSync, readdirSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport type { Row } from '@orieljs/contracts'\nimport { Collection } from '@orieljs/collections'\nimport { Str } from '@orieljs/support'\nimport { LogicError } from '../../errors'\nimport { formatDateTime } from '../../Query/values'\nimport type { EloquentCollection } from '../Collection'\nimport { Model } from '../Model'\nimport { BelongsTo } from '../Relations/BelongsTo'\nimport { BelongsToMany } from '../Relations/BelongsToMany'\nimport { HasOneOrMany } from '../Relations/HasOneOrMany'\nimport { MorphTo } from '../Relations/MorphTo'\n\ndeclare const MANY: unique symbol\n/** Type-level marker set by count(): make()/create() then return the model's Eloquent collection. */\nexport interface Many {\n readonly [MANY]: true\n}\n/** What make()/create() return: a model, or the model's Eloquent collection after count(), as Laravel's. */\nexport type FactoryResult<F, M extends Model> = F extends Many ? EloquentCollection<M> : M\n/** What raw() returns: the attributes, or a list of them after count(). */\nexport type RawResult<F> = F extends Many ? Row[] : Row\n\n/** Which model a state is being made for: its index in count() and the total. */\nexport interface StateContext {\n index: number\n count: number\n}\nexport type State = Row | ((attributes: Row, context: StateContext) => Row)\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyFactory = Factory<any>\n\n/**\n * What has() and for() need from a factory: its model, create(), createOne() and state(). A factory of any model,\n * counted or not, has them; Factory<any> itself would refuse a counted one, whose make(), create() and raw() return\n * lists.\n */\nexport interface RelatedFactory {\n readonly model: new () => Model\n create(attributes?: Row): Promise<unknown>\n createOne(attributes?: Row): Promise<Model>\n state(state: State): RelatedFactory\n}\n\n/**\n * A model's factory() typed as its own factory class (Laravel's `@use HasFactory<UserFactory>`): declare it in the\n * model, `declare static factory: HasFactory<UserFactory>` (with `import type`), and User.factory().unverified()\n * type-checks. The factory is still found at run time by name (database/factories/UserFactory.ts).\n */\nexport type HasFactory<F> = {\n (): F\n (count: number, state?: State): F & Many\n} & (typeof Model)['factory']\n\ninterface HasRelationship {\n factory: RelatedFactory\n relationship: string\n pivot: Row\n}\n\ninterface ForRelationship {\n parent: RelatedFactory | Model\n relationship: string\n}\n\n/** The for() parents one make()/create()/raw() call has resolved: shared by that call's models, made again by the next. */\ntype ResolvedParents = Map<ForRelationship, Model>\n\n/** The builder state newInstance() copies and changes. */\ninterface FactoryState<M extends Model> {\n countValue: number | undefined\n states: State[]\n hasRelations: HasRelationship[]\n forRelations: ForRelationship[]\n afterMakingCallbacks: Array<(model: M) => unknown>\n afterCreatingCallbacks: Array<(model: M) => unknown>\n}\n\nconst registry = new Map<typeof Model, new () => AnyFactory>()\n\n/**\n * Laravel's model factories: `class UserFactory extends Factory<User> { model = User; definition() { … } }`,\n * then `await User.factory().count(3).create()`, `UserFactory.new().unverified().make()`.\n * Every builder method returns a new factory, so a base factory can be reused.\n */\nexport abstract class Factory<M extends Model = Model> {\n /** The model class this factory makes. */\n abstract model: new () => M\n\n /** The default attributes. Values may be factories (created for their key) or (attributes) => value functions. */\n abstract definition(): Row\n\n protected countValue: number | undefined\n protected states: State[] = []\n protected hasRelations: HasRelationship[] = []\n protected forRelations: ForRelationship[] = []\n protected afterMakingCallbacks: Array<(model: M) => unknown> = []\n protected afterCreatingCallbacks: Array<(model: M) => unknown> = []\n\n /** A new factory with the given state (Laravel's Factory::new()). */\n static new<F extends AnyFactory>(this: new () => F, state?: State): F {\n const factory = new this().configure() as F\n return state ? factory.state(state) : factory\n }\n\n /** Registers factory classes for Model.factory() (discoverFactories() does this for database/factories). */\n static register(...factories: Array<new () => AnyFactory>): void {\n for (const factory of factories) registry.set(new factory().model as unknown as typeof Model, factory)\n }\n\n /** The registered factory for a model class. */\n static forModel<M extends Model>(model: new () => M): Factory<M> {\n const factory = registry.get(model as unknown as typeof Model)\n if (!factory) {\n throw new LogicError(`No factory registered for [${model.name}]. Add database/factories/${model.name}Factory.ts (default export) or call Factory.register().`)\n }\n return new factory().configure() as unknown as Factory<M>\n }\n\n /** Hook for afterMaking()/afterCreating() registrations; runs in new(). */\n configure(): this {\n return this\n }\n\n /** How many models make()/create() produce; they then return a Collection. */\n count(count: number): this & Many {\n return this.newInstance({ countValue: count }) as this & Many\n }\n\n /** Overrides attributes: state({ admin: true }) or state((attributes) => ({ … })). */\n state(state: State): this {\n return this.newInstance({ states: [...this.states, state] })\n }\n\n /** Cycles through states per model: sequence({ role: 'admin' }, { role: 'user' }). */\n sequence(...states: State[]): this {\n return this.state((attributes, context) => {\n const state = states[context.index % states.length]!\n return typeof state === 'function' ? state(attributes, context) : state\n })\n }\n\n /** deleted_at = now, for soft-deleting models. */\n trashed(): this {\n return this.state((_attributes) => ({ [new this.model().getDeletedAtColumn()]: formatDateTime(new Date()) }))\n }\n\n /** Creates related models for each created model: has(Post.factory().count(3)) (relationship default: 'posts'). */\n has(factory: RelatedFactory, relationship?: string, pivot: Row = {}): this {\n const name = relationship ?? Str.camel(Str.plural(new factory.model().constructor.name))\n return this.newInstance({ hasRelations: [...this.hasRelations, { factory, relationship: name, pivot }] })\n }\n\n /**\n * Sets a belongsTo parent: for(User.factory()) or for(user) (relationship default: 'user'). A factory parent is made\n * once per make()/create() call, for all of its models, and again by the next call, so a factory kept in a variable\n * never points at a parent an earlier test rolled back.\n */\n for(parent: RelatedFactory | Model, relationship?: string): this {\n const cls = parent instanceof Model ? parent.constructor : new parent.model().constructor\n return this.newInstance({ forRelations: [...this.forRelations, { parent, relationship: relationship ?? Str.camel(cls.name) }] })\n }\n\n afterMaking(callback: (model: M) => unknown): this {\n return this.newInstance({ afterMakingCallbacks: [...this.afterMakingCallbacks, callback] })\n }\n\n afterCreating(callback: (model: M) => unknown): this {\n return this.newInstance({ afterCreatingCallbacks: [...this.afterCreatingCallbacks, callback] })\n }\n\n /** The attributes only, without a model (a Row, or a Row[] after count()). */\n async raw(attributes: Row = {}): Promise<RawResult<this>> {\n const rows: Row[] = []\n const parents: ResolvedParents = new Map()\n for (let index = 0; index < (this.countValue ?? 1); index++) rows.push(await this.attributesFor(attributes, index, parents))\n return (this.countValue === undefined ? rows[0]! : rows) as RawResult<this>\n }\n\n /** Unsaved models (afterMaking callbacks run). */\n async make(attributes: Row = {}): Promise<FactoryResult<this, M>> {\n const models = await this.makeModels(attributes)\n return this.result(models)\n }\n\n /** Saved models, with their has() relations (afterCreating callbacks run). */\n async create(attributes: Row = {}): Promise<FactoryResult<this, M>> {\n const models = await this.makeModels(attributes)\n for (const model of models) {\n await model.save()\n await this.createChildren(model)\n for (const callback of this.afterCreatingCallbacks) await callback(model)\n }\n return this.result(models)\n }\n\n async makeOne(attributes: Row = {}): Promise<M> {\n return (await this.newInstance({ countValue: undefined }).makeModels(attributes))[0]!\n }\n\n async createOne(attributes: Row = {}): Promise<M> {\n return (await this.newInstance({ countValue: undefined }).create(attributes)) as M\n }\n\n /** One model per record (or `count` models), in the model's Eloquent collection. */\n async createMany(records: number | Row[]): Promise<EloquentCollection<M>> {\n const list = typeof records === 'number' ? Array.from({ length: records }, () => ({})) : records\n const created: M[] = []\n for (const record of list) created.push(await this.createOne(record))\n return this.collect(created)\n }\n\n /** The models in their own Eloquent collection (the model's newCollection()). */\n private collect(models: M[]): EloquentCollection<M> {\n return new this.model().newCollection(models)\n }\n\n protected newInstance(changes: Partial<FactoryState<M>>): this {\n const copy = Object.create(Object.getPrototypeOf(this) as object) as this\n Object.assign(copy, this, changes)\n return copy\n }\n\n protected async makeModels(attributes: Row): Promise<M[]> {\n const models: M[] = []\n const parents: ResolvedParents = new Map()\n for (let index = 0; index < (this.countValue ?? 1); index++) {\n const model = new this.model().forceFill(await this.attributesFor(attributes, index, parents))\n for (const callback of this.afterMakingCallbacks) await callback(model)\n models.push(model)\n }\n return models\n }\n\n /** definition() + states + overrides + for() parents, with factory and function values expanded. */\n protected async attributesFor(overrides: Row, index: number, parents: ResolvedParents = new Map()): Promise<Row> {\n const context: StateContext = { index, count: this.countValue ?? 1 }\n let attributes: Row = this.definition()\n for (const state of this.states) attributes = { ...attributes, ...(typeof state === 'function' ? state(attributes, context) : state) }\n attributes = { ...attributes, ...overrides }\n for (const parent of this.forRelations) Object.assign(attributes, await this.parentAttributes(parent, parents))\n const expanded: Row = {}\n for (const [key, value] of Object.entries(attributes)) {\n if (value instanceof Factory) expanded[key] = (await value.createOne()).getKey()\n else if (value instanceof Model) expanded[key] = value.getKey()\n else if (typeof value === 'function') expanded[key] = (value as (attributes: Row) => unknown)(attributes)\n else expanded[key] = value\n }\n return expanded\n }\n\n private async parentAttributes(parent: ForRelationship, parents: ResolvedParents): Promise<Row> {\n let resolved = parents.get(parent)\n if (resolved === undefined) {\n resolved = parent.parent instanceof Model ? parent.parent : ((await parent.parent.createOne()) as Model)\n parents.set(parent, resolved)\n }\n const relation = this.relationOn(new this.model(), parent.relationship)\n if (relation instanceof MorphTo) {\n return { [relation.getForeignKeyName()]: resolved.getKey(), [relation.getMorphType()]: resolved.getMorphClass() }\n }\n if (relation instanceof BelongsTo) return { [relation.getForeignKeyName()]: resolved.getAttribute(relation.getOwnerKeyName()) }\n throw new LogicError(`for() needs a belongsTo or morphTo relation; [${parent.relationship}] is neither.`)\n }\n\n private async createChildren(model: M): Promise<void> {\n for (const { factory, relationship, pivot } of this.hasRelations) {\n const relation = this.relationOn(model, relationship)\n if (relation instanceof BelongsToMany) {\n const related = await factory.create()\n await relation.attach(related instanceof Collection ? related.all() : (related as Model), pivot)\n } else if (relation instanceof HasOneOrMany) {\n const foreign: Row = { [relation.getForeignKeyName()]: relation.getParentKey() }\n if (relation.morph) foreign[relation.getMorphType()!] = relation.getMorphClass()\n await factory.state(foreign).create()\n } else {\n throw new LogicError(`has() needs a hasOne, hasMany, morphMany or belongsToMany relation; [${relationship}] is none of them.`)\n }\n }\n }\n\n private relationOn(model: Model, relationship: string) {\n return model.getRelationInstance(relationship)\n }\n\n private result(models: M[]): FactoryResult<this, M> {\n return (this.countValue === undefined ? models[0] : this.collect(models)) as FactoryResult<this, M>\n }\n}\n\n/** Imports every factory file in a directory and registers its exported Factory classes. */\nexport async function discoverFactories(path: string): Promise<void> {\n if (!existsSync(path)) return\n for (const file of readdirSync(path).sort()) {\n if (!/\\.(ts|js|mts|mjs)$/.test(file) || /\\.d\\.[mc]?ts$/.test(file)) continue\n const module = (await import(pathToFileURL(join(path, file)).href)) as Record<string, unknown>\n for (const exported of Object.values(module)) {\n if (typeof exported === 'function' && exported.prototype instanceof Factory) {\n Factory.register(exported as unknown as new () => AnyFactory)\n }\n }\n }\n}\n","import { Str } from '@orieljs/support'\nimport type { ColumnRef } from '../../Query/Builder'\nimport type { Builder } from '../Builder'\nimport type { Model } from '../Model'\nimport type { Column } from '../types'\nimport { Relation } from './Relation'\n\n/** post.author(): this model (the child) holds the related model's key. */\nexport class BelongsTo<R extends Model, P extends Model = Model> extends Relation<R, P, R | null> {\n /**\n * @param foreignKey the column on the child ('user_id')\n * @param ownerKey the key on the related model it points at ('id')\n */\n constructor(\n related: R,\n child: P,\n readonly foreignKey: string,\n readonly ownerKey: string,\n relationName?: string,\n ) {\n super(related, child)\n this.relationName = relationName\n this.init()\n }\n\n getChild(): P {\n return this.parent\n }\n\n getForeignKeyName(): string {\n return this.foreignKey\n }\n\n getQualifiedForeignKeyName(): string {\n return this.parent.qualifyColumn(this.foreignKey)\n }\n\n getOwnerKeyName(): string {\n return this.ownerKey\n }\n\n getQualifiedOwnerKeyName(): string {\n return this.model.qualifyColumn(this.ownerKey)\n }\n\n addConstraints(): void {\n this.where(this.getQualifiedOwnerKeyName() as Column<R>, '=', this.parent.getAttribute(this.foreignKey))\n }\n\n addEagerConstraints(models: P[]): void {\n this.whereIn(this.getQualifiedOwnerKeyName() as Column<R>, this.keysOf(models, this.foreignKey))\n }\n\n async getResults(): Promise<R | null> {\n const key = this.parent.getAttribute(this.foreignKey)\n if (key === null || key === undefined) return null\n return (await this.first()) ?? null\n }\n\n initRelation(models: P[], relation: string): P[] {\n for (const model of models) model.setRelation(relation, null)\n return models\n }\n\n match(models: P[], results: R[], relation: string): P[] {\n const owners = new Map(results.map((result) => [String(result.getAttribute(this.ownerKey)), result]))\n for (const model of models) model.setRelation(relation, owners.get(String(model.getAttribute(this.foreignKey))) ?? null)\n return models\n }\n\n /** Points the child at `model` (sets the foreign key and the loaded relation). Save the child afterwards. */\n associate(model: R | null): P {\n this.parent.setAttribute(this.foreignKey, model === null ? null : model.getAttribute(this.ownerKey))\n this.parent.setRelation(this.relationKey(), model)\n return this.parent\n }\n\n /** Clears the foreign key. Save the child afterwards. */\n dissociate(): P {\n return this.associate(null)\n }\n\n getRelationExistenceQuery(query: Builder<R>, _parentQuery: Builder<P>, columns: ColumnRef[] = ['*']): Builder<R> {\n this.aliasSelfTable(query)\n return query.select(...(columns as Array<Column<R>>)).whereColumn(this.getQualifiedForeignKeyName(), '=', this.getQualifiedOwnerKeyName())\n }\n\n /** The loaded-relation name: the resolved name, else the related class in camelCase (author → pass it explicitly). */\n private relationKey(): string {\n return this.relationName ?? Str.camel(this.model.constructor.name)\n }\n}\n","import { ClassRegistry } from '@orieljs/contracts'\nimport { currentContainer } from '@orieljs/container'\nimport { LogicError } from '../../errors'\nimport type { Model } from '../Model'\n\nconst aliases = new Map<string, typeof Model>()\nconst booted = new Map<string, typeof Model>()\n/** The Model base class, handed over by Model.ts once it is defined (importing it here would be a circular import). */\nlet modelBase: typeof Model | undefined\n\nexport function setModelBaseClass(base: typeof Model): void {\n modelBase = base\n}\n\n/**\n * The morph map: the value stored in `*_type` columns for each model class (Laravel's Relation::morphMap()).\n * Without an entry the class name is stored ('Post'). Returns the current map.\n */\nexport function morphMap(map?: Record<string, typeof Model>, merge = true): Record<string, typeof Model> {\n if (map) {\n if (!merge) aliases.clear()\n for (const [alias, model] of Object.entries(map)) aliases.set(alias, model)\n }\n return Object.fromEntries(aliases)\n}\n\n/** The model class for a morph map alias, if mapped. */\nexport function getMorphedModel(alias: string): typeof Model | undefined {\n return aliases.get(alias)\n}\n\n/** The morph map alias of a class, if mapped. */\nexport function getMorphAlias(model: typeof Model): string | undefined {\n for (const [alias, candidate] of aliases) if (candidate === model) return alias\n return undefined\n}\n\n/** Remembers a booted model class by name, so morphTo can find it without a morph map entry. */\nexport function rememberModelClass(model: typeof Model): void {\n booted.set(model.name, model)\n}\n\n/** The class for a stored morph type: the morph map, then the ClassRegistry (discovered models), then booted models. */\nexport function resolveMorphClass(type: string): typeof Model {\n const mapped = aliases.get(type)\n if (mapped) return mapped\n const container = currentContainer()\n if (container?.bound(ClassRegistry)) {\n const registry = container.make(ClassRegistry)\n if (registry.has(type)) {\n const cls = registry.resolve(type)\n if (!modelBase || !(cls.prototype instanceof modelBase)) throw new LogicError(`Class [${type}] is not a model, so it can't be the type of a morphTo relation.`)\n return cls as unknown as typeof Model\n }\n }\n const known = booted.get(type)\n if (known) return known\n throw new LogicError(`Class [${type}] not found for a morphTo relation. Add it to Relation.morphMap().`)\n}\n","import type { Collection } from '@orieljs/collections'\nimport type { ColumnRef } from '../../Query/Builder'\nimport { Expression } from '../../Query/Expression'\nimport { Builder } from '../Builder'\nimport type { Model } from '../Model'\nimport { relationConstraintsEnabled } from './constraints'\nimport { getMorphedModel, morphMap } from './morphMap'\n\n/**\n * A relation is the related model's query builder, constrained to the parent: post.comments() is a\n * Builder<Comment> with `where comments.post_id = ?`, so every builder method (where, orderBy, paginate, a local\n * scope, …) works on it. Subclasses add eager loading (addEagerConstraints/initRelation/match) and the existence\n * queries behind has()/whereHas()/withCount().\n */\n/** Counts the aliases self-referencing existence queries take (Laravel's getRelationCountHash()). */\nlet selfAliases = 0\n\nexport abstract class Relation<R extends Model = Model, P extends Model = Model, Result = unknown> extends Builder<R> {\n /** The name the relation is loaded under (set when resolved by name, for eager loading and associate()). */\n relationName: string | undefined\n\n /** Laravel's Relation::morphMap(): { post: Post } stores 'post' instead of 'Post' in *_type columns. */\n static morphMap(map?: Record<string, typeof Model>, merge = true): Record<string, typeof Model> {\n return morphMap(map, merge)\n }\n\n static getMorphedModel(alias: string): typeof Model | undefined {\n return getMorphedModel(alias)\n }\n\n protected constructor(\n related: R,\n readonly parent: P,\n ) {\n super(related)\n related.registerGlobalScopes(this)\n related.registerDefaultEagerLoads(this)\n }\n\n getParent(): P {\n return this.parent\n }\n\n getRelated(): R {\n return this.model\n }\n\n /**\n * When the related table is the parent's own (a category's children, a user's followers), the existence query reads it\n * under an alias, `oriel_reserved_<n>`, so its columns aren't the outer row's. The related model takes the alias as its\n * table, so its qualified columns (keys, soft deletes, a constraint's qualifyColumn()) follow. Returns the alias, or\n * undefined when the tables differ.\n */\n protected aliasSelfTable(query: Builder<R>): string | undefined {\n const table = query.getModel().getTable()\n if (table !== this.parent.getTable()) return undefined\n const alias = Relation.reserveAlias()\n query.from(`${table} as ${alias}`)\n query.getModel().setTable(alias)\n return alias\n }\n\n /** A new `oriel_reserved_<n>` alias, for a table a query reads twice. */\n protected static reserveAlias(): string {\n return `oriel_reserved_${selfAliases++}`\n }\n\n /**\n * @internal After an eager load's constraint: a limit() or offset() set there applies to each parent, as in Laravel 11,\n * on the relations that know the column holding the parent's key.\n */\n limitEagerPerParent(): void {\n const column = this.eagerPartitionColumn()\n if (column !== undefined) this.limitPerGroup(column)\n }\n\n /** The column of the eager query holding each row's parent key; undefined where a per-parent limit makes no sense. */\n protected eagerPartitionColumn(): string | undefined {\n return undefined\n }\n\n /** Subclasses call this last in their constructor: adds the per-parent constraints unless eager loading. */\n protected init(): void {\n if (relationConstraintsEnabled()) this.addConstraints()\n }\n\n /** The constraints for one parent: where comments.post_id = post.id. */\n abstract addConstraints(): void\n\n /** The constraints for many parents: where comments.post_id in (…). */\n abstract addEagerConstraints(models: P[]): void\n\n /** Sets the empty value (null or an empty collection) on every parent. */\n abstract initRelation(models: P[], relation: string): P[]\n\n /** Distributes the eagerly loaded results to their parents. */\n abstract match(models: P[], results: R[], relation: string): P[]\n\n /** The relation's value for this parent (a model, null or a collection). */\n abstract getResults(): Promise<Result>\n\n /** The query of has()/whereHas(): related rows that belong to the outer query's current row. */\n abstract getRelationExistenceQuery(query: Builder<R>, parentQuery: Builder<P>, columns?: ColumnRef[]): Builder<R>\n\n /** Runs the eager query. */\n getEager(): Promise<Collection<R>> {\n return this.get()\n }\n\n /** select count(*) … for withCount() and has('comments', '>=', 3). */\n getRelationExistenceCountQuery(query: Builder<R>, parentQuery: Builder<P>): Builder<R> {\n return this.getRelationExistenceQuery(query, parentQuery, [new Expression('count(*)')])\n }\n\n /** The distinct non-null values of `key` on the models (the eager whereIn list). */\n protected keysOf(models: Model[], key: string): unknown[] {\n const seen = new Map<string, unknown>()\n for (const model of models) {\n const value = model.getAttribute(key)\n if (value !== null && value !== undefined) seen.set(String(value), value)\n }\n return [...seen.values()]\n }\n}\n","import type { Row } from '@orieljs/contracts'\nimport { Collection } from '@orieljs/collections'\nimport type { Builder as QueryBuilder, ColumnRef } from '../../Query/Builder'\nimport { formatDateTime } from '../../Query/values'\nimport { Builder } from '../Builder'\nimport type { EloquentCollection } from '../Collection'\nimport { Pivot, type Model } from '../Model'\nimport type { Column, UntypedModel, WriteAttributes } from '../types'\nimport { Relation } from './Relation'\n\n/** attach()/sync() accept ids, models, or { id: pivotAttributes }. */\nexport type PivotIds = unknown | readonly unknown[] | Record<string, Row>\n\nexport interface SyncChanges {\n attached: unknown[]\n detached: unknown[]\n updated: unknown[]\n}\n\n/**\n * Many-to-many through a pivot table: post.tags() → belongsToMany(Tag) over post_tag (post_id, tag_id).\n * Each related model carries its pivot row as `tag.pivot` (withPivot() adds columns, withTimestamps() the timestamps).\n */\nexport class BelongsToMany<R extends Model, P extends Model = Model> extends Relation<R, P, EloquentCollection<R>> {\n protected pivotColumns: string[] = []\n protected pivotTimestamps: [string, string] | undefined\n\n constructor(\n related: R,\n parent: P,\n readonly table: string,\n readonly foreignPivotKey: string,\n readonly relatedPivotKey: string,\n readonly parentKey: string,\n readonly relatedKey: string,\n ) {\n super(related, parent)\n this.join(this.table, this.model.qualifyColumn(this.relatedKey), '=', this.qualifyPivotColumn(this.relatedPivotKey))\n this.init()\n }\n\n qualifyPivotColumn(column: string): string {\n return column.includes('.') ? column : `${this.table}.${column}`\n }\n\n getTable(): string {\n return this.table\n }\n\n getForeignPivotKeyName(): string {\n return this.foreignPivotKey\n }\n\n getRelatedPivotKeyName(): string {\n return this.relatedPivotKey\n }\n\n getParentKey(): unknown {\n return this.parent.getAttribute(this.parentKey)\n }\n\n addConstraints(): void {\n this.where(this.qualifyPivotColumn(this.foreignPivotKey) as Column<R>, '=', this.getParentKey())\n }\n\n addEagerConstraints(models: P[]): void {\n this.whereIn(this.qualifyPivotColumn(this.foreignPivotKey) as Column<R>, this.keysOf(models, this.parentKey))\n }\n\n /** Extra pivot columns to load onto tag.pivot. */\n withPivot(...columns: Array<string | string[]>): this {\n this.pivotColumns.push(...columns.flat())\n return this\n }\n\n /** The pivot table has created_at/updated_at: they are set on attach() and loaded onto tag.pivot. */\n withTimestamps(createdAt = 'created_at', updatedAt = 'updated_at'): this {\n this.pivotTimestamps = [createdAt, updatedAt]\n return this.withPivot(createdAt, updatedAt)\n }\n\n wherePivot(column: string, operator: unknown, value?: unknown): this {\n const qualified = this.qualifyPivotColumn(column) as Column<R>\n return value === undefined ? this.where(qualified, operator) : this.where(qualified, String(operator), value)\n }\n\n wherePivotIn(column: string, values: readonly unknown[]): this {\n return this.whereIn(this.qualifyPivotColumn(column) as Column<R>, values)\n }\n\n /** Selects the related columns plus the pivot columns (as pivot_*), then moves those onto each model's pivot. */\n override async runSelect(): Promise<R[]> {\n const query = this.clone() as this\n if (!query.columns.length) query.columns = [`${this.model.getTable()}.*`]\n query.columns.push(...this.pivotSelectColumns())\n const models = (await Builder.prototype.runSelect.call(query)) as R[]\n for (const model of models) this.hydratePivot(model)\n return models\n }\n\n async getResults(): Promise<EloquentCollection<R>> {\n const key = this.getParentKey()\n return key === null || key === undefined ? this.getRelated().newCollection<R>() : this.get()\n }\n\n initRelation(models: P[], relation: string): P[] {\n for (const model of models) model.setRelation(relation, this.getRelated().newCollection<R>())\n return models\n }\n\n match(models: P[], results: R[], relation: string): P[] {\n const dictionary = new Map<string, R[]>()\n for (const result of results) {\n const key = String(result.pivot?.getAttribute(this.foreignPivotKey))\n const group = dictionary.get(key)\n if (group) group.push(result)\n else dictionary.set(key, [result])\n }\n for (const model of models) model.setRelation(relation, this.getRelated().newCollection(dictionary.get(String(model.getAttribute(this.parentKey))) ?? []))\n return models\n }\n\n protected override eagerPartitionColumn(): string {\n return this.qualifyPivotColumn(this.foreignPivotKey)\n }\n\n getRelationExistenceQuery(query: Builder<R>, _parentQuery: Builder<P>, columns: ColumnRef[] = ['*']): Builder<R> {\n this.aliasSelfTable(query)\n return query\n .select(...(columns as Array<Column<R>>))\n .join(this.table, this.model.qualifyColumn(this.relatedKey), '=', this.qualifyPivotColumn(this.relatedPivotKey))\n .whereColumn(this.parent.qualifyColumn(this.parentKey), '=', this.qualifyPivotColumn(this.foreignPivotKey))\n }\n\n // ---------------------------------------------------------------- the pivot table\n\n /** Inserts pivot rows for ids (or models, or { id: attributes }), with shared extra attributes. */\n async attach(ids: PivotIds, attributes: Row = {}): Promise<void> {\n const rows = [...this.parseIds(ids)].map(([id, extra]) => this.pivotRow(id, { ...attributes, ...extra }, true))\n if (rows.length) await this.newPivotQuery().insert(rows)\n }\n\n /** Deletes pivot rows for ids, or every pivot row of the parent. Returns how many were deleted. */\n async detach(ids?: PivotIds): Promise<number> {\n const query = this.newPivotQuery().where(this.foreignPivotKey, '=', this.getParentKey())\n if (ids !== undefined) {\n const list = [...this.parseIds(ids).keys()]\n if (!list.length) return 0\n query.whereIn(this.relatedPivotKey, list)\n }\n return query.delete()\n }\n\n /** Makes the pivot rows exactly ids: attaches the missing ones, detaches the others, updates given attributes. */\n async sync(ids: PivotIds, detaching = true): Promise<SyncChanges> {\n const changes: SyncChanges = { attached: [], detached: [], updated: [] }\n const wanted = this.parseIds(ids)\n const current = await this.currentPivotIds()\n const wantedKeys = new Set([...wanted.keys()].map(String))\n if (detaching) {\n const detach = current.filter((id) => !wantedKeys.has(String(id)))\n if (detach.length) {\n await this.detach(detach)\n changes.detached.push(...detach)\n }\n }\n const currentKeys = new Set(current.map(String))\n for (const [id, attributes] of wanted) {\n if (!currentKeys.has(String(id))) {\n await this.attach(id, attributes)\n changes.attached.push(id)\n } else if (Object.keys(attributes).length && (await this.updateExistingPivot(id, attributes)) > 0) {\n changes.updated.push(id)\n }\n }\n return changes\n }\n\n syncWithoutDetaching(ids: PivotIds): Promise<SyncChanges> {\n return this.sync(ids, false)\n }\n\n /** Attaches the ids that aren't attached and detaches the ones that are. */\n async toggle(ids: PivotIds): Promise<{ attached: unknown[]; detached: unknown[] }> {\n const current = new Set((await this.currentPivotIds()).map(String))\n const attached: unknown[] = []\n const detached: unknown[] = []\n for (const [id, attributes] of this.parseIds(ids)) {\n if (current.has(String(id))) {\n await this.detach(id)\n detached.push(id)\n } else {\n await this.attach(id, attributes)\n attached.push(id)\n }\n }\n return { attached, detached }\n }\n\n /** Updates the pivot row of one related id. Returns the number of affected rows. */\n async updateExistingPivot(id: unknown, attributes: Row): Promise<number> {\n const values = { ...attributes }\n if (this.pivotTimestamps) values[this.pivotTimestamps[1]] = formatDateTime(this.parent.freshTimestamp())\n return this.newPivotQuery()\n .where(this.foreignPivotKey, '=', this.getParentKey())\n .where(this.relatedPivotKey, '=', this.idOf(id))\n .update(values)\n }\n\n /** Saves a new related model and attaches it. */\n override create<const T extends object = Row>(attributes?: T & WriteAttributes<R, T>, pivotAttributes?: Row): Promise<R>\n override create(this: BelongsToMany<UntypedModel, P>, attributes?: Row, pivotAttributes?: Row): Promise<R>\n override async create(attributes?: Row, pivotAttributes: Row = {}): Promise<R> {\n const model = this.model.newInstance((attributes ?? {}) as Row) as R\n await model.save()\n await this.attach(model, pivotAttributes)\n return model\n }\n\n /** Saves a related model and attaches it. */\n async save(model: R, pivotAttributes: Row = {}): Promise<R> {\n await model.save()\n await this.attach(model, pivotAttributes)\n return model\n }\n\n /** A plain query builder on the pivot table. */\n newPivotQuery(): QueryBuilder<Row> {\n return this.connection.table(this.table)\n }\n\n private async currentPivotIds(): Promise<unknown[]> {\n return (await this.newPivotQuery().where(this.foreignPivotKey, '=', this.getParentKey()).pluck(this.relatedPivotKey)).all()\n }\n\n private pivotSelectColumns(): string[] {\n const columns = [...new Set([this.foreignPivotKey, this.relatedPivotKey, ...this.pivotColumns])]\n return columns.map((column) => `${this.table}.${column} as pivot_${column}`)\n }\n\n private hydratePivot(model: R): void {\n const attributes = model.getAttributes()\n const pivotValues: Row = {}\n const own: Row = {}\n for (const [key, value] of Object.entries(attributes)) {\n if (key.startsWith('pivot_')) pivotValues[key.slice(6)] = value\n else own[key] = value\n }\n model.setRawAttributes(own, true)\n const pivot = new Pivot().setTable(this.table)\n pivot.timestamps = this.pivotTimestamps !== undefined\n pivot.setRawAttributes(pivotValues, true)\n pivot.exists = true\n model.setRelation('pivot', pivot)\n }\n\n private pivotRow(id: unknown, attributes: Row, creating: boolean): Row {\n const row: Row = { ...attributes, [this.foreignPivotKey]: this.getParentKey(), [this.relatedPivotKey]: this.idOf(id) }\n if (this.pivotTimestamps && creating) {\n const now = formatDateTime(this.parent.freshTimestamp())\n row[this.pivotTimestamps[0]] ??= now\n row[this.pivotTimestamps[1]] ??= now\n }\n return row\n }\n\n /** ids → Map(id → extra pivot attributes). Models become their related key. */\n private parseIds(ids: PivotIds): Map<unknown, Row> {\n const parsed = new Map<unknown, Row>()\n if (ids instanceof Collection) ids = ids.all()\n if (Array.isArray(ids)) {\n for (const id of ids) parsed.set(this.idOf(id), {})\n } else if (ids !== null && typeof ids === 'object' && !this.isModel(ids)) {\n for (const [id, attributes] of Object.entries(ids as Record<string, Row>)) parsed.set(this.castKey(id), attributes)\n } else {\n parsed.set(this.idOf(ids), {})\n }\n return parsed\n }\n\n private idOf(id: unknown): unknown {\n return this.isModel(id) ? id.getAttribute(this.relatedKey) : id\n }\n\n private isModel(value: unknown): value is Model {\n return typeof value === 'object' && value !== null && typeof (value as Model).getAttribute === 'function' && typeof (value as Model).getTable === 'function'\n }\n\n /** Object keys are strings; numeric ones go back to numbers for integer keys. */\n private castKey(id: string): unknown {\n return this.model.getKeyType() === 'int' && /^\\d+$/.test(id) ? Number(id) : id\n }\n}\n","import type { Row } from '@orieljs/contracts'\nimport { Str } from '@orieljs/support'\nimport { RelationNotFoundError } from '../../errors'\nimport type { ColumnRef } from '../../Query/Builder'\nimport type { Builder } from '../Builder'\nimport type { EloquentCollection } from '../Collection'\nimport type { Model } from '../Model'\nimport type { Column } from '../types'\nimport { Relation } from './Relation'\n\n/** For morphOne/morphMany: the qualified type column and the parent's morph class stored in it. */\nexport interface MorphConstraint {\n type: string\n value: string\n}\n\n/**\n * The shared half of hasOne, hasMany, morphOne and morphMany: the related table holds the foreign key (and, for\n * the morph relations, the parent's type).\n */\nexport abstract class HasOneOrMany<R extends Model, P extends Model, Result> extends Relation<R, P, Result> {\n /** The relation on each related model that chaperone() points back at the parent. */\n protected inverseRelationship: string | undefined\n /**\n * @param foreignKey the qualified foreign key on the related table ('comments.post_id')\n * @param localKey the key on the parent it points at ('id')\n * @param morph the type column and value, for morphOne/morphMany\n */\n constructor(\n related: R,\n parent: P,\n readonly foreignKey: string,\n readonly localKey: string,\n readonly morph?: MorphConstraint,\n ) {\n super(related, parent)\n this.init()\n }\n\n /** 'post_id' */\n getForeignKeyName(): string {\n return this.foreignKey.slice(this.foreignKey.lastIndexOf('.') + 1)\n }\n\n getQualifiedForeignKeyName(): string {\n return this.foreignKey\n }\n\n getParentKey(): unknown {\n return this.parent.getAttribute(this.localKey)\n }\n\n getQualifiedParentKeyName(): string {\n return this.parent.qualifyColumn(this.localKey)\n }\n\n /** 'commentable_type' for a morph relation. */\n getMorphType(): string | undefined {\n return this.morph?.type.slice(this.morph.type.lastIndexOf('.') + 1)\n }\n\n /** The parent's value in the type column, for a morph relation. */\n getMorphClass(): string | undefined {\n return this.morph?.value\n }\n\n /**\n * Laravel's chaperone(): every related model this relation loads, eagerly or lazily, or makes, gets the parent as\n * its `relation` (guessed when not given: post_id → post, the parent's class, owner), so reading it needs no query:\n * `comments() { return this.hasMany(Comment).chaperone() }`.\n */\n chaperone(relation?: string): this {\n const name = relation ?? this.guessInverseRelation()\n if (name === undefined || !this.model.isRelation(name)) throw new RelationNotFoundError(this.model.constructor.name, name ?? 'null')\n this.inverseRelationship = name\n return this\n }\n\n /** Laravel's inverse(): chaperone() under its other name. */\n inverse(relation?: string): this {\n return this.chaperone(relation)\n }\n\n withoutChaperone(): this {\n this.inverseRelationship = undefined\n return this\n }\n\n withoutInverse(): this {\n return this.withoutChaperone()\n }\n\n getInverseRelationship(): string | undefined {\n return this.inverseRelationship\n }\n\n /** The first of the possible names that is a relation of the related model. */\n protected guessInverseRelation(): string | undefined {\n return this.getPossibleInverseRelations().find((name) => this.model.isRelation(name))\n }\n\n /** Laravel's candidates: the morph name, the foreign key without the parent's key, the parent's class, owner, parent. */\n protected getPossibleInverseRelations(): string[] {\n const key = this.parent.getKeyName()\n const names = [\n this.morph ? Str.beforeLast(this.getMorphType()!, '_type') : '',\n Str.camel(Str.beforeLast(this.getForeignKeyName(), key)),\n Str.camel(Str.beforeLast(this.parent.getForeignKey(), key)),\n Str.camel(this.parent.constructor.name),\n 'owner',\n this.parent.constructor === this.model.constructor ? 'parent' : '',\n ]\n return [...new Set(names.filter((name) => name !== ''))]\n }\n\n /** Sets the parent on a related model, when chaperone() named the relation. */\n protected applyInverseRelationToModel<M extends R | null | undefined>(model: M, parent: P = this.parent): M {\n if (model && this.inverseRelationship !== undefined) model.setRelation(this.inverseRelationship, parent)\n return model\n }\n\n protected applyInverseRelationToMany(models: R[], parent: P = this.parent): R[] {\n for (const model of models) this.applyInverseRelationToModel(model, parent)\n return models\n }\n\n /** The relation query's rows (get(), first(), paginate(), …), pointing back at the parent with chaperone(). */\n override async runSelect(): Promise<R[]> {\n return this.applyInverseRelationToMany(await super.runSelect())\n }\n\n addConstraints(): void {\n this.where(this.foreignKey as Column<R>, '=', this.getParentKey())\n this.whereNotNull(this.foreignKey as Column<R>)\n if (this.morph) this.where(this.morph.type as Column<R>, '=', this.morph.value)\n }\n\n addEagerConstraints(models: P[]): void {\n this.whereIn(this.foreignKey as Column<R>, this.keysOf(models, this.localKey))\n if (this.morph) this.where(this.morph.type as Column<R>, '=', this.morph.value)\n }\n\n /** Related models grouped by their foreign key, as strings: bigint and integer keys compare equal. */\n protected buildDictionary(results: R[]): Map<string, R[]> {\n const dictionary = new Map<string, R[]>()\n const key = this.getForeignKeyName()\n for (const result of results) {\n const value = String(result.getAttribute(key))\n const group = dictionary.get(value)\n if (group) group.push(result)\n else dictionary.set(value, [result])\n }\n return dictionary\n }\n\n /** New related models get the parent's key (and type): post.comments().create({ body }) sets post_id. */\n override newModelInstance(attributes: Row = {}): R {\n return this.setForeignAttributes(super.newModelInstance(attributes))\n }\n\n /** Sets the foreign key (and type) on an existing model and saves it. */\n async save(model: R): Promise<R> {\n await this.setForeignAttributes(model).save()\n return model\n }\n\n protected setForeignAttributes(model: R): R {\n model.setAttribute(this.getForeignKeyName(), this.getParentKey())\n if (this.morph) model.setAttribute(this.getMorphType()!, this.morph.value)\n return this.applyInverseRelationToModel(model)\n }\n\n async saveMany(models: Iterable<R>): Promise<R[]> {\n const saved: R[] = []\n for (const model of models) saved.push(await this.save(model))\n return saved\n }\n\n /** One related model per record, in the related model's Eloquent collection. */\n async createMany(records: Row[]): Promise<EloquentCollection<R>> {\n const created: R[] = []\n for (const record of records) created.push(await this.create(record))\n return this.getRelated().newCollection(created)\n }\n\n protected override eagerPartitionColumn(): string {\n return this.foreignKey\n }\n\n getRelationExistenceQuery(query: Builder<R>, _parentQuery: Builder<P>, columns: ColumnRef[] = ['*']): Builder<R> {\n const alias = this.aliasSelfTable(query)\n const foreignKey = alias === undefined ? this.foreignKey : `${alias}.${this.getForeignKeyName()}`\n query.select(...(columns as Array<Column<R>>)).whereColumn(this.getQualifiedParentKeyName(), '=', foreignKey)\n if (this.morph) {\n const type = alias === undefined ? this.morph.type : `${alias}.${this.morph.type.slice(this.morph.type.lastIndexOf('.') + 1)}`\n query.where(type as Column<R>, '=', this.morph.value)\n }\n return query\n }\n}\n","import { Collection } from '@orieljs/collections'\nimport { LogicError } from '../../errors'\nimport type { Builder } from '../Builder'\nimport type { Model } from '../Model'\nimport { BelongsTo } from './BelongsTo'\nimport { resolveMorphClass } from './morphMap'\n\n/**\n * comment.commentable() → morphTo('commentable'): the parent's class comes from commentable_type (a morph map alias\n * or a class name) and its key from commentable_id. Eager loading runs one query per distinct type.\n */\nexport class MorphTo<R extends Model = Model, P extends Model = Model> extends BelongsTo<R, P> {\n /** Parents grouped by type, then by id, while eager loading. */\n private dictionary = new Map<string, Map<string, P[]>>()\n /** The stored type each eager result was loaded for (an alias or a class name), for match(). */\n private resultTypes = new WeakMap<Model, string>()\n\n /**\n * @param related an instance of the current type's class (the child's own class when the type is empty)\n * @param morphType the type column on the child ('commentable_type')\n * @param ownerKey the key on the parent (default: each class's primary key)\n */\n constructor(related: R, child: P, foreignKey: string, readonly morphTypeColumn: string, readonly ownerKeyOverride: string | undefined, relationName: string) {\n super(related, child, foreignKey, ownerKeyOverride ?? related.getKeyName(), relationName)\n // Without a type, `related` is only the child's own class standing in for the real ones: its default with and\n // withCount belong to the child, not to the parents getEager() loads (each type's query adds its own defaults).\n if (!child.getAttribute(morphTypeColumn)) {\n this.eagerLoad.clear()\n this.columns = []\n }\n }\n\n getMorphType(): string {\n return this.morphTypeColumn\n }\n\n override addConstraints(): void {\n if (this.parent.getAttribute(this.morphTypeColumn)) super.addConstraints()\n }\n\n override async getResults(): Promise<R | null> {\n if (!this.parent.getAttribute(this.morphTypeColumn)) return null\n return super.getResults()\n }\n\n /** Groups the children by type and id; the queries run in getEager(). */\n override addEagerConstraints(models: P[]): void {\n this.dictionary = new Map()\n for (const model of models) {\n const type = model.getAttribute(this.morphTypeColumn)\n const id = model.getAttribute(this.foreignKey)\n if (!type || id === null || id === undefined) continue\n const byId = this.dictionary.get(String(type)) ?? new Map<string, P[]>()\n const group = byId.get(String(id))\n if (group) group.push(model)\n else byId.set(String(id), [model])\n this.dictionary.set(String(type), byId)\n }\n }\n\n /** One query per type, with this relation's constraints and nested eager loads. */\n override async getEager(): Promise<Collection<R>> {\n const results: R[] = []\n for (const [type, byId] of this.dictionary) {\n const cls = resolveMorphClass(type)\n const instance = cls.prototypeInstance()\n const ownerKey = this.ownerKeyOverride ?? instance.getKeyName()\n const query = cls.query()\n for (const [name, constraint] of this.getEagerLoads()) query.with(constraint ? { [name]: constraint } : name)\n query.wheres.push(...this.wheres)\n const ids = [...byId.values()].map((models) => models[0]!.getAttribute(this.foreignKey))\n for (const result of (await query.whereIn(instance.qualifyColumn(ownerKey), ids).get()).all() as unknown as R[]) {\n this.resultTypes.set(result, type)\n results.push(result)\n }\n }\n return new Collection(results)\n }\n\n override match(models: P[], results: R[], relation: string): P[] {\n for (const result of results) {\n const byId = this.dictionary.get(this.resultTypes.get(result) ?? result.getMorphClass())\n const ownerKey = this.ownerKeyOverride ?? result.getKeyName()\n for (const model of byId?.get(String(result.getAttribute(ownerKey))) ?? []) model.setRelation(relation, result)\n }\n return models\n }\n\n /** Points the child at `model`: sets the id and the type columns and the loaded relation. */\n override associate(model: R | null): P {\n this.parent.setAttribute(this.foreignKey, model === null ? null : model.getAttribute(this.ownerKeyOverride ?? model.getKeyName()))\n this.parent.setAttribute(this.morphTypeColumn, model === null ? null : model.getMorphClass())\n this.parent.setRelation(this.relationName ?? this.morphTypeColumn.replace(/_type$/, ''), model)\n return this.parent\n }\n\n override getRelationExistenceQuery(): Builder<R> {\n throw new LogicError('has()/whereHas() on a morphTo relation needs the possible types, which Oriel v1 does not support.')\n }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport { EventDispatcher } from '@orieljs/contracts'\nimport { currentContainer } from '@orieljs/container'\nimport { LogicError } from '../errors'\n\n/** Laravel's model events. The -ing events of save, delete and restore can cancel by returning false. */\nexport const MODEL_EVENTS = [\n 'retrieved', 'creating', 'created', 'updating', 'updated', 'saving', 'saved',\n 'deleting', 'deleted', 'restoring', 'restored', 'forceDeleting', 'forceDeleted',\n] as const\nexport type ModelEvent = (typeof MODEL_EVENTS)[number]\n\n/** A listener receives the model. Returning false from a halting event cancels the operation. */\nexport type ModelListener<M> = (model: M) => unknown\n\nconst muted = new AsyncLocalStorage<boolean>()\n\n/** 'eloquent.created: Post' (Laravel uses the fully qualified class name; Oriel uses the class name). */\nexport function modelEventName(event: string, className: string): string {\n return `eloquent.${event}: ${className}`\n}\n\n/** The EventDispatcher of the current container, when one is bound. Firing without one is a no-op. */\nexport function eventDispatcher(): EventDispatcher | undefined {\n const container = currentContainer()\n return container?.bound(EventDispatcher) ? container.make(EventDispatcher) : undefined\n}\n\n/** The dispatcher for registering listeners: required, because silently dropping an observer would hide a bug. */\nexport function requireEventDispatcher(className: string): EventDispatcher {\n const dispatcher = eventDispatcher()\n if (!dispatcher) {\n throw new LogicError(`Registering model events on [${className}] needs an EventDispatcher. Is EventServiceProvider registered?`)\n }\n return dispatcher\n}\n\n/** Runs fn with model events off, for this async context only (Model.withoutEvents, saveQuietly). */\nexport function withoutModelEvents<R>(fn: () => R): R {\n return muted.run(true, fn)\n}\n\nexport function modelEventsMuted(): boolean {\n return muted.getStore() === true\n}\n","import type { EloquentCollection } from '../Collection'\nimport type { Model } from '../Model'\nimport { HasOneOrMany } from './HasOneOrMany'\n\n/** post.comments(): many related rows hold the parent's key. */\nexport class HasMany<R extends Model, P extends Model = Model> extends HasOneOrMany<R, P, EloquentCollection<R>> {\n async getResults(): Promise<EloquentCollection<R>> {\n const key = this.getParentKey()\n return key === null || key === undefined ? this.getRelated().newCollection<R>() : this.get()\n }\n\n initRelation(models: P[], relation: string): P[] {\n for (const model of models) model.setRelation(relation, this.getRelated().newCollection<R>())\n return models\n }\n\n match(models: P[], results: R[], relation: string): P[] {\n const dictionary = this.buildDictionary(results)\n for (const model of models) {\n const children = this.applyInverseRelationToMany(dictionary.get(String(model.getAttribute(this.localKey))) ?? [], model)\n model.setRelation(relation, this.getRelated().newCollection(children))\n }\n return models\n }\n}\n","import type { Row } from '@orieljs/contracts'\nimport type { ColumnRef } from '../../Query/Builder'\nimport { Builder } from '../Builder'\nimport type { EloquentCollection } from '../Collection'\nimport type { Model } from '../Model'\nimport type { Column } from '../types'\nimport { Relation } from './Relation'\n\nconst THROUGH_KEY = 'laravel_through_key'\n\n/**\n * Related rows reached through an intermediate model: country.posts() → hasManyThrough(Post, User):\n * posts join users on users.id = posts.user_id where users.country_id = countries.id.\n */\nexport class HasManyThrough<R extends Model, P extends Model = Model, T extends Model = Model> extends Relation<R, P, EloquentCollection<R>> {\n /** The through key of each loaded model (kept off its attributes, so it never reaches toJSON()). */\n private readonly throughKeys = new WeakMap<Model, unknown>()\n /**\n * The through table's alias when it is the related table too (a person's grandchildren, through their children):\n * every query of the relation reads it under this name, its keys and soft deletes included.\n */\n private readonly throughAlias: string | undefined\n\n /**\n * @param firstKey on the through table, pointing at the far parent ('users.country_id')\n * @param secondKey on the related table, pointing at the through model ('posts.user_id')\n * @param localKey on the far parent ('countries.id')\n * @param secondLocalKey on the through model ('users.id')\n */\n constructor(\n related: R,\n farParent: P,\n readonly throughParent: T,\n readonly firstKey: string,\n readonly secondKey: string,\n readonly localKey: string,\n readonly secondLocalKey: string,\n ) {\n super(related, farParent)\n this.throughAlias = throughParent.getTable() === related.getTable() ? HasManyThrough.reserveAlias() : undefined\n this.join(this.throughTable(this.throughAlias), this.getQualifiedParentKeyName(), '=', this.getQualifiedForeignKeyName())\n if (this.throughParent.usesSoftDeletes()) {\n this.withGlobalScope('SoftDeletableHasManyThrough', (query) => query.whereNull(this.throughColumn(this.throughParent.getDeletedAtColumn())))\n }\n this.init()\n }\n\n /** The through table to join: `users`, or `users as <alias>`. */\n private throughTable(alias: string | undefined): string {\n return alias === undefined ? this.throughParent.getTable() : `${this.throughParent.getTable()} as ${alias}`\n }\n\n /** A through column, qualified by the through table or by its alias. */\n private throughColumn(column: string, alias = this.throughAlias): string {\n return alias === undefined ? this.throughParent.qualifyColumn(column) : `${alias}.${column}`\n }\n\n /** users.country_id */\n getQualifiedFirstKeyName(): string {\n return this.throughColumn(this.firstKey)\n }\n\n /** posts.user_id */\n getQualifiedForeignKeyName(): string {\n return this.model.qualifyColumn(this.secondKey)\n }\n\n /** users.id */\n getQualifiedParentKeyName(): string {\n return this.throughColumn(this.secondLocalKey)\n }\n\n /** countries.id */\n getQualifiedLocalKeyName(): string {\n return this.parent.qualifyColumn(this.localKey)\n }\n\n addConstraints(): void {\n this.where(this.getQualifiedFirstKeyName() as Column<R>, '=', this.parent.getAttribute(this.localKey))\n }\n\n addEagerConstraints(models: P[]): void {\n this.whereIn(this.getQualifiedFirstKeyName() as Column<R>, this.keysOf(models, this.localKey))\n }\n\n /** Selects the related columns plus the through key, then moves the key off the attributes. */\n override async runSelect(): Promise<R[]> {\n const query = this.clone() as this\n if (!query.columns.length) query.columns = [`${this.model.getTable()}.*`]\n query.columns.push(`${this.getQualifiedFirstKeyName()} as ${THROUGH_KEY}`)\n const models = (await Builder.prototype.runSelect.call(query)) as R[]\n for (const model of models) {\n const { [THROUGH_KEY]: key, ...attributes } = model.getAttributes() as Row\n this.throughKeys.set(model, key)\n model.setRawAttributes(attributes, true)\n }\n return models\n }\n\n /** An eager limit() or offset() applies to each far parent, by the through table's key to it (Laravel 11). */\n protected override eagerPartitionColumn(): string {\n return this.getQualifiedFirstKeyName()\n }\n\n async getResults(): Promise<EloquentCollection<R>> {\n const key = this.parent.getAttribute(this.localKey)\n return key === null || key === undefined ? this.getRelated().newCollection<R>() : this.get()\n }\n\n override async getEager(): Promise<EloquentCollection<R>> {\n return this.get()\n }\n\n initRelation(models: P[], relation: string): P[] {\n for (const model of models) model.setRelation(relation, this.getRelated().newCollection<R>())\n return models\n }\n\n match(models: P[], results: R[], relation: string): P[] {\n const dictionary = new Map<string, R[]>()\n for (const result of results) {\n const key = String(this.throughKeys.get(result))\n const group = dictionary.get(key)\n if (group) group.push(result)\n else dictionary.set(key, [result])\n }\n for (const model of models) model.setRelation(relation, this.getRelated().newCollection(dictionary.get(String(model.getAttribute(this.localKey))) ?? []))\n return models\n }\n\n /**\n * The query of has()/withCount(), as Laravel's ...ForSelfRelation and ...ForThroughSelfRelation: a related table that\n * is the parent's is read under an alias, and so is a through table that is the parent's (or the related one).\n */\n getRelationExistenceQuery(query: Builder<R>, _parentQuery: Builder<P>, columns: ColumnRef[] = ['*']): Builder<R> {\n const related = this.aliasSelfTable(query) ?? query.getModel().getTable()\n const alias = this.throughAlias ?? (this.throughParent.getTable() === this.parent.getTable() ? HasManyThrough.reserveAlias() : undefined)\n query\n .select(...(columns as Array<Column<R>>))\n .join(this.throughTable(alias), this.throughColumn(this.secondLocalKey, alias), '=', `${related}.${this.secondKey}`)\n .whereColumn(this.getQualifiedLocalKeyName(), '=', this.throughColumn(this.firstKey, alias))\n if (this.throughParent.usesSoftDeletes()) query.whereNull(this.throughColumn(this.throughParent.getDeletedAtColumn(), alias) as Column<R>)\n return query\n }\n}\n","import type { Model } from '../Model'\nimport { HasOneOrMany } from './HasOneOrMany'\n\n/** user.profile(): one related row holds the parent's key. */\nexport class HasOne<R extends Model, P extends Model = Model> extends HasOneOrMany<R, P, R | null> {\n async getResults(): Promise<R | null> {\n const key = this.getParentKey()\n if (key === null || key === undefined) return null\n return (await this.first()) ?? null\n }\n\n initRelation(models: P[], relation: string): P[] {\n for (const model of models) model.setRelation(relation, null)\n return models\n }\n\n match(models: P[], results: R[], relation: string): P[] {\n const dictionary = this.buildDictionary(results)\n for (const model of models) {\n model.setRelation(relation, this.applyInverseRelationToModel(dictionary.get(String(model.getAttribute(this.localKey)))?.[0] ?? null, model))\n }\n return models\n }\n}\n","import type { Model } from '../Model'\nimport { HasMany } from './HasMany'\n\n/** post.comments() → morphMany(Comment, 'commentable'): comments.commentable_id + commentable_type = 'Post'. */\nexport class MorphMany<R extends Model, P extends Model = Model> extends HasMany<R, P> {\n /**\n * @param morphType the qualified type column ('comments.commentable_type')\n * @param foreignKey the qualified id column ('comments.commentable_id')\n */\n constructor(related: R, parent: P, morphType: string, foreignKey: string, localKey: string) {\n super(related, parent, foreignKey, localKey, { type: morphType, value: parent.getMorphClass() })\n }\n}\n","import type { Model } from '../Model'\nimport { HasOne } from './HasOne'\n\n/** user.image() → morphOne(Image, 'imageable'): images.imageable_id + imageable_type = 'User'. */\nexport class MorphOne<R extends Model, P extends Model = Model> extends HasOne<R, P> {\n constructor(related: R, parent: P, morphType: string, foreignKey: string, localKey: string) {\n super(related, parent, foreignKey, localKey, { type: morphType, value: parent.getMorphClass() })\n }\n}\n","import { Str } from '@orieljs/support'\nimport type { ModelConstructor } from './HasDatabaseNotifications'\n\n/**\n * Laravel's HasUniqueStringIds, shared by HasUuids and HasUlids: the primary key is a string the model fills on\n * insert, and a value of the wrong shape finds nothing without a query (route model binding, find(), findOrFail()).\n */\nfunction uniqueStringIds<TBase extends ModelConstructor>(Base: TBase, generate: () => string, valid: (value: unknown) => boolean): TBase {\n return class WithUniqueStringIds extends Base {\n override usesUniqueIds(): boolean {\n return true\n }\n\n override uniqueIds(): string[] {\n return [this.getKeyName()]\n }\n\n override newUniqueId(): string {\n return generate()\n }\n\n override isValidUniqueId(value: unknown): boolean {\n return valid(value)\n }\n\n override getKeyType(): 'int' | 'string' {\n return this.uniqueIds().includes(this.getKeyName()) ? 'string' : super.getKeyType()\n }\n\n override getIncrementing(): boolean {\n return this.uniqueIds().includes(this.getKeyName()) ? false : super.getIncrementing()\n }\n }\n}\n\n/** Laravel's HasUuids: `class Post extends HasUuids(Model) {}` keys new rows with a version 7 UUID. */\nexport function HasUuids<TBase extends ModelConstructor>(Base: TBase): TBase {\n return uniqueStringIds(Base, () => Str.uuid7(), Str.isUuid)\n}\n\n/** Laravel's HasUlids: `class Post extends HasUlids(Model) {}` keys new rows with a lower-case ULID. */\nexport function HasUlids<TBase extends ModelConstructor>(Base: TBase): TBase {\n return uniqueStringIds(Base, () => Str.ulid().toLowerCase(), Str.isUlid)\n}\n","import type { DatabaseNotification as DatabaseNotificationContract } from '@orieljs/contracts'\nimport type { Builder } from './Builder'\nimport type { CastDefinition } from './casts'\nimport { EloquentCollection } from './Collection'\nimport { HasUuids } from './HasUniqueStringIds'\nimport { Model } from './Model'\nimport { MorphMany } from './Relations/MorphMany'\nimport type { MorphTo } from './Relations/MorphTo'\n\n/**\n * Laravel's DatabaseNotification: one row of the `notifications` table, which the database channel writes. A UUID\n * string key (HasUuids: a malformed id finds nothing without a query, so it is a 404), `data` as an array cast and\n * `read_at` as a datetime. `user.notifications()` returns these, newest first.\n */\nexport class DatabaseNotification extends HasUuids(Model) implements DatabaseNotificationContract {\n protected override table: string | undefined = 'notifications'\n protected override keyType: 'int' | 'string' = 'string'\n override incrementing = false\n protected override guarded: string[] = []\n protected override casts: Readonly<Record<string, CastDefinition>> = { data: 'array', read_at: 'datetime' }\n\n declare $attributes?: {\n id: string\n type: string\n notifiable_type: string\n notifiable_id: number | string\n data: Record<string, unknown>\n read_at: Date | null\n created_at: Date | null\n updated_at: Date | null\n }\n\n declare readonly id: string\n declare readonly type: string\n declare readonly notifiable_type: string\n declare readonly notifiable_id: number | string\n declare readonly data: Record<string, unknown>\n declare read_at: Date | null\n declare readonly created_at: Date | null\n declare readonly updated_at: Date | null\n\n /** The model the notification was sent to. */\n notifiable<R extends Model = Model>(): MorphTo<R, this> {\n return this.morphTo<R>('notifiable')\n }\n\n /** Sets read_at to now and saves, unless it is already read. */\n async markAsRead(): Promise<void> {\n if (this.unread()) await this.forceFill({ read_at: this.freshTimestamp() }).save()\n }\n\n /** Clears read_at and saves, unless it is already unread. */\n async markAsUnread(): Promise<void> {\n if (this.read()) await this.forceFill({ read_at: null }).save()\n }\n\n read(): boolean {\n return this.read_at !== null && this.read_at !== undefined\n }\n\n unread(): boolean {\n return !this.read()\n }\n\n /** Queries of notifications return a DatabaseNotificationCollection (markAsRead() on all of them). */\n override newCollection<T extends Model>(this: T, models: T[] = []): EloquentCollection<T> {\n return new DatabaseNotificationCollection(models as unknown as DatabaseNotification[]) as unknown as EloquentCollection<T>\n }\n\n /** `query.read()`: only read notifications. */\n static scopeRead(query: Builder<DatabaseNotification>): Builder<DatabaseNotification> {\n return query.whereNotNull('read_at')\n }\n\n /** `query.unread()`: only unread notifications. */\n static scopeUnread(query: Builder<DatabaseNotification>): Builder<DatabaseNotification> {\n return query.whereNull('read_at')\n }\n}\n\n/** Laravel's DatabaseNotificationCollection: what `await user.notifications().get()` returns. */\nexport class DatabaseNotificationCollection extends EloquentCollection<DatabaseNotification> {\n /** Marks every notification as read (one save each, as in Laravel). */\n async markAsRead(): Promise<void> {\n for (const notification of this.all()) await notification.markAsRead()\n }\n\n /** Marks every notification as unread. */\n async markAsUnread(): Promise<void> {\n for (const notification of this.all()) await notification.markAsUnread()\n }\n}\n\n/**\n * The relation `notifications()`, `readNotifications()` and `unreadNotifications()` return: a morphMany over\n * DatabaseNotification whose results (get(), the loaded relation, eager loads) are DatabaseNotificationCollections.\n * Every builder method works on it: paginate(), count(), update({ read_at }), where(), …\n */\nexport class DatabaseNotificationsRelation<P extends Model = Model> extends MorphMany<DatabaseNotification, P> {\n override async get(): Promise<DatabaseNotificationCollection> {\n return new DatabaseNotificationCollection(await this.runSelect())\n }\n\n override async getResults(): Promise<DatabaseNotificationCollection> {\n const key = this.getParentKey()\n return key === null || key === undefined ? new DatabaseNotificationCollection() : this.get()\n }\n\n override initRelation(models: P[], relation: string): P[] {\n for (const model of models) model.setRelation(relation, new DatabaseNotificationCollection())\n return models\n }\n\n override match(models: P[], results: DatabaseNotification[], relation: string): P[] {\n const dictionary = this.buildDictionary(results)\n for (const model of models) {\n model.setRelation(relation, new DatabaseNotificationCollection(dictionary.get(String(model.getAttribute(this.localKey))) ?? []))\n }\n return models\n }\n}\n","import { DatabaseNotification, DatabaseNotificationsRelation } from './DatabaseNotification'\nimport type { Model } from './Model'\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ModelConstructor = new (...args: any[]) => Model\n\n/** What HasDatabaseNotifications adds to a model. */\nexport interface HasDatabaseNotificationsModel extends Model {\n /** The model's notifications, newest first: morphMany(DatabaseNotification, 'notifiable').latest(). */\n notifications(): DatabaseNotificationsRelation<this>\n /** The read ones (read_at set). */\n readNotifications(): DatabaseNotificationsRelation<this>\n /** The unread ones (read_at null). */\n unreadNotifications(): DatabaseNotificationsRelation<this>\n}\n\n/**\n * Laravel's HasDatabaseNotifications: the notifications the database channel stored for this model, as queries.\n * `class User extends HasDatabaseNotifications(Model) {}`; apps get it through `Notifiable`.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function HasDatabaseNotifications<TBase extends ModelConstructor>(Base: TBase): TBase & (new (...args: any[]) => HasDatabaseNotificationsModel) {\n class WithDatabaseNotifications extends Base implements HasDatabaseNotificationsModel {\n notifications(): DatabaseNotificationsRelation<this> {\n const related = this.newRelatedInstance(DatabaseNotification)\n return new DatabaseNotificationsRelation<this>(\n related,\n this,\n related.qualifyColumn('notifiable_type'),\n related.qualifyColumn('notifiable_id'),\n this.getKeyName(),\n ).latest()\n }\n\n readNotifications(): DatabaseNotificationsRelation<this> {\n return this.notifications().whereNotNull('read_at')\n }\n\n unreadNotifications(): DatabaseNotificationsRelation<this> {\n return this.notifications().whereNull('read_at')\n }\n }\n return WithDatabaseNotifications\n}\n","/**\n * A migration: `export default class extends Migration { async up() { await Schema.create(…) } async down() { … } }`.\n * Files live in database/migrations and run in file-name order. up() and down() are abstract (as in Laravel's\n * stub), so implementing them needs no `override` under noImplicitOverride.\n */\nexport abstract class Migration {\n /** The connection to run on (default: the default connection). */\n connection: string | undefined = undefined\n\n /** Wrap up()/down() in a transaction where DDL is transactional (Postgres, SQLite; not MySQL), like Laravel. */\n withinTransaction = true\n\n abstract up(): Promise<void> | void\n\n abstract down(): Promise<void> | void\n}\n","import { existsSync, mkdirSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { Str } from '@orieljs/support'\nimport { LogicError } from '../errors'\n\n/** Laravel 11's migration.create stub: an anonymous class, the form the Migrator loads. */\nexport 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`\n\n/** Laravel 11's migration.update stub. */\nexport 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`\n\n/** Laravel 11's blank migration stub. */\nexport 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`\n\n/**\n * Laravel's TableGuesser: create_posts_table → ['posts', true], add_votes_to_users_table → ['users', false].\n * Returns undefined when the name says nothing about a table.\n */\nexport function guessTable(migration: string): { table: string; create: boolean } | undefined {\n const create = /^create_(\\w+?)(?:_table)?$/.exec(migration)\n if (create) return { table: create[1]!, create: true }\n const change = /_(?:to|from|in)_(\\w+?)(?:_table)?$/.exec(migration)\n if (change) return { table: change[1]!, create: false }\n return undefined\n}\n\n/** Laravel's date prefix, Y_m_d_His (UTC). */\nexport function migrationDatePrefix(date: Date = new Date()): string {\n const pad = (value: number) => String(value).padStart(2, '0')\n return (\n `${date.getUTCFullYear()}_${pad(date.getUTCMonth() + 1)}_${pad(date.getUTCDate())}_` +\n `${pad(date.getUTCHours())}${pad(date.getUTCMinutes())}${pad(date.getUTCSeconds())}`\n )\n}\n\nexport interface CreateMigrationOptions {\n /** The table to create (--create). */\n create?: string\n /** The table to change (--table). */\n table?: string\n /** The package the migration imports Migration and Schema from (default '@orieljs/framework'). */\n importSource?: string\n /** For tests: the timestamp of the file name. */\n date?: Date\n}\n\n/** Laravel's MigrationCreator: writes <path>/<Y_m_d_His>_<name>.ts from the create, update or blank stub. */\nexport class MigrationCreator {\n /** Returns the path of the new file. */\n create(name: string, path: string, options: CreateMigrationOptions = {}): string {\n const snake = Str.snake(name.trim())\n let table = options.table ?? options.create\n let create = options.create !== undefined\n if (table === undefined) {\n const guessed = guessTable(snake)\n if (guessed) ({ table, create } = guessed)\n }\n const stub = table === undefined ? MIGRATION_STUB : create ? MIGRATION_CREATE_STUB : MIGRATION_UPDATE_STUB\n const file = join(path, `${migrationDatePrefix(options.date)}_${snake}.ts`)\n if (existsSync(file)) throw new LogicError(`Migration [${file}] already exists.`)\n mkdirSync(path, { recursive: true })\n writeFileSync(\n file,\n stub.replaceAll('{{ importSource }}', options.importSource ?? '@orieljs/framework').replaceAll('{{ table }}', table ?? ''),\n )\n return file\n }\n}\n","import type { Connection } from '../Connection'\n\nexport interface MigrationRecord {\n migration: string\n batch: number\n}\n\n/** The migrations table (id, migration, batch): which migration ran in which batch (Laravel's DatabaseMigrationRepository). */\nexport class MigrationRepository {\n constructor(\n protected readonly connection: Connection,\n readonly table = 'migrations',\n ) {}\n\n async repositoryExists(): Promise<boolean> {\n return this.connection.getSchemaBuilder().hasTable(this.table)\n }\n\n async createRepository(): Promise<void> {\n await this.connection.getSchemaBuilder().create(this.table, (table) => {\n table.increments('id')\n table.string('migration')\n table.integer('batch')\n })\n }\n\n async deleteRepository(): Promise<void> {\n await this.connection.getSchemaBuilder().dropIfExists(this.table)\n }\n\n /** Every migration that ran, oldest first. */\n async getRan(): Promise<string[]> {\n return (await this.query().orderBy('batch').orderBy('migration').pluck<string>('migration')).all()\n }\n\n /** The last `steps` migrations, newest first. */\n async getMigrations(steps: number): Promise<MigrationRecord[]> {\n return this.records(this.query().where('batch', '>=', 1).orderBy('batch', 'desc').orderBy('migration', 'desc').limit(steps))\n }\n\n /** The migrations of one batch, newest first. */\n async getMigrationsByBatch(batch: number): Promise<MigrationRecord[]> {\n return this.records(this.query().where('batch', batch).orderBy('migration', 'desc'))\n }\n\n /** The migrations of the last batch, newest first. */\n async getLast(): Promise<MigrationRecord[]> {\n return this.getMigrationsByBatch(await this.getLastBatchNumber())\n }\n\n /** migration name → batch. */\n async getMigrationBatches(): Promise<Record<string, number>> {\n const rows = await this.records(this.query().orderBy('batch').orderBy('migration'))\n return Object.fromEntries(rows.map((row) => [row.migration, row.batch]))\n }\n\n async log(migration: string, batch: number): Promise<void> {\n await this.query().insert({ migration, batch })\n }\n\n async delete(migration: string): Promise<void> {\n await this.query().where('migration', migration).delete()\n }\n\n async getNextBatchNumber(): Promise<number> {\n return (await this.getLastBatchNumber()) + 1\n }\n\n async getLastBatchNumber(): Promise<number> {\n return Number((await this.query().max('batch')) ?? 0)\n }\n\n private query() {\n return this.connection.table<MigrationRecord>(this.table)\n }\n\n private async records(query: ReturnType<MigrationRepository['query']>): Promise<MigrationRecord[]> {\n return (await query.get()).all().map((row) => ({ migration: String(row.migration), batch: Number(row.batch) }))\n }\n}\n","import { existsSync, readdirSync } from 'node:fs'\nimport { basename, extname, join } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport type { Connection } from '../Connection'\nimport type { DatabaseManagerImpl } from '../DatabaseManager'\nimport { LogicError } from '../errors'\nimport { assertSqliteForeignKeys, sqliteForeignKeysEnabled } from '../Schema/SqliteTableRebuild'\nimport { Migration } from './Migration'\nimport { MigrationRepository } from './MigrationRepository'\n\n/** Why a SQLite migration's foreign key check can fail where the same changes pass with foreign keys on. */\nconst SQLITE_MIGRATION_HINT =\n \"SQLite runs a migration with foreign keys off, so ON DELETE and ON UPDATE actions don't run in it: change the child rows first, or set withinTransaction = false.\"\n\nconst MIGRATION_FILE = /^(?!.*\\.d\\.[mc]?ts$).+\\.(ts|js|mts|mjs)$/\n\nexport interface MigrationStatus {\n name: string\n ran: boolean\n batch: number | undefined\n}\n\nexport interface MigratorOptions {\n /** Run each migration in its own batch (migrate --step). */\n step?: boolean\n}\n\nexport interface RollbackOptions {\n /** Roll back this many migrations instead of the last batch. */\n step?: number\n /** Roll back one batch by number. */\n batch?: number\n}\n\n/**\n * Runs database/migrations/*.ts in file-name order and records them in the migrations table\n * (Laravel's Migrator). Output lines go to `output`.\n */\nexport class Migrator {\n private connectionName: string | undefined\n\n constructor(\n protected readonly manager: DatabaseManagerImpl,\n protected readonly output: (line: string) => void = () => undefined,\n ) {}\n\n /** Use another connection for the repository and for migrations that don't name one (--database). */\n setConnection(name: string | undefined): this {\n this.connectionName = name\n return this\n }\n\n getConnection(): Connection {\n return this.manager.connection(this.connectionName)\n }\n\n getRepository(): MigrationRepository {\n return new MigrationRepository(this.getConnection(), this.manager.migrationsTable())\n }\n\n /** migration name (file name without extension) → absolute path, sorted by name across all paths. */\n getMigrationFiles(paths: readonly string[]): Map<string, string> {\n const files: Array<[string, string]> = []\n for (const path of paths) {\n if (!existsSync(path)) continue\n for (const file of readdirSync(path)) {\n if (MIGRATION_FILE.test(file)) files.push([basename(file, extname(file)), join(path, file)])\n }\n }\n return new Map(files.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))\n }\n\n /** Creates the migrations table when it doesn't exist yet. */\n async ensureRepository(): Promise<MigrationRepository> {\n const repository = this.getRepository()\n if (!(await repository.repositoryExists())) await repository.createRepository()\n return repository\n }\n\n /** Runs every pending migration in one new batch (or one batch each with step). Returns their names. */\n async run(paths: readonly string[], options: MigratorOptions = {}): Promise<string[]> {\n const repository = await this.ensureRepository()\n const ran = new Set(await repository.getRan())\n const pending = [...this.getMigrationFiles(paths)].filter(([name]) => !ran.has(name))\n if (!pending.length) {\n this.output('Nothing to migrate.')\n return []\n }\n let batch = await repository.getNextBatchNumber()\n this.output('Running migrations.')\n for (const [name, file] of pending) {\n await this.runMigration(await this.resolve(file), 'up')\n await repository.log(name, batch)\n this.output(` ${name} DONE`)\n if (options.step) batch++\n }\n return pending.map(([name]) => name)\n }\n\n /** Rolls back the last batch (or the last `step` migrations, or one batch). Returns the names rolled back. */\n async rollback(paths: readonly string[], options: RollbackOptions = {}): Promise<string[]> {\n const repository = await this.ensureRepository()\n const records = options.step\n ? await repository.getMigrations(options.step)\n : options.batch\n ? await repository.getMigrationsByBatch(options.batch)\n : await repository.getLast()\n if (!records.length) {\n this.output('Nothing to rollback.')\n return []\n }\n this.output('Rolling back migrations.')\n return this.rollDown(paths, records.map((record) => record.migration), repository)\n }\n\n /** Rolls back every migration, newest first. */\n async reset(paths: readonly string[]): Promise<string[]> {\n const repository = await this.ensureRepository()\n const ran = (await repository.getRan()).reverse()\n if (!ran.length) {\n this.output('Nothing to rollback.')\n return []\n }\n this.output('Rolling back migrations.')\n return this.rollDown(paths, ran, repository)\n }\n\n /** Drops every table, then runs every migration (migrate:fresh). */\n async fresh(paths: readonly string[]): Promise<string[]> {\n await this.getConnection().getSchemaBuilder().dropAllTables()\n this.output('Dropping all tables DONE')\n return this.run(paths)\n }\n\n /** Every migration file and every recorded migration, with its batch (all pending without a migrations table). */\n async status(paths: readonly string[]): Promise<MigrationStatus[]> {\n const repository = this.getRepository()\n const batches = (await repository.repositoryExists()) ? await repository.getMigrationBatches() : {}\n const names = new Set([...this.getMigrationFiles(paths).keys(), ...Object.keys(batches)])\n return [...names].sort().map((name) => ({ name, ran: name in batches, batch: batches[name] }))\n }\n\n /** Imports a migration file; its default export is a Migration class (or instance). */\n async resolve(file: string): Promise<Migration> {\n const module = (await import(pathToFileURL(file).href)) as { default?: unknown }\n const exported = module.default\n const migration = typeof exported === 'function' ? new (exported as new () => unknown)() : exported\n if (!(migration instanceof Migration)) {\n throw new LogicError(`Migration [${basename(file)}] must default-export a class extending Migration.`)\n }\n return migration\n }\n\n private async rollDown(paths: readonly string[], names: string[], repository: MigrationRepository): Promise<string[]> {\n const files = this.getMigrationFiles(paths)\n const rolledBack: string[] = []\n for (const name of names) {\n const file = files.get(name)\n if (!file) {\n this.output(` ${name} Migration not found`)\n continue\n }\n await this.runMigration(await this.resolve(file), 'down')\n await repository.delete(name)\n this.output(` ${name} DONE`)\n rolledBack.push(name)\n }\n return rolledBack\n }\n\n /** Runs up/down on the migration's connection (made the default meanwhile), in a transaction where DDL allows it. */\n private async runMigration(migration: Migration, method: 'up' | 'down'): Promise<void> {\n const name = migration.connection ?? this.connectionName\n await this.manager.usingConnection(name, async () => {\n const connection = this.manager.connection(name)\n const run = async () => {\n await migration[method]()\n }\n if (connection.getDriverName() === 'sqlite') await this.runOnSqlite(connection, migration, run)\n else if (migration.withinTransaction && connection.getDriverName() !== 'mysql') await connection.transaction(run)\n else await run()\n })\n }\n\n /**\n * SQLite's order for a migration in a transaction: foreign keys off before the transaction (SQLite ignores the pragma\n * inside one, and a table rebuild would otherwise run the ON DELETE actions of the tables that reference it), the\n * migration, a foreign key check before the commit (rows that break a key fail the migration), then foreign keys back\n * on. A migration outside a transaction runs with foreign keys as they are, so its ON DELETE and ON UPDATE actions\n * run; a table rebuild in it turns them off around itself and checks the table.\n */\n private async runOnSqlite(connection: Connection, migration: Migration, run: () => Promise<void>): Promise<void> {\n if (!migration.withinTransaction) return run()\n const toggle = connection.transactionLevel() === 0 && (await sqliteForeignKeysEnabled(connection))\n if (toggle) await connection.statement('PRAGMA foreign_keys = OFF')\n try {\n await connection.transaction(async () => {\n await run()\n if (toggle) await assertSqliteForeignKeys(connection, undefined, SQLITE_MIGRATION_HINT)\n })\n } finally {\n if (toggle) await connection.statement('PRAGMA foreign_keys = ON')\n }\n }\n}\n","import { Model } from './Eloquent/Model'\n\nexport type SeederClass = new () => Seeder\n\n/**\n * A database seeder (database/seeders/*.ts): run() inserts data, call() runs other seeders. Seeders run with mass\n * assignment protection off, as with Laravel's db:seed.\n */\nexport abstract class Seeder {\n protected output: (line: string) => void = () => undefined\n\n abstract run(): Promise<void> | void\n\n setOutput(output: (line: string) => void): this {\n this.output = output\n return this\n }\n\n /** Runs other seeders in order, printing their names. */\n async call(...seeders: Array<SeederClass | SeederClass[]>): Promise<void> {\n for (const seeder of seeders.flat()) {\n this.output(` ${seeder.name} RUNNING`)\n await new seeder().setOutput(this.output).invoke()\n this.output(` ${seeder.name} DONE`)\n }\n }\n\n /** Runs other seeders without output. */\n async callSilent(...seeders: Array<SeederClass | SeederClass[]>): Promise<void> {\n for (const seeder of seeders.flat()) await new seeder().invoke()\n }\n\n /** Runs run() unguarded. */\n async invoke(): Promise<void> {\n await Model.unguarded(() => this.run())\n }\n}\n","import { existsSync } from 'node:fs'\nimport { isAbsolute, join, relative } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport type { Application, CommandContext, ConsoleKernel } from '@orieljs/contracts'\nimport type { DatabaseManagerImpl } from '../DatabaseManager'\nimport { LogicError } from '../errors'\nimport { MigrationCreator } from '../Migrations/MigrationCreator'\nimport { Migrator } from '../Migrations/Migrator'\nimport type { ModelRegistry } from '../ModelRegistry'\nimport { Seeder } from '../Seeder'\nimport { TypeGenerator } from '../Types/TypeGenerator'\n\n/** The parts of the application and database the commands need (resolved lazily, when a command runs). */\nexport interface DatabaseCommandContext {\n app: Pick<Application, 'basePath' | 'databasePath' | 'isProduction'>\n manager(): DatabaseManagerImpl\n /** The discovered models. When given, model:types works and migrate regenerates the types outside production. */\n models?(): Promise<ModelRegistry>\n /** The package generated types import from (default '@orieljs/framework'). */\n typesImportSource?: string\n /** The package make:migration's stubs import from (default '@orieljs/framework'). */\n stubsImportSource?: string\n}\n\ntype Handler = (command: CommandContext) => Promise<number>\n\nconst text = (value: unknown): string | undefined => (typeof value === 'string' && value !== '' ? value : undefined)\nconst list = (value: unknown): string[] => (Array.isArray(value) ? value.map(String) : text(value) ? [String(value)] : [])\nconst integer = (value: unknown): number => {\n const number = Number(value ?? 0)\n return Number.isInteger(number) && number > 0 ? number : 0\n}\n\n/** A closure command with Laravel's description (shown by `oriel list`). */\nfunction define(kernel: ConsoleKernel, signature: string, description: string, handler: Handler): void {\n kernel\n .command(signature, async function (this: CommandContext) {\n return handler(this)\n })\n .purpose(description)\n}\n\n/** Laravel's ConfirmableTrait without the prompt: in production the command needs --force. */\nfunction confirmToProceed(context: DatabaseCommandContext, command: CommandContext): boolean {\n if (!context.app.isProduction() || command.option('force') === true) return true\n command.error('Application in production. Use --force to run this command.')\n return false\n}\n\n/** --path values (relative to the base path), or database/migrations. */\nfunction migrationPaths(context: DatabaseCommandContext, command: CommandContext): string[] {\n const paths = list(command.option('path'))\n if (!paths.length) return [context.app.databasePath('migrations')]\n return paths.map((path) => (isAbsolute(path) ? path : context.app.basePath(path)))\n}\n\nfunction migrator(context: DatabaseCommandContext, command: CommandContext): Migrator {\n return new Migrator(context.manager(), (line) => command.line(line)).setConnection(text(command.option('database')))\n}\n\n/** Imports database/seeders/<Class>.ts and runs it (default export or the export named after the class). */\nexport async function runSeeder(context: DatabaseCommandContext, className: string, output: (line: string) => void, database?: string): Promise<void> {\n const name = className.split('\\\\').pop()!\n const file = ['ts', 'js', 'mts', 'mjs'].map((extension) => context.app.databasePath(join('seeders', `${name}.${extension}`))).find(existsSync)\n if (!file) throw new LogicError(`Seeder [${name}] not found in ${context.app.databasePath('seeders')}.`)\n const module = (await import(pathToFileURL(file).href)) as Record<string, unknown>\n const exported = module.default ?? module[name]\n const seeder = typeof exported === 'function' ? new (exported as new () => unknown)() : exported\n if (!(seeder instanceof Seeder)) throw new LogicError(`Seeder [${name}] must export a class extending Seeder.`)\n await context.manager().usingConnection(database, () => seeder.setOutput(output).invoke())\n}\n\n/** Writes types/models.d.ts for the discovered models; returns the path relative to the base path. */\nexport async function generateModelTypes(context: DatabaseCommandContext): Promise<string | undefined> {\n if (!context.models) return undefined\n const outputFile = context.app.basePath(join('types', 'models.d.ts'))\n await new TypeGenerator({ outputFile, importSource: context.typesImportSource }).write((await context.models()).all())\n return relative(context.app.basePath(), outputFile)\n}\n\n/** After migrate, migrate:fresh and migrate:refresh: regenerates the model types, for apps that keep them (types/). */\nasync function writeModelTypes(context: DatabaseCommandContext, command: CommandContext): Promise<void> {\n if (context.app.isProduction() || !existsSync(context.app.basePath('types'))) return\n const written = await generateModelTypes(context)\n if (written) command.line(`Model types written to ${written}.`)\n}\n\n/** Laravel's needsSeeding(): --seed, or a --seeder class on its own. */\nasync function seedIfRequested(context: DatabaseCommandContext, command: CommandContext): Promise<void> {\n const seeder = text(command.option('seeder'))\n if (command.option('seed') !== true && seeder === undefined) return\n command.info('Seeding database.')\n await runSeeder(context, seeder ?? 'DatabaseSeeder', (line) => command.line(line), text(command.option('database')))\n}\n\n/** The migrate*, migrate:install, db:seed and make:migration commands (closure commands, PC1). */\nexport function registerMigrationCommands(kernel: ConsoleKernel, context: DatabaseCommandContext): void {\n define(kernel, 'migrate {--database=} {--force} {--path=*} {--seed} {--seeder=} {--step}', 'Run the database migrations', async (command) => {\n if (!confirmToProceed(context, command)) return 1\n await migrator(context, command).run(migrationPaths(context, command), { step: command.option('step') === true })\n await seedIfRequested(context, command)\n await writeModelTypes(context, command)\n return 0\n })\n\n define(kernel, 'migrate:install {--database=}', 'Create the migration repository', async (command) => {\n const repository = migrator(context, command).getRepository()\n if (!(await repository.repositoryExists())) await repository.createRepository()\n command.info('Migration table created successfully.')\n return 0\n })\n\n define(kernel, 'migrate:rollback {--database=} {--force} {--path=*} {--step=0} {--batch=0}', 'Rollback the last database migration', async (command) => {\n if (!confirmToProceed(context, command)) return 1\n await migrator(context, command).rollback(migrationPaths(context, command), {\n step: integer(command.option('step')),\n batch: integer(command.option('batch')),\n })\n return 0\n })\n\n define(kernel, 'migrate:reset {--database=} {--force} {--path=*}', 'Rollback all database migrations', async (command) => {\n if (!confirmToProceed(context, command)) return 1\n await migrator(context, command).reset(migrationPaths(context, command))\n return 0\n })\n\n define(kernel, 'migrate:refresh {--database=} {--force} {--path=*} {--seed} {--seeder=} {--step=0}', 'Reset and re-run all migrations', async (command) => {\n if (!confirmToProceed(context, command)) return 1\n const instance = migrator(context, command)\n const paths = migrationPaths(context, command)\n const step = integer(command.option('step'))\n if (step) await instance.rollback(paths, { step })\n else await instance.reset(paths)\n await instance.run(paths)\n await seedIfRequested(context, command)\n await writeModelTypes(context, command)\n return 0\n })\n\n define(kernel, 'migrate:fresh {--database=} {--force} {--path=*} {--seed} {--seeder=}', 'Drop all tables and re-run all migrations', async (command) => {\n if (!confirmToProceed(context, command)) return 1\n await migrator(context, command).fresh(migrationPaths(context, command))\n await seedIfRequested(context, command)\n await writeModelTypes(context, command)\n return 0\n })\n\n define(kernel, 'migrate:status {--database=} {--path=*}', 'Show the status of each migration', async (command) => {\n const instance = migrator(context, command)\n if (!(await instance.getRepository().repositoryExists())) {\n command.error('Migration table not found.')\n return 1\n }\n for (const status of await instance.status(migrationPaths(context, command))) {\n command.line(status.ran ? ` ${status.name} [${status.batch}] Ran` : ` ${status.name} Pending`)\n }\n return 0\n })\n\n define(kernel, 'db:seed {class?} {--class=DatabaseSeeder} {--database=} {--force}', 'Seed the database with records', async (command) => {\n if (!confirmToProceed(context, command)) return 1\n command.info('Seeding database.')\n const className = text(command.argument('class')) ?? text(command.option('class')) ?? 'DatabaseSeeder'\n await runSeeder(context, className, (line) => command.line(line), text(command.option('database')))\n return 0\n })\n\n const makeMigration =\n 'make:migration {name : The name of the migration} {--create= : The table to be created} ' +\n '{--table= : The table to migrate} {--path= : The location where the migration file should be created}'\n define(kernel, makeMigration, 'Create a new migration file', async (command) => {\n const name = text(command.argument('name'))\n if (name === undefined) {\n command.error('Not enough arguments (missing: \"name\").')\n return 1\n }\n const path = text(command.option('path'))\n const directory = path === undefined ? context.app.databasePath('migrations') : isAbsolute(path) ? path : context.app.basePath(path)\n const file = new MigrationCreator().create(name, directory, {\n create: text(command.option('create')),\n table: text(command.option('table')),\n importSource: context.stubsImportSource,\n })\n command.info(`Migration [${relative(context.app.basePath(), file)}] created successfully.`)\n return 0\n })\n}\n\n/** model:types: regenerates types/models.d.ts from the database schema and the discovered models. */\nexport function registerModelTypesCommand(kernel: ConsoleKernel, context: DatabaseCommandContext): void {\n define(kernel, 'model:types', \"Generate TypeScript types for the application's models\", async (command) => {\n const written = await generateModelTypes(context)\n if (!written) {\n command.error('No models registry is available: is DatabaseServiceProvider registered?')\n return 1\n }\n command.info(`Model types written to ${written}.`)\n return 0\n })\n}\n","import { mkdir, writeFile } from 'node:fs/promises'\nimport { dirname, relative, sep } from 'node:path'\nimport { Str } from '@orieljs/support'\nimport { enumValues, type CastDefinition } from '../Eloquent/casts'\nimport { Model } from '../Eloquent/Model'\nimport type { RegisteredModel } from '../ModelRegistry'\nimport type { ColumnInfo } from '../Schema/Grammar'\n\nexport interface TypeGeneratorOptions {\n /** Where the declarations go (the skeleton: types/models.d.ts). */\n outputFile: string\n /** The package the generated file imports ScopeStatic from. */\n importSource?: string\n}\n\nconst INTEGER = new Set(['int', 'integer', 'int2', 'int4', 'int8', 'bigint', 'smallint', 'mediumint', 'tinyint', 'serial', 'bigserial', 'smallserial', 'year'])\nconst FLOAT = new Set(['float', 'float4', 'float8', 'double', 'double precision', 'real'])\nconst BOOLEAN = new Set(['bool', 'boolean'])\nconst JSON_TYPES = new Set(['json', 'jsonb'])\nconst BINARY = new Set(['blob', 'bytea', 'binary', 'varbinary', 'longblob', 'mediumblob', 'tinyblob'])\n\n/** The TypeScript type for a cast, or undefined when the column type decides. */\nfunction castType(cast: CastDefinition | undefined): string | undefined {\n if (cast === undefined) return undefined\n if (typeof cast === 'string') {\n if (['int', 'integer', 'float', 'double', 'real', 'timestamp'].includes(cast)) return 'number'\n if (cast === 'string' || cast === 'hashed' || cast.startsWith('decimal:')) return 'string'\n if (cast === 'bool' || cast === 'boolean') return 'boolean'\n if (['date', 'datetime', 'immutable_date', 'immutable_datetime'].includes(cast)) return 'Date'\n return 'unknown'\n }\n if (typeof cast === 'object' && typeof (cast as { get?: unknown }).get !== 'function') {\n const literal = (value: string | number) => (typeof value === 'number' ? String(value) : `'${value.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`)\n return enumValues(cast as Record<string, string | number>).map(literal).join(' | ') || 'never'\n }\n return 'unknown'\n}\n\n/** The TypeScript type for a database column type (what the drivers hand back without a cast). */\nfunction columnType(column: ColumnInfo): string {\n const name = column.type_name.toLowerCase()\n if (INTEGER.has(name)) return 'number'\n if (FLOAT.has(name)) return 'number'\n if (BOOLEAN.has(name)) return 'boolean'\n if (JSON_TYPES.has(name)) return 'unknown'\n if (BINARY.has(name)) return 'Buffer'\n return 'string'\n}\n\n/** The get<Name>Attribute accessors on a model class, as [attribute, method] pairs. */\nfunction accessors(model: typeof Model): Array<[string, string]> {\n const found = new Map<string, string>()\n for (let proto: object | null = model.prototype; proto && proto !== Model.prototype; proto = Object.getPrototypeOf(proto) as object | null) {\n for (const key of Object.getOwnPropertyNames(proto)) {\n const match = /^get(.+)Attribute$/.exec(key)\n if (match && typeof Reflect.get(proto, key) === 'function' && !found.has(Str.snake(match[1]!))) found.set(Str.snake(match[1]!), key)\n }\n }\n return [...found]\n}\n\n/** The static scope<Name> methods of a model class, as [builder method, static method] pairs. */\nfunction scopes(model: typeof Model): Array<[string, string]> {\n const found = new Map<string, string>()\n for (let current: unknown = model; current && current !== Model; current = Object.getPrototypeOf(current)) {\n for (const key of Object.getOwnPropertyNames(current)) {\n if (key.startsWith('scope') && key.length > 5 && typeof Reflect.get(current as object, key) === 'function') {\n const name = Str.lcfirst(key.slice(5))\n if (!found.has(name)) found.set(name, key)\n }\n }\n }\n return [...found]\n}\n\n/**\n * Writes types/models.d.ts: for every model, the attribute types (from the database columns and the model's casts)\n * merged into the class by declaration merging, the phantom $attributes that Column<M> reads, accessor-only\n * attributes, and the static scope proxies (Post.published()).\n */\nexport class TypeGenerator {\n constructor(private readonly options: TypeGeneratorOptions) {}\n\n async generate(models: readonly RegisteredModel[]): Promise<string> {\n const blocks: string[] = []\n for (const entry of [...models].sort((a, b) => a.name.localeCompare(b.name))) {\n if (!entry.file) continue\n const block = await this.modelBlock(entry)\n if (block) blocks.push(block)\n }\n const importSource = this.options.importSource ?? '@orieljs/framework'\n return [\n '// Generated by `oriel model:types`. Do not edit: run `oriel model:types` (or `oriel migrate`) again.',\n // Built by concatenation so tools that scan source for imports don't mistake this template for one.\n 'import type { ScopeStatic } from ' + `'${importSource}'`,\n '',\n ...blocks,\n ].join('\\n')\n }\n\n /** Generates and writes the file; returns its path. */\n async write(models: readonly RegisteredModel[]): Promise<string> {\n await mkdir(dirname(this.options.outputFile), { recursive: true })\n await writeFile(this.options.outputFile, await this.generate(models))\n return this.options.outputFile\n }\n\n private async modelBlock({ name, model, file }: RegisteredModel): Promise<string | undefined> {\n const instance = model.prototypeInstance()\n const columns = await instance.getConnection().getSchemaBuilder().getColumns(instance.getTable())\n if (!columns.length) return undefined\n const casts = instance.getCasts()\n const attributes = columns.map((column) => {\n const type = castType(casts[column.name]) ?? columnType(column)\n return [column.name, column.nullable && type !== 'unknown' ? `${type} | null` : type] as const\n })\n const members = attributes.filter(([column]) => !(column in instance))\n const extra = accessors(model).filter(([attribute]) => !columns.some((column) => column.name === attribute) && !(attribute in instance))\n const statics = scopes(model).filter(([method]) => !(method in Model))\n // What toJSON() leaves out, keeps, and adds (columns, appends and relations alike): page prop types follow them.\n const names = (list: string[]) => list.map((item) => `'${item}'`).join(' | ')\n const hidden = instance.getHidden()\n const visible = instance.getVisible()\n const appends = instance.getAppends()\n const lines = [\n 'declare module ' + `'${this.modulePath(file!)}' {`,\n ` interface ${name} {`,\n ' $attributes?: {',\n ...attributes.map(([column, type]) => ` ${this.key(column)}: ${type}`),\n ' }',\n // The model itself, for its own methods: inside them `this` is a type parameter, and their writes and loads read\n // the attributes and relations they check from here.\n ` $self?: ${name}`,\n ...(hidden.length ? [` $hidden?: ${names(hidden)}`] : []),\n ...(visible.length ? [` $visible?: ${names(visible)}`] : []),\n ...(appends.length ? [` $appends?: ${names(appends)}`] : []),\n ...members.map(([column, type]) => ` ${this.key(column)}: ${type}`),\n ...extra.map(([attribute, method]) => ` ${this.key(attribute)}: ReturnType<${name}['${method}']>`),\n ' }',\n ]\n if (statics.length) {\n lines.push(` namespace ${name} {`, ...statics.map(([method, key]) => ` const ${method}: ScopeStatic<typeof ${name}, '${key}'>`), ' }')\n }\n lines.push('}', '')\n return lines.join('\\n')\n }\n\n /** '../app/Models/Post' for app/Models/Post.ts, relative to the output file. */\n private modulePath(file: string): string {\n const path = relative(dirname(this.options.outputFile), file).split(sep).join('/').replace(/\\.(ts|js|mts|mjs)$/, '')\n return path.startsWith('.') ? path : `./${path}`\n }\n\n private key(name: string): string {\n return /^[A-Za-z_$][\\w$]*$/.test(name) ? name : JSON.stringify(name)\n }\n}\n","import { existsSync, readdirSync, statSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { Str } from '@orieljs/support'\nimport { Model } from './Eloquent/Model'\n\nexport interface RegisteredModel {\n name: string\n model: typeof Model\n /** The file it was discovered in (used by model:types for the module path). */\n file?: string\n}\n\nconst MODEL_FILE = /^(?!.*\\.d\\.[mc]?ts$).+\\.(ts|js|mts|mjs)$/\n\n/**\n * The application's models, auto-discovered from app/Models: route model binding ({post} → Post), model:types,\n * and morphTo (through the ClassRegistry) look models up here by name.\n */\nexport class ModelRegistry {\n private readonly models = new Map<string, RegisteredModel>()\n\n /** Registers a model class (booting it, so static scope proxies such as Post.published() exist). */\n register(model: typeof Model, file?: string): RegisteredModel {\n const entry: RegisteredModel = { name: model.name, model, file }\n this.models.set(model.name, entry)\n model.bootIfNotBooted()\n return entry\n }\n\n /** Imports every file under `directory` and registers each exported Model subclass. */\n async discover(directory: string): Promise<RegisteredModel[]> {\n const found: RegisteredModel[] = []\n for (const file of listFiles(directory)) {\n const module = (await import(pathToFileURL(file).href)) as Record<string, unknown>\n for (const exported of Object.values(module)) {\n if (typeof exported === 'function' && exported.prototype instanceof Model && !this.models.has(exported.name)) {\n found.push(this.register(exported as typeof Model, file))\n }\n }\n }\n return found\n }\n\n /** A model by class name or route parameter name: 'Post', 'post', 'blog_post' and 'blogPost' find BlogPost. */\n get(name: string): RegisteredModel | undefined {\n return this.models.get(name) ?? this.models.get(Str.studly(name))\n }\n\n resolve(name: string): typeof Model | undefined {\n return this.get(name)?.model\n }\n\n has(name: string): boolean {\n return this.get(name) !== undefined\n }\n\n all(): RegisteredModel[] {\n return [...this.models.values()]\n }\n}\n\nfunction listFiles(directory: string): string[] {\n if (!existsSync(directory)) return []\n const files: string[] = []\n for (const entry of readdirSync(directory).sort()) {\n const path = join(directory, entry)\n if (statSync(path).isDirectory()) files.push(...listFiles(path))\n else if (MODEL_FILE.test(entry)) files.push(path)\n }\n return files\n}\n","import { randomUUID } from 'node:crypto'\nimport { DatabaseError, LogicError } from '../../errors'\n\nconst FIRST_NAMES = [\n 'Taylor', 'Abigail', 'Dayle', 'Mohamed', 'Jess', 'Nuno', 'James', 'Tim', 'Joe', 'Dries', 'Ana', 'Maria', 'Sofia',\n 'Liam', 'Noah', 'Emma', 'Olivia', 'Ava', 'Mia', 'Lucas', 'Hugo', 'Lea', 'Ines', 'Yuki', 'Aarav', 'Zara', 'Omar',\n 'Chloe', 'Ethan', 'Grace', 'Isaac', 'Julia', 'Kai', 'Leo', 'Nora', 'Owen', 'Priya', 'Quinn', 'Ruby', 'Sam',\n]\nconst LAST_NAMES = [\n 'Otwell', 'Smith', 'Johnson', 'Brown', 'Garcia', 'Miller', 'Davis', 'Martin', 'Lopez', 'Wilson', 'Anderson',\n 'Thomas', 'Moore', 'Jackson', 'White', 'Harris', 'Clark', 'Lewis', 'Walker', 'Hall', 'Young', 'King', 'Wright',\n 'Scott', 'Green', 'Baker', 'Adams', 'Nelson', 'Hill', 'Campbell', 'Mitchell', 'Roberts', 'Carter', 'Phillips',\n]\nconst WORDS = [\n 'lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur', 'adipiscing', 'elit', 'sed', 'do', 'eiusmod', 'tempor',\n 'incididunt', 'ut', 'labore', 'et', 'dolore', 'magna', 'aliqua', 'enim', 'ad', 'minim', 'veniam', 'quis', 'nostrud',\n 'exercitation', 'ullamco', 'laboris', 'nisi', 'aliquip', 'ex', 'ea', 'commodo', 'consequat', 'duis', 'aute',\n 'irure', 'in', 'reprehenderit', 'voluptate', 'velit', 'esse', 'cillum', 'fugiat', 'nulla', 'pariatur', 'excepteur',\n 'sint', 'occaecat', 'cupidatat', 'non', 'proident', 'sunt', 'culpa', 'qui', 'officia', 'deserunt', 'mollit', 'anim',\n]\nconst DOMAINS = ['example.com', 'example.org', 'example.net']\nconst CITIES = ['Springfield', 'Riverside', 'Fairview', 'Madison', 'Georgetown', 'Clinton', 'Salem', 'Franklin', 'Greenville', 'Bristol']\nconst COUNTRIES = ['France', 'Japan', 'Brazil', 'Canada', 'India', 'Kenya', 'Spain', 'Norway', 'Chile', 'Vietnam']\nconst COMPANY_SUFFIXES = ['Inc', 'LLC', 'Group', 'Ltd', 'and Sons']\n\n/** Thrown by fake().unique() when it can't find a new value (Laravel's OverflowException). */\nexport class FakerOverflowError extends DatabaseError {\n override readonly name = 'FakerOverflowError'\n}\n\nconst DURATION = /^([+-]?\\d+)\\s*(second|minute|hour|day|week|month|year)s?$/i\nconst UNIT_MS: Record<string, number> = {\n second: 1000, minute: 60_000, hour: 3_600_000, day: 86_400_000, week: 604_800_000, month: 2_629_800_000, year: 31_557_600_000,\n}\n\n/**\n * A small built-in fake data generator for factories and tests (the subset of Faker that factories typically use).\n * Seedable for repeatable data: fake().seed(1234). For anything richer, use sequence() or plain JavaScript.\n */\nexport class Faker {\n private state = Math.floor(Math.random() * 2 ** 32)\n private uniqueProxy: Faker | undefined\n private readonly seen = new Map<string, Set<unknown>>()\n\n /** Makes the sequence repeatable. */\n seed(seed: number): this {\n this.state = seed >>> 0\n return this\n }\n\n /** A float in [0, 1) (mulberry32). */\n random(): number {\n this.state = (this.state + 0x6d2b79f5) >>> 0\n let t = this.state\n t = Math.imul(t ^ (t >>> 15), t | 1)\n t ^= t + Math.imul(t ^ (t >>> 7), t | 61)\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296\n }\n\n /**\n * The same generator, but every call returns a value it hasn't returned before (per method). reset clears the\n * memory. Throws FakerOverflowError after 10000 tries.\n */\n unique(reset = false): Faker {\n if (reset) this.seen.clear()\n this.uniqueProxy ??= new Proxy(this, {\n get: (target, key, receiver) => {\n const value: unknown = Reflect.get(target, key, receiver)\n if (typeof value !== 'function' || typeof key === 'symbol' || key === 'unique' || key === 'seed' || key === 'random') return value\n return (...args: unknown[]) => {\n const seen = target.seen.get(key) ?? new Set<unknown>()\n target.seen.set(key, seen)\n for (let i = 0; i < 10_000; i++) {\n const candidate: unknown = (value as (...a: unknown[]) => unknown).apply(target, args)\n const fingerprint = typeof candidate === 'object' ? JSON.stringify(candidate) : candidate\n if (!seen.has(fingerprint)) {\n seen.add(fingerprint)\n return candidate\n }\n }\n throw new FakerOverflowError('Maximum retries of 10000 reached without finding a unique value')\n }\n },\n })\n return this.uniqueProxy\n }\n\n numberBetween(min = 0, max = 2147483647): number {\n return Math.floor(this.random() * (max - min + 1)) + min\n }\n\n /** A random integer with up to `digits` digits (strict: exactly that many). */\n randomNumber(digits = 9, strict = false): number {\n const max = 10 ** digits - 1\n return strict ? this.numberBetween(10 ** (digits - 1), max) : this.numberBetween(0, max)\n }\n\n randomFloat(decimals = 2, min = 0, max = 1000): number {\n return Number((this.random() * (max - min) + min).toFixed(decimals))\n }\n\n randomDigit(): number {\n return this.numberBetween(0, 9)\n }\n\n /** true with `chanceOfGettingTrue` percent. */\n boolean(chanceOfGettingTrue = 50): boolean {\n return this.random() * 100 < chanceOfGettingTrue\n }\n\n randomElement<T>(items: readonly T[]): T {\n if (!items.length) throw new LogicError('randomElement() needs at least one item.')\n return items[this.numberBetween(0, items.length - 1)]!\n }\n\n /** `count` distinct items, in random order. */\n randomElements<T>(items: readonly T[], count = 1): T[] {\n const pool = [...items]\n const picked: T[] = []\n while (picked.length < count && pool.length) picked.push(pool.splice(this.numberBetween(0, pool.length - 1), 1)[0]!)\n return picked\n }\n\n shuffle<T>(items: readonly T[]): T[] {\n return this.randomElements(items, items.length)\n }\n\n firstName(): string {\n return this.randomElement(FIRST_NAMES)\n }\n\n lastName(): string {\n return this.randomElement(LAST_NAMES)\n }\n\n name(): string {\n return `${this.firstName()} ${this.lastName()}`\n }\n\n userName(): string {\n return `${this.firstName().toLowerCase()}.${this.lastName().toLowerCase()}${this.numberBetween(1, 999)}`\n }\n\n /** An address at example.com/org/net, which never delivers mail. */\n safeEmail(): string {\n return `${this.userName()}@${this.randomElement(DOMAINS)}`\n }\n\n email(): string {\n return this.safeEmail()\n }\n\n word(): string {\n return this.randomElement(WORDS)\n }\n\n words(count = 3): string[] {\n return Array.from({ length: count }, () => this.word())\n }\n\n sentence(words = 6): string {\n const text = this.words(Math.max(1, words)).join(' ')\n return `${text.charAt(0).toUpperCase()}${text.slice(1)}.`\n }\n\n sentences(count = 3): string[] {\n return Array.from({ length: count }, () => this.sentence(this.numberBetween(4, 10)))\n }\n\n paragraph(sentences = 3): string {\n return this.sentences(sentences).join(' ')\n }\n\n paragraphs(count = 3): string[] {\n return Array.from({ length: count }, () => this.paragraph())\n }\n\n /** Text of at most `maxChars` characters. */\n text(maxChars = 200): string {\n let text = ''\n while (text.length < maxChars) text = text ? `${text} ${this.sentence()}` : this.sentence()\n return text.slice(0, maxChars).trimEnd()\n }\n\n slug(words = 3): string {\n return this.words(words).join('-')\n }\n\n title(): string {\n return this.sentence(this.numberBetween(2, 5)).slice(0, -1)\n }\n\n url(): string {\n return `https://${this.randomElement(DOMAINS)}/${this.slug()}`\n }\n\n city(): string {\n return this.randomElement(CITIES)\n }\n\n country(): string {\n return this.randomElement(COUNTRIES)\n }\n\n company(): string {\n return `${this.lastName()} ${this.randomElement(COMPANY_SUFFIXES)}`\n }\n\n phoneNumber(): string {\n return this.numerify('+1-###-###-####')\n }\n\n uuid(): string {\n return randomUUID()\n }\n\n /** Replaces every # with a digit. */\n numerify(pattern = '###'): string {\n return pattern.replace(/#/g, () => String(this.randomDigit()))\n }\n\n /** Replaces every ? with a letter. */\n lexify(pattern = '????'): string {\n return pattern.replace(/\\?/g, () => String.fromCharCode(97 + this.numberBetween(0, 25)))\n }\n\n /** numerify() and lexify() together. */\n bothify(pattern = '## ??'): string {\n return this.lexify(this.numerify(pattern))\n }\n\n hexColor(): string {\n return `#${this.numberBetween(0, 0xffffff).toString(16).padStart(6, '0')}`\n }\n\n /** A date between two points ('-30 years', 'now', '+1 week', a Date). */\n dateTimeBetween(start: Date | string = '-30 years', end: Date | string = 'now'): Date {\n const from = this.resolveDate(start).getTime()\n const to = this.resolveDate(end).getTime()\n return new Date(Math.floor(from + this.random() * (to - from)))\n }\n\n /** A date before `max` (default now). */\n dateTime(max: Date | string = 'now'): Date {\n return this.dateTimeBetween(new Date(0), max)\n }\n\n /** A Y-m-d date string before `max`. */\n date(max: Date | string = 'now'): string {\n return this.dateTime(max).toISOString().slice(0, 10)\n }\n\n private resolveDate(value: Date | string): Date {\n if (value instanceof Date) return value\n if (value === 'now') return new Date()\n const match = DURATION.exec(value.trim())\n if (match) return new Date(Date.now() + Number(match[1]) * UNIT_MS[match[2]!.toLowerCase()]!)\n const parsed = new Date(value)\n if (Number.isNaN(parsed.getTime())) throw new LogicError(`Unable to parse [${value}] as a date.`)\n return parsed\n }\n}\n\nlet shared: Faker | undefined\n\n/** The shared fake data generator (Laravel's fake() helper): fake().name(), fake().unique().safeEmail(). */\nexport function fake(): Faker {\n return (shared ??= new Faker())\n}\n","import type { Class, RouteModelResolver } from '@orieljs/contracts'\nimport { Model } from './Eloquent/Model'\nimport { LogicError, ModelNotFoundError } from './errors'\nimport type { ModelRegistry } from './ModelRegistry'\n\n/**\n * Route model binding for the router: {post} → Post (StudlyCase of the parameter, from the app/Models registry),\n * {post:slug} → Post where slug = value, Route.model('author', User) → resolveExplicit(User, …).\n * Named RouteModelResolverImpl so it never shadows the RouteModelResolver token.\n */\nexport class RouteModelResolverImpl implements RouteModelResolver {\n constructor(private readonly registry: ModelRegistry) {}\n\n /** undefined when no model is called `parameter` (the router keeps the string); throws ModelNotFoundError (404) when the row is missing. */\n async resolve(parameter: string, value: string, field?: string): Promise<unknown | undefined> {\n const model = this.registry.resolve(parameter)\n if (!model) return undefined\n return this.resolveExplicit(model, value, field)\n }\n\n /** The model of `model` whose route key (or `field`) equals value; ModelNotFoundError (404) when there is none. */\n async resolveExplicit(model: Class<unknown>, value: string, field?: string): Promise<unknown> {\n if (!(model.prototype instanceof Model)) throw new LogicError(`Route model binding needs a Model class; [${model.name}] isn't one.`)\n const cls = model as unknown as typeof Model\n const found = await cls.prototypeInstance().resolveRouteBinding(value, field)\n if (!found) throw new ModelNotFoundError(cls.name, [value])\n return found\n }\n}\n","import {\n Application,\n ClassRegistry,\n ConfigRepository,\n ConsoleKernel,\n DatabaseManager,\n HttpRequest,\n PaginationState,\n RouteModelResolver,\n} from '@orieljs/contracts'\nimport { BindingResolutionError, currentContainer } from '@orieljs/container'\nimport { ServiceProvider } from '@orieljs/support'\nimport { registerMigrationCommands, registerModelTypesCommand, type DatabaseCommandContext } from './Console/commands'\nimport { DatabaseManagerImpl, type DatabaseConfig } from './DatabaseManager'\nimport { discoverFactories } from './Eloquent/Factories/Factory'\nimport { Model } from './Eloquent/Model'\nimport { SchemaBuilderToken } from './facades'\nimport { ModelRegistry } from './ModelRegistry'\nimport { AbstractPaginator } from './Pagination/AbstractPaginator'\nimport { RouteModelResolverImpl } from './RouteModelResolver'\n\nconst env = (key: string, fallback?: string): string | undefined => {\n const value = process.env[key]\n return value === undefined || value === '' ? fallback : value\n}\n\n/** Laravel 11's config/database.php defaults (the app's config/database.ts wins, key by key). */\nexport function databaseConfigDefaults(app: Pick<Application, 'databasePath'>): DatabaseConfig & Record<string, unknown> {\n return {\n default: env('DB_CONNECTION', 'sqlite')!,\n connections: {\n sqlite: {\n driver: 'sqlite',\n url: env('DB_URL'),\n database: env('DB_DATABASE', app.databasePath('database.sqlite')),\n foreign_key_constraints: env('DB_FOREIGN_KEYS', 'true') !== 'false',\n },\n mysql: {\n driver: 'mysql',\n url: env('DB_URL'),\n host: env('DB_HOST', '127.0.0.1'),\n port: env('DB_PORT', '3306'),\n database: env('DB_DATABASE', 'laravel'),\n username: env('DB_USERNAME', 'root'),\n password: env('DB_PASSWORD', ''),\n charset: env('DB_CHARSET', 'utf8mb4'),\n collation: env('DB_COLLATION', 'utf8mb4_unicode_ci'),\n },\n pgsql: {\n driver: 'pgsql',\n url: env('DB_URL'),\n host: env('DB_HOST', '127.0.0.1'),\n port: env('DB_PORT', '5432'),\n database: env('DB_DATABASE', 'laravel'),\n username: env('DB_USERNAME', 'root'),\n password: env('DB_PASSWORD', ''),\n charset: env('DB_CHARSET', 'utf8'),\n search_path: 'public',\n },\n },\n migrations: { table: 'migrations', update_date_on_publish: true } as DatabaseConfig['migrations'],\n // Laravel keeps the Redis connections here; Cache, Queue and Session resolve database.redis.<connection>.\n redis: {\n client: 'ioredis',\n default: { url: env('REDIS_URL'), host: '127.0.0.1', port: 6379, password: undefined, db: 0 },\n cache: { url: env('REDIS_URL'), host: '127.0.0.1', port: 6379, password: undefined, db: 1 },\n },\n }\n}\n\n/** The current request, when the current container is a request scope with one. */\nfunction currentRequest(): HttpRequest | undefined {\n const container = currentContainer()\n if (!container?.bound(HttpRequest)) return undefined\n try {\n return container.make(HttpRequest)\n } catch {\n return undefined // scoped binding resolved outside a request scope (R13)\n }\n}\n\n/**\n * The PaginationState of the current container, when it resolves (Live binds one for the application, which answers\n * while a WithPagination component mounts, runs an update's hooks and actions, or renders).\n */\nfunction paginationState(): PaginationState | undefined {\n const container = currentContainer()\n if (!container?.bound(PaginationState)) return undefined\n try {\n return container.make(PaginationState)\n } catch (error) {\n if (error instanceof BindingResolutionError) return undefined // a scoped binding resolved outside a request scope\n throw error\n }\n}\n\n/**\n * Points the paginators at the current request: ?page=, ?cursor=, the URL and the query string (Laravel's resolvers).\n * A bound PaginationState is asked first for the page and the path (Livewire's WithPagination replaces Laravel's\n * resolvers the same way); what it leaves undefined comes from the request.\n */\nexport function usePaginationResolvers(): void {\n AbstractPaginator.currentPathResolver = () => paginationState()?.currentPath() ?? currentRequest()?.url() ?? '/'\n AbstractPaginator.currentPageResolver = (pageName) => {\n const state = paginationState()?.currentPage(pageName)\n if (state !== undefined) return state\n const page = Number(currentRequest()?.input(pageName))\n return Number.isInteger(page) && page >= 1 ? page : 1\n }\n AbstractPaginator.queryStringResolver = () => (currentRequest()?.query<Record<string, unknown>>() ?? {})\n AbstractPaginator.currentCursorResolver = (cursorName) => currentRequest()?.input(cursorName)\n}\n\n/**\n * Binds the database layer: the DatabaseManager (a root singleton owning the pools) behind the DB facade, the\n * Schema facade's SchemaBuilder, the ModelRegistry and the RouteModelResolver. At boot it discovers app/Models,\n * factories (console and tests), points pagination at the current request, and registers the migrate*, db:seed,\n * make:migration and model:types commands when a ConsoleKernel is bound. It also merges Laravel's database.redis\n * connections, which Cache, Queue and Session read.\n */\nexport class DatabaseServiceProvider extends ServiceProvider {\n override register(): void {\n // Models booted by an earlier application (tests make one per test) boot again, so the listeners that\n // static booted() registers reach this application's EventDispatcher.\n Model.clearBootedModels()\n this.mergeConfigFrom(databaseConfigDefaults(this.app), 'database')\n this.app.singleton(DatabaseManager, () => new DatabaseManagerImpl(() => this.app.make(ConfigRepository).get<DatabaseConfig>('database')))\n // At the end of the process: close every connection's pool (never builds a manager to do it).\n this.app.onShutdown(async () => {\n if (this.app.resolved(DatabaseManager)) await this.app.make(DatabaseManager).disconnectAll()\n })\n this.app.singleton(ModelRegistry)\n this.app.singleton(RouteModelResolver, () => new RouteModelResolverImpl(this.app.make(ModelRegistry)))\n this.app.bind(SchemaBuilderToken, () => this.manager().getSchemaBuilder())\n }\n\n override async boot(): Promise<void> {\n // post.author.name reads the relation method's name: warn about it while developing.\n Model.warnOnRelationPropertyAccess(!this.app.isProduction())\n usePaginationResolvers()\n const registry = this.app.make(ModelRegistry)\n const classes = this.app.bound(ClassRegistry) ? this.app.make(ClassRegistry) : undefined\n for (const entry of await registry.discover(this.app.appPath('Models'))) {\n // Queue and Live serialize models as class name + key.\n if (classes && !classes.has(entry.name)) classes.register(entry.model, entry.name)\n }\n if (this.app.runningInConsole() || this.app.runningUnitTests()) await discoverFactories(this.app.databasePath('factories'))\n if (this.app.bound(ConsoleKernel)) {\n const kernel = this.app.make(ConsoleKernel)\n const context: DatabaseCommandContext = { app: this.app, manager: () => this.manager(), models: async () => registry }\n registerMigrationCommands(kernel, context)\n registerModelTypesCommand(kernel, context)\n }\n }\n\n private manager(): DatabaseManagerImpl {\n return this.app.make(DatabaseManager) as DatabaseManagerImpl\n }\n}\n"],"mappings":";AAGO,IAAM,qBAAN,cAAiC,MAA4C;AAAA,EAKlF,YACW,OACA,MAAiB,CAAC,GAC3B;AACA,UAAM,+BAA+B,KAAK,IAAI,IAAI,SAAS,MAAM,IAAI,IAAI,MAAM,EAAE,KAAK,IAAI,IAAI,GAAG,EAAE;AAH1F;AACA;AAAA,EAGX;AAAA,EAJW;AAAA,EACA;AAAA,EANF,OAAO;AAAA,EACP,SAAS;AAAA,EACA,OAAO;AAQ3B;AAMO,IAAe,gBAAf,cAAqC,MAA4B;AAAA,EAC7D,OAAO;AAAA,EACP,SAAS;AACpB;AAGO,IAAM,aAAN,cAAyB,cAAc;AAAA,EAG5C,YACW,gBACAA,MACA,UACT,OACA;AACA,UAAM,GAAG,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,iBAAiB,cAAc,UAAUA,IAAG,KAAK,EAAE,MAAM,CAAC;AALhH;AACA,eAAAA;AACA;AAAA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AA,EAEA,MAAe,OAAsB;AAEnC,UAAM,6BAA6B,CAAC,KAAK,IAAI,aAAa,CAAC;AAC3D,2BAAuB;AACvB,UAAMC,YAAW,KAAK,IAAI,KAAK,aAAa;AAC5C,UAAM,UAAU,KAAK,IAAI,MAAMC,cAAa,IAAI,KAAK,IAAI,KAAKA,cAAa,IAAI;AAC/E,eAAW,SAAS,MAAMD,UAAS,SAAS,KAAK,IAAI,QAAQ,QAAQ,CAAC,GAAG;AAEvE,UAAI,WAAW,CAAC,QAAQ,IAAI,MAAM,IAAI,EAAG,SAAQ,SAAS,MAAM,OAAO,MAAM,IAAI;AAAA,IACnF;AACA,QAAI,KAAK,IAAI,iBAAiB,KAAK,KAAK,IAAI,iBAAiB,EAAG,OAAM,kBAAkB,KAAK,IAAI,aAAa,WAAW,CAAC;AAC1H,QAAI,KAAK,IAAI,MAAM,aAAa,GAAG;AACjC,YAAM,SAAS,KAAK,IAAI,KAAK,aAAa;AAC1C,YAAM,UAAkC,EAAE,KAAK,KAAK,KAAK,SAAS,MAAM,KAAK,QAAQ,GAAG,QAAQ,YAAYA,UAAS;AACrH,gCAA0B,QAAQ,OAAO;AACzC,gCAA0B,QAAQ,OAAO;AAAA,IAC3C;AAAA,EACF;AAAA,EAEQ,UAA+B;AACrC,WAAO,KAAK,IAAI,KAAKD,gBAAe;AAAA,EACtC;AACF;","names":["sql","castType","sql","Database","importOptional","importOptional","sql","Collection","sql","text","sql","list","sets","pad","sql","Collection","value","sql","sql","text","list","sql","join","sql","sql","join","sql","columnList","text","clauses","list","sql","sql","AsyncLocalStorage","AsyncLocalStorage","AsyncLocalStorage","DatabaseManager","Collection","currentContainer","Str","Collection","Str","Builder","Str","scopes","Collection","Collection","text","Collection","Collection","Collection","present","join","Collection","Str","Str","registry","Builder","Str","Collection","Builder","list","Collection","Str","Str","Collection","Collection","Str","list","Collection","join","AsyncLocalStorage","currentContainer","AsyncLocalStorage","currentContainer","Builder","handler","AsyncLocalStorage","Str","currentContainer","handler","scopes","currentContainer","sql","lower","Str","DatabaseManager","Builder","text","raw","Collection","list","Str","existsSync","join","Str","pad","Str","join","existsSync","existsSync","readdirSync","join","pathToFileURL","existsSync","readdirSync","join","pathToFileURL","existsSync","join","relative","pathToFileURL","Str","Str","list","list","handler","join","existsSync","pathToFileURL","relative","existsSync","readdirSync","join","pathToFileURL","Str","pathToFileURL","Str","existsSync","readdirSync","join","text","registry","ClassRegistry","DatabaseManager","currentContainer","currentContainer","DatabaseManager","registry","ClassRegistry"]}
|