Skip to main content

uqa_execution/query/scope/
recursive.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Recursive working rows and control widths publish and restore as one lexical binding.
8
9use super::{
10    bindings::{restore_cte_names, save_and_remove_cte_names_with_control, SavedCteBindings},
11    CteRowsMap, CteScope,
12};
13use uqa_core::memory::ProductionControl;
14use uqa_sql::{binding::production::BindingMap, SQLError};
15
16pub struct RecursiveCteScope<'a, 'n, S: Clone> {
17    scope: &'a mut CteScope<S>,
18    name: &'n str,
19    saved: Option<SavedCteBindings>,
20    width: Option<BindingMap<usize>>,
21}
22
23impl<S: Clone> CteScope<S> {
24    /// Complete both destinations before changing the scope. Saved nodes restore the parent on success, error and unwind without consuming more allowance.
25    pub fn enter_recursive_cte_with_control<'a, 'n>(
26        &'a mut self,
27        name: &'n str,
28        rows: crate::SharedSpill,
29        width: Option<usize>,
30        control: &ProductionControl<'_>,
31    ) -> Result<RecursiveCteScope<'a, 'n, S>, SQLError> {
32        let mut pending_rows = CteRowsMap::new();
33        pending_rows.insert_with_control(
34            name,
35            crate::query::cte::rows::CteRows::Complete(rows),
36            control,
37        )?;
38        let mut pending_width = BindingMap::new();
39        if let Some(width) = width {
40            pending_width.insert_with_control(name, width, control)?;
41        }
42        let saved = save_and_remove_cte_names_with_control(self, [name], control)?;
43        let previous_width = width.map(|_| self.recursive_control_widths.extract(name));
44        self.rows.append(pending_rows);
45        self.recursive_control_widths.append(pending_width);
46        Ok(RecursiveCteScope {
47            scope: self,
48            name,
49            saved: Some(saved),
50            width: previous_width,
51        })
52    }
53}
54
55impl<S: Clone> std::ops::Deref for RecursiveCteScope<'_, '_, S> {
56    type Target = CteScope<S>;
57    fn deref(&self) -> &Self::Target {
58        self.scope
59    }
60}
61impl<S: Clone> std::ops::DerefMut for RecursiveCteScope<'_, '_, S> {
62    fn deref_mut(&mut self) -> &mut Self::Target {
63        self.scope
64    }
65}
66impl<S: Clone> Drop for RecursiveCteScope<'_, '_, S> {
67    fn drop(&mut self) {
68        if let Some(width) = self.width.take() {
69            self.scope.recursive_control_widths.remove(self.name);
70            self.scope.recursive_control_widths.append(width);
71        }
72        restore_cte_names(
73            self.scope,
74            self.saved.take().expect("live recursive binding"),
75        );
76    }
77}