diff --git a/server/db.ts b/server/db.ts index 5bea859..eadd63f 100644 --- a/server/db.ts +++ b/server/db.ts @@ -18,9 +18,22 @@ const pool = new Pool({ export const db = drizzle(pool); +// Use raw pool client for DDL — Drizzle wraps queries in prepared statements +// and PostgreSQL rejects CREATE/ALTER IF NOT EXISTS in prepared queries. +async function executeDDL(query: string): Promise { + const client = await pool.connect(); + try { + await client.query(query); + } catch { + // Table/column already exists — ignore silently + } finally { + client.release(); + } +} + // Initialize users table if it doesn't exist (called at startup) export async function initDb(): Promise { - await db.execute(` + await executeDDL(` CREATE TABLE IF NOT EXISTS users ( id SERIAL PRIMARY KEY, name TEXT NOT NULL, @@ -32,14 +45,14 @@ export async function initDb(): Promise { created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW() ) `); - + // Add columns if they don't exist (for existing tables) - await addColumnIfExists('email_verified', 'BOOLEAN NOT NULL DEFAULT FALSE'); - await addColumnIfExists('verification_token', 'TEXT'); - await addColumnIfExists('verification_token_expiry', 'TIMESTAMP WITH TIME ZONE'); + await executeDDL(`ALTER TABLE users ADD COLUMN email_verified BOOLEAN NOT NULL DEFAULT FALSE`); + await executeDDL(`ALTER TABLE users ADD COLUMN verification_token TEXT`); + await executeDDL(`ALTER TABLE users ADD COLUMN verification_token_expiry TIMESTAMP WITH TIME ZONE`); // Create custom_symbols table - await db.execute(` + await executeDDL(` CREATE TABLE IF NOT EXISTS custom_symbols ( id SERIAL PRIMARY KEY, ticker TEXT NOT NULL UNIQUE, @@ -52,14 +65,6 @@ export async function initDb(): Promise { `); } -async function addColumnIfExists(column: string, typeDef: string): Promise { - try { - await db.execute(`ALTER TABLE users ADD COLUMN ${column} ${typeDef}`); - } catch { - // Column already exists or table doesn't exist — ignore - } -} - export async function createUser(data: NewUser): Promise { const [user] = await db.insert(users).values(data).returning(); return user;