Skip to main content

uqa_sql/semantics/rules/
action_binding.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Query-scope-aware binding for rewrite-rule OLD/NEW pseudo-relations.
8
9use std::collections::BTreeSet;
10
11use crate::ast::{Expr, FrameBound, OrderBy, Projection, RuleEvent, Statement, UpdateStmt};
12use crate::plan::copy::{CollectSyntax, SyntaxProduction};
13use crate::plpgsql::RewriteReference;
14use crate::plpgsql::{bind_statement, ResolvedVariable, VariableResolver};
15use crate::SQLError;
16use uqa_core::memory::{Produced, ProductionControl};
17
18mod owned;
19pub(super) use owned::returning_mut;
20pub use owned::BoundRuleStatement;
21mod query;
22use query::{bind_ctes, bind_from, bind_select_with_scope};
23mod insert;
24mod inspection;
25use insert::bind_insert;
26mod names;
27pub use names::ActionColumns;
28mod namespace;
29mod references;
30mod returning;
31mod row_expansion;
32mod scope;
33#[cfg(test)]
34mod tests;
35pub use references::{
36    first_rule_row_reference_in_expr, first_rule_row_reference_in_select,
37    first_rule_row_reference_in_statement, relation_rule_row_columns_with_control,
38    rule_action_has_set_operation, rule_action_input_columns_with_control,
39    rule_action_references_row_with_control, rule_condition_plan_references_whole_row,
40    rule_condition_plan_row_columns, rule_expr_references_row, rule_expr_references_whole_row,
41    rule_expr_row_columns, rule_new_row_columns, rule_new_row_columns_with_control,
42    rule_statement_references_row, rule_statement_references_whole_row, rule_statement_row_columns,
43};
44pub use returning::expand_rule_action_returning_stars;
45pub use row_expansion::expand_rule_action_row_stars;
46use scope::{collect_visible_scope, cte_output_columns, RuleBindingScope};
47
48pub fn action_target_qualifier_referenced(
49    catalog: &dyn RuleSourceCatalog,
50    action: &Statement,
51    qualifier: &str,
52) -> bool {
53    namespace::action_target_qualifier_referenced(catalog, action, qualifier)
54}
55
56mod context;
57use context::RuleBindingContext;
58pub use context::{
59    rule_action_target_columns, rule_action_target_columns_with_control,
60    rule_action_target_row_type, RuleSourceCatalog,
61};
62
63/// Bind an action's event-row OLD/NEW references while preserving the action
64/// row-image aliases visible to its DML RETURNING clause.
65pub fn bind_rule_action(
66    catalog: &dyn RuleSourceCatalog,
67    action: &Statement,
68    action_columns: &BTreeSet<String>,
69    resolver: &mut dyn VariableResolver,
70) -> Result<Statement, SQLError> {
71    Ok(bind_rule_action_with_control(
72        catalog,
73        action,
74        action_columns,
75        resolver,
76        &ProductionControl::uncontrolled(),
77    )?
78    .into_parts()
79    .0)
80}
81
82/// Construct the bound immutable action under its original request allowance. Scratch scopes retire before the completed syntax is returned.
83pub fn bind_rule_action_with_control(
84    catalog: &dyn RuleSourceCatalog,
85    action: &Statement,
86    action_columns: &dyn ActionColumns,
87    resolver: &mut dyn VariableResolver,
88    control: &ProductionControl<'_>,
89) -> Result<Produced<Statement>, SQLError> {
90    BoundRuleStatement::bind(catalog, action, action_columns, resolver, control)?.into_produced()
91}
92
93struct RuleActionBodyResolver<'a, 'resolver> {
94    action_columns: &'a dyn names::ActionColumns,
95    action_event: RuleEvent,
96    event_resolver: &'resolver mut dyn VariableResolver,
97}
98
99impl RuleActionBodyResolver<'_, '_> {
100    fn is_action_column(&self, name: &str) -> bool {
101        matches!(self.action_event, RuleEvent::Update | RuleEvent::Delete)
102            && self.action_columns.contains_folded(name)
103    }
104}
105
106impl VariableResolver for RuleActionBodyResolver<'_, '_> {
107    fn rewrite_with_control(
108        &mut self,
109        reference: RewriteReference<'_>,
110        control: &ProductionControl<'_>,
111    ) -> Result<Option<Produced<Expr>>, SQLError> {
112        control.check()?;
113        if matches!(reference, RewriteReference::Name(name) if self.is_action_column(name)) {
114            Ok(None)
115        } else {
116            self.event_resolver.rewrite_with_control(reference, control)
117        }
118    }
119
120    fn expand_with_control(
121        &mut self,
122        qualifier: &str,
123        control: &ProductionControl<'_>,
124    ) -> Result<Option<Produced<Vec<Expr>>>, SQLError> {
125        self.event_resolver.expand_with_control(qualifier, control)
126    }
127
128    fn resolve_name(&mut self, name: &str) -> Result<Option<ResolvedVariable>, SQLError> {
129        if self.is_action_column(name) {
130            Ok(None)
131        } else {
132            self.event_resolver.resolve_name(name)
133        }
134    }
135
136    fn resolve_qualified(
137        &mut self,
138        qualifier: &str,
139        column: &str,
140    ) -> Result<Option<ResolvedVariable>, SQLError> {
141        self.event_resolver.resolve_qualified(qualifier, column)
142    }
143
144    fn resolve_param(&mut self, index: usize) -> Result<Option<ResolvedVariable>, SQLError> {
145        self.event_resolver.resolve_param(index)
146    }
147
148    fn rewrite_name(&mut self, name: &str) -> Result<Option<Expr>, SQLError> {
149        if self.is_action_column(name) {
150            Ok(None)
151        } else {
152            self.event_resolver.rewrite_name(name)
153        }
154    }
155
156    fn rewrite_qualified(
157        &mut self,
158        qualifier: &str,
159        column: &str,
160    ) -> Result<Option<Expr>, SQLError> {
161        self.event_resolver.rewrite_qualified(qualifier, column)
162    }
163
164    fn rewrite_qualified_star(&mut self, qualifier: &str) -> Result<Option<Vec<Expr>>, SQLError> {
165        self.event_resolver.rewrite_qualified_star(qualifier)
166    }
167
168    fn rewrite_qualified_whole_row(&mut self, qualifier: &str) -> Result<Option<Expr>, SQLError> {
169        self.event_resolver.rewrite_qualified_whole_row(qualifier)
170    }
171
172    fn rewrite_param(&mut self, index: usize) -> Result<Option<Expr>, SQLError> {
173        self.event_resolver.rewrite_param(index)
174    }
175
176    fn rewrite_internal(
177        &mut self,
178        column: crate::ast::InternalColumnRef,
179    ) -> Result<Option<Expr>, SQLError> {
180        self.event_resolver.rewrite_internal(column)
181    }
182}
183
184/// Bind one expression while masking relation qualifiers supplied by the SQL scope around it. Nested query scopes add their own visible aliases.
185pub fn bind_rule_expr_scoped(
186    expr: &Expr,
187    resolver: &mut dyn VariableResolver,
188    shadowed: &BTreeSet<String>,
189) -> Result<Expr, SQLError> {
190    Ok(bind_rule_expr_scoped_with_control(
191        expr,
192        resolver,
193        shadowed,
194        &ProductionControl::uncontrolled(),
195    )?
196    .into_parts()
197    .0)
198}
199
200pub fn bind_rule_expr_scoped_with_control(
201    expr: &Expr,
202    resolver: &mut dyn VariableResolver,
203    shadowed: &BTreeSet<String>,
204    control: &ProductionControl<'_>,
205) -> Result<Produced<Expr>, SQLError> {
206    control.check()?;
207    let production = SyntaxProduction::new(*control);
208    let value = bind_rule_expr_with_scope(
209        expr,
210        resolver,
211        &RuleBindingScope::from_qualifiers_with_control(shadowed, control)?,
212        &RuleBindingContext::from_control(control),
213        &production,
214    )?;
215    production.finish(value)
216}
217
218fn rewrite_reference(
219    expr: &Expr,
220    reference: RewriteReference<'_>,
221    resolver: &mut dyn VariableResolver,
222    production: &SyntaxProduction<'_>,
223) -> Result<Expr, SQLError> {
224    match resolver.rewrite_with_control(reference, &production.control())? {
225        Some(value) => Ok(production.take(value)),
226        None => production.copy(expr),
227    }
228}
229
230fn bind_rule_expr_with_scope(
231    expr: &Expr,
232    resolver: &mut dyn VariableResolver,
233    scope: &RuleBindingScope,
234    context: &RuleBindingContext<'_>,
235    production: &SyntaxProduction<'_>,
236) -> Result<Expr, SQLError> {
237    production.check()?;
238    Ok(match expr {
239        Expr::Column(_)
240        | Expr::QualifiedColumn { .. }
241        | Expr::Param(_)
242        | Expr::InternalColumn(_)
243        | Expr::QualifiedStar(_) => bind_reference_expression(expr, resolver, scope, production)?,
244        Expr::Default
245        | Expr::Literal(_)
246        | Expr::TypedLiteral { .. }
247        | Expr::RetainedLiteral(_)
248        | Expr::Star => production.copy(expr)?,
249        Expr::Func { .. } => {
250            bind_rule_function_expression(expr, resolver, scope, context, production)?
251        }
252        Expr::Array(items) => Expr::Array(bind_exprs(items, resolver, scope, context, production)?),
253        Expr::Row(items) => Expr::Row(bind_expanding_exprs(
254            items, resolver, scope, context, production,
255        )?),
256        Expr::CompositeRow { items, binding } => Expr::CompositeRow {
257            items: bind_expanding_exprs(items, resolver, scope, context, production)?,
258            binding: production.copy(binding)?,
259        },
260        Expr::Binary { op, lhs, rhs } => Expr::Binary {
261            op: *op,
262            lhs: production.boxed(bind_rule_expr_with_scope(
263                lhs, resolver, scope, context, production,
264            )?)?,
265            rhs: production.boxed(bind_rule_expr_with_scope(
266                rhs, resolver, scope, context, production,
267            )?)?,
268        },
269        Expr::UnaryMinus(inner) => Expr::UnaryMinus(production.boxed(
270            bind_rule_expr_with_scope(inner, resolver, scope, context, production)?,
271        )?),
272        Expr::Not(inner) => Expr::Not(production.boxed(bind_rule_expr_with_scope(
273            inner, resolver, scope, context, production,
274        )?)?),
275        Expr::And(items) => Expr::And(bind_exprs(items, resolver, scope, context, production)?),
276        Expr::Or(items) => Expr::Or(bind_exprs(items, resolver, scope, context, production)?),
277        Expr::IsNull { expr, negated } => Expr::IsNull {
278            expr: production.boxed(bind_rule_expr_with_scope(
279                expr, resolver, scope, context, production,
280            )?)?,
281            negated: *negated,
282        },
283        Expr::Between { expr, low, high } => Expr::Between {
284            expr: production.boxed(bind_rule_expr_with_scope(
285                expr, resolver, scope, context, production,
286            )?)?,
287            low: production.boxed(bind_rule_expr_with_scope(
288                low, resolver, scope, context, production,
289            )?)?,
290            high: production.boxed(bind_rule_expr_with_scope(
291                high, resolver, scope, context, production,
292            )?)?,
293        },
294        Expr::InList {
295            expr,
296            list,
297            negated,
298        } => Expr::InList {
299            expr: production.boxed(bind_rule_expr_with_scope(
300                expr, resolver, scope, context, production,
301            )?)?,
302            list: bind_exprs(list, resolver, scope, context, production)?,
303            negated: *negated,
304        },
305        Expr::WindowCall { .. } => {
306            bind_rule_window_expression(expr, resolver, scope, context, production)?
307        }
308        Expr::Case { .. } => bind_rule_case_expression(expr, resolver, scope, context, production)?,
309        Expr::Cast { expr, ty, implicit } => Expr::Cast {
310            implicit: *implicit,
311            expr: production.boxed(bind_rule_expr_with_scope(
312                expr, resolver, scope, context, production,
313            )?)?,
314            ty: production.copy(ty)?,
315        },
316        Expr::ScalarSubquery(_) | Expr::Exists { .. } | Expr::InSubquery { .. } => {
317            bind_query_expression(expr, resolver, scope, context, production)?
318        }
319    })
320}
321
322fn bind_rule_function_expression(
323    expr: &Expr,
324    resolver: &mut dyn VariableResolver,
325    scope: &RuleBindingScope,
326    context: &RuleBindingContext<'_>,
327    production: &SyntaxProduction<'_>,
328) -> Result<Expr, SQLError> {
329    if let Some((qualifier, column)) = namespace::event_field_reference(expr, scope) {
330        return match resolver.rewrite_with_control(
331            RewriteReference::Qualified { qualifier, column },
332            &production.control(),
333        )? {
334            Some(value) => Ok(production.take(value)),
335            None => Ok(Expr::QualifiedColumn {
336                qualifier: production.text(qualifier)?,
337                column: production.text(column)?.into(),
338            }),
339        };
340    }
341    let Expr::Func {
342        order_syntax,
343        name,
344        binding,
345        args,
346        distinct,
347        order_by,
348        filter,
349    } = expr
350    else {
351        unreachable!("function binder received a non-function expression")
352    };
353    Ok(Expr::Func {
354        order_syntax: *order_syntax,
355        name: production.copy(name)?,
356        binding: production.copy(binding)?,
357        args: bind_exprs(args, resolver, scope, context, production)?,
358        distinct: *distinct,
359        order_by: bind_orders(order_by, resolver, scope, context, production)?,
360        filter: filter
361            .as_deref()
362            .map(|expr| {
363                bind_rule_expr_with_scope(expr, resolver, scope, context, production)
364                    .and_then(|value| production.boxed(value))
365            })
366            .transpose()?,
367    })
368}
369
370fn bind_window_spec(
371    spec: &crate::ast::WindowSpec,
372    resolver: &mut dyn VariableResolver,
373    scope: &RuleBindingScope,
374    context: &RuleBindingContext<'_>,
375    production: &SyntaxProduction<'_>,
376) -> Result<crate::ast::WindowSpec, SQLError> {
377    Ok(crate::ast::WindowSpec {
378        definition: spec.definition,
379        raw_definition: None,
380        reference: production.copy(&spec.reference)?,
381        partition_by: bind_exprs(&spec.partition_by, resolver, scope, context, production)?,
382        order_by: bind_orders(&spec.order_by, resolver, scope, context, production)?,
383        frame: spec
384            .frame
385            .as_ref()
386            .map(|frame| -> Result<crate::ast::WindowFrame, SQLError> {
387                Ok(crate::ast::WindowFrame {
388                    mode: frame.mode,
389                    start: bind_frame_bound(&frame.start, resolver, scope, context, production)?,
390                    end: bind_frame_bound(&frame.end, resolver, scope, context, production)?,
391                    between: frame.between,
392                    exclusion: frame.exclusion,
393                })
394            })
395            .transpose()?,
396    })
397}
398
399fn bind_rule_window_expression(
400    expr: &Expr,
401    resolver: &mut dyn VariableResolver,
402    scope: &RuleBindingScope,
403    context: &RuleBindingContext<'_>,
404    production: &SyntaxProduction<'_>,
405) -> Result<Expr, SQLError> {
406    let Expr::WindowCall {
407        name,
408        args,
409        spec,
410        filter,
411        modifiers,
412    } = expr
413    else {
414        unreachable!("window binder received a non-window expression")
415    };
416    Ok(Expr::WindowCall {
417        modifiers: *modifiers,
418        name: production.copy(name)?,
419        args: bind_exprs(args, resolver, scope, context, production)?,
420        filter: filter
421            .as_deref()
422            .map(|filter| {
423                bind_rule_expr_with_scope(filter, resolver, scope, context, production)
424                    .and_then(|value| production.boxed(value))
425            })
426            .transpose()?,
427        spec: production.boxed(bind_window_spec(
428            spec, resolver, scope, context, production,
429        )?)?,
430    })
431}
432
433fn bind_rule_case_expression(
434    expr: &Expr,
435    resolver: &mut dyn VariableResolver,
436    scope: &RuleBindingScope,
437    context: &RuleBindingContext<'_>,
438    production: &SyntaxProduction<'_>,
439) -> Result<Expr, SQLError> {
440    let Expr::Case {
441        base,
442        when,
443        else_branch,
444    } = expr
445    else {
446        unreachable!("CASE binder received a non-CASE expression")
447    };
448    Ok(Expr::Case {
449        base: base
450            .as_deref()
451            .map(|expr| {
452                bind_rule_expr_with_scope(expr, resolver, scope, context, production)
453                    .and_then(|value| production.boxed(value))
454            })
455            .transpose()?,
456        when: when
457            .iter()
458            .map(|(condition, result)| {
459                Ok((
460                    bind_rule_expr_with_scope(condition, resolver, scope, context, production)?,
461                    bind_rule_expr_with_scope(result, resolver, scope, context, production)?,
462                ))
463            })
464            .collect_syntax(production)?,
465        else_branch: else_branch
466            .as_deref()
467            .map(|expr| {
468                bind_rule_expr_with_scope(expr, resolver, scope, context, production)
469                    .and_then(|value| production.boxed(value))
470            })
471            .transpose()?,
472    })
473}
474
475fn bind_rule_statement_body(
476    statement: &Statement,
477    resolver: &mut dyn VariableResolver,
478    inherited: &RuleBindingScope,
479    context: &RuleBindingContext<'_>,
480    production: &SyntaxProduction<'_>,
481) -> Result<Statement, SQLError> {
482    Ok(match statement {
483        Statement::Select(select) => Statement::Select(production.boxed(
484            bind_select_with_scope(select, resolver, inherited, context, production)?,
485        )?),
486        Statement::Insert(insert) => Statement::Insert(bind_insert(
487            insert, resolver, inherited, context, production,
488        )?),
489        Statement::Update(update) => Statement::Update(bind_update(
490            update, resolver, inherited, context, production,
491        )?),
492        Statement::Delete(delete) => {
493            let with = bind_ctes(&delete.with, resolver, inherited, context, production)?;
494            let context = context.with_ctes(&delete.with)?;
495            let mut target_scope = inherited.copy(&context.control())?;
496            target_scope.insert_qualifier(&delete.target_qualifier, &context.control())?;
497            let using = delete
498                .using
499                .as_ref()
500                .map(|source| bind_from(source, resolver, &target_scope, &context, production))
501                .transpose()?;
502            let mut expression_scope = target_scope;
503            if let Some(source) = &delete.using {
504                collect_visible_scope(source, &context, &mut expression_scope)?;
505            }
506            let predicate = bind_optional_expr(
507                delete.r#where.as_ref(),
508                resolver,
509                &expression_scope,
510                &context,
511                production,
512            )?;
513            Statement::Delete(crate::ast::DeleteStmt {
514                table: production.copy(&delete.table)?,
515                target_relation_bound: delete.target_relation_bound,
516                target_qualifier: production.copy(&delete.target_qualifier)?,
517                target_alias: production.copy(&delete.target_alias)?,
518                include_descendants: delete.include_descendants,
519                with,
520                using,
521                r#where: predicate,
522                returning: Vec::new(),
523                returning_aliases: production.copy(&delete.returning_aliases)?,
524            })
525        }
526        Statement::Notify { .. } => production.copy(statement)?,
527        _ if production.control().budget().is_none() => return bind_statement(statement, resolver),
528        _ => {
529            return Err(SQLError::Internal(
530                "stored rule action has an invalid statement kind".into(),
531            ))
532        }
533    })
534}
535
536fn bind_assignment_targets(
537    targets: &crate::ast::AssignmentTargets,
538    resolver: &mut dyn VariableResolver,
539    scope: &RuleBindingScope,
540    context: &RuleBindingContext<'_>,
541    production: &SyntaxProduction<'_>,
542) -> Result<crate::ast::AssignmentTargets, SQLError> {
543    use crate::ast::{AssignmentTargets, MultipleAssignmentTargets};
544    Ok(match targets {
545        AssignmentTargets::Single(target) => AssignmentTargets::Single(bind_assignment_target(
546            target, resolver, scope, context, production,
547        )?),
548        AssignmentTargets::Multiple(group) => {
549            AssignmentTargets::Multiple(MultipleAssignmentTargets {
550                targets: group
551                    .targets
552                    .iter()
553                    .map(|target| {
554                        bind_assignment_target(target, resolver, scope, context, production)
555                    })
556                    .collect_syntax(production)?,
557                source_positions: production.copy(&group.source_positions)?,
558                source_width: group.source_width,
559            })
560        }
561    })
562}
563
564fn bind_assignment_target(
565    target: &crate::ast::AssignmentTarget,
566    resolver: &mut dyn VariableResolver,
567    scope: &RuleBindingScope,
568    context: &RuleBindingContext<'_>,
569    production: &SyntaxProduction<'_>,
570) -> Result<crate::ast::AssignmentTarget, SQLError> {
571    use crate::ast::{AssignmentStep, AssignmentTarget};
572    Ok(AssignmentTarget {
573        column: production.copy(&target.column)?,
574        indirection: target
575            .indirection
576            .iter()
577            .map(|step| {
578                Ok(match step {
579                    AssignmentStep::Field(name) => AssignmentStep::Field(production.copy(name)?),
580                    AssignmentStep::Index(expr) => AssignmentStep::Index(production.boxed(
581                        bind_rule_expr_with_scope(expr, resolver, scope, context, production)?,
582                    )?),
583                    AssignmentStep::Slice { lower, upper } => AssignmentStep::Slice {
584                        lower: lower
585                            .as_deref()
586                            .map(|expr| {
587                                production.boxed(bind_rule_expr_with_scope(
588                                    expr, resolver, scope, context, production,
589                                )?)
590                            })
591                            .transpose()?,
592                        upper: upper
593                            .as_deref()
594                            .map(|expr| {
595                                production.boxed(bind_rule_expr_with_scope(
596                                    expr, resolver, scope, context, production,
597                                )?)
598                            })
599                            .transpose()?,
600                    },
601                })
602            })
603            .collect_syntax(production)?,
604    })
605}
606
607fn bind_update(
608    update: &UpdateStmt,
609    resolver: &mut dyn VariableResolver,
610    inherited: &RuleBindingScope,
611    context: &RuleBindingContext<'_>,
612    production: &SyntaxProduction<'_>,
613) -> Result<UpdateStmt, SQLError> {
614    let with = bind_ctes(&update.with, resolver, inherited, context, production)?;
615    let context = context.with_ctes(&update.with)?;
616    let mut target_scope = inherited.copy(&context.control())?;
617    target_scope.insert_qualifier(&update.target_qualifier, &context.control())?;
618    let from = update
619        .from
620        .as_ref()
621        .map(|source| bind_from(source, resolver, &target_scope, &context, production))
622        .transpose()?;
623    let mut expression_scope = target_scope;
624    if let Some(source) = &update.from {
625        collect_visible_scope(source, &context, &mut expression_scope)?;
626    }
627    let assignments = update
628        .assignments
629        .iter()
630        .map(|(column, expr)| {
631            Ok((
632                bind_assignment_targets(column, resolver, &expression_scope, &context, production)?,
633                bind_rule_expr_with_scope(expr, resolver, &expression_scope, &context, production)?,
634            ))
635        })
636        .collect_syntax(production)?;
637    let predicate = bind_optional_expr(
638        update.r#where.as_ref(),
639        resolver,
640        &expression_scope,
641        &context,
642        production,
643    )?;
644    Ok(UpdateStmt {
645        table: production.copy(&update.table)?,
646        target_relation_bound: update.target_relation_bound,
647        target_qualifier: production.copy(&update.target_qualifier)?,
648        target_alias: production.copy(&update.target_alias)?,
649        include_descendants: update.include_descendants,
650        with,
651        from,
652        assignments,
653        r#where: predicate,
654        returning: Vec::new(),
655        returning_aliases: production.copy(&update.returning_aliases)?,
656    })
657}
658
659fn bind_frame_bound(
660    bound: &FrameBound,
661    resolver: &mut dyn VariableResolver,
662    scope: &RuleBindingScope,
663    context: &RuleBindingContext<'_>,
664    production: &SyntaxProduction<'_>,
665) -> Result<FrameBound, SQLError> {
666    Ok(match bound {
667        FrameBound::Preceding(expr) => FrameBound::Preceding(production.boxed(
668            bind_rule_expr_with_scope(expr, resolver, scope, context, production)?,
669        )?),
670        FrameBound::Following(expr) => FrameBound::Following(production.boxed(
671            bind_rule_expr_with_scope(expr, resolver, scope, context, production)?,
672        )?),
673        _ => production.copy(bound)?,
674    })
675}
676
677fn bind_projections(
678    projections: &[Projection],
679    resolver: &mut dyn VariableResolver,
680    scope: &RuleBindingScope,
681    context: &RuleBindingContext<'_>,
682    production: &SyntaxProduction<'_>,
683) -> Result<Vec<Projection>, SQLError> {
684    let mut bound = production.vector(projections.len())?;
685    for projection in projections {
686        if let Some(expressions) =
687            expand_qualified_star(&projection.expr, resolver, scope, production)?
688        {
689            for expr in production.elements(expressions) {
690                bound.push(Projection {
691                    expr,
692                    alias: production.copy(&projection.alias)?,
693                })?;
694            }
695        } else {
696            bound.push(Projection {
697                expr: bind_rule_expr_with_scope(
698                    &projection.expr,
699                    resolver,
700                    scope,
701                    context,
702                    production,
703                )?,
704                alias: production.copy(&projection.alias)?,
705            })?;
706        }
707    }
708    bound.finish()
709}
710
711fn bind_expanding_exprs(
712    expressions: &[Expr],
713    resolver: &mut dyn VariableResolver,
714    scope: &RuleBindingScope,
715    context: &RuleBindingContext<'_>,
716    production: &SyntaxProduction<'_>,
717) -> Result<Vec<Expr>, SQLError> {
718    let mut bound = production.vector(expressions.len())?;
719    for expression in expressions {
720        if let Some(expressions) = expand_qualified_star(expression, resolver, scope, production)? {
721            for expression in production.elements(expressions) {
722                bound.push(expression)?;
723            }
724        } else {
725            bound.push(bind_rule_expr_with_scope(
726                expression, resolver, scope, context, production,
727            )?)?;
728        }
729    }
730    bound.finish()
731}
732
733fn expand_qualified_star(
734    expression: &Expr,
735    resolver: &mut dyn VariableResolver,
736    scope: &RuleBindingScope,
737    production: &SyntaxProduction<'_>,
738) -> Result<Option<Produced<Vec<Expr>>>, SQLError> {
739    let Expr::QualifiedStar(qualifier) = expression else {
740        return Ok(None);
741    };
742    if scope.qualifier_is_shadowed(qualifier) {
743        return Ok(None);
744    }
745    resolver.expand_with_control(qualifier, &production.control())
746}
747
748fn bind_exprs(
749    expressions: &[Expr],
750    resolver: &mut dyn VariableResolver,
751    scope: &RuleBindingScope,
752    context: &RuleBindingContext<'_>,
753    production: &SyntaxProduction<'_>,
754) -> Result<Vec<Expr>, SQLError> {
755    expressions
756        .iter()
757        .map(|expr| bind_rule_expr_with_scope(expr, resolver, scope, context, production))
758        .collect_syntax(production)
759}
760
761fn bind_optional_expr(
762    expression: Option<&Expr>,
763    resolver: &mut dyn VariableResolver,
764    scope: &RuleBindingScope,
765    context: &RuleBindingContext<'_>,
766    production: &SyntaxProduction<'_>,
767) -> Result<Option<Expr>, SQLError> {
768    expression
769        .map(|expr| bind_rule_expr_with_scope(expr, resolver, scope, context, production))
770        .transpose()
771}
772
773fn bind_orders(
774    orders: &[OrderBy],
775    resolver: &mut dyn VariableResolver,
776    scope: &RuleBindingScope,
777    context: &RuleBindingContext<'_>,
778    production: &SyntaxProduction<'_>,
779) -> Result<Vec<OrderBy>, SQLError> {
780    orders
781        .iter()
782        .map(|order| {
783            Ok(OrderBy {
784                expr: bind_rule_expr_with_scope(&order.expr, resolver, scope, context, production)?,
785                descending: order.descending,
786                nulls: order.nulls,
787            })
788        })
789        .collect_syntax(production)
790}
791
792pub fn invalid_rule_relation_reference(qualifier: &str) -> SQLError {
793    SQLError::Diagnostic {
794        sqlstate: "42P01".into(),
795        message: format!("invalid reference to FROM-clause entry for table \"{qualifier}\""),
796        detail: Some(format!(
797            "There is an entry for table \"{qualifier}\", but it cannot be referenced from this part of the query."
798        )),
799        hint: None,
800    }
801}
802
803fn bind_reference_expression(
804    expr: &Expr,
805    resolver: &mut dyn VariableResolver,
806    scope: &RuleBindingScope,
807    production: &SyntaxProduction<'_>,
808) -> Result<Expr, SQLError> {
809    Ok(match expr {
810        Expr::Column(name) => {
811            if scope.qualifier_is_shadowed(name) || scope.column_is_shadowed(name) {
812                production.copy(expr)?
813            } else {
814                rewrite_reference(expr, RewriteReference::Name(name), resolver, production)?
815            }
816        }
817        Expr::QualifiedColumn { qualifier, column } => {
818            if scope.qualifier_is_shadowed(qualifier) {
819                production.copy(expr)?
820            } else {
821                rewrite_reference(
822                    expr,
823                    RewriteReference::Qualified { qualifier, column },
824                    resolver,
825                    production,
826                )?
827            }
828        }
829        Expr::Param(index) => rewrite_reference(
830            expr,
831            RewriteReference::Parameter(*index),
832            resolver,
833            production,
834        )?,
835        Expr::InternalColumn(column) => rewrite_reference(
836            expr,
837            RewriteReference::Internal(*column),
838            resolver,
839            production,
840        )?,
841        Expr::QualifiedStar(qualifier) => {
842            if scope.qualifier_is_shadowed(qualifier) {
843                production.copy(expr)?
844            } else {
845                rewrite_reference(
846                    expr,
847                    RewriteReference::WholeRow(qualifier),
848                    resolver,
849                    production,
850                )?
851            }
852        }
853        _ => unreachable!("reference binder received a different expression"),
854    })
855}
856
857fn bind_query_expression(
858    expr: &Expr,
859    resolver: &mut dyn VariableResolver,
860    scope: &RuleBindingScope,
861    context: &RuleBindingContext<'_>,
862    production: &SyntaxProduction<'_>,
863) -> Result<Expr, SQLError> {
864    Ok(match expr {
865        Expr::ScalarSubquery(body) => Expr::ScalarSubquery(production.boxed(
866            bind_select_with_scope(body, resolver, scope, context, production)?,
867        )?),
868        Expr::Exists { body, negated } => Expr::Exists {
869            body: production.boxed(bind_select_with_scope(
870                body, resolver, scope, context, production,
871            )?)?,
872            negated: *negated,
873        },
874        Expr::InSubquery {
875            expr,
876            body,
877            negated,
878        } => Expr::InSubquery {
879            expr: production.boxed(bind_rule_expr_with_scope(
880                expr, resolver, scope, context, production,
881            )?)?,
882            body: production.boxed(bind_select_with_scope(
883                body, resolver, scope, context, production,
884            )?)?,
885            negated: *negated,
886        },
887        _ => unreachable!("query binder received a different expression"),
888    })
889}