From 60d788178fd86b7b19c87de35c398c91189c4e8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Chsc=E2=80=9D?= <“huangsucan@kaiyili-lab.com”> Date: Thu, 10 Sep 2026 14:35:26 +0800 Subject: [PATCH] =?UTF-8?q?P3:=20=E6=95=B0=E6=8D=AE=E5=BA=93=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E8=86=A8=E8=83=80=20=E2=86=92=20=E5=90=AF=E5=8A=A8?= =?UTF-8?q?=E6=97=B6=E6=A3=80=E6=9F=A5=E6=96=87=E4=BB=B6=E8=BF=87=E6=9C=9F?= =?UTF-8?q?=EF=BC=88=E9=BB=98=E8=AE=A4180=E5=A4=A9=EF=BC=89=EF=BC=8C?= =?UTF-8?q?=E8=BF=87=E6=9C=9F=E5=88=99=E5=BD=92=E6=A1=A3=E9=87=8D=E5=91=BD?= =?UTF-8?q?=E5=90=8D=EF=BC=88SQL=5F=E5=BD=92=E6=A1=A3=5FyyyyMMdd=5FHHmmss.?= =?UTF-8?q?db=EF=BC=89=EF=BC=8C=E4=B8=8D=E5=88=A0=E9=99=A4=E8=AE=B0?= =?UTF-8?q?=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ACP/App.xaml.cs | 2 ++ ORM/DatabaseConfig.cs | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/ACP/App.xaml.cs b/ACP/App.xaml.cs index 24fceaf..876517c 100644 --- a/ACP/App.xaml.cs +++ b/ACP/App.xaml.cs @@ -121,6 +121,8 @@ namespace ACP //初始化数据库 DatabaseConfig.SetTenant(10001); DatabaseConfig.InitSqlite(); + // 启动时检查数据库文件是否过期,过期则归档(重命名加时间戳),后续会自动创建新库 + DatabaseConfig.TryArchiveOldDatabase(); DatabaseConfig.CreateDatabaseAndCheckConnection(createDatabase: true, checkConnection: true); SqlSugarContext.InitDatabase(); //显示登录窗口 diff --git a/ORM/DatabaseConfig.cs b/ORM/DatabaseConfig.cs index 0fa07cc..07f4b66 100644 --- a/ORM/DatabaseConfig.cs +++ b/ORM/DatabaseConfig.cs @@ -128,5 +128,44 @@ namespace ORM throw new Exception("连接数据库失败"); } } + + /// + /// 归档过期数据库文件:将旧的 SQLite 文件重命名为 "SQL_归档_yyyyMMdd_HHmmss.db", + /// 后续 会自动创建新的空数据库。 + /// + /// 必须在 之后、 之前调用, + /// 此时连接字符串已就绪但数据库文件尚未被打开。 + /// + /// + /// 数据库文件保留天数,默认 180 天(半年) + public static void TryArchiveOldDatabase(int retentionDays = 180) + { + try + { + // 从连接字符串中提取文件路径(格式:Data Source=xxx;) + string dbPath = DbConnectionString + .Replace("Data Source=", "", StringComparison.OrdinalIgnoreCase) + .TrimEnd(';'); + + if (!File.Exists(dbPath)) return; + + var cutoff = DateTime.Now.AddDays(-retentionDays); + var fileInfo = new FileInfo(dbPath); + + if (fileInfo.LastWriteTime < cutoff) + { + string archiveName = $"SQL_归档_{fileInfo.LastWriteTime:yyyyMMdd_HHmmss}.db"; + string archivePath = Path.Combine(fileInfo.DirectoryName!, archiveName); + + File.Move(dbPath, archivePath); + System.Diagnostics.Debug.WriteLine( + $"[数据库归档] {dbPath} → {archivePath}(文件最后修改于 {fileInfo.LastWriteTime:yyyy-MM-dd},已超过 {retentionDays} 天)"); + } + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"数据库归档失败(不影响软件正常使用):{ex.Message}"); + } + } } }