import 'server-only' import { Pool } from 'pg' import { drizzle } from 'drizzle-orm/node-postgres' import * as schema from './schema' function getDb() { if (!process.env.DATABASE_URL) { throw new Error('DATABASE_URL not configured') } if (!process.env.DATABASE_URL_ADMIN) { throw new Error('DATABASE_URL_ADMIN not configured') } // app_user pool: RLS enforced. Used for all normal user operations. const userPool = new Pool({ connectionString: process.env.DATABASE_URL, max: 10, }) // app_admin pool: BYPASSRLS. Used for admin user CRUD and service operations. const adminPool = new Pool({ connectionString: process.env.DATABASE_URL_ADMIN, max: 5, }) return { userDb: drizzle(userPool, { schema }), adminDb: drizzle(adminPool, { schema }), } } // Lazy singleton — pools are created on first access, not at module load time. // This prevents Next.js build from throwing during static analysis when env vars // are not present in the build environment. let _dbs: ReturnType | null = null function dbs() { if (!_dbs) _dbs = getDb() return _dbs } export const userDb = new Proxy({} as ReturnType['userDb'], { get(_target, prop) { return (dbs().userDb as unknown as Record)[prop] }, }) export const adminDb = new Proxy({} as ReturnType['adminDb'], { get(_target, prop) { return (dbs().adminDb as unknown as Record)[prop] }, }) export type UserDb = ReturnType['userDb'] export type AdminDb = ReturnType['adminDb']