127 lines
5.0 KiB
C#
127 lines
5.0 KiB
C#
using SqlSugar;
|
||
|
||
namespace PrivateBox.DataContext
|
||
{
|
||
/// <summary>
|
||
/// 数据库备份扩展类
|
||
/// </summary>
|
||
public static class DbBackupExtended
|
||
{
|
||
/// <summary>
|
||
/// 备份数据库【扩展方法】
|
||
/// </summary>
|
||
/// <param name="db">DbContext(ISqlSugarClient)</param>
|
||
/// <param name="options">备份选项配置委托</param>
|
||
public static void Backup(this ISqlSugarClient db,Action<DbBackupOptions>? options = null) {
|
||
var op = new DbBackupOptions();
|
||
options?.Invoke(op);
|
||
|
||
// 从SqlSugar连接串自动读取SQLite源文件路径,如果Options没手动指定SourceDbFilePath
|
||
if(string.IsNullOrWhiteSpace(op.SourceDbFilePath)) {
|
||
var connStr = db.Ado.Connection.ConnectionString;
|
||
// 解析 DataSource=xxx
|
||
op.SourceDbFilePath = GetSqliteDataSourcePath(connStr);
|
||
}
|
||
|
||
// 参数校验
|
||
if(string.IsNullOrWhiteSpace(op.SourceDbFilePath))
|
||
throw new ArgumentNullException(nameof(op.SourceDbFilePath),"无法获取源SQLite数据库文件路径,请在DbBackupOptions中手动指定SourceDbFilePath");
|
||
if(string.IsNullOrWhiteSpace(op.BackupDirectory))
|
||
throw new ArgumentNullException(nameof(op.BackupDirectory),"必须指定备份存放目录");
|
||
if(op.MaxBackupFileCount <= 0)
|
||
op.MaxBackupFileCount = 3; // 默认最多保留3个备份
|
||
|
||
try {
|
||
if(!File.Exists(op.SourceDbFilePath)) {
|
||
Console.WriteLine($"源数据库文件不存在:{op.SourceDbFilePath},跳过备份");
|
||
return;
|
||
}
|
||
|
||
// 创建备份目录
|
||
if(!Directory.Exists(op.BackupDirectory)) {
|
||
Directory.CreateDirectory(op.BackupDirectory);
|
||
}
|
||
|
||
// WAL刷盘,保证数据完整
|
||
db.Ado.ExecuteCommand("PRAGMA wal_checkpoint(FULL);");
|
||
|
||
// 生成带时间戳备份文件名
|
||
string backupFileName = $"db_backup_{DateTime.Now:yyyyMMdd_HHmmss}.sqlite";
|
||
string fullBackupFile = Path.Combine(op.BackupDirectory,backupFileName);
|
||
|
||
// 复制数据库文件
|
||
File.Copy(op.SourceDbFilePath,fullBackupFile,overwrite: false);
|
||
Console.WriteLine($"备份成功:{fullBackupFile}");
|
||
|
||
// 清理旧备份
|
||
CleanOldBackupFiles(op.BackupDirectory,op.MaxBackupFileCount);
|
||
}
|
||
catch(Exception ex) {
|
||
Console.WriteLine($"数据库备份异常:{ex.Message}");
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 从SQLite连接字符串解析DataSource路径
|
||
/// </summary>
|
||
private static string GetSqliteDataSourcePath(string connectionString) {
|
||
var pairs = connectionString.Split(';')
|
||
.Select(s => s.Trim())
|
||
.Where(s => !string.IsNullOrEmpty(s))
|
||
.Select(s => {
|
||
var kv = s.Split('=');
|
||
return new { Key = kv[0].Trim(),Value = kv.Length > 1 ? kv[1].Trim() : "" };
|
||
});
|
||
var item = pairs.FirstOrDefault(p => p.Key.Equals("DataSource",StringComparison.OrdinalIgnoreCase));
|
||
return item?.Value;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 清理过期备份,只保留最新MaxBackupFileCount个
|
||
/// </summary>
|
||
/// <param name="backupDir">备份目录</param>
|
||
/// <param name="maxCount">最大保留数量</param>
|
||
private static void CleanOldBackupFiles(string backupDir,int maxCount) {
|
||
var backupFiles = Directory.GetFiles(backupDir,"db_backup_*.sqlite")
|
||
.Select(f => new FileInfo(f))
|
||
.OrderBy(x => x.CreationTime) // 旧文件在前
|
||
.ToList();
|
||
|
||
if(backupFiles.Count > maxCount) {
|
||
var deleteList = backupFiles.Take(backupFiles.Count - maxCount).ToList();
|
||
foreach(var file in deleteList) {
|
||
try {
|
||
file.Delete();
|
||
Console.WriteLine($"删除过期备份:{file.FullName}");
|
||
}
|
||
catch(Exception ex) {
|
||
Console.WriteLine($"删除旧备份失败 {file.FullName}:{ex.Message}");
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 备份选项
|
||
/// </summary>
|
||
public class DbBackupOptions
|
||
{
|
||
/// <summary>
|
||
/// 源SQLite数据库文件完整路径,不设置则自动从SqlSugar连接串读取
|
||
/// </summary>
|
||
public string? SourceDbFilePath { get; set; }
|
||
|
||
/// <summary>
|
||
/// 备份存放目录
|
||
/// </summary>
|
||
public string? BackupDirectory { get; set; }
|
||
|
||
/// <summary>
|
||
/// 备份文件最大数量
|
||
/// </summary>
|
||
public int MaxBackupFileCount { get; set; }
|
||
}
|
||
|
||
}
|