fix: migrate() uses CREATE IF NOT EXISTS — no more data wipe on restart

This commit is contained in:
M1 2026-03-17 07:17:54 +04:00
parent 1794c05b4f
commit ed5e213b1a
1 changed files with 4 additions and 10 deletions

View File

@ -4,15 +4,9 @@ const sql = postgres(process.env.DATABASE_URL ?? "postgres://pingql:pingql@local
export default sql; export default sql;
// Run migrations on startup — full rebuild (no real users)
export async function migrate() { export async function migrate() {
await sql`DROP TABLE IF EXISTS pings CASCADE`;
await sql`DROP TABLE IF EXISTS api_keys CASCADE`;
await sql`DROP TABLE IF EXISTS monitors CASCADE`;
await sql`DROP TABLE IF EXISTS accounts CASCADE`;
await sql` await sql`
CREATE TABLE accounts ( CREATE TABLE IF NOT EXISTS accounts (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(), id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
key TEXT NOT NULL UNIQUE, key TEXT NOT NULL UNIQUE,
email_hash TEXT, email_hash TEXT,
@ -21,7 +15,7 @@ export async function migrate() {
`; `;
await sql` await sql`
CREATE TABLE monitors ( CREATE TABLE IF NOT EXISTS monitors (
id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text, id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text,
account_id UUID NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, account_id UUID NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
name TEXT NOT NULL, name TEXT NOT NULL,
@ -38,7 +32,7 @@ export async function migrate() {
`; `;
await sql` await sql`
CREATE TABLE pings ( CREATE TABLE IF NOT EXISTS pings (
id BIGSERIAL PRIMARY KEY, id BIGSERIAL PRIMARY KEY,
monitor_id TEXT NOT NULL REFERENCES monitors(id) ON DELETE CASCADE, monitor_id TEXT NOT NULL REFERENCES monitors(id) ON DELETE CASCADE,
checked_at TIMESTAMPTZ NOT NULL DEFAULT now(), checked_at TIMESTAMPTZ NOT NULL DEFAULT now(),
@ -54,7 +48,7 @@ export async function migrate() {
await sql`CREATE INDEX IF NOT EXISTS idx_pings_checked_at ON pings(checked_at)`; await sql`CREATE INDEX IF NOT EXISTS idx_pings_checked_at ON pings(checked_at)`;
await sql` await sql`
CREATE TABLE api_keys ( CREATE TABLE IF NOT EXISTS api_keys (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(), id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
key TEXT NOT NULL UNIQUE, key TEXT NOT NULL UNIQUE,
account_id UUID NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, account_id UUID NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,