import postgres from 'postgres'; import { readFile } from 'node:fs/promises'; import { fileURLToPath } from 'node:url'; import { dirname, resolve } from 'node:path'; import type { Config } from './config.js'; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); export type Sql = ReturnType; let sqlInstance: Sql | null = null; export function getSql(config: Config): Sql { if (sqlInstance) return sqlInstance; sqlInstance = postgres(config.DATABASE_URL, { max: 10, idle_timeout: 30, connect_timeout: 10, onnotice: () => {}, }); return sqlInstance; } export async function applySchema(sql: Sql): Promise { const schemaPath = resolve(__dirname, 'schema.sql'); const ddl = await readFile(schemaPath, 'utf8'); await sql.unsafe(ddl); } export async function pingDb(sql: Sql): Promise { try { await sql`SELECT 1`; return true; } catch { return false; } } export async function closeDb(): Promise { if (sqlInstance) { await sqlInstance.end({ timeout: 5 }); sqlInstance = null; } }