'use strict'; const TABLE_NAME = 'wms_order_express'; /** * 回填 wms_order_express.store_id。 * 从对应的仓库分表(current → history → dispatch)中获取 store_id。 * * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @return {Promise} 无返回值。 */ async function backfill(queryInterface) { // 获取所有不同的 warehouse_id const [ warehouses ] = await queryInterface.sequelize.query( `SELECT DISTINCT warehouse_id FROM ${TABLE_NAME} WHERE store_id IS NULL AND warehouse_id IS NOT NULL` ); if (!warehouses || warehouses.length === 0) { return; } for (const row of warehouses) { const warehouseId = row.warehouse_id; const tableTypes = [ `wms_order_delivery_${warehouseId}`, // current(配送表 / 待处理表) `wms_order_delivery_${warehouseId}_history`, // history `wms_order_delivery_${warehouseId}_dispatch`, // dispatch ]; for (const deliveryTable of tableTypes) { try { const [ result ] = await queryInterface.sequelize.query(` UPDATE ${TABLE_NAME} e INNER JOIN ${deliveryTable} d ON e.order_id = d.id AND e.warehouse_id = d.warehouse_id SET e.store_id = d.store_id WHERE e.store_id IS NULL AND d.store_id IS NOT NULL `); console.log(` warehouse=${warehouseId} table=${deliveryTable} rows=${result.info || result}`); } catch (err) { // 表可能不存在,跳过 if (err && err.parent && err.parent.code === 'ER_NO_SUCH_TABLE') { continue; } console.warn(` warehouse=${warehouseId} table=${deliveryTable} error=${err.message}`); } } } } module.exports = { /** * 执行迁移:回填 store_id。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @param {import('sequelize')} Sequelize Sequelize 实例。 * @return {Promise} 无返回值。 */ async up(queryInterface, Sequelize) { await backfill(queryInterface); }, /** * 回滚迁移:将 store_id 置为 NULL。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @param {import('sequelize')} Sequelize Sequelize 实例。 * @return {Promise} 无返回值。 */ async down(queryInterface, Sequelize) { await queryInterface.sequelize.query( `UPDATE ${TABLE_NAME} SET store_id = NULL` ); }, };