Files
Febe/src/Febe.Data/FebeDatabase.cs
T
Alby96andClaude Opus 5.5 ea4666d49b
verifica / controlli (push) Successful in 19s
verifica / prove (push) Canceled after 10m59s
verifica / installatore (push) Canceled after 0s
verifica / immagine (push) Canceled after 0s
E1: schema dell'esportazione, migrazione 0003, archivi ed ExportSettings (#58)
La tappa E1 della 0.3.0 prepara il database per le copie esterne senza cambiare
comportamento: nulla in interfaccia, motore o API usa ancora ciò che segue.

- Migrazione 0003: export_destination, export_account, export_copy, export_run,
  export_item, video_analysis e media_conversion (risposta di Alberto del 26
  novembre: i convertiti per la libreria in una tabella a parte, media non cambia),
  con i vincoli e gli indici di §8.3.
- Archivi IExportStore, IVideoAnalysisStore e IMediaConversionStore in IFebeStorage;
  ExportSettings sulle cinque chiavi esportazione.*.
- AccountStore.DeleteAsync spegne «Automatica» delle cartelle dell'account e vi
  scrive il suo nome prima di cancellarlo (finché non ci sono destinazioni non fa nulla).
- Prove: aggiornamento dei database delle versioni 1 e 2 con foreign_key_check
  pulito, database più nuovo rifiutato e lasciato intatto, vincoli, archivi,
  piani delle ricerche, impostazioni e documenti.
- SPECIFICA §4.10, §8.3 e §15, decisioni.md e stato.md aggiornati.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 19:29:14 +01:00

245 lines
8.8 KiB
C#

using Febe.Core.Storage;
using Febe.Data.Stores;
using Microsoft.Data.Sqlite;
namespace Febe.Data;
/// <summary>
/// The SQLite database of Febe (spec §8): <c>Dati/febe.sqlite</c> in WAL mode, foreign keys on, busy timeout,
/// numbered migrations applied at start-up. All writes go through one queue and one connection
/// (<see cref="SqliteWriter"/>); reads use separate pooled read-only connections and never block the writer.
/// </summary>
public sealed class FebeDatabase : IFebeStorage, IDatabaseMaintenance
{
/// <summary>File name inside the Data folder.</summary>
public const string FileName = "febe.sqlite";
private const int BusyTimeoutMs = 10_000;
private readonly SqliteConnection _writerConnection;
private readonly string _readConnectionString;
private int _disposed;
private FebeDatabase(string path, SqliteConnection writerConnection, string readConnectionString, int schemaVersion)
{
DatabasePath = path;
_writerConnection = writerConnection;
_readConnectionString = readConnectionString;
SchemaVersion = schemaVersion;
Writer = new SqliteWriter(writerConnection);
Accounts = new AccountStore(this);
Entries = new EntryStore(this);
Media = new MediaStore(this);
Highlights = new HighlightStore(this);
Duplicates = new DuplicateStore(this);
Tasks = new TaskStore(this);
ActionLog = new ActionLogStore(this);
Sessions = new SessionStore(this);
Incidents = new IncidentStore(this);
Events = new EventStore(this);
Following = new FollowingStore(this);
Imports = new ImportStore(this);
Exports = new ExportStore(this);
VideoAnalyses = new VideoAnalysisStore(this);
Conversions = new MediaConversionStore(this);
Settings = new SettingsStore(this);
}
public IAccountStore Accounts { get; }
public IEntryStore Entries { get; }
public IMediaStore Media { get; }
public IHighlightStore Highlights { get; }
public IDuplicateStore Duplicates { get; }
public ITaskStore Tasks { get; }
public IActionLogStore ActionLog { get; }
public ISessionStore Sessions { get; }
public IIncidentStore Incidents { get; }
public IEventStore Events { get; }
public IFollowingStore Following { get; }
public IImportStore Imports { get; }
public IExportStore Exports { get; }
public IVideoAnalysisStore VideoAnalyses { get; }
public IMediaConversionStore Conversions { get; }
public ISettingsStore Settings { get; }
public IDatabaseMaintenance Maintenance => this;
public string DatabasePath { get; }
public int SchemaVersion { get; }
internal SqliteWriter Writer { get; }
/// <summary>Opens (or creates) <c>febe.sqlite</c> inside the Data folder and applies pending migrations.</summary>
public static Task<FebeDatabase> OpenAsync(string dataFolder, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(dataFolder);
return OpenFileAsync(Path.Combine(dataFolder, FileName), ct);
}
/// <summary>Opens (or creates) a database file and applies pending migrations.</summary>
public static Task<FebeDatabase> OpenFileAsync(string databasePath, CancellationToken ct = default) =>
Task.FromResult(Open(databasePath, MigrationRunner.LoadEmbedded(), ct));
internal static FebeDatabase Open(string databasePath, IReadOnlyList<Migration> migrations, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(databasePath);
ct.ThrowIfCancellationRequested();
var path = Path.GetFullPath(databasePath);
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
var writerConnectionString = new SqliteConnectionStringBuilder
{
DataSource = path,
Mode = SqliteOpenMode.ReadWriteCreate,
Cache = SqliteCacheMode.Private,
Pooling = false,
ForeignKeys = true,
DefaultTimeout = BusyTimeoutMs / 1000,
}.ToString();
var readConnectionString = new SqliteConnectionStringBuilder
{
DataSource = path,
Mode = SqliteOpenMode.ReadOnly,
Cache = SqliteCacheMode.Private,
Pooling = true,
DefaultTimeout = BusyTimeoutMs / 1000,
}.ToString();
var connection = new SqliteConnection(writerConnectionString);
try
{
connection.Open();
var mode = connection.Scalar("PRAGMA journal_mode = WAL") as string;
if (!string.Equals(mode, "wal", StringComparison.OrdinalIgnoreCase))
{
throw new DatabaseMigrationException(
$"Febe non riesce a mettere il database in modalità WAL (modalità attuale: {mode}). La cartella dei dati deve stare su un disco locale.");
}
connection.Execute("PRAGMA synchronous = NORMAL");
connection.Execute($"PRAGMA busy_timeout = {BusyTimeoutMs}");
connection.Execute("PRAGMA foreign_keys = ON");
var version = MigrationRunner.Apply(connection, migrations);
return new FebeDatabase(path, connection, readConnectionString, version);
}
catch
{
connection.Dispose();
throw;
}
}
/// <summary>Queues a write; the task completes after the commit.</summary>
internal Task<T> WriteAsync<T>(Func<WriteContext, T> work, CancellationToken ct) => Writer.ExecuteAsync(work, ct);
internal Task WriteAsync(Action<WriteContext> work, CancellationToken ct) => Writer.ExecuteAsync(work, ct);
/// <summary>Runs a read on its own read-only connection.</summary>
internal Task<T> ReadAsync<T>(Func<SqliteConnection, T> work, CancellationToken ct)
{
if (ct.IsCancellationRequested)
{
return Task.FromCanceled<T>(ct);
}
ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this);
try
{
using var connection = OpenReadConnection();
using var commands = CommandScope.Begin(); // disposed first: the connection then really closes
return Task.FromResult(work(connection));
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
return Task.FromException<T>(ex);
}
}
internal SqliteConnection OpenReadConnection()
{
var connection = new SqliteConnection(_readConnectionString);
connection.Open();
return connection;
}
public Task BackupToAsync(string destinationFile, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(destinationFile);
var destination = Path.GetFullPath(destinationFile);
if (File.Exists(destination))
{
throw new IOException($"La copia {destination} esiste già: Febe non la sovrascrive.");
}
Directory.CreateDirectory(Path.GetDirectoryName(destination)!);
return ReadAsync(
connection =>
{
// VACUUM INTO reads a consistent snapshot; it works on a read-only connection and does not block the writer.
using var vacuum = connection.Command("VACUUM INTO @destination").With("@destination", destination);
vacuum.ExecuteNonQuery();
return true;
},
ct);
}
public Task<bool> CheckIntegrityAsync(CancellationToken ct = default) =>
ReadAsync(
connection =>
{
using var reader = connection.Command("PRAGMA quick_check").ExecuteReader();
return reader.Read() && string.Equals(reader.GetString(0), "ok", StringComparison.OrdinalIgnoreCase) && !reader.Read();
},
ct);
public Task OptimizeAsync(CancellationToken ct = default) =>
WriteAsync(context => context.Command("PRAGMA optimize").ExecuteNonQuery(), ct);
public ValueTask DisposeAsync()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0)
{
return ValueTask.CompletedTask;
}
Writer.Dispose();
// The idle read connections close first, so the writer is the last connection: only the writer can checkpoint
// and delete febe.sqlite-wal and -shm when it closes (a read-only connection leaves them behind).
using (var pooled = new SqliteConnection(_readConnectionString))
{
SqliteConnection.ClearPool(pooled);
}
try
{
_writerConnection.Execute("PRAGMA wal_checkpoint(TRUNCATE)");
}
catch (SqliteException)
{
// A reader may still hold a snapshot: the checkpoint is an optimization, not a requirement.
}
_writerConnection.Dispose();
return ValueTask.CompletedTask;
}
}