Skip to content
Source
Sign inSign up
samwillis/neonbricks
Open History to see the last commit

db.ts

45 lines1.3 KB

1import { Pool, type PoolClient } from "pg";
2import { attachDatabasePool } from "@neon/functions";
3const url = process.env.DATABASE_URL;
4if (!url) throw new Error("DATABASE_URL is required");
5const connection = new URL(url);
6if (
7 !connection.hostname.includes("localhost") &&
8 connection.hostname !== "127.0.0.1"
9)
10 connection.searchParams.set("sslmode", "verify-full");
11export const pool = new Pool({
12 connectionString: connection.toString(),
13 max: 8,
14 connectionTimeoutMillis: 15_000,
15 ssl:
16 url.includes("localhost") || url.includes("127.0.0.1")
17 ? undefined
18 : { rejectUnauthorized: true },
19});
20attachDatabasePool(pool);
21export async function transaction<T>(
22 run: (c: PoolClient) => Promise<T>,
23): Promise<T> {
24 for (let n = 0; ; n++) {
25 const c = await pool.connect();
26 try {
27 await c.query(
28 "BEGIN ISOLATION LEVEL READ COMMITTED; SET LOCAL lock_timeout='2500ms'; SET LOCAL statement_timeout='15000ms'",
29 );
30 const r = await run(c);
31 await c.query("COMMIT");
32 return r;
33 } catch (e) {
34 await c.query("ROLLBACK").catch(() => {});
35 if (
36 n < 2 &&
37 ["40P01", "40001"].includes((e as { code?: string }).code || "")
38 )
39 continue;
40 throw e;
41 } finally {
42 c.release();
43 }
44 }