import postgres from "postgres"; const sql = postgres(process.env.DATABASE_URL ?? "postgres://pingql:pingql@localhost:5432/pingql"); export default sql; export async function migrate() { await sql` CREATE TABLE IF NOT EXISTS accounts ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), key TEXT NOT NULL UNIQUE, email_hash TEXT, created_at TIMESTAMPTZ DEFAULT now() ) `; await sql` CREATE TABLE IF NOT EXISTS monitors ( id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text, account_id UUID NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, name TEXT NOT NULL, url TEXT NOT NULL, method TEXT NOT NULL DEFAULT 'GET', request_headers JSONB, request_body TEXT, timeout_ms INTEGER NOT NULL DEFAULT 30000, interval_s INTEGER NOT NULL DEFAULT 60, query JSONB, enabled BOOLEAN NOT NULL DEFAULT true, created_at TIMESTAMPTZ DEFAULT now() ) `; await sql` CREATE TABLE IF NOT EXISTS pings ( 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 ) `; await sql`CREATE INDEX IF NOT EXISTS idx_pings_monitor ON pings(monitor_id, checked_at DESC)`; await sql`CREATE INDEX IF NOT EXISTS idx_pings_checked_at ON pings(checked_at)`; await sql` CREATE TABLE IF NOT EXISTS api_keys ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), key TEXT NOT NULL UNIQUE, account_id UUID NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, label TEXT NOT NULL, created_at TIMESTAMPTZ DEFAULT now(), last_used_at TIMESTAMPTZ ) `; console.log("DB ready"); }