'use strict'; /** * 订单表 from_key 由 INTEGER(11) 改为 VARCHAR(100),用于承载上游对接应用的 appKey。 * * 背景:from_key 是「回原通道」的应用标识(出库单回传、取号业务分支都依赖它), * 历史上只存过奇门/ERP 的纯数字 appKey(如聚水潭 23060081、吉客云 24869601)。 * OpenAPI 创建来源的 appKey 是字符串(wms_api_app.self_app_key,如 * WMSD08A3696BBA9551F261C88BBF7F462BD),INTEGER 列无法承载, * 导致 API 渠道订单 from_key 全部落空。 * * 落库口径(统一为“上游对接应用 appKey”): * - QM :wms_qimen_apps.app_key * - API :wms_api_app.self_app_key * - MANUAL / STOCKOUT:NULL * * 覆盖范围:基表 wms_order_delivery + 全部分表 * (wms_order_delivery_{wh} 及 _{wh}_history / _{wh}_dispatch / _{wh}_outsourced)。 * * 注意:INTEGER → VARCHAR 在 MySQL 中需要重建表,重建会把 AUTO_INCREMENT * 重置为 MAX(id)+1。若原水位更高(曾删除数据),会与其它分表 id 区间重叠产生 * 主键冲突,因此每张表改列后都要恢复原 AUTO_INCREMENT 水位。 * * 幂等:列已是字符类型则跳过。 */ const BASE_TABLE = 'wms_order_delivery'; const SHARD_PATTERN = /^wms_order_delivery_(\d+)(?:_(history|dispatch|outsourced))?$/; const COLUMN_NAME = 'from_key'; const COLUMN_COMMENT = '来源键(上游对接应用 appKey:QM=wms_qimen_apps.app_key,API=wms_api_app.self_app_key)'; /** * 列举库内全部订单分表。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @return {Promise} 分表名列表。 */ async function listOrderShards(queryInterface) { const [ rows ] = await queryInterface.sequelize.query( 'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES ' + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE \'wms_order_delivery\\_%\' ' + 'ORDER BY TABLE_NAME' ); return (rows || []) .map(row => String(row.tableName || row.TABLE_NAME || '')) .filter(name => SHARD_PATTERN.test(name)); } /** * 判断表是否存在。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @param {string} tableName 表名。 * @return {Promise} 是否存在。 */ async function tableExists(queryInterface, tableName) { const [ rows ] = await queryInterface.sequelize.query( 'SELECT COUNT(*) AS total FROM INFORMATION_SCHEMA.TABLES ' + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?', { replacements: [ tableName ] } ); return Number(rows && rows[0] && rows[0].total || 0) > 0; } /** * 读取列当前类型。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @param {string} tableName 表名。 * @param {string} columnName 列名。 * @return {Promise} 类型字符串,列不存在返回 null。 */ async function getColumnType(queryInterface, tableName, columnName) { const described = await queryInterface.describeTable(tableName); const column = described && described[columnName]; return column ? String(column.type || '') : null; } /** * 判断类型是否为字符类型。 * @param {string} type 类型字符串。 * @return {boolean} 是否字符类型。 */ function isStringType(type) { return /char|text/i.test(String(type || '')); } /** * 读取表当前 AUTO_INCREMENT 水位。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @param {string} tableName 表名。 * @return {Promise} 水位,无自增主键返回 null。 */ async function getAutoIncrement(queryInterface, tableName) { const [ rows ] = await queryInterface.sequelize.query( 'SELECT AUTO_INCREMENT AS autoIncrement FROM INFORMATION_SCHEMA.TABLES ' + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?', { replacements: [ tableName ] } ); const value = rows && rows[0] && rows[0].autoIncrement; return value === null || value === undefined ? null : Number(value); } /** * 重建表后若自增水位被重置为更低值则恢复,避免与其它分表 id 重叠。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @param {string} tableName 表名。 * @param {number|null} previousAutoIncrement 改列前的水位。 * @return {Promise} 是否执行了恢复。 */ async function restoreAutoIncrement(queryInterface, tableName, previousAutoIncrement) { if (previousAutoIncrement === null) { return false; } const currentAutoIncrement = await getAutoIncrement(queryInterface, tableName); if (currentAutoIncrement === null || currentAutoIncrement >= previousAutoIncrement) { return false; } await queryInterface.sequelize.query( `ALTER TABLE \`${tableName}\` AUTO_INCREMENT = ${previousAutoIncrement}` ); return true; } module.exports = { /** * 执行迁移:把 from_key 改为 VARCHAR(100)。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @param {import('sequelize')} Sequelize Sequelize 构造器。 * @return {Promise} 无返回值。 */ async up(queryInterface, Sequelize) { const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ]; const results = []; for (const tableName of tables) { if (!await tableExists(queryInterface, tableName)) { results.push({ tableName, action: 'skip', reason: 'table_missing' }); continue; } const currentType = await getColumnType(queryInterface, tableName, COLUMN_NAME); if (currentType === null) { results.push({ tableName, action: 'skip', reason: 'column_missing' }); continue; } if (isStringType(currentType)) { results.push({ tableName, action: 'skip', reason: 'already_string', currentType }); continue; } const previousAutoIncrement = await getAutoIncrement(queryInterface, tableName); await queryInterface.changeColumn(tableName, COLUMN_NAME, { type: Sequelize.STRING(100), allowNull: true, defaultValue: null, comment: COLUMN_COMMENT, }); const autoIncrementRestored = await restoreAutoIncrement(queryInterface, tableName, previousAutoIncrement); results.push({ tableName, action: 'altered', from: currentType, autoIncrementRestored }); } console.log('[20261104100000-alter-order-delivery-from-key-to-varchar] up results:', JSON.stringify(results)); }, /** * 回滚迁移:把 from_key 改回 INTEGER(11)。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @param {import('sequelize')} Sequelize Sequelize 构造器。 * @return {Promise} 无返回值。 */ async down(queryInterface, Sequelize) { const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ]; const results = []; for (const tableName of tables) { if (!await tableExists(queryInterface, tableName)) { results.push({ tableName, action: 'skip', reason: 'table_missing' }); continue; } const currentType = await getColumnType(queryInterface, tableName, COLUMN_NAME); if (currentType === null) { results.push({ tableName, action: 'skip', reason: 'column_missing' }); continue; } if (!isStringType(currentType)) { results.push({ tableName, action: 'skip', reason: 'already_integer', currentType }); continue; } // 字符串 appKey 无法回滚进 INTEGER 列,先阻断避免截断成 0 造成脏数据 const [ incompatibleRows ] = await queryInterface.sequelize.query( `SELECT COUNT(*) AS total FROM \`${tableName}\` ` + `WHERE ${COLUMN_NAME} IS NOT NULL AND ${COLUMN_NAME} <> '' ` + `AND ${COLUMN_NAME} NOT REGEXP '^-?[0-9]+$'` ); const incompatibleCount = Number(incompatibleRows && incompatibleRows[0] && incompatibleRows[0].total || 0); if (incompatibleCount > 0) { results.push({ tableName, action: 'skip', reason: 'non_numeric_data', incompatibleCount }); continue; } const previousAutoIncrement = await getAutoIncrement(queryInterface, tableName); await queryInterface.changeColumn(tableName, COLUMN_NAME, { type: Sequelize.INTEGER(11), allowNull: true, defaultValue: null, comment: '来源键', }); const autoIncrementRestored = await restoreAutoIncrement(queryInterface, tableName, previousAutoIncrement); results.push({ tableName, action: 'reverted', autoIncrementRestored }); } console.log('[20261104100000-alter-order-delivery-from-key-to-varchar] down results:', JSON.stringify(results)); }, };