Files
XuJiacheng 3b98c6239b feat: 移除运行时代码中的数据库初始化与分区维护逻辑
- 新增备份 SQL 脚本 `01_init_schema.sql` 和 `02_create_partitions.sql`,用于数据库结构初始化和分区预创建。
- 新增 Node.js 脚本 `run_init.js` 和 `run_ensure_partitions.js`,支持通过外部程序调用进行数据库初始化和分区维护。
- 确保数据库初始化脚本支持幂等重复执行。
- 更新文档,说明新的执行顺序和使用方法。
- 移除运行时相关的数据库初始化和分区维护配置,简化服务职责。
- 保留写入失败时的缺分区兜底逻辑,确保服务稳定性。
2026-03-04 11:47:22 +08:00

113 lines
3.5 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env node
/**
* run_init.js
* 执行数据库 Schema 初始化01_init_schema.sql
*
* 用法:
* node SQL_Script/run_init.js
*
* 连接参数优先级:命令行参数 > 环境变量 > .env 文件
*
* 命令行参数(均可选):
* --host=<host> PostgreSQL 主机,默认 POSTGRES_HOST 或 127.0.0.1
* --port=<port> 端口,默认 POSTGRES_PORT 或 5432
* --user=<user> 用户,默认 POSTGRES_USER 或 postgres
* --password=<password> 密码,默认 POSTGRES_PASSWORD
* --database=<database> 数据库名,默认 POSTGRES_DATABASE 或 log_platform
*/
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { Client } from 'pg';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// ----------------------------------------------------------
// 1. 加载 .env
// ----------------------------------------------------------
function loadEnv() {
const candidates = [
path.resolve(process.cwd(), '.env'),
path.resolve(__dirname, '../.env'),
];
for (const envPath of candidates) {
if (!fs.existsSync(envPath)) continue;
const lines = fs.readFileSync(envPath, 'utf8').split(/\r?\n/);
for (const line of lines) {
const t = line.trim();
if (!t || t.startsWith('#')) continue;
const idx = t.indexOf('=');
if (idx <= 0) continue;
const key = t.slice(0, idx).trim();
let val = t.slice(idx + 1).trim();
if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
val = val.slice(1, -1);
}
if (process.env[key] === undefined) process.env[key] = val;
}
console.log(`[env] 已加载 ${envPath}`);
return;
}
}
// ----------------------------------------------------------
// 2. 解析命令行参数
// ----------------------------------------------------------
function parseArgs() {
const args = {};
for (const arg of process.argv.slice(2)) {
const m = arg.match(/^--([^=]+)=(.*)$/);
if (m) args[m[1]] = m[2];
}
return args;
}
// ----------------------------------------------------------
// 3. 主流程
// ----------------------------------------------------------
async function main() {
loadEnv();
const args = parseArgs();
const env = process.env;
const config = {
host: args.host ?? env.POSTGRES_HOST ?? env.PGHOST ?? '127.0.0.1',
port: Number(args.port ?? env.POSTGRES_PORT ?? env.PGPORT ?? 5432),
user: args.user ?? env.POSTGRES_USER ?? env.PGUSER ?? 'postgres',
password: args.password ?? env.POSTGRES_PASSWORD ?? env.PGPASSWORD ?? '',
database: args.database ?? env.POSTGRES_DATABASE ?? env.PGTARGETDB ?? 'log_platform',
};
console.log('[init] 连接数据库:', {
host: config.host,
port: config.port,
user: config.user,
database: config.database,
});
const sqlPath = path.resolve(__dirname, '01_init_schema.sql');
if (!fs.existsSync(sqlPath)) {
console.error(`[init] 找不到 SQL 文件: ${sqlPath}`);
process.exit(1);
}
const sql = fs.readFileSync(sqlPath, 'utf8');
const client = new Client(config);
try {
await client.connect();
console.log('[init] 数据库连接成功,开始执行初始化 SQL...');
await client.query(sql);
console.log('[init] ✅ Schema 初始化完成');
} catch (err) {
console.error('[init] ❌ 初始化失败:', err.message);
process.exit(1);
} finally {
await client.end();
}
}
main();