namespace Khaemhat.Data;
/// Helpers on .
public static class UnitOfWorkExtensions
{
///
/// Takes the application lock until the end of the current transaction (numerators, closings,
/// scheduler): pg_advisory_xact_lock on PostgreSQL; on SQLite the transaction already holds the write lock.
///
/// The unit of work, with an open transaction.
/// The lock key, for example numerator:FV:2026.
/// Cancellation.
/// A task completed when the lock is held.
public static async Task AcquireLockAsync(this IUnitOfWork unitOfWork, string key, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(unitOfWork);
ArgumentException.ThrowIfNullOrEmpty(key);
if (unitOfWork.Transaction is null)
{
throw new InvalidOperationException("An application lock is held until the end of a transaction: call BeginAsync first.");
}
var statement = unitOfWork.Dialect.AdvisoryLock(key);
if (!statement.IsEmpty)
{
await unitOfWork.ExecuteAsync(statement, cancellationToken).ConfigureAwait(false);
}
}
/// Runs in a transaction: commits if it completes, rolls back if it throws.
/// The unit of work.
/// The work.
/// Cancellation.
/// A task.
public static async Task InTransactionAsync(this IUnitOfWork unitOfWork, Func work, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(unitOfWork);
ArgumentNullException.ThrowIfNull(work);
await unitOfWork.BeginAsync(cancellationToken).ConfigureAwait(false);
try
{
await work(cancellationToken).ConfigureAwait(false);
await unitOfWork.CommitAsync(cancellationToken).ConfigureAwait(false);
}
catch
{
if (unitOfWork.Transaction is not null)
{
await unitOfWork.RollbackAsync(CancellationToken.None).ConfigureAwait(false);
}
throw;
}
}
}