using Serilog;
namespace YZWater.Core.Services;
///
/// 数据库备份服务
///
public static class BackupService
{
private static readonly string BackupDir = "Backups";
///
/// 创建数据库备份
///
public static async Task<(bool Success, string Path)> BackupAsync()
{
try
{
Directory.CreateDirectory(BackupDir);
var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
var backupPath = Path.Combine(BackupDir, $"yzwater_backup_{timestamp}.db");
// SQLite 备份:复制数据库文件
var sourcePath = "yzwater.db";
if (!File.Exists(sourcePath))
{
Log.Warning("数据库文件不存在: {Path}", sourcePath);
return (false, string.Empty);
}
// 使用 SqlSugar 的备份功能
var db = DatabaseService.Db;
await Task.Run(() =>
{
File.Copy(sourcePath, backupPath, true);
});
Log.Information("数据库备份成功: {Path}", backupPath);
AuditService.Log("系统", "Backup", $"数据库备份: {backupPath}");
return (true, backupPath);
}
catch (Exception ex)
{
Log.Error(ex, "数据库备份失败");
return (false, string.Empty);
}
}
///
/// 恢复数据库
///
public static async Task RestoreAsync(string backupPath)
{
try
{
if (!File.Exists(backupPath))
{
Log.Warning("备份文件不存在: {Path}", backupPath);
return false;
}
var targetPath = "yzwater.db";
// 先备份当前数据库
var preRestoreBackup = Path.Combine(BackupDir, $"yzwater_pre_restore_{DateTime.Now:yyyyMMdd_HHmmss}.db");
if (File.Exists(targetPath))
{
File.Copy(targetPath, preRestoreBackup, true);
}
await Task.Run(() =>
{
File.Copy(backupPath, targetPath, true);
});
Log.Information("数据库恢复成功,恢复前备份: {Path}", preRestoreBackup);
AuditService.Log("系统", "Restore", $"数据库恢复: {backupPath},恢复前备份: {preRestoreBackup}");
return true;
}
catch (Exception ex)
{
Log.Error(ex, "数据库恢复失败");
return false;
}
}
///
/// 获取备份列表
///
public static List<(string Path, DateTime Time, long Size)> GetBackups()
{
if (!Directory.Exists(BackupDir))
return new List<(string, DateTime, long)>();
return Directory.GetFiles(BackupDir, "*.db")
.Select(f => new FileInfo(f))
.OrderByDescending(f => f.CreationTime)
.Select(f => (f.FullName, f.CreationTime, f.Length))
.ToList();
}
///
/// 清理旧备份(保留最近 N 个)
///
public static int CleanupOldBackups(int keepCount = 10)
{
if (!Directory.Exists(BackupDir))
return 0;
var backups = Directory.GetFiles(BackupDir, "*.db")
.Select(f => new FileInfo(f))
.OrderByDescending(f => f.CreationTime)
.Skip(keepCount)
.ToList();
foreach (var backup in backups)
{
try
{
backup.Delete();
Log.Debug("已删除旧备份: {Path}", backup.FullName);
}
catch (Exception ex)
{
Log.Warning(ex, "删除旧备份失败: {Path}", backup.FullName);
}
}
if (backups.Count > 0)
Log.Information("已清理 {Count} 个旧备份", backups.Count);
return backups.Count;
}
}