using Chronos.Core.Model;
namespace Chronos.Data.Repositories;
/// Exports of sequences; keeps sequences.rendered_count in step.
public sealed class RenderRepository
{
private const string Columns =
"id, sequence_id, preset_name, settings_json, output_path, codec, width, height, fps, duration_seconds, bytes, created, produced_by";
private const string RecountSql =
"UPDATE sequences SET rendered_count = (SELECT count(*) FROM renders WHERE sequence_id = $1) WHERE id = $1";
private readonly DbAccess _db;
internal RenderRepository(DbAccess db) => _db = db;
public Task InsertAsync(Render render, CancellationToken cancellationToken = default) =>
_db.InTransactionAsync(async session =>
{
await LockSequenceAsync(session, render.SequenceId, cancellationToken).ConfigureAwait(false);
await session.ExecuteAsync($"INSERT INTO renders ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)",
[
render.Id, render.SequenceId, render.PresetName, DbParam.Json(render.SettingsJson), render.OutputPath, render.Codec,
render.Width, render.Height, render.Fps, render.DurationSeconds, render.Bytes, render.Created, render.ProducedBy,
], cancellationToken).ConfigureAwait(false);
return await session.ExecuteAsync(RecountSql, [render.SequenceId], cancellationToken).ConfigureAwait(false);
}, cancellationToken);
public Task GetAsync(Guid id, CancellationToken cancellationToken = default) =>
_db.SingleAsync($"SELECT {Columns} FROM renders WHERE id = $1", [id], Map, cancellationToken);
/// Renders of a sequence, newest first.
public Task> ListBySequenceAsync(Guid sequenceId, CancellationToken cancellationToken = default) =>
_db.ListAsync($"SELECT {Columns} FROM renders WHERE sequence_id = $1 ORDER BY created DESC, id DESC", [sequenceId], Map, cancellationToken);
public Task DeleteAsync(Guid id, CancellationToken cancellationToken = default) =>
_db.InTransactionAsync(async session =>
{
var sequenceId = await session.ScalarAsync("SELECT sequence_id FROM renders WHERE id = $1", [id], cancellationToken).ConfigureAwait(false);
if (sequenceId is null) return false;
await LockSequenceAsync(session, sequenceId.Value, cancellationToken).ConfigureAwait(false);
if (await session.ExecuteAsync("DELETE FROM renders WHERE id = $1", [id], cancellationToken).ConfigureAwait(false) == 0) return false;
await session.ExecuteAsync(RecountSql, [sequenceId], cancellationToken).ConfigureAwait(false);
return true;
}, cancellationToken);
///
/// Rewrites the archive-relative output paths of an archive's renders after the folder of sequence
/// moved (a Reorganize, or a move another index of the archive or the user made, which a
/// scan finds): an export inside the folder moved with it. Each render under the old folder whose file
/// the folder takes the new path: the caller tells the sequence's own exports there (which
/// follow unless their file stayed behind) from an export of another sequence saved inside it through the Export
/// folder picker (which follows only when its file moved with the folder: a sequence that took the old folder since, by
/// a later Reorganize another index made, keeps its own). An export of the sequence whose path an export of another
/// sequence names follows without asking: that path is the other sequence's now, which brought an export of that name
/// into the old folder. Outputs elsewhere (absolute paths, other folders) stay as they are.
///
/// Whether the render at the first archive-relative path follows to the second one; the third
/// argument is the sequence it is an export of.
/// Only paths still under change, so repeating it after a crash is harmless.
public async Task RebaseFolderAsync(Guid archiveId, Guid sequenceId, string oldFolder, string newFolder, Func follows,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(follows);
// The archive root never moves, and its prefix ("/") would match absolute paths outside the archive.
if (oldFolder.Length == 0) return 0;
// substr counts characters (code points) on both dialects.
var prefix = oldFolder + "/";
var under = await _db.ListAsync(
"SELECT r.id, r.sequence_id, r.output_path FROM renders r JOIN sequences s ON s.id = r.sequence_id WHERE s.archive_id = $1 AND substr(r.output_path, 1, $2) = $3",
[archiveId, prefix.EnumerateRunes().Count(), prefix], r => (Id: r.GetGuid(0), SequenceId: r.GetGuid(1), Path: r.GetString(2)), cancellationToken)
.ConfigureAwait(false);
var rebased = 0;
foreach (var (id, owner, path) in under)
{
var to = newFolder.Length == 0 ? path[prefix.Length..] : newFolder + path[oldFolder.Length..];
var taken = owner == sequenceId && under.Any(o => o.SequenceId != sequenceId && string.Equals(o.Path, path, StringComparison.Ordinal));
if (!taken && !follows(path, to, owner)) continue;
rebased += await _db.ExecuteAsync("UPDATE renders SET output_path = $2 WHERE id = $1", [id, to], cancellationToken).ConfigureAwait(false);
}
return rebased;
}
///
/// Serialises render changes per sequence on PostgreSQL, so the recount (a new statement, hence a new snapshot)
/// sees every committed render; SQLite's write lock already does this.
///
private async Task LockSequenceAsync(IDbSession session, Guid sequenceId, CancellationToken cancellationToken)
{
if (_db.Sql.IsPostgres) await SequenceRepository.LockAsync(session, sequenceId, cancellationToken).ConfigureAwait(false);
}
private static Render Map(DbRow r) => new()
{
Id = r.GetGuid(0),
SequenceId = r.GetGuid(1),
PresetName = r.GetString(2),
SettingsJson = r.GetStringOrNull(3),
OutputPath = r.GetString(4),
Codec = r.GetStringOrNull(5),
Width = r.GetInt32(6),
Height = r.GetInt32(7),
Fps = r.GetDouble(8),
DurationSeconds = r.GetDouble(9),
Bytes = r.GetInt64(10),
Created = r.GetDateTimeOffset(11),
ProducedBy = r.GetStringOrNull(12),
};
}