'use strict'; const ORDER_ITEM_SN_TABLE = 'wms_order_item_sn'; const ORDER_ITEM_SN_LOG_TABLE = 'wms_order_item_sn_log'; /** SN 编码目标长度:支持以链接/二维码内容作为 SN,同时保证 (warehouse_id, sn_code) 唯一索引不超过 3072 字节 */ const TARGET_SN_CODE_LENGTH = 512; /** * 读取列当前定义的字符长度。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @param {string} tableName 表名。 * @param {string} columnName 列名。 * @return {Promise} 当前字符长度,取不到时返回 0。 */ const getColumnLength = async (queryInterface, tableName, columnName) => { const tableDefinition = await queryInterface.describeTable(tableName); const column = tableDefinition[columnName]; if (!column) { return 0; } const length = Number(column.character_maximum_length || column.maxLength || 0); return Number.isFinite(length) ? length : 0; }; module.exports = { /** * 把 SN 编码列扩充到 512 字符(支持链接/二维码内容作为 SN 码)。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @param {import('sequelize')} Sequelize Sequelize 实例。 * @return {Promise} 无返回值。 */ async up(queryInterface, Sequelize) { const existingTables = new Set((await queryInterface.showAllTables()).map(table => ( typeof table === 'string' ? table : (table.tableName || table.name || '') ).toLowerCase())); for (const tableName of [ ORDER_ITEM_SN_TABLE, ORDER_ITEM_SN_LOG_TABLE ]) { if (!existingTables.has(tableName)) { continue; } const currentLength = await getColumnLength(queryInterface, tableName, 'sn_code'); if (currentLength >= TARGET_SN_CODE_LENGTH) { continue; } await queryInterface.changeColumn(tableName, 'sn_code', { type: Sequelize.STRING(TARGET_SN_CODE_LENGTH), allowNull: false, comment: 'SN编码(支持链接/二维码内容,最长512字符)', }); } }, /** * 回滚为 128 字符(超长数据会失败,需先清理)。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @param {import('sequelize')} Sequelize Sequelize 实例。 * @return {Promise} 无返回值。 */ async down(queryInterface, Sequelize) { for (const tableName of [ ORDER_ITEM_SN_TABLE, ORDER_ITEM_SN_LOG_TABLE ]) { await queryInterface.changeColumn(tableName, 'sn_code', { type: Sequelize.STRING(128), allowNull: false, comment: 'SN编码', }); } }, };