diff --git a/src/db.ts b/src/db.ts index 7e8f633..fdc4368 100644 --- a/src/db.ts +++ b/src/db.ts @@ -57,11 +57,22 @@ export function openDatabase(): Promise { }); } +async function tableExists(name: string): Promise { + const rows = await dbAll<{ cnt: number }>( + "SELECT COUNT(*) AS cnt FROM sqlite_master WHERE type='table' AND name=?", + [name], + ); + return (rows[0]?.cnt ?? 0) > 0; +} + export async function initDatabase(): Promise { fs.mkdirSync(MOCK_DIR, { recursive: true }); fs.mkdirSync(DATA_DIR, { recursive: true }); if (!fs.existsSync(DB_FILE) && fs.existsSync(LEGACY_DB_FILE)) { fs.copyFileSync(LEGACY_DB_FILE, DB_FILE); + console.log( + `[DB] 已从旧路径迁移数据库: ${LEGACY_DB_FILE} -> ${DB_FILE}`, + ); } await openDatabase(); await dbRun(` @@ -132,6 +143,7 @@ export async function initDatabase(): Promise { value TEXT NOT NULL ) `); + const hadIpRules = await tableExists("ip_rules"); await dbRun(` CREATE TABLE IF NOT EXISTS ip_rules ( ip TEXT PRIMARY KEY, @@ -145,6 +157,9 @@ export async function initDatabase(): Promise { target_https INTEGER ) `); + if (!hadIpRules) { + console.log("[DB] 数据库已自动升级: 新增 IP 管理(ip_rules)表"); + } // 清理不该出现在 mock 列表中的系统文件 await dbRun( "DELETE FROM mock_files WHERE file_path = ? OR file_path LIKE ?",