Skip to main content

uqa_sql/semantics/view_rewrite/
context.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Catalog and authorization inputs for automatic view analysis and DML rewriting.
8
9use crate::binding::production::{ControlledBindingContext, ControlledBindingSnapshot};
10use crate::catalog::view::ViewRewriteDefinitionRef;
11use crate::{
12    ast::{ColumnDef, RuleEvent, TriggerEvent, TriggerTiming},
13    binding::snapshot::BindingSnapshot,
14    catalog::{
15        analysis::CatalogReadView,
16        events::StoredRule,
17        resolution::RelationNameResolution,
18        view::{StoredViewKind, ViewRewriteDefinition},
19    },
20    semantics::sets::SetFunctionCatalog,
21    RowSchema, SQLError,
22};
23use std::collections::BTreeSet;
24use uqa_core::memory::{Produced, ProductionControl, ProductionVec};
25
26pub trait ViewRewriteCatalog {
27    fn view_definition(&self, name: &str) -> Result<Option<ViewRewriteDefinition>, SQLError>;
28    fn try_resolve_view_name(&self, name: &str) -> Result<Option<String>, String>;
29    fn try_describe_table(&self, name: &str) -> Result<Option<Vec<ColumnDef>>, String>;
30    fn try_table_columns(&self, name: &str) -> Result<Vec<String>, String>;
31    fn rules_for(&self, name: &str, event: RuleEvent) -> Result<Vec<StoredRule>, SQLError>;
32    fn capture_rules(
33        &self,
34        name: &str,
35        event: RuleEvent,
36    ) -> Result<crate::catalog::events::selection::CapturedRules, SQLError> {
37        self.capture_rules_with_control(name, event, &ProductionControl::uncontrolled())
38    }
39    fn capture_rules_with_control(
40        &self,
41        name: &str,
42        event: RuleEvent,
43        control: &ProductionControl<'_>,
44    ) -> Result<crate::catalog::events::selection::CapturedRules, SQLError> {
45        control.check()?;
46        crate::catalog::events::selection::CapturedRules::from_external(
47            self.rules_for(name, event)?,
48            control,
49        )
50    }
51    fn rule_definitions_for(
52        &self,
53        name: &str,
54        event: RuleEvent,
55    ) -> Result<Vec<StoredRule>, SQLError>;
56    fn has_trigger_definition(
57        &self,
58        name: &str,
59        timing: TriggerTiming,
60        event: TriggerEvent,
61        row: bool,
62    ) -> Result<bool, SQLError>;
63    fn rule_new_row_columns(&self, rule: &StoredRule)
64        -> Result<Option<BTreeSet<String>>, SQLError>;
65    fn target_view_kind(&self, name: &str) -> Result<Option<StoredViewKind>, SQLError>;
66    fn binding_scope(&self) -> Result<BindingSnapshot, SQLError>;
67    fn restored_view_catalog(&self) -> (CatalogReadView, RelationNameResolution);
68
69    /// External catalogs may return owned declarations; native catalogs lend fields from their retained immutable definition.
70    fn with_view_definition_with_control(
71        &self,
72        name: &str,
73        control: &ProductionControl<'_>,
74        read: &mut dyn FnMut(Option<ViewRewriteDefinitionRef<'_>>) -> Result<(), SQLError>,
75    ) -> Result<(), SQLError> {
76        control.check()?;
77        let definition = self.view_definition(name)?;
78        read(definition.as_ref().map(ViewRewriteDefinitionRef::from))?;
79        Ok(control.check()?)
80    }
81
82    fn try_resolve_view_name_with_control(
83        &self,
84        name: &str,
85        control: &ProductionControl<'_>,
86    ) -> Result<Option<Produced<String>>, SQLError> {
87        control.check()?;
88        self.try_resolve_view_name(name)
89            .map_err(|error| SQLError::Internal(format!("resolve DML view `{name}`: {error}")))?
90            .map(|name| control.copy_text(&name).map_err(Into::into))
91            .transpose()
92    }
93
94    /// External table catalogs may return owned names. Native adapters publish each selected declaration directly.
95    fn try_table_column_names_with_control(
96        &self,
97        name: &str,
98        control: &ProductionControl<'_>,
99    ) -> Result<Produced<Vec<String>>, SQLError> {
100        control.check()?;
101        let mut output = ProductionVec::new(*control);
102        self.visit_table_column_names_with_control(name, control, &mut |name| {
103            output.push_produced(control.copy_text(name)?)?;
104            Ok(())
105        })?;
106        Ok(output.finish()?)
107    }
108
109    /// Native catalogs lend each declared name under its retained table guard; external catalogs may supply their existing owned names.
110    fn visit_table_column_names_with_control(
111        &self,
112        name: &str,
113        control: &ProductionControl<'_>,
114        read: &mut dyn FnMut(&str) -> Result<(), SQLError>,
115    ) -> Result<(), SQLError> {
116        control.check()?;
117        for column in self.try_table_columns(name).map_err(|error| {
118            SQLError::Internal(format!("describe view source `{name}`: {error}"))
119        })? {
120            control.check()?;
121            read(&column)?;
122        }
123        Ok(())
124    }
125
126    fn try_relation_column_names_with_control(
127        &self,
128        name: &str,
129        control: &ProductionControl<'_>,
130    ) -> Result<Option<Produced<Vec<String>>>, SQLError> {
131        control.check()?;
132        let Some(definitions) = self.try_describe_table(name).map_err(|error| {
133            SQLError::Internal(format!("describe view source `{name}`: {error}"))
134        })?
135        else {
136            return Ok(None);
137        };
138        let mut output = ProductionVec::new(*control);
139        if definitions.is_empty() {
140            return self
141                .try_table_column_names_with_control(name, control)
142                .map(Some);
143        }
144        for definition in definitions {
145            output.push_produced(control.copy_text(&definition.name)?)?;
146        }
147        Ok(Some(output.finish()?))
148    }
149
150    fn visit_rules_with_control(
151        &self,
152        name: &str,
153        event: RuleEvent,
154        reverse: bool,
155        control: &ProductionControl<'_>,
156        visit: &mut dyn FnMut(&StoredRule) -> Result<(), SQLError>,
157    ) -> Result<(), SQLError> {
158        control.check()?;
159        let rules = self.rules_for(name, event)?;
160        if reverse {
161            for rule in rules.iter().rev() {
162                control.check()?;
163                visit(rule)?;
164            }
165        } else {
166            for rule in &rules {
167                control.check()?;
168                visit(rule)?;
169            }
170        }
171        Ok(())
172    }
173
174    fn rule_new_row_columns_with_control(
175        &self,
176        rule: &StoredRule,
177        control: &ProductionControl<'_>,
178    ) -> Result<Option<Produced<Vec<String>>>, SQLError> {
179        control.check()?;
180        let Some(columns) = self.rule_new_row_columns(rule)? else {
181            return Ok(None);
182        };
183        let mut output = ProductionVec::new(*control);
184        for column in columns {
185            output.push_produced(control.copy_text(&column)?)?;
186        }
187        Ok(Some(output.finish()?))
188    }
189
190    fn has_trigger_definition_with_control(
191        &self,
192        name: &str,
193        timing: TriggerTiming,
194        event: TriggerEvent,
195        row: bool,
196        control: &ProductionControl<'_>,
197    ) -> Result<bool, SQLError> {
198        control.check()?;
199        let result = self.has_trigger_definition(name, timing, event, row)?;
200        control.check()?;
201        Ok(result)
202    }
203
204    fn target_view_kind_with_control(
205        &self,
206        name: &str,
207        control: &ProductionControl<'_>,
208    ) -> Result<Option<StoredViewKind>, SQLError> {
209        control.check()?;
210        let result = self.target_view_kind(name)?;
211        control.check()?;
212        Ok(result)
213    }
214
215    fn binding_scope_with_control(
216        &self,
217        control: &ProductionControl<'_>,
218    ) -> Result<ControlledBindingSnapshot, SQLError> {
219        control.check()?;
220        self.binding_scope()?.copy_with_control(control)
221    }
222
223    fn restored_view_scope_with_control(
224        &self,
225        control: &ProductionControl<'_>,
226    ) -> Result<ControlledBindingContext<'static>, SQLError> {
227        control.check()?;
228        let (catalog, resolution) = self.restored_view_catalog();
229        Ok(ControlledBindingContext {
230            catalog,
231            resolution: crate::binding::production::BindingResolution::from_produced(
232                resolution.copy_with_control(control)?,
233            ),
234            ctes: crate::binding::production::BindingMap::new(),
235            deferred_ctes: crate::binding::production::BindingMap::new(),
236            non_returning_ctes: crate::binding::production::BindingNameSet::new(),
237            scalar_subqueries: &[],
238        })
239    }
240}
241
242#[derive(Clone, Copy)]
243pub struct ViewRewriteContext<'a> {
244    pub catalog: &'a dyn ViewRewriteCatalog,
245    pub routines: &'a dyn SetFunctionCatalog,
246    pub authorization: &'a dyn super::super::view_privileges::ViewPrivilegeCatalog,
247}
248
249pub fn stored_view_schema(
250    services: ViewRewriteContext<'_>,
251    definition: &ViewRewriteDefinition,
252) -> Result<RowSchema, SQLError> {
253    let (catalog, resolution) = services.catalog.restored_view_catalog();
254    definition.row_schema(services.routines, catalog, resolution)
255}
256
257pub fn stored_view_schema_with_control(
258    services: ViewRewriteContext<'_>,
259    definition: ViewRewriteDefinitionRef<'_>,
260    control: &ProductionControl<'_>,
261) -> Result<RowSchema, SQLError> {
262    definition.row_schema_with_control(
263        services.routines,
264        services.catalog.restored_view_scope_with_control(control)?,
265        control,
266    )
267}