53 lines
1.5 KiB
JavaScript

import pg from 'pg'
const { Pool } = pg
let pool
export function getPool() {
if (!pool) {
if (!process.env.DATABASE_URL) throw new Error('DATABASE_URL is required')
pool = new Pool({
connectionString: process.env.DATABASE_URL,
max: 10,
ssl: process.env.DATABASE_SSL === 'true' ? { rejectUnauthorized: false } : undefined
})
}
return pool
}
export async function initDb() {
const db = getPool()
await db.query(`
CREATE TABLE IF NOT EXISTS templates (
id text PRIMARY KEY,
tenant_id text NOT NULL,
name text NOT NULL,
type text NOT NULL CHECK (type IN ('email', 'report')),
status text NOT NULL DEFAULT 'draft',
draft_document jsonb NOT NULL,
sample_data jsonb NOT NULL DEFAULT '{}'::jsonb,
published_version integer,
created_by text,
updated_by text,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
)
`)
await db.query(`
CREATE TABLE IF NOT EXISTS template_versions (
id text PRIMARY KEY,
template_id text NOT NULL REFERENCES templates(id) ON DELETE CASCADE,
version integer NOT NULL,
document jsonb NOT NULL,
sample_data jsonb NOT NULL DEFAULT '{}'::jsonb,
created_by text,
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE(template_id, version)
)
`)
await db.query(`
CREATE INDEX IF NOT EXISTS templates_tenant_updated_idx
ON templates (tenant_id, updated_at DESC)
`)
}