const path = require('path'); const fs = require('fs'); const SequelizeLib = require('sequelize'); (async () => { const migrationName = '20260507100000-create-wms_order_wave_strategy_match.js'; const migrationPath = path.join(__dirname, '..', 'database', 'migrations', migrationName); if (!fs.existsSync(migrationPath)) { console.error('ERROR: migration file not found:', migrationPath); process.exitCode = 2; return; } const dbConfigFile = path.join(__dirname, '..', 'database', 'config.js'); let dbConfig; try { dbConfig = require(dbConfigFile); } catch (e) { console.error('ERROR: failed to load database config:', e.message); process.exitCode = 2; return; } const config = dbConfig.production; const sequelize = new SequelizeLib(config.database, config.username, config.password, { host: config.host, port: config.port, dialect: config.dialect || 'mysql', logging: false, define: config.define, pool: config.pool, }); const queryInterface = sequelize.getQueryInterface(); try { await sequelize.authenticate(); } catch (e) { console.error('ERROR: DB connection failed:', e.message); process.exitCode = 2; return; } // list migration files on disk const migrationsDir = path.join(__dirname, '..', 'database', 'migrations'); const migrationFiles = fs.readdirSync(migrationsDir).filter(f => f.endsWith('.js')).sort(); // ensure SequelizeMeta exists let tables = await queryInterface.showAllTables(); const normalizeTable = t => (typeof t === 'string' ? t : (t.tableName || t.name || '')).toLowerCase(); const tablesLower = tables.map(normalizeTable); if (!tablesLower.includes('sequelizemeta')) { await queryInterface.createTable('SequelizeMeta', { name: { type: SequelizeLib.STRING, allowNull: false, primaryKey: true } }); } // read applied migrations const appliedRows = await sequelize.query('SELECT name FROM SequelizeMeta', { type: SequelizeLib.QueryTypes.SELECT }); const appliedNames = appliedRows.map(r => (typeof r === 'string' ? r : r.name)).filter(Boolean); // detect pending migrations (not yet recorded) const pending = migrationFiles.filter(f => !appliedNames.includes(f)); const earlierPending = pending.filter(f => f < migrationName); if (earlierPending.length > 0) { console.error('ERROR: 存在早于目标迁移的 pending migration,拒绝单独执行。'); console.error('Pending earlier migrations:\n' + earlierPending.join('\n')); process.exitCode = 3; return; } if (appliedNames.includes(migrationName)) { console.log('INFO: 迁移已记录在 SequelizeMeta,跳过执行。'); } else { // run single migration up const migration = require(migrationPath); try { await migration.up(queryInterface, SequelizeLib); } catch (e) { console.error('ERROR: migration.up 执行失败:', e && e.message ? e.message : e); // attempt to collect state for rollback advice try { const tablesAfter = await queryInterface.showAllTables(); if (tablesAfter.map(normalizeTable).includes('wms_order_wave_strategy_match')) { console.error('STATE: 表 wms_order_wave_strategy_match 已存在(可能部分创建)。'); } } catch (e2) { // ignore } process.exitCode = 4; return; } // record migration in SequelizeMeta try { await sequelize.query('INSERT INTO SequelizeMeta(name) VALUES(?)', { replacements: [migrationName] }); } catch (e) { console.error('ERROR: 无法在 SequelizeMeta 中记录迁移:', e && e.message ? e.message : e); process.exitCode = 5; return; } console.log('INFO: migration 执行并记录完成。'); } // 验证:表存在、字段、索引、SequelizeMeta const result = { migrationRecorded: false, tableExists: false, columns: {}, indexes: {}, }; // migration recorded? const checkRow = await sequelize.query('SELECT name FROM SequelizeMeta WHERE name = ?', { replacements: [migrationName], type: SequelizeLib.QueryTypes.SELECT }); result.migrationRecorded = (checkRow && checkRow.length > 0); // table exists? tables = await queryInterface.showAllTables(); result.tableExists = tables.map(normalizeTable).includes('wms_order_wave_strategy_match'); if (result.tableExists) { const desc = await queryInterface.describeTable('wms_order_wave_strategy_match'); const needed = ['id', 'warehouse_id', 'order_id', 'strategy_id', 'create_time']; for (const col of needed) { result.columns[col] = !!desc[col]; if (desc[col]) { result.columns[col + '_meta'] = { type: desc[col].type, allowNull: desc[col].allowNull, defaultValue: desc[col].defaultValue, primaryKey: !!desc[col].primaryKey || !!desc[col].primary_key || false, autoIncrement: !!desc[col].autoIncrement || !!desc[col].auto_increment || false, }; } } const indexes = await queryInterface.showIndex('wms_order_wave_strategy_match'); const idxNames = (indexes || []).map(i => i.name); result.indexes.idx_warehouse_order = idxNames.includes('idx_warehouse_order'); result.indexes.idx_warehouse_strategy = idxNames.includes('idx_warehouse_strategy'); // further check fields for each index for (const idx of (indexes || [])) { if (idx.name === 'idx_warehouse_order') { result.indexes.idx_warehouse_order_fields = (idx.fields || []).map(f => f.attribute || f.field || f.column); } if (idx.name === 'idx_warehouse_strategy') { result.indexes.idx_warehouse_strategy_fields = (idx.fields || []).map(f => f.attribute || f.field || f.column); } } } console.log('\n=== VERIFICATION RESULT ==='); console.log(JSON.stringify(result, null, 2)); // close await sequelize.close(); process.exitCode = 0; })();