Files
Web_BLS_Heartbeat_Server/SQL_Script/run_init.js

113 lines
3.5 KiB
JavaScript
Raw Normal View History

#!/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();