'use strict'; module.exports = { async up(queryInterface, Sequelize) { const { INTEGER, BIGINT, STRING, DATE, TINYINT } = Sequelize; // 先检查表是否存在,避免重复创建 const [ tables ] = await queryInterface.sequelize.query( "SHOW TABLES LIKE 'wms_account_login_log'" ); if (tables.length > 0) { console.log('Table wms_account_login_log already exists, skipping creation'); return; } await queryInterface.createTable('wms_account_login_log', { id: { type: INTEGER(11), primaryKey: true, autoIncrement: true, allowNull: false, comment: '日志ID', }, user_id: { type: BIGINT(20), allowNull: false, references: { model: 'wms_account', key: 'id', }, onUpdate: 'CASCADE', onDelete: 'NO ACTION', comment: '用户ID', }, login_ip: { type: STRING(50), allowNull: false, comment: '登录IP', }, user_agent: { type: STRING(500), allowNull: false, comment: '用户代理', }, login_time: { type: DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), comment: '登录时间', }, success: { type: TINYINT(4), allowNull: false, defaultValue: 1, comment: '是否成功(0失败,1成功)', }, remark: { type: STRING(200), allowNull: true, comment: '备注', }, }, { engine: 'InnoDB', charset: 'utf8mb4', collate: 'utf8mb4_general_ci', comment: 'WMS账户登录日志表', }); // 安全创建索引的函数 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_account_login_log', [ 'user_id' ], { name: 'idx_user_id', }); await safeCreateIndex('wms_account_login_log', [ 'login_time' ], { name: 'idx_login_time', }); await safeCreateIndex('wms_account_login_log', [ 'success' ], { name: 'idx_success', }); await safeCreateIndex('wms_account_login_log', [ 'login_ip' ], { name: 'idx_login_ip', }); // 添加复合索引用于常用查询 await safeCreateIndex('wms_account_login_log', [ 'user_id', 'login_time' ], { name: 'idx_user_login_time', }); }, async down(queryInterface, Sequelize) { // 安全删除表 const [ tables ] = await queryInterface.sequelize.query( "SHOW TABLES LIKE 'wms_account_login_log'" ); if (tables.length > 0) { await queryInterface.dropTable('wms_account_login_log'); } }, };