'use strict'; const fs = require('node:fs'); const path = require('node:path'); /** * 判断值是否为普通对象(非数组、非 null)。 * @param {*} value 待判断的值。 * @return {boolean} 是普通对象返回 true。 */ function isPlainObject(value) { return !!value && typeof value === 'object' && !Array.isArray(value); } /** * 深合并两个普通对象,返回新对象,不修改入参。 * @param {object} target 目标对象。 * @param {object} source 来源对象。 * @return {object} 合并后的新对象。 */ function mergeDeep(target, source) { const output = isPlainObject(target) ? { ...target } : {}; if (!isPlainObject(source)) { return output; } for (const [ key, value ] of Object.entries(source)) { if (isPlainObject(value) && isPlainObject(output[key])) { output[key] = mergeDeep(output[key], value); } else if (isPlainObject(value)) { output[key] = mergeDeep({}, value); } else { output[key] = value; } } return output; } /** * 加载 Egg 配置文件,兼容工厂函数与普通对象两种形式。 * @param {string} configPath 配置文件绝对路径。 * @return {object} 解析后的配置对象,文件不存在时返回空对象。 */ function loadEggConfig(configPath) { if (!fs.existsSync(configPath)) { return {}; } const configFactory = require(configPath); const config = typeof configFactory === 'function' ? configFactory({ name: 'sequelize-cli', baseDir: path.dirname(path.dirname(configPath)) }) : configFactory; return isPlainObject(config) ? config : {}; } /** * 从 Egg 配置中解析指定名称的 MySQL 客户端。 * @param {object} appConfig Egg 应用配置。 * @param {string} clientName MySQL 客户端名称。 * @return {object} 解析出的 MySQL 客户端连接配置。 * @throws {Error} 找不到指定客户端时抛出异常。 */ function resolveMysqlClient(appConfig, clientName) { const clients = appConfig && appConfig.mysql && appConfig.mysql.clients; if (clients && clients[clientName]) { return clients[clientName]; } if (appConfig && appConfig.mysql && appConfig.mysql.host) { return appConfig.mysql; } throw new Error(`MySQL client "${clientName}" not found in Egg config.`); } /** * 解析数据库连接目标标记,防止 NODE_ENV 残留导致误连生产库。 * 优先级:WMS_DB_TARGET(显式标记) > NODE_ENV(兜底判断)。 * @param {string | undefined} envTarget 显式目标标记(WMS_DB_TARGET 环境变量值)。 * @param {string | undefined} nodeEnv NODE_ENV 环境变量值。 * @return {{ target: string, source: string, explicit: boolean }} 解析结果:target 为 'production' 或 'local',source 为判定来源,explicit 表示是否显式指定。 */ function resolveDbTarget(envTarget, nodeEnv) { const explicit = String(envTarget || '').trim().toLowerCase(); if (explicit === 'production' || explicit === 'prod') { return { target: 'production', source: 'WMS_DB_TARGET', explicit: true }; } if (explicit === 'local' || explicit === 'dev' || explicit === 'development') { return { target: 'local', source: 'WMS_DB_TARGET', explicit: true }; } if (explicit) { console.warn(`[DB-CONFIG] 未知的 WMS_DB_TARGET="${explicit}",已忽略并回退到 NODE_ENV 判断;可选值:local | production`); } const nodeEnvLower = String(nodeEnv || '').trim().toLowerCase(); return { target: nodeEnvLower === 'production' ? 'production' : 'local', source: nodeEnvLower === 'production' ? 'NODE_ENV' : 'default', explicit: false, }; } /** * 打印数据库连接目标提示(输出到 stderr,避免污染 stdout 上的 JSON 结果)。 * production 目标额外打印醒目告警,提醒操作者确认连接目标。 * @param {{ host: string, port: (number|string), database: string }} client 解析后的 MySQL 连接配置。 * @param {{ target: string, source: string }} resolved 目标解析结果。 * @return {void} */ function printDbTargetNotice(client, resolved) { const detail = `host=${client.host} port=${client.port} database=${client.database} (判定来源: ${resolved.source})`; if (resolved.target === 'production') { console.warn(''); console.warn('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'); console.warn('[DB-CONFIG] ⚠ 警告:当前解析为【生产数据库】连接目标'); console.warn(`[DB-CONFIG] ⚠ ${detail}`); console.warn('[DB-CONFIG] ⚠ 请确认这是预期环境;如属误判,请设置 WMS_DB_TARGET=local 强制使用开发库配置。'); console.warn('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'); console.warn(''); } else { console.warn(`[DB-CONFIG] 数据库连接目标: ${detail}`); } } const projectRoot = path.resolve(__dirname, '..'); // 解析连接目标:显式标记 WMS_DB_TARGET 优先于 NODE_ENV 兜底判断, // 避免终端残留 NODE_ENV=production 导致迁移/脚本误连生产库 const dbTarget = resolveDbTarget(process.env.WMS_DB_TARGET, process.env.NODE_ENV); const isProductionTarget = dbTarget.target === 'production'; let mysqlClient; if (process.env.DB_HOST) { mysqlClient = { host: process.env.DB_HOST, port: process.env.DB_PORT || 3306, user: process.env.DB_USER, password: process.env.DB_PASSWORD, database: process.env.DB_NAME || 'wms', }; printDbTargetNotice(mysqlClient, { target: 'manual', source: 'DB_HOST' }); } else { const defaultConfig = loadEggConfig(path.join(projectRoot, 'config', 'config.default.js')); const localConfig = isProductionTarget ? {} : loadEggConfig(path.join(projectRoot, 'config', 'config.local.js')); const appConfig = mergeDeep(defaultConfig, localConfig); const clientName = process.env.SEQUELIZE_DB_CLIENT || 'wms'; if (isProductionTarget) { const sequelizeConfig = appConfig && appConfig.sequelize; if (sequelizeConfig && sequelizeConfig.host) { mysqlClient = { host: sequelizeConfig.host, port: sequelizeConfig.port || 3306, user: sequelizeConfig.username || sequelizeConfig.user, password: sequelizeConfig.password, database: sequelizeConfig.database || 'wms', }; } else { mysqlClient = resolveMysqlClient(appConfig, clientName); } } else { mysqlClient = resolveMysqlClient(appConfig, clientName); } printDbTargetNotice(mysqlClient, dbTarget); } const baseConfig = { username: mysqlClient.user, password: mysqlClient.password, database: mysqlClient.database, host: mysqlClient.host, port: Number(mysqlClient.port || 3306), dialect: 'mysql', logging: false, define: { freezeTableName: true, underscored: true, timestamps: true, paranoid: true, deletedAt: 'deleted_at', }, }; module.exports = { development: { ...baseConfig }, test: { ...baseConfig }, production: { ...baseConfig }, // 解析出的连接目标元信息,供迁移脚本等调用方做断言与提示(不影响 sequelize-cli 读取 env 配置) dbTarget, };