fix: Use raw pool client for DDL to avoid Drizzle prepared statement issue with CREATE IF NOT EXISTS
parent
b8f590708d
commit
f35924eb54
31
server/db.ts
31
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<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)
|
||||
export async function initDb(): Promise<void> {
|
||||
await db.execute(`
|
||||
await executeDDL(`
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
|
|
@ -34,12 +47,12 @@ export async function initDb(): Promise<void> {
|
|||
`);
|
||||
|
||||
// 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<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> {
|
||||
const [user] = await db.insert(users).values(data).returning();
|
||||
return user;
|
||||
|
|
|
|||
Loading…
Reference in New Issue