118 lines
3.3 KiB
JavaScript
118 lines
3.3 KiB
JavaScript
const { Sequelize } = require('sequelize');
|
|
const path = require('path');
|
|
const fs = require('fs');
|
|
|
|
// Load environment variables
|
|
require('dotenv').config();
|
|
|
|
const runMigrations = async () => {
|
|
console.log('🔄 Starting database migrations...\n');
|
|
|
|
try {
|
|
// Create Sequelize instance
|
|
const sequelize = new Sequelize(
|
|
process.env.DB_NAME,
|
|
process.env.DB_USER,
|
|
process.env.DB_PASSWORD,
|
|
{
|
|
host: process.env.DB_HOST,
|
|
port: process.env.DB_PORT,
|
|
dialect: 'postgres',
|
|
logging: console.log,
|
|
}
|
|
);
|
|
|
|
// Test database connection
|
|
console.log('📡 Testing database connection...');
|
|
await sequelize.authenticate();
|
|
console.log('✅ Database connection established successfully.\n');
|
|
|
|
// Get migrations directory
|
|
const migrationsDir = path.join(__dirname, '../migrations');
|
|
|
|
if (!fs.existsSync(migrationsDir)) {
|
|
console.log('📁 No migrations directory found. Creating...');
|
|
fs.mkdirSync(migrationsDir, { recursive: true });
|
|
}
|
|
|
|
// Get all migration files
|
|
const migrationFiles = fs.readdirSync(migrationsDir)
|
|
.filter(file => file.endsWith('.js'))
|
|
.sort(); // Sort to ensure proper order
|
|
|
|
if (migrationFiles.length === 0) {
|
|
console.log('📝 No migration files found.');
|
|
return;
|
|
}
|
|
|
|
console.log(`📋 Found ${migrationFiles.length} migration files:`);
|
|
migrationFiles.forEach(file => console.log(` - ${file}`));
|
|
console.log('');
|
|
|
|
// Create migrations table if it doesn't exist
|
|
await sequelize.getQueryInterface().createTable('SequelizeMeta', {
|
|
name: {
|
|
type: Sequelize.STRING,
|
|
primaryKey: true,
|
|
allowNull: false
|
|
}
|
|
}).catch(() => {
|
|
// Table already exists, ignore error
|
|
});
|
|
|
|
// Get already executed migrations
|
|
const [executedMigrations] = await sequelize.query(
|
|
'SELECT name FROM "SequelizeMeta" ORDER BY name'
|
|
);
|
|
const executedNames = executedMigrations.map(row => row.name);
|
|
|
|
// Run pending migrations
|
|
for (const file of migrationFiles) {
|
|
const migrationName = file.replace('.js', '');
|
|
|
|
if (executedNames.includes(migrationName)) {
|
|
console.log(`⏭️ Skipping already executed migration: ${file}`);
|
|
continue;
|
|
}
|
|
|
|
console.log(`🚀 Running migration: ${file}`);
|
|
|
|
try {
|
|
// Load and execute migration
|
|
const migration = require(path.join(migrationsDir, file));
|
|
await migration.up(sequelize.getQueryInterface(), Sequelize);
|
|
|
|
// Record successful migration
|
|
await sequelize.query(
|
|
'INSERT INTO "SequelizeMeta" (name) VALUES (?)',
|
|
{
|
|
replacements: [migrationName],
|
|
type: Sequelize.QueryTypes.INSERT
|
|
}
|
|
);
|
|
|
|
console.log(`✅ Migration completed: ${file}\n`);
|
|
|
|
} catch (error) {
|
|
console.error(`❌ Migration failed: ${file}`);
|
|
console.error('Error:', error.message);
|
|
process.exit(1);
|
|
}
|
|
}
|
|
|
|
console.log('🎉 All migrations completed successfully!');
|
|
await sequelize.close();
|
|
|
|
} catch (error) {
|
|
console.error('❌ Migration process failed:', error);
|
|
process.exit(1);
|
|
}
|
|
};
|
|
|
|
// Run migrations if called directly
|
|
if (require.main === module) {
|
|
runMigrations();
|
|
}
|
|
|
|
module.exports = runMigrations;
|