Skip to main content

uqa_sql/binding/
view_dependencies.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Stored-view relation and sequence binding/dependency analysis.
8
9use crate::ast::FunctionBinding;
10use crate::{
11    plan::{QueryPlan, RelationalPlan, SourcePlan},
12    ScalarExpr,
13};
14use uqa_core::{RelationIdentity, Value};
15
16pub fn canonical_virtual_relation_reference(reference: &str) -> Option<String> {
17    crate::catalog::resolve_virtual_relation(&[], reference)
18        .map(crate::catalog::VirtualRelation::qualified_name)
19}
20
21pub fn sequence_function_reference_mut(expression: &mut ScalarExpr) -> Option<&mut String> {
22    let ScalarExpr::Func { name, args, .. } = expression else {
23        return None;
24    };
25    let lower = name.to_ascii_lowercase();
26    let local = lower.strip_prefix("pg_catalog.").unwrap_or(&lower);
27    if !matches!(local, "nextval" | "currval" | "setval")
28        || (lower.contains('.') && !lower.starts_with("pg_catalog."))
29    {
30        return None;
31    }
32    regclass_literal_mut(args.first_mut()?)
33}
34
35pub fn regclass_literal_mut(expression: &mut ScalarExpr) -> Option<&mut String> {
36    match expression {
37        ScalarExpr::Literal(Value::Str(reference)) => Some(reference),
38        ScalarExpr::Cast { expr, ty, .. }
39            if crate::ColumnType::from_sql_name(ty)
40                .is_ok_and(|ty| matches!(ty, crate::ColumnType::Regclass)) =>
41        {
42            regclass_literal_mut(expr)
43        }
44        _ => None,
45    }
46}
47
48pub fn bind_query_plan_sequence_references<E>(
49    plan: &mut QueryPlan,
50    resolve: &mut impl FnMut(&str) -> Result<String, E>,
51) -> Result<(), E> {
52    let mut error = None;
53    plan.rewrite_scalar_expressions(&mut |expression| {
54        if error.is_some() {
55            return;
56        }
57        let Some(reference) = sequence_function_reference_mut(expression) else {
58            return;
59        };
60        match resolve(reference) {
61            Ok(canonical) => *reference = canonical,
62            Err(binding_error) => error = Some(binding_error),
63        }
64    });
65    error.map_or(Ok(()), Err)
66}
67
68pub fn bind_query_plan_relations<E>(
69    plan: &mut QueryPlan,
70    inherited_ctes: &std::collections::BTreeSet<String>,
71    resolve: &mut impl FnMut(&str) -> Result<String, E>,
72) -> Result<(), E> {
73    bind_query_plan_relation_targets(plan, inherited_ctes, &mut |name, _| resolve(name))
74}
75
76/// Bind concrete relation references with their inheritance scope, excluding CTE aliases at every query boundary.
77pub fn bind_query_plan_relation_targets<E>(
78    plan: &mut QueryPlan,
79    inherited_ctes: &std::collections::BTreeSet<String>,
80    resolve: &mut impl FnMut(&str, bool) -> Result<String, E>,
81) -> Result<(), E> {
82    // Non-recursive CTEs see outer and preceding CTEs. WITH RECURSIVE makes every sibling visible while each body is bound, after which execution orders dependencies before their consumers.
83    let mut visible_ctes = inherited_ctes.clone();
84    let recursive_ctes = plan.ctes.iter().any(|cte| cte.recursive).then(|| {
85        plan.ctes
86            .iter()
87            .map(|cte| cte.name.clone())
88            .collect::<std::collections::BTreeSet<_>>()
89    });
90    for cte in &mut plan.ctes {
91        let body_ctes = recursive_ctes.as_ref().map_or_else(
92            || visible_ctes.clone(),
93            |ctes| inherited_ctes.union(ctes).cloned().collect(),
94        );
95        bind_cte_relation_targets(&mut cte.body, &body_ctes, resolve)?;
96        visible_ctes.insert(cte.name.clone());
97    }
98    bind_relational_targets(&mut plan.root, &visible_ctes, resolve)?;
99    plan.relations_bound = true;
100    Ok(())
101}
102
103pub fn bind_relational_plan_relations<E>(
104    plan: &mut RelationalPlan,
105    visible_ctes: &std::collections::BTreeSet<String>,
106    resolve: &mut impl FnMut(&str) -> Result<String, E>,
107) -> Result<(), E> {
108    bind_relational_targets(plan, visible_ctes, &mut |name, _| resolve(name))
109}
110
111fn bind_relational_targets<E>(
112    plan: &mut RelationalPlan,
113    visible_ctes: &std::collections::BTreeSet<String>,
114    resolve: &mut impl FnMut(&str, bool) -> Result<String, E>,
115) -> Result<(), E> {
116    match plan {
117        RelationalPlan::QueryBlock(block) => {
118            if let Some(source) = &mut block.from {
119                bind_source_targets(source, visible_ctes, resolve)?;
120            }
121            for subquery in &mut block.subqueries {
122                bind_query_plan_relation_targets(subquery, visible_ctes, resolve)?;
123            }
124        }
125        RelationalPlan::SetOp {
126            left,
127            right,
128            subqueries,
129            ..
130        } => {
131            bind_query_plan_relation_targets(left, visible_ctes, resolve)?;
132            bind_query_plan_relation_targets(right, visible_ctes, resolve)?;
133            for subquery in subqueries {
134                bind_query_plan_relation_targets(subquery, visible_ctes, resolve)?;
135            }
136        }
137        RelationalPlan::Values { subqueries, .. } => {
138            for subquery in subqueries {
139                bind_query_plan_relation_targets(subquery, visible_ctes, resolve)?;
140            }
141        }
142    }
143    Ok(())
144}
145
146pub fn bind_source_plan_relations<E>(
147    source: &mut SourcePlan,
148    visible_ctes: &std::collections::BTreeSet<String>,
149    resolve: &mut impl FnMut(&str) -> Result<String, E>,
150) -> Result<(), E> {
151    bind_source_targets(source, visible_ctes, &mut |name, _| resolve(name))
152}
153
154fn bind_source_targets<E>(
155    source: &mut SourcePlan,
156    visible_ctes: &std::collections::BTreeSet<String>,
157    resolve: &mut impl FnMut(&str, bool) -> Result<String, E>,
158) -> Result<(), E> {
159    match source {
160        crate::plan::SourcePlan::RetainedRows(_) => {}
161        SourcePlan::Table {
162            name,
163            qualifier,
164            include_descendants,
165            ..
166        } => {
167            if qualifier.is_empty() {
168                *qualifier = RelationIdentity::parse_reference(name)
169                    .map_or_else(|_| name.clone(), |(_, relation)| relation);
170            }
171            let is_cte = RelationIdentity::parse_reference(name).is_ok_and(|(schema, relation)| {
172                schema.is_none() && visible_ctes.contains(&relation)
173            });
174            if !is_cte {
175                *name = resolve(name, *include_descendants)?;
176            }
177        }
178        SourcePlan::Join { left, right, .. } => {
179            bind_source_targets(left, visible_ctes, resolve)?;
180            bind_source_targets(right, visible_ctes, resolve)?;
181        }
182        SourcePlan::Subquery { body, .. } => {
183            bind_query_plan_relation_targets(body, visible_ctes, resolve)?;
184        }
185        SourcePlan::Function {
186            name,
187            output_name,
188            relations,
189            ..
190        } => {
191            if output_name.is_empty() {
192                *output_name = RelationIdentity::parse_reference(name)
193                    .map_or_else(|_| name.clone(), |(_, function)| function);
194            }
195            if let Some(relations) = relations {
196                relations.left = resolve(&relations.left, false)?;
197                relations.right = resolve(&relations.right, false)?;
198            }
199        }
200        SourcePlan::FunctionGroup { functions, .. } => {
201            for function in functions {
202                if function.output_name.is_empty() {
203                    function.output_name = RelationIdentity::parse_reference(&function.name)
204                        .map_or_else(|_| function.name.clone(), |(_, name)| name);
205                }
206                if let Some(relations) = &mut function.relations {
207                    relations.left = resolve(&relations.left, false)?;
208                    relations.right = resolve(&relations.right, false)?;
209                }
210            }
211        }
212        SourcePlan::Values { .. } => {}
213    }
214    Ok(())
215}
216
217pub fn relation_reference_matches(reference: &str, target: &RelationIdentity) -> bool {
218    match RelationIdentity::parse_reference(reference) {
219        Ok((Some(schema), name)) => schema == target.schema && name == target.name,
220        Ok((None, name)) => name == target.name,
221        // A malformed stored plan must fail closed: treating it as unrelated
222        // could permit DDL to leave an unexecutable view behind.
223        Err(_) => true,
224    }
225}
226
227pub fn source_plan_references_relation(
228    source: &crate::plan::SourcePlan,
229    target: &RelationIdentity,
230    ctes: &std::collections::BTreeSet<String>,
231) -> bool {
232    match source {
233        crate::plan::SourcePlan::RetainedRows(_) => false,
234        crate::plan::SourcePlan::Table { name, .. } => {
235            let is_cte = RelationIdentity::parse_reference(name)
236                .is_ok_and(|(schema, relation)| schema.is_none() && ctes.contains(&relation));
237            !is_cte && relation_reference_matches(name, target)
238        }
239        crate::plan::SourcePlan::Join { left, right, .. } => {
240            source_plan_references_relation(left, target, ctes)
241                || source_plan_references_relation(right, target, ctes)
242        }
243        crate::plan::SourcePlan::Subquery { body, .. } => {
244            query_plan_references_relation(body, target, ctes)
245        }
246        crate::plan::SourcePlan::Function { relations, .. } => {
247            relations.as_ref().is_some_and(|relations| {
248                relation_reference_matches(&relations.left, target)
249                    || relation_reference_matches(&relations.right, target)
250            })
251        }
252        crate::plan::SourcePlan::FunctionGroup { functions, .. } => {
253            functions.iter().any(|function| {
254                function.relations.as_ref().is_some_and(|relations| {
255                    relation_reference_matches(&relations.left, target)
256                        || relation_reference_matches(&relations.right, target)
257                })
258            })
259        }
260        crate::plan::SourcePlan::Values { .. } => false,
261    }
262}
263
264pub fn query_plan_references_relation(
265    query: &crate::plan::QueryPlan,
266    target: &RelationIdentity,
267    inherited_ctes: &std::collections::BTreeSet<String>,
268) -> bool {
269    let mut ctes = inherited_ctes.clone();
270    ctes.extend(query.ctes.iter().map(|cte| cte.name.clone()));
271    if query
272        .ctes
273        .iter()
274        .any(|cte| cte_plan_references_relation(&cte.body, target, &ctes))
275    {
276        return true;
277    }
278    match &query.root {
279        crate::plan::RelationalPlan::QueryBlock(block) => {
280            block
281                .from
282                .as_ref()
283                .is_some_and(|source| source_plan_references_relation(source, target, &ctes))
284                || block
285                    .subqueries
286                    .iter()
287                    .any(|query| query_plan_references_relation(query, target, &ctes))
288        }
289        crate::plan::RelationalPlan::SetOp {
290            left,
291            right,
292            subqueries,
293            ..
294        } => {
295            query_plan_references_relation(left, target, &ctes)
296                || query_plan_references_relation(right, target, &ctes)
297                || subqueries
298                    .iter()
299                    .any(|query| query_plan_references_relation(query, target, &ctes))
300        }
301        crate::plan::RelationalPlan::Values { subqueries, .. } => subqueries
302            .iter()
303            .any(|query| query_plan_references_relation(query, target, &ctes)),
304    }
305}
306
307pub fn query_plan_references_sequence(plan: &QueryPlan, target: &RelationIdentity) -> bool {
308    let mut plan = plan.clone();
309    let mut referenced = false;
310    plan.rewrite_scalar_expressions(&mut |expression| {
311        if let Some(reference) = sequence_function_reference_mut(expression) {
312            referenced |= relation_reference_matches(reference, target);
313        }
314    });
315    referenced
316}
317
318pub use crate::routines::function_binding_matches;
319
320fn function_binding_needs_object_identity(binding: &FunctionBinding) -> bool {
321    !binding.builtin
322        && binding.dispatch.is_none()
323        && binding.resolution_error.is_none()
324        && binding.object_id.is_none()
325}
326
327fn source_plan_has_legacy_routine_identity(source: &SourcePlan) -> bool {
328    match source {
329        crate::plan::SourcePlan::RetainedRows(_) => false,
330        SourcePlan::Table { .. } | SourcePlan::Values { .. } => false,
331        SourcePlan::Join { left, right, .. } => {
332            source_plan_has_legacy_routine_identity(left)
333                || source_plan_has_legacy_routine_identity(right)
334        }
335        SourcePlan::Subquery { body, .. } => query_plan_sources_have_legacy_routine_identity(body),
336        SourcePlan::Function { binding, .. } => binding
337            .as_ref()
338            .is_some_and(function_binding_needs_object_identity),
339        SourcePlan::FunctionGroup { functions, .. } => functions.iter().any(|function| {
340            function
341                .binding
342                .as_ref()
343                .is_some_and(function_binding_needs_object_identity)
344        }),
345    }
346}
347
348fn relational_plan_has_legacy_routine_identity(plan: &RelationalPlan) -> bool {
349    match plan {
350        RelationalPlan::QueryBlock(block) => {
351            block
352                .from
353                .as_ref()
354                .is_some_and(source_plan_has_legacy_routine_identity)
355                || block
356                    .subqueries
357                    .iter()
358                    .any(query_plan_sources_have_legacy_routine_identity)
359        }
360        RelationalPlan::SetOp {
361            left,
362            right,
363            subqueries,
364            ..
365        } => {
366            query_plan_sources_have_legacy_routine_identity(left)
367                || query_plan_sources_have_legacy_routine_identity(right)
368                || subqueries
369                    .iter()
370                    .any(query_plan_sources_have_legacy_routine_identity)
371        }
372        RelationalPlan::Values { subqueries, .. } => subqueries
373            .iter()
374            .any(query_plan_sources_have_legacy_routine_identity),
375    }
376}
377
378fn query_plan_sources_have_legacy_routine_identity(plan: &QueryPlan) -> bool {
379    plan.ctes.iter().any(|cte| {
380        cte_relational_inputs_any(
381            &cte.body,
382            &query_plan_sources_have_legacy_routine_identity,
383            &source_plan_has_legacy_routine_identity,
384        )
385    }) || relational_plan_has_legacy_routine_identity(&plan.root)
386}
387
388pub fn query_plan_has_legacy_routine_identity(plan: &QueryPlan) -> bool {
389    query_plan_has_legacy_routine_identity_with_types(plan, None)
390}
391
392/// Preserve unbound host callbacks when their catalog context is available during restoration.
393pub fn query_plan_has_legacy_routine_identity_with_types(
394    plan: &QueryPlan,
395    types: Option<&dyn crate::FunctionTypeResolver>,
396) -> bool {
397    let mut scalar_plan = plan.clone();
398    let mut legacy = false;
399    scalar_plan.rewrite_scalar_expressions(&mut |expression| {
400        if let ScalarExpr::Func {
401            name,
402            binding,
403            order_syntax,
404            order_by,
405            ..
406        } = expression
407        {
408            legacy |= binding
409                .as_ref()
410                .is_some_and(function_binding_needs_object_identity);
411            legacy |=
412                crate::type_resolution::json_path::requires_binding(name, binding.as_ref(), types);
413            legacy |= crate::type_resolution::concatenation::requires_binding(
414                name,
415                binding.as_ref(),
416                types,
417            );
418            // Legacy ordered-set nodes lack the selected combined signature and
419            // written syntax; restore both in the existing initial-open transaction.
420            legacy |= *order_syntax == crate::ast::FunctionOrderSyntax::Legacy
421                && super::ordered_calls::uses_ordered_arguments(
422                    *order_syntax,
423                    name,
424                    binding.as_ref(),
425                    order_by.len(),
426                );
427        }
428    });
429    legacy || query_plan_sources_have_legacy_routine_identity(plan)
430}
431
432fn source_plan_references_function(source: &SourcePlan, target: &FunctionBinding) -> bool {
433    match source {
434        crate::plan::SourcePlan::RetainedRows(_) => false,
435        SourcePlan::Table { .. } | SourcePlan::Values { .. } => false,
436        SourcePlan::Join { left, right, .. } => {
437            source_plan_references_function(left, target)
438                || source_plan_references_function(right, target)
439        }
440        SourcePlan::Subquery { body, .. } => query_plan_sources_reference_function(body, target),
441        SourcePlan::Function { binding, .. } => binding
442            .as_ref()
443            .is_some_and(|binding| function_binding_matches(binding, target)),
444        SourcePlan::FunctionGroup { functions, .. } => functions.iter().any(|function| {
445            function
446                .binding
447                .as_ref()
448                .is_some_and(|binding| function_binding_matches(binding, target))
449        }),
450    }
451}
452
453fn relational_plan_references_function(plan: &RelationalPlan, target: &FunctionBinding) -> bool {
454    match plan {
455        RelationalPlan::QueryBlock(block) => {
456            block
457                .from
458                .as_ref()
459                .is_some_and(|source| source_plan_references_function(source, target))
460                || block
461                    .subqueries
462                    .iter()
463                    .any(|query| query_plan_sources_reference_function(query, target))
464        }
465        RelationalPlan::SetOp {
466            left,
467            right,
468            subqueries,
469            ..
470        } => {
471            query_plan_sources_reference_function(left, target)
472                || query_plan_sources_reference_function(right, target)
473                || subqueries
474                    .iter()
475                    .any(|query| query_plan_sources_reference_function(query, target))
476        }
477        RelationalPlan::Values { subqueries, .. } => subqueries
478            .iter()
479            .any(|query| query_plan_sources_reference_function(query, target)),
480    }
481}
482
483fn query_plan_sources_reference_function(plan: &QueryPlan, target: &FunctionBinding) -> bool {
484    plan.ctes.iter().any(|cte| {
485        cte_relational_inputs_any(
486            &cte.body,
487            &|query| query_plan_sources_reference_function(query, target),
488            &|source| source_plan_references_function(source, target),
489        )
490    }) || relational_plan_references_function(&plan.root, target)
491}
492
493pub fn query_plan_references_function(plan: &QueryPlan, target: &FunctionBinding) -> bool {
494    let mut scalar_plan = plan.clone();
495    let mut referenced = false;
496    scalar_plan.rewrite_scalar_expressions(&mut |expression| {
497        if let ScalarExpr::Func {
498            binding: Some(binding),
499            ..
500        } = expression
501        {
502            referenced |= function_binding_matches(binding, target);
503        }
504    });
505    referenced || query_plan_sources_reference_function(plan, target)
506}
507
508fn rewrite_source_plan_routine_identity(
509    source: &mut SourcePlan,
510    target: &FunctionBinding,
511    new_name: &str,
512) -> bool {
513    match source {
514        crate::plan::SourcePlan::RetainedRows(_) => false,
515        SourcePlan::Table { .. } | SourcePlan::Values { .. } => false,
516        SourcePlan::Join { left, right, .. } => {
517            rewrite_source_plan_routine_identity(left, target, new_name)
518                | rewrite_source_plan_routine_identity(right, target, new_name)
519        }
520        SourcePlan::Subquery { body, .. } => {
521            rewrite_query_source_routine_identity(body, target, new_name)
522        }
523        SourcePlan::Function { name, binding, .. } => {
524            let Some(binding) = binding.as_mut() else {
525                return false;
526            };
527            if !function_binding_matches(binding, target) {
528                return false;
529            }
530            *name = new_name.to_string();
531            binding.name = new_name.to_string();
532            true
533        }
534        SourcePlan::FunctionGroup { functions, .. } => {
535            let mut changed = false;
536            for function in functions {
537                let Some(binding) = function.binding.as_mut() else {
538                    continue;
539                };
540                if function_binding_matches(binding, target) {
541                    function.name = new_name.to_string();
542                    binding.name = new_name.to_string();
543                    changed = true;
544                }
545            }
546            changed
547        }
548    }
549}
550
551fn rewrite_relational_plan_source_routine_identity(
552    plan: &mut RelationalPlan,
553    target: &FunctionBinding,
554    new_name: &str,
555) -> bool {
556    match plan {
557        RelationalPlan::QueryBlock(block) => {
558            let mut changed = block.from.as_mut().is_some_and(|source| {
559                rewrite_source_plan_routine_identity(source, target, new_name)
560            });
561            for subquery in &mut block.subqueries {
562                changed |= rewrite_query_source_routine_identity(subquery, target, new_name);
563            }
564            changed
565        }
566        RelationalPlan::SetOp {
567            left,
568            right,
569            subqueries,
570            ..
571        } => {
572            let mut changed = rewrite_query_source_routine_identity(left, target, new_name)
573                | rewrite_query_source_routine_identity(right, target, new_name);
574            for subquery in subqueries {
575                changed |= rewrite_query_source_routine_identity(subquery, target, new_name);
576            }
577            changed
578        }
579        RelationalPlan::Values { subqueries, .. } => {
580            let mut changed = false;
581            for subquery in subqueries {
582                changed |= rewrite_query_source_routine_identity(subquery, target, new_name);
583            }
584            changed
585        }
586    }
587}
588
589fn rewrite_query_source_routine_identity(
590    plan: &mut QueryPlan,
591    target: &FunctionBinding,
592    new_name: &str,
593) -> bool {
594    let mut changed = false;
595    for cte in &mut plan.ctes {
596        changed |= rewrite_cte_source_routine_identity(&mut cte.body, target, new_name);
597    }
598    changed | rewrite_relational_plan_source_routine_identity(&mut plan.root, target, new_name)
599}
600
601pub fn rewrite_query_plan_routine_identity(
602    plan: &mut QueryPlan,
603    target: &FunctionBinding,
604    new_name: &str,
605) -> bool {
606    let mut changed = false;
607    plan.rewrite_scalar_expressions(&mut |expression| {
608        let ScalarExpr::Func {
609            name,
610            binding: Some(binding),
611            ..
612        } = expression
613        else {
614            return;
615        };
616        if function_binding_matches(binding, target) {
617            *name = new_name.to_string();
618            binding.name = new_name.to_string();
619            changed = true;
620        }
621    });
622    changed | rewrite_query_source_routine_identity(plan, target, new_name)
623}
624
625pub fn bind_cte_plan_relations<E>(
626    body: &mut crate::plan::CtePlanBody,
627    inherited: &std::collections::BTreeSet<String>,
628    resolve: &mut impl FnMut(&str) -> Result<String, E>,
629) -> Result<(), E> {
630    bind_cte_relation_targets(body, inherited, &mut |name, _| resolve(name))
631}
632
633fn bind_cte_relation_targets<E>(
634    body: &mut crate::plan::CtePlanBody,
635    inherited: &std::collections::BTreeSet<String>,
636    resolve: &mut impl FnMut(&str, bool) -> Result<String, E>,
637) -> Result<(), E> {
638    let crate::plan::CtePlanBody::Command(command) = body else {
639        let crate::plan::CtePlanBody::Query(query) = body else {
640            unreachable!()
641        };
642        return bind_query_plan_relation_targets(query, inherited, resolve);
643    };
644    let include_descendants = match command.as_ref() {
645        crate::plan::CommandPlan::Update(plan) => plan.include_descendants,
646        crate::plan::CommandPlan::Delete(plan) => plan.include_descendants,
647        _ => false,
648    };
649    if let Some(target) = command.mutation_target_mut() {
650        *target = resolve(target, include_descendants)?;
651    }
652    match command.as_mut() {
653        crate::plan::CommandPlan::Insert(plan) => {
654            plan.target_relation_bound = true;
655            plan.relations_bound = true;
656        }
657        crate::plan::CommandPlan::Update(plan) => {
658            plan.target_relation_bound = true;
659            plan.relations_bound = true;
660        }
661        crate::plan::CommandPlan::Delete(plan) => {
662            plan.target_relation_bound = true;
663            plan.relations_bound = true;
664        }
665        _ => {}
666    }
667    let mut visible = inherited.clone();
668    if let Some(ctes) = command.ctes_mut() {
669        let recursive = ctes.iter().any(|cte| cte.recursive).then(|| {
670            ctes.iter()
671                .map(|cte| cte.name.clone())
672                .collect::<std::collections::BTreeSet<_>>()
673        });
674        for cte in ctes {
675            let scope = recursive.as_ref().map_or_else(
676                || visible.clone(),
677                |names| inherited.union(names).cloned().collect(),
678            );
679            bind_cte_relation_targets(&mut cte.body, &scope, resolve)?;
680            visible.insert(cte.name.clone());
681        }
682    }
683    if let Some(source) = command.source_input_mut() {
684        bind_source_targets(source, &visible, resolve)?;
685    }
686    for query in command.query_inputs_mut() {
687        bind_query_plan_relation_targets(query, &visible, resolve)?;
688    }
689    Ok(())
690}
691
692fn cte_plan_references_relation(
693    body: &crate::plan::CtePlanBody,
694    target: &RelationIdentity,
695    inherited: &std::collections::BTreeSet<String>,
696) -> bool {
697    match body {
698        crate::plan::CtePlanBody::Query(query) => {
699            query_plan_references_relation(query, target, inherited)
700        }
701        crate::plan::CtePlanBody::Command(command) => {
702            let mut visible = inherited.clone();
703            visible.extend(command.ctes().iter().map(|cte| cte.name.clone()));
704            command
705                .mutation_target()
706                .is_some_and(|name| relation_reference_matches(name, target))
707                || command
708                    .ctes()
709                    .iter()
710                    .any(|cte| cte_plan_references_relation(&cte.body, target, &visible))
711                || command
712                    .source_input()
713                    .is_some_and(|source| source_plan_references_relation(source, target, &visible))
714                || command
715                    .query_inputs()
716                    .iter()
717                    .any(|query| query_plan_references_relation(query, target, &visible))
718        }
719    }
720}
721
722fn cte_relational_inputs_any(
723    body: &crate::plan::CtePlanBody,
724    query: &dyn Fn(&QueryPlan) -> bool,
725    source: &dyn Fn(&crate::plan::SourcePlan) -> bool,
726) -> bool {
727    match body {
728        crate::plan::CtePlanBody::Query(plan) => query(plan),
729        crate::plan::CtePlanBody::Command(command) => {
730            command
731                .ctes()
732                .iter()
733                .any(|cte| cte_relational_inputs_any(&cte.body, query, source))
734                || command.query_inputs().iter().any(|plan| query(plan))
735                || command.source_input().is_some_and(source)
736        }
737    }
738}
739
740fn rewrite_cte_source_routine_identity(
741    body: &mut crate::plan::CtePlanBody,
742    target: &FunctionBinding,
743    new_name: &str,
744) -> bool {
745    match body {
746        crate::plan::CtePlanBody::Query(query) => {
747            rewrite_query_source_routine_identity(query, target, new_name)
748        }
749        crate::plan::CtePlanBody::Command(command) => {
750            let mut changed = false;
751            if let Some(ctes) = command.ctes_mut() {
752                for cte in ctes {
753                    changed |= rewrite_cte_source_routine_identity(&mut cte.body, target, new_name);
754                }
755            }
756            if let Some(source) = command.source_input_mut() {
757                changed |= rewrite_source_plan_routine_identity(source, target, new_name);
758            }
759            for query in command.query_inputs_mut() {
760                changed |= rewrite_query_source_routine_identity(query, target, new_name);
761            }
762            changed
763        }
764    }
765}
766
767pub mod restoration;