AstroCom-API/migrations.js

66 lines
2.6 KiB
JavaScript

const sqlite3 = require('sqlite3').verbose();
const fs = require('fs');
const path = require('path');
const util = require("util");
function runMigrations(db) {
return new Promise((resolve, reject) => {
const migrationDir = path.join(__dirname, 'migrations');
const runQuery = util.promisify(db.run.bind(db));
const getQuery = util.promisify(db.get.bind(db));
// Ensure a migrations table exists to track applied migrations
runQuery(`CREATE TABLE IF NOT EXISTS migrations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);`)
.then(() => {
// Read all migration files
const files = fs.readdirSync(migrationDir).sort(); // Sort to apply in order
return files.reduce((promise, file) => {
return promise.then(() => {
const migrationName = path.basename(file);
// Check if the migration has already been applied
return getQuery(
'SELECT 1 FROM migrations WHERE name = ? LIMIT 1',
[migrationName]
).then((row) => {
if (row) {
// console.log(`Skipping already applied migration: ${migrationName}`);
return; // Skip this migration
}
// Read and execute the migration SQL
const migrationPath = path.join(migrationDir, file);
const sql = fs.readFileSync(migrationPath, 'utf8');
return runQuery(sql).then(() => {
// Record the applied migration
return runQuery(
'INSERT INTO migrations (name) VALUES (?)',
[migrationName]
).then(() => {
console.log(`Applied migration: ${migrationName}`);
});
});
});
});
}, Promise.resolve());
})
.then(() => {
console.log('All migrations applied successfully!');
resolve();
})
.catch((err) => {
console.error('Error running migrations:', err);
reject(err);
})
});
}
module.exports = runMigrations;