/** * Database utilities using bun-query-builder * * This module provides the database connection and query builder * configured using the stacks database config. */ import { AsyncLocalStorage } from 'node:async_hooks' import { isPromise, isProxy } from 'node:util/types' import type { QueryHooks } from '@stacksjs/query-builder' import { config as queryBuilderConfig, createQueryBuilder, registerPersistentQueryHooks, resetConnection as resetQueryBuilderConnection, setConfig, settle, standingFor, wait } from '@stacksjs/query-builder' // Use default values to avoid circular dependencies initially // These can be overridden later once config is fully loaded // Read from environment variables first import { SQL } from 'bun' import { closeDatabaseConnectionsAndPending, retireDatabaseConnections } from './connection-lifecycle' import type { PendingDatabaseConnectionClosures } from './connection-lifecycle' import { runInTransactionScope } from './transaction-context' import { env as envVars } from '@stacksjs/env/runtime' import type { QueryBuilderDialect } from './dialect' import type { FrameworkSchema } from './framework-schema' import type { PoolConfig, ReadPolicyConfig, ReplicaConfig } from './driver-config' import { resolvePoolConfig } from './pool-defaults' import { getConnectionDefaults } from './defaults' import { isLibsqlDriver, isMysqlWire, isVitessSharded, normalizeDatabaseDriver, setConfiguredDatabaseDriver, toQueryBuilderDialect } from './dialect' import { relativeMigrationDirectory, resolveMigrationDirectory, snapshotDirForQueryBuilder } from './migration-path' import { configureDatabaseRoutingContext, contextInTransaction, markContextWrote, replicaConnectionKey, resolveReplicaConnection, runInDatabaseRoutingContext, selectReplica, shouldRouteToReplica, withDatabaseRoutingContext, withTransactionContext } from './replicas' import { aggregateFunctions } from './types' interface DbConnectionConfig { database?: string /** A libSQL server (`turso`): `libsql://…`, `https://…`, or `http://…` for `turso dev`. */ url?: string /** Turso database token. A secret: never logged. */ authToken?: string name?: string host?: string username?: string password?: string port?: number prefix?: string pool?: PoolConfig replicas?: ReplicaConfig[] sharded?: boolean } interface DbConfig { /** The chosen dialect, from `config/database.ts`. */ default?: string connections: { sqlite: DbConnectionConfig mysql: DbConnectionConfig singlestore: DbConnectionConfig vitess: DbConnectionConfig postgres: DbConnectionConfig turso?: DbConnectionConfig } reads?: ReadPolicyConfig } const sqliteDefaults = getConnectionDefaults('sqlite', envVars) const mysqlDefaults = getConnectionDefaults('mysql', envVars) const postgresDefaults = getConnectionDefaults('postgres', envVars) let appEnv: string = envVars.APP_ENV || 'local' let dbDriver: string = normalizeDatabaseDriver(envVars.DB_CONNECTION || 'sqlite') let queryBuilderDialect: QueryBuilderDialect = toQueryBuilderDialect(dbDriver) let queryLoggingEnabled = envVars.DB_QUERY_LOGGING_ENABLED ?? !isProductionEnvironment(appEnv) /** * Every connection as the environment alone describes it. * * The baseline an application's `config/database.ts` is merged over, per * connection and per field, so a connection the app does not define - or a * field it leaves out - still comes from `DB_*` rather than vanishing. */ const envDbConfig = (): DbConfig => ({ connections: { sqlite: { database: sqliteDefaults.database, prefix: '' }, mysql: { name: mysqlDefaults.database, host: mysqlDefaults.host, username: mysqlDefaults.username, password: mysqlDefaults.password, port: mysqlDefaults.port, prefix: '' }, singlestore: { name: mysqlDefaults.database, host: mysqlDefaults.host, username: mysqlDefaults.username, password: mysqlDefaults.password, port: mysqlDefaults.port, prefix: '' }, // vtgate's port, not mysqld's — see VitessConfig in ./driver-config. vitess: { name: mysqlDefaults.database, host: mysqlDefaults.host, username: mysqlDefaults.username, password: mysqlDefaults.password, port: 15306, prefix: '', sharded: isVitessSharded() }, postgres: { name: postgresDefaults.database, host: postgresDefaults.host, username: postgresDefaults.username, password: postgresDefaults.password, port: postgresDefaults.port, prefix: '' }, turso: { url: envVars.TURSO_DATABASE_URL || '', authToken: envVars.TURSO_AUTH_TOKEN || '', prefix: '' }, }, }) let dbConfig: DbConfig = envDbConfig() // Test-only config mutex (stacksjs/stacks#1862 follow-up) ------------------ // // `initializeDbConfig` mutates process-wide state (`dbConfig`, `dbDriver`, // `appEnv`, and the cached `_dbInstance` below). Bun's test runner evaluates // multiple test files' top-level code — including their `beforeAll`/`it` // callbacks — concurrently in one process, so two files that each want // their own isolated sqlite database and both call `initializeDbConfig()` // can interleave: file B's call clobbers file A's config (and nulls the // shared `_dbInstance`) while file A's own hooks/tests are still mid-flight, // silently pointing file A's queries at file B's database instead. // // There's no per-file isolation of this state today — that would need // AsyncLocalStorage-scoped config threaded through bun:test's hook // scheduling, which bun:test doesn't expose a seam for — so instead, any // test file that calls `initializeDbConfig` with its own database should // hold this lock for its *entire* lifetime: acquire first thing in // `beforeAll`, release last thing in `afterAll` (wrap the release in a // `finally` so a thrown cleanup error can't leave the lock stuck and hang // every subsequent file). That serializes just the subset of files that // mutate this shared config against each other, while every other test // file keeps running fully concurrently. let dbConfigLockTail: Promise = Promise.resolve() /** * How long one file may hold the config lock before the queue moves on without * it. Generous, because a holder is a whole test file: it should never be * reached by a file that is merely slow, only by one that has stopped. */ const DB_CONFIG_LOCK_MAX_HOLD_MS = 60_000 export function acquireDbConfigLock(): Promise<() => void> { let release: () => void = () => {} const held = new Promise((resolve) => { release = resolve }) const acquired = dbConfigLockTail.then(() => { // Armed on acquisition rather than on request, so a long queue does not // start the clock on files that are still waiting their turn. // // The advice above - always release from a `finally` - is still the right // way to use this, but it cannot be the only thing standing between one // file and every file after it. A holder that never releases, because it // crashed or its own hook timed out before `afterAll` ran, used to strand // the chain permanently: the next file's `beforeAll` waited on a promise // nothing would ever resolve, and bun reported it as a hook timeout in a // file that had done nothing wrong. That is what this watchdog is for. const watchdog = setTimeout(() => { console.warn( `[database] the db config lock was held for over ${DB_CONFIG_LOCK_MAX_HOLD_MS / 1000}s. ` + 'Releasing it so the queue can proceed - a test file most likely failed before its afterAll ran.', ) release() }, DB_CONFIG_LOCK_MAX_HOLD_MS) // Never keep the process alive just to watch a lock. ;(watchdog as { unref?: () => void }).unref?.() void held.then(() => clearTimeout(watchdog)) return release }) // `catch` keeps the chain alive: a rejection anywhere in it would otherwise // reject every future acquisition rather than just the file that failed. dbConfigLockTail = dbConfigLockTail.then(() => held).catch(() => {}) return acquired } // Function to initialize the config when it's available /** * The slice of the app config this reads, written out rather than left as * `any`. It is called with the whole config object, so naming only what it * consumes keeps it callable from anywhere while still checking the four * paths it walks. */ export interface DbConfigSource { app?: { env?: string } database?: { default?: string /* * Every connection optional, because that is how the app config declares * them - `config/database.ts` types each dialect as optional even though * it supplies them all. The stored `DbConfig` below requires all five, so * these two shapes were never the same type; the parameter being `any` is * what let them be assigned to one another without anybody noticing. */ connections?: Partial reads?: DbConfig['reads'] queryLogging?: { enabled?: boolean } } } export function initializeDbConfig(config: DbConfigSource | null | undefined): void { if (config?.app?.env) appEnv = config.app.env if (config?.database?.default) { dbDriver = normalizeDatabaseDriver(config.database.default) // So every pass that renders DDL resolves the configured driver rather // than `DB_CONNECTION`. See `resolvedDatabaseDriver` in ./dialect. setConfiguredDatabaseDriver(dbDriver) } queryBuilderDialect = toQueryBuilderDialect(dbDriver) // Merged over the environment's baseline, per connection and per field, // rather than replacing it. Replacing it dropped every connection the // config did not name, so their `DB_*` values were ignored, and left the // migration runner - which read the environment directly - pointed at a // different database from the app whenever the two disagreed // (`database: 'database/myapp.sqlite'` in config, nothing in `.env`). if (config?.database?.connections) { const baseline = envDbConfig() const supplied = config.database.connections as Partial> const connections: Record = { ...baseline.connections } for (const [name, connection] of Object.entries(supplied)) { if (connection && typeof connection === 'object') connections[name] = { ...(connections[name] ?? {}), ...connection } } dbConfig = { ...(config.database as DbConfig), connections: connections as DbConfig['connections'] } } configureDatabaseRoutingContext(getReplicas().length > 0) queryLoggingEnabled = config?.database?.queryLogging?.enabled ?? envVars.DB_QUERY_LOGGING_ENABLED ?? !isProductionEnvironment(appEnv) syncDatabaseQueryHooks() // Update bun-query-builder config updateQueryBuilderConfig() // Drop the cached query-builder instance so the next `db` access renders // SQL for the overridden dialect. The connection itself is rebuilt by // bun-query-builder's signature check, but the cached instance keeps // rendering with the dialect captured at creation — a config override // from mysql back to sqlite otherwise executes `NOW()`-style SQL against // the sqlite connection (cross-file test interference). _dbInstance = null // Replica builders own their own connections to hosts named in the old // config, so a reconfigured replica list must not keep being served by // them. Dropped rather than closed: the pools are garbage-collected with // the builders, and closing here would race any read still in flight. _replicaInstances = new Map() } // Simple functions with defensive defaults function getEnv(): string { return appEnv } function isProductionEnvironment(value: string): boolean { return value === 'production' || value === 'prod' } function getDriver(): string { return dbDriver } function getDatabaseConfig(): DbConfig { return dbConfig } /** * The database this process talks to: the driver and every connection, as * resolved from `config/database.ts` over the environment. * * One answer for everything that opens a connection. The migration runner * used to build its own from `DB_*` alone, so an app whose config named a * different SQLite file was migrated in one file and served from another. * Await `ensureDatabaseConfigLoaded()` first: until the app's config has * loaded, this is the environment's baseline. */ export function resolvedDatabaseConfig(): { driver: string, connections: DbConfig['connections'] } { return { driver: dbDriver, connections: dbConfig.connections } } /** * Get the dialect type for bun-query-builder. * * Collapses through the capability table rather than an if-chain: Stacks * tracks dialects that bun-query-builder has no separate renderer for * (they diverge only in DDL), and those must be handed down as the dialect * whose SQL they actually speak. Unknown values still fall back to sqlite, * matching the previous behavior. */ function getDialect(): QueryBuilderDialect { return queryBuilderDialect } /** The initialized database's SQL dialect, including application config overrides. */ export { getDialect as getDatabaseDialect } /** * Get database configuration for bun-query-builder */ interface QueryBuilderDatabaseConfig { database: string username?: string password?: string host?: string port?: number url?: string authToken?: string } /** * The connection settings handed to bun-query-builder. * * `url` and `authToken` are always present, `undefined` unless the driver is * `turso`: `setConfig` MERGES the database section, so leaving the keys out * when switching back to a file would keep the libSQL URL - and every query * would keep going to the server. */ function getDbConfig(): QueryBuilderDatabaseConfig { return { url: undefined, authToken: undefined, ...getDriverDbConfig() } } function getDriverDbConfig(): QueryBuilderDatabaseConfig { const driver = getDriver() const database = getDatabaseConfig() const env = getEnv() // Turso / libSQL: SQLite's SQL over Hrana-over-HTTP. bun-query-builder keeps // the sqlite dialect and selects its libSQL transport from the URL. if (isLibsqlDriver(driver)) { const turso = database.connections?.turso const url = turso?.url || envVars.TURSO_DATABASE_URL || '' if (!url) { throw new Error( '[database] DB_CONNECTION=turso needs the database URL: set TURSO_DATABASE_URL ' + '(libsql://-.turso.io, or http://127.0.0.1:8080 for `turso dev`) or connections.turso.url in config/database.ts.', ) } return { database: url, url, authToken: turso?.authToken || envVars.TURSO_AUTH_TOKEN || undefined, } } if (driver === 'sqlite') { const defaultName = env !== 'testing' ? 'database/stacks.sqlite' : 'database/stacks_testing.sqlite' return { database: database.connections?.sqlite?.database ?? defaultName, } } if (driver === 'mysql') { return { database: database.connections?.mysql?.name || 'stacks', host: database.connections?.mysql?.host ?? '127.0.0.1', username: database.connections?.mysql?.username ?? 'root', password: database.connections?.mysql?.password ?? '', port: database.connections?.mysql?.port ?? 3306, } } // SingleStore reuses the MySQL connection shape (wire protocol + port 3306). if (driver === 'singlestore') { return { database: database.connections?.singlestore?.name || 'stacks', host: database.connections?.singlestore?.host ?? '127.0.0.1', username: database.connections?.singlestore?.username ?? 'root', password: database.connections?.singlestore?.password ?? '', port: database.connections?.singlestore?.port ?? 3306, } } // Vitess is dialed through vtgate on the MySQL wire protocol; `name` is a // keyspace rather than a database, but it occupies the same slot. if (driver === 'vitess') { return { database: database.connections?.vitess?.name || 'stacks', host: database.connections?.vitess?.host ?? '127.0.0.1', username: database.connections?.vitess?.username ?? 'root', password: database.connections?.vitess?.password ?? '', port: database.connections?.vitess?.port ?? 15306, } } if (driver === 'postgres') { const dbName = database.connections?.postgres?.name ?? 'stacks' const finalDbName = env === 'testing' ? `${dbName}_testing` : dbName return { database: finalDbName, host: database.connections?.postgres?.host ?? '127.0.0.1', username: database.connections?.postgres?.username ?? '', password: database.connections?.postgres?.password ?? '', port: database.connections?.postgres?.port ?? 5432, } } return { database: ':memory:' } } /** * Update bun-query-builder configuration */ /** * Where the model snapshot lives, relative to the project root. * * Exported and referenced by every `setConfig` call rather than repeated at * each one: `setConfig` replaces the query-builder config wholesale, so a call * site that omits this silently reverts the snapshot to the library default * and writes `.qb` into the project root. That has now happened twice from two * different call sites, which is a sign the value wants one home. */ export const QB_SNAPSHOT_DIR = 'storage/framework/database' /** * The snapshot directory to hand to `setConfig`, resolved at call time. * * Read fresh on every call rather than frozen into a module constant: on a * Capistrano-style deploy `DB_SNAPSHOT_PATH` points at a shared directory that * outlives the release, and a value captured at import time would miss an env * loaded after this module (stacksjs/stacks#2351). */ export function qbSnapshotDir(): string { return snapshotDirForQueryBuilder() } let migrationDirOrigin: { value: string | undefined } | undefined /** * The user's directory, captured before either connection setup or migration * generation writes a resolved corpus into shared query-builder config. * Capturing only in the generator was too late after MySQL connection setup: * a later Postgres generation inherited the MySQL directory (#2949). */ export function qbMigrationDir(): string | undefined { migrationDirOrigin ??= { value: queryBuilderConfig.migrationDir } return migrationDirOrigin.value } /** * Process-wide query-builder soft-delete filtering must stay disabled. * * The raw query builder has no model definition, so it cannot know whether * the selected table carries the `useSoftDeletes` trait or even has a * `deleted_at` column. ModelQueryBuilder applies the trait-aware scope, and * the generated REST routes apply it from the model definition. Enabling * this global filter would incorrectly scope every raw table query. */ export const RAW_QUERY_SOFT_DELETE_CONFIG = { enabled: false, column: 'deleted_at', defaultFilter: true, } as const export interface DatabaseQueryLogEvent { query: { sql: string parameters?: unknown[] } queryDurationMillis: number error?: unknown } export function createDatabaseQueryHooks(dispatch: (event: DatabaseQueryLogEvent) => void | Promise): QueryHooks { function forward(event: DatabaseQueryLogEvent): void { try { void Promise.resolve(dispatch(event)).catch(() => {}) } catch { // Query diagnostics must never change the query result. } } return { onQueryEnd: event => forward({ query: { sql: event.sql, parameters: event.params, }, queryDurationMillis: event.durationMs, }), onQueryError: event => forward({ query: { sql: event.sql, parameters: event.params, }, queryDurationMillis: event.durationMs, error: event.error, }), } } let queryLoggerModule: Promise | undefined function forwardDatabaseQuery(event: DatabaseQueryLogEvent): void { // Keep delivery asynchronous without resolving the same module per query. // Failed imports remain retryable, so an unavailable logger cannot poison // diagnostics for the rest of the process. // Diagnostics run later and own their persistence, not the caller's // transaction connection. Preserve other ALS state (request/recursion). transactionConnection.exit(() => { queryLoggerModule ??= import('./query-logger').catch((error) => { queryLoggerModule = undefined throw error }) void queryLoggerModule .then(({ logQuery }) => logQuery(event)) .catch(() => {}) }) } let unregisterDatabaseQueryHooks: (() => void) | undefined function syncDatabaseQueryHooks(): void { const shouldInstall = !isProductionEnvironment(appEnv) || queryLoggingEnabled if (shouldInstall && !unregisterDatabaseQueryHooks) { unregisterDatabaseQueryHooks = registerPersistentQueryHooks(createDatabaseQueryHooks(forwardDatabaseQuery)) } else if (!shouldInstall && unregisterDatabaseQueryHooks) { unregisterDatabaseQueryHooks() unregisterDatabaseQueryHooks = undefined } } syncDatabaseQueryHooks() /** * The active connection's pool: its declared block over the framework's * defaults, with DB_POOL_* from the environment on top (see pool-defaults). * * SQLite is excluded on purpose: it is embedded and single-connection, so * a pool block there is a config mistake rather than something to honor. */ function getPoolConfig(): PoolConfig | undefined { const driver = getDriver() // libSQL requests are stateless HTTP calls Bun's fetch pools itself. if (driver === 'sqlite' || isLibsqlDriver(driver)) return undefined const connections = getDatabaseConfig().connections as Record return resolvePoolConfig(connections?.[driver]?.pool, envVars) } /** Replicas declared on the active connection. */ const EMPTY_REPLICAS: ReplicaConfig[] = [] function getReplicas(): ReplicaConfig[] { const driver = getDriver() // Turso replicates behind one URL; there is no replica list to route to. if (driver === 'sqlite' || isLibsqlDriver(driver)) return EMPTY_REPLICAS const connections = getDatabaseConfig().connections as Record return connections?.[driver]?.replicas ?? EMPTY_REPLICAS } /** The app's read-routing policy. */ function getReadPolicy(): ReadPolicyConfig { return getDatabaseConfig().reads ?? {} } export { runInDatabaseRoutingContext, withDatabaseRoutingContext } /** * Translate the framework's millisecond pool knobs onto Bun's SQL driver * options, which are named differently and measured in seconds. * * `min` and `autoReconnect` are accepted on `PoolConfig` but not forwarded * — Bun's driver manages both itself, and passing unknown keys through * would be silently ignored anyway. Keeping them out of the mapping makes * that deliberate rather than accidental. */ function toBunPoolOptions(pool?: PoolConfig): Record { if (!pool) return {} const options: Record = {} if (pool.max !== undefined) options.max = pool.max if (pool.idleTimeoutMs !== undefined) options.idleTimeout = Math.round(pool.idleTimeoutMs / 1000) if (pool.acquireTimeoutMs !== undefined) options.connectionTimeout = Math.round(pool.acquireTimeoutMs / 1000) if (pool.maxLifetimeMs !== undefined) options.maxLifetime = Math.round(pool.maxLifetimeMs / 1000) if (pool.preparedStatements !== undefined) options.prepare = pool.preparedStatements return options } function updateQueryBuilderConfig(): void { const dialect = getDialect() const dbConfigForQb = getDbConfig() const pool = getPoolConfig() setConfig({ dialect: dialect as Parameters[0]['dialect'], vitess: { sharded: isVitessSharded(dbConfig.connections.vitess?.sharded), }, // bun-query-builder accepts `pool` on its database config and maps it // onto Bun's driver options itself, so the block is handed down as-is // rather than pre-translated here. `toBunPoolOptions` exists for the // replica connections below, which are constructed directly. database: (pool ? { ...dbConfigForQb, pool } : dbConfigForQb), verbose: getEnv() !== 'production', // Must match the value migrations.ts sets. setConfig replaces the config // wholesale, so omitting this here silently reverts the snapshot to the // library default and writes a second copy to `.qb` in the project root - // the exact directory moving it was meant to remove. snapshotDir: qbSnapshotDir(), migrationDir: relativeMigrationDirectory(resolveMigrationDirectory(toQueryBuilderDialect(dialect), { configured: qbMigrationDir(), snapshotDir: qbSnapshotDir() })), timestamps: { createdAt: 'created_at', updatedAt: 'updated_at', defaultOrderColumn: 'created_at', }, softDeletes: RAW_QUERY_SOFT_DELETE_CONFIG, }) } // Initialize config immediately at module load time with env defaults // This ensures bun-query-builder is configured before any queries run updateQueryBuilderConfig() /** * Lazy query builder instance - only created when first accessed. * This ensures the database connection is not made at module load time * which can cause issues in compiled binaries. */ let _dbInstance: ReturnType | null = null let _configInitPromise: Promise | null = null function ensureConfigLoaded(): Promise { if (!_configInitPromise) { _configInitPromise = (async () => { try { const { config, overridesReady } = await import('@stacksjs/config/runtime') // `config.database` is a Proxy read (see `readMerged()` in // @stacksjs/config) that falls back to framework defaults until the // project's own `config/database.ts` has actually finished loading. // `overridesReady` is the signal for that — awaiting it here closes // a race where a fast one-shot script (e.g. a `bun -e` script or a // CLI command issuing its first query very early in boot) reads the // proxy before the project override lands, locks in the framework's // default connection settings via `initializeDbConfig`, and never // retries since `_dbInstance` is only invalidated from inside // `initializeDbConfig` itself. await overridesReady if (config) { initializeDbConfig(config) // Reset instance so next access uses updated config _dbInstance = null } } catch { // Config not available, use defaults from env vars } })() } return _configInitPromise } export async function ensureDatabaseConfigLoaded(): Promise { await ensureConfigLoaded() } // SQLite bootstrap pragmas (stacksjs/stacks#1951) now live in // @stacksjs/query-builder — the one chokepoint every framework // query-builder instance is created through — so EVERY fresh sqlite // connection gets `foreign_keys = ON`, including builders created outside // this module (e.g. the ORM auto-CRUD routes). Re-exported here for // backwards compatibility with existing imports. export { applySqlitePragmas, SQLITE_BOOTSTRAP_PRAGMAS } from '@stacksjs/query-builder' /** * SQLite transaction serialization (stacksjs/stacks#1953). * * Bun.SQL's sqlite adapter is a single shared connection and * bun-query-builder tracks transaction depth per-connection, so two * CONCURRENT `db.transaction()` calls interleave: the second BEGIN is * issued as a savepoint inside the first caller's transaction (or fails * outright with "cannot start a transaction within a transaction"), and * the first COMMIT destroys the second caller's savepoint ("no such * savepoint: qb_sp_N"). Either way the loser 500s on perfectly legal * work — e.g. two near-simultaneous registrations for different emails. * Queue transactions through a promise-chain mutex so they run one at a * time instead of colliding. MySQL/Postgres pool connections, so they * are unaffected; the patch is only applied for the sqlite dialect. * * Same-async-context NESTING is exempt from the queue: a nested * `db.transaction()` inside an open transaction's callback is the * sequential savepoint case bun-query-builder handles correctly, and * queueing it would deadlock — the inner call would wait for the outer * transaction (its own caller) to finish. */ interface SqliteTransactionOwner { parent?: SqliteTransactionOwner accepting: boolean transactions: number /** The transactions its completion has enrolled and not yet finished. None when there are none. */ completionTail?: Promise } const sqliteTxOwner = new AsyncLocalStorage() /** The transaction that holds the shared connection, and those queued behind it. None when it is free. */ let sqliteTxTail: Promise | undefined function runOwnedSqliteTransaction(run: () => T, parent?: SqliteTransactionOwner): T { const owner: SqliteTransactionOwner = { parent, accepting: true, transactions: 0 } return sqliteTxOwner.run(owner, () => settle(function* (): Generator { try { return (yield* wait(run())) as T } finally { // Lingering continuations must acquire a fresh lock. Already-enrolled // completion transactions finish before we release the shared connection. owner.accepting = false if (owner.completionTail) yield* wait(owner.completionTail) } })) } /** * A transaction on a free connection runs where it is called: nothing else * can touch the connection while it runs, because nothing else runs at all. * If its callback has to wait, the transaction is a promise and the connection * is held until it settles; a transaction that arrives meanwhile queues behind * it, and is a promise too, whatever its own callback does. */ function serializeSqliteTransaction(run: () => T): T { let owner = sqliteTxOwner.getStore() // A child's late continuation can still belong to an active ancestor's // completion. Queueing it globally would make that ancestor wait on itself. while (owner && !owner.accepting) owner = owner.parent if (owner?.accepting && owner.transactions > 0) return sqliteTxOwner.run(owner, run) // Completion still owns the connection, but its new transactions are not // savepoints. Give siblings a local queue instead of bypassing serialization // or deadlocking behind their enclosing completion's global lock. const completionOwner = owner?.accepting ? owner : undefined const tailNow = (): Promise | undefined => completionOwner ? completionOwner.completionTail : sqliteTxTail const setTail = (tail: Promise | undefined): void => { if (completionOwner) completionOwner.completionTail = tail else sqliteTxTail = tail } // Keep the chain alive after a rollback: the rejection still surfaces to // this transaction's caller. The connection is free again once the last one // queued on it has settled, and it is marked free in the first reaction to // that: this one, registered before the caller is handed the promise. So the // caller's own next line already finds it free. const hold = (pending: PromiseLike): void => { const release = (): void => { if (tailNow() === tail) setTail(undefined) } const tail: Promise = Promise.resolve(pending).then(release, release) setTail(tail) } const ahead = tailNow() if (!ahead) { const result = runOwnedSqliteTransaction(run, completionOwner) if (isPromise(result)) hold(result) return result } const result = ahead.then(() => runOwnedSqliteTransaction(run, completionOwner)) hold(result) return result as T } function applySqliteTransactionSerialization(instance: RawQueryBuilder): void { // Patch the instance's own property (not the proxy) so internal callers // like `transactional()` — which invokes `this.transaction(...)` — are // serialized too. const original = (instance.transaction as (...args: any[]) => unknown).bind(instance) ;(instance).transaction = ((...args: any[]) => serializeSqliteTransaction(() => original(...args))) as RawQueryBuilder['transaction'] } /** * Open the after-commit dispatch scope for every `db.transaction()` call. * * `runInTransactionScope` is what `isInTransaction()` and * `enqueueAfterCommit()` read, and it was only ever opened by * `@stacksjs/orm`'s `transaction()`. The raw builder's own * `db.transaction()` got SQLite serialization and replica routing but not * this - so a `job(...).dispatch()` inside its callback saw * `isInTransaction() === false` and dispatched immediately instead of * buffering until commit (stacksjs/stacks#2539). * * That is not merely early. A rollback then leaves the side effect done: the * row can roll back with the shared SQLite connection, but a Redis push or an * HTTP call cannot, which is exactly what after-commit buffering exists to * prevent. The queue's own comments describe `db.transaction(...)` as * activating it. * * Applied BEFORE the routing patch, so routing stays the outermost wrapper as * documented below and the buffered callbacks flush while the routing context * is still open. Flushing outside it would send an after-commit read to a * replica, which can lag the commit that callback is predicated on. * * The ORM delegates here so this wrapper alone owns completion. Nested calls * share the buffer. Each callback handle is instrumented too, since * bun-query-builder creates a new builder for nested transactions/savepoints. */ const dispatchScopedBuilders = new WeakSet() interface TransactionConnectionScope { connection: RawQueryBuilder parent?: TransactionConnectionScope active: boolean nested: boolean } const transactionConnection = new AsyncLocalStorage() function activeTransactionConnection(): RawQueryBuilder | undefined { const scope = transactionConnection.getStore() if (!scope) return assertTransactionConnection(scope) return scope.connection } /** * Require a live native transaction owner before registering non-SQL work. * Uses the same closed-callback and overlapping-savepoint checks as `db`. * This checks ownership only; callers retain their own domain/scope validation. */ export function assertActiveTransaction(): void { if (!activeTransactionConnection()) throw new Error('An active database transaction is required.') } function assertTransactionConnection(scope: TransactionConnectionScope): void { for (let owner: TransactionConnectionScope | undefined = scope; owner; owner = owner.parent) { if (!owner.active) throw new Error('Database work cannot continue from a closed transaction callback.') } // Sibling savepoints share one connection, not independent transactions. // Reject overlap rather than let one rollback erase another caller's work. if (scope.nested) throw new Error('Await the active nested transaction before issuing more database work.') } /** Check retained fluent/lazy statements when invoked, not only when built. */ function guardTransactionQuery(value: T): T { const scope = transactionConnection.getStore() if (!scope || !value || typeof value !== 'object' || typeof (value as { execute?: unknown }).execute !== 'function') return value const wrappers = new WeakMap() const wrap = (target: object): object => { const cached = wrappers.get(target) if (cached) return cached const proxy = new Proxy(target, { get(object, property) { const member = Reflect.get(object, property, object) if (typeof member !== 'function') return member return (...args: unknown[]) => { assertTransactionConnection(scope) if (transactionConnection.getStore() !== scope) throw new Error('A transaction query must execute in the callback that created it.') // Fluent helpers pass their raw builder to callbacks (tap, when, // pipe, $call). Keep that escape hatch inside the same ownership. const guardedArgs = args.map(arg => typeof arg === 'function' ? function (this: unknown, ...values: unknown[]) { return Reflect.apply(arg, this, values.map(value => value && typeof value === 'object' && typeof Reflect.get(value, 'execute') === 'function' ? wrap(value) : value)) } : arg) const result = Reflect.apply(member, object, guardedArgs) if (result === object) return proxy if (result && typeof result === 'object' && !isPromise(result) && (typeof Reflect.get(result, 'execute') === 'function' || typeof Reflect.get(result, 'next') === 'function')) return wrap(result) return result } }, }) wrappers.set(target, proxy) return proxy } return wrap(value) as T } function applyTransactionDispatchScope(instance: RawQueryBuilder): void { if (dispatchScopedBuilders.has(instance)) return dispatchScopedBuilders.add(instance) let defaultOptions: NonNullable[1]> = {} const setDefaults = instance.setTransactionDefaults.bind(instance) instance.setTransactionDefaults = (defaults) => { setDefaults(defaults) defaultOptions = { ...defaultOptions, ...defaults } } for (const method of ['transaction', 'savepoint'] as const) { const original = instance[method].bind(instance) as RawQueryBuilder['transaction'] instance[method] = ((callback: (tx: RawQueryBuilder) => unknown, options?: Parameters[1]) => { const active = activeTransactionConnection() // Retained db.transaction functions and pre-created transactional() // helpers must resolve the connection at invocation, not capture root. if (active && active !== instance) return (active[method] as (...args: unknown[]) => unknown)(callback, options) const parent = transactionConnection.getStore() const effectiveOptions = { ...defaultOptions, ...options } const afterCommit = method === 'transaction' ? effectiveOptions.afterCommit : undefined // Upstream invokes these synchronous observers after rollback, before // original() settles. Their parent connection is usable at that point. const parentObserver = (listener?: (...args: TArgs) => void) => listener ? (...args: TArgs) => { const nested = parent?.nested if (parent) parent.nested = false try { listener(...args) } finally { if (parent) parent.nested = nested! } } : undefined // Written to answer where it is called: a callback that does commits in // place, and its after-commit work has run by the next line. A callback // that has to wait makes the whole of this a promise, as it always was. return settle(function* (): Generator { const result = yield* wait(runInTransactionScope(runAttempt => settle(function* (): Generator { const owner = sqliteTxOwner.getStore() if (owner) owner.transactions++ if (parent) parent.nested = true try { // bun-query-builder runs the callback in the async context // `transaction()` was called from, even when a pooled driver // starts it from another, and adds the scope that puts model // writes in the transaction. Binding it here as well restored the // context from before that scope, so `User.update()` inside the // callback stayed outside the transaction (stacksjs/stacks#3269). // The builder is handed this wrapper, not the caller's callback, // so it is told here what it could otherwise see for itself: // whether that callback is `async` and will hold the transaction // open across an `await`. const runCallback = standingFor((tx: RawQueryBuilder) => runAttempt(() => { applyTransactionDispatchScope(tx) const scope: TransactionConnectionScope = { connection: tx, parent, active: true, nested: false } return transactionConnection.run(scope, () => settle(function* (): Generator { try { return yield* wait(callback(tx)) } finally { scope.active = false } })) }), callback) return yield* wait((original as (...args: unknown[]) => unknown)(runCallback, method === 'transaction' ? { ...options, afterCommit: undefined, onRollback: parentObserver(effectiveOptions.onRollback), afterRollback: parentObserver(effectiveOptions.afterRollback), onRetry: parentObserver(effectiveOptions.onRetry), } : options)) } finally { if (parent) parent.nested = false if (owner) owner.transactions-- } }))) // Observer failures happen after the real commit. They must not make // the dispatch scope discard work or make the driver retry that commit. yield* wait(afterCommit?.()) return result }) }) as RawQueryBuilder['transaction'] } } /** * Mark the routing context as "inside a transaction" for the duration of * every `db.transaction()` call. * * Without this, rule 2 in `./replicas` could not be enforced: a SELECT * issued inside a transaction callback would look like any other read and * could be routed to a replica, where it would miss the transaction's own * uncommitted writes and run outside its isolation entirely. * * Patched onto the instance's own property rather than a wrapper object so * internal callers reach it too — `transactional()` invokes * `this.transaction(...)`, which would bypass a wrapper. */ function applyTransactionRoutingContext(instance: RawQueryBuilder): void { const original = (instance.transaction as (...args: any[]) => unknown).bind(instance) ;(instance).transaction = ((...args: any[]) => withTransactionContext(() => original(...args))) as RawQueryBuilder['transaction'] } function getDb(): ReturnType { if (_databaseClosePromise) throw new Error('Database connections are shutting down') const active = activeTransactionConnection() if (active) return active if (!_dbInstance) { updateQueryBuilderConfig() // stacksjs/stacks#1951 — the wrapped createQueryBuilder applies the // sqlite bootstrap pragmas to the freshly captured connection, so every // instance recreation (config reload nulls `_dbInstance`, and a config // change can swap bun-query-builder's signature-keyed singleton) is // re-bootstrapped without an explicit call here. _dbInstance = createQueryBuilder() applyTransactionDispatchScope(_dbInstance) // stacksjs/stacks#1953 — re-applied on every instance recreation // (config reload nulls `_dbInstance`). Pragmas themselves are applied // inside the wrapped createQueryBuilder (#1951), so only the // transaction serialization patch is needed here. It must surround the // completion wrapper too: observers and queued effects use the same // SQLite connection and must not land inside another caller's transaction. if (getDialect() === 'sqlite') applySqliteTransactionSerialization(_dbInstance) // Applied after the sqlite patch so the routing context is the // outermost wrapper — a read issued while queued behind another // transaction is then treated as in-transaction and stays on the // primary, which is the conservative direction to be wrong in. applyTransactionRoutingContext(_dbInstance) } return _dbInstance } /** * Query builders bound to a replica, keyed by the full resolved connection * identity so per-replica credential overrides cannot reuse the wrong pool. * * Cached because a builder owns a connection pool — rebuilding one per * read would open a fresh pool on every SELECT. Cleared alongside * `_dbInstance` whenever the config changes, so a reconfigured replica * list cannot keep serving reads from the old hosts. */ let _replicaInstances = new Map>() let _databaseClosePromise: Promise | null = null const _retiredConnectionClosures: PendingDatabaseConnectionClosures = new Set() /** * Discard every cached database client after the underlying query-builder * connection is reset. * * The Stacks `db` proxy caches a query-builder instance, while * bun-query-builder separately caches the SQL connection captured by that * instance. Resetting only the lower cache leaves the proxy pointing at a * closed SQLite handle. Migration flows reconfigure the lower layer between * reset and replay, so both caches must be invalidated as one operation. */ export function resetDatabaseConnection(): void { const connections = [ ...(_dbInstance ? [_dbInstance] : []), ..._replicaInstances.values(), ] if (connections.length > 0) retireDatabaseConnections(_retiredConnectionClosures, connections, error => console.error(`[database] Failed to close retired connection: ${(error as Error).message}`)) resetQueryBuilderConnection() lastGeneralSqliteStatement = undefined _dbInstance = null _replicaInstances = new Map() } /** * Close every framework-owned database pool and wait until it has drained. * * Unlike resetDatabaseConnection(), this is a shutdown boundary. New queries * are rejected while the cached primary and replica builders close so they * cannot attach themselves to a pool that is already draining. */ export function closeDatabaseConnection(): Promise { if (_databaseClosePromise) return _databaseClosePromise const connections = [ ...(_dbInstance ? [_dbInstance] : []), ..._replicaInstances.values(), ] _dbInstance = null _replicaInstances = new Map() lastGeneralSqliteStatement = undefined const closing = (async () => { try { await closeDatabaseConnectionsAndPending(connections, _retiredConnectionClosures) } finally { // The builders above own the same primary SQL pool cached by upstream. // Clear that lower cache only after close() has finished so its lazy // proxy cannot create and close a replacement connection by mistake. resetQueryBuilderConnection() } })() _databaseClosePromise = closing void closing.then( () => { if (_databaseClosePromise === closing) _databaseClosePromise = null }, () => { if (_databaseClosePromise === closing) _databaseClosePromise = null }, ) return closing } /** * Build (or reuse) a query builder pointed at `replica`. * * The builder is created with an injected `SQL` connection, which is the * seam bun-query-builder provides for exactly this: the process-wide * config still supplies the dialect and rendering rules — correct, since a * replica runs the same engine as its primary — while the connection * itself points somewhere else. */ function getReplicaDb(replica: ReplicaConfig): ReturnType { const primary = getDbConfig() const resolved = resolveReplicaConnection(replica, primary) const key = replicaConnectionKey(resolved) const cached = _replicaInstances.get(key) if (cached) return cached const scheme = isMysqlWire(getDriver()) ? 'mysql' : 'postgres' const auth = resolved.username ? `${encodeURIComponent(resolved.username)}:${encodeURIComponent(resolved.password ?? '')}@` : '' const url = `${scheme}://${auth}${resolved.host}:${resolved.port}/${resolved.database}` const sql = new SQL(url, { ...toBunPoolOptions(getPoolConfig()), database: resolved.database }) const instance = createQueryBuilder({ sql }) _replicaInstances.set(key, instance) return instance } /** * The builder a read should use right now. * * Falls back to the primary whenever routing is not permitted — no * replicas configured, auto-routing off, inside a transaction, or after a * write in this async context. See `./replicas` for why each of those * carve-outs exists. */ function getReadDb(): ReturnType { const active = activeTransactionConnection() if (active) return active const replicas = getReplicas() if (replicas.length === 0) return getDb() const policy = getReadPolicy() if (!shouldRouteToReplica({ policy, replicas })) return getDb() const replica = selectReplica(replicas, policy.strategy) return replica ? getReplicaDb(replica) : getDb() } /** * Explicitly replica-routed handle: `db.read.selectFrom('users')`. * * Unlike automatic routing this ignores `reads.autoRoute` — asking for * `db.read` IS the statement that this particular query tolerates a stale * result. It still respects the transaction carve-out, because a read * inside a transaction must see that transaction's own writes no matter * how it was requested. */ function getExplicitReadDb(): ReturnType { const active = activeTransactionConnection() if (active) return active const replicas = getReplicas() if (!replicas.length || contextInTransaction()) return getDb() const replica = selectReplica(replicas, getReadPolicy().strategy) return replica ? getReplicaDb(replica) : getDb() } /** Statements that mutate, for the read-your-writes tracking in `./replicas`. */ const WRITE_ENTRY_POINTS = new Set([ 'insertInto', 'updateTable', 'deleteFrom', 'create', 'createMany', 'insertOrIgnore', 'insertGetId', 'updateOrInsert', 'upsert', ]) /** Reads that are candidates for replica routing. */ const READ_ENTRY_POINTS = new Set([ 'selectFrom', 'selectFromSub', 'select', ]) // Start config loading in the background ensureConfigLoaded() /** * What raw SQL answers: rows whose shape only the SQL knows. * * The query builder types `unsafe()` as `Promise`, and at runtime it hands * back a Bun SQL statement that also has `.execute()`. Both halves are declared * here - and the rows are `Record` rather than `any`, because * that is the truth about a hand-written `SELECT`: it has aliases this code * cannot see, and every column wants reading out. * * `any` was worse than useless here: it made `rows.map(row => …)` an implicit * any at every call site, which is the error `noImplicitAny` exists to raise. */ type UnsafeRow = Record type UnsafeReturn = Promise & { /** The rows, where the connection answers in place; a promise of them where it cannot. */ execute: () => UnsafeRow[] executeSync: () => UnsafeRow[] } /** * A raw result as the drivers actually hand it back. * * `UnsafeReturn` above says "the rows", and for most drivers that is true. Some * answer `{ rows: [...] }` and some answer nothing at all, which is why callers * across migrations, the query logger and the scheduler all write * `Array.isArray(r) ? r : (r?.rows ?? [])`. Behind a `(db)` that read * typechecked; without one the `.rows` branch narrows to `never`, because the * declared type admits only the array. This names the shape they handle. */ export type UnsafeRowsResult = UnsafeRow[] | { rows?: UnsafeRow[] } | undefined /** * What a write statement run through `db.unsafe` resolves to. * * `UnsafeReturn` above describes a SELECT - the rows. An UPDATE, INSERT or * DELETE resolves to the driver's own result object instead, and every driver * spells the affected-row count differently. * * **Do not read the count off these fields yourself.** Use `mutationCount` * from `./affected-rows`. Hand-rolled readers here were wrong on two of three * dialects: `changes ?? rowCount` reads 0 on both PostgreSQL and MySQL, and * reading `count` before `affectedRows` reads 0 on MySQL. */ export interface DbWriteResult { /** bun:sqlite. */ changes?: number numUpdatedRows?: number | bigint numAffectedRows?: number | bigint numDeletedRows?: number | bigint /** Bun's MySQL client sets the real count here. `null` on PostgreSQL. */ affectedRows?: number | null /** Bun's PostgreSQL client sets the count here. Always `0` for a MySQL write. */ count?: number | null rowsAffected?: number /** node-postgres. Bun's PostgreSQL client never sets it. */ rowCount?: number lastInsertRowid?: number | bigint insertId?: number | bigint /** * Some drivers answer with an array of result rows rather than one object, * which is why callers probe `result[0]?.numUpdatedRows` alongside * `result.numUpdatedRows`. Both spellings are real, so both are described. */ [index: number]: DbWriteResult | undefined } /** * Fluent chain returned by entry-point methods like `selectFrom`/`updateTable`. * * bun-query-builder marks legacy chain methods (e.g. `selectAll`, `whereILike`, * `selectAllRelations`) as optional in its declarations even though they're * always present at runtime. Re-typing them here avoids forcing every call * site to use `?.()` or `!` on the chain. * * **The chain carries its row type.** `TRow` comes from the augmented * `DatabaseSchema` that `buddy generate:db-types` writes, so * `db.selectFrom('users').executeTakeFirst()` answers a `users` row rather than * `any` - and `select(['id', 'handle'])` narrows it to those two columns. * * Every terminal used to be `Promise`, and the cost was not theoretical: * an application on top of this ends up annotating every result `any` to say * what it already knows, which is a thousand places the compiler has been told * to stop looking. A row it cannot type is `Record` instead - * still a value the caller has to narrow, but one narrowing it is checked. * * A join or an aliased select list widens the row to * `Record`: the shape then depends on the aliases rather than * on any one table, and claiming otherwise would be worse than not knowing. */ /** * State the shape of rows this package knows and the query cannot. * * A raw query answers `Record` when the table is not in the * generated `DatabaseSchema` - which is always true *inside* the framework, * because an application's schema does not exist at framework build time. The * package that ships the model does know the shape, and this is where that * knowledge is written down: once, at the boundary, named and greppable. * * It is an assertion, and deliberately an obvious one. What it replaces is a * `Promise` that spread the same claim silently through every caller. * * Application code should not need it: `buddy generate:db-types` gives `db` the * real column types, and a row that arrives typed does not want asserting. */ export function asRows(rows: ReadonlyArray>): TRow[] { return rows as unknown as TRow[] } /** The single-row form of {@link asRows}. */ export function asRow(row: Record | undefined): TRow | undefined { return row as unknown as TRow | undefined } /** * The keys a row type actually declares, or `never` for a loose record. * * `keyof Record` is `string`, so a narrowing overload written * against it will happily accept *anything* as a column - including * `'menu_items.id as id'`, which then becomes a property name in the result * type. That is worse than not narrowing: the row type looks specific and every * key in it is fiction. */ export type KnownKeys = string extends keyof T ? never : keyof T /** * A value a write may put in a column besides its own type: SQL NULL, a * `Date` (bound as a timestamp), or a raw SQL fragment (`sql.raw(...)`, * `db.fn.now()`). A numeric column also takes a boolean: generated schemas type * a boolean column as `number` where the dialect stores it as 0/1, and every * driver binds `true`/`false` correctly. */ export type WriteValue = null | Date | { toSQL: unknown } | { readonly sql: unknown } | { raw: string } /** * The row a write to `T` takes. * * One of the application's own tables - in the `DatabaseSchema` that * `buddy generate:db-types` writes from `app/Models` - takes its own columns, * each optional, each of its own type or a {@link WriteValue}. A misspelt or * removed column, or a string where the column is a number, then fails to * compile instead of failing at runtime (or succeeding against a database * whose column happens to be text). * * Any other table takes any object: tables outside every model, apps that * have not generated types, and the framework's own tables, whose generated * `FrameworkSchema` is not yet exact enough to hold writes to. `object` rather * than `Record`, because an *interface* has no index signature * and is not assignable to the latter, and callers declaring their own row * shape pass exactly that. */ export type WriteOf = T extends keyof DatabaseSchema ? { [K in keyof Shape]?: Shape[K] | WriteValue | (Shape[K] extends number | null ? boolean : never) } : object /** * Which verb started a chain, so its terminals can answer the right thing. * * `returning` is its own kind rather than a flag on the others: a mutation with * `RETURNING` answers rows, and that is the difference between reading * `rows[0].id` and reading a count. */ export type ChainKind = 'select' | 'insert' | 'update' | 'delete' | 'returning' /** What `execute()` resolves to for each verb. */ export type ResultOf = TKind extends 'select' | 'returning' ? TRow[] : number /** * What an insert reports when it was not asked to return rows. * * Every field optional and every one differently named, because drivers * disagree: Postgres answers a count, SQLite a `changes`, MySQL an `insertId`. * Typing this as the row - which is what the query builder's own declarations * do - is how framework code came to read `insertId` off a value that is not a * row and cannot have one. * * `returning(...)` is the way to get rows out of an insert, and it changes the * chain's kind so the types follow. */ export interface InsertReceipt { insertId?: number | bigint numInsertedOrUpdatedRows?: number | bigint numAffectedRows?: number | bigint affectedRows?: number changes?: number } /** * What `executeTakeFirst()` resolves to for each verb. * * The counts are *required*, because the runtime always sets them: an update * that changed nothing answers `{ numUpdatedRows: 0 }`. Declaring them optional * would make every caller write `?? 0` for a case that cannot happen. */ export type FirstOf = TKind extends 'select' | 'returning' ? TRow | undefined : TKind extends 'insert' ? InsertReceipt | undefined : TKind extends 'update' ? { numUpdatedRows: number } : { numDeletedRows: number } export interface BaseFluentChain, TKind extends ChainKind = 'select', TWrite = object> { where(callback: (eb: import('./types').StacksExpressionBuilder) => unknown): FluentChain where(...args: unknown[]): FluentChain whereNull: (...args: unknown[]) => FluentChain whereNotNull: (...args: unknown[]) => FluentChain whereIn: (...args: unknown[]) => FluentChain whereNotIn: (...args: unknown[]) => FluentChain whereLike: (...args: unknown[]) => FluentChain whereNotLike: (...args: unknown[]) => FluentChain whereILike: (...args: unknown[]) => FluentChain whereNotILike: (...args: unknown[]) => FluentChain whereBetween: (...args: unknown[]) => FluentChain whereNotBetween: (...args: unknown[]) => FluentChain whereRaw: (...args: unknown[]) => FluentChain whereColumn: (...args: unknown[]) => FluentChain orWhere: (...args: unknown[]) => FluentChain orWhereNull: (...args: unknown[]) => FluentChain orWhereNotNull: (...args: unknown[]) => FluentChain orWhereIn: (...args: unknown[]) => FluentChain orWhereNotIn: (...args: unknown[]) => FluentChain orWhereLike: (...args: unknown[]) => FluentChain orWhereNotLike: (...args: unknown[]) => FluentChain orWhereILike: (...args: unknown[]) => FluentChain orWhereColumn: (...args: unknown[]) => FluentChain andWhere: (...args: unknown[]) => FluentChain // The multi-column predicates the query builder ships (`whereAny(columns, // op, value)` and friends). They were missing here, so a caller that used // one - the log search does, across message/project/file/stacktrace - had // no type for the chain it got back. whereAny: (...args: unknown[]) => FluentChain whereAll: (...args: unknown[]) => FluentChain whereNone: (...args: unknown[]) => FluentChain having: (...args: unknown[]) => FluentChain groupBy: (...args: unknown[]) => FluentChain orderBy: (...args: unknown[]) => FluentChain limit: (...args: unknown[]) => FluentChain offset: (...args: unknown[]) => FluentChain /** * Narrow the select list, and the row type with it. * * A list of plain column names narrows to exactly those columns. Anything * else - an alias, an expression builder callback, a raw fragment - answers a * `Record` chain, because what comes back is then named by * the aliases rather than by the table. */ select & string>(columns: readonly K[]): FluentChain, TKind> select(selection: ((eb: import('./types').StacksExpressionBuilder) => unknown) | ReadonlyArray unknown) | unknown>): FluentChain, TKind> select(...args: unknown[]): FluentChain, TKind> selectAll: () => FluentChain selectAllRelations: () => FluentChain, TKind> selectRaw: (...args: unknown[]) => FluentChain, TKind> distinct: () => FluentChain distinctOn: (...args: unknown[]) => FluentChain /* * A joined chain's rows are not this table's rows. * * `Record` rather than `TRow`, because the select list after * a join is written as aliases - `'users.id as user_id'` - and a row typed as * the base table would be confidently wrong about every one of them. */ innerJoin: (...args: unknown[]) => FluentChain, TKind> leftJoin: (...args: unknown[]) => FluentChain, TKind> rightJoin: (...args: unknown[]) => FluentChain, TKind> fullJoin: (...args: unknown[]) => FluentChain, TKind> crossJoin: (...args: unknown[]) => FluentChain, TKind> with: (...args: unknown[]) => FluentChain, TKind> union: (...args: unknown[]) => FluentChain, TKind> unionAll: (...args: unknown[]) => FluentChain, TKind> /** * `values()` and `set()` take what the table holds, and keep the row type for * `returning()`. Straight after `insertInto()` / `updateTable()` on one of the * application's own tables that is checked: a column the table does not have, * or a value of the wrong type, is a type error (see {@link WriteOf}). Any * other table takes any object. */ values: (values: TWrite | ReadonlyArray) => FluentChain set: (values: TWrite) => FluentChain /* * `RETURNING` turns a mutation into something that answers rows, which is * why it changes the chain's kind rather than only its row type: the whole * point of writing it is that `execute()` stops answering a count. */ returning & string>(columns: readonly K[]): FluentChain, 'returning'> returning(...args: unknown[]): FluentChain, 'returning'> returningAll: () => FluentChain onConflict: (...args: unknown[]) => FluentChain onDuplicateKeyUpdate: (...args: unknown[]) => FluentChain onConflictDoNothing: (...args: unknown[]) => FluentChain onDuplicateKeyIgnore: () => FluentChain forUpdate: () => FluentChain forShare: () => FluentChain toSQL: () => string /** * What running this chain answers, decided by which verb started it. * * A select resolves rows; an update or a delete resolves how many rows it * changed. Both were `Promise` before, which is why callers in this * framework and in applications on top of it read `numUpdatedRows` off a * value that might be a number - the type never told them which they had. */ execute: () => ResultOf /** SQLite fast path only. The same answer as `execute()`, kept for code written when that was a promise. */ executeSync?: () => ResultOf /** SQLite fast path only. Executes and returns the first row without an array. */ executeTakeFirstSync?: () => FirstOf executeTakeFirst: () => FirstOf executeTakeFirstOrThrow: () => NonNullable> pluck: (...args: unknown[]) => unknown[] count: (...args: unknown[]) => number sum: (...args: unknown[]) => number avg: (...args: unknown[]) => number min: (...args: unknown[]) => unknown max: (...args: unknown[]) => unknown exists: () => boolean doesntExist: () => boolean $call: (callback: (query: FluentChain) => FluentChain) => FluentChain /* * The rest of the builder bun-query-builder ships. * * These were reachable only through the `[key: string]: any` index signature * that used to sit at the bottom of this interface: present at runtime, * absent from the type, and typed as `any` when anybody used one. Removing * that signature without declaring them would have been a capability * regression - which is exactly how it was found, on `orderByRaw`. * * Declared as chain-returning, because that is what they are. The arguments * stay `unknown[]`: each one's real signature lives in the query builder, and * restating a hundred of them here is a second declaration to keep in step. */ abort: (...args: unknown[]) => FluentChain addSelect: (...args: unknown[]) => FluentChain applyPivotColumns: (...args: unknown[]) => FluentChain cache: (...args: unknown[]) => FluentChain clone: (...args: unknown[]) => FluentChain crossJoinSub: (...args: unknown[]) => FluentChain denseRank: (...args: unknown[]) => FluentChain doesntHave: (...args: unknown[]) => FluentChain dump: (...args: unknown[]) => FluentChain forPage: (...args: unknown[]) => FluentChain groupByRaw: (...args: unknown[]) => FluentChain has: (...args: unknown[]) => FluentChain havingRaw: (...args: unknown[]) => FluentChain inRandomOrder: (...args: unknown[]) => FluentChain join: (...args: unknown[]) => FluentChain joinSub: (...args: unknown[]) => FluentChain latest: (...args: unknown[]) => FluentChain leftJoinSub: (...args: unknown[]) => FluentChain lockForUpdate: (...args: unknown[]) => FluentChain oldest: (...args: unknown[]) => FluentChain onlyTrashed: (...args: unknown[]) => FluentChain orWhereBetween: (...args: unknown[]) => FluentChain orWhereExists: (...args: unknown[]) => FluentChain orWhereGroup: (...args: unknown[]) => FluentChain orWhereNested: (...args: unknown[]) => FluentChain orWhereNotILike: (...args: unknown[]) => FluentChain orWhereRaw: (...args: unknown[]) => FluentChain orderByDesc: (...args: unknown[]) => FluentChain orderByRaw: (...args: unknown[]) => FluentChain pipe: (...args: unknown[]) => FluentChain reorder: (...args: unknown[]) => FluentChain rowNumber: (...args: unknown[]) => FluentChain scope: (...args: unknown[]) => FluentChain sharedLock: (...args: unknown[]) => FluentChain tap: (...args: unknown[]) => FluentChain when: (...args: unknown[]) => FluentChain whereDate: (...args: unknown[]) => FluentChain whereDoesntHave: (...args: unknown[]) => FluentChain whereExists: (...args: unknown[]) => FluentChain whereGroup: (...args: unknown[]) => FluentChain whereHas: (...args: unknown[]) => FluentChain whereJsonContains: (...args: unknown[]) => FluentChain whereJsonContainsKey: (...args: unknown[]) => FluentChain whereJsonDoesntContain: (...args: unknown[]) => FluentChain whereJsonDoesntContainKey: (...args: unknown[]) => FluentChain whereJsonLength: (...args: unknown[]) => FluentChain whereJsonPath: (...args: unknown[]) => FluentChain whereNested: (...args: unknown[]) => FluentChain wherePivot: (...args: unknown[]) => FluentChain wherePivotIn: (...args: unknown[]) => FluentChain wherePivotNotIn: (...args: unknown[]) => FluentChain wherePivotNotNull: (...args: unknown[]) => FluentChain wherePivotNull: (...args: unknown[]) => FluentChain withAvg: (...args: unknown[]) => FluentChain withCTE: (...args: unknown[]) => FluentChain withCount: (...args: unknown[]) => FluentChain withMax: (...args: unknown[]) => FluentChain withMin: (...args: unknown[]) => FluentChain withPivot: (...args: unknown[]) => FluentChain withRecursive: (...args: unknown[]) => FluentChain withSum: (...args: unknown[]) => FluentChain withTimeout: (...args: unknown[]) => FluentChain withTrashed: (...args: unknown[]) => FluentChain /* The terminals, which answer rows rather than a chain. */ get: () => TRow[] first: () => TRow | undefined firstOrFail: () => TRow find: (id: number | string) => TRow | undefined findMany: (ids: Array) => TRow[] findOrFail: (id: number | string) => TRow value: (column: K) => TRow[K] lazy: () => AsyncIterable lazyById: () => AsyncIterable chunk: >(size: number, handler: (rows: TRow[]) => R) => R chunkById: = void>(size: number, column?: keyof TRow & string, handler?: (rows: TRow[]) => R) => R eachById: = void>(size: number, column?: keyof TRow & string, handler?: (row: TRow) => R) => R paginate: (perPage: number, page?: number, opts?: unknown) => { data: TRow[], meta: Record } simplePaginate: (perPage: number, page?: number) => { data: TRow[], meta: Record } cursorPaginate: (perPage: number, cursor?: string | number, column?: string, direction?: 'asc' | 'desc') => { data: TRow[], meta: Record } explain: () => Record[] raw: () => unknown[][] toParams: () => unknown[] toText: () => string simple: () => unknown cancel: () => void dd: () => never } /** `created_at` -> `CreatedAt`, for the dynamic helper names below. */ type SnakeToPascal = S extends `${infer Head}_${infer Tail}` ? `${Capitalize}${SnakeToPascal}` : Capitalize /** * The dynamic `where` helpers bun-query-builder generates. * * Derived from the row type rather than allowed by an index signature. The * index signature that used to be here (`[key: string]: any`) made every * misspelling legal and every result `any`: `whereHndle('a')` compiled, and so * did reading a property that does not exist. */ export type DynamicWhereMethods = { [K in keyof TRow & string as `where${SnakeToPascal}`]: (value: TRow[K]) => FluentChain } & { [K in keyof TRow & string as `orWhere${SnakeToPascal}`]: (value: TRow[K]) => FluentChain } & { [K in keyof TRow & string as `andWhere${SnakeToPascal}`]: (value: TRow[K]) => FluentChain } /** * A chain over one table's rows: the methods, plus the generated helpers. * * A type alias rather than an interface because the helper half is a mapped * type over `TRow`, and an interface can only extend members TypeScript knows * statically. */ export type FluentChain, TKind extends ChainKind = 'select', TWrite = object> = BaseFluentChain & DynamicWhereMethods /** * Top-level surface of the lazy `db` proxy. Methods that return a chainable * builder are typed as `FluentChain` to flatten the optional-method noise * inherent in bun-query-builder's declarations. Methods that introduce their * own generics (`transaction`, etc.) are kept as their original signatures * via the underlying QueryBuilder type so call-site inference still works. */ type RawQueryBuilder = ReturnType type GenericPassthroughKeys = | 'transaction' | 'savepoint' | 'beginDistributed' | 'transactional' | 'configure' | 'reserve' | 'commitDistributed' | 'rollbackDistributed' | 'setTransactionDefaults' | 'close' | 'listen' | 'unlisten' | 'notify' | 'copyTo' | 'copyFrom' | 'ping' | 'waitForReady' | 'count' | 'sum' | 'avg' | 'min' | 'max' | 'insertOrIgnore' | 'insertGetId' | 'updateOrInsert' | 'upsert' | 'create' | 'createMany' | 'sql' | 'raw' | 'simple' | 'file' /** * Userland-augmentable table registry (stacksjs/stacks#1923). * * Empty by default — the framework can't know an app's tables at its * own build time. `buddy generate:types` walks `app/Models/*.ts` and * emits `database/types.d.ts` containing: * * ```ts * declare module '@stacksjs/database' { * interface DatabaseSchema { * court_houses: { columns: { id: number; name: string; ... } } * judges: { columns: { id: number; name: string; court_id: number; ... } } * } * } * ``` * * Once that file is loaded into the TS project, `db.selectFrom('co|')` * autocompletes to known table names. Apps without a generated file * still compile — the `(string & {})` branch on `TableName` keeps the * type as a literal-union+escape-hatch, so any string is accepted * but known keys are surfaced first by the language server. */ // eslint-disable-next-line ts/no-empty-object-type export interface DatabaseSchema {} /** * Accept either a registered table name (from augmented * `DatabaseSchema`) for autocomplete, or any other string for apps * that haven't generated types yet / tables not in a model file. * * The `(string & {})` branch prevents TS from collapsing the union * back to `string` and losing the autocomplete narrowing — a * well-documented LiteralUnion trick. */ // eslint-disable-next-line ts/no-empty-object-type export type TableName = (keyof DatabaseSchema & string) | (keyof FrameworkSchema & string) | (string & {}) /** * The row type of a registered table, or an unknown-valued record. * * A table the generated `DatabaseSchema` knows answers its own columns. One it * does not - an app that has never run `buddy generate:db-types`, or a table * that lives outside a model - answers `Record`: still a value * the caller narrows, but narrowing it is checked rather than waved through. */ export type RowOf = T extends keyof DatabaseSchema ? Shape : T extends keyof FrameworkSchema ? Shape : Record /** * A generated entry, whichever of the two shapes it was written in. * * The app generator has emitted a flat column record for a while; the * `{ columns }` form is what the query builder's own schema type uses. Both are * accepted so an app does not have to regenerate to keep compiling. */ type Shape = T extends { columns: infer C } ? C : T interface Db extends Pick, GenericPassthroughKeys> { fn: import('./types').ExpressionFunctions selectFrom: (table: T) => FluentChain, 'select'> insertInto: (table: T) => FluentChain, 'insert', WriteOf> updateTable: (table: T) => FluentChain, 'update', WriteOf> deleteFrom: (table: T) => FluentChain, 'delete'> table: (table: T) => FluentChain, 'select'> /* * A subquery's rows are named by its own select list, so there is no table to * take a shape from. */ selectFromSub: (sub: unknown, alias: string) => FluentChain> select: (table: T, ...columns: string[]) => FluentChain> unsafe: (query: string, params?: unknown[]) => UnsafeReturn /** * Replica-routed handle. Reads issued through it go to a read replica * when one is configured, accepting replication lag in exchange for * taking load off the primary. Falls back to the primary when no * replicas are declared or inside a transaction. */ read: Omit /** Strongly consistent reads, still bound to the active transaction. */ primary: Omit } const SIMPLE_SQLITE_TABLE = /^[A-Z_][A-Z0-9_]*$/i const SIMPLE_SQLITE_COLUMN = /^[A-Z_][A-Z0-9_]*(?:\.[A-Z_][A-Z0-9_]*)?$/i const SIMPLE_SQLITE_SELECTION = /^[A-Z_][A-Z0-9_]*(?:\.[A-Z_][A-Z0-9_]*)?(?:\s+AS\s+[A-Z_][A-Z0-9_]*)?$/i const SIMPLE_SQLITE_OPERATORS = new Set(['=', '!=', '<>', '<', '<=', '>', '>=', 'like', 'not like']) const SQLITE_IDENTIFIER_CACHE_LIMIT = 512 function memoizeSqliteIdentifier(pattern: RegExp): (value: string) => boolean { const valid = new Set() return (value) => { if (valid.has(value)) return true if (!pattern.test(value)) return false if (valid.size < SQLITE_IDENTIFIER_CACHE_LIMIT) valid.add(value) return true } } const isSimpleSqliteTable = memoizeSqliteIdentifier(SIMPLE_SQLITE_TABLE) const isSimpleSqliteColumn = memoizeSqliteIdentifier(SIMPLE_SQLITE_COLUMN) const isSimpleSqliteSelection = memoizeSqliteIdentifier(SIMPLE_SQLITE_SELECTION) // Endpoint reads tend to repeat one structural query while only bound values // change. Keep the cache deliberately single-entry so that locality avoids SQL // string assembly without retaining arbitrary application query shapes. let lastParameterizedSqliteSelect: { instance: RawQueryBuilder selectKeyword: string selected: string table: string predicateColumn: string predicateOperator: string | undefined limit: number | undefined sql: string statement?: FastSqliteStatement } | undefined let lastUnparameterizedSqliteSelect: { instance: RawQueryBuilder selectKeyword: string selected: string table: string limit: number | undefined sql: string statement?: FastSqliteStatement } | undefined // Selection validation and rendering are also structural. Snapshot the last // validated list so caller mutation cannot make cached SQL describe new input. let lastSqliteSelection: { columns: string[], sql: string } | undefined // These methods forward retained calls themselves, avoiding a second closure. const GUARDED_SQLITE_SELECT_METHODS = new Set(['select', 'where', 'limit', 'execute', 'executeSync', 'executeTakeFirstSync']) function hasActiveQueryBuilderHooks(): boolean { return Boolean(queryBuilderConfig.hooks && Object.values(queryBuilderConfig.hooks).some(value => value !== undefined)) } function resolveDeferredSqliteTerminal( target: Record, property: string | symbol, executeStatement: (firstOnly?: boolean, selection?: string) => UnsafeRow[], executeFirstStatement: () => UnsafeRow | undefined, materialize: () => ReturnType, proxy: Record, ): unknown { if (property === 'get') { target.get = target.execute return target.execute } if (property === 'selectAll') { const selectAll = () => proxy target.selectAll = selectAll return selectAll } if (property === 'first') { const first = () => executeFirstStatement() target.first = first return first } if (property === 'firstOrFail' || property === 'executeTakeFirstOrThrow') { const firstOrFail = () => { const row = executeFirstStatement() if (row === undefined) throw new Error('Record not found') return row } target.firstOrFail = firstOrFail target.executeTakeFirstOrThrow = firstOrFail return firstOrFail } if (property === 'exists' || property === 'doesntExist') { const findsRow = property === 'exists' const check = () => (executeFirstStatement() !== undefined) === findsRow target[property] = check return check } if (property === 'value') { const value = (column: string) => executeFirstStatement()?.[column] target.value = value return value } if (property === 'count' || property === 'sum' || property === 'avg' || property === 'min' || property === 'max') { const emptyValue = property === 'min' || property === 'max' ? null : 0 const aggregate = (...args: unknown[]) => runDeferredSqliteAggregate(property, args, emptyValue, materialize, executeStatement) target[property] = aggregate return aggregate } if (property === 'pluck') { const pluck = (...args: unknown[]) => { if (args.length !== 1) { const builder = materialize() const apply = builder.pluck as unknown as (...values: unknown[]) => unknown[] return apply.call(builder, ...args) } const column = args[0] as string const rows = executeStatement() const values = new Array(rows.length) for (let index = 0; index < rows.length; index++) values[index] = rows[index]?.[column] return values } target.pluck = pluck return pluck } } function runDeferredSqliteAggregate( name: 'count' | 'sum' | 'avg' | 'min' | 'max', args: unknown[], emptyValue: unknown, materialize: () => ReturnType, executeStatement: (firstOnly?: boolean, selection?: string) => UnsafeRow[], ): unknown { const column = args[0] const acceptsNoColumn = name === 'count' && args.length === 0 if (!acceptsNoColumn && (args.length !== 1 || typeof column !== 'string' || !isSimpleSqliteColumn(column))) { const builder = materialize() as unknown as Record unknown> return builder[name].call(builder, ...args) } const expression = `${name.toUpperCase()}(${acceptsNoColumn ? '*' : column}) AS aggregate` const value = executeStatement(false, expression)[0]?.aggregate ?? emptyValue return name === 'count' || name === 'sum' || name === 'avg' ? Number(value) : value } interface FastSqliteStatement { all: (...params: unknown[]) => UnsafeRow[] get: (...params: unknown[]) => UnsafeRow | null } interface FastSqliteDatabase { query: (sql: string) => FastSqliteStatement } const fastSqliteDatabaseCache = new WeakMap() // Keep only the most recent general SELECT statement, never bound values or rows. let lastGeneralSqliteStatement: { database: FastSqliteDatabase, sql: string, statement: FastSqliteStatement } | undefined /** * Resolve bun-query-builder's already-bootstrapped SQLite connection. * * `_wrapper` is an upstream implementation detail, so every access is * feature-detected and cached. A changed upstream shape falls back to * `instance.unsafe()` in `runSql`; it never opens a second connection. Keeping * the live handle matters for transactions because a separate read connection * would not see the transaction's uncommitted writes. */ function fastSqliteDatabase(instance: RawQueryBuilder): FastSqliteDatabase | undefined { if (fastSqliteDatabaseCache.has(instance)) return fastSqliteDatabaseCache.get(instance) ?? undefined const sql = (instance as unknown as { sql?: { _wrapper?: { database?: unknown } } }).sql const database = sql?._wrapper?.database as Partial | undefined const resolved = database && typeof database.query === 'function' ? database as FastSqliteDatabase : null fastSqliteDatabaseCache.set(instance, resolved) return resolved ?? undefined } function runFastSqliteSql( instance: RawQueryBuilder, sqliteDatabase: FastSqliteDatabase | undefined, sql: string, params?: unknown[], ): UnsafeRow[] { if (sqliteDatabase) { let cached = lastGeneralSqliteStatement if (!cached || cached.database !== sqliteDatabase || cached.sql !== sql) { cached = { database: sqliteDatabase, sql, statement: sqliteDatabase.query(sql) } lastGeneralSqliteStatement = cached } return params ? cached.statement.all(...params) : cached.statement.all() } return (instance.unsafe(sql, params) as unknown as UnsafeReturn).executeSync() } let lastSqlitePlaceholders: { length: number, sql: string } | undefined function renderSqlitePlaceholders(length: number): string { const cached = lastSqlitePlaceholders if (cached && cached.length === length) return cached.sql const sql = Array(length).fill('?').join(', ') if (typeof length === 'number') lastSqlitePlaceholders = { length, sql } return sql } function snapshotSimpleSqliteMembershipValues(values: unknown[]): unknown[] | undefined { // Inspect stored values without invoking user getters, iterators or species. // Complex arrays stay on the upstream path with their original binding arity. if (isProxy(values) || Object.getPrototypeOf(values) !== Array.prototype || Object.hasOwn(values, Symbol.iterator)) return const snapshot = new Array(values.length) for (let index = 0; index < values.length; index++) { const descriptor = Object.getOwnPropertyDescriptor(values, index) if (!descriptor || !('value' in descriptor)) return snapshot[index] = descriptor.value } return snapshot } /** * Build the common SQLite SELECT shape without allocating bun-query-builder's * complete relationship, aggregate, window, pagination, and dynamic-where API. * Any method or argument outside this deliberately small surface materializes * the upstream builder and replays the calls, so capability and behavior stay * intact for complex queries. */ function createDeferredSqliteSelect(instance: RawQueryBuilder, table: string): unknown { const sqliteDatabase = fastSqliteDatabase(instance) let selectKeyword = 'SELECT' let columns: string | string[] | undefined let selectedColumnsSql: string | undefined let predicateColumn: string | undefined let predicateOperator: string | undefined let predicateValue: unknown let predicateParameterized = true let predicateValues: unknown[] | undefined let additionalPredicates: Array<{ column: string, operator: string, value: unknown, parameterized: boolean, values?: unknown[] }> | undefined let orderings: Array<{ column: string, direction: 'asc' | 'desc' }> | undefined let rowLimit: number | undefined let rowOffset: number | undefined let materialized: ReturnType | undefined const materialize = (): ReturnType => { if (materialized) return materialized let builder = instance.selectFrom(table) if (columns) { const apply = builder.select as unknown as (value: unknown) => typeof builder builder = apply.call(builder, columns) } if (selectKeyword === 'SELECT DISTINCT') { const apply = builder.distinct as unknown as () => typeof builder builder = apply.call(builder) } if (predicateColumn !== undefined) { if (predicateValues) { if (predicateOperator === 'LIKE LOWER' || predicateOperator === 'NOT LIKE LOWER') { const method = predicateOperator === 'LIKE LOWER' ? 'whereILike' : 'whereNotILike' const apply = builder[method] as unknown as (column: unknown, value: unknown) => typeof builder builder = apply.call(builder, predicateColumn.slice(6, -1), predicateValues[0]) } else { const method = predicateOperator === 'IN' ? 'whereIn' : 'whereNotIn' const apply = builder[method] as unknown as (column: unknown, values: unknown[]) => typeof builder builder = apply.call(builder, predicateColumn, predicateValues) } } else if (predicateParameterized) { const apply = builder.where as unknown as (column: unknown, operator: unknown, value: unknown) => typeof builder builder = apply.call(builder, predicateColumn, predicateOperator, predicateValue) } else { const method = predicateOperator === 'IS NULL' ? 'whereNull' : 'whereNotNull' const apply = builder[method] as unknown as (column: unknown) => typeof builder builder = apply.call(builder, predicateColumn) } if (additionalPredicates) { for (const predicate of additionalPredicates) { if (predicate.values) { if (predicate.operator === 'LIKE LOWER' || predicate.operator === 'NOT LIKE LOWER') { const method = predicate.operator === 'LIKE LOWER' ? 'whereILike' : 'whereNotILike' const apply = builder[method] as unknown as (column: unknown, value: unknown) => typeof builder builder = apply.call(builder, predicate.column.slice(6, -1), predicate.values[0]) } else { const method = predicate.operator === 'IN' ? 'whereIn' : 'whereNotIn' const apply = builder[method] as unknown as (column: unknown, values: unknown[]) => typeof builder builder = apply.call(builder, predicate.column, predicate.values) } } else if (predicate.parameterized) { const apply = builder.where as unknown as (column: unknown, operator: unknown, value: unknown) => typeof builder builder = apply.call(builder, predicate.column, predicate.operator, predicate.value) } else { const method = predicate.operator === 'IS NULL' ? 'whereNull' : 'whereNotNull' const apply = builder[method] as unknown as (column: unknown) => typeof builder builder = apply.call(builder, predicate.column) } } } } if (orderings) { const apply = builder.orderBy as unknown as (column: string, direction: 'asc' | 'desc') => typeof builder for (const ordering of orderings) builder = apply.call(builder, ordering.column, ordering.direction) } if (rowLimit !== undefined) { const apply = builder.limit as unknown as (value: unknown) => typeof builder builder = apply.call(builder, rowLimit) } if (rowOffset !== undefined) { const apply = builder.offset as unknown as (value: unknown) => typeof builder builder = apply.call(builder, rowOffset) } materialized = builder return builder } let proxy: Record const executeStatement = (firstOnly = false, selection?: string): UnsafeRow[] => { const selected = selection ?? selectedColumnsSql ?? '*' const effectiveLimit = rowLimit ?? (firstOnly && rowOffset === undefined ? 1 : undefined) if (predicateColumn === undefined && orderings === undefined && rowOffset === undefined) { const cached = lastUnparameterizedSqliteSelect if ( cached && cached.instance === instance && cached.selectKeyword === selectKeyword && cached.selected === selected && cached.table === table && cached.limit === effectiveLimit ) { if (sqliteDatabase) { const statement = cached.statement ??= sqliteDatabase.query(cached.sql) if (effectiveLimit === 1) { const row = statement.get() return row === null ? [] : [row] } return statement.all() } return runFastSqliteSql(instance, sqliteDatabase, cached.sql) } const limit = effectiveLimit === undefined ? '' : ` LIMIT ${effectiveLimit}` const sql = `${selectKeyword} ${selected} FROM ${table}${limit}` lastUnparameterizedSqliteSelect = { instance, selectKeyword, selected, table, limit: effectiveLimit, sql, statement: sqliteDatabase?.query(sql), } if (lastUnparameterizedSqliteSelect.statement) { if (effectiveLimit === 1) { const row = lastUnparameterizedSqliteSelect.statement.get() return row === null ? [] : [row] } return lastUnparameterizedSqliteSelect.statement.all() } return runFastSqliteSql(instance, sqliteDatabase, sql) } if ( predicateColumn !== undefined && predicateValues === undefined && predicateParameterized && additionalPredicates === undefined && orderings === undefined && rowOffset === undefined ) { const cached = lastParameterizedSqliteSelect if ( cached && cached.instance === instance && cached.selectKeyword === selectKeyword && cached.selected === selected && cached.table === table && cached.predicateColumn === predicateColumn && cached.predicateOperator === predicateOperator && cached.limit === effectiveLimit ) { if (sqliteDatabase) { const statement = cached.statement ??= sqliteDatabase.query(cached.sql) if (effectiveLimit === 1) { const row = statement.get(predicateValue) return row === null ? [] : [row] } return statement.all(predicateValue) } return runFastSqliteSql(instance, sqliteDatabase, cached.sql, [predicateValue]) } const sql = `${selectKeyword} ${selected} FROM ${table} WHERE ${predicateColumn} ${predicateOperator} ?${effectiveLimit === undefined ? '' : ` LIMIT ${effectiveLimit}`}` lastParameterizedSqliteSelect = { instance, selectKeyword, selected, table, predicateColumn, predicateOperator, limit: effectiveLimit, sql, statement: sqliteDatabase?.query(sql), } if (lastParameterizedSqliteSelect.statement) { if (effectiveLimit === 1) { const row = lastParameterizedSqliteSelect.statement.get(predicateValue) return row === null ? [] : [row] } return lastParameterizedSqliteSelect.statement.all(predicateValue) } return runFastSqliteSql(instance, sqliteDatabase, sql, [predicateValue]) } let query = `${selectKeyword} ${selected} FROM ${table}` const params: unknown[] = [] if (predicateColumn !== undefined) { query += ` WHERE ${predicateColumn} ${predicateOperator}` if (predicateValues) { query += ` (${renderSqlitePlaceholders(predicateValues.length)})` params.push(...predicateValues) } else if (predicateParameterized) { query += ' ?' params.push(predicateValue) } if (additionalPredicates) { // Appended in place rather than through `map(...).join(' AND ')`, which // allocated a temporary array of rendered fragments and invoked a // closure per predicate on every execution. // // The traversal is bounded by the length read BEFORE visiting anything, // which is the one guarantee `map` was providing: binding a predicate's // parameters can run user code, and a predicate appended by that code // must not execute in the same traversal. The array itself is dense by // construction - every element arrives through a `push` in this module - // so there are no holes for `map`'s hole-skipping to matter on. // // A defined-but-empty `additionalPredicates` cannot occur (the array is // created by `??= []` immediately before its first push), and the // unconditional separator keeps the emitted SQL identical if it ever did. const additionalCount = additionalPredicates.length query += ' AND ' for (let index = 0; index < additionalCount; index++) { if (index > 0) query += ' AND ' const predicate = additionalPredicates[index]! if (predicate.values) { params.push(...predicate.values) query += `${predicate.column} ${predicate.operator} (${renderSqlitePlaceholders(predicate.values.length)})` continue } if (predicate.parameterized) { params.push(predicate.value) query += `${predicate.column} ${predicate.operator} ?` continue } query += `${predicate.column} ${predicate.operator}` } } } if (orderings) query += ` ORDER BY ${orderings.map(ordering => `${ordering.column} ${ordering.direction.toUpperCase()}`).join(', ')}` // bun-query-builder leaves an offset-only SQLite query invalid, including // through first-row terminals that append LIMIT after OFFSET. Preserve // that behavior instead of silently repairing the caller's query. if (effectiveLimit !== undefined) query += ` LIMIT ${effectiveLimit}` if (rowOffset !== undefined) query += ` OFFSET ${rowOffset}` return runFastSqliteSql(instance, sqliteDatabase, query, params) } // First-row terminals use Statement.get() directly. Keep this separate from // executeStatement so the established array-returning path gains no mode // branch while first(), exists(), value(), and executeTakeFirstSync() avoid // allocating a one-element result array. const executeFirstStatement = (): UnsafeRow | undefined => { if (rowLimit === 0) return const selected = selectedColumnsSql ?? '*' if (predicateColumn === undefined && orderings === undefined && rowOffset === undefined) { const cached = lastUnparameterizedSqliteSelect if ( cached && cached.instance === instance && cached.selectKeyword === selectKeyword && cached.selected === selected && cached.table === table && cached.limit === 1 ) { if (sqliteDatabase) return (cached.statement ??= sqliteDatabase.query(cached.sql)).get() ?? undefined return runFastSqliteSql(instance, sqliteDatabase, cached.sql)[0] } const sql = `${selectKeyword} ${selected} FROM ${table} LIMIT 1` const statement = sqliteDatabase?.query(sql) lastUnparameterizedSqliteSelect = { instance, selectKeyword, selected, table, limit: 1, sql, statement, } return statement ? statement.get() ?? undefined : runFastSqliteSql(instance, sqliteDatabase, sql)[0] } if ( predicateColumn !== undefined && predicateValues === undefined && predicateParameterized && additionalPredicates === undefined && orderings === undefined && rowOffset === undefined ) { const cached = lastParameterizedSqliteSelect if ( cached && cached.instance === instance && cached.selectKeyword === selectKeyword && cached.selected === selected && cached.table === table && cached.predicateColumn === predicateColumn && cached.predicateOperator === predicateOperator && cached.limit === 1 ) { if (sqliteDatabase) return (cached.statement ??= sqliteDatabase.query(cached.sql)).get(predicateValue) ?? undefined return runFastSqliteSql(instance, sqliteDatabase, cached.sql, [predicateValue])[0] } const sql = `${selectKeyword} ${selected} FROM ${table} WHERE ${predicateColumn} ${predicateOperator} ? LIMIT 1` const statement = sqliteDatabase?.query(sql) lastParameterizedSqliteSelect = { instance, selectKeyword, selected, table, predicateColumn, predicateOperator, limit: 1, sql, statement, } return statement ? statement.get(predicateValue) ?? undefined : runFastSqliteSql(instance, sqliteDatabase, sql, [predicateValue])[0] } return executeStatement(true)[0] } /* * The benchmark and the dominant application read shape only touch * select, where, limit, and execute. Keep that four-method surface eager; * allocating every supported convenience method here accounted for most of * the lightweight builder's remaining overhead. The broader fast surface is * created only when a query actually asks for one of those methods. */ const createExtensions = (): Record => ({ distinct() { if (selectKeyword === 'SELECT DISTINCT') return materialize().distinct() selectKeyword = 'SELECT DISTINCT' return proxy }, where(column: unknown, operator?: unknown, value?: unknown) { if (column !== null && typeof column === 'object' && !Array.isArray(column) && operator === undefined && value === undefined) { const prototype = Object.getPrototypeOf(column) const entries = prototype === Object.prototype || prototype === null ? Object.entries(column as Record) : [] if (entries.length > 0 && entries.every(([key]) => isSimpleSqliteColumn(key))) { for (const [key, entryValue] of entries) { if (predicateColumn === undefined) { predicateColumn = key predicateOperator = '=' predicateValue = entryValue predicateParameterized = true predicateValues = undefined } else { ;(additionalPredicates ??= []).push({ column: key, operator: '=', value: entryValue, parameterized: true }) } } return proxy } } const builder = materialize() const apply = builder.where as unknown as (column: unknown, operator: unknown, value: unknown) => typeof builder return apply.call(builder, column, operator, value) }, whereNull(column: unknown) { if (typeof column !== 'string' || !isSimpleSqliteColumn(column)) { const builder = materialize() const apply = builder.whereNull as unknown as (column: unknown) => typeof builder return apply.call(builder, column) } if (predicateColumn === undefined) { predicateColumn = column predicateOperator = 'IS NULL' predicateValue = undefined predicateParameterized = false predicateValues = undefined } else { ;(additionalPredicates ??= []).push({ column, operator: 'IS NULL', value: undefined, parameterized: false }) } return proxy }, whereNotNull(column: unknown) { if (typeof column !== 'string' || !isSimpleSqliteColumn(column)) { const builder = materialize() const apply = builder.whereNotNull as unknown as (column: unknown) => typeof builder return apply.call(builder, column) } if (predicateColumn === undefined) { predicateColumn = column predicateOperator = 'IS NOT NULL' predicateValue = undefined predicateParameterized = false predicateValues = undefined } else { ;(additionalPredicates ??= []).push({ column, operator: 'IS NOT NULL', value: undefined, parameterized: false }) } return proxy }, whereLike(column: unknown, value: unknown, caseSensitive: unknown = false) { if (typeof column !== 'string' || !isSimpleSqliteColumn(column)) { const builder = materialize() const apply = builder.whereLike as unknown as (column: unknown, value: unknown, caseSensitive?: unknown) => typeof builder return apply.call(builder, column, value, caseSensitive) } if (!caseSensitive) return (proxy.whereILike as (column: string, value: unknown) => unknown)(column, value) if (predicateColumn === undefined) { predicateColumn = column predicateOperator = 'LIKE' predicateValue = value predicateParameterized = true predicateValues = undefined } else { ;(additionalPredicates ??= []).push({ column, operator: 'LIKE', value, parameterized: true }) } return proxy }, whereNotLike(column: unknown, value: unknown, caseSensitive: unknown = false) { if (typeof column !== 'string' || !isSimpleSqliteColumn(column)) { const builder = materialize() const apply = builder.whereNotLike as unknown as (column: unknown, value: unknown, caseSensitive?: unknown) => typeof builder return apply.call(builder, column, value, caseSensitive) } if (!caseSensitive) return (proxy.whereNotILike as (column: string, value: unknown) => unknown)(column, value) if (predicateColumn === undefined) { predicateColumn = column predicateOperator = 'NOT LIKE' predicateValue = value predicateParameterized = true predicateValues = undefined } else { ;(additionalPredicates ??= []).push({ column, operator: 'NOT LIKE', value, parameterized: true }) } return proxy }, whereILike(column: unknown, value: unknown) { if (typeof column !== 'string' || !isSimpleSqliteColumn(column)) { const builder = materialize() const apply = builder.whereILike as unknown as (column: unknown, value: unknown) => typeof builder return apply.call(builder, column, value) } const sqlColumn = `LOWER(${column})` if (predicateColumn === undefined) { predicateColumn = sqlColumn predicateOperator = 'LIKE LOWER' predicateValue = undefined predicateParameterized = false predicateValues = [value] } else { ;(additionalPredicates ??= []).push({ column: sqlColumn, operator: 'LIKE LOWER', value: undefined, parameterized: false, values: [value] }) } return proxy }, whereNotILike(column: unknown, value: unknown) { if (typeof column !== 'string' || !isSimpleSqliteColumn(column)) { const builder = materialize() const apply = builder.whereNotILike as unknown as (column: unknown, value: unknown) => typeof builder return apply.call(builder, column, value) } const sqlColumn = `LOWER(${column})` if (predicateColumn === undefined) { predicateColumn = sqlColumn predicateOperator = 'NOT LIKE LOWER' predicateValue = undefined predicateParameterized = false predicateValues = [value] } else { ;(additionalPredicates ??= []).push({ column: sqlColumn, operator: 'NOT LIKE LOWER', value: undefined, parameterized: false, values: [value] }) } return proxy }, whereIn(column: unknown, values: unknown) { if (typeof column !== 'string' || !isSimpleSqliteColumn(column) || !Array.isArray(values)) { const builder = materialize() const apply = builder.whereIn as unknown as (column: unknown, values: unknown) => typeof builder return apply.call(builder, column, values) } const snapshot = values.slice() if (predicateColumn === undefined) { predicateColumn = column predicateOperator = 'IN' predicateValue = undefined predicateParameterized = false predicateValues = snapshot } else { ;(additionalPredicates ??= []).push({ column, operator: 'IN', value: undefined, parameterized: false, values: snapshot }) } return proxy }, whereNotIn(column: unknown, values: unknown) { if (typeof column !== 'string' || !isSimpleSqliteColumn(column) || !Array.isArray(values)) { const builder = materialize() const apply = builder.whereNotIn as unknown as (column: unknown, values: unknown) => typeof builder return apply.call(builder, column, values) } const snapshot = values.slice() if (predicateColumn === undefined) { predicateColumn = column predicateOperator = 'NOT IN' predicateValue = undefined predicateParameterized = false predicateValues = snapshot } else { ;(additionalPredicates ??= []).push({ column, operator: 'NOT IN', value: undefined, parameterized: false, values: snapshot }) } return proxy }, whereBetween(...args: unknown[]) { const [column, startOrValues, end] = args const values = Array.isArray(startOrValues) ? startOrValues : args.length >= 3 ? [startOrValues, end] : undefined if (typeof column !== 'string' || !isSimpleSqliteColumn(column) || !values || values.length < 2) { const builder = materialize() const apply = builder.whereBetween as unknown as (...values: unknown[]) => typeof builder return apply.call(builder, ...args) } const lower = values[0] const upper = values[1] if (predicateColumn === undefined) { predicateColumn = column predicateOperator = '>=' predicateValue = lower predicateParameterized = true predicateValues = undefined } else { ;(additionalPredicates ??= []).push({ column, operator: '>=', value: lower, parameterized: true }) } ;(additionalPredicates ??= []).push({ column, operator: '<=', value: upper, parameterized: true }) return proxy }, whereDate(...args: unknown[]) { const [column, operator, date] = args if (typeof column !== 'string' || !isSimpleSqliteColumn(column) || typeof operator !== 'string' || !SIMPLE_SQLITE_OPERATORS.has(operator.toLowerCase()) || (typeof date !== 'string' && !(date instanceof Date))) { const builder = materialize() const apply = builder.whereDate as unknown as (...values: unknown[]) => typeof builder return apply.call(builder, ...args) } const normalizedDate = date instanceof Date ? date.toISOString() : date if (predicateColumn === undefined) { predicateColumn = column predicateOperator = operator predicateValue = normalizedDate predicateParameterized = true predicateValues = undefined } else { ;(additionalPredicates ??= []).push({ column, operator, value: normalizedDate, parameterized: true }) } return proxy }, orderBy(column: unknown, direction: unknown = 'asc') { if (typeof column !== 'string' || !isSimpleSqliteColumn(column)) { const builder = materialize() const apply = builder.orderBy as unknown as (column: unknown, direction?: unknown) => typeof builder return apply.call(builder, column, direction) } ;(orderings ??= []).push({ column, direction: direction === 'asc' ? 'asc' : 'desc' }) return proxy }, orderByDesc(column: unknown) { if (typeof column !== 'string' || !isSimpleSqliteColumn(column)) { const builder = materialize() const apply = builder.orderByDesc as unknown as (column: unknown) => typeof builder return apply.call(builder, column) } ;(orderings ??= []).push({ column, direction: 'desc' }) return proxy }, latest(column?: unknown) { const resolvedColumn = column ?? queryBuilderConfig.timestamps.defaultOrderColumn if (typeof resolvedColumn !== 'string' || !isSimpleSqliteColumn(resolvedColumn)) { const builder = materialize() const apply = builder.latest as unknown as (value?: unknown) => typeof builder return apply.call(builder, column) } ;(orderings ??= []).push({ column: resolvedColumn, direction: 'desc' }) return proxy }, oldest(column?: unknown) { const resolvedColumn = column ?? queryBuilderConfig.timestamps.defaultOrderColumn if (typeof resolvedColumn !== 'string' || !isSimpleSqliteColumn(resolvedColumn)) { const builder = materialize() const apply = builder.oldest as unknown as (value?: unknown) => typeof builder return apply.call(builder, column) } ;(orderings ??= []).push({ column: resolvedColumn, direction: 'asc' }) return proxy }, offset(value: unknown) { if (typeof value !== 'number' || value < 0 || !Number.isInteger(value)) { const builder = materialize() const apply = builder.offset as unknown as (value: unknown) => typeof builder return apply.call(builder, value) } rowOffset = value return proxy }, }) let extensions: Record | undefined const base = { select(value: unknown) { if (materialized) return Reflect.apply(materialized.select as (...args: unknown[]) => unknown, materialized, arguments) if (typeof value === 'string') { if (value !== '*' && !isSimpleSqliteSelection(value)) { const builder = materialize() const apply = builder.select as unknown as (selection: unknown) => typeof builder return apply.call(builder, value) } columns = value selectedColumnsSql = value return proxy } const selected = Array.isArray(value) ? value : [value] let simple = false let selection: string | undefined const cached = lastSqliteSelection if (cached && cached.columns.length === selected.length) { simple = true for (let index = 0; simple && index < selected.length; index++) simple = cached.columns[index] === selected[index] if (simple) selection = cached.sql } if (!simple) { simple = selected.length > 0 selection = '' for (let index = 0; simple && index < selected.length; index++) { const column = selected[index] simple = typeof column === 'string' && (column === '*' || isSimpleSqliteSelection(column)) if (simple) selection += index === 0 ? column : `, ${column}` } if (simple) lastSqliteSelection = { columns: (selected as string[]).slice(), sql: selection } } if (!simple) { const builder = materialize() const apply = builder.select as unknown as (value: unknown) => typeof builder return apply.call(builder, value) } columns = selected as string[] selectedColumnsSql = selection return proxy }, where(column: unknown, operator?: unknown, value?: unknown) { if (materialized) return Reflect.apply(materialized.where, materialized, arguments) if (typeof column !== 'string' || !isSimpleSqliteColumn(column) || typeof operator !== 'string' || (operator !== '=' && !SIMPLE_SQLITE_OPERATORS.has(operator) && !SIMPLE_SQLITE_OPERATORS.has(operator.toLowerCase()))) { if (typeof column === 'string' && isSimpleSqliteColumn(column) && typeof operator === 'string') { const normalized = operator.toLowerCase() if (normalized === 'in' || normalized === 'not in') { const values = Array.isArray(value) ? snapshotSimpleSqliteMembershipValues(value) : [value] if (values !== undefined) { const membershipOperator = normalized === 'in' ? 'IN' : 'NOT IN' if (predicateColumn === undefined) { predicateColumn = column predicateOperator = membershipOperator predicateValue = undefined predicateParameterized = false predicateValues = values } else { ;(additionalPredicates ??= []).push({ column, operator: membershipOperator, value: undefined, parameterized: false, values }) } return proxy } } } const extended = extensions ??= createExtensions() return (extended.where as (column: unknown, operator?: unknown, value?: unknown) => unknown)(column, operator, value) } if (predicateColumn === undefined) { predicateColumn = column predicateOperator = operator predicateValue = value predicateParameterized = true predicateValues = undefined } else { ;(additionalPredicates ??= []).push({ column, operator, value, parameterized: true }) } return proxy }, limit(value: unknown) { if (materialized) return Reflect.apply(materialized.limit, materialized, arguments) if (typeof value !== 'number' || value < 0 || !Number.isInteger(value)) { const builder = materialize() const apply = builder.limit as unknown as (value: unknown) => typeof builder return apply.call(builder, value) } rowLimit = value return proxy }, execute() { if (materialized) return Reflect.apply(materialized.execute, materialized, arguments) return executeStatement() }, executeSync() { if (materialized) return Reflect.apply((materialized as unknown as Record<'executeSync', () => unknown>).executeSync, materialized, arguments) return executeStatement() }, executeTakeFirstSync() { if (materialized) return Reflect.apply((materialized as unknown as Record<'executeTakeFirstSync', () => unknown>).executeTakeFirstSync, materialized, arguments) return executeFirstStatement() }, } let forwardedMethods: Record | undefined proxy = new Proxy(base as Record, { get(target, property) { if (materialized) { const builder = materialized as unknown as Record const value = builder[property] return typeof value === 'function' ? value.bind(builder) : value } if (property === 'executeTakeFirst') { return target.executeTakeFirst ??= function () { if (materialized) return Reflect.apply(materialized.executeTakeFirst, materialized, arguments) return executeFirstStatement() } } if (GUARDED_SQLITE_SELECT_METHODS.has(property)) return target[property] const cached = forwardedMethods?.[property] if (cached !== undefined) return cached const value = target[property] ?? resolveDeferredSqliteTerminal(target, property, executeStatement, executeFirstStatement, materialize, proxy) ?? (extensions ??= createExtensions())[property as string] if (value === undefined) { const builder = materialize() as unknown as Record const fallback = builder[property] return typeof fallback === 'function' ? fallback.bind(builder) : fallback } if (typeof value !== 'function') return value // Callers may retain or bind a method before another operation forces // fallback. Those methods must follow the builder that now owns the query. const forward = (...args: unknown[]) => { const builder = materialized as unknown as Record | undefined return builder ? Reflect.apply(builder[property] as (...values: unknown[]) => unknown, builder, args) : Reflect.apply(value, proxy, args) } ;(forwardedMethods ??= Object.create(null))[property] = forward return forward }, }) return proxy } /** * Whether the synchronous SQLite select path may serve this query. * * It reads through `bun:sqlite` in the same tick, which only an embedded * database can do. Turso keeps the sqlite dialect but answers over the * network, so it always takes the ordinary async builder. */ function usesDeferredSqliteSelect(table: string): boolean { return getDialect() === 'sqlite' && !isLibsqlDriver(getDriver()) && !queryBuilderConfig.softDeletes?.enabled && !hasActiveQueryBuilderHooks() && isSimpleSqliteTable(table) } function selectFromDatabase(table: string): unknown { const dialect = getDialect() const instance = dialect === 'sqlite' ? getDb() : getReadDb() if (usesDeferredSqliteSelect(table)) return guardTransactionQuery(createDeferredSqliteSelect(instance, table)) return guardTransactionQuery(instance.selectFrom(table)) } function selectFromExplicitReadDatabase(table: string): unknown { const instance = getExplicitReadDb() if (usesDeferredSqliteSelect(table)) return guardTransactionQuery(createDeferredSqliteSelect(instance, table)) return guardTransactionQuery(instance.selectFrom(table)) } function unsafeDatabase(query: string, params?: unknown[]): UnsafeReturn { return guardTransactionQuery(getDb().unsafe(query, params)) as unknown as UnsafeReturn } function unsafeExplicitReadDatabase(query: string, params?: unknown[]): UnsafeReturn { return guardTransactionQuery(getExplicitReadDb().unsafe(query, params)) as unknown as UnsafeReturn } function insertIntoDatabase(table: string): unknown { markContextWrote() return guardTransactionQuery(getDb().insertInto(table)) } function updateTableDatabase(table: string): unknown { markContextWrote() return guardTransactionQuery(getDb().updateTable(table)) } function deleteFromDatabase(table: string): unknown { markContextWrote() return guardTransactionQuery(getDb().deleteFrom(table)) } function tableDatabase(table: string): unknown { return guardTransactionQuery(getDb().table(table)) } function selectDatabase(table: string, ...columns: string[]): unknown { return guardTransactionQuery(getReadDb().select(table, ...columns)) } function selectFromSubDatabase(subquery: unknown, alias: string): unknown { return guardTransactionQuery(getReadDb().selectFromSub(subquery as { toSQL: () => string }, alias)) } function tableExplicitReadDatabase(table: string): unknown { return guardTransactionQuery(getExplicitReadDb().table(table)) } function selectExplicitReadDatabase(table: string, ...columns: string[]): unknown { return guardTransactionQuery(getExplicitReadDb().select(table, ...columns)) } function selectFromSubExplicitReadDatabase(subquery: unknown, alias: string): unknown { return guardTransactionQuery(getExplicitReadDb().selectFromSub(subquery as { toSQL: () => string }, alias)) } /** A reusable decorator owns no connection until it is invoked. */ function transactionalDatabase( callback: (tx: RawQueryBuilder, ...args: TArgs) => R, options?: Parameters[1], ): (...args: TArgs) => R { return (...args) => getDb().transaction(tx => callback(tx, ...args), options) } /** * Lazy fallback for the query-builder surface. The common facade properties * live on `db` itself below, so `db.selectFrom()` does not enter a Proxy on * every read; uncommon methods still resolve lazily through this prototype. */ const dbFallback = new Proxy({} as Db, { get(_target, prop) { // Reads consult the router; everything else (transactions, DDL, raw // `unsafe`) stays on the primary unconditionally. `unsafe` is a // deliberate omission — its SQL is opaque here, so it could be a write, // and routing it on a guess would be the worst kind of wrong. const resolveInstance = typeof prop === 'string' && READ_ENTRY_POINTS.has(prop) ? getReadDb : getDb const instance = resolveInstance() const value = (instance as unknown as Record)[prop] if (typeof value === 'function') { return forwardDatabaseMethod(prop, resolveInstance) } return value }, }) /** Retained eager helpers must resolve and validate before they issue SQL. */ function forwardDatabaseMethod(prop: string | symbol, resolveInstance: () => RawQueryBuilder): (...args: unknown[]) => unknown { const scope = transactionConnection.getStore() return (...args) => { if (scope) { assertTransactionConnection(scope) if (transactionConnection.getStore() !== scope) throw new Error('A transaction query must execute in the callback that created it.') } const instance = resolveInstance() if (typeof prop === 'string' && WRITE_ENTRY_POINTS.has(prop)) markContextWrote() return guardTransactionQuery(Reflect.apply(Reflect.get(instance, prop), instance, args)) } } /** * Lazy query-builder facade. Own properties bypass the Proxy prototype while * preserving the same connection-on-first-use behavior. */ export const db: Db = Object.create(dbFallback) as Db Object.defineProperties(db, { deleteFrom: { value: deleteFromDatabase }, fn: { value: aggregateFunctions }, insertInto: { value: insertIntoDatabase }, primary: { get: () => primaryDb }, read: { get: () => readDb }, select: { value: selectDatabase }, selectFrom: { value: selectFromDatabase }, selectFromSub: { value: selectFromSubDatabase }, table: { value: tableDatabase }, transactional: { value: transactionalDatabase }, unsafe: { value: unsafeDatabase }, updateTable: { value: updateTableDatabase }, }) /** * Replica-routed handle exposed as `db.read`. * * Its common properties use the same facade shape as `db`; the Proxy * prototype retains the complete builder surface without putting common * SQLite reads through the generic builder. */ const readDbFallback = new Proxy({} as Db, { get(_target, prop) { const instance = getExplicitReadDb() const value = (instance as unknown as Record)[prop] if (typeof value === 'function') { return forwardDatabaseMethod(prop, getExplicitReadDb) } return value }, }) export const readDb: Omit = Object.create(readDbFallback) as Omit Object.defineProperties(readDb, { fn: { value: aggregateFunctions }, select: { value: selectExplicitReadDatabase }, selectFrom: { value: selectFromExplicitReadDatabase }, selectFromSub: { value: selectFromSubExplicitReadDatabase }, table: { value: tableExplicitReadDatabase }, transactional: { value: transactionalDatabase }, unsafe: { value: unsafeExplicitReadDatabase }, }) // Authentication and other consistency-sensitive reads must see committed // primary state even when the application opts into automatic replica reads. // Resolve lazily through getDb so an active transaction remains authoritative; // forwardDatabaseMethod also guards retained methods after that scope ends. const primaryDb = new Proxy({} as Omit, { get(_target, prop) { const instance = getDb() const value = Reflect.get(instance, prop) return typeof value === 'function' ? forwardDatabaseMethod(prop, getDb) : value }, }) // Export setConfig if available export { setConfig }