Skip to main content

uqa_sql/semantics/privileges/
coverage.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Structural coverage of one successful complete SELECT privilege check.
8
9use super::{context::PrivilegeScope, ensure_select_privileges_for_query_block};
10use crate::{
11    plan::{QueryBlockPlan, QueryPlan, RelationalPlan, SourcePlan},
12    SQLError,
13};
14
15/// Borrows only syntax visited by a successful complete check. The consumer must independently preserve the immutable catalog, namespace, CTE definitions, outer lineage and complete authorization subject. Structural coverage alone never authorizes a changed execution scope.
16#[derive(Clone, Copy)]
17pub struct SelectSourceCoverage<'a> {
18    source: &'a SourcePlan,
19    block: Option<&'a QueryBlockPlan>,
20}
21
22impl SelectSourceCoverage<'_> {
23    pub fn matches_source(&self, source: &SourcePlan) -> bool {
24        std::ptr::eq(self.source, source)
25    }
26
27    /// A changed projection must be checked even when it uses the same source.
28    pub fn covers_query(&self, block: &QueryBlockPlan, source: &SourcePlan) -> bool {
29        self.matches_source(source)
30            && self
31                .block
32                .is_some_and(|checked| std::ptr::eq(checked, block))
33    }
34
35    pub fn join_child(&self, right: bool) -> Option<Self> {
36        let SourcePlan::Join {
37            left, right: rhs, ..
38        } = self.source
39        else {
40            return None;
41        };
42        Some(Self {
43            source: if right { rhs } else { left },
44            block: None,
45        })
46    }
47
48    /// Project coverage onto an original direct derived block. CTE and set-operation execution keep their independent checks.
49    pub fn query_source(&self, block: &QueryBlockPlan) -> Option<Self> {
50        let SourcePlan::Subquery { body, .. } = self.source else {
51            return None;
52        };
53        if !body.ctes.is_empty() {
54            return None;
55        }
56        let RelationalPlan::QueryBlock(checked) = &body.root else {
57            return None;
58        };
59        if !std::ptr::eq(checked.as_ref(), block) {
60            return None;
61        }
62        Some(Self {
63            source: checked.from.as_ref()?,
64            block: Some(checked),
65        })
66    }
67}
68
69/// Complete the original ordered lineage and table/column checks before issuing any coverage. Failed or partial expression checks cannot construct this value.
70pub fn check_query_source<'a>(
71    block: &'a QueryBlockPlan,
72    source: &'a SourcePlan,
73    scope: &PrivilegeScope<'_, impl AsRef<[QueryPlan]>>,
74) -> Result<SelectSourceCoverage<'a>, SQLError> {
75    ensure_select_privileges_for_query_block(block, source, scope)?;
76    Ok(SelectSourceCoverage {
77        source,
78        block: Some(block),
79    })
80}
81
82#[cfg(test)]
83mod tests;