E1: schema dell'esportazione, migrazione 0003, archivi ed ExportSettings (#58)
La tappa E1 della 0.3.0 prepara il database per le copie esterne senza cambiare comportamento: nulla in interfaccia, motore o API usa ancora ciò che segue. - Migrazione 0003: export_destination, export_account, export_copy, export_run, export_item, video_analysis e media_conversion (risposta di Alberto del 26 novembre: i convertiti per la libreria in una tabella a parte, media non cambia), con i vincoli e gli indici di §8.3. - Archivi IExportStore, IVideoAnalysisStore e IMediaConversionStore in IFebeStorage; ExportSettings sulle cinque chiavi esportazione.*. - AccountStore.DeleteAsync spegne «Automatica» delle cartelle dell'account e vi scrive il suo nome prima di cancellarlo (finché non ci sono destinazioni non fa nulla). - Prove: aggiornamento dei database delle versioni 1 e 2 con foreign_key_check pulito, database più nuovo rifiutato e lasciato intatto, vincoli, archivi, piani delle ricerche, impostazioni e documenti. - SPECIFICA §4.10, §8.3 e §15, decisioni.md e stato.md aggiornati. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
dc92cabe5c
commit
ea4666d49b
23 files changed
+3756
-7
No files matched your search
@@ -11,8 +11,19 @@ public sealed class MigrationTests
|
||||
[
|
||||
"setting", "account", "entry", "media", "highlight", "highlight_entry", "duplicate_pair", "task", "action_log",
|
||||
"session", "incident", "event", "following", "import_run", "import_file",
|
||||
"export_destination", "export_account", "export_copy", "export_run", "export_item", "video_analysis", "media_conversion",
|
||||
];
|
||||
|
||||
/// <summary>The tables of schema version 1, which migrations 2 and 3 never rewrite.</summary>
|
||||
private static readonly string[] Version1Tables =
|
||||
[
|
||||
"setting", "account", "entry", "media", "highlight", "highlight_entry", "duplicate_pair", "task", "action_log",
|
||||
"session", "incident", "event", "following", "import_run", "import_file",
|
||||
];
|
||||
|
||||
private static readonly string[] ExportTables =
|
||||
["export_destination", "export_account", "export_copy", "export_run", "export_item", "video_analysis", "media_conversion"];
|
||||
|
||||
[TestMethod]
|
||||
public void EmbeddedMigrationsAreNumberedFromOne()
|
||||
{
|
||||
@@ -24,6 +35,8 @@ public sealed class MigrationTests
|
||||
}
|
||||
|
||||
Assert.AreEqual("schema", migrations[0].Name);
|
||||
Assert.AreEqual("ordine_scaricamento", migrations[1].Name);
|
||||
Assert.AreEqual("esportazione", migrations[2].Name);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -145,6 +158,234 @@ public sealed class MigrationTests
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task DatabaseAtVersion1IsUpgradedWithForeignKeysClean() => await UpgradeKeepsEverything(1);
|
||||
|
||||
[TestMethod]
|
||||
public async Task DatabaseAtVersion2IsUpgradedWithForeignKeysClean() => await UpgradeKeepsEverything(2);
|
||||
|
||||
[TestMethod]
|
||||
public void MigrationThreeChangesNoExistingTable()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
var path = temp.Combine("dati", FebeDatabase.FileName);
|
||||
var all = MigrationRunner.LoadEmbedded();
|
||||
Close(FebeDatabase.Open(path, all.Take(2).ToList()));
|
||||
var before = SchemaOf(path, Version1Tables);
|
||||
var shapesBefore = TableShapes(path, Version1Tables);
|
||||
|
||||
Close(FebeDatabase.Open(path, all));
|
||||
|
||||
CollectionAssert.AreEqual(before, SchemaOf(path, Version1Tables), "la migrazione 3 non tocca tabelle né indici esistenti");
|
||||
CollectionAssert.AreEqual(shapesBefore, TableShapes(path, Version1Tables), "colonne e indici delle tabelle esistenti restano gli stessi");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task DatabaseOneVersionNewerIsRefusedAndLeftUntouched()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
var path = temp.Combine("dati", FebeDatabase.FileName);
|
||||
await using (var db = await TestDatabase.OpenAsync(temp))
|
||||
{
|
||||
await db.Settings.SetAsync("prova", "1");
|
||||
}
|
||||
|
||||
var next = MigrationRunner.LoadEmbedded().Count + 1;
|
||||
SetUserVersion(path, next);
|
||||
var bytes = File.ReadAllBytes(path);
|
||||
|
||||
var error = await Assert.ThrowsExactlyAsync<DatabaseMigrationException>(() => FebeDatabase.OpenFileAsync(path));
|
||||
|
||||
Assert.Contains("più recente", error.Message);
|
||||
Assert.AreEqual((long)next, GetUserVersion(path));
|
||||
CollectionAssert.AreEqual(bytes, File.ReadAllBytes(path), "Febe non scrive nel database più recente");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A database left at an older version with data in every table is brought to the latest version: references
|
||||
/// clean, data unchanged, export tables empty, no export setting written.
|
||||
/// </summary>
|
||||
private static async Task UpgradeKeepsEverything(int fromVersion)
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
var path = temp.Combine("dati", FebeDatabase.FileName);
|
||||
var all = MigrationRunner.LoadEmbedded();
|
||||
Close(FebeDatabase.Open(path, all.Take(fromVersion).ToList()));
|
||||
Fill(path, fromVersion);
|
||||
var columns = ColumnsOf(path, Version1Tables);
|
||||
var before = Snapshot(path, columns);
|
||||
|
||||
await using (var db = FebeDatabase.Open(path, all))
|
||||
{
|
||||
Assert.AreEqual(all.Count, db.SchemaVersion);
|
||||
Assert.AreEqual(3, db.SchemaVersion);
|
||||
}
|
||||
|
||||
using var connection = Connect(path);
|
||||
Assert.AreEqual(0L, connection.Command("SELECT COUNT(*) FROM pragma_foreign_key_check").ScalarInt64(), "foreign_key_check pulito");
|
||||
Assert.AreEqual("ok", connection.Command("PRAGMA integrity_check").ExecuteScalar());
|
||||
CollectionAssert.AreEqual(before, Snapshot(path, columns), "i dati di prima restano uguali");
|
||||
foreach (var table in ExportTables)
|
||||
{
|
||||
Assert.AreEqual(0L, connection.Command($"SELECT COUNT(*) FROM {table}").ScalarInt64(), $"{table} nasce vuota");
|
||||
}
|
||||
|
||||
Assert.AreEqual(0L, connection.Command("SELECT COUNT(*) FROM setting WHERE key LIKE 'esportazione.%'").ScalarInt64());
|
||||
if (fromVersion >= 2)
|
||||
{
|
||||
Assert.AreEqual("storie,post", connection.Command("SELECT download_order FROM account WHERE username = 'marta.demo'").ExecuteScalar());
|
||||
Assert.AreEqual(1L, connection.Command("SELECT COUNT(*) FROM entry WHERE is_reel = 1").ScalarInt64());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Raw rows in every table of version 1 (and the columns of version 2), written without the stores.</summary>
|
||||
private static void Fill(string path, int version)
|
||||
{
|
||||
using var connection = Connect(path);
|
||||
connection.Command("PRAGMA foreign_keys = ON").ExecuteNonQuery();
|
||||
var sha = Make.Sha(7);
|
||||
var other = Make.Sha(8);
|
||||
connection.Command($"""
|
||||
INSERT INTO setting (key, value) VALUES ('libreria.schema', 'a/b'), ('motore.profilo', 'Prudent');
|
||||
INSERT INTO account (id, instagram_id, username, state, frequency, content_types, history_depth, backfill_posts_per_day, added_at)
|
||||
VALUES (1, '100', 'marta.demo', 'Active', 'Normal', 63, 'Everything', 50, 1000),
|
||||
(2, '200', 'luca.demo', 'Active', 'Normal', 63, 'Everything', 50, 1000);
|
||||
INSERT INTO entry (id, account_id, kind, instagram_id, published_at, state, provenance, discovered_at)
|
||||
VALUES (1, 1, 'Post', '555', 2000, 'Downloaded', 'Downloaded', 2000),
|
||||
(2, 2, 'Tagged', '555', 2000, 'Downloaded', 'Downloaded', 2000),
|
||||
(3, 1, 'Story', '777', 3000, 'Downloaded', 'Downloaded', 3000);
|
||||
INSERT INTO media (id, entry_id, position, kind, state, relative_path, bytes, sha256, downloaded_at)
|
||||
VALUES (1, 1, 1, 'Photo', 'Downloaded', 'post/a.jpg', 10, '{sha}', 2100),
|
||||
(2, 2, 1, 'Photo', 'Downloaded', 'taggati/a.jpg', 10, '{sha}', 2100),
|
||||
(3, 3, 1, 'Video', 'Downloaded', 'storie/b.mp4', 20, '{other}', 3100);
|
||||
INSERT INTO highlight (id, account_id, instagram_id, title, discovered_at) VALUES (1, 1, 'h1', 'Estate', 3000);
|
||||
INSERT INTO highlight_entry (highlight_id, entry_id, position) VALUES (1, 3, 1);
|
||||
INSERT INTO task (kind, account_id, due_at, state, created_at) VALUES ('Profile', 1, 4000, 'Pending', 4000);
|
||||
INSERT INTO import_run (id, source_path, mode, state, started_at) VALUES (1, 'C:/vecchie', 'Copy', 'Completed', 5000);
|
||||
INSERT INTO import_file (id, run_id, relative_path, folder, outcome, matched_media_id, decision, state)
|
||||
VALUES (1, 1, 'marta/a.jpg', 'marta', 'ProbableDuplicate', 1, 'None', 'Analyzed');
|
||||
INSERT INTO duplicate_pair (origin, reason, existing_media_id, candidate_import_file_id, decision, created_at)
|
||||
VALUES ('Import', 'PerceptualHash', 1, 1, 'Pending', 5000);
|
||||
INSERT INTO session (id, started_at, ended_at, action_count, outcome, summary) VALUES (1, 6000, 6500, 3, 'Completed', 'tre azioni');
|
||||
INSERT INTO action_log (at, category, account_id, session_id, amount) VALUES (6100, 'Profile', 1, 1, 1);
|
||||
INSERT INTO incident (at, level, signal, url, session_id, note) VALUES (6200, 'Pause', 'Http429', '/p/x', 1, 'prova');
|
||||
INSERT INTO event (at, severity, code, message, account_id, session_id) VALUES (6300, 'Info', 'Downloaded', 'scaricato', 1, 1);
|
||||
INSERT INTO "following" (instagram_id, username, display_name, is_private, position, read_at) VALUES ('300', 'anna.demo', 'Anna', 0, 1, 6400);
|
||||
""").ExecuteNonQuery();
|
||||
if (version >= 2)
|
||||
{
|
||||
connection.Command("UPDATE account SET download_order = 'storie,post' WHERE id = 1; UPDATE entry SET is_reel = 1 WHERE id = 1;").ExecuteNonQuery();
|
||||
}
|
||||
|
||||
Assert.AreEqual(0L, connection.Command("SELECT COUNT(*) FROM pragma_foreign_key_check").ScalarInt64());
|
||||
foreach (var table in Version1Tables)
|
||||
{
|
||||
Assert.IsGreaterThan(0L, connection.Command($"SELECT COUNT(*) FROM \"{table}\"").ScalarInt64(), $"{table} ha dati prima dell'aggiornamento");
|
||||
}
|
||||
}
|
||||
|
||||
private static SqliteConnection Connect(string path)
|
||||
{
|
||||
var connection = new SqliteConnection($"Data Source={path};Pooling=False");
|
||||
connection.Open();
|
||||
return connection;
|
||||
}
|
||||
|
||||
private static void Close(FebeDatabase db) => db.DisposeAsync().AsTask().GetAwaiter().GetResult();
|
||||
|
||||
/// <summary>The columns of the tables now, so a later snapshot reads the same ones.</summary>
|
||||
private static Dictionary<string, string[]> ColumnsOf(string path, IEnumerable<string> tables)
|
||||
{
|
||||
using var connection = Connect(path);
|
||||
var columns = new Dictionary<string, string[]>(StringComparer.Ordinal);
|
||||
foreach (var table in tables)
|
||||
{
|
||||
using var r = connection.Command($"SELECT name FROM pragma_table_info('{table}') ORDER BY cid").ExecuteReader();
|
||||
var names = new List<string>();
|
||||
while (r.Read())
|
||||
{
|
||||
names.Add(r.GetString(0));
|
||||
}
|
||||
|
||||
columns[table] = [.. names];
|
||||
}
|
||||
|
||||
return columns;
|
||||
}
|
||||
|
||||
/// <summary>Every row of the tables (the given columns), as text, in a stable order.</summary>
|
||||
private static List<string> Snapshot(string path, Dictionary<string, string[]> columns)
|
||||
{
|
||||
using var connection = Connect(path);
|
||||
var rows = new List<string>();
|
||||
foreach (var (table, names) in columns)
|
||||
{
|
||||
using var r = connection.Command($"SELECT {string.Join(", ", names.Select(n => $"\"{n}\""))} FROM \"{table}\"").ExecuteReader();
|
||||
var tableRows = new List<string>();
|
||||
while (r.Read())
|
||||
{
|
||||
var values = new string[r.FieldCount];
|
||||
for (var i = 0; i < r.FieldCount; i++)
|
||||
{
|
||||
values[i] = r.GetName(i) + "=" + (r.IsDBNull(i) ? "NULL" : Convert.ToString(r.GetValue(i), System.Globalization.CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
tableRows.Add(table + ": " + string.Join(", ", values));
|
||||
}
|
||||
|
||||
tableRows.Sort(StringComparer.Ordinal);
|
||||
rows.AddRange(tableRows);
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
/// <summary>The SQL of the tables and of their indexes and triggers.</summary>
|
||||
private static List<string> SchemaOf(string path, IEnumerable<string> tables)
|
||||
{
|
||||
using var connection = Connect(path);
|
||||
var list = new List<string>();
|
||||
using var command = connection.Command("SELECT type || ' ' || name || ': ' || ifnull(sql, '') FROM sqlite_master WHERE tbl_name = @t ORDER BY type, name");
|
||||
foreach (var table in tables)
|
||||
{
|
||||
command.With("@t", table);
|
||||
using var r = command.ExecuteReader();
|
||||
while (r.Read())
|
||||
{
|
||||
list.Add(r.GetString(0));
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>Columns (pragma_table_info) and indexes (pragma_index_list) of the tables.</summary>
|
||||
private static List<string> TableShapes(string path, IEnumerable<string> tables)
|
||||
{
|
||||
using var connection = Connect(path);
|
||||
var list = new List<string>();
|
||||
foreach (var table in tables)
|
||||
{
|
||||
using (var r = connection.Command($"SELECT cid, name, type, \"notnull\", ifnull(dflt_value, ''), pk FROM pragma_table_info('{table}') ORDER BY cid").ExecuteReader())
|
||||
{
|
||||
while (r.Read())
|
||||
{
|
||||
list.Add($"{table} column {r.GetInt64(0)} {r.GetString(1)} {r.GetString(2)} {r.GetInt64(3)} {r.GetString(4)} {r.GetInt64(5)}");
|
||||
}
|
||||
}
|
||||
|
||||
using (var r = connection.Command($"SELECT name, \"unique\", origin, partial FROM pragma_index_list('{table}') ORDER BY name").ExecuteReader())
|
||||
{
|
||||
while (r.Read())
|
||||
{
|
||||
list.Add($"{table} index {r.GetString(0)} {r.GetInt64(1)} {r.GetString(2)} {r.GetInt64(3)}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
private static void SetUserVersion(string path, int version)
|
||||
{
|
||||
using var connection = new SqliteConnection($"Data Source={path};Pooling=False");
|
||||
|
||||
Reference in new issue
Block a user