diff --git a/src/Febe.Core/Domain/Export.cs b/src/Febe.Core/Domain/Export.cs index 0f66d94..a8e679b 100644 --- a/src/Febe.Core/Domain/Export.cs +++ b/src/Febe.Core/Domain/Export.cs @@ -343,8 +343,47 @@ public sealed record ExportItem public string? LastError { get; init; } } -/// Outcome of the still-video analysis of one algorithm for one SHA-256 (spec §8.3 video_analysis). -public sealed record VideoAnalysis(string Sha256, int Algorithm, VideoAnalysisOutcome Outcome, DateTimeOffset AnalyzedAt); +/// +/// Outcome of the still-video analysis of one algorithm for one SHA-256 (spec §8.3 video_analysis, migration +/// 0005 of tappa E4). is the shown instant of the frame «Salva il fotogramma» saves: set for +/// and only for it. says why, as codes of +/// separated by spaces: always set for . +/// +public sealed record VideoAnalysis( + string Sha256, + int Algorithm, + VideoAnalysisOutcome Outcome, + DateTimeOffset AnalyzedAt, + TimeSpan? FrameAt = null, + string? Note = null); + +/// +/// The codes of video_analysis.note (tappa E4), English, separated by spaces like export_item.note. They +/// say why a video is «Non analizzabile». +/// +public static class VideoAnalysisNotes +{ + /// The video has no frames Febe can decode (codec, profile or container outside spec §3, damaged headers). + public const string FrameNotAvailable = "FrameNotAvailable"; + + /// The video has more than one frame and no known duration. + public const string DurationUnknown = "DurationUnknown"; + + /// The frames of the video cannot be read (a damaged or truncated file). + public const string Unreadable = "Unreadable"; + + /// The analysis took longer than its time limit (only an analysis from a selection stores it). + public const string TooSlow = "TooSlow"; + + /// Every frame looked at is black or nearly black (answer 42 of Alberto, 29 November 2026). + public const string AllDark = "AllDark"; + + /// Every frame looked at is all of one single colour, not dark (answer 42 of Alberto, 29 November 2026). + public const string SingleColor = "SingleColor"; + + /// Every code of algorithm 1, in the order above. + public static IReadOnlyList All { get; } = [FrameNotAvailable, DurationUnknown, Unreadable, TooSlow, AllDark, SingleColor]; +} /// /// A converted file added to an entry by the conversion for the library (spec §4.10, §8.3 media_conversion), diff --git a/src/Febe.Core/Storage/IVideoAnalysisStore.cs b/src/Febe.Core/Storage/IVideoAnalysisStore.cs index 129ae4d..a8bb317 100644 --- a/src/Febe.Core/Storage/IVideoAnalysisStore.cs +++ b/src/Febe.Core/Storage/IVideoAnalysisStore.cs @@ -4,7 +4,8 @@ namespace Febe.Core.Storage; /// /// Outcomes of «È un video fermo?» by SHA-256 of the video and number of the algorithm (spec §4.10, §8.3 -/// video_analysis). No link to the library: an outcome outlives deletion and re-import of the same file. +/// video_analysis, columns frame_at_ms and note from migration 0005). No link to the library: an +/// outcome outlives deletion and re-import of the same file. /// public interface IVideoAnalysisStore { @@ -14,6 +15,11 @@ public interface IVideoAnalysisStore /// The analysis with the highest algorithm number for each SHA-256 that has one, keyed by lower-case SHA-256. Task> GetManyAsync(IReadOnlyCollection sha256s, CancellationToken ct = default); - /// Stores (or replaces) the outcome of one algorithm for one SHA-256. + /// + /// Stores (or replaces) the outcome of one algorithm for one SHA-256, with the instant of its frame and its note. + /// Throws for a still video without an instant (or before the start), an instant on + /// another outcome, a note that is not codes separated by spaces, or a «Non analizzabile» without a note. The instant + /// is kept in whole milliseconds. + /// Task SetAsync(VideoAnalysis analysis, CancellationToken ct = default); } diff --git a/src/Febe.Data/Migrations/0005_video_fermi.sql b/src/Febe.Data/Migrations/0005_video_fermi.sql new file mode 100644 index 0000000..28b0b45 --- /dev/null +++ b/src/Febe.Data/Migrations/0005_video_fermi.sql @@ -0,0 +1,27 @@ +-- Febe, schema version 5: «Video fermi» (tappa E4 of 0.3.0, issue #58; spec §4.10, §8.3). +-- Run by the migration runner inside a transaction; PRAGMA user_version is set by the runner. +-- Two columns and one index on video_analysis: no other table, column or index changes, and no data of another table. + +-- No version of Febe before tappa E4 wrote video_analysis, so the table is empty here. SQLite tests the CHECKs of a new +-- column against the rows already there: should a row be there anyway (written by hand), a «Fermo» without the instant +-- of its frame or a «Non analizzabile» without its reason cannot be kept, and it would stop the migration. Such a row +-- goes, and «È un video fermo?» analyses that video again when asked; an «In movimento» stays as it is. +DELETE FROM video_analysis WHERE outcome <> 'Moving'; + +-- The instant of the frame «Salva il fotogramma» saves, in milliseconds of shown time (as export_copy.frame_at_ms): +-- the sharpest frame the analysis looked at, never a dark one of a fade (answer 45 of Alberto, 29 November 2026). +-- Set for a «Fermo» outcome and only for it. +ALTER TABLE video_analysis ADD COLUMN frame_at_ms INTEGER + CHECK (frame_at_ms IS NULL OR frame_at_ms >= 0) + CHECK ((outcome = 'Still') = (frame_at_ms IS NOT NULL)); + +-- Why the outcome is what it is: English codes separated by spaces, like export_item.note (FrameNotAvailable, +-- DurationUnknown, Unreadable, TooSlow, AllDark, SingleColor). Always set for «Non analizzabile», so the viewer can +-- say why; a video all black or all of one colour is «Non analizzabile» (answer 42 of Alberto, 29 November 2026). +ALTER TABLE video_analysis ADD COLUMN note TEXT + CHECK (note IS NULL OR length(note) > 0) + CHECK (outcome <> 'NotAnalyzable' OR note IS NOT NULL); + +-- The «Video fermi» filter of the library reads the still outcomes and joins them to the files by SHA-256 +-- (ix_media_sha256_entry, migration 0004); the primary key (sha256, algorithm) is in the index too. +CREATE INDEX ix_video_analysis_still ON video_analysis (sha256) WHERE outcome = 'Still'; diff --git a/src/Febe.Data/Stores/VideoAnalysisStore.cs b/src/Febe.Data/Stores/VideoAnalysisStore.cs index f0d2858..5166c6d 100644 --- a/src/Febe.Data/Stores/VideoAnalysisStore.cs +++ b/src/Febe.Data/Stores/VideoAnalysisStore.cs @@ -8,8 +8,10 @@ internal sealed class VideoAnalysisStore(FebeDatabase db) : IVideoAnalysisStore { private const int KeysPerQuery = 500; + private const string Columns = "sha256, algorithm, outcome, analyzed_at, frame_at_ms, note"; + private static VideoAnalysis Read(SqliteDataReader r) => - new(r.GetString(0), r.GetInt32(1), r.GetEnum(2), r.GetTime(3)); + new(r.GetString(0), r.GetInt32(1), r.GetEnum(2), r.GetTime(3), r.GetDurationOrNull(4), r.GetTextOrNull(5)); public Task GetAsync(string sha256, CancellationToken ct = default) { @@ -17,8 +19,8 @@ internal sealed class VideoAnalysisStore(FebeDatabase db) : IVideoAnalysisStore return db.ReadAsync( c => { - using var r = c.Command(""" - SELECT sha256, algorithm, outcome, analyzed_at FROM video_analysis WHERE sha256 = @h ORDER BY algorithm DESC LIMIT 1 + using var r = c.Command($""" + SELECT {Columns} FROM video_analysis WHERE sha256 = @h ORDER BY algorithm DESC LIMIT 1 """).With("@h", sha).ExecuteReader(); return r.Read() ? Read(r) : null; }, @@ -36,7 +38,7 @@ internal sealed class VideoAnalysisStore(FebeDatabase db) : IVideoAnalysisStore foreach (var chunk in keys.Chunk(KeysPerQuery)) { using var command = c.Command(string.Empty); - command.CommandText = $"SELECT sha256, algorithm, outcome, analyzed_at FROM video_analysis WHERE sha256 IN ({command.AddList("h", chunk)})"; + command.CommandText = $"SELECT {Columns} FROM video_analysis WHERE sha256 IN ({command.AddList("h", chunk)})"; using var r = command.ExecuteReader(); while (r.Read()) { @@ -58,12 +60,55 @@ internal sealed class VideoAnalysisStore(FebeDatabase db) : IVideoAnalysisStore ArgumentNullException.ThrowIfNull(analysis); var sha = ExportValues.Sha(analysis.Sha256, nameof(analysis)); ArgumentOutOfRangeException.ThrowIfLessThan(analysis.Algorithm, 1, nameof(analysis)); + ValidateFrame(analysis.Outcome, analysis.FrameAt, nameof(analysis)); + var note = Note(analysis.Outcome, analysis.Note, nameof(analysis)); return db.WriteAsync( w => w.Command(""" - INSERT INTO video_analysis (sha256, algorithm, outcome, analyzed_at) VALUES (@h, @alg, @o, @at) - ON CONFLICT (sha256, algorithm) DO UPDATE SET outcome = excluded.outcome, analyzed_at = excluded.analyzed_at + INSERT INTO video_analysis (sha256, algorithm, outcome, analyzed_at, frame_at_ms, note) VALUES (@h, @alg, @o, @at, @fr, @n) + ON CONFLICT (sha256, algorithm) DO UPDATE SET + outcome = excluded.outcome, analyzed_at = excluded.analyzed_at, frame_at_ms = excluded.frame_at_ms, note = excluded.note """).With("@h", sha).With("@alg", (long)analysis.Algorithm).With("@o", Sql.Enum(analysis.Outcome)).With("@at", Sql.Time(analysis.AnalyzedAt)) + .With("@fr", Sql.Duration(analysis.FrameAt)).With("@n", (object?)note ?? DBNull.Value) .ExecuteNonQuery(), ct); } + + /// A still video has the instant of its frame, at or after the start; no other outcome has one. + private static void ValidateFrame(VideoAnalysisOutcome outcome, TimeSpan? frameAt, string name) + { + if (outcome == VideoAnalysisOutcome.Still) + { + if (frameAt is not { } f || f < TimeSpan.Zero) + { + throw new ArgumentException("Un video fermo ha l'istante del suo fotogramma, dall'inizio in poi.", name); + } + } + else if (frameAt is not null) + { + throw new ArgumentException("Solo un video fermo ha l'istante di un fotogramma.", name); + } + } + + /// + /// The note as stored: codes of ASCII letters and digits starting upper case (a «Code:Arg» too) separated by single + /// spaces, null for none. Never free text, so no path or message can end up in it; «Non analizzabile» always says why. + /// + private static string? Note(VideoAnalysisOutcome outcome, string? note, string name) + { + var codes = (note ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + foreach (var code in codes) + { + if (!char.IsAsciiLetterUpper(code[0]) || !code.All(c => char.IsAsciiLetterOrDigit(c) || c == ':')) + { + throw new ArgumentException("La nota di un'analisi è fatta di codici separati da spazi.", name); + } + } + + if (codes.Length == 0 && outcome == VideoAnalysisOutcome.NotAnalyzable) + { + throw new ArgumentException("Un video non analizzabile dice perché nella nota.", name); + } + + return codes.Length == 0 ? null : string.Join(' ', codes); + } } diff --git a/tests/Febe.Tests/Data/ExportConstraintTests.cs b/tests/Febe.Tests/Data/ExportConstraintTests.cs index 9ee2ea1..116a860 100644 --- a/tests/Febe.Tests/Data/ExportConstraintTests.cs +++ b/tests/Febe.Tests/Data/ExportConstraintTests.cs @@ -57,7 +57,7 @@ public sealed class ExportConstraintTests 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(("outcome", "Fermo"), ("frame_at_ms", null), ("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( @@ -188,6 +188,31 @@ public sealed class ExportConstraintTests await InsertAsync(db, "media_conversion", Converted(w, "Jpg", Make.Sha(2), ("bytes", 0L))); } + /// + /// The columns of migration 0005 (tappa E4): a still video has the instant of its frame, no other outcome has one, and + /// a «Non analizzabile» says why. Each row breaks that CHECK alone (the same row with a valid value is accepted). + /// + [TestMethod] + public async Task VideoAnalysisFrameAndNoteGoWithTheOutcome() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + + await RejectedAsync(db, "video_analysis", AnalysisRow(("frame_at_ms", null)), "fermo senza istante"); + await RejectedAsync(db, "video_analysis", AnalysisRow(("frame_at_ms", -1L)), "istante negativo"); + await RejectedAsync(db, "video_analysis", AnalysisRow(("outcome", "Moving")), "in movimento con un istante"); + await RejectedAsync(db, "video_analysis", AnalysisRow(("outcome", "NotAnalyzable"), ("frame_at_ms", null)), "non analizzabile senza nota"); + await RejectedAsync(db, "video_analysis", AnalysisRow(("outcome", "Moving"), ("frame_at_ms", null), ("note", "")), "nota vuota"); + await SchemaDeclaresAsync(db, "video_analysis", "CHECK ((outcome = 'Still') = (frame_at_ms IS NOT NULL))"); + await SchemaDeclaresAsync(db, "video_analysis", "CHECK (outcome <> 'NotAnalyzable' OR note IS NOT NULL)"); + + await InsertAsync(db, "video_analysis", AnalysisRow()); + await InsertAsync(db, "video_analysis", AnalysisRow(("sha256", Make.Sha(6)), ("frame_at_ms", 1125L), ("note", "Prova"))); + await InsertAsync(db, "video_analysis", AnalysisRow(("sha256", Make.Sha(7)), ("outcome", "Moving"), ("frame_at_ms", null))); + await InsertAsync(db, "video_analysis", AnalysisRow(("sha256", Make.Sha(8)), ("outcome", "NotAnalyzable"), ("frame_at_ms", null), ("note", "TooSlow"))); + Assert.AreEqual(4L, await ScalarAsync(db, "SELECT COUNT(*) FROM video_analysis")); + } + /// The removed account kept on a copy: only on a row without account, never empty, and both may be unknown. [TestMethod] public async Task TheRemovedAccountIsKeptOnlyOnOrphanCopies() diff --git a/tests/Febe.Tests/Data/ExportStoreTests.cs b/tests/Febe.Tests/Data/ExportStoreTests.cs index 55508c8..1eb0e20 100644 --- a/tests/Febe.Tests/Data/ExportStoreTests.cs +++ b/tests/Febe.Tests/Data/ExportStoreTests.cs @@ -791,20 +791,22 @@ public sealed class ExportStoreTests await using var db = await TestDatabase.OpenAsync(temp); Assert.IsNull(await db.VideoAnalyses.GetAsync(Make.Sha(1))); - await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1).ToUpperInvariant(), 1, VideoAnalysisOutcome.Still, Make.T0)); - Assert.AreEqual(new VideoAnalysis(Make.Sha(1), 1, VideoAnalysisOutcome.Still, Make.T0), await db.VideoAnalyses.GetAsync(Make.Sha(1))); + await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1).ToUpperInvariant(), 1, VideoAnalysisOutcome.Still, Make.T0, TimeSpan.FromMilliseconds(1125))); + Assert.AreEqual(new VideoAnalysis(Make.Sha(1), 1, VideoAnalysisOutcome.Still, Make.T0, TimeSpan.FromMilliseconds(1125)), await db.VideoAnalyses.GetAsync(Make.Sha(1))); await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1), 2, VideoAnalysisOutcome.Moving, Make.T0.AddDays(1))); Assert.AreEqual(2, (await db.VideoAnalyses.GetAsync(Make.Sha(1)))!.Algorithm, "vale l'algoritmo più alto"); - await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1), 1, VideoAnalysisOutcome.NotAnalyzable, Make.T0.AddDays(2))); + await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1), 1, VideoAnalysisOutcome.NotAnalyzable, Make.T0.AddDays(2), Note: VideoAnalysisNotes.TooSlow)); Assert.AreEqual(VideoAnalysisOutcome.Moving, (await db.VideoAnalyses.GetAsync(Make.Sha(1)))!.Outcome); - await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1), 2, VideoAnalysisOutcome.Still, Make.T0.AddDays(3))); - Assert.AreEqual(new VideoAnalysis(Make.Sha(1), 2, VideoAnalysisOutcome.Still, Make.T0.AddDays(3)), await db.VideoAnalyses.GetAsync(Make.Sha(1)), "lo stesso algoritmo si sostituisce"); + await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1), 2, VideoAnalysisOutcome.Still, Make.T0.AddDays(3), TimeSpan.Zero)); + Assert.AreEqual(new VideoAnalysis(Make.Sha(1), 2, VideoAnalysisOutcome.Still, Make.T0.AddDays(3), TimeSpan.Zero), await db.VideoAnalyses.GetAsync(Make.Sha(1)), "lo stesso algoritmo si sostituisce"); Assert.AreEqual(2L, await ScalarAsync(db, "SELECT COUNT(*) FROM video_analysis")); for (var i = 10; i < 710; i++) { - await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(i), 1, i % 2 == 0 ? VideoAnalysisOutcome.Still : VideoAnalysisOutcome.Moving, Make.T0)); + await db.VideoAnalyses.SetAsync(i % 2 == 0 + ? new VideoAnalysis(Make.Sha(i), 1, VideoAnalysisOutcome.Still, Make.T0, TimeSpan.FromMilliseconds(i)) + : new VideoAnalysis(Make.Sha(i), 1, VideoAnalysisOutcome.Moving, Make.T0)); } var keys = Enumerable.Range(0, 800).Select(Make.Sha).ToList(); @@ -812,7 +814,54 @@ public sealed class ExportStoreTests Assert.HasCount(701, many); Assert.AreEqual(2, many[Make.Sha(1)].Algorithm); Assert.AreEqual(VideoAnalysisOutcome.Moving, many[Make.Sha(709)].Outcome); - await Assert.ThrowsExactlyAsync(() => db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1), 0, VideoAnalysisOutcome.Still, Make.T0))); + Assert.AreEqual(TimeSpan.FromMilliseconds(708), many[Make.Sha(708)].FrameAt, "GetManyAsync legge anche l'istante"); + await Assert.ThrowsExactlyAsync(() => db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1), 0, VideoAnalysisOutcome.Still, Make.T0, TimeSpan.Zero))); + } + + /// + /// The instant of the frame and the note of migration 0005 (tappa E4) round-trip; the store keeps a still video with + /// its instant and only it, and a «Non analizzabile» with the reason, so the viewer can always say why. + /// + [TestMethod] + public async Task VideoAnalysesKeepTheFrameAndTheNote() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + + foreach (var code in VideoAnalysisNotes.All) + { + var sha = Make.Sha(100 + VideoAnalysisNotes.All.ToList().IndexOf(code)); + await db.VideoAnalyses.SetAsync(new VideoAnalysis(sha, 1, VideoAnalysisOutcome.NotAnalyzable, Make.T0, Note: code)); + Assert.AreEqual(new VideoAnalysis(sha, 1, VideoAnalysisOutcome.NotAnalyzable, Make.T0, null, code), await db.VideoAnalyses.GetAsync(sha), code); + } + + await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1), 1, VideoAnalysisOutcome.NotAnalyzable, Make.T0, Note: " TooSlow Unreadable ")); + Assert.AreEqual("TooSlow Unreadable", (await db.VideoAnalyses.GetAsync(Make.Sha(1)))!.Note, "codici separati da uno spazio"); + await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1), 1, VideoAnalysisOutcome.Still, Make.T0, TimeSpan.FromMilliseconds(2500.7), " ")); + var still = await db.VideoAnalyses.GetAsync(Make.Sha(1)); + Assert.AreEqual(new VideoAnalysis(Make.Sha(1), 1, VideoAnalysisOutcome.Still, Make.T0, TimeSpan.FromMilliseconds(2500), null), still, "millisecondi interi, nessuna nota vuota"); + await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1), 1, VideoAnalysisOutcome.Moving, Make.T0)); + Assert.AreEqual(new VideoAnalysis(Make.Sha(1), 1, VideoAnalysisOutcome.Moving, Make.T0), await db.VideoAnalyses.GetAsync(Make.Sha(1)), "lo stesso algoritmo toglie istante e nota"); + Assert.AreEqual(1L, await ScalarAsync(db, $"SELECT COUNT(*) FROM video_analysis WHERE sha256 = '{Make.Sha(1)}'")); + + var refused = new[] + { + new VideoAnalysis(Make.Sha(2), 1, VideoAnalysisOutcome.Still, Make.T0), + new VideoAnalysis(Make.Sha(2), 1, VideoAnalysisOutcome.Still, Make.T0, TimeSpan.FromMilliseconds(-1)), + new VideoAnalysis(Make.Sha(2), 1, VideoAnalysisOutcome.Moving, Make.T0, TimeSpan.Zero), + new VideoAnalysis(Make.Sha(2), 1, VideoAnalysisOutcome.NotAnalyzable, Make.T0, TimeSpan.Zero, VideoAnalysisNotes.TooSlow), + new VideoAnalysis(Make.Sha(2), 1, VideoAnalysisOutcome.NotAnalyzable, Make.T0), + new VideoAnalysis(Make.Sha(2), 1, VideoAnalysisOutcome.NotAnalyzable, Make.T0, Note: " "), + new VideoAnalysis(Make.Sha(2), 1, VideoAnalysisOutcome.NotAnalyzable, Make.T0, Note: "C:/video/a.mp4"), + new VideoAnalysis(Make.Sha(2), 1, VideoAnalysisOutcome.NotAnalyzable, Make.T0, Note: "Il video non si legge"), + new VideoAnalysis(Make.Sha(2), 1, VideoAnalysisOutcome.Moving, Make.T0, Note: "1Code"), + }; + foreach (var analysis in refused) + { + await Assert.ThrowsExactlyAsync(() => db.VideoAnalyses.SetAsync(analysis), analysis.ToString()); + } + + Assert.IsNull(await db.VideoAnalyses.GetAsync(Make.Sha(2)), "nulla di rifiutato si scrive"); } [TestMethod] diff --git a/tests/Febe.Tests/Data/ExportWorld.cs b/tests/Febe.Tests/Data/ExportWorld.cs index 4387e13..ceafe70 100644 --- a/tests/Febe.Tests/Data/ExportWorld.cs +++ b/tests/Febe.Tests/Data/ExportWorld.cs @@ -104,7 +104,7 @@ internal sealed record ExportWorld(long Marta, long Luca, long MartaEntry, long changes); public static Dictionary AnalysisRow(params (string Column, object? Value)[] changes) => Row( - new() { ["sha256"] = Make.Sha(5), ["algorithm"] = 1L, ["outcome"] = "Still", ["analyzed_at"] = 0L }, + new() { ["sha256"] = Make.Sha(5), ["algorithm"] = 1L, ["outcome"] = "Still", ["analyzed_at"] = 0L, ["frame_at_ms"] = 0L }, changes); public Dictionary ConversionRow(params (string Column, object? Value)[] changes) => Row( diff --git a/tests/Febe.Tests/Data/MigrationTests.cs b/tests/Febe.Tests/Data/MigrationTests.cs index d21125f..df26d26 100644 --- a/tests/Febe.Tests/Data/MigrationTests.cs +++ b/tests/Febe.Tests/Data/MigrationTests.cs @@ -37,6 +37,8 @@ public sealed class MigrationTests Assert.AreEqual("schema", migrations[0].Name); Assert.AreEqual("ordine_scaricamento", migrations[1].Name); Assert.AreEqual("esportazione", migrations[2].Name); + Assert.AreEqual("esportazione_filtro", migrations[3].Name); + Assert.AreEqual("video_fermi", migrations[4].Name); } [TestMethod] @@ -167,6 +169,9 @@ public sealed class MigrationTests [TestMethod] public async Task DatabaseAtVersion3IsUpgradedWithForeignKeysClean() => await UpgradeKeepsEverything(3); + [TestMethod] + public async Task DatabaseAtVersion4IsUpgradedWithForeignKeysClean() => await UpgradeKeepsEverything(4); + [TestMethod] public void MigrationThreeChangesNoExistingTable() { @@ -213,6 +218,68 @@ public sealed class MigrationTests StringAssert.Contains(plan, "COVERING INDEX ix_media_sha256_entry", plan); } + /// + /// Migration 5 (tappa E4) adds to video_analysis only the columns frame_at_ms and note and the partial index of the + /// still outcomes: every other table, column and index stays the same, and the «Video fermi» filter reads the index. + /// + [TestMethod] + public void MigrationFiveOnlyAddsTheFrameTheNoteAndTheStillIndex() + { + using var temp = new TempFolder(); + var path = temp.Combine("dati", FebeDatabase.FileName); + var all = MigrationRunner.LoadEmbedded(); + Assert.IsGreaterThanOrEqualTo(5, all.Count); + Close(FebeDatabase.Open(path, all.Take(4).ToList())); + var tables = TablesOf(path); + var others = tables.Where(t => t != "video_analysis").ToList(); + var before = SchemaOf(path, others); + var shapesBefore = TableShapes(path, others); + var columnsBefore = ColumnsOf(path, ["video_analysis"])["video_analysis"]; + + Close(FebeDatabase.Open(path, all.Take(5).ToList())); + + CollectionAssert.AreEqual(tables, TablesOf(path), "nessuna tabella nuova"); + CollectionAssert.AreEqual(before, SchemaOf(path, others), "le altre tabelle non cambiano"); + CollectionAssert.AreEqual(shapesBefore, TableShapes(path, others), "colonne e indici delle altre tabelle restano gli stessi"); + CollectionAssert.AreEqual( + columnsBefore.Concat(["frame_at_ms", "note"]).ToList(), + ColumnsOf(path, ["video_analysis"])["video_analysis"], + "due colonne in fondo"); + var indexes = TableShapes(path, ["video_analysis"]).Where(s => s.Contains(" index ", StringComparison.Ordinal)).ToList(); + CollectionAssert.Contains(indexes, "video_analysis index ix_video_analysis_still 0 c 1", string.Join(" | ", indexes)); + using var connection = Connect(path); + var plan = string.Join(" | ", ReadColumn(connection, + "EXPLAIN QUERY PLAN SELECT m.entry_id FROM video_analysis va JOIN media m ON m.sha256 = va.sha256 WHERE va.outcome = 'Still'", 3)); + StringAssert.Contains(plan, "ix_video_analysis_still", plan); + } + + /// + /// No Febe before tappa E4 wrote video_analysis; a row written there by hand anyway does not stop migration 5: an + /// «In movimento» stays, a «Fermo» without its instant and a «Non analizzabile» without its reason go. + /// + [TestMethod] + public void MigrationFiveKeepsOnlyTheRowsItCanKeep() + { + using var temp = new TempFolder(); + var path = temp.Combine("dati", FebeDatabase.FileName); + var all = MigrationRunner.LoadEmbedded(); + Close(FebeDatabase.Open(path, all.Take(4).ToList())); + using (var connection = Connect(path)) + { + connection.Command($""" + INSERT INTO video_analysis (sha256, algorithm, outcome, analyzed_at) + VALUES ('{Make.Sha(1)}', 1, 'Still', 1000), ('{Make.Sha(2)}', 1, 'Moving', 2000), ('{Make.Sha(3)}', 1, 'NotAnalyzable', 3000); + """).ExecuteNonQuery(); + } + + Close(FebeDatabase.Open(path, all)); + + using var after = Connect(path); + var rows = ReadColumn(after, "SELECT sha256 || ' ' || outcome || ' ' || analyzed_at || ' ' || ifnull(frame_at_ms, '-') || ' ' || ifnull(note, '-') FROM video_analysis", 0); + CollectionAssert.AreEqual(new[] { $"{Make.Sha(2)} Moving 2000 - -" }, rows); + Assert.AreEqual("ok", after.Command("PRAGMA integrity_check").ExecuteScalar()); + } + [TestMethod] public async Task DatabaseOneVersionNewerIsRefusedAndLeftUntouched() { @@ -251,7 +318,7 @@ public sealed class MigrationTests await using (var db = FebeDatabase.Open(path, all)) { Assert.AreEqual(all.Count, db.SchemaVersion); - Assert.AreEqual(4, db.SchemaVersion); + Assert.AreEqual(5, db.SchemaVersion); } using var connection = Connect(path);