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_core::memory::{Produced, ProductionControl, ProductionVec};
11use uqa_sql::SQLError;
12
13pub trait RelationLockSession {
14    fn acquire(
15        &self,
16        name: &str,
17        mode: RelationLockMode,
18        nowait: bool,
19    ) -> Result<Option<ScopedRelationLock<'_>>, SQLError>;
20    fn refresh_after_wait(&self) -> Result<(), SQLError>;
21}
22
23/// Definition writers acquire and revalidate logical locks before physical write admission.
24pub trait RelationDefinitionSession: RelationLockSession {
25    fn prepare_definition_write(&self) -> Result<(), SQLError>;
26}
27
28pub trait RelationLockCatalog {
29    fn relation_object_id(&self, name: &str) -> Result<Option<[u8; 16]>, SQLError>;
30    fn relation_object_id_with_control(
31        &self,
32        name: &str,
33        control: &ProductionControl<'_>,
34    ) -> Result<Option<[u8; 16]>, SQLError>;
35    fn table_name_with_control(
36        &self,
37        object_id: [u8; 16],
38        control: &ProductionControl<'_>,
39    ) -> Result<Option<Produced<String>>, SQLError>;
40    /// The `pg_class` OID of a table, view, materialized view or foreign table, which addresses its catalog tuple.
41    fn relation_catalog_oid(&self, name: &str) -> Result<Option<u32>, SQLError>;
42    fn table_name(&self, object_id: [u8; 16]) -> Option<String>;
43    /// The current name of the table, view, materialized view, sequence or foreign table with the object identity.
44    fn relation_name(&self, object_id: [u8; 16]) -> Option<String>;
45}
46
47pub struct RelationBinding<T> {
48    pub name: String,
49    pub object_id: Option<[u8; 16]>,
50    pub value: T,
51}
52
53pub fn acquire_relation<'a>(
54    session: &'a dyn RelationLockSession,
55    name: &str,
56    mode: RelationLockMode,
57    nowait: bool,
58) -> Result<ScopedRelationLock<'a>, SQLError> {
59    session.acquire(name, mode, nowait)?.ok_or_else(|| {
60        let local = uqa_core::RelationIdentity::parse_reference(name)
61            .map_or_else(|_| name.to_string(), |(_, local)| local);
62        SQLError::Routine {
63            sqlstate: "55P03".into(),
64            message: format!("could not obtain lock on relation \"{local}\""),
65        }
66    })
67}
68
69/// 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.
70pub fn lock_any_relation_identity(
71    catalog: &dyn RelationLockCatalog,
72    session: &dyn RelationLockSession,
73    mut name: String,
74    object_id: [u8; 16],
75    mode: RelationLockMode,
76) -> Result<Option<String>, SQLError> {
77    loop {
78        let acquired = acquire_relation(session, &name, mode, false)?;
79        session.refresh_after_wait()?;
80        let Some(current) = catalog.relation_name(object_id) else {
81            return Ok(None);
82        };
83        if current == name {
84            acquired.retain();
85            return Ok(Some(current));
86        }
87        name = current;
88    }
89}
90
91/// 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.
92pub fn bind_relation<T>(
93    session: &dyn RelationLockSession,
94    mode: RelationLockMode,
95    nowait: bool,
96    resolve: impl FnMut() -> Result<Option<RelationBinding<T>>, SQLError>,
97    validate: impl FnMut(&RelationBinding<T>) -> Result<(), SQLError>,
98) -> Result<Option<RelationBinding<T>>, SQLError> {
99    bind_relation_with_mode(session, |_| mode, nowait, resolve, validate)
100}
101
102/// Select the lock from the resolved relation kind and repeat that choice if a wait replaces the target.
103pub fn bind_relation_with_mode<T>(
104    session: &dyn RelationLockSession,
105    mode: impl Fn(&RelationBinding<T>) -> RelationLockMode,
106    nowait: bool,
107    mut resolve: impl FnMut() -> Result<Option<RelationBinding<T>>, SQLError>,
108    mut validate: impl FnMut(&RelationBinding<T>) -> Result<(), SQLError>,
109) -> Result<Option<RelationBinding<T>>, SQLError> {
110    loop {
111        let Some(initial) = resolve()? else {
112            return Ok(None);
113        };
114        validate(&initial)?;
115        let lock_mode = mode(&initial);
116        let guard = acquire_relation(session, &initial.name, lock_mode, nowait)?;
117        session.refresh_after_wait()?;
118        let Some(current) = resolve()? else {
119            return Ok(None);
120        };
121        if initial.name == current.name
122            && initial.object_id == current.object_id
123            && lock_mode == mode(&current)
124        {
125            validate(&current)?;
126            guard.retain();
127            return Ok(Some(current));
128        }
129    }
130}
131
132/// Inherited members retain their original identity through a concurrent rename. A dropped member is skipped; a reused old name never substitutes for that member.
133pub fn lock_descendants(
134    catalog: &dyn RelationLockCatalog,
135    session: &dyn RelationLockSession,
136    names: impl Iterator<Item = String>,
137    mode: RelationLockMode,
138    nowait: bool,
139) -> Result<(), SQLError> {
140    let targets = names
141        .map(|name| {
142            catalog
143                .relation_object_id(&name)
144                .map(|id| id.map(|id| (name, id)))
145        })
146        .collect::<Result<Vec<_>, _>>()?;
147    for (name, object_id) in targets.into_iter().flatten() {
148        lock_relation_identity(catalog, session, name, object_id, mode, nowait)?;
149    }
150    Ok(())
151}
152
153/// Return the current locked name of the original table, or None if it was removed.
154pub fn lock_relation_identity(
155    catalog: &dyn RelationLockCatalog,
156    session: &dyn RelationLockSession,
157    name: String,
158    object_id: [u8; 16],
159    mode: RelationLockMode,
160    nowait: bool,
161) -> Result<Option<String>, SQLError> {
162    lock_table_identity(
163        session,
164        name,
165        String::as_str,
166        || Ok(catalog.table_name(object_id)),
167        mode,
168        nowait,
169        &ProductionControl::uncontrolled(),
170    )
171}
172
173fn lock_table_identity<T>(
174    session: &dyn RelationLockSession,
175    mut name: T,
176    as_name: impl Fn(&T) -> &str,
177    mut current_name: impl FnMut() -> Result<Option<T>, SQLError>,
178    mode: RelationLockMode,
179    nowait: bool,
180    control: &ProductionControl<'_>,
181) -> Result<Option<T>, SQLError> {
182    loop {
183        control.check()?;
184        let acquired = match acquire_relation(session, as_name(&name), mode, nowait) {
185            Err(error) if error.sqlstate() != Some("55P03") => return Err(error),
186            other => other,
187        };
188        session.refresh_after_wait()?;
189        let Some(current) = current_name()? else {
190            return Ok(None);
191        };
192        if as_name(&current) == as_name(&name) {
193            acquired?.retain();
194            return Ok(Some(current));
195        }
196        name = current;
197    }
198}
199
200/// Resolve every selected descendant before the first wait, then retain each original identity through rename or removal. Scratch and renamed spellings keep the invoking allowance.
201pub fn lock_descendants_with_control<'a>(
202    catalog: &dyn RelationLockCatalog,
203    session: &dyn RelationLockSession,
204    names: impl Iterator<Item = &'a str>,
205    mode: RelationLockMode,
206    nowait: bool,
207    control: &ProductionControl<'_>,
208) -> Result<(), SQLError> {
209    control.check()?;
210    let mut targets = ProductionVec::new(*control);
211    for name in names {
212        if let Some(object_id) = catalog.relation_object_id_with_control(name, control)? {
213            targets.push_copy((name, object_id))?;
214        }
215    }
216    for (name, object_id) in targets.iter() {
217        lock_table_identity(
218            session,
219            control.copy_text(name)?,
220            |name| name.as_str(),
221            || catalog.table_name_with_control(*object_id, control),
222            mode,
223            nowait,
224            control,
225        )?;
226    }
227    Ok(())
228}
229
230#[cfg(test)]
231mod tests;