chore(db): 数据库脚本连接目标保护(WMS_DB_TARGET 显式解析防误连生产库)
This commit is contained in:
parent
58cc5bb7b6
commit
373bb84294
@ -3,10 +3,21 @@
|
||||
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)) {
|
||||
@ -26,6 +37,11 @@ function mergeDeep(target, source) {
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载 Egg 配置文件,兼容工厂函数与普通对象两种形式。
|
||||
* @param {string} configPath 配置文件绝对路径。
|
||||
* @return {object} 解析后的配置对象,文件不存在时返回空对象。
|
||||
*/
|
||||
function loadEggConfig(configPath) {
|
||||
if (!fs.existsSync(configPath)) {
|
||||
return {};
|
||||
@ -39,6 +55,13 @@ function loadEggConfig(configPath) {
|
||||
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]) {
|
||||
@ -52,8 +75,62 @@ function resolveMysqlClient(appConfig, clientName) {
|
||||
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 = {
|
||||
@ -63,13 +140,13 @@ if (process.env.DB_HOST) {
|
||||
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 isProduction = process.env.NODE_ENV === 'production';
|
||||
const localConfig = isProduction ? {} : loadEggConfig(path.join(projectRoot, 'config', 'config.local.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 (isProduction) {
|
||||
if (isProductionTarget) {
|
||||
const sequelizeConfig = appConfig && appConfig.sequelize;
|
||||
if (sequelizeConfig && sequelizeConfig.host) {
|
||||
mysqlClient = {
|
||||
@ -85,6 +162,7 @@ if (process.env.DB_HOST) {
|
||||
} else {
|
||||
mysqlClient = resolveMysqlClient(appConfig, clientName);
|
||||
}
|
||||
printDbTargetNotice(mysqlClient, dbTarget);
|
||||
}
|
||||
|
||||
const baseConfig = {
|
||||
@ -108,4 +186,6 @@ module.exports = {
|
||||
development: { ...baseConfig },
|
||||
test: { ...baseConfig },
|
||||
production: { ...baseConfig },
|
||||
// 解析出的连接目标元信息,供迁移脚本等调用方做断言与提示(不影响 sequelize-cli 读取 env 配置)
|
||||
dbTarget,
|
||||
};
|
||||
|
||||
@ -1,4 +1,9 @@
|
||||
module.exports = {
|
||||
/**
|
||||
* ⚠ 生产数据库连接配置(仅用于 script/db-query.ps1 显式指定 -ConfigPath 时)。
|
||||
* 默认情况下 db-query.ps1 使用 config/config.local.js(开发库),
|
||||
* 只有显式传入本文件才会连接生产库,请确认后再使用。
|
||||
*/
|
||||
module.exports = {
|
||||
mysql: {
|
||||
clients: {
|
||||
wms: {
|
||||
|
||||
@ -63,6 +63,9 @@ const { createRequire } = require("module");
|
||||
const [rows] = await connection.query(query);
|
||||
const payload = JSON.stringify({
|
||||
client: clientName,
|
||||
host: client.host,
|
||||
port: client.port,
|
||||
database: client.database,
|
||||
rowCount: Array.isArray(rows) ? rows.length : 0,
|
||||
rows,
|
||||
});
|
||||
@ -105,6 +108,7 @@ try {
|
||||
Remove-Item -Path $jsonOutFile -ErrorAction SilentlyContinue
|
||||
}
|
||||
Write-Host "Client: $($result.client)"
|
||||
Write-Host "Target: $($result.host):$($result.port)/$($result.database)"
|
||||
Write-Host "Rows: $($result.rowCount)"
|
||||
|
||||
if ($AsTable) {
|
||||
|
||||
@ -2,8 +2,14 @@
|
||||
const fs = require('fs');
|
||||
const SequelizeLib = require('sequelize');
|
||||
|
||||
(async () => {
|
||||
const migrationName = process.argv[2] || process.env.MIGRATION_NAME;
|
||||
/**
|
||||
* 单条迁移执行主流程:加载数据库配置、执行迁移并验证结果,支持 --dry-run 预览。
|
||||
* @return {Promise<void>} 无返回值,通过 process.exitCode 表达执行结果。
|
||||
*/
|
||||
async function main() {
|
||||
const args = process.argv.slice(2);
|
||||
const dryRun = args.includes('--dry-run');
|
||||
const migrationName = args.find(arg => !arg.startsWith('--')) || process.env.MIGRATION_NAME;
|
||||
if (!migrationName) {
|
||||
console.error('ERROR: 必须通过命令行参数或环境变量 MIGRATION_NAME 传入迁移文件名。');
|
||||
console.error('USAGE: node ./script/run-single-migration.cjs 20260523130000-add-cainiao-to-wms-express.js');
|
||||
@ -28,6 +34,18 @@ const SequelizeLib = require('sequelize');
|
||||
}
|
||||
|
||||
const config = dbConfig.production;
|
||||
const targetMeta = dbConfig.dbTarget || { target: 'unknown', source: 'unknown' };
|
||||
console.log(`[RUN-MIGRATION] 连接目标: host=${config.host} port=${config.port} database=${config.database} (判定来源: ${targetMeta.source})`);
|
||||
if (targetMeta.target === 'production') {
|
||||
console.warn('[RUN-MIGRATION] ⚠ 目标为生产库,请确认后再执行;如属误判请设置 WMS_DB_TARGET=local 后重试。');
|
||||
}
|
||||
if (dryRun) {
|
||||
console.log('[RUN-MIGRATION] DRY-RUN 模式:仅展示执行计划,不连接数据库、不执行任何 DDL。');
|
||||
console.log(`[RUN-MIGRATION] 计划执行迁移文件: ${migrationName}`);
|
||||
console.log(`[RUN-MIGRATION] 目标库: ${config.host}:${config.port}/${config.database}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const sequelize = new SequelizeLib(config.database, config.username, config.password, {
|
||||
host: config.host,
|
||||
port: config.port,
|
||||
@ -97,7 +115,7 @@ const SequelizeLib = require('sequelize');
|
||||
|
||||
// record migration in SequelizeMeta
|
||||
try {
|
||||
await sequelize.query('INSERT INTO SequelizeMeta(name) VALUES(?)', { replacements: [migrationName] });
|
||||
await sequelize.query('INSERT INTO SequelizeMeta(name) VALUES(?)', { replacements: [ migrationName ] });
|
||||
} catch (e) {
|
||||
console.error('ERROR: 无法在 SequelizeMeta 中记录迁移:', e && e.message ? e.message : e);
|
||||
process.exitCode = 5;
|
||||
@ -115,7 +133,7 @@ const SequelizeLib = require('sequelize');
|
||||
};
|
||||
|
||||
// migration recorded?
|
||||
const checkRow = await sequelize.query('SELECT name FROM SequelizeMeta WHERE name = ?', { replacements: [migrationName], type: SequelizeLib.QueryTypes.SELECT });
|
||||
const checkRow = await sequelize.query('SELECT name FROM SequelizeMeta WHERE name = ?', { replacements: [ migrationName ], type: SequelizeLib.QueryTypes.SELECT });
|
||||
result.migrationRecorded = (checkRow && checkRow.length > 0);
|
||||
|
||||
// table exists?
|
||||
@ -124,7 +142,7 @@ const SequelizeLib = require('sequelize');
|
||||
|
||||
if (result.tableExists) {
|
||||
const desc = await queryInterface.describeTable('wms_order_wave_strategy_match');
|
||||
const needed = ['id', 'warehouse_id', 'order_id', 'strategy_id', 'create_time'];
|
||||
const needed = [ 'id', 'warehouse_id', 'order_id', 'strategy_id', 'create_time' ];
|
||||
for (const col of needed) {
|
||||
result.columns[col] = !!desc[col];
|
||||
if (desc[col]) {
|
||||
@ -159,4 +177,6 @@ const SequelizeLib = require('sequelize');
|
||||
// close
|
||||
await sequelize.close();
|
||||
process.exitCode = 0;
|
||||
})();
|
||||
}
|
||||
|
||||
main();
|
||||
|
||||
@ -77,7 +77,10 @@ function readJsonFile(filePath) {
|
||||
}
|
||||
|
||||
function detectIndent(raw) {
|
||||
const match = raw.match(/^([ \t]+)"[^"]+":/m);
|
||||
// 取第一个带缩进的值行(对象键、数组元素对象 `{` 或字符串元素)作为单层缩进;
|
||||
// 根为数组的文档(methods/changes/*.json)首行 `[` 后紧跟元素 `{`,
|
||||
// 避免把第二层缩进误判为单层缩进,导致全文件重排
|
||||
const match = raw.match(/^([ \t]+)[\[{"]/m);
|
||||
return match ? match[1] : ' ';
|
||||
}
|
||||
|
||||
@ -212,6 +215,15 @@ function validateSpec(spec, args) {
|
||||
methodNames.add(item.method);
|
||||
});
|
||||
|
||||
let deleteMethods = [];
|
||||
if (Object.prototype.hasOwnProperty.call(spec, 'deleteMethods')) {
|
||||
ensureStringArray(spec.deleteMethods, 'spec.deleteMethods');
|
||||
deleteMethods = spec.deleteMethods;
|
||||
}
|
||||
deleteMethods.forEach(item => {
|
||||
assert(!methodNames.has(item), `Method conflict: ${item} appears in both spec.methods and spec.deleteMethods.`);
|
||||
});
|
||||
|
||||
if (!args.docOnly) {
|
||||
validateChange(spec.change, 'spec.change');
|
||||
} else if (Object.prototype.hasOwnProperty.call(spec, 'change')) {
|
||||
@ -225,6 +237,7 @@ function validateSpec(spec, args) {
|
||||
docMeta: spec.docMeta || {},
|
||||
group: spec.group,
|
||||
methods: spec.methods,
|
||||
deleteMethods,
|
||||
change: spec.change || null,
|
||||
};
|
||||
}
|
||||
@ -251,7 +264,7 @@ function cloneJson(value) {
|
||||
return JSON.parse(JSON.stringify(value));
|
||||
}
|
||||
|
||||
function applyDocUpdate(doc, groupSpec, methods, docMeta) {
|
||||
function applyDocUpdate(doc, groupSpec, methods, docMeta, deleteMethods = []) {
|
||||
const groups = doc.methods.groups;
|
||||
let groupIndex = findGroupIndex(groups, groupSpec);
|
||||
|
||||
@ -275,6 +288,8 @@ function applyDocUpdate(doc, groupSpec, methods, docMeta) {
|
||||
inserted: [],
|
||||
updated: [],
|
||||
moved: [],
|
||||
deleted: [],
|
||||
deleteNotFound: [],
|
||||
};
|
||||
|
||||
for (const methodDoc of methods) {
|
||||
@ -298,6 +313,16 @@ function applyDocUpdate(doc, groupSpec, methods, docMeta) {
|
||||
summary.moved.push(methodDoc.method);
|
||||
}
|
||||
|
||||
for (const methodName of deleteMethods) {
|
||||
const location = findMethodLocation(groups, methodName);
|
||||
if (!location) {
|
||||
summary.deleteNotFound.push(methodName);
|
||||
continue;
|
||||
}
|
||||
groups[location.groupIndex].list.splice(location.methodIndex, 1);
|
||||
summary.deleted.push(methodName);
|
||||
}
|
||||
|
||||
if (docMeta.updatedAt) {
|
||||
doc.updatedAt = docMeta.updatedAt;
|
||||
}
|
||||
@ -339,7 +364,7 @@ function main() {
|
||||
}
|
||||
|
||||
const docNext = cloneJson(docState.json);
|
||||
const summary = applyDocUpdate(docNext, normalized.group, normalized.methods, normalized.docMeta);
|
||||
const summary = applyDocUpdate(docNext, normalized.group, normalized.methods, normalized.docMeta, normalized.deleteMethods);
|
||||
JSON.parse(JSON.stringify(docNext));
|
||||
|
||||
let changeNext = null;
|
||||
@ -354,6 +379,8 @@ function main() {
|
||||
console.log(`inserted: ${summary.inserted.length ? summary.inserted.join(', ') : '-'}`);
|
||||
console.log(`updated: ${summary.updated.length ? summary.updated.join(', ') : '-'}`);
|
||||
console.log(`moved: ${summary.moved.length ? summary.moved.join(', ') : '-'}`);
|
||||
console.log(`deleted: ${summary.deleted.length ? summary.deleted.join(', ') : '-'}`);
|
||||
console.log(`delete-not-found: ${summary.deleteNotFound.length ? summary.deleteNotFound.join(', ') : '-'}`);
|
||||
if (!args.docOnly && normalized.change) {
|
||||
console.log(`change version: ${normalized.change.version}`);
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user