import { drizzle } from "drizzle-orm/postgres-js"; import postgres from "postgres"; import * as appSchema from "./schema"; import * as authSchema from "./auth-schema"; const schema = { ...appSchema, ...authSchema }; type PostgresClient = ReturnType; type Database = ReturnType>; export type { Database }; const globalDatabase = globalThis as typeof globalThis & { albumPostgresClient?: PostgresClient; albumDatabase?: Database; }; let client = globalDatabase.albumPostgresClient; let database = globalDatabase.albumDatabase; export function getDb() { if (database) return database; const url = process.env.DATABASE_URL; if (!url) { throw new Error("DATABASE_URL is required for database operations"); } client = postgres(url, { max: process.env.NODE_ENV === "production" ? 10 : 3, idle_timeout: 20, }); database = drizzle(client, { schema }); if (process.env.NODE_ENV !== "production") { globalDatabase.albumPostgresClient = client; globalDatabase.albumDatabase = database; } return database; } export async function closeDb() { await client?.end(); client = undefined; database = undefined; globalDatabase.albumPostgresClient = undefined; globalDatabase.albumDatabase = undefined; }