44 lines
2.4 KiB
JavaScript
44 lines
2.4 KiB
JavaScript
// 只读查询/受控清库小工具(连 docker 里的 mysql_db)
|
||
// 用法:
|
||
// node bin/logtool.js q "select count(*) from sys_oper_log"
|
||
// node bin/logtool.js clear-operlog 清理操作日志(先备份到 bin/backup/)
|
||
// node bin/logtool.js clear-operlog --yes 跳过确认
|
||
const fs = require('fs');
|
||
const path = require('path');
|
||
const { execFileSync } = require('child_process');
|
||
|
||
const MYSQL = ['exec', 'mysql_db', 'mysql', '-uchangzhou', '-piTSJSPPZM3LSGAPC', '--default-character-set=utf8mb4', '-D', 'changzhou'];
|
||
|
||
function sql(statement) {
|
||
return execFileSync('docker', [...MYSQL, '-N', '-B', '-e', statement],
|
||
{ encoding: 'buffer', maxBuffer: 256 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] }).toString('utf8');
|
||
}
|
||
|
||
const [cmd, ...rest] = process.argv.slice(2);
|
||
|
||
if (cmd === 'q') {
|
||
console.log(sql(rest.join(' ')));
|
||
} else if (cmd === 'clear-operlog') {
|
||
const before = sql('select count(*) from sys_oper_log').trim();
|
||
console.log(`清空前 sys_oper_log: ${before} 行`);
|
||
if (before === '0') process.exit(0);
|
||
// 备份成 INSERT 语句,清错了还能捞回来
|
||
const dir = path.resolve(__dirname, 'backup');
|
||
fs.mkdirSync(dir, { recursive: true });
|
||
const dump = execFileSync('docker', [...MYSQL, '-N', '-B', '-e',
|
||
'select concat("insert into sys_oper_log (title,business_type,method,request_method,operator_type,oper_name,dept_name,oper_url,oper_ip,oper_location,oper_param,json_result,status,error_msg,cost_time,oper_time) values (",' +
|
||
'quote(title),",",business_type,",",quote(method),",",quote(request_method),",",operator_type,",",quote(oper_name),",",quote(dept_name),",",quote(oper_url),",",quote(oper_ip),",",quote(oper_location),",",quote(oper_param),",",quote(json_result),",",status,",",quote(error_msg),",",cost_time,",",quote(oper_time),");") from sys_oper_log'],
|
||
{ encoding: 'buffer', maxBuffer: 256 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] }).toString('utf8');
|
||
const file = path.join(dir, `sys_oper_log_${new Date().toISOString().replace(/[:.]/g, '-')}.sql`);
|
||
fs.writeFileSync(file, dump, 'utf8');
|
||
console.log(`已备份 → ${file}`);
|
||
if (!rest.includes('--yes')) {
|
||
console.error('要真清空请加 --yes');
|
||
process.exit(2);
|
||
}
|
||
sql('truncate table sys_oper_log');
|
||
console.log(`清空后 sys_oper_log: ${sql('select count(*) from sys_oper_log').trim()} 行`);
|
||
} else {
|
||
console.log('用法: node bin/logtool.js q "<sql>" | node bin/logtool.js clear-operlog [--yes]');
|
||
}
|