AstroCom-API/migrations.js

72 lines
2 KiB
JavaScript

const mariadb = require('mariadb');
const fs = require('fs');
const path = require('path');
const util = require("util")
function runMigrations(pool) {
return new Promise((resolve, reject) => {
let connection;
pool.getConnection()
.then(conn => {
connection = conn;
// Ensure a migrations table exists to track applied migrations
return connection.query(`CREATE TABLE IF NOT EXISTS migrations (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);`);
})
.then(() => {
// Read all migration files
const migrationDir = path.join(__dirname, 'migrations');
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 connection.query(
'SELECT 1 FROM migrations WHERE name = ? LIMIT 1',
[migrationName]
).then(([rows]) => {
if (Object.keys(rows || {}).length > 0) {
//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 connection.query(sql).then(() => {
// Record the applied migration
return connection.query(
'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.errorr('Error running migrations:', err);
reject(err);
})
.finally(() => {
if (connection) connection.release();
});
});
}
module.exports = runMigrations