'use strict'; const fs = require('node:fs'); const path = require('node:path'); const Sequelize = require('sequelize'); const ROOT = path.resolve(__dirname, '..'); const MIGRATIONS_DIR = path.join(ROOT, 'database', 'migrations'); async function main() { // 1. 收集本地所有迁移文件 const allFiles = fs.readdirSync(MIGRATIONS_DIR).filter(f => f.endsWith('.js')).sort(); console.log(`[本地] 迁移文件总数: ${allFiles.length}`); // 2. 连接生产数据库 const dbConfig = { host: '112.124.21.102', port: 3306, user: 'wms', password: 'P6j3YTHTpirepYWz', database: 'wms', }; const sequelize = new Sequelize(dbConfig.database, dbConfig.user, dbConfig.password, { host: dbConfig.host, port: dbConfig.port, dialect: 'mysql', logging: false, }); try { await sequelize.authenticate(); console.log('[DB] 生产数据库连接成功'); } catch (e) { console.error('[DB] 生产数据库连接失败:', e.message); process.exit(2); } // 3. 检查 SequelizeMeta 表是否存在 let appliedNames = []; try { const [rows] = await sequelize.query('SELECT name FROM SequelizeMeta ORDER BY name'); appliedNames = rows.map(r => (typeof r === 'string' ? r : r.name)).filter(Boolean); } catch (e) { console.error('[DB] 读取 SequelizeMeta 失败:', e.message); await sequelize.close(); process.exit(2); } console.log(`[DB] SequelizeMeta 已记录迁移数: ${appliedNames.length}`); // 4. 找出未执行的迁移 const appliedSet = new Set(appliedNames); const pending = allFiles.filter(f => !appliedSet.has(f)); const archived = allFiles.filter(f => f.startsWith('archive/')); console.log(`\n========== 结果汇总 ==========`); console.log(`本地迁移文件总数: ${allFiles.length}`); console.log(`已执行 (SequelizeMeta): ${appliedNames.length}`); console.log(`未执行 (pending): ${pending.length}`); console.log(`===============================\n`); if (pending.length === 0) { console.log('✅ 所有迁移脚本均已执行,无 pending migration。'); } else { console.log(`❌ 发现 ${pending.length} 个未执行的迁移脚本:\n`); pending.forEach((f, i) => { console.log(` ${String(i + 1).padStart(3, ' ')}. ${f}`); }); // 额外检查:有没有本地没有但 DB 已记录的(可能被删除了) const localSet = new Set(allFiles); const orphanInDb = appliedNames.filter(n => !localSet.has(n)); if (orphanInDb.length > 0) { console.log(`\n⚠️ DB 中记录了 ${orphanInDb.length} 个本地已不存在的迁移(可能已被删除):`); orphanInDb.forEach(n => console.log(` - ${n}`)); } } await sequelize.close(); console.log('\n[DONE] 检查完成'); } main().catch(err => { console.error('脚本执行异常:', err); process.exit(1); });