namespace Khaemhat.Data.PostgreSql;
///
/// Application locks on PostgreSQL (SPEC ยง5.2) for numerators, closings and the scheduler. The text key is hashed to
/// 64 bits by the server (hashtextextended); transaction locks are released by commit or rollback.
///
public static class PostgresAdvisoryLocks
{
/// Waits for the lock and holds it until the end of the transaction.
/// The lock key.
/// The statement.
public static SqlFragment TransactionLock(string key)
{
ArgumentException.ThrowIfNullOrEmpty(key);
return SqlFragment.Of($"SELECT pg_advisory_xact_lock(hashtextextended({key}, 0))");
}
/// Takes the lock if free, without waiting; the statement returns a boolean.
/// The lock key.
/// The statement.
public static SqlFragment TryTransactionLock(string key)
{
ArgumentException.ThrowIfNullOrEmpty(key);
return SqlFragment.Of($"SELECT pg_try_advisory_xact_lock(hashtextextended({key}, 0))");
}
}