using Febe.Core.Domain;
using Febe.Data;
using Febe.Data.Stores;
using Febe.Tests.Support;
using Microsoft.Data.Sqlite;
using static Febe.Tests.Data.ExportWorld;
namespace Febe.Tests.Data;
/// The constraints of migration 0003 (spec §4.10, §8.3), written with raw SQL so the CHECKs answer alone.
[TestClass]
public sealed class ExportConstraintTests
{
private static readonly string[] ExportTables =
["export_destination", "export_account", "export_copy", "export_run", "export_item", "video_analysis", "media_conversion"];
private static readonly string Sha63 = Make.Sha(1)[1..];
private static readonly string Sha65 = Make.Sha(1) + "0";
[TestMethod]
public async Task UnknownValuesAreRejectedInEveryTable()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
var run = await InsertAsync(db, "export_run", w.RunRow());
await InsertAsync(db, "export_item", w.ItemRow(run));
await InsertAsync(db, "export_account", new Dictionary { ["account_id"] = w.Luca, ["enabled"] = 1L });
await InsertAsync(db, "video_analysis", AnalysisRow());
await InsertAsync(db, "media_conversion", w.ConversionRow());
await InsertAsync(db, "export_copy", w.CopyRow());
await RejectedAsync(db, "export_destination", DestinationRow(("scope", "Tutti")), "ambito sconosciuto");
await RejectedAsync(db, "export_destination", DestinationRow(("photo_format", "Mp4")), "formato video per le foto");
await RejectedAsync(db, "export_destination", DestinationRow(("video_format", "Jpg")), "formato foto per i video");
await RejectedAsync(db, "export_destination", DestinationRow(("content_types", -1L)), "tipi negativi");
await RejectedAsync(db, "export_account", new Dictionary { ["account_id"] = w.Marta, ["enabled"] = 2L }, "interruttore non booleano");
await RejectedAsync(db, "export_copy", w.CopyRow(("state", "Gone"), ("relative_path", "x/1.jpg")), "stato della copia");
await RejectedAsync(db, "export_copy", w.CopyRow(("variant", "Intero"), ("relative_path", "x/2.jpg")), "variante");
await RejectedAsync(db, "export_copy", w.CopyRow(("format", "Gif"), ("variant", "Converted"), ("copy_sha256", Make.Sha(2)), ("relative_path", "x/3.jpg")), "formato");
await RejectedAsync(db, "export_copy", w.CopyRow(("origin", "Copied"), ("account_id", w.Luca), ("media_id", w.LucaMedia), ("relative_path", "x/4.jpg")), "origine");
await RejectedAsync(db, "export_run", w.RunRow(("kind", "Export")), "tipo di lavoro");
await RejectedAsync(db, "export_run", w.RunRow(("origin", "Auto")), "origine del lavoro");
await RejectedAsync(db, "export_run", w.RunRow(("state", "Done")), "stato del lavoro");
await RejectedAsync(db, "export_item", w.ItemRow(run, ("state", "Done"), ("media_id", w.LucaMedia)), "stato del file");
await RejectedAsync(db, "export_item", w.ItemRow(run, ("variant", "Intero"), ("media_id", w.LucaMedia)), "variante del file");
await RejectedAsync(db, "export_item", w.ItemRow(run, ("format", "Gif"), ("variant", "Converted"), ("media_id", w.LucaMedia)), "formato del file");
await RejectedAsync(db, "video_analysis", AnalysisRow(("outcome", "Fermo"), ("sha256", Make.Sha(6))), "esito");
await RejectedAsync(db, "video_analysis", AnalysisRow(("algorithm", 0L), ("sha256", Make.Sha(6))), "algoritmo 0");
await RejectedAsync(db, "media_conversion", w.ConversionRow(("format", "Original"), ("media_id", w.LucaMedia)), "un convertito ha un altro formato");
await RejectedAsync(
db,
"media_conversion",
w.ConversionRow(("state", "Done"), ("media_id", w.LucaMedia), ("relative_path", "taggati/a.jpg.jpg"), ("bytes", 1L), ("sha256", Make.Sha(2)), ("converted_at", 0L)),
"stato della conversione");
}
[TestMethod]
public async Task Sha256MustHave64Characters()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
var run = await InsertAsync(db, "export_run", w.RunRow());
foreach (var bad in new[] { Sha63, Sha65 })
{
await RejectedAsync(db, "export_copy", w.CopyRow(("source_sha256", bad), ("state", "Failed"), ("relative_path", null), ("bytes", null), ("copy_sha256", null)), "source_sha256");
await RejectedAsync(db, "export_copy", w.CopyRow(("variant", "Converted"), ("format", "Jpg"), ("copy_sha256", bad)), "copy_sha256");
await RejectedAsync(db, "export_copy", w.CopyRow(("state", "Removed"), ("superseded_by_sha256", bad)), "superseded_by_sha256");
await RejectedAsync(db, "export_item", w.ItemRow(run, ("source_sha256", bad)), "export_item.source_sha256");
await RejectedAsync(db, "video_analysis", AnalysisRow(("sha256", bad)), "video_analysis.sha256");
await RejectedAsync(db, "media_conversion", w.ConversionRow(("source_sha256", bad)), "media_conversion.source_sha256");
await RejectedAsync(db, "media_conversion", w.ConversionRow(("sha256", bad)), "media_conversion.sha256");
}
}
[TestMethod]
public async Task VariantAndFormatGoTogether()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
var run = await InsertAsync(db, "export_run", w.RunRow());
await RejectedAsync(db, "export_copy", w.CopyRow(("format", "Jpg")), "intero in JPG");
await RejectedAsync(db, "export_copy", w.CopyRow(("variant", "Converted"), ("copy_sha256", Make.Sha(2))), "convertito in Originale");
await RejectedAsync(db, "export_copy", w.CopyRow(("variant", "Frame"), ("format", "Mp4"), ("frame_at_ms", 0L), ("copy_sha256", Make.Sha(2))), "fotogramma in MP4");
await RejectedAsync(db, "export_copy", w.CopyRow(("variant", "Frame"), ("format", "Jpg"), ("copy_sha256", Make.Sha(2))), "fotogramma senza istante");
await RejectedAsync(db, "export_copy", w.CopyRow(("frame_at_ms", 0L)), "intero con un istante");
await RejectedAsync(db, "export_copy", w.CopyRow(("copy_sha256", Make.Sha(2))), "intero con uno SHA-256 diverso dall'originale");
await RejectedAsync(db, "export_copy", w.CopyRow(("variant", "Converted"), ("format", "Jpg")), "convertito uguale all'originale: è un intero");
await RejectedAsync(db, "export_item", w.ItemRow(run, ("format", "Jpg")), "file intero in JPG");
await RejectedAsync(db, "export_item", w.ItemRow(run, ("variant", "Frame"), ("format", "Png")), "file fotogramma senza istante");
await InsertAsync(db, "export_copy", w.CopyRow(("variant", "Converted"), ("format", "Jpg"), ("copy_sha256", Make.Sha(2)), ("relative_path", "marta.demo/a.jpg")));
await InsertAsync(db, "export_copy", w.CopyRow(("variant", "Frame"), ("format", "Png"), ("frame_at_ms", 1000L), ("copy_sha256", Make.Sha(3)), ("relative_path", "marta.demo/a_t0m01s000.png")));
await InsertAsync(db, "export_item", w.ItemRow(run, ("variant", "Frame"), ("format", "WebpLossless"), ("frame_at_ms", 0L)));
}
[TestMethod]
public async Task EveryStateButFailedHadAFile()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
await RejectedAsync(db, "export_copy", w.CopyRow(("relative_path", null)), "copiato senza percorso");
await RejectedAsync(db, "export_copy", w.CopyRow(("bytes", null)), "copiato senza byte");
await RejectedAsync(db, "export_copy", w.CopyRow(("copy_sha256", null)), "copiato senza SHA-256 della copia");
await RejectedAsync(db, "export_copy", w.CopyRow(("state", "Removed"), ("relative_path", null)), "tolto senza percorso");
await RejectedAsync(db, "export_copy", w.CopyRow(("relative_path", "")), "percorso vuoto");
await InsertAsync(db, "export_copy", w.CopyRow(("state", "Failed"), ("relative_path", null), ("bytes", null), ("copy_sha256", null)));
}
[TestMethod]
public async Task SupersededNeedsTheFileThatTookItsPlace()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
await RejectedAsync(db, "export_copy", w.CopyRow(("state", "Superseded")), "superato senza il file nuovo");
await RejectedAsync(db, "export_copy", w.CopyRow(("superseded_by_sha256", Make.Sha(9))), "copiato con il file nuovo");
await RejectedAsync(db, "export_copy", w.CopyRow(("state", "Failed"), ("superseded_by_sha256", Make.Sha(9))), "non riuscito con il file nuovo");
await RejectedAsync(db, "export_copy", w.CopyRow(("state", "Superseded"), ("superseded_by_sha256", Make.Sha(1)), ("relative_path", "marta.demo/c.jpg")), "superata dal suo stesso originale");
await RejectedAsync(db, "export_copy", w.CopyRow(("state", "Removed"), ("superseded_by_sha256", Make.Sha(1))), "tolta e segnata con il suo stesso originale");
await InsertAsync(db, "export_copy", w.CopyRow(("state", "Removed"), ("superseded_by_sha256", Make.Sha(9))));
await InsertAsync(db, "export_copy", w.CopyRow(("state", "Superseded"), ("superseded_by_sha256", Make.Sha(9)), ("relative_path", "marta.demo/b.jpg")));
}
[TestMethod]
public async Task OneCurrentConversionPerFileAndFormat()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
var first = await InsertAsync(db, "media_conversion", w.ConversionRow());
await RejectedAsync(db, "media_conversion", w.ConversionRow(), "due conversioni in JPG in coda per lo stesso file");
await RejectedAsync(db, "media_conversion", w.ConversionRow(("state", "Failed")), "una non riuscita accanto a una in coda");
await RejectedAsync(db, "media_conversion", Converted(w, "Jpg", Make.Sha(2)), "una fatta accanto a una in coda");
await InsertAsync(db, "media_conversion", w.ConversionRow(("format", "Png")));
await InsertAsync(db, "media_conversion", w.ConversionRow(("media_id", w.LucaMedia)));
await ExecuteAsync(db, "UPDATE media_conversion SET state = 'Removed', relative_path = 'post/a.jpg.jpg', bytes = 1, sha256 = @h, converted_at = 0 WHERE id = @id", ("@id", first), ("@h", Make.Sha(2)));
var second = await InsertAsync(db, "media_conversion", Converted(w, "Jpg", Make.Sha(3)));
await ExecuteAsync(db, "UPDATE media_conversion SET state = 'Superseded' WHERE id = @id", ("@id", second));
await InsertAsync(db, "media_conversion", w.ConversionRow());
await RejectedAsync(db, "media_conversion", Converted(w, "WebpLossless", Make.Sha(1)), "un convertito uguale al suo originale");
await InsertAsync(db, "media_conversion", Converted(w, "WebpLossless", Make.Sha(4)));
}
private static Dictionary Converted(ExportWorld w, string format, string sha256) =>
w.ConversionRow(("format", format), ("state", "Converted"), ("relative_path", $"post/a.jpg.{format}"), ("bytes", 1L), ("sha256", sha256), ("converted_at", 0L));
[TestMethod]
public async Task DestinationsKeepTheirRules()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
await RejectedAsync(db, "export_destination", DestinationRow(("removed_at", null)), "una seconda cartella generale in uso");
await RejectedAsync(db, "export_destination", DestinationRow(("account_id", w.Marta)), "la cartella generale non ha account");
await RejectedAsync(db, "export_destination", DestinationRow(("removed_account_username", "marta.demo")), "la cartella generale non ha nome d'account");
await RejectedAsync(db, "export_destination", DestinationRow(("root_path", null)), "senza cartella");
await RejectedAsync(db, "export_destination", DestinationRow(("root_path", "")), "cartella vuota");
await RejectedAsync(db, "export_destination", DestinationRow(("content_types", null)), "senza tipi");
await RejectedAsync(db, "export_destination", DestinationRow(("scope", "Account"), ("account_id", w.Marta), ("removed_at", null)), "una seconda cartella in uso per un account");
await RejectedAsync(db, "export_destination", DestinationRow(("scope", "Account")), "una cartella d'account senza account né nome");
await RejectedAsync(db, "export_destination", DestinationRow(("removed_at", null), ("scope", "Account"), ("account_id", w.Luca), ("automatic_since", 5L)), "«Solo i nuovi» senza «Automatica»");
await RejectedAsync(db, "export_destination", DestinationRow(("automatic", 1L)), "una destinazione ritirata non è automatica");
await ExecuteAsync(db, "UPDATE export_destination SET removed_at = 1 WHERE id = @id", ("@id", w.General));
await InsertAsync(db, "export_destination", DestinationRow(("removed_at", null)));
await ExecuteAsync(db, "UPDATE export_destination SET removed_at = 1 WHERE id = @id", ("@id", w.Own));
await InsertAsync(db, "export_destination", DestinationRow(("scope", "Account"), ("account_id", w.Marta), ("removed_at", null), ("automatic", 1L), ("automatic_since", 5L)));
(string, object?)[] orphan = [("scope", "Account"), ("removed_account_username", "vecchio.demo"), ("removed_at", null)];
await RejectedAsync(db, "export_destination", DestinationRow([.. orphan, ("automatic", 1L)]), "una cartella senza il suo account non è automatica");
await InsertAsync(db, "export_destination", DestinationRow(orphan));
}
[TestMethod]
public async Task OneCurrentCopyPerIdentity()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
var first = await InsertAsync(db, "export_copy", w.CopyRow(("relative_path", "marta.demo/1.jpg")));
await RejectedAsync(db, "export_copy", w.CopyRow(("relative_path", "marta.demo/2.jpg")), "la stessa identità copiata due volte");
await RejectedAsync(db, "export_copy", w.CopyRow(("state", "Failed"), ("relative_path", null), ("bytes", null), ("copy_sha256", null)), "non riuscita accanto a una copiata");
await ExecuteAsync(db, "UPDATE export_copy SET state = 'Removed' WHERE id = @id", ("@id", first));
var second = await InsertAsync(db, "export_copy", w.CopyRow(("relative_path", "marta.demo/2.jpg")));
await ExecuteAsync(db, "UPDATE export_copy SET state = 'Superseded', superseded_by_sha256 = @h WHERE id = @id", ("@id", second), ("@h", Make.Sha(9)));
await InsertAsync(db, "export_copy", w.CopyRow(("relative_path", "marta.demo/3.jpg")));
await InsertAsync(db, "export_copy", w.CopyRow(("account_id", w.Luca), ("media_id", w.LucaMedia), ("relative_path", "luca.demo/1.jpg")));
await InsertAsync(db, "export_copy", w.CopyRow(("variant", "Converted"), ("format", "Png"), ("copy_sha256", Make.Sha(2)), ("relative_path", "marta.demo/1.png")));
await InsertAsync(db, "export_copy", w.CopyRow(("variant", "Frame"), ("format", "Jpg"), ("frame_at_ms", 0L), ("copy_sha256", Make.Sha(3)), ("relative_path", "marta.demo/f0.jpg")));
await InsertAsync(db, "export_copy", w.CopyRow(("variant", "Frame"), ("format", "Jpg"), ("frame_at_ms", 1000L), ("copy_sha256", Make.Sha(4)), ("relative_path", "marta.demo/f1.jpg")));
}
[TestMethod]
public async Task APathIsNeverRecordedTwice()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
var first = await InsertAsync(db, "export_copy", w.CopyRow(("relative_path", "marta.demo/x.jpg")));
await RejectedAsync(db, "export_copy", w.CopyRow(("account_id", w.Luca), ("relative_path", "marta.demo/x.jpg")), "due copie sullo stesso file");
await RejectedAsync(db, "export_copy", w.CopyRow(("account_id", w.Luca), ("relative_path", "Marta.Demo/X.JPG")), "lo stesso file su Windows, maiuscole diverse");
await RejectedAsync(db, "export_copy", w.CopyRow(("account_id", w.Luca), ("state", "Superseded"), ("superseded_by_sha256", Make.Sha(9)), ("relative_path", "marta.demo/x.jpg")), "superata sullo stesso file");
await InsertAsync(db, "export_copy", w.CopyRow(("destination_id", w.Own), ("relative_path", "marta.demo/x.jpg")));
await ExecuteAsync(db, "UPDATE export_copy SET state = 'Removed' WHERE id = @id", ("@id", first));
await InsertAsync(db, "export_copy", w.CopyRow(("account_id", w.Luca), ("relative_path", "marta.demo/x.jpg")));
}
[TestMethod]
public async Task RecordsCannotBeDeletedFromUnderTheirCopies()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
await InsertAsync(db, "export_copy", w.CopyRow());
await InsertAsync(db, "export_run", w.RunRow(("destination_id", w.Own)));
var conversion = await InsertAsync(db, "media_conversion", w.ConversionRow());
var withCopy = await Assert.ThrowsExactlyAsync(() => ExecuteAsync(db, "DELETE FROM export_destination WHERE id = @id", ("@id", w.General)));
Assert.AreEqual(19, withCopy.SqliteErrorCode, "una destinazione con copie si ritira, non si cancella");
var withRun = await Assert.ThrowsExactlyAsync(() => ExecuteAsync(db, "DELETE FROM export_destination WHERE id = @id", ("@id", w.Own)));
Assert.AreEqual(19, withRun.SqliteErrorCode, "una destinazione con lavori si ritira, non si cancella");
var entry = await Assert.ThrowsExactlyAsync(() => db.Entries.RemoveAsync(w.MartaEntry));
Assert.AreEqual(19, entry.SqliteErrorCode, "un file con un convertito registrato non si cancella");
Assert.IsNotNull(await db.Entries.GetAsync(w.MartaEntry));
Assert.IsNotNull(await db.Media.GetAsync(w.MartaMedia));
Assert.IsNotNull(await db.Conversions.GetAsync(conversion));
var account = await Assert.ThrowsExactlyAsync(() => db.Accounts.DeleteAsync(w.Marta));
Assert.AreEqual(19, account.SqliteErrorCode, "anche attraverso la rimozione dell'account");
Assert.IsNotNull(await db.Accounts.GetAsync(w.Marta));
Assert.IsNotNull(await db.Conversions.GetAsync(conversion));
}
[TestMethod]
public async Task EntryRemovalKeepsCopiesBySha256()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
var copy = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg"));
var run = await db.Exports.CreateRunAsync(new ExportRun { DestinationId = w.General, StartedAt = Make.T0 });
await db.Exports.AddItemsAsync([new ExportItem { RunId = run.Id, MediaId = w.MartaMedia, AccountId = w.Marta, SourceSha256 = Make.Sha(1) }]);
await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1), 1, VideoAnalysisOutcome.Moving, Make.T0));
await db.Entries.RemoveAsync(w.MartaEntry);
var kept = await db.Exports.GetCopyAsync(copy.Id);
Assert.IsNotNull(kept);
Assert.IsNull(kept.MediaId);
Assert.AreEqual(Make.Sha(1), kept.SourceSha256);
Assert.AreEqual(w.Marta, kept.AccountId);
Assert.Contains(kept, await db.Exports.ListCopiesBySha256Async(Make.Sha(1)));
var item = (await db.Exports.ListItemsAsync(new() { RunId = run.Id })).Single();
Assert.IsNull(item.MediaId);
Assert.AreEqual(Make.Sha(1), item.SourceSha256);
Assert.IsNotNull(await db.VideoAnalyses.GetAsync(Make.Sha(1)));
Assert.AreEqual(0L, await ForeignKeyProblemsAsync(db));
}
[TestMethod]
public async Task AccountRemovalKeepsItsDestination()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
await db.Exports.RetireDestinationAsync(w.Own, Make.T0.AddDays(1));
var current = await db.Exports.AddDestinationAsync(Destination(ExportScope.Account, w.Marta, @"H:\Marta") with { Automatic = true, AutomaticSince = Make.T0.AddDays(2) });
await db.Exports.SetAccountExportEnabledAsync(w.Marta, true);
var martaCopy = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg"));
var lucaCopy = await db.Exports.AddCopyAsync(w.WholeCopy("luca.demo/a.jpg", account: w.Luca, media: w.LucaMedia));
await db.Accounts.DeleteAsync(w.Marta);
await db.Accounts.DeleteAsync(w.Luca);
foreach (var id in new[] { w.Own, current.Id })
{
var destination = (await db.Exports.GetDestinationAsync(id))!;
Assert.IsNull(destination.AccountId);
Assert.AreEqual("marta.demo", destination.RemovedAccountUsername);
Assert.IsTrue(destination.IsOrphan);
}
var disabled = (await db.Exports.GetDestinationAsync(current.Id))!;
Assert.IsNull(disabled.RemovedAt, "la cartella in uso resta in uso, senza account");
Assert.IsFalse(disabled.Automatic, "rimuovere l'account la disattiva");
Assert.IsNull(disabled.AutomaticSince, "e dimentica «Solo i nuovi»");
Assert.IsFalse((await db.Exports.ListDestinationsAsync()).Any(d => d.Automatic));
Assert.IsNull(await db.Exports.GetAccountExportEnabledAsync(w.Marta));
Assert.AreEqual(0L, await ScalarAsync(db, "SELECT COUNT(*) FROM export_account"));
var general = (await db.Exports.GetGeneralDestinationAsync())!;
Assert.AreEqual(w.General, general.Id);
Assert.IsNull(general.AccountId);
Assert.IsNull(general.RemovedAccountUsername);
// Two orphan copies with the same identity but for the account (now NULL): both kept.
var copies = await db.Exports.ListCopiesBySha256Async(Make.Sha(1));
CollectionAssert.AreEquivalent(new[] { martaCopy.Id, lucaCopy.Id }, copies.Select(c => c.Id).ToArray());
Assert.IsTrue(copies.All(c => c.AccountId is null && c.MediaId is null && c.Identity is null));
Assert.AreEqual(0L, await ForeignKeyProblemsAsync(db));
}
[TestMethod]
public async Task RawAccountDeleteWithoutUserNameFails()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
var error = await Assert.ThrowsExactlyAsync(() => ExecuteAsync(db, "DELETE FROM account WHERE id = @id", ("@id", w.Marta)));
Assert.AreEqual(19, error.SqliteErrorCode, "il CHECK vale anche sull'azione SET NULL");
Assert.IsNotNull(await db.Accounts.GetAsync(w.Marta));
Assert.AreEqual(w.Marta, (await db.Exports.GetDestinationAsync(w.Own))!.AccountId);
}
[TestMethod]
public async Task RemovedAccountComesBack()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
var ownCopy = await db.Exports.AddCopyAsync(w.WholeCopy("a.jpg", destination: w.Own));
var generalCopy = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg"));
await db.Exports.UpdateDestinationAsync((await db.Exports.GetDestinationAsync(w.Own))! with { Automatic = true, AutomaticSince = Make.T0.AddDays(1) });
await db.Accounts.DeleteAsync(w.Marta);
var orphan = (await db.Exports.GetDestinationAsync(w.Own))!;
Assert.IsFalse(orphan.Automatic, "rimuovere l'account la disattiva");
Assert.IsNull(orphan.AutomaticSince);
await Assert.ThrowsExactlyAsync(() => db.Exports.UpdateDestinationAsync(orphan with { Automatic = true }), "senza account non si accende");
var again = await db.Accounts.AddAsync(Make.Account("marta.demo", "100"));
await db.Exports.AttachDestinationAsync(w.Own, again.Id);
var own = (await db.Exports.GetDestinationAsync(w.Own))!;
Assert.AreEqual(again.Id, own.AccountId);
Assert.IsNull(own.RemovedAccountUsername);
Assert.IsFalse(own.Automatic, "ridata all'account, «Automatica» resta spenta: riaccenderla chiede di nuovo");
Assert.IsNull(own.AutomaticSince, "il vecchio «Solo i nuovi» non torna");
await db.Exports.UpdateDestinationAsync(own with { Automatic = true, AutomaticSince = Make.T0.AddDays(3) });
Assert.AreEqual(Make.T0.AddDays(3), (await db.Exports.GetDestinationAsync(w.Own))!.AutomaticSince);
Assert.AreEqual(own.Id, (await db.Exports.GetAccountDestinationAsync(again.Id))!.Id);
Assert.AreEqual(again.Id, (await db.Exports.GetCopyAsync(ownCopy.Id))!.AccountId);
Assert.IsNull((await db.Exports.GetCopyAsync(generalCopy.Id))!.AccountId, "le copie di altre destinazioni restano orfane finché non si adottano");
var relinked = await db.Exports.RelinkOrphanCopyAsync(generalCopy.Id, again.Id, null, Make.T0.AddDays(2));
Assert.AreEqual(again.Id, relinked.AccountId);
Assert.AreEqual(Make.T0.AddDays(2), relinked.StateChangedAt);
Assert.AreEqual(generalCopy.Id, (await db.Exports.FindCopyByPathAsync(w.General, "marta.demo/a.jpg"))!.Id);
Assert.AreEqual(1L, await ScalarAsync(db, "SELECT COUNT(*) FROM export_copy WHERE destination_id = @d AND relative_path = 'marta.demo/a.jpg'", ("@d", w.General)));
Assert.AreEqual(0L, await ForeignKeyProblemsAsync(db));
await Assert.ThrowsExactlyAsync(() => db.Exports.AttachDestinationAsync(w.Own, again.Id));
await Assert.ThrowsExactlyAsync(() => db.Exports.AttachDestinationAsync(w.General, again.Id));
await Assert.ThrowsExactlyAsync(() => db.Exports.RelinkOrphanCopyAsync(generalCopy.Id, again.Id, null, Make.T0));
await Assert.ThrowsExactlyAsync(() => db.Exports.RelinkOrphanCopyAsync(9999, again.Id, null, Make.T0));
}
[TestMethod]
public async Task DestinationRetirementKeepsRecords()
{
using var temp = new TempFolder();
var root = temp.Combine("copie");
Directory.CreateDirectory(Path.Combine(root, "marta.demo"));
var file = Path.Combine(root, "marta.demo", "a.jpg");
await File.WriteAllBytesAsync(file, [1, 2, 3]);
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db, root);
var copy = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg"));
var run = await db.Exports.CreateRunAsync(new ExportRun { DestinationId = w.General, StartedAt = Make.T0, State = ExportRunState.Completed });
await db.Exports.AddItemsAsync([new ExportItem { RunId = run.Id, MediaId = w.MartaMedia, AccountId = w.Marta, SourceSha256 = Make.Sha(1), State = ExportItemState.Copied, CopyId = copy.Id }]);
await db.Exports.RetireDestinationAsync(w.General, Make.T0.AddDays(1));
Assert.IsNull(await db.Exports.GetGeneralDestinationAsync());
Assert.AreEqual(Make.T0.AddDays(1), (await db.Exports.GetDestinationAsync(w.General))!.RemovedAt);
Assert.IsNotNull(await db.Exports.GetCopyAsync(copy.Id));
Assert.IsNotNull(await db.Exports.GetRunAsync(run.Id));
Assert.HasCount(1, await db.Exports.ListItemsAsync(new() { RunId = run.Id }));
Assert.IsTrue(File.Exists(file), "togliere una destinazione non tocca i file già copiati");
var next = await db.Exports.AddDestinationAsync(Destination(ExportScope.General, null, temp.Combine("altre")));
Assert.AreEqual(next.Id, (await db.Exports.GetGeneralDestinationAsync())!.Id);
}
///
/// Every foreign key of the new tables has an index usable for child = ?: the plan of that lookup is a SEARCH,
/// never a SCAN (an index merely starting with the column is not enough when it is partial on another condition).
///
[TestMethod]
public async Task ExportForeignKeysHaveAnIndex()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var checkedKeys = 0;
foreach (var table in ExportTables)
{
var columns = await db.ReadAsync(
c =>
{
using var r = c.Command($"SELECT \"from\" FROM pragma_foreign_key_list('{table}')").ExecuteReader();
var list = new List();
while (r.Read())
{
list.Add(r.GetString(0));
}
return list;
},
default);
foreach (var column in columns)
{
var plan = await PlanAsync(db, $"SELECT 1 FROM {table} WHERE {column} = 1");
Assert.Contains("SEARCH", plan, $"{table}.{column}: {plan}");
Assert.DoesNotContain("SCAN", plan, $"{table}.{column}: {plan}");
checkedKeys++;
}
}
Assert.AreEqual(11, checkedKeys, "le chiavi esterne delle tabelle nuove");
}
///
/// The lookups of the stores read their index, with and without ANALYZE statistics: a SEARCH, no SCAN and no
/// temporary B-tree (but the ORDER BY of the handful of rows of a SHA-256). Index names only where the choice is the point.
///
[TestMethod]
public async Task ExportLookupsUseTheirIndex()
{
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
await FillAsync(db, w);
// Without statistics the planner's choice is the point for the «Copie» set shape and the latest row of an identity.
var setShape = await PlanAsync(
db,
"""
SELECT m.entry_id FROM export_copy c JOIN media m ON m.sha256 = c.source_sha256
JOIN entry x ON x.id = m.entry_id AND x.account_id = c.account_id
WHERE c.destination_id = @d AND c.state = 'Copied'
""",
("@d", w.General));
Assert.Contains("USING COVERING INDEX ix_export_copy_destination (destination_id=? AND state=?)", setShape, setShape);
var latest = await PlanAsync(db, ExportStore.LatestCopySql, Identity(w));
Assert.Contains("ix_export_copy_sha256", latest, latest);
Assert.DoesNotContain("TEMP B-TREE", latest, latest);
await CheckLookupsAsync(db, w, "senza ANALYZE");
await db.WriteAsync(x => x.Command("ANALYZE").ExecuteNonQuery(), default);
await CheckLookupsAsync(db, w, "con ANALYZE");
}
private static async Task CheckLookupsAsync(FebeDatabase db, ExportWorld w, string when)
{
var run = await ScalarAsync(db, "SELECT MIN(id) FROM export_run");
var lookups = new (string Name, string Sql, (string, object?)[] Parameters, bool SortAllowed)[]
{
("FindCurrentCopyAsync", ExportStore.CurrentCopySql, Identity(w), false),
("FindLatestCopyAsync", ExportStore.LatestCopySql, Identity(w), false),
("FindCopyByPathAsync", ExportStore.CopyByPathSql, [("@d", w.General), ("@p", "marta.demo/17.jpg")], false),
("ListCopiesBySha256Async", ExportStore.CopiesBySha256Sql, [("@h", Make.Sha(17))], true),
("ListCopiesAsync", ExportStore.CopiesOfDestinationSql(false), [("@d", w.General), ("@after", 0L), ("@limit", 500L)], false),
("ListCopiesAsync (stato)", ExportStore.CopiesOfDestinationSql(true), [("@d", w.General), ("@s", "Copied"), ("@after", 0L), ("@limit", 500L)], false),
("CountCopiesAsync", ExportStore.CountCopiesSql, [("@d", w.General)], false),
("ListUnfinishedRunsAsync", ExportStore.UnfinishedRunsSql, [], false),
("ListItemsAsync", ExportStore.ItemsOfRunSql(false), [("@r", run), ("@after", 0L), ("@limit", 500L)], false),
("ListItemsAsync (stato)", ExportStore.ItemsOfRunSql(true), [("@r", run), ("@s", "Pending"), ("@after", 0L), ("@limit", 500L)], false),
("ListPendingAsync", MediaConversionStore.PendingSql, [("@after", 0L), ("@limit", 500L)], false),
};
var problems = new List();
foreach (var (name, sql, parameters, sortAllowed) in lookups)
{
var plan = await PlanAsync(db, sql, parameters);
var withoutAllowedSort = sortAllowed ? plan.Replace("USE TEMP B-TREE FOR ORDER BY", string.Empty, StringComparison.Ordinal) : plan;
if (!plan.Contains("SEARCH", StringComparison.Ordinal) || plan.Contains("SCAN", StringComparison.Ordinal)
|| withoutAllowedSort.Contains("TEMP B-TREE", StringComparison.Ordinal))
{
problems.Add($"{name}: {plan}");
}
}
Assert.IsEmpty(problems, $"{when}: {string.Join(" || ", problems)}");
}
private static (string, object?)[] Identity(ExportWorld w) =>
[("@d", w.General), ("@h", Make.Sha(17)), ("@a", w.Marta), ("@v", "Whole"), ("@f", "Original"), ("@fr", -1L)];
/// About 1,000 copies over three destinations and two accounts, three jobs with their items, 300 finished jobs, and a queue of conversions.
private static Task FillAsync(FebeDatabase db, ExportWorld w) =>
db.WriteAsync(
x =>
{
var destinations = new[] { w.General, w.Own, InsertDestination(x, w.Luca) };
var copied = x.Command("""
INSERT INTO export_copy (destination_id, account_id, source_sha256, variant, format, state, superseded_by_sha256,
relative_path, bytes, copy_sha256, copied_at)
VALUES (@d, @a, @h, 'Whole', 'Original', @s, @by, @p, 10, @h, 0)
""");
var failed = x.Command("""
INSERT INTO export_copy (destination_id, account_id, source_sha256, variant, format, state, copied_at)
VALUES (@d, @a, @h, 'Whole', 'Original', 'Failed', 0)
""");
for (var i = 0; i < 1000; i++)
{
var destination = destinations[i % 3];
var account = i % 2 == 0 ? w.Marta : w.Luca;
var state = (i % 10) switch { 7 => "Removed", 8 => "Superseded", _ => "Copied" };
if (i % 10 == 9)
{
failed.With("@d", destination).With("@a", account).With("@h", Make.Sha(i)).ExecuteNonQuery();
continue;
}
copied.With("@d", destination).With("@a", account).With("@h", Make.Sha(i)).With("@s", state)
.With("@by", state == "Superseded" ? Make.Sha(5000 + i) : null)
.With("@p", $"{(account == w.Marta ? "marta.demo" : "luca.demo")}/{i}.jpg").ExecuteNonQuery();
}
var run = x.Command("INSERT INTO export_run (destination_id, kind, origin, state, started_at) VALUES (@d, 'Copy', 'Manual', @s, 0)");
var item = x.Command("""
INSERT INTO export_item (run_id, media_id, account_id, source_sha256, variant, format, frame_at_ms, state)
VALUES (@r, NULL, @a, @h, 'Frame', 'Jpg', @f, @s)
""");
foreach (var state in new[] { "Completed", "Running", "Interrupted" })
{
run.With("@d", w.General).With("@s", state).ExecuteNonQuery();
var runId = x.LastInsertRowId();
for (var i = 0; i < 200; i++)
{
item.With("@r", runId).With("@a", w.Marta).With("@h", Make.Sha(i)).With("@f", (long)i * 1000).With("@s", i % 3 == 0 ? "Pending" : "Copied").ExecuteNonQuery();
}
}
// The finished jobs of months of use: the unfinished ones are a handful among many.
for (var i = 0; i < 300; i++)
{
run.With("@d", w.General).With("@s", i % 5 == 0 ? "Cancelled" : "Completed").ExecuteNonQuery();
}
var entry = x.Command("INSERT INTO entry (account_id, kind, published_at, state, provenance, discovered_at) VALUES (@a, 'Post', 0, 'Downloaded', 'Imported', 0)");
var media = x.Command("INSERT INTO media (entry_id, position, kind, state, sha256) VALUES (@e, 1, 'Photo', 'Imported', @h)");
var conversion = x.Command("INSERT INTO media_conversion (media_id, format, state, source_sha256, created_at) VALUES (@m, @f, @s, @h, 0)");
for (var i = 0; i < 100; i++)
{
entry.With("@a", w.Marta).ExecuteNonQuery();
media.With("@e", x.LastInsertRowId()).With("@h", Make.Sha(9000 + i)).ExecuteNonQuery();
var mediaId = x.LastInsertRowId();
foreach (var format in new[] { "Jpg", "Png" })
{
conversion.With("@m", mediaId).With("@f", format).With("@s", i % 4 == 0 ? "Pending" : "Failed").With("@h", Make.Sha(9000 + i)).ExecuteNonQuery();
}
}
},
default);
private static long InsertDestination(WriteContext x, long account)
{
x.Command("INSERT INTO export_destination (scope, account_id, root_path, content_types, created_at) VALUES ('Account', @a, 'K:/Luca', 63, 0)")
.With("@a", account).ExecuteNonQuery();
return x.LastInsertRowId();
}
private static Task PlanAsync(FebeDatabase db, string sql, params (string Name, object? Value)[] parameters) =>
db.ReadAsync(
c =>
{
var command = c.Command("EXPLAIN QUERY PLAN " + sql);
foreach (var (name, value) in parameters)
{
command.With(name, value);
}
using var r = command.ExecuteReader();
var lines = new List();
while (r.Read())
{
lines.Add(r.GetString(3));
}
return string.Join(" | ", lines);
},
default);
}