/** * 批量更新生产数据库 stock_warehouse.gross_weight * * 用法: * node ./script/update-stock-warehouse-weight.cjs [--dry-run] [--file stocksWeight.txt] * * 文件格式(每行一条,tab 分隔): * * * 选项: * --dry-run 仅预览,不实际执行 UPDATE * --file 指定数据文件路径,默认 ./stocksWeight.txt */ const fs = require('fs'); const path = require('path'); const readline = require('readline'); // ─── 解析命令行参数 ─────────────────────────────────────────── const args = process.argv.slice(2); const dryRun = args.includes('--dry-run'); const fileIndex = args.indexOf('--file'); const dataFile = fileIndex !== -1 ? args[fileIndex + 1] : path.join(__dirname, '..', 'stocksWeight.txt'); // ─── 加载数据库配置(复用 database/config.js 的生产环境路由逻辑) ── function loadDbConfig() { const projectRoot = path.resolve(__dirname, '..'); // 加载默认配置 const defaultConfigPath = path.join(projectRoot, 'config', 'config.default.js'); const defaultConfigFactory = require(defaultConfigPath); const defaultConfig = typeof defaultConfigFactory === 'function' ? defaultConfigFactory({ name: 'update-stock-weight', baseDir: projectRoot }) : defaultConfigFactory; // 生产环境使用 config.default.js 中的 sequelize 配置 const sequelizeConfig = defaultConfig && defaultConfig.sequelize; if (sequelizeConfig && sequelizeConfig.host) { return { host: sequelizeConfig.host, port: Number(sequelizeConfig.port || 3306), user: sequelizeConfig.username, password: sequelizeConfig.password, database: sequelizeConfig.database || 'wms', }; } // 兜底:使用 mysql.clients.wms const mysqlClient = defaultConfig && defaultConfig.mysql && defaultConfig.mysql.clients && defaultConfig.mysql.clients.wms; if (mysqlClient) { return { host: mysqlClient.host, port: Number(mysqlClient.port || 3306), user: mysqlClient.user, password: mysqlClient.password, database: mysqlClient.database, }; } throw new Error('无法解析生产数据库配置'); } // ─── 解析数据文件 ────────────────────────────────────────────── async function parseDataFile(filePath) { const records = []; const errors = []; if (!fs.existsSync(filePath)) { throw new Error(`数据文件不存在: ${filePath}`); } const fileStream = fs.createReadStream(filePath, 'utf8'); const rl = readline.createInterface({ input: fileStream, crlfDelay: Infinity }); let lineNo = 0; for await (const line of rl) { lineNo++; const trimmed = line.trim(); if (!trimmed) continue; // 跳过空行 const parts = trimmed.split(/\s+/); if (parts.length < 2) { errors.push(`第 ${lineNo} 行格式错误(需要 id 和 weight): "${trimmed}"`); continue; } const id = parseInt(parts[0], 10); const weight = parseFloat(parts[1]); if (isNaN(id) || id <= 0) { errors.push(`第 ${lineNo} 行 ID 无效: "${parts[0]}"`); continue; } if (isNaN(weight) || weight < 0) { errors.push(`第 ${lineNo} 行重量无效: "${parts[1]}"`); continue; } records.push({ id, weight }); } return { records, errors }; } // ─── 主流程 ──────────────────────────────────────────────────── (async () => { console.log('═══════════════════════════════════════════════'); console.log(' 生产数据库 - stock_warehouse 重量批量更新'); console.log('═══════════════════════════════════════════════'); console.log(` 数据文件: ${dataFile}`); console.log(` 模式: ${dryRun ? 'DRY-RUN(仅预览,不实际更新)' : '正式执行'}`); console.log(''); // 1. 解析数据文件 let records, errors; try { ({ records, errors } = await parseDataFile(dataFile)); } catch (e) { console.error(`[ERROR] 读取数据文件失败: ${e.message}`); process.exit(1); } if (errors.length > 0) { console.error(`[WARNING] 数据文件存在 ${errors.length} 行解析错误:`); errors.forEach(e => console.error(` - ${e}`)); if (records.length === 0) { console.error('[ERROR] 没有有效的记录可以处理,退出。'); process.exit(1); } console.error(` 将继续处理其余 ${records.length} 条有效记录。\n`); } console.log(` 共解析 ${records.length} 条有效记录。\n`); // 2. 连接数据库 const dbConfig = loadDbConfig(); console.log(`[DB] 生产环境 → ${dbConfig.host}:${dbConfig.port}/${dbConfig.database}`); console.log(''); const mysql = require('mysql2/promise'); const connection = await mysql.createConnection({ host: dbConfig.host, port: dbConfig.port, user: dbConfig.user, password: dbConfig.password, database: dbConfig.database, charset: 'utf8mb4', }); try { // 3. 预览:查询现有记录 const ids = records.map(r => r.id); console.log('[预览] 查询现有记录...'); const [existingRows] = await connection.query( `SELECT id, item_code, item_name, gross_weight FROM wms_stock_warehouse WHERE id IN (?) ORDER BY id`, [ids] ); const existingMap = new Map(); existingRows.forEach(row => { existingMap.set(row.id, row); }); const notFound = ids.filter(id => !existingMap.has(id)); if (notFound.length > 0) { console.error(`[WARNING] 以下 ${notFound.length} 个 ID 在 stock_warehouse 表中不存在:`); console.error(` ${notFound.join(', ')}`); console.error(''); } // 4. 显示变更预览 console.log('───────────────────────────────────────────────'); console.log(' 变更预览(前 30 条):'); console.log('───────────────────────────────────────────────'); console.log(' ID | 商品编码 | 商品名称 | 旧重量 → 新重量'); console.log(' ----------|---------------|-------------------------|----------------'); let displayCount = 0; const changes = []; for (const { id, weight } of records) { const existing = existingMap.get(id); if (existing) { const oldWeight = Number(existing.gross_weight) || 0; if (oldWeight !== weight) { changes.push({ id, weight, oldWeight, itemCode: existing.item_code, itemName: existing.item_name }); if (displayCount < 30) { const code = (existing.item_code || '').padEnd(13); const name = (existing.item_name || '').substring(0, 24).padEnd(24); console.log(` ${String(id).padEnd(10)}| ${code}| ${name}| ${oldWeight} → ${weight}`); displayCount++; } } } } if (changes.length > 30) { console.log(` ... 还有 ${changes.length - 30} 条变更,省略显示`); } console.log(''); const unchangedCount = records.length - changes.length - notFound.length; console.log(` 汇总: 共 ${records.length} 条记录`); console.log(` - 需要更新: ${changes.length} 条`); console.log(` - 无需变更: ${unchangedCount} 条`); console.log(` - ID 不存在: ${notFound.length} 条`); console.log(''); if (changes.length === 0) { console.log(' 没有需要更新的记录,退出。'); return; } // 5. dry-run 模式到此为止 if (dryRun) { console.log('[DRY-RUN] 预览完成,未执行任何 UPDATE。'); console.log(' 去掉 --dry-run 参数即可正式执行。'); return; } // 6. 确认执行 console.log('═══════════════════════════════════════════════'); console.log(' ⚠️ 即将在生产数据库执行 UPDATE 操作!'); console.log(` ⚠️ 将更新 ${changes.length} 条 stock_warehouse.gross_weight 记录`); console.log('═══════════════════════════════════════════════'); console.log(''); console.log(' 请在 10 秒内按 Ctrl+C 取消,或等待自动执行...'); // 倒计时 for (let i = 5; i > 0; i--) { process.stdout.write(` ${i}...`); await new Promise(resolve => setTimeout(resolve, 1000)); } console.log('\n'); // 7. 执行更新 console.log('[执行] 开始批量更新...'); let successCount = 0; let failCount = 0; const failures = []; for (const { id, weight } of changes) { try { await connection.query( 'UPDATE wms_stock_warehouse SET gross_weight = ? WHERE id = ?', [weight, id] ); successCount++; if (successCount % 50 === 0) { console.log(` 进度: ${successCount}/${changes.length} 条已更新`); } } catch (e) { failCount++; failures.push({ id, weight, error: e.message }); console.error(` [FAIL] id=${id}: ${e.message}`); } } // 8. 输出结果 console.log(''); console.log('═══════════════════════════════════════════════'); console.log(' 执行完成'); console.log('═══════════════════════════════════════════════'); console.log(` 成功: ${successCount} 条`); console.log(` 失败: ${failCount} 条`); if (failures.length > 0) { console.log(' 失败详情:'); failures.forEach(f => console.log(` id=${f.id}: ${f.error}`)); } console.log(''); } finally { await connection.end(); } })().catch(e => { console.error(`[FATAL] ${e.stack || e.message}`); process.exit(1); });