use tokio_postgres::Client;
use super::error::ApplyError;
pub const PGEVOLVE_LOCK_KEY: i64 = i64::from_be_bytes(*b"PGEVOLVE");
pub async fn try_acquire_lock(client: &Client, actor: &str) -> Result<(), ApplyError> {
let row = client
.query_one("SELECT pg_try_advisory_lock($1)", &[&PGEVOLVE_LOCK_KEY])
.await?;
let acquired: bool = row.get(0);
if !acquired {
return Err(ApplyError::LockHeld);
}
client
.execute(
"UPDATE pgevolve.lock
SET held_by=$1, held_since=now(), pgevolve_version=$2
WHERE singleton=true",
&[&actor, &pgevolve_core::VERSION],
)
.await?;
Ok(())
}
pub async fn release_lock(client: &Client) -> Result<(), ApplyError> {
client
.execute(
"UPDATE pgevolve.lock
SET held_by=NULL, held_since=NULL, pgevolve_version=NULL
WHERE singleton=true",
&[],
)
.await?;
client
.execute("SELECT pg_advisory_unlock($1)", &[&PGEVOLVE_LOCK_KEY])
.await?;
Ok(())
}