fix: Use raw pool client for DDL to avoid Drizzle prepared statement issue with CREATE IF NOT EXISTS

master
isnowglobal-admin 2026-06-30 10:11:40 -04:00
parent b8f590708d
commit f35924eb54
1 changed files with 19 additions and 14 deletions

View File

@ -18,9 +18,22 @@ const pool = new Pool({
export const db = drizzle(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<void> {
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) // Initialize users table if it doesn't exist (called at startup)
export async function initDb(): Promise<void> { export async function initDb(): Promise<void> {
await db.execute(` await executeDDL(`
CREATE TABLE IF NOT EXISTS users ( CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY, id SERIAL PRIMARY KEY,
name TEXT NOT NULL, name TEXT NOT NULL,
@ -32,14 +45,14 @@ export async function initDb(): Promise<void> {
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW() created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
) )
`); `);
// Add columns if they don't exist (for existing tables) // Add columns if they don't exist (for existing tables)
await addColumnIfExists('email_verified', 'BOOLEAN NOT NULL DEFAULT FALSE'); await executeDDL(`ALTER TABLE users ADD COLUMN email_verified BOOLEAN NOT NULL DEFAULT FALSE`);
await addColumnIfExists('verification_token', 'TEXT'); await executeDDL(`ALTER TABLE users ADD COLUMN verification_token TEXT`);
await addColumnIfExists('verification_token_expiry', 'TIMESTAMP WITH TIME ZONE'); await executeDDL(`ALTER TABLE users ADD COLUMN verification_token_expiry TIMESTAMP WITH TIME ZONE`);
// Create custom_symbols table // Create custom_symbols table
await db.execute(` await executeDDL(`
CREATE TABLE IF NOT EXISTS custom_symbols ( CREATE TABLE IF NOT EXISTS custom_symbols (
id SERIAL PRIMARY KEY, id SERIAL PRIMARY KEY,
ticker TEXT NOT NULL UNIQUE, ticker TEXT NOT NULL UNIQUE,
@ -52,14 +65,6 @@ export async function initDb(): Promise<void> {
`); `);
} }
async function addColumnIfExists(column: string, typeDef: string): Promise<void> {
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<User> { export async function createUser(data: NewUser): Promise<User> {
const [user] = await db.insert(users).values(data).returning(); const [user] = await db.insert(users).values(data).returning();
return user; return user;