import { drizzle } from 'drizzle-orm/node-postgres'; import type { NodePgDatabase } from 'drizzle-orm/node-postgres'; import * as schema from './schema'; import '@/lib/env-config'; let _db: NodePgDatabase | null = null; function getDb() { if (!_db) { const DATABASE_URL = process.env.POSTGRES_URL; if (!DATABASE_URL) { throw new Error('POSTGRES_URL environment variable is required'); } _db = drizzle(DATABASE_URL, { schema }); } return _db; } export const db = new Proxy({} as NodePgDatabase, { get(target, prop) { const database = getDb(); const value = database[prop as keyof typeof database]; return typeof value === 'function' ? value.bind(database) : value; }, }); // Re-export schema types for convenience export * from './schema';