// database/migrations/20241201000010-create-wms-entry-items.js 'use strict'; module.exports = { async up(queryInterface, Sequelize) { const { BIGINT, STRING, INTEGER } = Sequelize; // 先检查表是否存在,避免重复创建 const [ tables ] = await queryInterface.sequelize.query( "SHOW TABLES LIKE 'wms_entry_items'" ); if (tables.length > 0) { console.log('Table wms_entry_items already exists, skipping creation'); return; } await queryInterface.createTable('wms_entry_items', { id: { type: BIGINT(20), primaryKey: true, autoIncrement: true, allowNull: false, comment: '入库单明细ID', }, order_id: { type: BIGINT(20), allowNull: false, references: { model: 'wms_entry_order', key: 'id', }, onUpdate: 'CASCADE', onDelete: 'NO ACTION', comment: '入库单ID', }, out_biz_code: { type: STRING(255), allowNull: true, comment: '外部业务编码', }, order_line_no: { type: INTEGER(12), allowNull: true, comment: '订单行号', }, owner_code: { type: STRING(50), allowNull: true, comment: '货主编码', }, item_code: { type: STRING(50), allowNull: true, comment: '商品编码', }, item_id: { type: BIGINT(20), allowNull: true, comment: '商品ID', }, count: { type: INTEGER(12), allowNull: true, comment: '数量', }, inventory_type: { type: STRING(255), allowNull: true, comment: '库存类型', }, stock_id: { type: BIGINT(20), allowNull: true, references: { model: 'wms_stock_warehouse', key: 'id', }, onUpdate: 'RESTRICT', onDelete: 'NO ACTION', comment: '库存ID', }, }, { engine: 'InnoDB', charset: 'utf8mb4', collate: 'utf8mb4_general_ci', comment: '入库单明细表', }); // 安全创建索引的函数 const safeCreateIndex = async (tableName, fields, options) => { const [ existingIndexes ] = await queryInterface.sequelize.query( `SHOW INDEX FROM ${tableName} WHERE Key_name = '${options.name}'` ); if (existingIndexes.length === 0) { await queryInterface.addIndex(tableName, fields, options); } }; // 添加唯一索引 await safeCreateIndex('wms_entry_items', [ 'order_id', 'out_biz_code' ], { name: 'uk_order_out_biz', unique: true, }); // 添加普通索引 await safeCreateIndex('wms_entry_items', [ 'stock_id' ], { name: 'idx_stock_id', }); await safeCreateIndex('wms_entry_items', [ 'order_id' ], { name: 'idx_order_id', }); await safeCreateIndex('wms_entry_items', [ 'item_code' ], { name: 'idx_item_code', }); await safeCreateIndex('wms_entry_items', [ 'item_id' ], { name: 'idx_item_id', }); await safeCreateIndex('wms_entry_items', [ 'owner_code' ], { name: 'idx_owner_code', }); await safeCreateIndex('wms_entry_items', [ 'order_line_no' ], { name: 'idx_order_line_no', }); // 添加复合索引 await safeCreateIndex('wms_entry_items', [ 'order_id', 'item_code' ], { name: 'idx_order_item', }); await safeCreateIndex('wms_entry_items', [ 'order_id', 'order_line_no' ], { name: 'idx_order_line', }); }, async down(queryInterface, Sequelize) { // 安全删除表 const [ tables ] = await queryInterface.sequelize.query( "SHOW TABLES LIKE 'wms_entry_items'" ); if (tables.length > 0) { await queryInterface.dropTable('wms_entry_items'); } }, };