Skip to main content

uqa_sql/binding/statements/procedural/
owned.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Procedural cache publication moves analyzed executables and shares their exact metadata owners.
8
9use super::{
10    AnalyzedResult, PreparedAnalysisDependencies, PreparedDependencySnapshot,
11    RoutineOverloadContext, RoutineTypeCatalog, SQLError, SQLParam, StatementAnalysisContext,
12};
13use crate::{
14    binding::production::ControlledBindingContext,
15    catalog::resolution::EffectiveSearchPath,
16    plan::{CommandPlan, MutableExecutablePlan, OwnedExecutablePlan, PlanRef},
17    prepared::{definition::PreparedDefinition, ownership::SharedPreparedInput},
18    ColumnType,
19};
20use uqa_core::memory::{Produced, ProductionControl};
21
22pub struct OwnedProceduralPlanAnalysis {
23    pub plan: OwnedExecutablePlan,
24    pub composite_inputs: crate::prepared::composites::CompositeInputs,
25    pub result: AnalyzedResult,
26    pub parameter_types: SharedPreparedInput<Vec<Option<ColumnType>>>,
27    pub dependencies: SharedPreparedInput<PreparedAnalysisDependencies>,
28    pub effective_search_path: SharedPreparedInput<Option<EffectiveSearchPath>>,
29    pub dependency_snapshot: SharedPreparedInput<Option<PreparedDependencySnapshot>>,
30}
31
32impl OwnedProceduralPlanAnalysis {
33    pub fn prepared_definition_owned(
34        self,
35        control: &ProductionControl<'_>,
36    ) -> Result<PreparedDefinition<OwnedExecutablePlan>, SQLError> {
37        let result_schema = match &self.result {
38            AnalyzedResult::Command => None,
39            AnalyzedResult::Schema(schema) => Some(schema.clone()),
40            AnalyzedResult::Rows(types) => {
41                Some(crate::RowSchema::with_column_metadata_with_control(
42                    None,
43                    types.iter().map(|ty| ("", ty.as_ref(), None)),
44                    control,
45                )?)
46            }
47        };
48        control.check()?;
49        Ok(PreparedDefinition {
50            composite_inputs: self.composite_inputs,
51            logical_plan: self.plan,
52            parameter_types: self.parameter_types,
53            result_schema,
54            effective_search_path: self.effective_search_path,
55            dependencies: self.dependencies,
56            dependency_snapshot: self.dependency_snapshot,
57        })
58    }
59}
60
61pub fn analyze_procedural_plan_owned(
62    context: &StatementAnalysisContext<'_>,
63    overloads: &RoutineOverloadContext<'_>,
64    types: &dyn RoutineTypeCatalog,
65    plan: MutableExecutablePlan,
66    params: &[SQLParam],
67    control: &ProductionControl<'_>,
68) -> Result<OwnedProceduralPlanAnalysis, SQLError> {
69    let mut source = Some(plan);
70    let mut analyzed = None;
71    context
72        .scopes
73        .with_controlled_scope(control, &mut |binding| {
74            let plan = source
75                .take()
76                .ok_or_else(|| SQLError::Internal("procedural analysis scope ran twice".into()))?;
77            let catalog = binding.catalog.clone();
78            let resolution = binding.resolution.copy_with_control(control)?;
79            let metadata = binding.copy_with_control(control)?;
80            let (plan, result, dependencies) =
81                analyze_inputs(context, overloads, types, plan, params, binding, control)?;
82            let plan = crate::routines::compilation::bind_analyzed_sql_body_types_owned(
83                types, plan, control,
84            )?;
85            let parameter_types =
86                crate::binding::parameter_input_types_with_control(params, control)?;
87            let plan = crate::binding::preparation::retain_input_metadata_owned(
88                context.routines,
89                plan,
90                params,
91                metadata,
92                control,
93            )?;
94            let plan = plan.finish(control)?;
95            let composite_inputs =
96                crate::prepared::composites::CompositeInputs::capture_with_control(
97                    &plan,
98                    context.routines,
99                    control,
100                )?;
101            let effective_search_path =
102                catalog.effective_search_path_with_control(&resolution, control)?;
103            let snapshot =
104                catalog.prepared_dependency_snapshot_with_control(&dependencies, control)?;
105            analyzed = Some(OwnedProceduralPlanAnalysis {
106                plan,
107                composite_inputs,
108                result,
109                parameter_types: SharedPreparedInput::from_produced(parameter_types, control)?,
110                dependencies: SharedPreparedInput::from_produced(dependencies, control)?,
111                effective_search_path: SharedPreparedInput::from_produced(
112                    effective_search_path,
113                    control,
114                )?,
115                dependency_snapshot: SharedPreparedInput::from_produced(
116                    control.finish(snapshot, control.empty_reservation())?,
117                    control,
118                )?,
119            });
120            Ok(())
121        })?;
122    analyzed.ok_or_else(|| SQLError::Internal("procedural analysis scope did not run".into()))
123}
124
125fn analyze_inputs(
126    context: &StatementAnalysisContext<'_>,
127    overloads: &RoutineOverloadContext<'_>,
128    types: &dyn RoutineTypeCatalog,
129    plan: MutableExecutablePlan,
130    params: &[SQLParam],
131    binding: ControlledBindingContext<'_>,
132    control: &ProductionControl<'_>,
133) -> Result<
134    (
135        MutableExecutablePlan,
136        AnalyzedResult,
137        Produced<PreparedAnalysisDependencies>,
138    ),
139    SQLError,
140> {
141    if let PlanRef::Command(command) = plan.as_plan_ref() {
142        if matches!(command, CommandPlan::Call { .. }) {
143            let declared = crate::binding::parameter_input_types_with_control(params, control)?;
144            let (schema, input) = crate::binding::read_procedure_inputs_owned(
145                context, overloads, types, plan, &declared, binding, control,
146            )?;
147            return Ok((
148                input.plan,
149                schema.map_or(AnalyzedResult::Command, AnalyzedResult::Schema),
150                input.dependencies,
151            ));
152        }
153        if matches!(command, CommandPlan::Explain { .. }) {
154            let MutableExecutablePlan::Command(command) = plan else {
155                unreachable!();
156            };
157            let mut dependencies = None;
158            let command = command.map_executable_body(control, |body| {
159                let (body, _, selected) =
160                    analyze_inputs(context, overloads, types, body, params, binding, control)?;
161                dependencies = Some(selected);
162                Ok(body)
163            })?;
164            return Ok((
165                MutableExecutablePlan::Command(command),
166                AnalyzedResult::Command,
167                dependencies.expect("EXPLAIN analyzed its body"),
168            ));
169        }
170    }
171    let input = crate::binding::read_procedural_inputs_owned(
172        context.routines,
173        plan,
174        params,
175        binding,
176        context.aliases,
177        control,
178    )?;
179    Ok((input.plan, input.result, input.dependencies))
180}