import { Kysely, ParseJSONResultsPlugin } from "kysely"; import { BunSqliteDialect } from "kysely-bun-sqlite"; import { Database } from "bun:sqlite"; import { ParseBooleanResultsPlugin, type BooleanColumnsMap } from "./kysely-parse-boolean"; /** * Synchronously introspect BOOLEAN/BOOL columns from a bun:sqlite Database. * * We can't use kysely's async introspector here because the bun-sqlite driver * serializes connection access with a mutex, and kysely holds the connection * across plugin transformResult calls. If transformResult awaits a promise * that's waiting on introspection, the second introspection query deadlocks * on the mutex held by the user query. Building the cache up-front avoids * the race entirely. */ function introspectBooleanColumnsSync(database: Database): BooleanColumnsMap { const cache = new Map>(); const tables = database .prepare(`SELECT name FROM sqlite_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite_%'`) .all() as Array<{ name: string }>; for (const { name: tableName } of tables) { const cols = database.prepare(`PRAGMA table_info(${JSON.stringify(tableName)})`).all() as Array<{ name: string; type: string; }>; const booleanCols = new Set(); for (const col of cols) { const dataType = (col.type ?? "").toUpperCase(); if (dataType === "BOOLEAN" || dataType === "BOOL") { booleanCols.add(col.name); } } if (booleanCols.size > 0) { cache.set(tableName, booleanCols); } } return cache; } export function createKyselyDatasourceClient(dbPath: string = ":memory:"): Kysely { console.debug("Creating Kysely client (bun) with dbPath:", dbPath); const database = new Database(dbPath, { create: true }); // Synchronous introspection eliminates the races (deadlock and silent-skip) // that arise from doing it asynchronously after Kysely is built. const booleanPlugin = new ParseBooleanResultsPlugin( Promise.resolve(introspectBooleanColumnsSync(database)), ); return new Kysely({ dialect: new BunSqliteDialect({ database }), plugins: [new ParseJSONResultsPlugin(), booleanPlugin], log: process.env.FLIPPABLE_ENV !== "production" ? ["query", "error"] : ["error"], }); }