Skip to main content

uqa_sql/prepared/definition/
production.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Preparation constructs each executable and cache descriptor in its invoking allowance.
8
9use super::{PreparedDefinition, PreparedDefinitionContext};
10use crate::{
11    binding::{production::ControlledBindingContext, statements::StatementAnalysisScopes},
12    catalog::resolution::EffectiveSearchPath,
13    plan::{
14        CommandPlan, MutableExecutablePlan, OwnedExecutablePlan, PlanRef, SharedExecutablePlan,
15    },
16    prepared::{
17        dependencies::{PreparedAnalysisDependencies, PreparedDependencySnapshot},
18        ownership::SharedPreparedInput,
19    },
20    ColumnType, RowSchema, SQLError,
21};
22use uqa_core::memory::{Produced, ProductionControl};
23
24impl PreparedDefinition<OwnedExecutablePlan> {
25    pub fn into_shared_with_control(
26        self,
27        control: &ProductionControl<'_>,
28    ) -> Result<PreparedDefinition<SharedExecutablePlan>, SQLError> {
29        Ok(PreparedDefinition {
30            composite_inputs: self.composite_inputs,
31            logical_plan: self.logical_plan.into_shared(control)?,
32            parameter_types: self.parameter_types,
33            result_schema: self.result_schema,
34            effective_search_path: self.effective_search_path,
35            dependencies: self.dependencies,
36            dependency_snapshot: self.dependency_snapshot,
37        })
38    }
39}
40
41pub fn analyze_definition_owned(
42    context: &PreparedDefinitionContext<'_>,
43    logical_plan: MutableExecutablePlan,
44    declared: &[ColumnType],
45    control: &ProductionControl<'_>,
46) -> Result<PreparedDefinition<OwnedExecutablePlan>, SQLError> {
47    analyze_definition_with_finalizer(context, logical_plan, declared, control, |plan, _| Ok(plan))
48}
49
50/// SQL routines validate the result before binding retained type spellings, while the same private destination remains editable.
51pub fn analyze_routine_definition_owned(
52    context: &PreparedDefinitionContext<'_>,
53    types: &dyn crate::routines::declaration::RoutineTypeCatalog,
54    logical_plan: MutableExecutablePlan,
55    declared: &[ColumnType],
56    validate: &dyn Fn(Option<&RowSchema>) -> Result<(), SQLError>,
57    control: &ProductionControl<'_>,
58) -> Result<PreparedDefinition<OwnedExecutablePlan>, SQLError> {
59    analyze_definition_with_finalizer(context, logical_plan, declared, control, |plan, schema| {
60        validate(schema)?;
61        crate::routines::compilation::bind_analyzed_sql_body_types_owned(types, plan, control)
62    })
63}
64
65fn analyze_definition_with_finalizer(
66    context: &PreparedDefinitionContext<'_>,
67    logical_plan: MutableExecutablePlan,
68    declared: &[ColumnType],
69    control: &ProductionControl<'_>,
70    finalize: impl FnOnce(
71        MutableExecutablePlan,
72        Option<&RowSchema>,
73    ) -> Result<MutableExecutablePlan, SQLError>,
74) -> Result<PreparedDefinition<OwnedExecutablePlan>, SQLError> {
75    let parameter_types = crate::prepared::declared_parameter_types_for_plan_with_control(
76        context.types,
77        logical_plan.as_plan_ref(),
78        declared,
79        control,
80    )?;
81    if !crate::prepared::utility::requires_analysis_ref(logical_plan.as_plan_ref()) {
82        let result_schema = crate::prepared::utility::result_schema_with_control(
83            context.session,
84            logical_plan.as_plan_ref(),
85            control,
86        )?;
87        return Ok(PreparedDefinition {
88            composite_inputs: crate::prepared::composites::CompositeInputs::default(),
89            logical_plan: finalize(logical_plan, result_schema.as_ref())?.finish(control)?,
90            parameter_types: SharedPreparedInput::from_produced(parameter_types, control)?,
91            result_schema,
92            effective_search_path: shared(None, control)?,
93            dependencies: shared(PreparedAnalysisDependencies::default(), control)?,
94            dependency_snapshot: shared(None, control)?,
95        });
96    }
97    let mut source = Some(logical_plan);
98    let (logical_plan, parameter_types, dependencies, effective_path, snapshot) =
99        with_controlled_scope_result(context.scopes, control, |binding| {
100            let catalog = binding.catalog.clone();
101            let resolution = binding.resolution.copy_with_control(control)?;
102            let plan = source.take().ok_or_else(|| {
103                SQLError::Internal("prepared analysis scope invoked its operation twice".into())
104            })?;
105            let input = read_definition_inputs(context, plan, &parameter_types, binding, control)?;
106            let plan =
107                crate::schema::dependencies::oid_alias::read_prepared_oid_alias_constants_owned(
108                    context.aliases,
109                    input.plan,
110                    control,
111                )?;
112            let (mut dependencies, memory) = input.dependencies.into_parts();
113            let mut result = Ok(());
114            let mut include = |expression: &crate::ScalarExpr| {
115                if result.is_ok() {
116                    result = dependencies.include_expression_with_control(expression, control);
117                }
118            };
119            match plan.as_plan_ref() {
120                PlanRef::Query(query) => query.visit_scalar_expressions(&mut include),
121                PlanRef::Command(command) => command.visit_scalar_expressions(&mut include),
122            }
123            result?;
124            let path = catalog.effective_search_path_with_control(&resolution, control)?;
125            let snapshot =
126                catalog.prepared_dependency_snapshot_with_control(&dependencies, control)?;
127            Ok((
128                plan,
129                input.parameter_types,
130                control.finish(dependencies, memory)?,
131                path,
132                snapshot,
133            ))
134        })?;
135    let result_schema = analyze_result_schema_with_control(
136        context,
137        logical_plan.as_plan_ref(),
138        &parameter_types,
139        control,
140    )?;
141    let composite_inputs =
142        crate::prepared::composites::CompositeInputs::capture_for_plan_with_control(
143            logical_plan.as_plan_ref(),
144            context.types,
145            control,
146        )?;
147    let logical_plan = finalize(logical_plan, result_schema.as_ref())?.finish(control)?;
148    Ok(PreparedDefinition {
149        composite_inputs,
150        logical_plan,
151        parameter_types: SharedPreparedInput::from_produced(parameter_types, control)?,
152        result_schema,
153        effective_search_path: SharedPreparedInput::from_produced(effective_path, control)?,
154        dependencies: SharedPreparedInput::from_produced(dependencies, control)?,
155        dependency_snapshot: shared(snapshot, control)?,
156    })
157}
158
159fn shared<T>(
160    value: T,
161    control: &ProductionControl<'_>,
162) -> Result<SharedPreparedInput<T>, SQLError> {
163    SharedPreparedInput::from_produced(control.finish(value, control.empty_reservation())?, control)
164}
165
166pub fn analysis_is_current_with_control(
167    context: &PreparedDefinitionContext<'_>,
168    retained_path: Option<&EffectiveSearchPath>,
169    dependencies: &PreparedAnalysisDependencies,
170    retained_snapshot: Option<&PreparedDependencySnapshot>,
171    control: &ProductionControl<'_>,
172) -> Result<bool, SQLError> {
173    control.check()?;
174    if retained_path.is_none() && retained_snapshot.is_none() {
175        return Ok(true);
176    }
177    with_controlled_scope_result(context.scopes, control, |binding| {
178        if let Some(path) = retained_path {
179            if binding
180                .catalog
181                .effective_search_path_with_control(&binding.resolution, control)?
182                .as_ref()
183                != Some(path)
184            {
185                return Ok(false);
186            }
187        }
188        match retained_snapshot {
189            Some(snapshot) => Ok(binding
190                .catalog
191                .prepared_dependency_snapshot_with_control(dependencies, control)?
192                .as_ref()
193                == Some(snapshot)),
194            None => Ok(true),
195        }
196    })
197}
198
199pub fn effective_search_path_with_control(
200    context: &PreparedDefinitionContext<'_>,
201    control: &ProductionControl<'_>,
202) -> Result<Produced<Option<EffectiveSearchPath>>, SQLError> {
203    with_controlled_scope_result(context.scopes, control, |binding| {
204        binding
205            .catalog
206            .effective_search_path_with_control(&binding.resolution, control)
207    })
208}
209
210pub fn analyze_result_schema_with_control(
211    context: &PreparedDefinitionContext<'_>,
212    plan: PlanRef<'_>,
213    parameter_types: &[Option<ColumnType>],
214    control: &ProductionControl<'_>,
215) -> Result<Option<RowSchema>, SQLError> {
216    if !crate::prepared::utility::requires_analysis_ref(plan) {
217        return crate::prepared::utility::result_schema_with_control(
218            context.session,
219            plan,
220            control,
221        );
222    }
223    with_controlled_scope_result(context.scopes, control, |binding| {
224        let params = crate::prepared::analysis_parameters_with_control(parameter_types, control)?;
225        if let PlanRef::Command(CommandPlan::Call { name, args }) = plan {
226            return crate::routines::call::OwnedProcedureCallAnalysis::new(args, control)?
227                .result_schema_with_control(
228                    name,
229                    &crate::routines::resolution::RoutineOverloadContext {
230                        catalog: context.procedures,
231                    },
232                    context.procedures,
233                    &mut |argument| {
234                        crate::binding::production::analyze_expression_plan_type_with_control(
235                            context.routines,
236                            argument,
237                            &params,
238                            binding.copy_with_control(control)?,
239                            control,
240                        )
241                    },
242                    control,
243                );
244        }
245        match plan {
246            PlanRef::Query(query) => {
247                crate::binding::production::analyze_query_plan_schema_with_control(
248                    context.routines,
249                    query,
250                    &params,
251                    binding,
252                    None,
253                    control,
254                )
255                .map(Some)
256            }
257            PlanRef::Command(command) => {
258                crate::binding::analyze_prepared_command_schema_with_control(
259                    context.routines,
260                    command,
261                    &params,
262                    binding,
263                    control,
264                )
265            }
266        }
267    })
268}
269
270fn with_controlled_scope_result<T>(
271    scopes: &dyn StatementAnalysisScopes,
272    control: &ProductionControl<'_>,
273    mut analyze: impl FnMut(ControlledBindingContext<'_>) -> Result<T, SQLError>,
274) -> Result<T, SQLError> {
275    let mut result = None;
276    scopes.with_controlled_scope(control, &mut |binding| {
277        result = Some(analyze(binding)?);
278        Ok(())
279    })?;
280    result.ok_or_else(|| {
281        SQLError::Internal("prepared analysis scope did not invoke its operation".into())
282    })
283}
284
285fn read_definition_inputs(
286    context: &PreparedDefinitionContext<'_>,
287    plan: MutableExecutablePlan,
288    parameter_types: &[Option<ColumnType>],
289    binding: ControlledBindingContext<'_>,
290    control: &ProductionControl<'_>,
291) -> Result<crate::binding::PreparedOwnedInputs, SQLError> {
292    Ok(
293        if matches!(
294            plan.as_plan_ref(),
295            PlanRef::Command(CommandPlan::Call { .. })
296        ) {
297            let metadata_binding = binding.copy_with_control(control)?;
298            let (_, mut input) = crate::binding::read_procedure_inputs_owned(
299                &crate::binding::statements::StatementAnalysisContext {
300                    routines: context.routines,
301                    scopes: context.scopes,
302                    aliases: context.aliases,
303                },
304                &crate::routines::resolution::RoutineOverloadContext {
305                    catalog: context.procedures,
306                },
307                context.procedures,
308                plan,
309                parameter_types,
310                binding,
311                control,
312            )?;
313            input.plan = crate::binding::retain_prepared_input_metadata_owned(
314                context.routines,
315                input.plan,
316                &input.parameter_types,
317                metadata_binding,
318                control,
319            )?;
320            input
321        } else {
322            crate::binding::read_prepared_inputs_owned(
323                context.routines,
324                plan,
325                parameter_types,
326                binding,
327                Some(context.aliases),
328                control,
329            )?
330        },
331    )
332}