Esportazione, tappa E4: video fermi #80

Merged
Alby96 merged 22 commits from funzione/video-fermi into main 2026-12-01 21:56:37 +01:00
8 changed files with 278 additions and 20 deletions
Showing only changes of commit 0cd842a518 - Show all commits

No files matched your search

+41 -2
View File
@@ -343,8 +343,47 @@ public sealed record ExportItem
public string? LastError { get; init; }
}
/// <summary>Outcome of the still-video analysis of one algorithm for one SHA-256 (spec §8.3 <c>video_analysis</c>).</summary>
public sealed record VideoAnalysis(string Sha256, int Algorithm, VideoAnalysisOutcome Outcome, DateTimeOffset AnalyzedAt);
/// <summary>
/// Outcome of the still-video analysis of one algorithm for one SHA-256 (spec §8.3 <c>video_analysis</c>, migration
/// 0005 of tappa E4). <paramref name="FrameAt"/> is the shown instant of the frame «Salva il fotogramma» saves: set for
/// <see cref="VideoAnalysisOutcome.Still"/> and only for it. <paramref name="Note"/> says why, as codes of
/// <see cref="VideoAnalysisNotes"/> separated by spaces: always set for <see cref="VideoAnalysisOutcome.NotAnalyzable"/>.
/// </summary>
public sealed record VideoAnalysis(
string Sha256,
int Algorithm,
VideoAnalysisOutcome Outcome,
DateTimeOffset AnalyzedAt,
TimeSpan? FrameAt = null,
string? Note = null);
/// <summary>
/// The codes of <c>video_analysis.note</c> (tappa E4), English, separated by spaces like <c>export_item.note</c>. They
/// say why a video is «Non analizzabile».
/// </summary>
public static class VideoAnalysisNotes
{
/// <summary>The video has no frames Febe can decode (codec, profile or container outside spec §3, damaged headers).</summary>
public const string FrameNotAvailable = "FrameNotAvailable";
/// <summary>The video has more than one frame and no known duration.</summary>
public const string DurationUnknown = "DurationUnknown";
/// <summary>The frames of the video cannot be read (a damaged or truncated file).</summary>
public const string Unreadable = "Unreadable";
/// <summary>The analysis took longer than its time limit (only an analysis from a selection stores it).</summary>
public const string TooSlow = "TooSlow";
/// <summary>Every frame looked at is black or nearly black (answer 42 of Alberto, 29 November 2026).</summary>
public const string AllDark = "AllDark";
/// <summary>Every frame looked at is all of one single colour, not dark (answer 42 of Alberto, 29 November 2026).</summary>
public const string SingleColor = "SingleColor";
/// <summary>Every code of algorithm 1, in the order above.</summary>
public static IReadOnlyList<string> All { get; } = [FrameNotAvailable, DurationUnknown, Unreadable, TooSlow, AllDark, SingleColor];
}
/// <summary>
/// A converted file added to an entry by the conversion for the library (spec §4.10, §8.3 <c>media_conversion</c>),
+8 -2
View File
@@ -4,7 +4,8 @@ namespace Febe.Core.Storage;
/// <summary>
/// Outcomes of «È un video fermo?» by SHA-256 of the video and number of the algorithm (spec §4.10, §8.3
/// <c>video_analysis</c>). No link to the library: an outcome outlives deletion and re-import of the same file.
/// <c>video_analysis</c>, columns <c>frame_at_ms</c> and <c>note</c> from migration 0005). No link to the library: an
/// outcome outlives deletion and re-import of the same file.
/// </summary>
public interface IVideoAnalysisStore
{
@@ -14,6 +15,11 @@ public interface IVideoAnalysisStore
/// <summary>The analysis with the highest algorithm number for each SHA-256 that has one, keyed by lower-case SHA-256.</summary>
Task<IReadOnlyDictionary<string, VideoAnalysis>> GetManyAsync(IReadOnlyCollection<string> sha256s, CancellationToken ct = default);
/// <summary>Stores (or replaces) the outcome of one algorithm for one SHA-256.</summary>
/// <summary>
/// Stores (or replaces) the outcome of one algorithm for one SHA-256, with the instant of its frame and its note.
/// Throws <see cref="ArgumentException"/> 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.
/// </summary>
Task SetAsync(VideoAnalysis analysis, CancellationToken ct = default);
}
@@ -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';
+51 -6
View File
@@ -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<VideoAnalysisOutcome>(2), r.GetTime(3));
new(r.GetString(0), r.GetInt32(1), r.GetEnum<VideoAnalysisOutcome>(2), r.GetTime(3), r.GetDurationOrNull(4), r.GetTextOrNull(5));
public Task<VideoAnalysis?> 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);
}
/// <summary>A still video has the instant of its frame, at or after the start; no other outcome has one.</summary>
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);
}
}
/// <summary>
/// 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.
/// </summary>
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);
}
}
+26 -1
View File
@@ -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)));
}
/// <summary>
/// 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).
/// </summary>
[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"));
}
/// <summary>The removed account kept on a copy: only on a row without account, never empty, and both may be unknown.</summary>
[TestMethod]
public async Task TheRemovedAccountIsKeptOnlyOnOrphanCopies()
+56 -7
View File
@@ -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<ArgumentOutOfRangeException>(() => 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<ArgumentOutOfRangeException>(() => db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1), 0, VideoAnalysisOutcome.Still, Make.T0, TimeSpan.Zero)));
}
/// <summary>
/// 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.
/// </summary>
[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<ArgumentException>(() => db.VideoAnalyses.SetAsync(analysis), analysis.ToString());
}
Assert.IsNull(await db.VideoAnalyses.GetAsync(Make.Sha(2)), "nulla di rifiutato si scrive");
}
[TestMethod]
+1 -1
View File
@@ -104,7 +104,7 @@ internal sealed record ExportWorld(long Marta, long Luca, long MartaEntry, long
changes);
public static Dictionary<string, object?> 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<string, object?> ConversionRow(params (string Column, object? Value)[] changes) => Row(
+68 -1
View File
@@ -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);
}
/// <summary>
/// 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.
/// </summary>
[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);
}
/// <summary>
/// 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.
/// </summary>
[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);