import { parseYamlConfig } from './yaml-config.mjs' /** * Flatten config-vars.yaml's `database:` section into the DB_* env-shape that * resolveDbConfig consumes. Pure; tolerates a missing section. * * @param {Record} config parsed config-vars.yaml * @returns {Record} */ export function dbEnvFromConfig(config) { const db = (config && config.database) || {} return { DB_HOST: db.host, DB_PORT: db.port != null ? String(db.port) : undefined, DB_USER: db.user, DB_PASSWORD: db.password, DB_SCHEMA: db.schema, } } /** * Apply a DDL file to a MySQL database using mysql2/promise. * DB credentials are read from config-vars.yaml's `database:` section. * * @param {{configPath: string, ddlPath: string}} opts * @returns {Promise} */ export async function applyDDL({ configPath, ddlPath }) { const { readFileSync } = await import('node:fs') const env = dbEnvFromConfig(parseYamlConfig(readFileSync(configPath, 'utf8'))) const ddl = readFileSync(ddlPath, 'utf8') const { host, port, user, password, database } = resolveDbConfig(env, configPath) let mysql try { ;({ default: mysql } = await import('mysql2/promise')) } catch { throw new MysqlUnavailableError() } const conn = await mysql.createConnection({ host, port, user, password, database, multipleStatements: true, }) try { await conn.query(ddl) } finally { await conn.end() } } /** * Resolve mysql2 connection settings from a parsed env object. Pure (no I/O), * so it is unit-testable without mysql2 installed. * * Throws if no schema resolves — V1 has no USE/CREATE DATABASE. * * @param {Record} env * @param {string} [cfgPath] only used to make the error message actionable * @returns {{host:string, port:number, user:string, password:string, database:string}} */ export function resolveDbConfig(env, cfgPath = 'config-vars.yaml') { const host = env.DB_HOST || env.MYSQL_HOST || '127.0.0.1' const port = Number(env.DB_PORT || env.MYSQL_PORT || 3306) const user = env.DB_USER || env.MYSQL_USER || 'root' const password = env.DB_PASS || env.DB_PASSWORD || env.MYSQL_PASSWORD || '' const database = env.DB_SCHEMA || env.DB_NAME || env.MYSQL_DATABASE || undefined if (!database) { throw new Error(`apply-ddl: 缺数据库名 — 请在 ${cfgPath} 的 database.schema 填写`) } if (!Number.isInteger(port) || port <= 0 || port > 65535) { throw new Error(`apply-ddl: 端口非法 — ${cfgPath} 的 database.port 必须是 1..65535 的整数`) } return { host, port, user, password, database } } /** Distinct error type so the CLI can emit a friendly install hint. */ export class MysqlUnavailableError extends Error { constructor() { super('mysql2 is not installed') this.name = 'MysqlUnavailableError' } } // CLI entry guard:pathToFileURL 规范化 argv[1] 以匹配 import.meta.url(路径含空格 / 非 ASCII / Windows 反斜杠时字面比较会失配) const { pathToFileURL } = await import('node:url') if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { const [configPath, ddlPath] = process.argv.slice(2) if (!configPath || !ddlPath) { console.error('usage: node lib/apply-ddl.mjs ') process.exit(2) } try { await applyDDL({ configPath, ddlPath }) console.log(`apply-ddl: applied ${ddlPath} using ${configPath}`) } catch (e) { if (e instanceof MysqlUnavailableError) { console.error('apply-ddl: mysql2 not found. Please run `npm i mysql2` in the target project.') process.exit(1) } console.error(`apply-ddl: failed — ${e?.message || e}`) process.exit(1) } }