import type { D1Database } from '@cloudflare/workers-types' import { drizzle, type DrizzleD1Database } from 'drizzle-orm/d1' import * as schema from './schema' type DbClient = DrizzleD1Database let dbInstance: DbClient | null = null function isQueryLoggingDisabled(): boolean { const flag = (globalThis as any).ENV?.DRIZZLE_LOG ?? (globalThis as any).process?.env?.DRIZZLE_LOG return flag === false || flag === 'false' || flag === '0' } const queryLogger = { logQuery(query: string, params: unknown[]): void { if (params?.length) { console.log(`[drizzle] ${query}`, params) } else { console.log(`[drizzle] ${query}`) } }, } export function initDb(database: D1Database): void { const base = drizzle(database, { schema, // logger: isQueryLoggingDisabled() ? undefined : queryLogger, }) as DbClient dbInstance = Object.assign(base, { transaction: async (handler: (tx: DbClient) => Promise): Promise => { return handler(base) }, }) } export const db = new Proxy({} as DbClient, { get(_target, prop: keyof DbClient) { if (!dbInstance) { throw new Error('D1 database not initialized. Call initDb(env.DB) before using db helpers.') } return dbInstance[prop] }, })