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>
403 lines
18 KiB
C#
403 lines
18 KiB
C#
using Febe.Data;
|
|
using Febe.Tests.Support;
|
|
using Microsoft.Data.Sqlite;
|
|
|
|
namespace Febe.Tests.Data;
|
|
|
|
[TestClass]
|
|
public sealed class MigrationTests
|
|
{
|
|
private static readonly string[] Tables =
|
|
[
|
|
"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()
|
|
{
|
|
var migrations = MigrationRunner.LoadEmbedded();
|
|
Assert.IsNotEmpty(migrations);
|
|
for (var i = 0; i < migrations.Count; i++)
|
|
{
|
|
Assert.AreEqual(i + 1, migrations[i].Version);
|
|
}
|
|
|
|
Assert.AreEqual("schema", migrations[0].Name);
|
|
Assert.AreEqual("ordine_scaricamento", migrations[1].Name);
|
|
Assert.AreEqual("esportazione", migrations[2].Name);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void NumberingWithGapsIsRefused()
|
|
{
|
|
Assert.ThrowsExactly<DatabaseMigrationException>(() => MigrationRunner.Validate([new Migration(1, "a", "SELECT 1"), new Migration(3, "c", "SELECT 1")]));
|
|
Assert.ThrowsExactly<DatabaseMigrationException>(() => MigrationRunner.Validate([new Migration(1, "a", "SELECT 1"), new Migration(1, "b", "SELECT 1")]));
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task FreshDatabaseHasEveryTableAndTheLatestVersion()
|
|
{
|
|
using var temp = new TempFolder();
|
|
await using var db = await TestDatabase.OpenAsync(temp);
|
|
|
|
Assert.AreEqual(MigrationRunner.LoadEmbedded().Count, db.SchemaVersion);
|
|
Assert.AreEqual(Path.Combine(temp.Combine("dati"), FebeDatabase.FileName), db.DatabasePath);
|
|
var tables = await db.ReadAsync(
|
|
c =>
|
|
{
|
|
using var r = c.Command("SELECT name FROM sqlite_master WHERE type = 'table'").ExecuteReader();
|
|
var names = new List<string>();
|
|
while (r.Read())
|
|
{
|
|
names.Add(r.GetString(0));
|
|
}
|
|
|
|
return names;
|
|
},
|
|
default);
|
|
foreach (var table in Tables)
|
|
{
|
|
Assert.Contains(table, tables);
|
|
}
|
|
|
|
var version = await db.ReadAsync(c => c.Command("PRAGMA user_version").ScalarInt64(), default);
|
|
Assert.AreEqual((long)db.SchemaVersion, version);
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task DatabaseUsesWalForeignKeysAndBusyTimeout()
|
|
{
|
|
using var temp = new TempFolder();
|
|
await using var db = await TestDatabase.OpenAsync(temp);
|
|
|
|
var mode = await db.ReadAsync(c => (string)c.Command("PRAGMA journal_mode").ExecuteScalar()!, default);
|
|
Assert.AreEqual("wal", mode);
|
|
var foreignKeys = await db.WriteAsync(w => w.Command("PRAGMA foreign_keys").ScalarInt64(), default);
|
|
Assert.AreEqual(1L, foreignKeys);
|
|
var timeout = await db.WriteAsync(w => w.Command("PRAGMA busy_timeout").ScalarInt64(), default);
|
|
Assert.IsGreaterThanOrEqualTo(5000L, timeout);
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task ReopeningKeepsDataAndDoesNotRerunMigrations()
|
|
{
|
|
using var temp = new TempFolder();
|
|
await using (var db = await TestDatabase.OpenAsync(temp))
|
|
{
|
|
await db.Settings.SetAsync("prova", "1");
|
|
}
|
|
|
|
await using (var db = await TestDatabase.OpenAsync(temp))
|
|
{
|
|
Assert.AreEqual("1", await db.Settings.GetAsync("prova"));
|
|
Assert.AreEqual(MigrationRunner.LoadEmbedded().Count, db.SchemaVersion);
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task NewerDatabaseIsRefusedAndLeftUntouched()
|
|
{
|
|
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");
|
|
}
|
|
|
|
SetUserVersion(path, 99);
|
|
var error = await Assert.ThrowsExactlyAsync<DatabaseMigrationException>(() => FebeDatabase.OpenFileAsync(path));
|
|
Assert.Contains("più recente", error.Message);
|
|
Assert.AreEqual(99L, GetUserVersion(path));
|
|
}
|
|
|
|
[TestMethod]
|
|
public void FailingMigrationRollsBackEntirely()
|
|
{
|
|
using var temp = new TempFolder();
|
|
var path = temp.Combine("dati", FebeDatabase.FileName);
|
|
var good = MigrationRunner.LoadEmbedded();
|
|
var broken = good.Append(new Migration(good.Count + 1, "rotta", "CREATE TABLE extra (id INTEGER); INSERT INTO nowhere VALUES (1);")).ToList();
|
|
|
|
Assert.ThrowsExactly<DatabaseMigrationException>(() => FebeDatabase.Open(path, broken));
|
|
|
|
Assert.AreEqual((long)good.Count, GetUserVersion(path));
|
|
using var connection = new SqliteConnection($"Data Source={path};Pooling=False");
|
|
connection.Open();
|
|
Assert.AreEqual(0L, connection.Command("SELECT COUNT(*) FROM sqlite_master WHERE name = 'extra'").ScalarInt64());
|
|
}
|
|
|
|
[TestMethod]
|
|
public void MigrationAddingDataAppliesOnTopOfTheSchema()
|
|
{
|
|
using var temp = new TempFolder();
|
|
var path = temp.Combine("dati", FebeDatabase.FileName);
|
|
var good = MigrationRunner.LoadEmbedded();
|
|
var next = good.Append(new Migration(good.Count + 1, "dati", "INSERT INTO setting (key, value) VALUES ('migrata', 'si');")).ToList();
|
|
|
|
var db = FebeDatabase.Open(path, next);
|
|
try
|
|
{
|
|
Assert.AreEqual(good.Count + 1, db.SchemaVersion);
|
|
Assert.AreEqual("si", db.Settings.GetAsync("migrata").GetAwaiter().GetResult());
|
|
}
|
|
finally
|
|
{
|
|
db.DisposeAsync().AsTask().GetAwaiter().GetResult();
|
|
}
|
|
}
|
|
|
|
[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");
|
|
connection.Open();
|
|
connection.Command($"PRAGMA user_version = {version}").ExecuteNonQuery();
|
|
}
|
|
|
|
private static long GetUserVersion(string path)
|
|
{
|
|
using var connection = new SqliteConnection($"Data Source={path};Pooling=False");
|
|
connection.Open();
|
|
return connection.Command("PRAGMA user_version").ScalarInt64();
|
|
}
|
|
}
|