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            self.durable.shells.read().values(),
128            self.durable.ranges.read().values(),
129            identity,
130        );
131        if user_type {
132            return true;
133        }
134        let views = self.durable.views.snapshot();
135        let foreign = self.durable.foreign_tables.snapshot();
136        // Release the registry lock before reading individual table metadata.
137        let tables = self.storage.tables.read().clone();
138        let tables = tables
139            .iter()
140            .map(|(name, table)| (name, table_array_metadata(table)));
141        let views = views.iter().map(|(name, view)| {
142            (
143                name,
144                RelationArrayMetadata {
145                    array_oid: view.relation_oids().array_type,
146                    recorded_name: view.row_type_array_name.as_deref().map(Cow::Borrowed),
147                },
148            )
149        });
150        let foreign = foreign.iter().map(|(name, table)| {
151            (
152                name,
153                RelationArrayMetadata {
154                    array_oid: table.relation_oids().array_type,
155                    recorded_name: table.row_type_array_name.as_deref().map(Cow::Borrowed),
156                },
157            )
158        });
159        uqa_execution::schema::types::relation_arrays::type_name_exists(
160            tables.chain(views).chain(foreign),
161            identity,
162        )
163    }
164    fn tables(&self) -> Box<dyn CreationRelationNames + '_> {
165        Box::new(CreationNamesGuard(self.storage.tables.read()))
166    }
167    fn views(&self) -> Box<dyn CreationRelationNames + '_> {
168        Box::new(CreationNamesGuard(self.durable.views.read()))
169    }
170    fn sequences(&self) -> Box<dyn CreationRelationNames + '_> {
171        Box::new(CreationNamesGuard(self.durable.sequences.read()))
172    }
173    fn foreign_tables(&self) -> Box<dyn CreationRelationNames + '_> {
174        Box::new(CreationNamesGuard(self.durable.foreign_tables.read()))
175    }
176    fn indexes(&self) -> Box<dyn CreationRelationNames + '_> {
177        Box::new(CreationNamesGuard(self.durable.catalog_indexes.read()))
178    }
179    fn composite_types(&self) -> Box<dyn CreationRelationNames + '_> {
180        Box::new(CompositeNamesGuard(self.durable.composites.read()))
181    }
182}
183
184/// The composite registry is keyed by qualified type name, which is also the composite relation's name.
185struct CompositeNamesGuard<G>(G);
186impl<G: std::ops::Deref<Target = uqa_execution::catalog::composite_type::CompositeRegistry>>
187    CreationRelationNames for CompositeNamesGuard<G>
188{
189    fn contains(&self, relation: &RelationIdentity) -> bool {
190        self.0.contains_key(&relation.qualified_name())
191    }
192}
193impl RelationCreationRuntime for Engine {
194    fn relation_array_name(&self, relation: &RelationIdentity, array_oid: u32) -> Option<String> {
195        let views = self.durable.views.snapshot();
196        let foreign = self.durable.foreign_tables.snapshot();
197        let table = self.storage.tables.read().get(relation).cloned();
198        uqa_execution::schema::types::relation_arrays::current_array_name(
199            [
200                table.as_deref().map(table_array_metadata),
201                views.get(relation).map(|view| RelationArrayMetadata {
202                    array_oid: view.relation_oids().array_type,
203                    recorded_name: view.row_type_array_name.as_deref().map(Cow::Borrowed),
204                }),
205                foreign.get(relation).map(|table| RelationArrayMetadata {
206                    array_oid: table.relation_oids().array_type,
207                    recorded_name: table.row_type_array_name.as_deref().map(Cow::Borrowed),
208                }),
209            ]
210            .into_iter()
211            .flatten(),
212            array_oid,
213        )
214    }
215    fn displace_generated_array(&self, identity: &RelationIdentity) -> Result<bool, SQLError> {
216        let context = self.type_lifecycle_context();
217        uqa_execution::schema::types::arrays::displace_array_type(
218            &context.creation,
219            context.registries,
220            identity,
221        )
222    }
223    fn displace_relation_array(&self, identity: &RelationIdentity) -> Result<bool, SQLError> {
224        uqa_execution::schema::types::relation_arrays::displace(
225            self.relation_array_context(),
226            &self.relation_creation_context(),
227            identity,
228        )
229    }
230    fn synchronize_catalog_registries(&self) -> StorageBackendResult<()> {
231        Engine::synchronize_catalog_registries(self)
232    }
233    fn synchronize_table_catalog(&self) -> StorageBackendResult<()> {
234        Engine::synchronize_table_catalog(self)
235    }
236    fn synchronize_table_data(&self) -> StorageBackendResult<()> {
237        Engine::synchronize_table_data(self)
238    }
239    fn backend_transaction_is_deferred(&self) -> bool {
240        Engine::backend_transaction_is_deferred(self)
241    }
242    fn fence_catalog_writer_and_refresh_snapshot(&self) -> Result<(), SQLError> {
243        Engine::fence_catalog_writer_and_refresh_snapshot(self)
244    }
245    fn create_temporary_namespace(&self) -> Result<(), SQLError> {
246        let oids = self
247            .catalog_identity_reservation_context()
248            .allocator(uqa_execution::catalog::identity::allocate_catalog_object_id)
249            .allocate_temporary_namespace_oids(|oid| {
250                Ok(uqa_execution::schema::namespaces::identity::namespace_oid_in_use(self, oid))
251            })?;
252        self.session.state.write().temporary_namespace = Some(oids);
253        Ok(())
254    }
255}
256
257fn table_array_metadata(table: &crate::TableState) -> RelationArrayMetadata<'_> {
258    RelationArrayMetadata {
259        array_oid: table.relation_oids().array_type,
260        recorded_name: table.row_type_array_name.read().clone().map(Cow::Owned),
261    }
262}
263impl Engine {
264    pub(crate) fn relation_creation_context(&self) -> RelationCreationContext<'_> {
265        RelationCreationContext {
266            names: self,
267            roles: self,
268            locks: self,
269            schemas: self,
270            database: self,
271            state: self,
272            relations: self,
273            runtime: self,
274        }
275    }
276}