Skip to main content

uqa_sql/binding/execution/
sources.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Transfer freshly bound derived-source metadata along its borrowed execution tree.
8
9use crate::{
10    plan::{QueryBlockPlan, RelationalPlan, SourcePlan},
11    RowSchema, SQLError,
12};
13use std::{ptr::NonNull, sync::Arc};
14use uqa_core::memory::{OwnedMap, Produced, ProductionControl};
15
16pub type SharedExecutionSourceBindings<'a> = Arc<Produced<ExecutionSourceBindings<'a>>>;
17type SourceChildren<'a> = (
18    SharedExecutionSourceBindings<'a>,
19    SharedExecutionSourceBindings<'a>,
20);
21
22/// Metadata from one successful execution-source binding. The owner must keep the catalog, CTE definitions, routines and parameters unchanged while constructing the corresponding physical source. This is not a prepared-plan cache or pre-optimization annotation.
23pub struct ExecutionSourceBindings<'a> {
24    source: &'a SourcePlan,
25    children: Option<Produced<Box<SourceChildren<'a>>>>,
26    query: Option<QuerySourceBinding<'a>>,
27}
28
29struct QuerySourceBinding<'a> {
30    block: &'a QueryBlockPlan,
31    schema: RowSchema,
32    outer: Option<RowSchema>,
33    sources: Option<SharedExecutionSourceBindings<'a>>,
34}
35
36impl<'a> ExecutionSourceBindings<'a> {
37    /// A rewritten or copied source must obtain its own binding.
38    pub fn matches_source(&self, source: &SourcePlan) -> bool {
39        std::ptr::eq(self.source, source)
40    }
41
42    pub fn join_child(&self, right: bool) -> Option<SharedExecutionSourceBindings<'a>> {
43        self.children.as_ref().map(|children| {
44            if right {
45                children.1.clone()
46            } else {
47                children.0.clone()
48            }
49        })
50    }
51
52    /// Transfer a derived block's raw source schema only under its complete original enclosing descriptor. Identity checks borrow live syntax; no address is retained beyond that syntax's lifetime.
53    pub fn query_source(
54        &self,
55        block: &QueryBlockPlan,
56        outer: Option<&RowSchema>,
57        defer_distinct_limit: bool,
58    ) -> Option<(RowSchema, Option<SharedExecutionSourceBindings<'a>>)> {
59        let query = self.query.as_ref()?;
60        if defer_distinct_limit
61            || !std::ptr::eq(query.block, block)
62            || query.outer.as_ref() != outer
63        {
64            return None;
65        }
66        Some((query.schema.clone(), query.sources.clone()))
67    }
68}
69
70/// Addresses exist only while collecting metadata from the original borrowed tree. Temporary view, CTE and function-member syntax cannot replace an original node, and extraction returns borrowed structural owners rather than address keys.
71#[derive(Default)]
72pub(in crate::binding) struct CapturedSources {
73    blocks: OwnedMap<NonNull<QueryBlockPlan>, Option<(RowSchema, Option<RowSchema>)>>,
74}
75
76impl CapturedSources {
77    pub(super) fn for_source(
78        source: &SourcePlan,
79        control: &ProductionControl<'_>,
80    ) -> Result<Self, SQLError> {
81        let mut result = Self::default();
82        result.collect(source, control)?;
83        Ok(result)
84    }
85
86    pub(super) fn is_empty(&self) -> bool {
87        self.blocks.is_empty()
88    }
89
90    fn collect(
91        &mut self,
92        source: &SourcePlan,
93        control: &ProductionControl<'_>,
94    ) -> Result<(), SQLError> {
95        control.check()?;
96        match source {
97            SourcePlan::Join { left, right, .. } => {
98                self.collect(left, control)?;
99                self.collect(right, control)?;
100            }
101            SourcePlan::Subquery { body, .. } if body.ctes.is_empty() => {
102                if let RelationalPlan::QueryBlock(block) = &body.root {
103                    if !block
104                        .from
105                        .as_ref()
106                        .is_some_and(super::source_binds_routines)
107                    {
108                        let key = NonNull::from(block.as_ref());
109                        match control.budget() {
110                            Some(budget) => {
111                                self.blocks.insert_budgeted(key, None, budget)?;
112                            }
113                            None => {
114                                self.blocks.insert(key, None);
115                            }
116                        }
117                        if let Some(source) = &block.from {
118                            self.collect(source, control)?;
119                        }
120                    }
121                }
122            }
123            _ => {}
124        }
125        Ok(())
126    }
127
128    pub(in crate::binding) fn record(
129        &mut self,
130        block: &QueryBlockPlan,
131        schema: &RowSchema,
132        outer: Option<&RowSchema>,
133    ) {
134        if !schema.columns_are_open(None) {
135            if let Some(slot) = self.blocks.get_mut(&NonNull::from(block)) {
136                *slot = Some((schema.clone(), outer.cloned()));
137            }
138        }
139    }
140
141    pub(super) fn take<'a>(
142        &mut self,
143        source: &'a SourcePlan,
144        control: &ProductionControl<'_>,
145    ) -> Result<SharedExecutionSourceBindings<'a>, SQLError> {
146        control.check()?;
147        let children = match source {
148            SourcePlan::Join { left, right, .. } => {
149                let left = self.take(left, control)?;
150                let right = self.take(right, control)?;
151                let memory = control.reserve(size_of::<SourceChildren<'a>>())?;
152                Some(control.finish(Box::new((left, right)), memory)?)
153            }
154            _ => None,
155        };
156        let query = match source {
157            SourcePlan::Subquery { body, .. } => match &body.root {
158                RelationalPlan::QueryBlock(block) => self
159                    .blocks
160                    .remove(&NonNull::from(block.as_ref()))
161                    .flatten()
162                    .map(|(schema, outer)| {
163                        Ok::<_, SQLError>(QuerySourceBinding {
164                            block,
165                            schema,
166                            outer,
167                            sources: block
168                                .from
169                                .as_ref()
170                                .map(|source| self.take(source, control))
171                                .transpose()?,
172                        })
173                    })
174                    .transpose()?,
175                _ => None,
176            },
177            _ => None,
178        };
179        Ok(control
180            .finish(
181                ExecutionSourceBindings {
182                    source,
183                    children,
184                    query,
185                },
186                control.empty_reservation(),
187            )?
188            .into_shared(control)?)
189    }
190}