Skip to main content

uqa_sql/semantics/privileges/
context.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Immutable relation authorization and CTE name inputs for column lineage analysis.
8
9use super::ownership::{self, Named};
10use crate::binding::production::BindingResolution;
11use crate::catalog::roles::RoleReference;
12use crate::{
13    catalog::resolution::RelationNameResolution,
14    plan::{CtePlan, QueryPlan},
15    SQLError,
16};
17use std::borrow::Cow;
18use uqa_core::memory::{OwnedProductionControl, Produced, ProductionControl, ProductionVec};
19
20#[derive(Clone, Copy, Debug)]
21pub enum PrivilegeRelationKind {
22    System(crate::catalog::SystemRelation),
23    Table,
24    View,
25    MaterializedView,
26    ForeignTable,
27}
28impl PrivilegeRelationKind {
29    pub const fn has_system_columns(self) -> bool {
30        match self {
31            Self::System(relation) => matches!(relation.kind().as_bytes(), b"table"),
32            _ => matches!(self, Self::Table | Self::ForeignTable),
33        }
34    }
35    pub const fn description(self) -> &'static str {
36        match self {
37            Self::System(relation) => relation.kind(),
38            Self::Table => "table",
39            Self::View => "view",
40            Self::MaterializedView => "materialized view",
41            Self::ForeignTable => "foreign table",
42        }
43    }
44}
45#[derive(Debug)]
46pub struct PrivilegeRelation {
47    pub canonical: String,
48    pub columns: Vec<String>,
49    pub kind: PrivilegeRelationKind,
50}
51pub trait PrivilegeCatalog {
52    fn relation(
53        &self,
54        resolution: &RelationNameResolution,
55        name: &str,
56    ) -> Result<Option<PrivilegeRelation>, SQLError>;
57    fn relation_with_control(
58        &self,
59        resolution: &RelationNameResolution,
60        name: &str,
61        control: &ProductionControl<'_>,
62    ) -> Result<Option<Produced<PrivilegeRelation>>, SQLError> {
63        control.check()?;
64        self.relation(resolution, name)?
65            .map(|relation| {
66                PrivilegeRelation::from_names(
67                    &relation.canonical,
68                    relation.columns.iter().map(String::as_str),
69                    relation.kind,
70                    control,
71                )
72            })
73            .transpose()
74    }
75    fn has_select_privilege_with_control(
76        &self,
77        resolution: &RelationNameResolution,
78        relation: &PrivilegeRelation,
79        column: Option<&str>,
80        subject: &RoleReference,
81        control: &ProductionControl<'_>,
82    ) -> Result<bool, SQLError> {
83        control.check()?;
84        self.has_select_privilege(resolution, relation, column, subject)
85    }
86    fn has_select_privilege(
87        &self,
88        resolution: &RelationNameResolution,
89        relation: &PrivilegeRelation,
90        column: Option<&str>,
91        subject: &RoleReference,
92    ) -> Result<bool, SQLError>;
93}
94pub trait PrivilegeCteCatalog {
95    fn is_visible_cte(&self, name: &str) -> bool;
96    fn is_visible_cte_with_control(
97        &self,
98        name: &str,
99        control: &ProductionControl<'_>,
100    ) -> Result<bool, SQLError> {
101        control.check()?;
102        Ok(self.is_visible_cte(name))
103    }
104    fn materialized_columns(&self, name: &str) -> Option<Vec<String>>;
105    fn materialized_columns_with_control(
106        &self,
107        name: &str,
108        control: &ProductionControl<'_>,
109    ) -> Result<Option<Produced<Vec<String>>>, SQLError> {
110        control.check()?;
111        self.materialized_columns(name)
112            .map(|columns| copy_columns(columns.iter().map(String::as_str), control))
113            .transpose()
114    }
115    fn deferred_reference(&self, name: &str) -> Option<&CtePlan>;
116    fn deferred_reference_with_control(
117        &self,
118        name: &str,
119        control: &ProductionControl<'_>,
120    ) -> Result<Option<&CtePlan>, SQLError> {
121        control.check()?;
122        Ok(self.deferred_reference(name))
123    }
124    fn privilege_subject(&self) -> Result<&RoleReference, SQLError>;
125}
126pub struct PrivilegeScope<'a, Queries = Vec<QueryPlan>> {
127    pub catalog: &'a dyn PrivilegeCatalog,
128    pub resolution: BindingResolution,
129    pub inherited: &'a dyn PrivilegeCteCatalog,
130    pub scalar_subqueries: Queries,
131    local_ctes: Named<Cow<'a, CtePlan>>,
132    control: OwnedProductionControl,
133    pub(super) include_authorization_only_columns: bool,
134    pub(super) relation_privilege_subject: Option<Produced<RoleReference>>,
135}
136impl<'a> PrivilegeScope<'a> {
137    pub fn new(
138        catalog: &'a dyn PrivilegeCatalog,
139        resolution: RelationNameResolution,
140        inherited: &'a dyn PrivilegeCteCatalog,
141        scalar_subqueries: Vec<QueryPlan>,
142    ) -> Self {
143        Self {
144            catalog,
145            resolution: resolution.into(),
146            inherited,
147            scalar_subqueries,
148            local_ctes: Named::new(),
149            control: ProductionControl::uncontrolled().capture(),
150            include_authorization_only_columns: true,
151            relation_privilege_subject: None,
152        }
153    }
154}
155
156impl<'a> PrivilegeScope<'a, &'a [QueryPlan]> {
157    /// Borrow the executing statement's immutable query arena without copying its plans. The owned constructor and its public vector remain available for callers that retain a scope.
158    pub fn borrowed(
159        catalog: &'a dyn PrivilegeCatalog,
160        resolution: RelationNameResolution,
161        inherited: &'a dyn PrivilegeCteCatalog,
162        scalar_subqueries: &'a [QueryPlan],
163    ) -> Self {
164        Self {
165            catalog,
166            resolution: resolution.into(),
167            inherited,
168            scalar_subqueries,
169            local_ctes: Named::new(),
170            control: ProductionControl::uncontrolled().capture(),
171            include_authorization_only_columns: true,
172            relation_privilege_subject: None,
173        }
174    }
175}
176
177impl<'a> PrivilegeScope<'a, &'a [QueryPlan]> {
178    pub fn borrowed_with_control(
179        catalog: &'a dyn PrivilegeCatalog,
180        resolution: Produced<RelationNameResolution>,
181        inherited: &'a dyn PrivilegeCteCatalog,
182        scalar_subqueries: &'a [QueryPlan],
183        control: &ProductionControl<'_>,
184    ) -> Self {
185        Self {
186            catalog,
187            resolution: BindingResolution::from_produced(resolution),
188            inherited,
189            scalar_subqueries,
190            local_ctes: Named::new(),
191            control: control.capture(),
192            include_authorization_only_columns: true,
193            relation_privilege_subject: None,
194        }
195    }
196}
197
198impl<'a, Queries: AsRef<[QueryPlan]>> PrivilegeScope<'a, Queries> {
199    pub(super) fn control(&self) -> ProductionControl<'_> {
200        self.control.control()
201    }
202
203    pub fn insert_deferred(&mut self, plan: CtePlan) -> Result<(), SQLError> {
204        let control = self.control.clone();
205        let name = control.control().copy_text(&plan.name)?;
206        let value = Cow::Owned(plan);
207        match control.control().budget() {
208            Some(budget) => {
209                self.local_ctes.insert_budgeted(name, value, budget)?;
210            }
211            None => {
212                self.local_ctes.insert(name, value);
213            }
214        }
215        Ok(())
216    }
217
218    pub(super) fn insert_deferred_ref(&mut self, plan: &'a CtePlan) -> Result<(), SQLError> {
219        ownership::insert(
220            &mut self.local_ctes,
221            &plan.name,
222            Cow::Borrowed(plan),
223            &self.control.control(),
224        )
225    }
226
227    pub(super) fn reborrow(&self) -> Result<PrivilegeScope<'_, &[QueryPlan]>, SQLError> {
228        let control = self.control();
229        let mut local_ctes = Named::new();
230        for (name, plan) in &self.local_ctes {
231            ownership::insert(
232                &mut local_ctes,
233                name,
234                Cow::Borrowed(plan.as_ref()),
235                &control,
236            )?;
237        }
238        Ok(PrivilegeScope {
239            catalog: self.catalog,
240            resolution: self.resolution.copy_with_control(&control)?,
241            inherited: self.inherited,
242            scalar_subqueries: self.scalar_subqueries.as_ref(),
243            local_ctes,
244            control: self.control.clone(),
245            include_authorization_only_columns: self.include_authorization_only_columns,
246            relation_privilege_subject: self
247                .relation_privilege_subject
248                .as_ref()
249                .map(|role| role.clone_with_control(&control))
250                .transpose()?,
251        })
252    }
253    fn local(&self, reference: &str) -> Option<&CtePlan> {
254        let reference = uqa_core::RelationIdentity::borrowed_reference(reference)?;
255        if reference.schema.is_some() {
256            return None;
257        }
258        self.local_ctes
259            .get_by(|name| reference.name.cmp(&uqa_core::RelationName::decoded(name)))
260            .map(AsRef::as_ref)
261    }
262    pub fn is_visible_cte_with_control(&self, name: &str) -> Result<bool, SQLError> {
263        self.control().check()?;
264        if self.local(name).is_some() {
265            Ok(true)
266        } else {
267            self.inherited
268                .is_visible_cte_with_control(name, &self.control())
269        }
270    }
271    pub fn materialized_for_scan(
272        &self,
273        name: &str,
274    ) -> Result<Option<Produced<Vec<String>>>, SQLError> {
275        let Some(reference) = uqa_core::RelationIdentity::borrowed_reference(name) else {
276            return Ok(None);
277        };
278        if reference.schema.is_some() || self.local(name).is_some() {
279            Ok(None)
280        } else {
281            self.inherited
282                .materialized_columns_with_control(name, &self.control())
283        }
284    }
285    pub fn deferred_reference_with_control(
286        &self,
287        name: &str,
288    ) -> Result<Option<&CtePlan>, SQLError> {
289        self.control().check()?;
290        if uqa_core::RelationIdentity::borrowed_reference(name)
291            .is_none_or(|reference| reference.schema.is_some())
292        {
293            return Ok(None);
294        }
295        if let Some(plan) = self.local(name) {
296            Ok(Some(plan))
297        } else {
298            self.inherited
299                .deferred_reference_with_control(name, &self.control())
300        }
301    }
302    pub fn privilege_subject(&self) -> Result<&RoleReference, SQLError> {
303        self.relation_privilege_subject
304            .as_deref()
305            .map_or_else(|| self.inherited.privilege_subject(), Ok)
306    }
307}
308
309pub(super) fn copy_columns<'a>(
310    columns: impl IntoIterator<Item = &'a str>,
311    control: &ProductionControl<'_>,
312) -> Result<Produced<Vec<String>>, SQLError> {
313    let mut output = ProductionVec::new(*control);
314    for column in columns {
315        output.push_produced(control.copy_text(column)?)?;
316    }
317    Ok(output.finish()?)
318}
319
320impl PrivilegeRelation {
321    pub fn from_names<'a>(
322        canonical: &str,
323        columns: impl IntoIterator<Item = &'a str>,
324        kind: PrivilegeRelationKind,
325        control: &ProductionControl<'_>,
326    ) -> Result<Produced<Self>, SQLError> {
327        let canonical = control.copy_text(canonical)?;
328        let columns = copy_columns(columns, control)?;
329        Self::from_columns(canonical, columns, kind, control)
330    }
331
332    pub fn from_columns(
333        canonical: Produced<String>,
334        columns: Produced<Vec<String>>,
335        kind: PrivilegeRelationKind,
336        control: &ProductionControl<'_>,
337    ) -> Result<Produced<Self>, SQLError> {
338        let (canonical, name_memory) = canonical.into_parts();
339        let (columns, column_memory) = columns.into_parts();
340        Ok(control.finish(
341            Self {
342                canonical,
343                columns,
344                kind,
345            },
346            control.combine(name_memory, column_memory),
347        )?)
348    }
349}