P3: 数据库文件膨胀 → 启动时检查文件过期(默认180天),过期则归档重命名(SQL_归档_yyyyMMdd_HHmmss.db),不删除记录
This commit is contained in:
@@ -121,6 +121,8 @@ namespace ACP
|
||||
//初始化数据库
|
||||
DatabaseConfig.SetTenant(10001);
|
||||
DatabaseConfig.InitSqlite();
|
||||
// 启动时检查数据库文件是否过期,过期则归档(重命名加时间戳),后续会自动创建新库
|
||||
DatabaseConfig.TryArchiveOldDatabase();
|
||||
DatabaseConfig.CreateDatabaseAndCheckConnection(createDatabase: true, checkConnection: true);
|
||||
SqlSugarContext.InitDatabase();
|
||||
//显示登录窗口
|
||||
|
||||
@@ -128,5 +128,44 @@ namespace ORM
|
||||
throw new Exception("连接数据库失败");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 归档过期数据库文件:将旧的 SQLite 文件重命名为 "SQL_归档_yyyyMMdd_HHmmss.db",
|
||||
/// 后续 <see cref="CreateDatabaseAndCheckConnection"/> 会自动创建新的空数据库。
|
||||
/// <para>
|
||||
/// 必须在 <see cref="InitSqlite"/> 之后、<see cref="CreateDatabaseAndCheckConnection"/> 之前调用,
|
||||
/// 此时连接字符串已就绪但数据库文件尚未被打开。
|
||||
/// </para>
|
||||
/// </summary>
|
||||
/// <param name="retentionDays">数据库文件保留天数,默认 180 天(半年)</param>
|
||||
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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user