/** * 数据库初始化脚本 * @file init-db.js * @description 初始化数据库结构和基础数据 */ const { sequelize, syncModels } = require('../models'); const { User, Role, UserRole } = require('../models'); const bcrypt = require('bcrypt'); const migrationManager = require('./migration-manager'); const seedManager = require('./seed-manager'); async function initDb() { try { console.log('开始初始化数据库...'); // 测试数据库连接 await sequelize.authenticate(); console.log('数据库连接成功'); // 创建迁移表 await migrationManager.createMigrationTable(); console.log('迁移表创建成功'); // 创建种子表 await seedManager.createSeedTable(); console.log('种子表创建成功'); // 运行待处理的迁移 await migrationManager.runPendingMigrations(); console.log('迁移完成'); // 运行种子数据 await seedManager.runAllSeeds(); console.log('种子数据应用完成'); // 同步模型(确保所有模型都已同步到数据库) await syncModels({ alter: true }); console.log('模型同步完成'); // 检查是否有管理员用户 const adminUser = await User.findOne({ where: { username: 'admin' } }); // 如果有管理员用户,检查密码是否为123456的哈希值 if (adminUser) { // 检查密码是否为123456的哈希值 const isCorrectPassword = await adminUser.validPassword('123456'); // 如果密码不是123456的哈希值,则更新密码 if (!isCorrectPassword) { adminUser.password = await bcrypt.hash('123456', 10); await adminUser.save(); console.log('管理员密码已重置为123456'); } else { console.log('管理员密码已是123456'); } // 确保管理员有admin角色 const adminRole = await Role.findOne({ where: { name: 'admin' } }); if (adminRole) { const hasAdminRole = await adminUser.hasRole('admin'); if (!hasAdminRole) { await adminUser.assignRole(adminRole.id); console.log('已为管理员分配admin角色'); } else { console.log('管理员已有admin角色'); } } } else { // 如果没有管理员用户,则创建一个 const newAdmin = await User.create({ username: 'admin', email: 'admin@example.com', password: await bcrypt.hash('123456', 10) }); console.log('管理员用户已创建,用户名: admin,密码: 123456'); // 为新管理员分配admin角色 const adminRole = await Role.findOne({ where: { name: 'admin' } }); if (adminRole) { await newAdmin.assignRole(adminRole.id); console.log('已为新管理员分配admin角色'); } } console.log('数据库初始化完成'); // 关闭数据库连接 await sequelize.close(); console.log('数据库连接已关闭'); process.exit(0); } catch (error) { console.error('数据库初始化失败:', error); // 尝试关闭数据库连接 try { await sequelize.close(); console.log('数据库连接已关闭'); } catch (closeError) { console.error('关闭数据库连接失败:', closeError); } process.exit(1); } } // 如果直接运行此脚本,则执行初始化 if (require.main === module) { initDb(); } module.exports = initDb;