fix(migrate): créer un nouveau pg.Client à chaque tentative de retry

pg.Client ne peut pas être réutilisé après un connect() échoué.
Le retry créait le même client → "Client has already been connected"
dès l'attempt 2. On crée maintenant un nouveau client à chaque essai.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Nicolas Fryder 2026-06-27 16:16:28 +02:00
parent c55366fb25
commit 70dd610aa2

View file

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