68 lines
2.5 KiB
JavaScript
68 lines
2.5 KiB
JavaScript
const { sequelize, setupRelationships, syncDatabase } = require('../models');
|
|
|
|
/**
|
|
* Script to sync all Sequelize models to database
|
|
* This will create all tables with proper foreign keys and indexes
|
|
*/
|
|
async function syncAllTables() {
|
|
try {
|
|
console.log('🚀 Starting database synchronization...\n');
|
|
|
|
// Setup model relationships first
|
|
setupRelationships();
|
|
console.log('✅ Model relationships configured\n');
|
|
|
|
// Test database connection
|
|
await sequelize.authenticate();
|
|
console.log('✅ Database connection established\n');
|
|
|
|
// Show current tables
|
|
const [tablesBefore] = await sequelize.query(`
|
|
SELECT TABLE_NAME
|
|
FROM information_schema.TABLES
|
|
WHERE TABLE_SCHEMA = DATABASE()
|
|
ORDER BY TABLE_NAME;
|
|
`);
|
|
console.log('📊 Tables before sync:', tablesBefore.length);
|
|
console.log(tablesBefore.map(t => t.TABLE_NAME).join(', '), '\n');
|
|
|
|
// Sync database (force: false = don't drop existing tables)
|
|
// Use { alter: true } to modify existing tables without dropping data
|
|
// Use { force: true } to drop and recreate all tables (CAREFUL: data loss!)
|
|
console.log('⚙️ Syncing database with alter mode...');
|
|
await syncDatabase({ alter: true });
|
|
|
|
// Show tables after sync
|
|
const [tablesAfter] = await sequelize.query(`
|
|
SELECT TABLE_NAME
|
|
FROM information_schema.TABLES
|
|
WHERE TABLE_SCHEMA = DATABASE()
|
|
ORDER BY TABLE_NAME;
|
|
`);
|
|
console.log('\n📊 Tables after sync:', tablesAfter.length);
|
|
console.log(tablesAfter.map(t => t.TABLE_NAME).join(', '), '\n');
|
|
|
|
// Show newly created tables
|
|
const newTables = tablesAfter.filter(
|
|
t => !tablesBefore.some(b => b.TABLE_NAME === t.TABLE_NAME)
|
|
);
|
|
if (newTables.length > 0) {
|
|
console.log('✨ Newly created tables:', newTables.length);
|
|
console.log(newTables.map(t => t.TABLE_NAME).join(', '), '\n');
|
|
}
|
|
|
|
console.log('╔════════════════════════════════════════════════════════╗');
|
|
console.log('║ ✅ DATABASE SYNC COMPLETED SUCCESSFULLY ║');
|
|
console.log('╚════════════════════════════════════════════════════════╝');
|
|
|
|
process.exit(0);
|
|
} catch (error) {
|
|
console.error('\n❌ Database sync failed:');
|
|
console.error(error);
|
|
process.exit(1);
|
|
}
|
|
}
|
|
|
|
// Run sync
|
|
syncAllTables();
|