Skip to main content

uqa_execution/row_locks/
binding.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Retain relation locks only after refreshing and revalidating the selected identity.
8
9use super::{RelationLockMode, ScopedRelationLock};
10use uqa_sql::SQLError;
11
12pub trait RelationLockSession {
13    fn acquire(
14        &self,
15        name: &str,
16        mode: RelationLockMode,
17        nowait: bool,
18    ) -> Result<Option<ScopedRelationLock<'_>>, SQLError>;
19    fn refresh_after_wait(&self) -> Result<(), SQLError>;
20}
21
22/// Definition writers acquire and revalidate logical locks before physical write admission.
23pub trait RelationDefinitionSession: RelationLockSession {
24    fn prepare_definition_write(&self) -> Result<(), SQLError>;
25}
26
27pub trait RelationLockCatalog {
28    fn relation_object_id(&self, name: &str) -> Result<Option<[u8; 16]>, SQLError>;
29    /// The `pg_class` OID of a table, view, materialized view or foreign table, which addresses its catalog tuple.
30    fn relation_catalog_oid(&self, name: &str) -> Result<Option<u32>, SQLError>;
31    fn table_name(&self, object_id: [u8; 16]) -> Option<String>;
32    /// The current name of the table, view, materialized view, sequence or foreign table with the object identity.
33    fn relation_name(&self, object_id: [u8; 16]) -> Option<String>;
34}
35
36pub struct RelationBinding<T> {
37    pub name: String,
38    pub object_id: Option<[u8; 16]>,
39    pub value: T,
40}
41
42pub fn acquire_relation<'a>(
43    session: &'a dyn RelationLockSession,
44    name: &str,
45    mode: RelationLockMode,
46    nowait: bool,
47) -> Result<ScopedRelationLock<'a>, SQLError> {
48    session.acquire(name, mode, nowait)?.ok_or_else(|| {
49        let local = uqa_core::RelationIdentity::parse_reference(name)
50            .map_or_else(|_| name.to_string(), |(_, local)| local);
51        SQLError::Routine {
52            sqlstate: "55P03".into(),
53            message: format!("could not obtain lock on relation \"{local}\""),
54        }
55    })
56}
57
58/// Lock a relation by its object identity, as `PostgreSQL` locks relations by OID: a relation renamed while the lock waited is followed to its new name, and the lock on the old name, which another relation may use now, is released. Returns the locked name, or `None` if the relation was removed while the lock waited.
59pub fn lock_any_relation_identity(
60    catalog: &dyn RelationLockCatalog,
61    session: &dyn RelationLockSession,
62    mut name: String,
63    object_id: [u8; 16],
64    mode: RelationLockMode,
65) -> Result<Option<String>, SQLError> {
66    loop {
67        let acquired = acquire_relation(session, &name, mode, false)?;
68        session.refresh_after_wait()?;
69        let Some(current) = catalog.relation_name(object_id) else {
70            return Ok(None);
71        };
72        if current == name {
73            acquired.retain();
74            return Ok(Some(current));
75        }
76        name = current;
77    }
78}
79
80/// A wait can change both the name's identity and the same object's definition or privileges. Resolve and validate again before retaining the provisional lock; a changed identity releases that acquisition before retrying.
81pub fn bind_relation<T>(
82    session: &dyn RelationLockSession,
83    mode: RelationLockMode,
84    nowait: bool,
85    resolve: impl FnMut() -> Result<Option<RelationBinding<T>>, SQLError>,
86    validate: impl FnMut(&RelationBinding<T>) -> Result<(), SQLError>,
87) -> Result<Option<RelationBinding<T>>, SQLError> {
88    bind_relation_with_mode(session, |_| mode, nowait, resolve, validate)
89}
90
91/// Select the lock from the resolved relation kind and repeat that choice if a wait replaces the target.
92pub fn bind_relation_with_mode<T>(
93    session: &dyn RelationLockSession,
94    mode: impl Fn(&RelationBinding<T>) -> RelationLockMode,
95    nowait: bool,
96    mut resolve: impl FnMut() -> Result<Option<RelationBinding<T>>, SQLError>,
97    mut validate: impl FnMut(&RelationBinding<T>) -> Result<(), SQLError>,
98) -> Result<Option<RelationBinding<T>>, SQLError> {
99    loop {
100        let Some(initial) = resolve()? else {
101            return Ok(None);
102        };
103        validate(&initial)?;
104        let lock_mode = mode(&initial);
105        let guard = acquire_relation(session, &initial.name, lock_mode, nowait)?;
106        session.refresh_after_wait()?;
107        let Some(current) = resolve()? else {
108            return Ok(None);
109        };
110        if initial.name == current.name
111            && initial.object_id == current.object_id
112            && lock_mode == mode(&current)
113        {
114            validate(&current)?;
115            guard.retain();
116            return Ok(Some(current));
117        }
118    }
119}
120
121/// Inherited members retain their original identity through a concurrent rename. A dropped member is skipped; a reused old name never substitutes for that member.
122pub fn lock_descendants(
123    catalog: &dyn RelationLockCatalog,
124    session: &dyn RelationLockSession,
125    names: impl Iterator<Item = String>,
126    mode: RelationLockMode,
127    nowait: bool,
128) -> Result<(), SQLError> {
129    let targets = names
130        .map(|name| {
131            catalog
132                .relation_object_id(&name)
133                .map(|id| id.map(|id| (name, id)))
134        })
135        .collect::<Result<Vec<_>, _>>()?;
136    for (name, object_id) in targets.into_iter().flatten() {
137        lock_relation_identity(catalog, session, name, object_id, mode, nowait)?;
138    }
139    Ok(())
140}
141
142/// Return the current locked name of the original table, or None if it was removed.
143pub fn lock_relation_identity(
144    catalog: &dyn RelationLockCatalog,
145    session: &dyn RelationLockSession,
146    mut name: String,
147    object_id: [u8; 16],
148    mode: RelationLockMode,
149    nowait: bool,
150) -> Result<Option<String>, SQLError> {
151    loop {
152        let acquired = match acquire_relation(session, &name, mode, nowait) {
153            Err(error) if error.sqlstate() != Some("55P03") => return Err(error),
154            other => other,
155        };
156        session.refresh_after_wait()?;
157        let Some(current) = catalog.table_name(object_id) else {
158            return Ok(None);
159        };
160        if current == name {
161            acquired?.retain();
162            return Ok(Some(current));
163        }
164        name = current;
165    }
166}
167
168#[cfg(test)]
169mod tests;