const fs = require('fs'); const path = require('path'); const { query } = require('./db'); async function runMigrations() { try { await query(` CREATE TABLE IF NOT EXISTS schema_migrations ( id SERIAL PRIMARY KEY, filename VARCHAR(255) UNIQUE NOT NULL, applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) `); await query(` CREATE INDEX IF NOT EXISTS idx_schema_migrations_filename ON schema_migrations(filename) `); // Get all migration files const migrationsDir = path.join(__dirname, 'migrations'); if (!fs.existsSync(migrationsDir)) { return; } const files = fs .readdirSync(migrationsDir) .filter((f) => f.endsWith('.sql')) .sort(); // Run in alphabetical order (001_, 002_, etc.) if (files.length === 0) { return; } let appliedCount = 0; let skippedCount = 0; // Process each migration file for (const file of files) { // Check if migration has already been applied const checkResult = await query('SELECT * FROM schema_migrations WHERE filename = $1', [ file, ]); if (checkResult.rows.length > 0) { skippedCount++; continue; } // Apply new migration try { const filePath = path.join(migrationsDir, file); const sql = fs.readFileSync(filePath, 'utf8'); // Execute migration SQL await query(sql); // Record migration as applied await query('INSERT INTO schema_migrations (filename) VALUES ($1)', [file]); appliedCount++; } catch (error) { console.error(` ❌ ${file} - FAILED`); console.error(` Error: ${error.message}`); throw error; // Stop on first error } } } catch (error) { console.error('\n' + '='.repeat(50)); console.error('❌ Migration failed!'); console.error('='.repeat(50)); console.error(error); console.error('\n⚠️ Server startup aborted due to migration failure\n'); throw error; // Re-throw to prevent server from starting } } module.exports = { runMigrations };