Db: Make backups work for open databases

rendering
Liza 2023-02-23 16:13:46 +01:00
parent f02aeffb26
commit 17f7dcdf12
2 changed files with 18 additions and 13 deletions

View File

@ -1,9 +1,7 @@
using Dalamud.Logging;
using System;
using System;
using System.Linq;
using System.Security.Cryptography;
using Microsoft.Extensions.Logging;
using Pal.Client.DependencyInjection.Logging;
namespace Pal.Client.Configuration
{

View File

@ -114,7 +114,7 @@ namespace Pal.Client
var toDelete = backupFiles.OrderByDescending(x => x.Date)
.Skip(configuration.Backups.MinimumBackupsToKeep)
.Where(x => (DateTime.Today.ToUniversalTime() - x.Date).Days > configuration.Backups.DaysToDeleteAfter)
.Where(x => (DateTime.Now.ToUniversalTime() - x.Date).Days > configuration.Backups.DaysToDeleteAfter)
.Select(x => x.Path);
foreach (var path in toDelete)
{
@ -136,22 +136,29 @@ namespace Pal.Client
var pluginInterface = scope.ServiceProvider.GetRequiredService<DalamudPluginInterface>();
string backupPath = Path.Join(pluginInterface.GetPluginConfigDirectory(),
$"backup-{DateTime.Today.ToUniversalTime():yyyy-MM-dd}.data.sqlite3");
$"backup-{DateTime.Now.ToUniversalTime():yyyy-MM-dd}.data.sqlite3");
string sourcePath = Path.Join(pluginInterface.GetPluginConfigDirectory(),
DependencyInjectionContext.DatabaseFileName);
if (File.Exists(sourcePath) && !File.Exists(backupPath))
{
if (File.Exists(sourcePath + "-shm") || File.Exists(sourcePath + "-wal"))
{
_logger.LogWarning("Could not create backup, database is open in another program");
return;
}
_logger.LogInformation("Creating database backup '{Path}'", backupPath);
try
{
if (File.Exists(sourcePath + "-shm") || File.Exists(sourcePath + "-wal"))
{
_logger.LogInformation("Creating database backup '{Path}' (open db)", backupPath);
await using var db = scope.ServiceProvider.GetRequiredService<PalClientContext>();
await using SqliteConnection source = new(db.Database.GetConnectionString());
await source.OpenAsync();
await using SqliteConnection backup = new($"Data Source={backupPath}");
source.BackupDatabase(backup);
SqliteConnection.ClearPool(backup);
}
else
{
_logger.LogInformation("Creating database backup '{Path}' (file copy)", backupPath);
File.Copy(sourcePath, backupPath);
}
}
catch (Exception e)
{
_logger.LogError(e, "Could not create backup");