Skip to main content

uqa_sql/prepared/
definition.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Analyze prepared declarations with separate retained inference and descriptor scopes.
8
9use super::dependencies::{PreparedAnalysisDependencies, PreparedDependencySnapshot};
10use super::ownership::SharedPreparedInput;
11use crate::{
12    binding::statements::{StatementAnalysisScopes, StatementBindingScope},
13    catalog::resolution::EffectiveSearchPath,
14    plan::UnifiedPlan,
15    routines::RoutineResolution,
16    ColumnType, FunctionTypeResolver, RowSchema, SQLError,
17};
18
19mod production;
20pub use production::{
21    analysis_is_current_with_control, analyze_definition_owned, analyze_result_schema_with_control,
22    analyze_routine_definition_owned, effective_search_path_with_control,
23};
24
25#[derive(Clone, Copy)]
26pub struct PreparedDefinitionContext<'a> {
27    pub types: &'a dyn FunctionTypeResolver,
28    pub routines: &'a dyn RoutineResolution,
29    pub procedures: &'a dyn crate::routines::resolution::RoutineOverloadCatalog,
30    pub scopes: &'a dyn StatementAnalysisScopes,
31    pub session: &'a dyn super::utility::PreparedSessionMetadata,
32    /// The catalog the `reg*` input functions read object names from when the statement is analyzed.
33    pub aliases: &'a dyn crate::schema::dependencies::oid_alias::OidAliasInput,
34}
35
36pub struct PreparedDefinition<P = UnifiedPlan> {
37    pub composite_inputs: super::composites::CompositeInputs,
38    pub logical_plan: P,
39    pub parameter_types: SharedPreparedInput<Vec<Option<ColumnType>>>,
40    pub result_schema: Option<RowSchema>,
41    pub effective_search_path: SharedPreparedInput<Option<EffectiveSearchPath>>,
42    pub dependencies: SharedPreparedInput<PreparedAnalysisDependencies>,
43    pub dependency_snapshot: SharedPreparedInput<Option<PreparedDependencySnapshot>>,
44}
45
46impl PreparedDefinition {
47    /// Publish ordinary analysis storage without copying its tree. Admitted producers publish their existing shared owner directly.
48    pub fn into_shared(self) -> PreparedDefinition<crate::plan::SharedExecutablePlan> {
49        PreparedDefinition {
50            composite_inputs: self.composite_inputs,
51            logical_plan: self.logical_plan.into(),
52            parameter_types: self.parameter_types,
53            result_schema: self.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_definition(
62    context: &PreparedDefinitionContext<'_>,
63    mut logical_plan: UnifiedPlan,
64    declared: &[ColumnType],
65) -> Result<PreparedDefinition, SQLError> {
66    let parameter_types =
67        super::declared_parameter_types(context.types, &mut logical_plan, declared)?;
68    if !super::utility::requires_analysis(&logical_plan) {
69        let result_schema = super::utility::result_schema(context.session, &logical_plan)?;
70        return Ok(PreparedDefinition {
71            composite_inputs: super::composites::CompositeInputs::default(),
72            logical_plan,
73            parameter_types: parameter_types.into(),
74            result_schema,
75            effective_search_path: None.into(),
76            dependencies: PreparedAnalysisDependencies::default().into(),
77            dependency_snapshot: None.into(),
78        });
79    }
80    let (input, effective_search_path, dependency_snapshot) = with_scope_result(
81        context.scopes,
82        |scope| {
83            let binding = scope.binding_context()?;
84            let mut input = if matches!(&logical_plan, UnifiedPlan::Command(command) if matches!(command.as_ref(), crate::plan::CommandPlan::Call { .. }))
85            {
86                let (_, input) = crate::binding::read_procedure_inputs(
87                    &crate::binding::statements::StatementAnalysisContext {
88                        routines: context.routines,
89                        scopes: context.scopes,
90                        aliases: context.aliases,
91                    },
92                    &crate::routines::resolution::RoutineOverloadContext {
93                        catalog: context.procedures,
94                    },
95                    context.procedures,
96                    &mut logical_plan,
97                    &parameter_types,
98                    &binding,
99                )?;
100                crate::binding::retain_prepared_input_metadata(
101                    context.routines,
102                    &mut logical_plan,
103                    &input.parameter_types,
104                    &binding,
105                )?;
106                input
107            } else {
108                crate::binding::read_prepared_inputs(
109                    context.routines,
110                    &mut logical_plan,
111                    &parameter_types,
112                    &binding,
113                    Some(context.aliases),
114                )?
115            };
116            crate::schema::dependencies::oid_alias::read_prepared_oid_alias_constants(
117                context.aliases,
118                &mut logical_plan,
119            )?;
120            logical_plan.visit_scalar_expressions(&mut |expression| {
121                input.dependencies.include_expression(expression);
122            });
123            let effective_search_path =
124                binding.catalog.effective_search_path(&binding.resolution)?;
125            let dependency_snapshot = binding
126                .catalog
127                .prepared_dependency_snapshot(&input.dependencies)?;
128            Ok((input, effective_search_path, dependency_snapshot))
129        },
130    )?;
131    let result_schema = analyze_result_schema(context, &logical_plan, &input.parameter_types)?;
132    Ok(PreparedDefinition {
133        composite_inputs: super::composites::CompositeInputs::capture(
134            &logical_plan,
135            context.types,
136        )?,
137        logical_plan,
138        parameter_types: input.parameter_types.into(),
139        result_schema,
140        effective_search_path: effective_search_path.into(),
141        dependencies: input.dependencies.into(),
142        dependency_snapshot: dependency_snapshot.into(),
143    })
144}
145
146/// Check analysis dependencies in one retained namespace. Catalogs that supplied no path or revision capability at analysis leave that part of freshness to their owner's invalidation events.
147pub fn analysis_is_current(
148    context: &PreparedDefinitionContext<'_>,
149    retained_path: Option<&EffectiveSearchPath>,
150    dependencies: &PreparedAnalysisDependencies,
151    retained_snapshot: Option<&PreparedDependencySnapshot>,
152) -> Result<bool, SQLError> {
153    if retained_path.is_none() && retained_snapshot.is_none() {
154        return Ok(true);
155    }
156    with_scope_result(context.scopes, |scope| {
157        let binding = scope.binding_context()?;
158        if let Some(path) = retained_path {
159            if binding
160                .catalog
161                .effective_search_path(&binding.resolution)?
162                .as_ref()
163                != Some(path)
164            {
165                return Ok(false);
166            }
167        }
168        match retained_snapshot {
169            Some(snapshot) => Ok(binding
170                .catalog
171                .prepared_dependency_snapshot(dependencies)?
172                .as_ref()
173                == Some(snapshot)),
174            None => Ok(true),
175        }
176    })
177}
178
179/// Read the live namespace through one retained binding scope before selecting a previously analyzed prepared statement.
180pub fn effective_search_path(
181    context: &PreparedDefinitionContext<'_>,
182) -> Result<Option<EffectiveSearchPath>, SQLError> {
183    with_scope_result(context.scopes, |scope| {
184        let binding = scope.binding_context()?;
185        binding.catalog.effective_search_path(&binding.resolution)
186    })
187}
188
189pub fn analyze_result_schema(
190    context: &PreparedDefinitionContext<'_>,
191    logical_plan: &UnifiedPlan,
192    parameter_types: &[Option<ColumnType>],
193) -> Result<Option<RowSchema>, SQLError> {
194    if !super::utility::requires_analysis(logical_plan) {
195        return super::utility::result_schema(context.session, logical_plan);
196    }
197    with_scope_result(context.scopes, |scope| {
198        let binding = scope.binding_context()?;
199        if let UnifiedPlan::Command(command) = logical_plan {
200            if let crate::plan::CommandPlan::Call { name, args } = command.as_ref() {
201                let params = super::analysis_parameters(parameter_types);
202                return crate::routines::call::ProcedureCallAnalysis::new(args)?.result_schema(
203                    name,
204                    &crate::routines::resolution::RoutineOverloadContext {
205                        catalog: context.procedures,
206                    },
207                    context.procedures,
208                    &mut |argument| {
209                        crate::binding::analyze_expression_plan_type(
210                            context.routines,
211                            argument,
212                            &params,
213                            &binding,
214                        )
215                    },
216                );
217            }
218        }
219        super::analyze_prepared_plan(context.routines, logical_plan, parameter_types, &binding)
220    })
221}
222
223fn with_scope_result<T>(
224    scopes: &dyn StatementAnalysisScopes,
225    mut analyze: impl FnMut(&dyn StatementBindingScope) -> Result<T, SQLError>,
226) -> Result<T, SQLError> {
227    let mut result = None;
228    scopes.with_scope(&mut |scope| {
229        result = Some(analyze(scope)?);
230        Ok(())
231    })?;
232    result.ok_or_else(|| {
233        SQLError::Internal("prepared analysis scope did not invoke its operation".into())
234    })
235}
236
237#[cfg(test)]
238mod tests;