Skip to main content

uqa_sql/prepared/entry/
reuse.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Recognize executables whose mutable dependencies are covered by their retained analysis snapshot.
8
9use super::PreparedStatementPlan;
10use crate::prepared::composites::CompositeInputs;
11use crate::{
12    ast::FunctionBinding,
13    plan::{QueryPlan, RelationalPlan, SourcePlan, UnifiedPlan},
14    ColumnType, ScalarExpr,
15};
16use uqa_core::Value;
17
18impl PreparedStatementPlan {
19    /// Primitive expressions and selected fixed builtins can retain their executable across an unrelated registry refresh. Relations require exact analysis revisions, checked before every plan selection; surviving calls still check current execution privileges.
20    #[must_use]
21    pub fn has_tracked_executable_dependencies(&self) -> bool {
22        let composites = &self.composite_inputs;
23        let tracked_type = |ty: &ColumnType| independent_type(ty) || composites.tracks_type(ty);
24        if self.needs_analysis
25            || !self.dependencies.routines.is_empty()
26            || !self
27                .parameter_types
28                .iter()
29                .all(|ty| ty.as_ref().is_some_and(tracked_type))
30        {
31            return false;
32        }
33        let Some(schema) = &self.result_schema else {
34            return false;
35        };
36        if !schema
37            .column_types()
38            .iter()
39            .all(|ty| ty.as_ref().is_some_and(tracked_type))
40            || (0..schema.len()).any(|index| {
41                schema.record_fields(index).is_some()
42                    && schema.column_types()[index]
43                        .as_ref()
44                        .is_none_or(|ty| !composites.tracks_type(ty))
45            })
46        {
47            return false;
48        }
49        let tracked_relations = !self.dependencies.relations.is_empty()
50            && self.dependency_snapshot.as_ref().is_some_and(|snapshot| {
51                snapshot.global_catalog.is_some()
52                    && self
53                        .dependencies
54                        .relations
55                        .iter()
56                        .all(|oid| snapshot.relations.get(oid).is_some_and(Option::is_some))
57            });
58        if !self.dependencies.relations.is_empty() && !tracked_relations {
59            return false;
60        }
61        self.plan
62            .as_ref()
63            .is_some_and(|plan| independent_plan(plan, true, tracked_relations, composites))
64            // Composite analysis has replaced written type names and ROW casts with retained identities; its logical tree carries every remaining executable input.
65            && (composites.has_inputs()
66                || independent_plan(&self.source_plan, false, tracked_relations, composites))
67            && independent_plan(&self.logical_plan, false, tracked_relations, composites)
68    }
69}
70
71fn independent_plan(
72    plan: &UnifiedPlan,
73    executable: bool,
74    tracked_relations: bool,
75    composites: &CompositeInputs,
76) -> bool {
77    match plan {
78        UnifiedPlan::Query(query) => {
79            independent_query(query, executable, tracked_relations, composites)
80        }
81        UnifiedPlan::Command(_) => false,
82    }
83}
84
85fn independent_query(
86    query: &QueryPlan,
87    executable: bool,
88    tracked_relations: bool,
89    composites: &CompositeInputs,
90) -> bool {
91    if !query.ctes.is_empty() {
92        return false;
93    }
94    let admitted =
95        |expression: &ScalarExpr| independent_expression(expression, executable, composites);
96    match &query.root {
97        RelationalPlan::QueryBlock(block) => {
98            block.from.as_ref().is_none_or(|source| {
99                tracked_relations && matches!(source, SourcePlan::Table { .. })
100            }) && block.subqueries.is_empty()
101                && block.windows.is_empty()
102                && block.locking.is_empty()
103                && block.query_expressions().all(admitted)
104        }
105        RelationalPlan::SetOp {
106            left,
107            right,
108            order_by,
109            limit,
110            offset,
111            subqueries,
112            ..
113        } => {
114            subqueries.is_empty()
115                && independent_query(left, executable, tracked_relations, composites)
116                && independent_query(right, executable, tracked_relations, composites)
117                && order_by
118                    .iter()
119                    .map(|order| &order.expr)
120                    .chain(limit.as_deref())
121                    .chain(offset.as_deref())
122                    .all(admitted)
123        }
124        RelationalPlan::Values { rows, subqueries } => {
125            subqueries.is_empty() && rows.iter().flatten().all(admitted)
126        }
127    }
128}
129
130fn independent_expression(
131    expression: &ScalarExpr,
132    executable: bool,
133    composites: &CompositeInputs,
134) -> bool {
135    let mut independent = true;
136    expression.visit(&mut |part| {
137        independent &= match part {
138            ScalarExpr::Literal(value) => independent_value(value),
139            ScalarExpr::RetainedLiteral(literal) => {
140                // Retained values are already evaluated. Classify their selected identity without decoding resident or spilled payloads.
141                literal
142                    .ty
143                    .as_ref()
144                    .is_some_and(|ty| independent_type(ty) || composites.tracks_type(ty))
145                    && literal.declaration.as_deref().is_none_or(|name| {
146                        independent_type_name(name) || composites.tracks_name(name)
147                    })
148            }
149            ScalarExpr::Collated { ty, .. } => independent_type(ty) || composites.tracks_type(ty),
150            ScalarExpr::Cast { ty, .. } => independent_type_name(ty) || composites.tracks_name(ty),
151            ScalarExpr::TypedLiteral {
152                value,
153                ty,
154                bound_type,
155                parameter_index,
156                ..
157            } => {
158                parameter_index.is_none()
159                    && ((bound_type
160                        .as_ref()
161                        .is_some_and(|ty| composites.tracks_type(ty))
162                        || composites.tracks_name(ty))
163                        || (independent_value(value)
164                            && bound_type
165                                .as_ref()
166                                .map_or_else(|| independent_type_name(ty), independent_type)))
167            }
168            ScalarExpr::CompositeRow {
169                bound_type,
170                binding,
171                ..
172            } => {
173                bound_type
174                    .as_ref()
175                    .is_some_and(|ty| composites.tracks_type(ty))
176                    || composites.tracks_name(&binding.ty)
177            }
178            ScalarExpr::Func {
179                binding,
180                args,
181                distinct,
182                order_by,
183                filter,
184                ..
185            } => {
186                !*distinct
187                    && order_by.is_empty()
188                    && filter.is_none()
189                    && binding.as_ref().map_or(!executable, |binding| {
190                        tracked_field(binding, composites)
191                            || (independent_binding(binding)
192                                && (!executable
193                                    || (args.len() == binding.argument_types.len()
194                                        && crate::fixed_builtin_return_type(binding)
195                                            .is_some_and(|ty| independent_type(&ty)))))
196                    })
197            }
198            ScalarExpr::Column(_)
199            | ScalarExpr::QualifiedColumn { .. }
200            | ScalarExpr::Param(_)
201            | ScalarExpr::Array(_)
202            | ScalarExpr::Binary { .. }
203            | ScalarExpr::UnaryMinus(_)
204            | ScalarExpr::Not(_)
205            | ScalarExpr::And(_)
206            | ScalarExpr::Or(_)
207            | ScalarExpr::IsNull { .. }
208            | ScalarExpr::Between { .. }
209            | ScalarExpr::InList { .. }
210            | ScalarExpr::Case { .. } => true,
211            _ => false,
212        };
213    });
214    independent
215}
216
217fn tracked_field(binding: &FunctionBinding, composites: &CompositeInputs) -> bool {
218    binding.builtin
219        && binding.object_id.is_none()
220        && binding.dispatch == Some(crate::ast::FunctionDispatch::FieldSelect)
221        && binding.invocation.is_none()
222        && binding.resolution_error.is_none()
223        && binding.composite_field().is_some_and(|field| {
224            composites.tracks_oid(field.type_oid)
225                && (independent_type(&field.result_type)
226                    || composites.tracks_type(&field.result_type))
227        })
228}
229
230fn independent_binding(binding: &FunctionBinding) -> bool {
231    binding.builtin
232        && binding.object_id.is_none()
233        && binding.dispatch.is_none()
234        && binding.invocation.is_none()
235        && binding.resolution_error.is_none()
236        && binding
237            .argument_types
238            .iter()
239            .all(|ty| independent_type_name(ty))
240}
241
242fn independent_value(value: &Value) -> bool {
243    match value {
244        Value::Null
245        | Value::Bool(_)
246        | Value::Int(_)
247        | Value::Float(_)
248        | Value::Str(_)
249        | Value::FixedChar(_)
250        | Value::Bytes(_)
251        | Value::BitString(_)
252        | Value::Decimal(_)
253        | Value::Json(_)
254        | Value::JsonB(_) => true,
255        Value::Datum(datum) => crate::catalog::type_metadata::builtin_scalar_type(datum.type_oid())
256            .is_some_and(independent_type),
257        Value::Array(array) => array.elements().iter().all(independent_value),
258        _ => false,
259    }
260}
261
262fn independent_type_name(name: &str) -> bool {
263    ColumnType::from_sql_name(name).is_ok_and(|ty| independent_type(&ty))
264}
265
266// The admitted set has catalog-free input and result identities. Keep pseudo, reg*, temporal, domain, enum and composite types on the existing conservative invalidation path.
267fn independent_type(ty: &ColumnType) -> bool {
268    match ty {
269        ColumnType::Array(element) => independent_type(element),
270        ColumnType::SmallInteger
271        | ColumnType::Integer
272        | ColumnType::BigInteger
273        | ColumnType::Boolean
274        | ColumnType::Text
275        | ColumnType::Name
276        | ColumnType::Uuid
277        | ColumnType::Varchar(_)
278        | ColumnType::Bpchar
279        | ColumnType::Character(_)
280        | ColumnType::Real
281        | ColumnType::DoublePrecision
282        | ColumnType::Numeric { .. }
283        | ColumnType::Json
284        | ColumnType::JsonB
285        | ColumnType::Bytea
286        | ColumnType::InternalChar => true,
287        _ => false,
288    }
289}
290
291#[cfg(test)]
292mod tests;