Skip to main content

uqa_engine/capabilities/
table_locks.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Bind explicit relation locking to live catalogs and transaction-owned lock marks.
8
9use crate::Engine;
10use uqa_core::memory::{Produced, ProductionControl};
11use uqa_execution::{
12    row_locks::{
13        binding::{RelationDefinitionSession, RelationLockCatalog, RelationLockSession},
14        shared_objects::{SharedCatalogLock, SharedObjectLockSession},
15        RelationLockMode, ScopedRelationLock,
16    },
17    statement::table_locks::{
18        TableLockCatalog, TableLockContext, TableLockMetadata, TableLockSession,
19    },
20};
21use uqa_sql::catalog::roles::RoleReference;
22use uqa_sql::{
23    catalog::{resolution::RelationResolution, stored_view::StoredView},
24    SQLError,
25};
26
27impl Engine {
28    pub(crate) fn table_lock_context(&self) -> TableLockContext<'_> {
29        TableLockContext {
30            catalog: self,
31            roles: self,
32            session: self,
33        }
34    }
35}
36
37impl TableLockCatalog for Engine {
38    fn resolve(&self, name: &str, bound: bool) -> Result<RelationResolution, SQLError> {
39        if bound {
40            self.resolve_bound_relation_kind(name)
41        } else {
42            self.resolve_visible_relation_kind(name)
43        }
44    }
45
46    fn table(
47        &self,
48        name: &str,
49        _roles: &std::collections::BTreeMap<String, uqa_sql::catalog::roles::RoleDefinition>,
50    ) -> Result<Option<TableLockMetadata>, SQLError> {
51        let relation =
52            uqa_core::RelationIdentity::from_legacy_name(name).map_err(SQLError::Internal)?;
53        self.storage
54            .tables
55            .read()
56            .get(&relation)
57            .map(|table| {
58                Ok(TableLockMetadata {
59                    object_id: table.object_id(),
60                    security: table.security(),
61                })
62            })
63            .transpose()
64    }
65
66    fn view(&self, name: &str) -> Result<Option<StoredView>, SQLError> {
67        let relation =
68            uqa_core::RelationIdentity::from_legacy_name(name).map_err(SQLError::Internal)?;
69        Ok(self.durable.views.read().get(&relation).cloned())
70    }
71
72    fn descendants(&self, name: &str) -> Result<Vec<String>, SQLError> {
73        self.hierarchy_scan_tables(name, true)
74    }
75}
76
77impl TableLockSession for Engine {
78    fn in_transaction_block(&self) -> bool {
79        Engine::in_transaction_block(self)
80    }
81    fn current_role(&self) -> RoleReference {
82        self.current_role()
83    }
84}
85
86impl RelationLockSession for Engine {
87    fn acquire(
88        &self,
89        name: &str,
90        mode: RelationLockMode,
91        nowait: bool,
92    ) -> Result<Option<ScopedRelationLock<'_>>, SQLError> {
93        self.prepare_transaction_lock_wait()?;
94        let relation =
95            uqa_core::RelationIdentity::from_legacy_name(name).map_err(SQLError::Internal)?;
96        let identity = self
97            .durable
98            .catalog_indexes
99            .read()
100            .get(&relation)
101            .map(crate::catalog_indexes::index_definition)
102            .transpose()
103            .map_err(|error| {
104                uqa_sql::catalog::errors::storage_error("index lock identity", &error)
105            })?
106            .and_then(|definition| definition.catalog.map(|catalog| catalog.identity.object_id));
107        let table = identity.map_or_else(
108            || self.row_locks.table_key(name),
109            |identity| self.row_locks.index_key(identity),
110        );
111        let marks = self.temporary_relation_lock_marks()?;
112        if nowait {
113            self.row_locks.try_acquire_scoped_relation(
114                self.session_id,
115                table,
116                mode,
117                marks,
118                &self.runtime.cancellation,
119            )
120        } else {
121            self.row_locks
122                .acquire_scoped_relation(
123                    self.session_id,
124                    table,
125                    mode,
126                    marks,
127                    &self.runtime.cancellation,
128                )
129                .map(Some)
130        }
131    }
132    fn refresh_after_wait(&self) -> Result<(), SQLError> {
133        self.refresh_explicit_statement_snapshot()
134    }
135}
136
137impl RelationDefinitionSession for Engine {
138    fn prepare_definition_write(&self) -> Result<(), SQLError> {
139        self.prepare_explicit_transaction_writer().map(|_| ())
140    }
141}
142
143impl SharedObjectLockSession for Engine {
144    fn acquire_shared_catalog(
145        &self,
146        target: SharedCatalogLock<'_>,
147        mode: RelationLockMode,
148    ) -> Result<ScopedRelationLock<'_>, SQLError> {
149        self.prepare_transaction_lock_wait()?;
150        let key = self.row_locks.shared_catalog_key(target);
151        let marks = self.temporary_relation_lock_marks()?;
152        self.row_locks.acquire_scoped_relation(
153            self.session_id,
154            key,
155            mode,
156            marks,
157            &self.runtime.cancellation,
158        )
159    }
160
161    fn refresh_shared_catalog(&self) -> Result<(), SQLError> {
162        self.refresh_explicit_statement_snapshot()
163    }
164
165    fn next_catalog_oid(&self) -> Result<u32, SQLError> {
166        let durable = self
167            .storage
168            .backend
169            .as_ref()
170            .and_then(|backend| backend.identifier_allocator());
171        self.row_locks.catalog_oids().next_oid(durable, || {
172            let catalog = self.catalog_execution();
173            uqa_execution::catalog::projection::largest_catalog_oid(
174                &catalog.catalog_read_view(),
175                &catalog.session.relation_name_resolution(),
176            )
177        })
178    }
179}
180
181impl RelationLockCatalog for Engine {
182    fn relation_object_id(&self, name: &str) -> Result<Option<[u8; 16]>, SQLError> {
183        self.relation_object_id_with_control(name, &ProductionControl::uncontrolled())
184    }
185    fn relation_object_id_with_control(
186        &self,
187        name: &str,
188        control: &ProductionControl<'_>,
189    ) -> Result<Option<[u8; 16]>, SQLError> {
190        control.check()?;
191        let reference = uqa_core::RelationIdentity::try_borrowed_reference(name).map_err(
192            |error| match control.format(format_args!("{error}")) {
193                Ok(message) => SQLError::Internal(message.into_parts().0),
194                Err(error) => error.into(),
195            },
196        )?;
197        let relation =
198            reference.identity_with_control(uqa_core::RelationName::decoded("public"), control)?;
199        if let Some(system) = uqa_sql::catalog::SystemRelation::at(&relation.schema, &relation.name)
200        {
201            return Ok(Some(system.object_id()));
202        }
203        if let Some(table) = self.storage.tables.read().get(&*relation) {
204            return Ok(Some(table.object_id()));
205        }
206        if let Some(view) = self.durable.views.read().get(&*relation) {
207            return Ok(Some(view.object_id));
208        }
209        if let Some(object_id) = self.durable.sequence_object_ids.read().get(&*relation) {
210            return Ok(Some(*object_id));
211        }
212        if let Some(index) = self.durable.catalog_indexes.read().get(&*relation) {
213            return crate::catalog_indexes::index_definition(index)
214                .map(|definition| definition.catalog.map(|catalog| catalog.identity.object_id))
215                .map_err(|error| {
216                    uqa_sql::catalog::errors::storage_error("index lock identity", &error)
217                });
218        }
219        Ok(self
220            .durable
221            .foreign_tables
222            .read()
223            .get(&*relation)
224            .map(|table| table.object_id))
225    }
226    fn relation_catalog_oid(&self, name: &str) -> Result<Option<u32>, SQLError> {
227        let relation =
228            uqa_core::RelationIdentity::from_legacy_name(name).map_err(SQLError::Internal)?;
229        if let Some(table) = self.storage.tables.read().get(&relation) {
230            return Ok(Some(table.relation_oids().relation));
231        }
232        if let Some(view) = self.durable.views.read().get(&relation) {
233            return Ok(Some(view.relation_oids().relation));
234        }
235        Ok(self
236            .durable
237            .foreign_tables
238            .read()
239            .get(&relation)
240            .map(|table| table.relation_oids().relation))
241    }
242    fn table_name(&self, object_id: [u8; 16]) -> Option<String> {
243        self.table_name_with_control(object_id, &ProductionControl::uncontrolled())
244            .expect("ordinary table identity lookup")
245            .map(|name| {
246                name.into_uncontrolled()
247                    .expect("ordinary table identity name")
248            })
249    }
250    fn table_name_with_control(
251        &self,
252        object_id: [u8; 16],
253        control: &ProductionControl<'_>,
254    ) -> Result<Option<Produced<String>>, SQLError> {
255        control.check()?;
256        for (name, table) in self.storage.tables.read().iter() {
257            control.check()?;
258            if table.object_id() == object_id {
259                return Ok(Some(name.qualified_name_with_control(control)?));
260            }
261        }
262        Ok(None)
263    }
264    fn relation_name(&self, object_id: [u8; 16]) -> Option<String> {
265        self.table_name(object_id)
266            .or_else(|| {
267                self.durable.views.read().iter().find_map(|(name, view)| {
268                    (view.object_id == object_id).then(|| name.qualified_name())
269                })
270            })
271            .or_else(|| {
272                self.durable
273                    .sequence_object_ids
274                    .read()
275                    .iter()
276                    .find_map(|(name, id)| (*id == object_id).then(|| name.qualified_name()))
277            })
278            .or_else(|| {
279                self.durable
280                    .foreign_tables
281                    .read()
282                    .iter()
283                    .find_map(|(name, table)| {
284                        (table.object_id == object_id).then(|| name.qualified_name())
285                    })
286            })
287    }
288}