Files
Alberto-Audrix 32a36cceff
CI / lint-and-test (push) Canceled after 0s
first commit
2026-07-28 08:55:05 +07:00

68 lines
1.9 KiB
JavaScript

const fs = require('fs');
const path = require('path');
const { query, closePool, dbReady } = require('./db');
const MIGRATIONS_DIR = path.join(__dirname, 'migrations');
async function runMigrations() {
try {
// Wait for schema to be initialized before running migrations
await dbReady;
// Create migrations tracking table if it doesn't exist
await query(`
CREATE TABLE IF NOT EXISTS schema_migrations (
id SERIAL PRIMARY KEY,
filename VARCHAR(255) NOT NULL UNIQUE,
applied_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
)
`);
// Get list of already applied migrations
const applied = await query('SELECT filename FROM schema_migrations ORDER BY filename');
const appliedSet = new Set(applied.rows.map((r) => r.filename));
// Read all .sql files from migrations directory, sorted alphabetically
const files = fs
.readdirSync(MIGRATIONS_DIR)
.filter((f) => f.endsWith('.sql'))
.sort();
let migrationsRun = 0;
for (const file of files) {
if (appliedSet.has(file)) {
continue;
}
const filePath = path.join(MIGRATIONS_DIR, file);
const sql = fs.readFileSync(filePath, 'utf8');
// Execute the entire migration as a single statement block
await query(sql);
// Record the migration
await query('INSERT INTO schema_migrations (filename) VALUES ($1)', [file]);
migrationsRun++;
}
if (migrationsRun === 0) {
} else {
}
} catch (error) {
console.error('Migration error:', error.message);
throw error;
}
}
// Run if executed directly
if (require.main === module) {
runMigrations()
.then(() => closePool())
.then(() => process.exit(0))
.catch(() => {
closePool().then(() => process.exit(1));
});
}
module.exports = { runMigrations };