183 lines
7.1 KiB
JavaScript
183 lines
7.1 KiB
JavaScript
const path = require('path');
|
||
const fs = require('fs');
|
||
const SequelizeLib = require('sequelize');
|
||
|
||
/**
|
||
* 单条迁移执行主流程:加载数据库配置、执行迁移并验证结果,支持 --dry-run 预览。
|
||
* @return {Promise<void>} 无返回值,通过 process.exitCode 表达执行结果。
|
||
*/
|
||
async function main() {
|
||
const args = process.argv.slice(2);
|
||
const dryRun = args.includes('--dry-run');
|
||
const migrationName = args.find(arg => !arg.startsWith('--')) || process.env.MIGRATION_NAME;
|
||
if (!migrationName) {
|
||
console.error('ERROR: 必须通过命令行参数或环境变量 MIGRATION_NAME 传入迁移文件名。');
|
||
console.error('USAGE: node ./script/run-single-migration.cjs 20260523130000-add-cainiao-to-wms-express.js');
|
||
process.exitCode = 2;
|
||
return;
|
||
}
|
||
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 targetMeta = dbConfig.dbTarget || { target: 'unknown', source: 'unknown' };
|
||
console.log(`[RUN-MIGRATION] 连接目标: host=${config.host} port=${config.port} database=${config.database} (判定来源: ${targetMeta.source})`);
|
||
if (targetMeta.target === 'production') {
|
||
console.warn('[RUN-MIGRATION] ⚠ 目标为生产库,请确认后再执行;如属误判请设置 WMS_DB_TARGET=local 后重试。');
|
||
}
|
||
if (dryRun) {
|
||
console.log('[RUN-MIGRATION] DRY-RUN 模式:仅展示执行计划,不连接数据库、不执行任何 DDL。');
|
||
console.log(`[RUN-MIGRATION] 计划执行迁移文件: ${migrationName}`);
|
||
console.log(`[RUN-MIGRATION] 目标库: ${config.host}:${config.port}/${config.database}`);
|
||
return;
|
||
}
|
||
|
||
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;
|
||
}
|
||
|
||
main();
|