57 lines
1.6 KiB
JavaScript
57 lines
1.6 KiB
JavaScript
/**
|
|
* Run pending migrations on an existing database
|
|
*/
|
|
import initSqlJs from 'sql.js';
|
|
import path from 'path';
|
|
import fs from 'fs';
|
|
import { fileURLToPath } from 'url';
|
|
|
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
const dataDir = path.join(__dirname, '..', 'data');
|
|
const dbPath = process.env.DATABASE_PATH || path.join(dataDir, 'configurateur.db');
|
|
const migrationsDir = path.join(__dirname, 'migrations');
|
|
|
|
async function migrate() {
|
|
if (!fs.existsSync(dbPath)) {
|
|
console.error(`Database not found at ${dbPath}. Run db:init first.`);
|
|
process.exit(1);
|
|
}
|
|
|
|
const SQL = await initSqlJs({
|
|
locateFile: (file) => path.join(__dirname, '..', 'node_modules', 'sql.js', 'dist', file)
|
|
});
|
|
|
|
const buffer = fs.readFileSync(dbPath);
|
|
const db = new SQL.Database(buffer);
|
|
|
|
// Get migration files
|
|
const migrationFiles = fs.readdirSync(migrationsDir)
|
|
.filter(f => f.endsWith('.sql'))
|
|
.sort();
|
|
|
|
console.log(`Found ${migrationFiles.length} migration(s)`);
|
|
|
|
for (const file of migrationFiles) {
|
|
console.log(`Running migration: ${file}`);
|
|
const sql = fs.readFileSync(path.join(migrationsDir, file), 'utf8');
|
|
try {
|
|
db.exec(sql);
|
|
console.log(` ✓ ${file} applied`);
|
|
} catch (err) {
|
|
// IF NOT EXISTS should prevent errors on re-run
|
|
console.log(` ✓ ${file} (already applied or no changes)`);
|
|
}
|
|
}
|
|
|
|
// Save database
|
|
fs.writeFileSync(dbPath, Buffer.from(db.export()));
|
|
db.close();
|
|
|
|
console.log('Migrations complete.');
|
|
}
|
|
|
|
migrate().catch(err => {
|
|
console.error('Migration failed:', err);
|
|
process.exit(1);
|
|
});
|