Skip to main content

uqa_sql/binding/
snapshot.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Owned catalog and CTE type inputs for analysis that rewrites nested scopes.
8
9use super::context::BindingContext;
10use crate::{
11    catalog::{analysis::CatalogReadView, resolution::RelationNameResolution},
12    plan::{CtePlan, QueryPlan},
13    RowSchema,
14};
15use std::collections::{BTreeMap, BTreeSet};
16use std::sync::Arc;
17
18#[derive(Clone)]
19pub struct BindingSnapshot {
20    pub catalog: CatalogReadView,
21    pub resolution: RelationNameResolution,
22    pub ctes: BTreeMap<String, RowSchema>,
23    pub deferred_ctes: BTreeMap<String, crate::plan::RetainedCtePlan>,
24    pub non_returning_ctes: BTreeSet<String>,
25    pub scalar_subqueries: Arc<[QueryPlan]>,
26}
27impl From<BindingContext<'_>> for BindingSnapshot {
28    fn from(context: BindingContext<'_>) -> Self {
29        Self {
30            catalog: context.catalog,
31            resolution: context.resolution,
32            ctes: context.ctes,
33            deferred_ctes: context.deferred_ctes,
34            non_returning_ctes: context.non_returning_ctes,
35            scalar_subqueries: context.scalar_subqueries.into(),
36        }
37    }
38}
39impl BindingSnapshot {
40    pub fn context(&self) -> BindingContext<'_> {
41        BindingContext {
42            catalog: self.catalog.clone(),
43            resolution: self.resolution.clone(),
44            ctes: self.ctes.clone(),
45            deferred_ctes: self.deferred_ctes.clone(),
46            non_returning_ctes: self.non_returning_ctes.clone(),
47            scalar_subqueries: &self.scalar_subqueries,
48        }
49    }
50    pub fn inherit_cte_bindings(&mut self, parent: &Self) {
51        self.ctes.clone_from(&parent.ctes);
52        self.deferred_ctes.clone_from(&parent.deferred_ctes);
53        self.non_returning_ctes
54            .clone_from(&parent.non_returning_ctes);
55    }
56    pub fn insert_deferred(&mut self, plan: CtePlan) {
57        self.ctes.remove(&plan.name);
58        if plan.body.returns_rows() {
59            self.non_returning_ctes.remove(&plan.name);
60        } else {
61            self.non_returning_ctes.insert(plan.name.clone());
62        }
63        self.deferred_ctes.insert(plan.name.clone(), plan.into());
64    }
65}