Skip to main content

uqa_sql/plan/scalar/owned/
query_ids.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Query-index changes are allocation-free and retain every scalar constructor.
8
9use super::{OwnedScalarExpr, ScalarExpr};
10use crate::SQLError;
11use uqa_core::memory::ProductionControl;
12
13impl OwnedScalarExpr {
14    pub(crate) fn remap_query_occurrences(
15        mut self,
16        control: &ProductionControl<'_>,
17        map: &mut dyn FnMut(usize) -> Result<usize, SQLError>,
18    ) -> Result<Self, SQLError> {
19        self.assert_owner(control);
20        let mut result: Result<(), SQLError> = Ok(());
21        crate::plan::rewrite_scalar_expression(&mut self.expression, &mut |node| {
22            if result.is_err() {
23                return;
24            }
25            result = (|| {
26                control.check()?;
27                match node {
28                    ScalarExpr::ScalarSubquery(id)
29                    | ScalarExpr::Exists { subquery: id, .. }
30                    | ScalarExpr::InSubquery { subquery: id, .. } => *id = map(*id)?,
31                    _ => {}
32                }
33                Ok(())
34            })();
35        });
36        result?;
37        Ok(self)
38    }
39
40    /// Remap only this expression's local scalar-query references after their query owners have moved together. Nested query arenas are not part of the scalar tree.
41    pub fn remap_subquery_ids(
42        mut self,
43        control: &ProductionControl<'_>,
44        map: &mut dyn FnMut(usize) -> usize,
45    ) -> Result<Self, SQLError> {
46        self.assert_owner(control);
47        let mut checked = Ok(());
48        self.expression.visit_mut(&mut |node| {
49            if checked.is_ok() {
50                checked = control.check();
51                match node {
52                    ScalarExpr::ScalarSubquery(id)
53                    | ScalarExpr::Exists { subquery: id, .. }
54                    | ScalarExpr::InSubquery { subquery: id, .. } => *id = map(*id),
55                    _ => {}
56                }
57            }
58        });
59        checked?;
60        Ok(self)
61    }
62}