Skip to main content

uqa_engine/capabilities/
schema_privileges.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Bind schema privilege rules to live namespace registries and session identity.
8
9use crate::Engine;
10use parking_lot::MappedRwLockReadGuard;
11use std::{borrow::Cow, collections::BTreeMap, sync::Arc};
12use uqa_graph::GraphStoreHandle;
13use uqa_sql::catalog::graph_oids::GraphCatalogOids;
14use uqa_sql::catalog::roles::identity::RoleSubject;
15use uqa_sql::{
16    catalog::security::{
17        schema::SchemaAclPrivilege,
18        schema_inquiry::{
19            GraphNamespaceRead, SchemaPrivilegeCatalog, SchemaPrivilegeInquiry, SchemaRegistryRead,
20        },
21        BoundSchemaSecurity,
22    },
23    SQLError,
24};
25
26struct GraphNamesGuard<'a> {
27    graphs: MappedRwLockReadGuard<'a, BTreeMap<String, Arc<GraphStoreHandle>>>,
28    oids: MappedRwLockReadGuard<'a, BTreeMap<String, GraphCatalogOids>>,
29}
30impl GraphNamespaceRead for GraphNamesGuard<'_> {
31    fn names(&self) -> Box<dyn Iterator<Item = &str> + '_> {
32        Box::new(self.graphs.keys().map(String::as_str))
33    }
34    fn contains(&self, name: &str) -> bool {
35        self.graphs.contains_key(name)
36    }
37    fn namespace_oid(&self, name: &str) -> i64 {
38        self.oids.get(name).map_or_else(
39            || uqa_sql::catalog::oids::schema_oid(name),
40            |oids| i64::from(oids.namespace),
41        )
42    }
43}
44
45impl SchemaPrivilegeCatalog for Engine {
46    fn refresh_namespace_catalog(&self) -> Result<(), SQLError> {
47        self.synchronize_catalog_registries().map_err(|error| {
48            SQLError::Internal(format!("load schemas for privilege inquiry: {error}"))
49        })
50    }
51    fn schemas(&self) -> SchemaRegistryRead<'_> {
52        Box::new(self.durable.schemas.read())
53    }
54    fn graphs(&self) -> Box<dyn GraphNamespaceRead + '_> {
55        Box::new(GraphNamesGuard {
56            graphs: self.durable.graphs.read(),
57            oids: self.durable.graph_catalog_oids.read(),
58        })
59    }
60    fn temporary_namespace_oids(
61        &self,
62    ) -> Option<uqa_sql::catalog::temporary_namespace::TemporaryNamespaceOids> {
63        self.temporary_namespace_oids()
64    }
65    fn temporary_schema_name(&self) -> String {
66        self.temporary_schema_name()
67    }
68}
69
70impl Engine {
71    pub(crate) fn schema_privilege_inquiry(&self) -> SchemaPrivilegeInquiry<'_> {
72        SchemaPrivilegeInquiry {
73            catalog: self,
74            names: self,
75            roles: self,
76        }
77    }
78    pub(crate) fn schema_has_privilege_for_role(
79        &self,
80        schema: &str,
81        role: &(impl RoleSubject + ?Sized),
82        privilege: SchemaAclPrivilege,
83    ) -> bool {
84        self.schema_privilege_inquiry()
85            .schema_has_privilege_for_role(schema, role, privilege)
86    }
87    pub(crate) fn schema_security_for_privilege(
88        &self,
89        schema: &str,
90    ) -> Option<BoundSchemaSecurity> {
91        self.schema_privilege_inquiry()
92            .schema_security_for_privilege(schema)
93    }
94    pub(crate) fn require_schema_privilege(
95        &self,
96        schema: &str,
97        role: &(impl RoleSubject + ?Sized),
98        privilege: SchemaAclPrivilege,
99    ) -> Result<(), SQLError> {
100        self.schema_privilege_inquiry()
101            .require_schema_privilege(schema, role, privilege)
102    }
103}
104
105use uqa_core::RelationIdentity;
106use uqa_execution::schema::namespaces::relations::{
107    RelationCreationContext, RelationCreationRuntime,
108};
109use uqa_execution::schema::types::relation_arrays::RelationArrayMetadata;
110use uqa_sql::catalog::resolution::creation::{CreationRelationGuards, CreationRelationNames};
111use uqa_storage::StorageBackendResult;
112
113struct CreationNamesGuard<G>(G);
114impl<T, G: std::ops::Deref<Target = BTreeMap<RelationIdentity, T>>> CreationRelationNames
115    for CreationNamesGuard<G>
116{
117    fn contains(&self, relation: &RelationIdentity) -> bool {
118        self.0.contains_key(relation)
119    }
120}
121impl CreationRelationGuards for Engine {
122    fn named_type_exists(&self, identity: &RelationIdentity) -> bool {
123        let user_type = uqa_execution::catalog::projection::named_type_exists(
124            self.durable.domains.read().values(),
125            self.durable.enums.read().values(),
126            self.durable.composites.read().values(),
127            identity,
128        );
129        if user_type {
130            return true;
131        }
132        let views = self.durable.views.snapshot();
133        let foreign = self.durable.foreign_tables.snapshot();
134        // Release the registry lock before reading individual table metadata.
135        let tables = self.storage.tables.read().clone();
136        let tables = tables
137            .iter()
138            .map(|(name, table)| (name, table_array_metadata(table)));
139        let views = views.iter().map(|(name, view)| {
140            (
141                name,
142                RelationArrayMetadata {
143                    array_oid: view.relation_oids().array_type,
144                    recorded_name: view.row_type_array_name.as_deref().map(Cow::Borrowed),
145                },
146            )
147        });
148        let foreign = foreign.iter().map(|(name, table)| {
149            (
150                name,
151                RelationArrayMetadata {
152                    array_oid: table.relation_oids().array_type,
153                    recorded_name: table.row_type_array_name.as_deref().map(Cow::Borrowed),
154                },
155            )
156        });
157        uqa_execution::schema::types::relation_arrays::type_name_exists(
158            tables.chain(views).chain(foreign),
159            identity,
160        )
161    }
162    fn tables(&self) -> Box<dyn CreationRelationNames + '_> {
163        Box::new(CreationNamesGuard(self.storage.tables.read()))
164    }
165    fn views(&self) -> Box<dyn CreationRelationNames + '_> {
166        Box::new(CreationNamesGuard(self.durable.views.read()))
167    }
168    fn sequences(&self) -> Box<dyn CreationRelationNames + '_> {
169        Box::new(CreationNamesGuard(self.durable.sequences.read()))
170    }
171    fn foreign_tables(&self) -> Box<dyn CreationRelationNames + '_> {
172        Box::new(CreationNamesGuard(self.durable.foreign_tables.read()))
173    }
174    fn indexes(&self) -> Box<dyn CreationRelationNames + '_> {
175        Box::new(CreationNamesGuard(self.durable.catalog_indexes.read()))
176    }
177    fn composite_types(&self) -> Box<dyn CreationRelationNames + '_> {
178        Box::new(CompositeNamesGuard(self.durable.composites.read()))
179    }
180}
181
182/// The composite registry is keyed by qualified type name, which is also the composite relation's name.
183struct CompositeNamesGuard<G>(G);
184impl<G: std::ops::Deref<Target = uqa_execution::catalog::composite_type::CompositeRegistry>>
185    CreationRelationNames for CompositeNamesGuard<G>
186{
187    fn contains(&self, relation: &RelationIdentity) -> bool {
188        self.0.contains_key(&relation.qualified_name())
189    }
190}
191impl RelationCreationRuntime for Engine {
192    fn relation_array_name(&self, relation: &RelationIdentity, array_oid: u32) -> Option<String> {
193        let views = self.durable.views.snapshot();
194        let foreign = self.durable.foreign_tables.snapshot();
195        let table = self.storage.tables.read().get(relation).cloned();
196        uqa_execution::schema::types::relation_arrays::current_array_name(
197            [
198                table.as_deref().map(table_array_metadata),
199                views.get(relation).map(|view| RelationArrayMetadata {
200                    array_oid: view.relation_oids().array_type,
201                    recorded_name: view.row_type_array_name.as_deref().map(Cow::Borrowed),
202                }),
203                foreign.get(relation).map(|table| RelationArrayMetadata {
204                    array_oid: table.relation_oids().array_type,
205                    recorded_name: table.row_type_array_name.as_deref().map(Cow::Borrowed),
206                }),
207            ]
208            .into_iter()
209            .flatten(),
210            array_oid,
211        )
212    }
213    fn displace_generated_array(&self, identity: &RelationIdentity) -> Result<bool, SQLError> {
214        let context = self.type_lifecycle_context();
215        uqa_execution::schema::types::arrays::displace_array_type(
216            &context.creation,
217            context.registries,
218            identity,
219        )
220    }
221    fn displace_relation_array(&self, identity: &RelationIdentity) -> Result<bool, SQLError> {
222        uqa_execution::schema::types::relation_arrays::displace(
223            self.relation_array_context(),
224            &self.relation_creation_context(),
225            identity,
226        )
227    }
228    fn synchronize_catalog_registries(&self) -> StorageBackendResult<()> {
229        Engine::synchronize_catalog_registries(self)
230    }
231    fn synchronize_table_catalog(&self) -> StorageBackendResult<()> {
232        Engine::synchronize_table_catalog(self)
233    }
234    fn synchronize_table_data(&self) -> StorageBackendResult<()> {
235        Engine::synchronize_table_data(self)
236    }
237    fn backend_transaction_is_deferred(&self) -> bool {
238        Engine::backend_transaction_is_deferred(self)
239    }
240    fn fence_catalog_writer_and_refresh_snapshot(&self) -> Result<(), SQLError> {
241        Engine::fence_catalog_writer_and_refresh_snapshot(self)
242    }
243    fn create_temporary_namespace(&self) -> Result<(), SQLError> {
244        let oids = self
245            .catalog_identity_reservation_context()
246            .allocator(uqa_execution::catalog::identity::allocate_catalog_object_id)
247            .allocate_temporary_namespace_oids(|oid| {
248                Ok(uqa_execution::schema::namespaces::identity::namespace_oid_in_use(self, oid))
249            })?;
250        self.session.state.write().temporary_namespace = Some(oids);
251        Ok(())
252    }
253}
254
255fn table_array_metadata(table: &crate::TableState) -> RelationArrayMetadata<'_> {
256    RelationArrayMetadata {
257        array_oid: table.relation_oids().array_type,
258        recorded_name: table.row_type_array_name.read().clone().map(Cow::Owned),
259    }
260}
261impl Engine {
262    pub(crate) fn relation_creation_context(&self) -> RelationCreationContext<'_> {
263        RelationCreationContext {
264            names: self,
265            roles: self,
266            locks: self,
267            schemas: self,
268            database: self,
269            state: self,
270            relations: self,
271            runtime: self,
272        }
273    }
274}