using Chronos.Data.Migrations;
using Chronos.Data.Repositories;
using Chronos.Data.Sqlite;
namespace Chronos.Data;
/// The repositories of the Chronos schema, bound either to the database (one session per call) or to one transaction.
public abstract class ChronosRepositories
{
private protected ChronosRepositories(DbAccess access)
{
Archives = new ArchiveRepository(access);
Sequences = new SequenceRepository(access);
Frames = new FrameRepository(access);
Renders = new RenderRepository(access);
Jobs = new JobRepository(access);
MediaCards = new MediaCardRepository(access);
Users = new UserRepository(access);
Tokens = new TokenRepository(access);
RenderNodes = new RenderNodeRepository(access);
Settings = new SettingsRepository(access);
Tags = new TagRepository(access);
Audit = new AuditRepository(access);
Uploads = new UploadRepository(access);
Schedules = new ScheduleRepository(access);
FrameRemovals = new FrameRemovalRepository(access);
}
public ArchiveRepository Archives { get; }
public SequenceRepository Sequences { get; }
public FrameRepository Frames { get; }
public RenderRepository Renders { get; }
public JobRepository Jobs { get; }
public MediaCardRepository MediaCards { get; }
public UserRepository Users { get; }
public TokenRepository Tokens { get; }
public RenderNodeRepository RenderNodes { get; }
public SettingsRepository Settings { get; }
public TagRepository Tags { get; }
public AuditRepository Audit { get; }
public UploadRepository Uploads { get; }
/// Scheduled jobs (owner review 2, R10).
public ScheduleRepository Schedules { get; }
/// Tombstones of the photos removed from sequences (owner review 2, R6).
public FrameRemovalRepository FrameRemovals { get; }
}
///
/// Entry point of the data layer: opens SQLite or PostgreSQL, migrates the schema and exposes the repositories.
/// Each repository call borrows a pooled session; use to group calls atomically.
///
///
///
/// await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Parse(connectionString), ct);
/// var page = await db.Sequences.ListAsync(new SequenceQuery { Year = 2026 }, ct);
/// await using var tx = await db.BeginAsync(ct);
/// await tx.Frames.InsertAsync(frame, ct);
/// await tx.Sequences.RefreshStatsAsync(frame.SequenceId, ct);
/// await tx.CommitAsync(ct);
///
///
public sealed class ChronosDatabase : ChronosRepositories, IAsyncDisposable
{
private ChronosDatabase(IDatabase database, int schemaVersion)
: base(new DbAccess(database))
{
Database = database;
SchemaVersion = schemaVersion;
}
/// The underlying engine, for raw sessions and engine-specific features (backups, LISTEN).
public IDatabase Database { get; }
public Dialect Dialect => Database.Dialect;
/// Schema version after migration.
public int SchemaVersion { get; private set; }
///
/// Opens the database and applies pending migrations. Throws when a newer
/// build already migrated it.
///
public static async Task OpenAsync(DatabaseOptions options, CancellationToken cancellationToken = default)
{
var database = DatabaseFactory.Open(options);
try
{
var version = await MigrationRunner.MigrateAsync(database, cancellationToken).ConfigureAwait(false);
return new ChronosDatabase(database, version);
}
catch
{
await database.DisposeAsync().ConfigureAwait(false);
throw;
}
}
/// Starts a transaction whose repositories all run on it; dispose without committing to roll back.
public async Task BeginAsync(CancellationToken cancellationToken = default)
{
var session = await Database.OpenAsync(cancellationToken).ConfigureAwait(false);
try
{
return new ChronosTransaction(session, await session.BeginAsync(cancellationToken).ConfigureAwait(false));
}
catch
{
await session.DisposeAsync().ConfigureAwait(false);
throw;
}
}
/// SQLite only: writes a VACUUM INTO copy into , keeping the newest .
public Task BackupAsync(string directory, int keep = 3, CancellationToken cancellationToken = default) =>
AsSqlite().BackupAsync(directory, keep, cancellationToken);
/// SQLite only: replaces the database with a backup, then migrates it to this build's schema.
public async Task RestoreAsync(string backupPath, CancellationToken cancellationToken = default)
{
await AsSqlite().RestoreAsync(backupPath, cancellationToken).ConfigureAwait(false);
SchemaVersion = await MigrationRunner.MigrateAsync(Database, cancellationToken).ConfigureAwait(false);
}
///
/// SQLite only: the size of the database file and the bytes its free pages hold, which gives
/// back; null on PostgreSQL, whose autovacuum keeps the tables compact by itself.
///
public async Task SpaceAsync(CancellationToken cancellationToken = default)
{
if (Dialect != Dialect.Sqlite) return null;
await using var session = await Database.OpenAsync(cancellationToken).ConfigureAwait(false);
var pageSize = await session.ScalarAsync("PRAGMA page_size", [], cancellationToken).ConfigureAwait(false);
var pages = await session.ScalarAsync("PRAGMA page_count", [], cancellationToken).ConfigureAwait(false);
var free = await session.ScalarAsync("PRAGMA freelist_count", [], cancellationToken).ConfigureAwait(false);
return new IndexSpace(pages * pageSize, free * pageSize);
}
///
/// SQLite only: rewrites the database without its free pages (VACUUM, BRIEF ยง12.5 Maintenance). Writers wait
/// meanwhile; readers continue on the previous snapshot. Returns the space before and after.
///
public async Task<(IndexSpace Before, IndexSpace After)> VacuumAsync(CancellationToken cancellationToken = default)
{
AsSqlite();
var before = (await SpaceAsync(cancellationToken).ConfigureAwait(false))!;
await using (var session = await Database.OpenAsync(cancellationToken).ConfigureAwait(false))
await session.ExecuteScriptAsync("VACUUM", cancellationToken).ConfigureAwait(false);
var after = (await SpaceAsync(cancellationToken).ConfigureAwait(false))!;
return (before, after);
}
public ValueTask DisposeAsync() => Database.DisposeAsync();
private SqliteDatabase AsSqlite() =>
Database as SqliteDatabase ?? throw new NotSupportedException("Backups of a PostgreSQL database are made with the server's own tools.");
}
/// Size of an SQLite index file and the bytes of its free pages (reclaimable by a vacuum).
public sealed record IndexSpace(long FileBytes, long ReclaimableBytes);
/// Repositories bound to one open transaction.
public sealed class ChronosTransaction : ChronosRepositories, IAsyncDisposable
{
private readonly IDbTransaction _transaction;
internal ChronosTransaction(IDbSession session, IDbTransaction transaction)
: base(new DbAccess(session))
{
Session = session;
_transaction = transaction;
}
/// The session the transaction runs on, for statements of your own inside it.
public IDbSession Session { get; }
public Task CommitAsync(CancellationToken cancellationToken = default) => _transaction.CommitAsync(cancellationToken);
public Task RollbackAsync(CancellationToken cancellationToken = default) => _transaction.RollbackAsync(cancellationToken);
/// Rolls back unless committed, and returns the session to the pool.
public async ValueTask DisposeAsync()
{
try
{
await _transaction.DisposeAsync().ConfigureAwait(false);
}
finally
{
await Session.DisposeAsync().ConfigureAwait(false);
}
}
}