using System.Text; using Febe.Core.Domain; using Febe.Core.Library; using Febe.Core.Storage; using Microsoft.Data.Sqlite; using static Febe.Data.Stores.EntryMapping; namespace Febe.Data.Stores; internal sealed class EntryStore(FebeDatabase db) : IEntryStore { public Task GetAsync(long entryId, CancellationToken ct = default) => db.ReadAsync(c => ReadEntryById(sql => c.Command(sql), entryId), ct); public Task GetWithMediaAsync(long entryId, CancellationToken ct = default) => db.ReadAsync( c => { var entry = ReadEntryById(sql => c.Command(sql), entryId); return entry is null ? null : new EntryWithMedia(entry, ReadMediaOf(sql => c.Command(sql), entryId)); }, ct); public Task FindAsync(long accountId, EntryKind kind, string instagramId, CancellationToken ct = default) { ArgumentException.ThrowIfNullOrWhiteSpace(instagramId); return db.ReadAsync(c => FindIdentity(sql => c.Command(sql), accountId, kind, instagramId.Trim()), ct); } public async Task IsKnownAsync(long accountId, EntryKind kind, string instagramId, CancellationToken ct = default) => await FindAsync(accountId, kind, instagramId, ct).ConfigureAwait(false) is not null; public Task> GetKnownInstagramIdsAsync(long accountId, EntryKind kind, IReadOnlyCollection instagramIds, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(instagramIds); var ids = instagramIds.Where(i => !string.IsNullOrWhiteSpace(i)).Select(i => i.Trim()).Distinct(StringComparer.Ordinal).ToList(); return db.ReadAsync>( c => { var known = new HashSet(StringComparer.Ordinal); foreach (var chunk in ids.Chunk(500)) { var command = c.Command(string.Empty).With("@a", accountId).With("@k", Sql.Enum(kind)); var list = command.AddList("i", chunk); command.CommandText = $"SELECT instagram_id FROM entry WHERE account_id = @a AND kind = @k AND instagram_id IN ({list})"; using var r = command.ExecuteReader(); while (r.Read()) { known.Add(r.GetString(0)); } } return known; }, ct); } public Task> FindByInstagramIdAsync(long accountId, string instagramId, CancellationToken ct = default) { ArgumentException.ThrowIfNullOrWhiteSpace(instagramId); return db.ReadAsync>( c => ReadEntries(c.Command($"SELECT {EntryColumns} FROM entry e WHERE e.account_id = @a AND e.instagram_id = @i ORDER BY e.id") .With("@a", accountId).With("@i", instagramId.Trim())), ct); } public Task FindByPublicationTimeAsync(long accountId, EntryKind kind, DateTimeOffset publishedAt, TimeSpan tolerance, CancellationToken ct = default) { var ms = Sql.Time(publishedAt); var tol = (long)Math.Abs(tolerance.TotalMilliseconds); return db.ReadAsync( c => { using var r = c.Command($""" SELECT {EntryColumns} FROM entry e WHERE e.account_id = @a AND e.kind = @k AND e.published_at BETWEEN @from AND @to ORDER BY abs(e.published_at - @p), e.id LIMIT 1 """) .With("@a", accountId).With("@k", Sql.Enum(kind)).With("@from", ms - tol).With("@to", ms + tol).With("@p", ms) .ExecuteReader(); return r.Read() ? ReadEntry(r) : null; }, ct); } public Task AddAsync(Entry entry, IReadOnlyList media, CancellationToken ct = default) { Validate(entry, media); return db.WriteAsync(w => Add(w, entry, media), ct); } public Task> AddManyAsync(IReadOnlyList entries, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(entries); foreach (var item in entries) { Validate(item.Entry, item.Media); } return db.WriteAsync>(w => entries.Select(item => Add(w, item.Entry, item.Media)).ToList(), ct); } public Task UpdateAsync(Entry entry, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(entry); return db.WriteAsync( w => { var c = w.Command(""" UPDATE entry SET instagram_id = @instagram_id, code = @code, published_at = @published_at, caption = @caption, author_username = @author_username, author_instagram_id = @author_instagram_id, state = @state, provenance = @provenance, discovered_at = @discovered_at, downloaded_at = @downloaded_at, deleted_at = @deleted_at, expires_at = @expires_at, search_text = @search_text, is_reel = max(is_reel, @is_reel) WHERE id = @id """); BindEntry(c, entry); c.With("@id", entry.Id); try { if (c.ExecuteNonQuery() == 0) { throw new KeyNotFoundException($"Elemento {entry.Id} non trovato."); } } catch (SqliteException ex) when (ex.IsUniqueViolation()) { throw new DuplicateRecordException("Esiste già un elemento con lo stesso identificativo Instagram per questo account e tipo.", ex); } }, ct); } public Task MarkReelAsync(long entryId, CancellationToken ct = default) => db.WriteAsync(w => w.Command("UPDATE entry SET is_reel = 1 WHERE id = @id AND kind = 'Post'").With("@id", entryId).ExecuteNonQuery(), ct); public Task SetStateAsync(long entryId, EntryState state, CancellationToken ct = default) => db.WriteAsync( w => { if (w.Command("UPDATE entry SET state = @s WHERE id = @id").With("@s", Sql.Enum(state)).With("@id", entryId).ExecuteNonQuery() == 0) { throw new KeyNotFoundException($"Elemento {entryId} non trovato."); } }, ct); public Task RecomputeStateAsync(long entryId, CancellationToken ct = default) => db.WriteAsync(w => RecomputeState(w, entryId), ct); public Task MarkDeletedAsync(long entryId, DateTimeOffset at, CancellationToken ct = default) => db.WriteAsync( w => { var rows = w.Command("UPDATE entry SET state = 'Deleted', deleted_at = @at WHERE id = @id") .With("@at", Sql.Time(at)).With("@id", entryId).ExecuteNonQuery(); if (rows == 0) { throw new KeyNotFoundException($"Elemento {entryId} non trovato."); } w.Command(""" UPDATE media SET state = 'Deleted', relative_path = NULL, has_thumbnail = 0, phash = NULL, source_url = NULL, cover_url = NULL WHERE entry_id = @id """).With("@id", entryId).ExecuteNonQuery(); }, ct); public Task RemoveAsync(long entryId, CancellationToken ct = default) => db.WriteAsync(w => w.Command("DELETE FROM entry WHERE id = @id").With("@id", entryId).ExecuteNonQuery(), ct); public Task> ListByAccountAsync(long accountId, EntryListOptions? options = null, CancellationToken ct = default) { options ??= new EntryListOptions(); return db.ReadAsync>( c => { var command = c.Command(string.Empty).With("@a", accountId).With("@limit", (long)Math.Clamp(options.Limit, 1, 10_000)); var sql = new StringBuilder($"SELECT {EntryColumns} FROM entry e WHERE e.account_id = @a"); if (options.Kind is { } kind) { sql.Append(" AND e.kind = @k"); command.With("@k", Sql.Enum(kind)); } if (options.States is { Count: > 0 } states) { sql.Append(" AND e.state IN (").Append(command.AddList("s", states.Select(s => s.ToString()))).Append(')'); } if (options.Before is { } before) { sql.Append(" AND (e.published_at, e.id) < (@bp, @bi)"); command.With("@bp", Sql.Time(before.PublishedAt)).With("@bi", before.EntryId); } sql.Append(" ORDER BY e.published_at DESC, e.id DESC LIMIT @limit"); command.CommandText = sql.ToString(); return ReadEntries(command); }, ct); } // The window of a recipe is a few minutes: the range on ix_entry_discovered (migration 0002) reads only those rows, // whatever the size of the library or of the account. private const string ArrivedWhere = """ discovered_at >= @f AND discovered_at <= @t AND (@a IS NULL OR account_id = @a) AND provenance = @p AND state <> 'Deleted' """; public Task ListDiscoveredAsync(long? accountId, DateTimeOffset from, DateTimeOffset to, int limit, CancellationToken ct = default) => db.ReadAsync( c => { var ids = new List(); using (var r = c.Command($""" SELECT id FROM entry WHERE {ArrivedWhere} ORDER BY discovered_at DESC, id DESC LIMIT @l """).With("@a", accountId).With("@f", Sql.Time(from)).With("@t", Sql.Time(to)).With("@p", Sql.Enum(Provenance.Downloaded)) .With("@l", (long)Math.Clamp(limit, 1, 100)).ExecuteReader()) { while (r.Read()) { ids.Add(r.GetInt64(0)); } } var total = (int)c.Command($""" SELECT COUNT(*) FROM entry WHERE {ArrivedWhere} """).With("@a", accountId).With("@f", Sql.Time(from)).With("@t", Sql.Time(to)).With("@p", Sql.Enum(Provenance.Downloaded)).ScalarInt64(); return new ArrivedEntries(ids, total); }, ct); public Task CountDiscoveredAsync(long accountId, EntryKind kind, DateTimeOffset from, DateTimeOffset to, CancellationToken ct = default) => db.ReadAsync( c => (int)c.Command(""" SELECT COUNT(*) FROM entry WHERE account_id = @a AND kind = @k AND discovered_at >= @f AND discovered_at < @t """).With("@a", accountId).With("@k", Sql.Enum(kind)).With("@f", Sql.Time(from)).With("@t", Sql.Time(to)).ScalarInt64(), ct); public Task QueryLibraryAsync(LibraryQuery query, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(query); var limit = Math.Clamp(query.Limit, 1, 1000); if (query.Mode == MosaicMode.Files) { return db.ReadAsync(c => QueryFiles(c, query, limit), ct); } return db.ReadAsync( c => { // Phase 1: keys only, so that sorting never computes the tile columns of rows outside the window. var command = c.Command(string.Empty); var where = BuildWhere(c, command, query.Filter); var newer = query.Direction == LibraryDirection.Newer; var sql = new StringBuilder($"SELECT e.id FROM entry e WHERE {where}"); if (query.Cursor is { } cursor) { sql.Append(newer ? " AND (e.published_at, e.id) > (@cp, @ci)" : " AND (e.published_at, e.id) < (@cp, @ci)"); command.With("@cp", Sql.Time(cursor.PublishedAt)).With("@ci", cursor.EntryId); } // With a text search the whole table is scanned and the matches sorted: about a tenth of a second on // 200,000 entries whether the word is rare or common, instead of walking the index row by row. var order = string.IsNullOrWhiteSpace(query.Filter.Search) ? "e.published_at" : "+e.published_at"; sql.Append(newer ? $" ORDER BY {order} ASC, e.id ASC" : $" ORDER BY {order} DESC, e.id DESC"); sql.Append(" LIMIT @limit"); command.With("@limit", (long)limit + 1); command.CommandText = sql.ToString(); var ids = new List(limit + 1); using (var r = command.ExecuteReader()) { while (r.Read()) { ids.Add(r.GetInt64(0)); } } var moreInDirection = ids.Count > limit; if (moreInDirection) { ids.RemoveAt(ids.Count - 1); } if (newer) { ids.Reverse(); } // Phase 2: the tiles of the window, in display order. var tiles = TilesOf(c, ids); if (tiles.Count == 0) { return new LibraryPage(tiles, null, null); } var first = new LibraryCursor(tiles[0].PublishedAt, tiles[0].EntryId); var last = new LibraryCursor(tiles[^1].PublishedAt, tiles[^1].EntryId); bool hasOlder, hasNewer; if (newer) { hasNewer = moreInDirection; hasOlder = Exists(c, query.Filter, last, older: true); } else { hasOlder = moreInDirection; hasNewer = query.Cursor is not null && Exists(c, query.Filter, first, older: false); } return new LibraryPage(tiles, hasOlder ? last : null, hasNewer ? first : null); }, ct); } public Task GetLibraryTotalsAsync(LibraryFilter filter, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(filter); return db.ReadAsync( c => { var command = c.Command(string.Empty); var where = BuildWhere(c, command, filter); command.CommandText = $"SELECT COUNT(*), COUNT(DISTINCT e.account_id) FROM entry e WHERE {where}"; using var r = command.ExecuteReader(); r.Read(); return new LibraryTotals(r.GetInt32(0), r.GetInt32(1)); }, ct); } public Task CountLibraryFilesAsync(LibraryFilter filter, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(filter); return db.ReadAsync( c => { var command = c.Command(string.Empty); var where = BuildWhere(c, command, EntriesOfFiles(filter)); var counts = FileCounts(c, filter); if (counts is null) { command.CommandText = $"SELECT COALESCE(SUM({FilesOfEntry(filter)}), 0) FROM entry e WHERE {where}"; return (int)command.ScalarInt64(); } command.CommandText = $"SELECT e.id FROM entry e WHERE {where}"; var total = 0; using var r = command.ExecuteReader(); while (r.Read()) { total += counts.GetValueOrDefault(r.GetInt64(0)); } return total; }, ct); } public Task> CountLibraryByDayAsync(LibraryFilter filter, TimeZoneInfo zone, MosaicMode mode = MosaicMode.Grouped, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(filter); ArgumentNullException.ThrowIfNull(zone); return db.ReadAsync>( c => { // Stream the publication times in index order and fold them into local days here: no time zone logic // in SQL, no sort, and the day bounds are computed once per day rather than once per entry. var command = c.Command(string.Empty); var files = mode == MosaicMode.Files; var where = BuildWhere(c, command, files ? EntriesOfFiles(filter) : filter); var counts = files ? FileCounts(c, filter) : null; var perEntry = files && counts is null; command.CommandText = !files ? $"SELECT e.published_at FROM entry e WHERE {where} ORDER BY e.published_at" : perEntry ? $"SELECT e.published_at, {FilesOfEntry(filter)} FROM entry e WHERE {where} ORDER BY e.published_at" : $"SELECT e.published_at, e.id FROM entry e WHERE {where} ORDER BY e.published_at"; var days = new List(); long dayStart = long.MaxValue, dayEnd = long.MinValue; DateOnly day = default; var count = 0; using (var r = command.ExecuteReader()) { while (r.Read()) { var ms = r.GetInt64(0); if (ms < dayStart || ms >= dayEnd) { if (count > 0) { days.Add(new DayCount(day, count)); } day = LocalCalendar.Today(Sql.ToTime(ms), zone); var (start, end) = LocalCalendar.DayBounds(day, zone); (dayStart, dayEnd, count) = (Sql.Time(start), Sql.Time(end), 0); } count += !files ? 1 : perEntry ? r.GetInt32(1) : counts!.GetValueOrDefault(r.GetInt64(1)); } } if (count > 0) { days.Add(new DayCount(day, count)); } days.Reverse(); return days; }, ct); } public Task> GetTilesAsync(IReadOnlyList entryIds, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(entryIds); return db.ReadAsync>(c => TilesOf(c, entryIds), ct); } // --------------------------------------------------------------------------------------------- /// Tiles of the given entries, in the given order (unknown keys are skipped). private static List TilesOf(SqliteConnection c, IReadOnlyList entryIds) { var byId = new Dictionary(entryIds.Count); foreach (var chunk in entryIds.Distinct().Chunk(500)) { using var command = c.Command(string.Empty); var list = command.AddList("i", chunk); command.CommandText = $"SELECT {TileColumns} {TileFrom} WHERE e.id IN ({list})"; using var r = command.ExecuteReader(); while (r.Read()) { var tile = ReadTile(r); byId[tile.EntryId] = tile; } } return entryIds.Where(byId.ContainsKey).Select(id => byId[id]).ToList(); } // --------------------------------------------------------------------------------------------- «Tutte le foto» /// The files of «Tutte le foto» on media m: those in the library, of the kind of «Foto» or «Video». private static string FileTerms(LibraryFilter filter) => // The unary + keeps SQLite on the key of the entry (entry_id, position) rather than on the broad state index. "+m.state IN ('Downloaded', 'Imported')" + filter.Kind switch { LibraryKindFilter.Photos => " AND m.kind = 'Photo'", LibraryKindFilter.Videos => " AND m.kind = 'Video'", _ => string.Empty, }; /// /// The files of «Tutte le foto» of every entry, in one pass over ix_media_entry_files: over the whole library a /// count per entry would cost a subquery for each of 200,000 rows (over a second), this a tenth of that. With a /// filter on accounts the entries are few and are counted one by one instead (null). /// private static Dictionary? FileCounts(SqliteConnection c, LibraryFilter filter) { if (filter.AccountIds is { Count: > 0 }) { return null; } using var command = c.Command($"SELECT m.entry_id, COUNT(*) FROM media m WHERE {FileTerms(filter)} GROUP BY m.entry_id"); var counts = new Dictionary(); using var r = command.ExecuteReader(); while (r.Read()) { counts[r.GetInt64(0)] = r.GetInt32(1); } return counts; } /// /// The entries whose files a count of «Tutte le foto» adds up: for «Foto» and «Video» every post, since the kind of /// the files already decides (a post without videos adds 0) and the EXISTS per post of the grouped filter would cost /// a second over 200,000 entries. /// private static LibraryFilter EntriesOfFiles(LibraryFilter filter) => filter.Kind is LibraryKindFilter.Photos or LibraryKindFilter.Videos ? filter with { Kind = LibraryKindFilter.Posts } : filter; /// A correlated count of the files of «Tutte le foto» of the entry e. private static string FilesOfEntry(LibraryFilter filter) => $"(SELECT COUNT(*) FROM media m WHERE m.entry_id = e.id AND {FileTerms(filter)})"; /// /// A window of «Tutte le foto»: the keys of the entries come from the same keyset scan of the publication index as /// the grouped mosaic (so it stays as fast over 200,000 entries), then their files are read by key and laid out in /// order, entry by entry and each by position. More entries are read only when those had too few files. /// private static LibraryPage QueryFiles(SqliteConnection c, LibraryQuery query, int limit) { var newer = query.Direction == LibraryDirection.Newer; var wanted = limit + 1; var files = new List(wanted); var cursor = query.Cursor; var from = cursor; // The first read includes the entry of the cursor, for its files after (or before) the cursor's position. var inclusive = true; while (files.Count < wanted) { var keys = EntryKeys(c, query.Filter, from, newer, inclusive, wanted); if (keys.Count == 0) { break; } var byEntry = FilesOf(c, keys.Select(k => k.Id).ToList(), query.Filter); foreach (var (id, _) in keys) { if (!byEntry.TryGetValue(id, out var list)) { continue; } for (var i = 0; i < list.Count && files.Count < wanted; i++) { var file = list[newer ? list.Count - 1 - i : i]; if (cursor is { } at && at.EntryId == id && (newer ? file.Position >= at.Position : file.Position <= at.Position)) { continue; } files.Add(file); } if (files.Count == wanted) { break; } } if (keys.Count < wanted) { break; } from = new LibraryCursor(Sql.ToTime(keys[^1].PublishedAt), keys[^1].Id); inclusive = false; } var moreInDirection = files.Count > limit; if (moreInDirection) { files.RemoveAt(files.Count - 1); } if (newer) { files.Reverse(); } var entries = TilesOf(c, files.Select(f => f.EntryId).Distinct().ToList()).ToDictionary(t => t.EntryId); var tiles = new List(files.Count); foreach (var f in files) { if (entries.TryGetValue(f.EntryId, out var entry)) { tiles.Add(entry with { CoverMediaId = f.MediaId, CoverKind = f.Kind, CoverWidth = f.Width, CoverHeight = f.Height, CoverDuration = f.Duration, CoverSha256 = f.Sha256, CoverHasThumbnail = f.HasThumbnail, FilePosition = f.Position, }); } } if (tiles.Count == 0) { return new LibraryPage(tiles, null, null); } var first = new LibraryCursor(tiles[0].PublishedAt, tiles[0].EntryId, tiles[0].FilePosition ?? 0); var last = new LibraryCursor(tiles[^1].PublishedAt, tiles[^1].EntryId, tiles[^1].FilePosition ?? 0); bool hasOlder, hasNewer; if (newer) { hasNewer = moreInDirection; hasOlder = FileExists(c, query.Filter, last, older: true); } else { hasOlder = moreInDirection; hasNewer = cursor is not null && FileExists(c, query.Filter, first, older: false); } return new LibraryPage(tiles, hasOlder ? last : null, hasNewer ? first : null); } /// Keys of the entries of a filter from a cursor, in the order of the direction (the grouped keyset scan). private static List<(long Id, long PublishedAt)> EntryKeys(SqliteConnection c, LibraryFilter filter, LibraryCursor? cursor, bool newer, bool inclusive, int limit) { using var command = c.Command(string.Empty); var where = BuildWhere(c, command, filter); var sql = new StringBuilder($"SELECT e.id, e.published_at FROM entry e WHERE {where}"); if (cursor is { } at) { var op = (newer, inclusive) switch { (true, true) => ">=", (true, false) => ">", (false, true) => "<=", _ => "<" }; sql.Append(" AND (e.published_at, e.id) ").Append(op).Append(" (@cp, @ci)"); command.With("@cp", Sql.Time(at.PublishedAt)).With("@ci", at.EntryId); } var order = string.IsNullOrWhiteSpace(filter.Search) ? "e.published_at" : "+e.published_at"; sql.Append(newer ? $" ORDER BY {order} ASC, e.id ASC" : $" ORDER BY {order} DESC, e.id DESC"); sql.Append(" LIMIT @limit"); command.With("@limit", (long)limit); command.CommandText = sql.ToString(); var keys = new List<(long, long)>(limit); using var r = command.ExecuteReader(); while (r.Read()) { keys.Add((r.GetInt64(0), r.GetInt64(1))); } return keys; } /// The files of «Tutte le foto» of the given entries, each list by position. private static Dictionary> FilesOf(SqliteConnection c, IReadOnlyList entryIds, LibraryFilter filter) { var byEntry = new Dictionary>(entryIds.Count); foreach (var chunk in entryIds.Chunk(500)) { using var command = c.Command(string.Empty); var list = command.AddList("f", chunk); command.CommandText = "SELECT m.entry_id, m.id, m.position, m.kind, m.width, m.height, m.duration_ms, m.sha256, m.has_thumbnail " + $"FROM media m WHERE m.entry_id IN ({list}) AND {FileTerms(filter)} ORDER BY m.entry_id, m.position"; using var r = command.ExecuteReader(); while (r.Read()) { var row = new FileRow( r.GetInt64(0), r.GetInt64(1), r.GetInt32(2), r.GetEnum(3), r.GetInt32OrNull(4), r.GetInt32OrNull(5), r.GetDurationOrNull(6), r.GetTextOrNull(7), r.GetBool(8)); if (!byEntry.TryGetValue(row.EntryId, out var files)) { byEntry[row.EntryId] = files = []; } files.Add(row); } } return byEntry; } /// Whether «Tutte le foto» has a file after (older) or before (newer) a cursor. private static bool FileExists(SqliteConnection c, LibraryFilter filter, LibraryCursor cursor, bool older) { using var command = c.Command(string.Empty); var where = BuildWhere(c, command, filter); var terms = FileTerms(filter); command.CommandText = $"SELECT EXISTS (SELECT 1 FROM media m WHERE m.entry_id = @xi AND m.position {(older ? ">" : "<")} @xn AND {terms} " + $"AND EXISTS (SELECT 1 FROM entry e WHERE e.id = m.entry_id AND {where})) " + $"OR EXISTS (SELECT 1 FROM entry e WHERE {where} AND (e.published_at, e.id) {(older ? "<" : ">")} (@xp, @xi) " + $"AND EXISTS (SELECT 1 FROM media m WHERE m.entry_id = e.id AND {terms}))"; command.With("@xp", Sql.Time(cursor.PublishedAt)).With("@xi", cursor.EntryId).With("@xn", (long)cursor.Position); return command.ScalarInt64() != 0; } /// A file of «Tutte le foto»: what its tile needs. private readonly record struct FileRow(long EntryId, long MediaId, int Position, MediaKind Kind, int? Width, int? Height, TimeSpan? Duration, string? Sha256, bool HasThumbnail); private static void Validate(Entry entry, IReadOnlyList media) { ArgumentNullException.ThrowIfNull(entry); ArgumentNullException.ThrowIfNull(media); if (media.Select(m => m.Position).Distinct().Count() != media.Count) { throw new ArgumentException("Le posizioni dei file di un elemento devono essere distinte.", nameof(media)); } if (media.Any(m => m.Position < 1)) { throw new ArgumentException("Le posizioni dei file partono da 1.", nameof(media)); } } private static AddEntryResult Add(WriteContext w, Entry entry, IReadOnlyList media) { var instagramId = NormalizeId(entry.InstagramId); if (instagramId is not null && FindIdentity(w.Command, entry.AccountId, entry.Kind, instagramId) is { } existing) { return new AddEntryResult(new EntryWithMedia(existing, ReadMediaOf(w.Command, existing.Id)), false); } var state = EntryStateRules.FromMedia(entry.State, entry.Provenance, media.Select(m => m.State).ToList()); var stored = entry with { InstagramId = instagramId, State = state }; var insert = w.Command(""" INSERT INTO entry (account_id, kind, instagram_id, code, published_at, caption, author_username, author_instagram_id, state, provenance, discovered_at, downloaded_at, deleted_at, expires_at, search_text, is_reel) VALUES (@account_id, @kind, @instagram_id, @code, @published_at, @caption, @author_username, @author_instagram_id, @state, @provenance, @discovered_at, @downloaded_at, @deleted_at, @expires_at, @search_text, @is_reel) """); BindEntry(insert, stored); insert.ExecuteNonQuery(); var entryId = w.LastInsertRowId(); stored = stored with { Id = entryId }; var files = new List(media.Count); foreach (var file in media.OrderBy(m => m.Position)) { var row = file with { EntryId = entryId, Sha256 = file.Sha256?.ToLowerInvariant(), InstagramId = NormalizeId(file.InstagramId) }; var command = w.Command(InsertMediaSql); BindMedia(command, row); command.ExecuteNonQuery(); files.Add(row with { Id = w.LastInsertRowId() }); } return new AddEntryResult(new EntryWithMedia(stored, files), true); } private static Entry? FindIdentity(Func command, long accountId, EntryKind kind, string instagramId) { using var r = command($"SELECT {EntryColumns} FROM entry e WHERE e.account_id = @a AND e.kind = @k AND e.instagram_id = @i") .With("@a", accountId).With("@k", Sql.Enum(kind)).With("@i", instagramId).ExecuteReader(); return r.Read() ? ReadEntry(r) : null; } private static List ReadEntries(SqliteCommand command) { using var r = command.ExecuteReader(); var list = new List(); while (r.Read()) { list.Add(ReadEntry(r)); } return list; } private static bool Exists(SqliteConnection c, LibraryFilter filter, LibraryCursor cursor, bool older) { var command = c.Command(string.Empty); var where = BuildWhere(c, command, filter); command.CommandText = $"SELECT EXISTS (SELECT 1 FROM entry e WHERE {where} AND (e.published_at, e.id) {(older ? "<" : ">")} (@xp, @xi))"; command.With("@xp", Sql.Time(cursor.PublishedAt)).With("@xi", cursor.EntryId); return command.ScalarInt64() != 0; } /// The WHERE clause of a library filter on entry e; parameters are added to . internal static string BuildWhere(SqliteConnection c, SqliteCommand command, LibraryFilter filter) { var parts = new List(); var states = filter.States is { Count: > 0 } s ? s : EntryStateRules.Visible; // The unary + keeps SQLite from using the state and kind indexes for these broad terms: the keyset scan of the // publication index is what keeps a window fast over 200,000 entries, with or without ANALYZE statistics. parts.Add($"+e.state IN ({command.AddList("st", states.Select(x => x.ToString()))})"); parts.Add(filter.Kind switch { LibraryKindFilter.All => "+e.kind IN ('Post', 'Story', 'Highlight', 'Tagged')", // Like «Tutto», a broad term: on the kind index every post would need its table row for the state (most of // the library); the publication index already holds kind and state. LibraryKindFilter.Posts => "+e.kind = 'Post'", LibraryKindFilter.Photos => "e.kind = 'Post' AND EXISTS (SELECT 1 FROM media mk WHERE mk.entry_id = e.id AND mk.kind = 'Photo')", LibraryKindFilter.Videos => "e.kind = 'Post' AND EXISTS (SELECT 1 FROM media mk WHERE mk.entry_id = e.id AND mk.kind = 'Video')", LibraryKindFilter.Stories => "e.kind = 'Story'", LibraryKindFilter.Highlights => "(e.kind = 'Highlight' OR EXISTS (SELECT 1 FROM highlight_entry he WHERE he.entry_id = e.id))", LibraryKindFilter.Tagged => "e.kind = 'Tagged'", LibraryKindFilter.ProfilePictures => "e.kind = 'ProfilePicture'", _ => throw new ArgumentOutOfRangeException(nameof(filter), filter.Kind, null), }); if (filter.AccountIds is { } accounts) { parts.Add($"e.account_id IN ({command.AddList("ac", accounts)})"); } if (filter.From is { } from) { parts.Add("e.published_at >= @from"); command.With("@from", Sql.Time(from)); } if (filter.To is { } to) { parts.Add("e.published_at < @to"); command.With("@to", Sql.Time(to)); } if (filter.Provenance is { } provenance) { parts.Add("e.provenance = @prov"); command.With("@prov", Sql.Enum(provenance)); } var term = TextSearch.Normalize(filter.Search); if (term.Length > 0) { // Accounts are few: match their names here, accent-insensitively, then filter entries by key. var matching = new List(); using (var r = c.Command("SELECT id, username, display_name FROM account").ExecuteReader()) { while (r.Read()) { var name = TextSearch.Normalize(r.GetString(1)); var display = TextSearch.Normalize(r.GetTextOrNull(2)); var bare = term.TrimStart('@'); if (name.Contains(bare, StringComparison.Ordinal) || display.Contains(term, StringComparison.Ordinal)) { matching.Add(r.GetInt64(0)); } } } command.With("@q", TextSearch.LikePattern(term)); parts.Add(matching.Count == 0 ? "e.search_text LIKE @q ESCAPE '\\'" : $"(e.search_text LIKE @q ESCAPE '\\' OR e.account_id IN ({command.AddList("sa", matching)}))"); } return string.Join(" AND ", parts); } }