src/lib/db/index.ts
Linked repository file from this build.
import { drizzle as drizzleNeon } from "drizzle-orm/neon-http";
import { drizzle as drizzlePostgres } from "drizzle-orm/node-postgres";
import { neon } from "@neondatabase/serverless";
import { Pool } from "pg";
import type { SQL } from "drizzle-orm";
let pool: Pool | undefined;
function localDb(url: string) {
pool ??= new Pool({ connectionString: url });
const db = drizzlePostgres(pool);
return Object.assign(db, {
/** Match Neon's batch: one transaction, and one row array per query. */
async batch(queries: { getSQL(): SQL }[]): Promise<Record<string, unknown>[][]> {
return db.transaction(async (tx) => {
const results = [];
for (const query of queries) results.push((await tx.execute(query.getSQL())).rows);
return results;
});
},
});
}
export function getDb() {
const url = process.env.DATABASE_URL;
if (!url) throw new Error("DATABASE_URL is not configured.");
const host = new URL(url).hostname;
if (host === "localhost" || host === "127.0.0.1") return localDb(url);
return drizzleNeon(neon(url));
}