import { existsSync, readFileSync } from 'node:fs'; import path from 'node:path'; import { LEGACY_COLUMNS, type LegacyTable } from './columns'; import { readTable, toObjects, type SqlValue } from './parser'; /** * 旧库 dump 的默认位置。 * 兼顾两种运行方式:`pnpm legacy:check`(cwd 为包根)与 vitest(cwd 为包根)。 * 可用 LEGACY_DUMP 环境变量覆盖。 */ function resolveDefaultDumpPath(): string { const candidates = [ path.resolve(process.cwd(), '../数据库/api_yeomai_site_mysql.sql'), path.resolve(process.cwd(), '数据库/api_yeomai_site_mysql.sql'), ]; return candidates.find((p) => existsSync(p)) ?? candidates[0]!; } export const DEFAULT_DUMP_PATH = process.env.LEGACY_DUMP ?? resolveDefaultDumpPath(); export type LegacyRows = Record[]>; export function loadLegacyDump(dumpPath: string = process.env.LEGACY_DUMP ?? DEFAULT_DUMP_PATH): LegacyRows { const sql = readFileSync(dumpPath, 'utf8'); const result = {} as LegacyRows; for (const table of Object.keys(LEGACY_COLUMNS) as LegacyTable[]) { result[table] = toObjects(readTable(sql, table), [...LEGACY_COLUMNS[table]]); } return result; } export function asString(v: SqlValue): string { return v === null ? '' : String(v); }