SPB Git
1006 B · 15 lines typescript
1import postgres from "postgres";23export type Sql = ReturnType<typeof postgres>;4const g = globalThis as unknown as { __wpSql?: Sql; __wpSqlPublic?: Sql };5const opts = { max: 6, idle_timeout: 30, prepare: false, transform: { undefined: null }, onnotice: () => {} } as const;6function need(name: string) { const v = process.env[name]; if (!v) throw new Error(`${name} is not set`); return v; }78/** Full-privilege client (admin, worker, scripts). Never import from public route modules. */9export const sql: Sql = g.__wpSql ?? postgres(need("DATABASE_URL"), opts);10/** Read-only client for everything public: `wp_reader` role (SELECT on public views only, INSERT on events/search_log). */11export const sqlPublic: Sql = g.__wpSqlPublic ?? postgres(process.env.DATABASE_URL_PUBLIC ?? need("DATABASE_URL"), { ...opts, max: 12 });12if (process.env.NODE_ENV !== "production") { g.__wpSql = sql; g.__wpSqlPublic = sqlPublic; }1314export async function closeDb() { await Promise.all([sql.end(), sqlPublic.end()]); }15
Files · main
Menu

Theme