Add Postgres pool, health query and start-time migrations

This commit is contained in:
Grok Bot
2026-11-26 09:10:37 +00:00
parent 3c470ba85b
commit 4924059685
3 changed files with 134 additions and 0 deletions
+15
View File
@@ -0,0 +1,15 @@
// Next.js calls register() once when the server starts (also in the standalone server),
// which is where we run migrations. It runs before the first request is served.
export async function register() {
if (process.env.NEXT_RUNTIME !== 'nodejs') return;
if (process.env.NEXT_PHASE === 'phase-production-build') return; // never migrate during `next build`
if (process.env.SKIP_MIGRATIONS === '1') return;
const { runMigrations } = await import('./lib/migrate');
try {
await runMigrations();
} catch (e) {
console.error('[migrate] FATAL:', (e as Error).message);
process.exit(1); // let the platform restart / surface the failure
}
}
+45
View File
@@ -0,0 +1,45 @@
import { Pool } from 'pg';
declare global {
// eslint-disable-next-line no-var
var __pgPool: Pool | undefined;
}
export function connectionString(env: NodeJS.ProcessEnv = process.env): string {
const url = env.DATABASE_URL;
if (url) return url;
// Fallback: discrete variables (PG* standard, or DB_*)
const host = env.PGHOST || env.DB_HOST;
const user = env.PGUSER || env.DB_USER;
const db = env.PGDATABASE || env.DB_NAME;
if (!host || !user || !db) {
throw new Error('DATABASE_URL is not set (or provide DB_HOST/DB_USER/DB_PASSWORD/DB_NAME)');
}
const pass = encodeURIComponent(env.PGPASSWORD || env.DB_PASSWORD || '');
const port = env.PGPORT || env.DB_PORT || '5432';
return `postgres://${encodeURIComponent(user)}:${pass}@${host}:${port}/${db}`;
}
export function getPool(): Pool {
if (!globalThis.__pgPool) {
globalThis.__pgPool = new Pool({
connectionString: connectionString(),
max: 10,
idleTimeoutMillis: 30_000,
connectionTimeoutMillis: 10_000,
ssl: process.env.DATABASE_SSL === 'true' ? { rejectUnauthorized: false } : undefined,
});
globalThis.__pgPool.on('error', (e) => console.error('[pg] idle client error', e.message));
}
return globalThis.__pgPool;
}
export async function dbHealth() {
const started = Date.now();
try {
const r = await getPool().query('select version() as v, now() as now');
return { status: 'up' as const, latencyMs: Date.now() - started, serverVersion: String(r.rows[0].v).split(' ').slice(0, 2).join(' ') };
} catch (e) {
return { status: 'down' as const, error: (e as { code?: string; message: string }).code || (e as Error).message };
}
}
+74
View File
@@ -0,0 +1,74 @@
import { getPool } from './db';
// Migrations are embedded in code (not .sql files) so they are always present in
// Next.js' standalone output, which only traces files that are imported.
export const migrations: { id: string; sql: string }[] = [
{
id: '001_create_tasks',
sql: `
CREATE TABLE IF NOT EXISTS tasks (
id SERIAL PRIMARY KEY,
title VARCHAR(200) NOT NULL,
status VARCHAR(10) NOT NULL DEFAULT 'todo' CHECK (status IN ('todo','doing','done')),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
)`,
},
{
id: '002_tasks_status_index',
sql: `CREATE INDEX IF NOT EXISTS idx_tasks_status ON tasks (status, id)`,
},
{
id: '003_tasks_assignee_notes',
sql: `
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS assignee VARCHAR(80);
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS notes TEXT`,
},
];
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
/** Idempotent: safe to run on every start and from several instances at once. */
export async function runMigrations(log: Pick<Console, 'log' | 'warn'> = console) {
const retries = Number(process.env.DB_CONNECT_RETRIES || 30);
const delay = Number(process.env.DB_CONNECT_RETRY_MS || 2000);
let client;
for (let i = 1; ; i++) {
try {
client = await getPool().connect();
break;
} catch (e) {
log.warn(`[migrate] DB connect attempt ${i}/${retries} failed: ${(e as { code?: string; message: string }).code || (e as Error).message}`);
if (i >= retries) throw e;
await sleep(delay);
}
}
try {
await client.query('SELECT pg_advisory_lock(727001)');
await client.query(`CREATE TABLE IF NOT EXISTS schema_migrations (
id TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT now())`);
const { rows } = await client.query('SELECT id FROM schema_migrations');
const done = new Set(rows.map((r) => r.id));
let ran = 0;
for (const m of migrations) {
if (done.has(m.id)) continue;
await client.query('BEGIN');
try {
for (const stmt of m.sql.split(';').map((s) => s.trim()).filter(Boolean)) await client.query(stmt);
await client.query('INSERT INTO schema_migrations (id) VALUES ($1)', [m.id]);
await client.query('COMMIT');
log.log(`[migrate] applied ${m.id}`);
ran++;
} catch (e) {
await client.query('ROLLBACK');
throw new Error(`migration ${m.id} failed: ${(e as Error).message}`);
}
}
if (!ran) log.log('[migrate] schema up to date');
return ran;
} finally {
await client.query('SELECT pg_advisory_unlock(727001)').catch(() => {});
client.release();
}
}