M1 Dati e libreria: modello, archivi SQLite con scrittore unico, nomi dei file, scrittura sicura, miniature, impronte, _febe.jsonl, copie, eliminazione e ricostruzione
Modello del dominio e interfacce degli archivi in Febe.Core; implementazione SQLite in Febe.Data (WAL, chiavi esterne, migrazioni numerate in transazione, coda di scrittura su un solo thread); logica della libreria in Febe.Core/Library; 164 prove MSTest, compresa la ricostruzione del database da una libreria di prova e la scala a 200.000 elementi. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
69 files changed
+12472
No files matched your search
@@ -0,0 +1,459 @@
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Core.Storage;
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
namespace Febe.Data.Stores;
|
||||
|
||||
internal sealed class AccountStore(FebeDatabase db) : IAccountStore
|
||||
{
|
||||
internal const string Columns =
|
||||
"a.id, a.instagram_id, a.username, a.display_name, a.is_private, a.is_followed, a.is_mine, a.state, a.state_changed_at, "
|
||||
+ "a.unreachable_reason, a.keep_updated, a.frequency, a.custom_post_interval_min, a.custom_story_interval_min, a.content_types, "
|
||||
+ "a.history_depth, a.history_last_posts, a.history_from, a.backfill_posts_per_day, a.max_video_bytes, a.story_videos, a.folder, "
|
||||
+ "a.backfill_cursor, a.backfill_completed_at, a.post_count, a.last_profile_check_at, a.next_profile_check_at, "
|
||||
+ "a.last_stories_check_at, a.next_stories_check_at, a.notices, a.previous_username, a.renamed_at, a.format_unrecognized_at, a.added_at";
|
||||
|
||||
internal const int ColumnCount = 34;
|
||||
|
||||
private static readonly string Visible = string.Join(", ", EntryStateRules.Visible.Select(s => $"'{s}'"));
|
||||
|
||||
internal static Account Read(SqliteDataReader r, int o = 0) => new()
|
||||
{
|
||||
Id = r.GetInt64(o),
|
||||
InstagramId = r.GetTextOrNull(o + 1),
|
||||
Username = r.GetString(o + 2),
|
||||
DisplayName = r.GetTextOrNull(o + 3),
|
||||
IsPrivate = r.GetBool(o + 4),
|
||||
IsFollowed = r.GetBool(o + 5),
|
||||
IsMine = r.GetBool(o + 6),
|
||||
State = r.GetEnum<AccountState>(o + 7),
|
||||
StateChangedAt = r.GetTimeOrNull(o + 8),
|
||||
UnreachableReason = r.GetEnumOrNull<UnreachableReason>(o + 9),
|
||||
KeepUpdated = r.GetBool(o + 10),
|
||||
Frequency = r.GetEnum<Frequency>(o + 11),
|
||||
CustomPostInterval = r.GetMinutesOrNull(o + 12),
|
||||
CustomStoryInterval = r.GetMinutesOrNull(o + 13),
|
||||
ContentTypes = (ContentTypes)r.GetInt32(o + 14),
|
||||
Limits = new AccountLimits
|
||||
{
|
||||
Depth = r.GetEnum<HistoryDepth>(o + 15),
|
||||
LastPosts = r.GetInt32OrNull(o + 16),
|
||||
FromDate = r.GetTimeOrNull(o + 17),
|
||||
BackfillPostsPerDay = r.GetInt32(o + 18),
|
||||
MaxVideoBytes = r.GetInt64OrNull(o + 19),
|
||||
StoryVideos = r.GetBool(o + 20),
|
||||
},
|
||||
Folder = r.GetTextOrNull(o + 21),
|
||||
BackfillCursor = r.GetTextOrNull(o + 22),
|
||||
BackfillCompletedAt = r.GetTimeOrNull(o + 23),
|
||||
PostCount = r.GetInt32OrNull(o + 24),
|
||||
LastProfileCheckAt = r.GetTimeOrNull(o + 25),
|
||||
NextProfileCheckAt = r.GetTimeOrNull(o + 26),
|
||||
LastStoriesCheckAt = r.GetTimeOrNull(o + 27),
|
||||
NextStoriesCheckAt = r.GetTimeOrNull(o + 28),
|
||||
Notices = (AccountNotices)r.GetInt32(o + 29),
|
||||
PreviousUsername = r.GetTextOrNull(o + 30),
|
||||
RenamedAt = r.GetTimeOrNull(o + 31),
|
||||
FormatUnrecognizedAt = r.GetTimeOrNull(o + 32),
|
||||
AddedAt = r.GetTime(o + 33),
|
||||
};
|
||||
|
||||
private static void Bind(SqliteCommand c, Account a)
|
||||
{
|
||||
c.With("@instagram_id", Sql.Text(Normalize(a.InstagramId)))
|
||||
.With("@username", NormalizeUsername(a.Username))
|
||||
.With("@display_name", Sql.Text(a.DisplayName))
|
||||
.With("@is_private", Sql.Bool(a.IsPrivate))
|
||||
.With("@is_followed", Sql.Bool(a.IsFollowed))
|
||||
.With("@is_mine", Sql.Bool(a.IsMine))
|
||||
.With("@state", Sql.Enum(a.State))
|
||||
.With("@state_changed_at", Sql.Time(a.StateChangedAt))
|
||||
.With("@unreachable_reason", Sql.Enum(a.UnreachableReason))
|
||||
.With("@keep_updated", Sql.Bool(a.KeepUpdated))
|
||||
.With("@frequency", Sql.Enum(a.Frequency))
|
||||
.With("@custom_post_interval_min", Sql.Minutes(a.CustomPostInterval))
|
||||
.With("@custom_story_interval_min", Sql.Minutes(a.CustomStoryInterval))
|
||||
.With("@content_types", (long)a.ContentTypes)
|
||||
.With("@history_depth", Sql.Enum(a.Limits.Depth))
|
||||
.With("@history_last_posts", Sql.Int(a.Limits.LastPosts))
|
||||
.With("@history_from", Sql.Time(a.Limits.FromDate))
|
||||
.With("@backfill_posts_per_day", (long)a.Limits.BackfillPostsPerDay)
|
||||
.With("@max_video_bytes", Sql.Int(a.Limits.MaxVideoBytes))
|
||||
.With("@story_videos", Sql.Bool(a.Limits.StoryVideos))
|
||||
.With("@folder", Sql.Text(a.Folder))
|
||||
.With("@backfill_cursor", Sql.Text(a.BackfillCursor))
|
||||
.With("@backfill_completed_at", Sql.Time(a.BackfillCompletedAt))
|
||||
.With("@post_count", Sql.Int(a.PostCount))
|
||||
.With("@last_profile_check_at", Sql.Time(a.LastProfileCheckAt))
|
||||
.With("@next_profile_check_at", Sql.Time(a.NextProfileCheckAt))
|
||||
.With("@last_stories_check_at", Sql.Time(a.LastStoriesCheckAt))
|
||||
.With("@next_stories_check_at", Sql.Time(a.NextStoriesCheckAt))
|
||||
.With("@notices", (long)a.Notices)
|
||||
.With("@previous_username", Sql.Text(a.PreviousUsername))
|
||||
.With("@renamed_at", Sql.Time(a.RenamedAt))
|
||||
.With("@format_unrecognized_at", Sql.Time(a.FormatUnrecognizedAt))
|
||||
.With("@added_at", Sql.Time(a.AddedAt));
|
||||
}
|
||||
|
||||
private static string? Normalize(string? instagramId) => string.IsNullOrWhiteSpace(instagramId) ? null : instagramId.Trim();
|
||||
|
||||
private static string NormalizeUsername(string username) => username.Trim().TrimStart('@');
|
||||
|
||||
private static void Validate(Account account)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(account);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(account.Username);
|
||||
if (account.Limits.BackfillPostsPerDay < 0)
|
||||
{
|
||||
throw new ArgumentException("Il massimo di storico al giorno non può essere negativo.", nameof(account));
|
||||
}
|
||||
|
||||
if (account.Frequency == Frequency.Custom && (account.CustomPostInterval is null || account.CustomStoryInterval is null))
|
||||
{
|
||||
throw new ArgumentException("Con la frequenza «Su misura» servono i due intervalli.", nameof(account));
|
||||
}
|
||||
}
|
||||
|
||||
public Task<Account?> GetAsync(long accountId, CancellationToken ct = default) =>
|
||||
db.ReadAsync(c => ReadOne(c.Command($"SELECT {Columns} FROM account a WHERE a.id = @id").With("@id", accountId)), ct);
|
||||
|
||||
public Task<Account?> FindByInstagramIdAsync(string instagramId, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(instagramId);
|
||||
return db.ReadAsync(
|
||||
c => ReadOne(c.Command($"SELECT {Columns} FROM account a WHERE a.instagram_id = @id").With("@id", instagramId.Trim())),
|
||||
ct);
|
||||
}
|
||||
|
||||
public Task<Account?> FindByUsernameAsync(string username, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(username);
|
||||
var name = username.Trim().TrimStart('@');
|
||||
return db.ReadAsync(
|
||||
c => ReadOne(c.Command($"SELECT {Columns} FROM account a WHERE a.username = @u ORDER BY a.id LIMIT 1").With("@u", name)),
|
||||
ct);
|
||||
}
|
||||
|
||||
public Task<Account?> GetMineAsync(CancellationToken ct = default) =>
|
||||
db.ReadAsync(c => ReadOne(c.Command($"SELECT {Columns} FROM account a WHERE a.is_mine = 1")), ct);
|
||||
|
||||
public Task<IReadOnlyList<Account>> ListAsync(CancellationToken ct = default) =>
|
||||
db.ReadAsync<IReadOnlyList<Account>>(
|
||||
c =>
|
||||
{
|
||||
using var r = c.Command($"SELECT {Columns} FROM account a ORDER BY a.username, a.id").ExecuteReader();
|
||||
var list = new List<Account>();
|
||||
while (r.Read())
|
||||
{
|
||||
list.Add(Read(r));
|
||||
}
|
||||
|
||||
return list;
|
||||
},
|
||||
ct);
|
||||
|
||||
public Task<IReadOnlyList<AccountSummary>> ListSummariesAsync(DateTimeOffset newSince, CancellationToken ct = default) =>
|
||||
db.ReadAsync<IReadOnlyList<AccountSummary>>(
|
||||
c =>
|
||||
{
|
||||
// One pass over the (account, kind, state, discovered) index for every account at once.
|
||||
var counts = new Dictionary<long, (int Entries, int Posts, int NewPosts, int NewStories)>();
|
||||
var sql = $"""
|
||||
SELECT e.account_id,
|
||||
SUM(e.kind <> 'ProfilePicture' AND e.state IN ({Visible})),
|
||||
SUM(e.kind = 'Post' AND e.state IN ({Visible})),
|
||||
SUM(e.kind = 'Post' AND e.discovered_at >= @since),
|
||||
SUM(e.kind = 'Story' AND e.discovered_at >= @since)
|
||||
FROM entry e GROUP BY e.account_id
|
||||
""";
|
||||
using (var r = c.Command(sql).With("@since", Sql.Time(newSince)).ExecuteReader())
|
||||
{
|
||||
while (r.Read())
|
||||
{
|
||||
counts[r.GetInt64(0)] = (r.GetInt32(1), r.GetInt32(2), r.GetInt32(3), r.GetInt32(4));
|
||||
}
|
||||
}
|
||||
|
||||
using var accounts = c.Command($"SELECT {Columns} FROM account a ORDER BY a.username, a.id").ExecuteReader();
|
||||
var list = new List<AccountSummary>();
|
||||
while (accounts.Read())
|
||||
{
|
||||
var account = Read(accounts);
|
||||
var (entries, posts, newPosts, newStories) = counts.GetValueOrDefault(account.Id);
|
||||
list.Add(new AccountSummary(account, entries, posts, newPosts, newStories));
|
||||
}
|
||||
|
||||
return list;
|
||||
},
|
||||
ct);
|
||||
|
||||
public Task<AccountStats> GetStatsAsync(long accountId, CancellationToken ct = default) =>
|
||||
db.ReadAsync(
|
||||
c =>
|
||||
{
|
||||
var sql = $"""
|
||||
SELECT e.kind, COUNT(*), MAX(e.published_at) FROM entry e
|
||||
WHERE e.account_id = @a AND e.state IN ({Visible}) GROUP BY e.kind
|
||||
""";
|
||||
var stats = new AccountStats { AccountId = accountId };
|
||||
DateTimeOffset? last = null;
|
||||
using (var r = c.Command(sql).With("@a", accountId).ExecuteReader())
|
||||
{
|
||||
while (r.Read())
|
||||
{
|
||||
var kind = r.GetEnum<EntryKind>(0);
|
||||
var count = r.GetInt32(1);
|
||||
var max = r.GetTimeOrNull(2);
|
||||
stats = kind switch
|
||||
{
|
||||
EntryKind.Post => stats with { Posts = count },
|
||||
EntryKind.Story => stats with { Stories = count },
|
||||
EntryKind.Highlight => stats with { HighlightItems = count },
|
||||
EntryKind.Tagged => stats with { Tagged = count },
|
||||
EntryKind.ProfilePicture => stats with { ProfilePictures = count },
|
||||
_ => stats,
|
||||
};
|
||||
if (kind != EntryKind.ProfilePicture && max is { } m && (last is null || m > last))
|
||||
{
|
||||
last = m;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var bytes = c.Command("""
|
||||
SELECT COALESCE(SUM(m.bytes), 0) FROM media m JOIN entry e ON e.id = m.entry_id
|
||||
WHERE e.account_id = @a AND m.state IN ('Downloaded', 'Imported')
|
||||
""").With("@a", accountId).ScalarInt64();
|
||||
var pending = c.Command("""
|
||||
SELECT COUNT(*) FROM media m JOIN entry e ON e.id = m.entry_id
|
||||
WHERE e.account_id = @a AND m.state IN ('ToDownload', 'Expired')
|
||||
""").With("@a", accountId).ScalarInt64();
|
||||
var collections = c.Command("SELECT COUNT(*) FROM highlight WHERE account_id = @a AND removed_at IS NULL")
|
||||
.With("@a", accountId).ScalarInt64();
|
||||
|
||||
return stats with
|
||||
{
|
||||
EntriesInLibrary = stats.Posts + stats.Stories + stats.HighlightItems + stats.Tagged,
|
||||
Bytes = bytes,
|
||||
PendingFiles = (int)pending,
|
||||
HighlightCollections = (int)collections,
|
||||
LastPublishedAt = last,
|
||||
};
|
||||
},
|
||||
ct);
|
||||
|
||||
public Task<Account> AddAsync(Account account, CancellationToken ct = default)
|
||||
{
|
||||
Validate(account);
|
||||
return db.WriteAsync(
|
||||
w =>
|
||||
{
|
||||
var c = w.Command("""
|
||||
INSERT INTO account (instagram_id, username, display_name, is_private, is_followed, is_mine, state, state_changed_at,
|
||||
unreachable_reason, keep_updated, frequency, custom_post_interval_min, custom_story_interval_min, content_types,
|
||||
history_depth, history_last_posts, history_from, backfill_posts_per_day, max_video_bytes, story_videos, folder,
|
||||
backfill_cursor, backfill_completed_at, post_count, last_profile_check_at, next_profile_check_at,
|
||||
last_stories_check_at, next_stories_check_at, notices, previous_username, renamed_at, format_unrecognized_at, added_at)
|
||||
VALUES (@instagram_id, @username, @display_name, @is_private, @is_followed, @is_mine, @state, @state_changed_at,
|
||||
@unreachable_reason, @keep_updated, @frequency, @custom_post_interval_min, @custom_story_interval_min, @content_types,
|
||||
@history_depth, @history_last_posts, @history_from, @backfill_posts_per_day, @max_video_bytes, @story_videos, @folder,
|
||||
@backfill_cursor, @backfill_completed_at, @post_count, @last_profile_check_at, @next_profile_check_at,
|
||||
@last_stories_check_at, @next_stories_check_at, @notices, @previous_username, @renamed_at, @format_unrecognized_at, @added_at)
|
||||
""");
|
||||
Bind(c, account);
|
||||
try
|
||||
{
|
||||
c.ExecuteNonQuery();
|
||||
}
|
||||
catch (SqliteException ex) when (ex.IsUniqueViolation())
|
||||
{
|
||||
throw new DuplicateRecordException(
|
||||
account.IsMine
|
||||
? "Esiste già un account con lo stesso identificativo Instagram, oppure il profilo «Tu» è già presente."
|
||||
: "Esiste già un account con lo stesso identificativo Instagram.",
|
||||
ex);
|
||||
}
|
||||
|
||||
return account with { Id = w.LastInsertRowId(), InstagramId = Normalize(account.InstagramId), Username = NormalizeUsername(account.Username) };
|
||||
},
|
||||
ct);
|
||||
}
|
||||
|
||||
public Task UpdateAsync(Account account, CancellationToken ct = default)
|
||||
{
|
||||
Validate(account);
|
||||
return db.WriteAsync(
|
||||
w =>
|
||||
{
|
||||
var c = w.Command("""
|
||||
UPDATE account SET instagram_id = @instagram_id, username = @username, display_name = @display_name,
|
||||
is_private = @is_private, is_followed = @is_followed, is_mine = @is_mine, state = @state, state_changed_at = @state_changed_at,
|
||||
unreachable_reason = @unreachable_reason, keep_updated = @keep_updated, frequency = @frequency,
|
||||
custom_post_interval_min = @custom_post_interval_min, custom_story_interval_min = @custom_story_interval_min,
|
||||
content_types = @content_types, history_depth = @history_depth, history_last_posts = @history_last_posts,
|
||||
history_from = @history_from, backfill_posts_per_day = @backfill_posts_per_day, max_video_bytes = @max_video_bytes,
|
||||
story_videos = @story_videos, folder = @folder, backfill_cursor = @backfill_cursor,
|
||||
backfill_completed_at = @backfill_completed_at, post_count = @post_count,
|
||||
last_profile_check_at = @last_profile_check_at, next_profile_check_at = @next_profile_check_at,
|
||||
last_stories_check_at = @last_stories_check_at, next_stories_check_at = @next_stories_check_at, notices = @notices,
|
||||
previous_username = @previous_username, renamed_at = @renamed_at, format_unrecognized_at = @format_unrecognized_at,
|
||||
added_at = @added_at
|
||||
WHERE id = @id
|
||||
""");
|
||||
Bind(c, account);
|
||||
c.With("@id", account.Id);
|
||||
try
|
||||
{
|
||||
RequireOne(c.ExecuteNonQuery(), account.Id);
|
||||
}
|
||||
catch (SqliteException ex) when (ex.IsUniqueViolation())
|
||||
{
|
||||
throw new DuplicateRecordException("Esiste già un account con lo stesso identificativo Instagram, oppure il profilo «Tu» è già presente.", ex);
|
||||
}
|
||||
},
|
||||
ct);
|
||||
}
|
||||
|
||||
public Task SetStateAsync(long accountId, AccountState state, DateTimeOffset at, UnreachableReason? reason = null, CancellationToken ct = default) =>
|
||||
db.WriteAsync(
|
||||
w => RequireOne(
|
||||
w.Command("""
|
||||
UPDATE account SET state = @state, unreachable_reason = @reason,
|
||||
state_changed_at = CASE WHEN state = @state THEN state_changed_at ELSE @at END
|
||||
WHERE id = @id
|
||||
""")
|
||||
.With("@state", Sql.Enum(state))
|
||||
.With("@reason", state == AccountState.Unreachable ? Sql.Enum(reason) : DBNull.Value)
|
||||
.With("@at", Sql.Time(at))
|
||||
.With("@id", accountId)
|
||||
.ExecuteNonQuery(),
|
||||
accountId),
|
||||
ct);
|
||||
|
||||
public Task UpdateChecksAsync(long accountId, AccountCheckTimes times, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(times);
|
||||
return db.WriteAsync(
|
||||
w => RequireOne(
|
||||
w.Command("""
|
||||
UPDATE account SET
|
||||
last_profile_check_at = COALESCE(@lp, last_profile_check_at),
|
||||
next_profile_check_at = COALESCE(@np, next_profile_check_at),
|
||||
last_stories_check_at = COALESCE(@ls, last_stories_check_at),
|
||||
next_stories_check_at = COALESCE(@ns, next_stories_check_at),
|
||||
post_count = COALESCE(@pc, post_count),
|
||||
is_private = COALESCE(@pr, is_private),
|
||||
is_followed = COALESCE(@fo, is_followed),
|
||||
display_name = COALESCE(@dn, display_name)
|
||||
WHERE id = @id
|
||||
""")
|
||||
.With("@lp", Sql.Time(times.LastProfileCheckAt))
|
||||
.With("@np", Sql.Time(times.NextProfileCheckAt))
|
||||
.With("@ls", Sql.Time(times.LastStoriesCheckAt))
|
||||
.With("@ns", Sql.Time(times.NextStoriesCheckAt))
|
||||
.With("@pc", Sql.Int(times.PostCount))
|
||||
.With("@pr", Sql.Bool(times.IsPrivate))
|
||||
.With("@fo", Sql.Bool(times.IsFollowed))
|
||||
.With("@dn", Sql.Text(times.DisplayName))
|
||||
.With("@id", accountId)
|
||||
.ExecuteNonQuery(),
|
||||
accountId),
|
||||
ct);
|
||||
}
|
||||
|
||||
public Task SetBackfillAsync(long accountId, string? cursor, DateTimeOffset? completedAt, CancellationToken ct = default) =>
|
||||
db.WriteAsync(
|
||||
w => RequireOne(
|
||||
w.Command("UPDATE account SET backfill_cursor = @c, backfill_completed_at = @d WHERE id = @id")
|
||||
.With("@c", Sql.Text(cursor))
|
||||
.With("@d", Sql.Time(completedAt))
|
||||
.With("@id", accountId)
|
||||
.ExecuteNonQuery(),
|
||||
accountId),
|
||||
ct);
|
||||
|
||||
public Task RenameAsync(long accountId, string newUsername, DateTimeOffset at, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(newUsername);
|
||||
var name = newUsername.Trim().TrimStart('@');
|
||||
return db.WriteAsync(
|
||||
w =>
|
||||
{
|
||||
string? oldName;
|
||||
using (var r = w.Command("SELECT username, folder FROM account WHERE id = @id").With("@id", accountId).ExecuteReader())
|
||||
{
|
||||
if (!r.Read())
|
||||
{
|
||||
throw new KeyNotFoundException($"Account {accountId} non trovato.");
|
||||
}
|
||||
|
||||
oldName = r.GetString(0);
|
||||
}
|
||||
|
||||
if (string.Equals(oldName, name, StringComparison.Ordinal))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// A default folder follows the user name: pin it to the old name so the folder is kept (spec §4.2).
|
||||
w.Command("""
|
||||
UPDATE account SET folder = COALESCE(folder, @pinned), previous_username = username, username = @u,
|
||||
renamed_at = @at, notices = notices | @renamed
|
||||
WHERE id = @id
|
||||
""")
|
||||
.With("@pinned", WindowsFileNames.SanitizeSegment(oldName))
|
||||
.With("@u", name)
|
||||
.With("@at", Sql.Time(at))
|
||||
.With("@renamed", (long)AccountNotices.Renamed)
|
||||
.With("@id", accountId)
|
||||
.ExecuteNonQuery();
|
||||
},
|
||||
ct);
|
||||
}
|
||||
|
||||
public Task AddNoticesAsync(long accountId, AccountNotices notices, DateTimeOffset at, CancellationToken ct = default) =>
|
||||
db.WriteAsync(
|
||||
w => RequireOne(
|
||||
w.Command("""
|
||||
UPDATE account SET notices = notices | @n,
|
||||
format_unrecognized_at = CASE WHEN (@n & @uf) <> 0 THEN @at ELSE format_unrecognized_at END,
|
||||
renamed_at = CASE WHEN (@n & @rn) <> 0 THEN @at ELSE renamed_at END
|
||||
WHERE id = @id
|
||||
""")
|
||||
.With("@n", (long)notices)
|
||||
.With("@uf", (long)AccountNotices.UnrecognizedFormat)
|
||||
.With("@rn", (long)AccountNotices.Renamed)
|
||||
.With("@at", Sql.Time(at))
|
||||
.With("@id", accountId)
|
||||
.ExecuteNonQuery(),
|
||||
accountId),
|
||||
ct);
|
||||
|
||||
public Task ClearNoticesAsync(long accountId, AccountNotices notices, CancellationToken ct = default) =>
|
||||
db.WriteAsync(
|
||||
w => RequireOne(
|
||||
w.Command("UPDATE account SET notices = notices & ~@n WHERE id = @id")
|
||||
.With("@n", (long)notices)
|
||||
.With("@id", accountId)
|
||||
.ExecuteNonQuery(),
|
||||
accountId),
|
||||
ct);
|
||||
|
||||
public Task DeleteAsync(long accountId, CancellationToken ct = default) =>
|
||||
db.WriteAsync(w => w.Command("DELETE FROM account WHERE id = @id").With("@id", accountId).ExecuteNonQuery(), ct);
|
||||
|
||||
private static Account? ReadOne(SqliteCommand command)
|
||||
{
|
||||
using var r = command.ExecuteReader();
|
||||
return r.Read() ? Read(r) : null;
|
||||
}
|
||||
|
||||
private static void RequireOne(int rows, long accountId)
|
||||
{
|
||||
if (rows == 0)
|
||||
{
|
||||
throw new KeyNotFoundException($"Account {accountId} non trovato.");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user