Skip to main content

uqa_sql/semantics/rules/action_binding/
context.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Read-only relation shapes used to bind stored rule actions.
8use super::{
9    cte_output_columns,
10    names::{self, Columns, Named},
11    SQLError,
12};
13use crate::ast::{ColumnType, Statement, CTE};
14use uqa_core::memory::{OwnedProductionControl, Produced, ProductionControl, ProductionVec};
15
16pub trait RuleSourceCatalog {
17    fn query_source_columns(
18        &self,
19        name: &str,
20        relations_bound: bool,
21    ) -> Result<Option<Vec<String>>, SQLError>;
22    fn query_source_columns_with_control(
23        &self,
24        name: &str,
25        relations_bound: bool,
26        control: &ProductionControl<'_>,
27    ) -> Result<Option<Produced<Vec<String>>>, SQLError> {
28        control.check()?;
29        let Some(columns) = self.query_source_columns(name, relations_bound)? else {
30            return Ok(None);
31        };
32        if control.budget().is_none() {
33            return Ok(Some(control.finish(columns, None)?));
34        }
35        let mut output = ProductionVec::new(*control);
36        for column in columns {
37            output.push_produced(control.copy_text(&column)?)?;
38        }
39        Ok(Some(output.finish()?))
40    }
41    fn rule_relation_columns_with_control(
42        &self,
43        name: &str,
44        control: &ProductionControl<'_>,
45    ) -> Result<Produced<Vec<String>>, SQLError> {
46        control.check()?;
47        let columns = self.rule_relation_definitions(name)?;
48        let mut output = ProductionVec::new(*control);
49        for column in columns {
50            output.push_produced(control.copy_text(&column.name)?)?;
51        }
52        Ok(output.finish()?)
53    }
54    fn rule_relation_definitions(&self, name: &str)
55        -> Result<Vec<crate::ast::ColumnDef>, SQLError>;
56    /// External catalogs may return an owned declaration; native catalogs override this to admit copies directly from retained inputs.
57    fn rule_relation_definitions_with_control(
58        &self,
59        name: &str,
60        control: &ProductionControl<'_>,
61    ) -> Result<Produced<Vec<crate::ast::ColumnDef>>, SQLError> {
62        control.check()?;
63        let columns = self.rule_relation_definitions(name)?;
64        crate::plan::copy::copy_syntax_with_control(&columns, control)
65    }
66}
67
68pub(super) struct RuleBindingContext<'a> {
69    pub(super) catalog: Option<&'a dyn RuleSourceCatalog>,
70    pub(super) relations_bound: bool,
71    pub(super) ctes: Named<Columns>,
72    control: OwnedProductionControl,
73}
74impl Default for RuleBindingContext<'_> {
75    fn default() -> Self {
76        Self::from_control(&ProductionControl::uncontrolled())
77    }
78}
79impl<'a> RuleBindingContext<'a> {
80    pub(super) fn from_control(control: &ProductionControl<'_>) -> Self {
81        Self {
82            catalog: None,
83            relations_bound: false,
84            ctes: Named::new(),
85            control: control.capture(),
86        }
87    }
88    pub(super) fn with_catalog(catalog: &'a dyn RuleSourceCatalog, relations_bound: bool) -> Self {
89        Self::with_control(catalog, relations_bound, &ProductionControl::uncontrolled())
90    }
91    pub(super) fn with_control(
92        catalog: &'a dyn RuleSourceCatalog,
93        relations_bound: bool,
94        control: &ProductionControl<'_>,
95    ) -> Self {
96        Self {
97            catalog: Some(catalog),
98            relations_bound,
99            ctes: Named::new(),
100            control: control.capture(),
101        }
102    }
103    pub(super) fn control(&self) -> ProductionControl<'_> {
104        self.control.control()
105    }
106    pub(super) fn copy(&self) -> Result<Self, SQLError> {
107        let mut ctes = Named::new();
108        let control = self.control();
109        for (name, columns) in &self.ctes {
110            names::insert(&mut ctes, name, columns.copy(&control)?, &control)?;
111        }
112        Ok(Self {
113            catalog: self.catalog,
114            relations_bound: self.relations_bound,
115            ctes,
116            control: self.control.clone(),
117        })
118    }
119    pub(super) fn relation_columns(&self, name: &str) -> Result<Columns, SQLError> {
120        let control = self.control();
121        control.check()?;
122        if let Some(columns) = self.ctes.get_by(|key| names::folded_cmp(name, key)) {
123            return columns.copy(&control);
124        }
125        let Some(catalog) = self.catalog else {
126            return Ok(Columns::new(&control));
127        };
128        let columns = catalog
129            .query_source_columns_with_control(name, self.relations_bound, &control)?
130            .ok_or_else(|| SQLError::UnknownTable(name.to_string()))?;
131        Columns::from_produced(columns, &control)
132    }
133    fn recursive_placeholder(&mut self, cte: &CTE) -> Result<(), SQLError> {
134        if cte.recursive
135            && self
136                .ctes
137                .get_by(|key| names::folded_cmp(&cte.name, key))
138                .is_none()
139        {
140            let control = self.control.clone();
141            let control = control.control();
142            names::insert(&mut self.ctes, &cte.name, Columns::new(&control), &control)?;
143        }
144        Ok(())
145    }
146    pub(super) fn prepare_recursive_cte(&mut self, cte: &CTE) -> Result<(), SQLError> {
147        if cte.recursive {
148            self.recursive_placeholder(cte)?;
149            self.record_cte_columns(cte, false)?;
150        }
151        Ok(())
152    }
153    pub(super) fn record_cte(&mut self, cte: &CTE) -> Result<(), SQLError> {
154        self.record_cte_columns(cte, true)
155    }
156    fn record_cte_columns(&mut self, cte: &CTE, extra: bool) -> Result<(), SQLError> {
157        let mut columns = cte_output_columns(&cte.body, self)?;
158        let owner = self.control.clone();
159        let control = owner.control();
160        columns.rename(&cte.columns, &control)?;
161        if extra {
162            if let Some(search) = &cte.search {
163                columns.push(&search.sequence_column, &control)?;
164            }
165            if let Some(cycle) = &cte.cycle {
166                columns.push(&cycle.mark_column, &control)?;
167                columns.push(&cycle.path_column, &control)?;
168            }
169        }
170        names::insert(&mut self.ctes, &cte.name, columns, &control)
171    }
172    pub(super) fn with_ctes(&self, ctes: &[CTE]) -> Result<Self, SQLError> {
173        let mut context = self.copy()?;
174        for cte in ctes {
175            context.recursive_placeholder(cte)?;
176            context.record_cte(cte)?;
177        }
178        Ok(context)
179    }
180}
181
182pub fn rule_action_target_row_type(
183    catalog: &dyn RuleSourceCatalog,
184    action: &Statement,
185) -> Result<Vec<(String, ColumnType)>, SQLError> {
186    let table = match action {
187        Statement::Insert(statement) => &statement.table,
188        Statement::Update(statement) => &statement.table,
189        Statement::Delete(statement) => &statement.table,
190        _ => return Ok(Vec::new()),
191    };
192    Ok(catalog
193        .rule_relation_definitions(table)?
194        .into_iter()
195        .map(|column| (column.name, column.ty))
196        .collect())
197}
198pub fn rule_action_target_columns(
199    catalog: &dyn RuleSourceCatalog,
200    action: &Statement,
201) -> Result<std::collections::BTreeSet<String>, SQLError> {
202    Ok(rule_action_target_row_type(catalog, action)?
203        .into_iter()
204        .map(|(column, _)| column)
205        .collect())
206}
207
208/// Borrow native target names without copying unrelated declaration payloads.
209pub fn rule_action_target_columns_with_control(
210    catalog: &dyn RuleSourceCatalog,
211    action: &Statement,
212    control: &ProductionControl<'_>,
213) -> Result<Produced<Vec<String>>, SQLError> {
214    control.check()?;
215    let target = match action {
216        Statement::Insert(action) => &action.table,
217        Statement::Update(action) => &action.table,
218        Statement::Delete(action) => &action.table,
219        _ => return Ok(control.finish(Vec::new(), control.empty_reservation())?),
220    };
221    catalog.rule_relation_columns_with_control(target, control)
222}