-
Notifications
You must be signed in to change notification settings - Fork 6
/
SynchronizedSummitDbContextFactory.cs
102 lines (84 loc) · 3.17 KB
/
SynchronizedSummitDbContextFactory.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
using Microsoft.EntityFrameworkCore;
using Microsoft.JSInterop;
using MvpSummit.Domain;
namespace MvpSummitWasm.Data
{
public class SynchronizedSummitDbContextFactory : ISummitTaskContextFactory
{
private readonly IDbContextFactory<SummitTaskContext> dbContextFactory;
private readonly IJSRuntime Js;
private Task<int>? lastTask = null;
private int lastStatus = -2;
private bool init = false;
private string backupName = backup;
public const string backup = $"{dbFilename}_bak";
public const string dbFilename = "todos.sqlite3";
public SynchronizedSummitDbContextFactory(
IJSRuntime js,
IDbContextFactory<SummitTaskContext> dbContextFactory)
{
Js = js;
this.dbContextFactory = dbContextFactory;
lastTask = SynchronizeAsync();
this.dbContextFactory = dbContextFactory;
}
public async Task<SummitTaskContext> CreateSummitContextAsync()
{
await CheckForPendingTasksAsync();
var ctx = await dbContextFactory.CreateDbContextAsync();
if (!init)
{
Console.WriteLine($"Last status: {lastStatus}");
await ctx.Database.EnsureCreatedAsync();
init = true;
}
ctx.SavedChanges += Ctx_SavedChanges;
return ctx;
}
private async Task CheckForPendingTasksAsync()
{
if (lastTask != null)
{
lastStatus = await lastTask;
lastTask.Dispose();
lastTask = null;
if (lastStatus == 0)
{
Restore();
}
}
}
private void Ctx_SavedChanges(object? sender, SavedChangesEventArgs e) =>
lastTask = SynchronizeAsync();
private async Task<int> SynchronizeAsync()
{
if (init)
{
Backup();
}
var result = await Js.InvokeAsync<int>(
"db.synchronizeDbWithCache", backupName);
var resultText = result == -1 ? "Failure" : (result == 0 ? "Restored" : "Cached");
Console.WriteLine($"Synchronization status: {resultText}");
return result;
}
private void Backup() => DoSwap(false);
private void Restore() => DoSwap(true);
private void DoSwap(bool restore)
{
backupName = restore ? backup : $"{backup}-{Guid.NewGuid().ToString().Split('-')[0]}";
var dir = restore ? nameof(restore) : nameof(backup);
Console.WriteLine($"Begin {dir}.");
var source = restore ? $"Data Source={backupName}" : $"Data Source={dbFilename}";
var target = restore ? $"Data Source={dbFilename}" : $"Data Source={backupName}";
/*using var src = new SqliteConnection(source);
using var tgt = new SqliteConnection(target);
src.Open();
tgt.Open();
src.BackupDatabase(tgt);
tgt.Close();
src.Close();*/
Console.WriteLine($"End {dir}.");
}
}
}