import { Kysely, ParseJSONResultsPlugin } from "kysely"; import { D1Dialect } from "./kysely-d1"; import { D1Database } from "@cloudflare/workers-types"; import { env } from "cloudflare:workers"; import { D1EventPlugin } from "./kysely-events"; import { ParseBooleanResultsPlugin, introspectBooleanColumns, type BooleanColumnsMap, } from "./kysely-parse-boolean"; /** * * @param _dbPath not to be used - just to keep the same signature as the bun client * @returns */ export function createKyselyDatasourceClient(_dbPath: string = "") { const d1Database = (env as unknown as { DB: D1Database }).DB; // Use a deferred promise so user queries that race introspection will await it // (instead of seeing an empty cache and silently skipping conversion). let resolveCols!: (cols: BooleanColumnsMap) => void; const colsPromise = new Promise((resolve) => { resolveCols = resolve; }); const booleanPlugin = new ParseBooleanResultsPlugin(colsPromise); const db = new Kysely({ dialect: new D1Dialect({ database: d1Database, }), plugins: [new ParseJSONResultsPlugin(), booleanPlugin, new D1EventPlugin((): Kysely => db)], log: process.env.FLIPPABLE_ENV !== "production" ? ["query", "error"] : ["error"], }); // Run introspection through a plugin-less view of the db: the plugin's // transformResult would otherwise await colsPromise and deadlock against // the introspection queries that are themselves trying to populate it. introspectBooleanColumns(db.withoutPlugins()) .then(resolveCols) .catch((err) => { console.error("Error introspecting boolean columns:", err); resolveCols(new Map()); }); return db; }