import postgres from "postgres"; const sql = postgres(process.env.DATABASE_URL ?? "postgres://pingql:pingql@localhost:5432/pingql"); export default sql; // Run migrations on startup export async function migrate() { await sql` CREATE TABLE IF NOT EXISTS accounts ( id TEXT PRIMARY KEY, -- random 16-digit key email_hash TEXT, -- optional, for recovery only created_at TIMESTAMPTZ DEFAULT now() ) `; await sql` CREATE TABLE IF NOT EXISTS monitors ( id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text, account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, name TEXT NOT NULL, url TEXT NOT NULL, interval_s INTEGER NOT NULL DEFAULT 60, -- check interval in seconds query JSONB, -- pingql query filter enabled BOOLEAN NOT NULL DEFAULT true, created_at TIMESTAMPTZ DEFAULT now() ) `; await sql` CREATE TABLE IF NOT EXISTS check_results ( id BIGSERIAL PRIMARY KEY, monitor_id TEXT NOT NULL REFERENCES monitors(id) ON DELETE CASCADE, checked_at TIMESTAMPTZ NOT NULL DEFAULT now(), status_code INTEGER, latency_ms INTEGER, up BOOLEAN NOT NULL, error TEXT, meta JSONB -- headers, body snippet, etc. ) `; await sql`CREATE INDEX IF NOT EXISTS idx_results_monitor ON check_results(monitor_id, checked_at DESC)`; console.log("DB ready"); }