UBS/migrations.js

85 lines
2.5 KiB
JavaScript

const mariadb = require('mariadb');
const fs = require('fs');
const path = require('path');
const util = require("util")
require("dotenv").config()
const log = require("./log");
// Create a MariaDB connection pool
const pool = mariadb.createPool({
host: process.env.DB_HOST, // Replace with your database host
port: process.env.DB_PORT || 3306,
user: process.env.DB_USER, // Replace with your database username
password: process.env.DB_PASS, // Replace with your database password
database: process.env.DB_DATABASE, // Replace with your database name
connectionLimit: 5 // Adjust connection limit as needed
});
function runMigrations() {
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) {
//log.info(`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(() => {
log.info(`Applied migration: ${migrationName}`);
});
});
});
});
}, Promise.resolve());
})
.then(() => {
log.info('All migrations applied successfully!');
resolve();
})
.catch(err => {
log.error('Error running migrations:', err);
reject(err);
})
.finally(() => {
if (connection) connection.release();
});
});
}
module.exports = runMigrations