diff --git a/lib/db/index.ts b/lib/db/index.ts index bfdeab1..eed9e22 100644 --- a/lib/db/index.ts +++ b/lib/db/index.ts @@ -1,13 +1,28 @@ import { drizzle } from 'drizzle-orm/node-postgres'; +import type { NodePgDatabase } from 'drizzle-orm/node-postgres'; import * as schema from './schema'; import '@/lib/env-config'; -const DATABASE_URL = process.env.POSTGRES_URL; -if (!DATABASE_URL) { - throw new Error('POSTGRES_URL environment variable is required'); +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 = drizzle(DATABASE_URL, { schema }); +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';