diff --git a/packages/db/src/drizzle.ts b/packages/db/src/drizzle.ts index 0daa4d63..b990905b 100644 --- a/packages/db/src/drizzle.ts +++ b/packages/db/src/drizzle.ts @@ -1,17 +1,38 @@ import { drizzle } from 'drizzle-orm/postgres-js' +import type { PostgresJsDatabase } from 'drizzle-orm/postgres-js' import postgres from 'postgres' import * as schema from './schema' -if (!process.env.POSTGRES_URL) { - throw new Error( - 'Missing POSTGRES_URL environment variable. Add your Supabase database connection string.', - ) +let _db: PostgresJsDatabase | null = null +let _client: ReturnType | null = null + +function getDb() { + if (!_db) { + const postgresUrl = process.env.POSTGRES_URL + + if (!postgresUrl) { + throw new Error( + 'Missing POSTGRES_URL environment variable. Please configure it in your deployment settings or .env.local file.', + ) + } + + // Create postgres connection + _client = postgres(postgresUrl) + + // Create drizzle instance + _db = drizzle(_client, { schema }) + } + return _db } -// Create postgres connection -const client = postgres(process.env.POSTGRES_URL) - -// Create drizzle instance -export const db = drizzle(client, { schema }) +/** + * Drizzle database instance + * Initialized lazily to avoid requiring env vars at build time + */ +export const db = new Proxy({} as PostgresJsDatabase, { + get(_target, prop) { + return Reflect.get(getDb(), prop) + }, +}) export type Database = typeof db