2026-03-19 14:00:32 -06:00
|
|
|
import { drizzle } from "drizzle-orm/postgres-js";
|
|
|
|
|
import postgres from "postgres";
|
2026-03-19 13:30:52 -06:00
|
|
|
import * as schema from "./schema";
|
|
|
|
|
|
2026-03-19 13:33:15 -06:00
|
|
|
type DrizzleDb = ReturnType<typeof createDb>;
|
|
|
|
|
|
|
|
|
|
function createDb() {
|
|
|
|
|
const url = process.env.DATABASE_URL;
|
|
|
|
|
if (!url) {
|
|
|
|
|
throw new Error("DATABASE_URL environment variable is not set");
|
|
|
|
|
}
|
2026-04-03 16:53:18 -06:00
|
|
|
const client = postgres(url, { max: 5 });
|
2026-03-19 14:00:32 -06:00
|
|
|
return drizzle({ client, schema });
|
2026-03-19 13:33:15 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Lazy singleton — created on first use, not at module load time
|
|
|
|
|
let _db: DrizzleDb | undefined;
|
|
|
|
|
|
|
|
|
|
export const db = new Proxy({} as DrizzleDb, {
|
|
|
|
|
get(_target, prop: string | symbol) {
|
|
|
|
|
if (!_db) _db = createDb();
|
|
|
|
|
return (_db as unknown as Record<string | symbol, unknown>)[prop];
|
|
|
|
|
},
|
|
|
|
|
});
|