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 std::{collections::BTreeMap, ptr::NonNull, sync::Arc};
10
11use crate::{
12    plan::{QueryBlockPlan, RelationalPlan, SourcePlan},
13    RowSchema,
14};
15
16/// 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.
17pub struct ExecutionSourceBindings<'a> {
18    source: &'a SourcePlan,
19    children: Option<Box<(Arc<Self>, Arc<Self>)>>,
20    query: Option<QuerySourceBinding<'a>>,
21}
22
23struct QuerySourceBinding<'a> {
24    block: &'a QueryBlockPlan,
25    schema: RowSchema,
26    outer: Option<RowSchema>,
27    sources: Option<Arc<ExecutionSourceBindings<'a>>>,
28}
29
30impl ExecutionSourceBindings<'_> {
31    /// A rewritten or copied source must obtain its own binding.
32    pub fn matches_source(&self, source: &SourcePlan) -> bool {
33        std::ptr::eq(self.source, source)
34    }
35
36    pub fn join_child(&self, right: bool) -> Option<Arc<Self>> {
37        self.children.as_ref().map(|children| {
38            if right {
39                children.1.clone()
40            } else {
41                children.0.clone()
42            }
43        })
44    }
45
46    /// 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.
47    pub fn query_source(
48        &self,
49        block: &QueryBlockPlan,
50        outer: Option<&RowSchema>,
51        defer_distinct_limit: bool,
52    ) -> Option<(RowSchema, Option<Arc<Self>>)> {
53        let query = self.query.as_ref()?;
54        if defer_distinct_limit
55            || !std::ptr::eq(query.block, block)
56            || query.outer.as_ref() != outer
57        {
58            return None;
59        }
60        Some((query.schema.clone(), query.sources.clone()))
61    }
62}
63
64/// 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.
65#[derive(Default)]
66pub(in crate::binding) struct CapturedSources {
67    blocks: BTreeMap<NonNull<QueryBlockPlan>, Option<(RowSchema, Option<RowSchema>)>>,
68}
69
70impl CapturedSources {
71    pub(super) fn for_source(source: &SourcePlan) -> Self {
72        let mut result = Self::default();
73        result.collect(source);
74        result
75    }
76
77    pub(super) fn is_empty(&self) -> bool {
78        self.blocks.is_empty()
79    }
80
81    fn collect(&mut self, source: &SourcePlan) {
82        match source {
83            SourcePlan::Join { left, right, .. } => {
84                self.collect(left);
85                self.collect(right);
86            }
87            SourcePlan::Subquery { body, .. } if body.ctes.is_empty() => {
88                if let RelationalPlan::QueryBlock(block) = &body.root {
89                    if !block
90                        .from
91                        .as_ref()
92                        .is_some_and(super::source_binds_routines)
93                    {
94                        self.blocks.insert(NonNull::from(block.as_ref()), None);
95                        if let Some(source) = &block.from {
96                            self.collect(source);
97                        }
98                    }
99                }
100            }
101            _ => {}
102        }
103    }
104
105    pub(in crate::binding) fn record(
106        &mut self,
107        block: &QueryBlockPlan,
108        schema: &RowSchema,
109        outer: Option<&RowSchema>,
110    ) {
111        if !schema.columns_are_open(None) {
112            if let Some(slot) = self.blocks.get_mut(&NonNull::from(block)) {
113                *slot = Some((schema.clone(), outer.cloned()));
114            }
115        }
116    }
117
118    pub(super) fn take<'a>(&mut self, source: &'a SourcePlan) -> Arc<ExecutionSourceBindings<'a>> {
119        let children = match source {
120            SourcePlan::Join { left, right, .. } => {
121                Some(Box::new((self.take(left), self.take(right))))
122            }
123            _ => None,
124        };
125        let query = match source {
126            SourcePlan::Subquery { body, .. } => match &body.root {
127                RelationalPlan::QueryBlock(block) => self
128                    .blocks
129                    .remove(&NonNull::from(block.as_ref()))
130                    .flatten()
131                    .map(|(schema, outer)| QuerySourceBinding {
132                        block,
133                        schema,
134                        outer,
135                        sources: block.from.as_ref().map(|source| self.take(source)),
136                    }),
137                _ => None,
138            },
139            _ => None,
140        };
141        Arc::new(ExecutionSourceBindings {
142            source,
143            children,
144            query,
145        })
146    }
147}