loreal-sla-calculator/server/db/migrate.js
2026-03-13 10:52:07 +00:00

39 lines
1.1 KiB
JavaScript
Executable file

'use strict';
require('dotenv').config({ path: `${__dirname}/../.env` });
const fs = require('fs');
const path = require('path');
const pool = require('./index');
async function migrate() {
const migrationsDir = path.join(__dirname, 'migrations');
const files = fs.readdirSync(migrationsDir).filter(f => f.endsWith('.sql')).sort();
// Ensure migrations tracking table exists
await pool.query(`
CREATE TABLE IF NOT EXISTS _migrations (
id SERIAL PRIMARY KEY,
filename TEXT UNIQUE NOT NULL,
run_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
`);
for (const file of files) {
const { rows } = await pool.query('SELECT 1 FROM _migrations WHERE filename = $1', [file]);
if (rows.length > 0) {
console.log(` skip ${file}`);
continue;
}
const sql = fs.readFileSync(path.join(migrationsDir, file), 'utf8');
await pool.query(sql);
await pool.query('INSERT INTO _migrations (filename) VALUES ($1)', [file]);
console.log(` apply ${file}`);
}
console.log('Migrations complete.');
await pool.end();
}
migrate().catch(err => {
console.error('Migration failed:', err);
process.exit(1);
});