1import postgres, { type PostgresClient } from "@prisma-next/postgres/runtime";
2import { Pool } from "pg";
3import type { Contract } from "./contract.d";
4import contractJson from "./contract.json" with { type: "json" };
5
6type Db = PostgresClient<Contract>;
7
8let cached: { db: Db; pool: Pool } | undefined;
9
10export function getDb(): Db {
11 if (!cached) {
12 const connectionString = process.env.DATABASE_URL;
13 if (!connectionString) {
14 throw new Error("DATABASE_URL is required for Prisma Next queries.");
15 }
16
17 const poolMax = process.env.PRISMA_TANSTACK_PG_POOL_MAX;
18 const pool = new Pool({
19 connectionString,
20 ...(poolMax === undefined ? {} : { max: Number(poolMax) }),
21 });
22
23 pool.on("error", (error) => {
24 console.error("[prisma-tanstack-start] pg pool error:", error.message);
25 });
26
27 cached = {
28 db: postgres<Contract>({
29 contractJson,
30 binding: { kind: "pgPool", pool },
31 }),
32 pool,
33 };
34 }
35
36 return cached.db;
37}
38
39export async function closeDb() {
40 if (!cached) return;
41 const { pool } = cached;
42 cached = undefined;
43 await pool.end();
44}
45
46if (import.meta.hot) {
47 import.meta.hot.dispose(async () => {
48 await closeDb();
49 });
50}