diff --git a/apps/api/src/migrate.js b/apps/api/src/migrate.js index f8d9bf7..8694139 100644 --- a/apps/api/src/migrate.js +++ b/apps/api/src/migrate.js @@ -6,12 +6,14 @@ import { fileURLToPath } from 'url'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const MIGRATIONS_DIR = path.join(__dirname, '../migrations'); -async function connectWithRetry(client, maxAttempts = 12) { +async function connectWithRetry(connStr, maxAttempts = 12) { for (let i = 1; i <= maxAttempts; i++) { + const client = new pg.Client({ connectionString: connStr }); try { await client.connect(); - return; + return client; } catch (err) { + await client.end().catch(() => {}); if (i === maxAttempts) throw err; const delay = Math.min(2000 * i, 30000); console.log(`[migrate] DB not ready (attempt ${i}/${maxAttempts}), retry in ${delay}ms — ${err.message}`); @@ -20,10 +22,8 @@ async function connectWithRetry(client, maxAttempts = 12) { } } -const client = new pg.Client({ connectionString: process.env.DATABASE_URL }); - async function run() { - await connectWithRetry(client); + const client = await connectWithRetry(process.env.DATABASE_URL); await client.query(` CREATE TABLE IF NOT EXISTS schema_migrations (