Skip to main content

uqa_execution/query/scope/production/
rows.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7use crate::query::cte::rows::CteRows;
8use std::{borrow::Borrow, cmp::Ordering, sync::Arc};
9use uqa_core::memory::{BudgetedMapIter, OwnedMap, Produced, ProductionControl};
10use uqa_sql::SQLError;
11
12#[derive(Clone)]
13enum Name {
14    Ordinary(String),
15    Captured(Arc<Produced<String>>),
16}
17impl Name {
18    fn value(&self) -> &String {
19        match self {
20            Self::Ordinary(value) => value,
21            Self::Captured(value) => value,
22        }
23    }
24}
25impl Borrow<str> for Name {
26    fn borrow(&self) -> &str {
27        self.value()
28    }
29}
30impl PartialEq for Name {
31    fn eq(&self, other: &Self) -> bool {
32        self.value() == other.value()
33    }
34}
35impl Eq for Name {}
36impl PartialOrd for Name {
37    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
38        Some(self.cmp(other))
39    }
40}
41impl Ord for Name {
42    fn cmp(&self, other: &Self) -> Ordering {
43        self.value().cmp(other.value())
44    }
45}
46
47/// Ordered lexical row bindings. Admitted keys retain their text through every shared name owner, while each exact map node releases its own allowance when removed.
48#[derive(Clone, Default)]
49pub struct CteRowsMap {
50    rows: OwnedMap<Name, CteRows>,
51}
52
53impl CteRowsMap {
54    pub fn new() -> Self {
55        Self::default()
56    }
57    pub fn len(&self) -> usize {
58        self.rows.len()
59    }
60    pub fn is_empty(&self) -> bool {
61        self.rows.is_empty()
62    }
63    pub fn get(&self, name: &str) -> Option<&CteRows> {
64        self.rows.get(name)
65    }
66    pub(in crate::query::scope) fn get_name(
67        &self,
68        name: uqa_core::RelationName<'_>,
69    ) -> Option<&CteRows> {
70        self.rows
71            .get_by(|key| name.cmp(&uqa_core::RelationName::decoded(key.value())))
72    }
73    pub fn get_mut(&mut self, name: &str) -> Option<&mut CteRows> {
74        self.rows.get_mut(name)
75    }
76    pub fn contains_key(&self, name: &str) -> bool {
77        self.rows.contains_key(name)
78    }
79    pub fn remove(&mut self, name: &str) -> Option<CteRows> {
80        self.rows.remove(name)
81    }
82    pub fn clear(&mut self) {
83        self.rows.clear();
84    }
85    pub fn iter(&self) -> CteRowsIter<'_> {
86        CteRowsIter(self.rows.iter())
87    }
88    pub fn keys(&self) -> impl ExactSizeIterator<Item = &String> {
89        self.iter().map(|(name, _)| name)
90    }
91    pub fn values(&self) -> impl ExactSizeIterator<Item = &CteRows> {
92        self.iter().map(|(_, rows)| rows)
93    }
94
95    pub(in crate::query::scope) fn copy_with_control(
96        &self,
97        control: &ProductionControl<'_>,
98    ) -> Result<Self, SQLError> {
99        control.check()?;
100        let mut output = Self::new();
101        for (name, rows) in self.rows.iter() {
102            control.check()?;
103            let name = match name {
104                Name::Ordinary(name) => {
105                    Name::Captured(control.copy_text(name)?.into_shared(control)?)
106                }
107                Name::Captured(name) => Name::Captured(Arc::clone(name)),
108            };
109            if let Some(budget) = control.budget() {
110                output.rows.insert_budgeted(name, rows.clone(), budget)?;
111            } else {
112                output.rows.insert(name, rows.clone());
113            }
114        }
115        Ok(output)
116    }
117
118    pub(in crate::query::scope) fn extract(&mut self, name: &str) -> Self {
119        Self {
120            rows: self.rows.extract(name),
121        }
122    }
123    pub(in crate::query::scope) fn append(&mut self, rows: Self) {
124        self.rows.append(rows.rows);
125    }
126
127    pub fn insert(&mut self, name: String, rows: CteRows) -> Option<CteRows> {
128        if let Some(previous) = self.rows.get_mut(name.as_str()) {
129            return Some(std::mem::replace(previous, rows));
130        }
131        self.rows.insert(Name::Ordinary(name), rows)
132    }
133
134    pub(in crate::query::scope) fn insert_with_control(
135        &mut self,
136        name: &str,
137        rows: CteRows,
138        control: &ProductionControl<'_>,
139    ) -> Result<Option<CteRows>, SQLError> {
140        control.check()?;
141        if let Some(previous) = self.rows.get_mut(name) {
142            return Ok(Some(std::mem::replace(previous, rows)));
143        }
144        let name = Name::Captured(control.copy_text(name)?.into_shared(control)?);
145        Ok(if let Some(budget) = control.budget() {
146            self.rows.insert_budgeted(name, rows, budget)?
147        } else {
148            self.rows.insert(name, rows)
149        })
150    }
151}
152
153impl Extend<(String, CteRows)> for CteRowsMap {
154    fn extend<I: IntoIterator<Item = (String, CteRows)>>(&mut self, entries: I) {
155        for (name, rows) in entries {
156            self.insert(name, rows);
157        }
158    }
159}
160impl FromIterator<(String, CteRows)> for CteRowsMap {
161    fn from_iter<I: IntoIterator<Item = (String, CteRows)>>(entries: I) -> Self {
162        let mut map = Self::new();
163        map.extend(entries);
164        map
165    }
166}
167impl std::ops::Index<&str> for CteRowsMap {
168    type Output = CteRows;
169    fn index(&self, name: &str) -> &Self::Output {
170        self.get(name).expect("missing lexical row binding")
171    }
172}
173
174pub struct CteRowsIter<'a>(BudgetedMapIter<'a, Name, CteRows>);
175impl<'a> Iterator for CteRowsIter<'a> {
176    type Item = (&'a String, &'a CteRows);
177    fn next(&mut self) -> Option<Self::Item> {
178        self.0.next().map(|(name, rows)| (name.value(), rows))
179    }
180    fn size_hint(&self) -> (usize, Option<usize>) {
181        self.0.size_hint()
182    }
183}
184impl ExactSizeIterator for CteRowsIter<'_> {}
185impl std::iter::FusedIterator for CteRowsIter<'_> {}
186impl<'a> IntoIterator for &'a CteRowsMap {
187    type Item = (&'a String, &'a CteRows);
188    type IntoIter = CteRowsIter<'a>;
189    fn into_iter(self) -> Self::IntoIter {
190        self.iter()
191    }
192}