Skip to main content

uqa_sql/plpgsql/
binding.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Variable binding across expressions, queries, and statements.
8
9use super::{Expr, FromClause, MergeWhen, Projection, Result, SelectStmt, Statement, Value, CTE};
10use crate::ast::InternalColumnRef;
11mod rewrite;
12pub use rewrite::RewriteReference;
13
14/// Runtime datum value together with the concrete SQL type declared by PL/pgSQL. The type is optional for composite fields and pseudo-types whose runtime carrier already identifies their category.
15#[derive(Debug, Clone)]
16pub struct ResolvedVariable {
17    pub value: Value,
18    pub declared_type: Option<String>,
19    /// Selected implicit collation of a declared variable or event field. Absence preserves the declared type's default.
20    pub collation_oid: Option<u32>,
21}
22
23impl ResolvedVariable {
24    #[must_use]
25    pub fn untyped(value: Value) -> Self {
26        Self {
27            value,
28            declared_type: None,
29            collation_oid: None,
30        }
31    }
32
33    pub(crate) fn into_expression(self) -> Expr {
34        match self.declared_type {
35            Some(ty) => Expr::TypedLiteral {
36                collation_oid: self.collation_oid,
37                composite_source: None,
38                value: self.value,
39                ty,
40            },
41            None => Expr::Literal(self.value),
42        }
43    }
44}
45
46/// Resolves routine variables while a compiled expression / statement
47/// is being specialized for one execution.
48pub trait VariableResolver {
49    /// Native expression producers override this operation and admit the selected replacement before construction. External callbacks retain their own construction policy; this default copies their completed result into the caller's syntax owner.
50    fn rewrite_with_control(
51        &mut self,
52        reference: RewriteReference<'_>,
53        control: &uqa_core::memory::ProductionControl<'_>,
54    ) -> Result<Option<uqa_core::memory::Produced<Expr>>> {
55        control.check()?;
56        reference
57            .resolve(self)?
58            .map(|value| {
59                if control.budget().is_none() {
60                    Ok(control.finish(value, None)?)
61                } else {
62                    crate::plan::copy::copy_syntax_with_control(&value, control)
63                }
64            })
65            .transpose()
66    }
67
68    /// List expansion has a separate constructor because scalar whole-row references remain one expression.
69    fn expand_with_control(
70        &mut self,
71        qualifier: &str,
72        control: &uqa_core::memory::ProductionControl<'_>,
73    ) -> Result<Option<uqa_core::memory::Produced<Vec<Expr>>>> {
74        control.check()?;
75        self.rewrite_qualified_star(qualifier)?
76            .map(|value| {
77                if control.budget().is_none() {
78                    Ok(control.finish(value, None)?)
79                } else {
80                    crate::plan::copy::copy_syntax_with_control(&value, control)
81                }
82            })
83            .transpose()
84    }
85
86    /// External resolvers may retain their own callback allocation policy. Native activations override this producer and admit values and type descriptors before copying them.
87    fn resolve_input_with_control(
88        &mut self,
89        reference: &super::PLpgSQLVariableReference,
90        control: &uqa_core::memory::ProductionControl<'_>,
91    ) -> Result<Option<uqa_core::memory::Produced<super::PLpgSQLInput>>> {
92        control.check()?;
93        let value = match reference {
94            super::PLpgSQLVariableReference::Name(name) => self.resolve_name(name)?,
95            super::PLpgSQLVariableReference::Qualified { qualifier, column } => {
96                self.resolve_qualified(qualifier, column)?
97            }
98            super::PLpgSQLVariableReference::Parameter(index) => self.resolve_param(*index)?,
99        };
100        value
101            .map(|value| {
102                let ty = value
103                    .declared_type
104                    .as_deref()
105                    .and_then(|name| self.parameter_type(name));
106                super::PLpgSQLInput::from_parts(
107                    control.copy_value(&value.value)?,
108                    ty.as_ref()
109                        .map(|ty| ty.clone_with_control(control))
110                        .transpose()?,
111                    value.collation_oid,
112                    control,
113                )
114            })
115            .transpose()
116    }
117
118    /// Read a prepared variable with its selected concrete type. Existing resolvers
119    /// retain textual resolution; typed activation records can preserve their
120    /// descriptor without spelling and resolving it again.
121    fn resolve_parameter(
122        &mut self,
123        reference: &super::PLpgSQLVariableReference,
124    ) -> Result<Option<crate::SQLParam>> {
125        super::parameters::resolve_parameter(reference, self)
126    }
127
128    /// Concrete parameter metadata for a declared datum; catalog implementations
129    /// preserve user-type identity instead of inferring from a carrier value.
130    fn parameter_type(&self, name: &str) -> Option<crate::ColumnType> {
131        crate::ColumnType::from_sql_name(name).ok()
132    }
133
134    /// Current value of an unqualified name. `Ok(None)` leaves the
135    /// column reference for the engine to resolve.
136    fn resolve_name(&mut self, name: &str) -> Result<Option<ResolvedVariable>>;
137    /// Current value of `qualifier.column` (record field access).
138    fn resolve_qualified(
139        &mut self,
140        qualifier: &str,
141        column: &str,
142    ) -> Result<Option<ResolvedVariable>>;
143    /// Value of a positional `$n` reference (function arguments).
144    fn resolve_param(&mut self, index: usize) -> Result<Option<ResolvedVariable>>;
145
146    /// Optional expression-level rewrite hook. The default preserves the variable-substitution behavior used by PL/pgSQL while allowing catalog lifecycle code to rewrite a reference without fabricating a literal value.
147    fn rewrite_name(&mut self, name: &str) -> Result<Option<Expr>> {
148        Ok(self
149            .resolve_name(name)?
150            .map(ResolvedVariable::into_expression))
151    }
152
153    /// Expression-level counterpart of [`Self::resolve_qualified`].
154    fn rewrite_qualified(&mut self, qualifier: &str, column: &str) -> Result<Option<Expr>> {
155        Ok(self
156            .resolve_qualified(qualifier, column)?
157            .map(ResolvedVariable::into_expression))
158    }
159
160    /// Expand `qualifier.*` when the containing SQL construct treats it as a
161    /// list item. Scalar binding deliberately does not call this hook because
162    /// `PostgreSQL` treats the same syntax as a composite whole-row value in
163    /// scalar contexts.
164    fn rewrite_qualified_star(&mut self, _qualifier: &str) -> Result<Option<Vec<Expr>>> {
165        Ok(None)
166    }
167
168    /// Resolve `qualifier.*` when it appears in a scalar context and therefore denotes one composite whole-row value rather than a projection list.
169    fn rewrite_qualified_whole_row(&mut self, _qualifier: &str) -> Result<Option<Expr>> {
170        Ok(None)
171    }
172
173    /// Expression-level counterpart of [`Self::resolve_param`].
174    fn rewrite_param(&mut self, index: usize) -> Result<Option<Expr>> {
175        Ok(self
176            .resolve_param(index)?
177            .map(ResolvedVariable::into_expression))
178    }
179
180    /// Observe or replace an executor-only structural column reference. SQL
181    /// variable resolvers normally leave these untouched.
182    fn rewrite_internal(&mut self, _column: InternalColumnRef) -> Result<Option<Expr>> {
183        Ok(None)
184    }
185}
186
187/// Rewrite an expression, substituting resolvable variable references
188/// with literals. References the resolver declines stay untouched.
189#[expect(
190    clippy::too_many_lines,
191    reason = "PL/pgSQL lowering preserves parser order and datum validation"
192)]
193pub fn bind_expr(expr: &Expr, r: &mut dyn VariableResolver) -> Result<Expr> {
194    Ok(match expr {
195        Expr::Column(name) => match r.rewrite_name(name)? {
196            Some(value) => value,
197            None => expr.clone(),
198        },
199        Expr::QualifiedColumn {
200            qualifier, column, ..
201        } => match r.rewrite_qualified(qualifier, column)? {
202            Some(value) => value,
203            None => expr.clone(),
204        },
205        Expr::Param(index) => match r.rewrite_param(*index)? {
206            Some(value) => value,
207            None => expr.clone(),
208        },
209        Expr::InternalColumn(column) => match r.rewrite_internal(*column)? {
210            Some(value) => value,
211            None => expr.clone(),
212        },
213        Expr::QualifiedStar(qualifier) => r
214            .rewrite_qualified_whole_row(qualifier)?
215            .unwrap_or_else(|| expr.clone()),
216        Expr::Default
217        | Expr::Literal(_)
218        | Expr::TypedLiteral { .. }
219        | Expr::RetainedLiteral(_)
220        | Expr::Star => expr.clone(),
221        Expr::Func {
222            order_syntax,
223            name,
224            binding,
225            args,
226            distinct,
227            order_by,
228            filter,
229        } => Expr::Func {
230            order_syntax: *order_syntax,
231            name: name.clone(),
232            binding: binding.clone(),
233            args: bind_exprs(args, r)?,
234            distinct: *distinct,
235            order_by: bind_order_by(order_by, r)?,
236            filter: match filter {
237                Some(f) => Some(Box::new(bind_expr(f, r)?)),
238                None => None,
239            },
240        },
241        Expr::Array(items) => Expr::Array(bind_exprs(items, r)?),
242        Expr::Row(items) => Expr::Row(bind_exprs(items, r)?),
243        Expr::CompositeRow { items, binding } => Expr::CompositeRow {
244            items: bind_exprs(items, r)?,
245            binding: binding.clone(),
246        },
247        Expr::Binary { op, lhs, rhs } => Expr::Binary {
248            op: *op,
249            lhs: Box::new(bind_expr(lhs, r)?),
250            rhs: Box::new(bind_expr(rhs, r)?),
251        },
252        Expr::UnaryMinus(inner) => Expr::UnaryMinus(Box::new(bind_expr(inner, r)?)),
253        Expr::Not(inner) => Expr::Not(Box::new(bind_expr(inner, r)?)),
254        Expr::And(items) => Expr::And(bind_exprs(items, r)?),
255        Expr::Or(items) => Expr::Or(bind_exprs(items, r)?),
256        Expr::IsNull { expr, negated } => Expr::IsNull {
257            expr: Box::new(bind_expr(expr, r)?),
258            negated: *negated,
259        },
260        Expr::Between { expr, low, high } => Expr::Between {
261            expr: Box::new(bind_expr(expr, r)?),
262            low: Box::new(bind_expr(low, r)?),
263            high: Box::new(bind_expr(high, r)?),
264        },
265        Expr::InList {
266            expr,
267            list,
268            negated,
269        } => Expr::InList {
270            expr: Box::new(bind_expr(expr, r)?),
271            list: bind_exprs(list, r)?,
272            negated: *negated,
273        },
274        Expr::WindowCall {
275            name,
276            args,
277            spec,
278            filter,
279            modifiers,
280        } => Expr::WindowCall {
281            modifiers: *modifiers,
282            name: name.clone(),
283            args: bind_exprs(args, r)?,
284            spec: Box::new(bind_window_spec(spec, r)?),
285            filter: match filter {
286                Some(f) => Some(Box::new(bind_expr(f, r)?)),
287                None => None,
288            },
289        },
290        Expr::Case {
291            base,
292            when,
293            else_branch,
294        } => Expr::Case {
295            base: match base {
296                Some(b) => Some(Box::new(bind_expr(b, r)?)),
297                None => None,
298            },
299            when: when
300                .iter()
301                .map(|(c, v)| Ok((bind_expr(c, r)?, bind_expr(v, r)?)))
302                .collect::<Result<Vec<_>>>()?,
303            else_branch: match else_branch {
304                Some(e) => Some(Box::new(bind_expr(e, r)?)),
305                None => None,
306            },
307        },
308        Expr::Cast { expr, ty, implicit } => Expr::Cast {
309            implicit: *implicit,
310            expr: Box::new(bind_expr(expr, r)?),
311            ty: ty.clone(),
312        },
313        Expr::ScalarSubquery(body) => Expr::ScalarSubquery(Box::new(bind_select(body, r)?)),
314        Expr::Exists { body, negated } => Expr::Exists {
315            body: Box::new(bind_select(body, r)?),
316            negated: *negated,
317        },
318        Expr::InSubquery {
319            expr,
320            body,
321            negated,
322        } => Expr::InSubquery {
323            expr: Box::new(bind_expr(expr, r)?),
324            body: Box::new(bind_select(body, r)?),
325            negated: *negated,
326        },
327    })
328}
329
330/// A frame offset may name a PL/pgSQL variable, which becomes a parameter of the query.
331fn bind_frame_bound(
332    bound: &crate::ast::FrameBound,
333    r: &mut dyn VariableResolver,
334) -> Result<crate::ast::FrameBound> {
335    use crate::ast::FrameBound;
336    Ok(match bound {
337        FrameBound::Preceding(offset) => FrameBound::Preceding(Box::new(bind_expr(offset, r)?)),
338        FrameBound::Following(offset) => FrameBound::Following(Box::new(bind_expr(offset, r)?)),
339        FrameBound::UnboundedPreceding => FrameBound::UnboundedPreceding,
340        FrameBound::UnboundedFollowing => FrameBound::UnboundedFollowing,
341        FrameBound::CurrentRow => FrameBound::CurrentRow,
342    })
343}
344
345pub(super) fn bind_exprs(exprs: &[Expr], r: &mut dyn VariableResolver) -> Result<Vec<Expr>> {
346    exprs.iter().map(|e| bind_expr(e, r)).collect()
347}
348
349pub(super) fn bind_opt_expr(
350    expr: Option<&Expr>,
351    r: &mut dyn VariableResolver,
352) -> Result<Option<Expr>> {
353    match expr {
354        Some(e) => Ok(Some(bind_expr(e, r)?)),
355        None => Ok(None),
356    }
357}
358
359pub(super) fn bind_order_by(
360    items: &[crate::ast::OrderBy],
361    r: &mut dyn VariableResolver,
362) -> Result<Vec<crate::ast::OrderBy>> {
363    items
364        .iter()
365        .map(|o| {
366            Ok(crate::ast::OrderBy {
367                expr: bind_expr(&o.expr, r)?,
368                descending: o.descending,
369                nulls: o.nulls,
370            })
371        })
372        .collect()
373}
374
375pub(super) fn bind_projections(
376    items: &[Projection],
377    r: &mut dyn VariableResolver,
378) -> Result<Vec<Projection>> {
379    items
380        .iter()
381        .map(|p| {
382            Ok(Projection {
383                expr: bind_expr(&p.expr, r)?,
384                alias: p.alias.clone(),
385            })
386        })
387        .collect()
388}
389
390pub(super) fn bind_assignments(
391    items: &[(crate::ast::AssignmentTargets, Expr)],
392    r: &mut dyn VariableResolver,
393) -> Result<Vec<(crate::ast::AssignmentTargets, Expr)>> {
394    items
395        .iter()
396        .map(|(target, expression)| {
397            Ok((
398                {
399                    let mut group = target.clone();
400                    for target in group.targets_mut() {
401                        *target = bind_assignment_target(target, r)?;
402                    }
403                    group
404                },
405                bind_expr(expression, r)?,
406            ))
407        })
408        .collect()
409}
410
411fn bind_assignment_target(
412    target: &crate::ast::AssignmentTarget,
413    resolver: &mut dyn VariableResolver,
414) -> Result<crate::ast::AssignmentTarget> {
415    let mut target = target.clone();
416    for expression in target.expressions_mut() {
417        *expression = bind_expr(expression, resolver)?;
418    }
419    Ok(target)
420}
421
422pub(super) fn bind_ctes(items: &[CTE], r: &mut dyn VariableResolver) -> Result<Vec<CTE>> {
423    items
424        .iter()
425        .map(|cte| {
426            Ok(CTE {
427                name: cte.name.clone(),
428                columns: cte.columns.clone(),
429                recursive: cte.recursive,
430                materialization: cte.materialization,
431                search: cte.search.clone(),
432                cycle: cte
433                    .cycle
434                    .as_ref()
435                    .map(|cycle| -> Result<crate::ast::CteCycleClause> {
436                        Ok(crate::ast::CteCycleClause {
437                            columns: cycle.columns.clone(),
438                            mark_column: cycle.mark_column.clone(),
439                            mark_value: bind_expr(&cycle.mark_value, r)?,
440                            mark_default: bind_expr(&cycle.mark_default, r)?,
441                            path_column: cycle.path_column.clone(),
442                        })
443                    })
444                    .transpose()?,
445                body: crate::ast::CteBody::try_from(bind_statement(
446                    &cte.body.clone().into_statement(),
447                    r,
448                )?)?,
449            })
450        })
451        .collect()
452}
453
454pub(super) fn bind_rows(
455    rows: &[Vec<Expr>],
456    r: &mut dyn VariableResolver,
457) -> Result<Vec<Vec<Expr>>> {
458    rows.iter().map(|row| bind_exprs(row, r)).collect()
459}
460
461fn bind_window_spec(
462    spec: &crate::ast::WindowSpec,
463    r: &mut dyn VariableResolver,
464) -> Result<crate::ast::WindowSpec> {
465    Ok(crate::ast::WindowSpec {
466        definition: spec.definition,
467        raw_definition: None,
468        reference: spec.reference.clone(),
469        partition_by: bind_exprs(&spec.partition_by, r)?,
470        order_by: bind_order_by(&spec.order_by, r)?,
471        frame: spec
472            .frame
473            .as_ref()
474            .map(|frame| -> Result<crate::ast::WindowFrame> {
475                Ok(crate::ast::WindowFrame {
476                    start: bind_frame_bound(&frame.start, r)?,
477                    end: bind_frame_bound(&frame.end, r)?,
478                    ..frame.clone()
479                })
480            })
481            .transpose()?,
482    })
483}
484
485/// Rewrite a `SELECT` body, substituting resolvable variables.
486pub fn bind_select(stmt: &SelectStmt, r: &mut dyn VariableResolver) -> Result<SelectStmt> {
487    Ok(SelectStmt {
488        windows: stmt
489            .windows
490            .iter()
491            .map(|window| {
492                Ok(crate::ast::WindowDefinition {
493                    name: window.name.clone(),
494                    inherited: window.inherited,
495                    spec: bind_window_spec(&window.spec, r)?,
496                })
497            })
498            .collect::<Result<Vec<_>>>()?,
499        projections: bind_projections(&stmt.projections, r)?,
500        values: bind_rows(&stmt.values, r)?,
501        from: match stmt.from.as_ref() {
502            Some(f) => Some(bind_from(f, r)?),
503            None => None,
504        },
505        r#where: bind_opt_expr(stmt.r#where.as_ref(), r)?,
506        group_by: bind_exprs(&stmt.group_by, r)?,
507        grouping_sets: stmt
508            .grouping_sets
509            .iter()
510            .map(|set| bind_exprs(set, r))
511            .collect::<Result<Vec<_>>>()?,
512        group_distinct: stmt.group_distinct,
513        having: bind_opt_expr(stmt.having.as_ref(), r)?,
514        order_by: bind_order_by(&stmt.order_by, r)?,
515        limit: bind_opt_expr(stmt.limit.as_ref(), r)?,
516        with_ties: stmt.with_ties,
517        offset: bind_opt_expr(stmt.offset.as_ref(), r)?,
518        with: bind_ctes(&stmt.with, r)?,
519        set_op: match stmt.set_op.as_ref() {
520            Some(op) => Some(Box::new(crate::ast::SetOp {
521                kind: op.kind,
522                all: op.all,
523                left: op
524                    .left
525                    .as_ref()
526                    .map(|left| bind_select(left, r).map(Box::new))
527                    .transpose()?,
528                right: bind_select(&op.right, r)?,
529                combined_order_by: bind_order_by(&op.combined_order_by, r)?,
530                combined_limit: bind_opt_expr(op.combined_limit.as_ref(), r)?,
531                combined_with_ties: op.combined_with_ties,
532                combined_offset: bind_opt_expr(op.combined_offset.as_ref(), r)?,
533            })),
534            None => None,
535        },
536        distinct: stmt.distinct,
537        distinct_on: bind_exprs(&stmt.distinct_on, r)?,
538        locking: stmt.locking.clone(),
539    })
540}
541
542pub(super) fn bind_from(from: &FromClause, r: &mut dyn VariableResolver) -> Result<FromClause> {
543    Ok(match from {
544        crate::ast::FromClause::RetainedRows(_) => from.clone(),
545        FromClause::Table { .. } => from.clone(),
546        FromClause::Join {
547            comma,
548            left,
549            right,
550            kind,
551            on,
552            using,
553            natural,
554            alias,
555            column_aliases,
556            lateral,
557        } => FromClause::Join {
558            comma: *comma,
559            left: Box::new(bind_from(left, r)?),
560            right: Box::new(bind_from(right, r)?),
561            kind: *kind,
562            on: bind_opt_expr(on.as_ref(), r)?,
563            using: using.clone(),
564            natural: *natural,
565            alias: alias.clone(),
566            column_aliases: column_aliases.clone(),
567            lateral: *lateral,
568        },
569        FromClause::Values {
570            lateral,
571            rows,
572            alias,
573            column_aliases,
574            internal_relation,
575            internal_column_types,
576            internal_column_collations,
577        } => FromClause::Values {
578            lateral: *lateral,
579            rows: bind_rows(rows, r)?,
580            alias: alias.clone(),
581            column_aliases: column_aliases.clone(),
582            internal_relation: *internal_relation,
583            internal_column_types: internal_column_types.clone(),
584            internal_column_collations: internal_column_collations.clone(),
585        },
586        FromClause::Function {
587            name,
588            binding,
589            output_name,
590            relations,
591            args,
592            alias,
593            column_aliases,
594            ordinality,
595            column_types,
596        } => FromClause::Function {
597            name: name.clone(),
598            binding: binding.clone(),
599            output_name: output_name.clone(),
600            relations: relations.clone(),
601            args: bind_exprs(args, r)?,
602            alias: alias.clone(),
603            column_aliases: column_aliases.clone(),
604            ordinality: *ordinality,
605            column_types: column_types.clone(),
606        },
607        FromClause::FunctionGroup {
608            functions,
609            alias,
610            column_aliases,
611            ordinality,
612        } => FromClause::FunctionGroup {
613            functions: functions
614                .iter()
615                .map(|function| {
616                    Ok(crate::ast::TableFunction {
617                        name: function.name.clone(),
618                        binding: function.binding.clone(),
619                        output_name: function.output_name.clone(),
620                        relations: function.relations.clone(),
621                        args: bind_exprs(&function.args, r)?,
622                        column_aliases: function.column_aliases.clone(),
623                        column_types: function.column_types.clone(),
624                    })
625                })
626                .collect::<Result<Vec<_>>>()?,
627            alias: alias.clone(),
628            column_aliases: column_aliases.clone(),
629            ordinality: *ordinality,
630        },
631        FromClause::Subquery {
632            lateral,
633            body,
634            alias,
635            column_aliases,
636        } => FromClause::Subquery {
637            lateral: *lateral,
638            body: Box::new(bind_select(body, r)?),
639            alias: alias.clone(),
640            column_aliases: column_aliases.clone(),
641        },
642    })
643}
644
645/// Rewrite a full statement, substituting resolvable variables in
646/// every expression position. Statements without expression payloads
647/// pass through unchanged.
648#[expect(
649    clippy::too_many_lines,
650    reason = "PL/pgSQL lowering preserves parser order and datum validation"
651)]
652pub fn bind_statement(stmt: &Statement, r: &mut dyn VariableResolver) -> Result<Statement> {
653    Ok(match stmt {
654        Statement::Select(body) => Statement::Select(Box::new(bind_select(body, r)?)),
655        Statement::Insert(insert) => {
656            let mut out = insert.clone();
657            out.columns = insert
658                .columns
659                .iter()
660                .map(|target| bind_assignment_target(target, r))
661                .collect::<Result<_>>()?;
662            out.with = bind_ctes(&insert.with, r)?;
663            out.rows = bind_rows(&insert.rows, r)?;
664            out.select_source = match insert.select_source.as_ref() {
665                Some(body) => Some(Box::new(bind_select(body, r)?)),
666                None => None,
667            };
668            out.on_conflict = match insert.on_conflict.as_ref() {
669                Some(oc) => Some(crate::ast::OnConflict {
670                    predicate: bind_opt_expr(oc.predicate.as_deref(), r)?.map(Box::new),
671                    constraint: oc.constraint.clone(),
672                    conflict_columns: oc.conflict_columns.clone(),
673                    expressions: oc
674                        .expressions
675                        .iter()
676                        .map(|expr| bind_expr(expr, r))
677                        .collect::<Result<Vec<_>>>()?,
678                    action: match &oc.action {
679                        crate::ast::OnConflictAction::Nothing => {
680                            crate::ast::OnConflictAction::Nothing
681                        }
682                        crate::ast::OnConflictAction::Update {
683                            assignments,
684                            r#where,
685                        } => crate::ast::OnConflictAction::Update {
686                            assignments: bind_assignments(assignments, r)?,
687                            r#where: bind_opt_expr(r#where.as_deref(), r)?.map(Box::new),
688                        },
689                    },
690                }),
691                None => None,
692            };
693            out.returning = bind_projections(&insert.returning, r)?;
694            Statement::Insert(out)
695        }
696        Statement::Update(update) => {
697            let mut out = update.clone();
698            out.assignments = bind_assignments(&update.assignments, r)?;
699            out.r#where = bind_opt_expr(update.r#where.as_ref(), r)?;
700            out.with = bind_ctes(&update.with, r)?;
701            out.from = match update.from.as_ref() {
702                Some(f) => Some(bind_from(f, r)?),
703                None => None,
704            };
705            out.returning = bind_projections(&update.returning, r)?;
706            Statement::Update(out)
707        }
708        Statement::Delete(delete) => {
709            let mut out = delete.clone();
710            out.r#where = bind_opt_expr(delete.r#where.as_ref(), r)?;
711            out.with = bind_ctes(&delete.with, r)?;
712            out.using = match delete.using.as_ref() {
713                Some(f) => Some(bind_from(f, r)?),
714                None => None,
715            };
716            out.returning = bind_projections(&delete.returning, r)?;
717            Statement::Delete(out)
718        }
719        Statement::Values { rows } => Statement::Values {
720            rows: bind_rows(rows, r)?,
721        },
722        Statement::CreateTableAs {
723            name,
724            if_not_exists,
725            column_names,
726            with_no_data,
727            select_into,
728            persistence,
729            on_commit,
730            body,
731        } => Statement::CreateTableAs {
732            name: name.clone(),
733            if_not_exists: *if_not_exists,
734            column_names: column_names.clone(),
735            with_no_data: *with_no_data,
736            select_into: *select_into,
737            persistence: *persistence,
738            on_commit: *on_commit,
739            body: Box::new(bind_select(body, r)?),
740        },
741        Statement::CreateMaterializedView {
742            name,
743            column_names,
744            if_not_exists,
745            with_no_data,
746            options,
747            body,
748        } => Statement::CreateMaterializedView {
749            name: name.clone(),
750            column_names: column_names.clone(),
751            if_not_exists: *if_not_exists,
752            with_no_data: *with_no_data,
753            options: options.clone(),
754            body: Box::new(bind_select(body, r)?),
755        },
756        Statement::Explain { options, body } => Statement::Explain {
757            options: options.clone(),
758            body: Box::new(bind_statement(body, r)?),
759        },
760        Statement::DeclareCursor(cursor) => {
761            let mut out = cursor.clone();
762            out.query = Box::new(bind_select(&cursor.query, r)?);
763            Statement::DeclareCursor(out)
764        }
765        Statement::Merge(merge) => {
766            let mut out = merge.clone();
767            out.with = bind_ctes(&merge.with, r)?;
768            out.source = bind_from(&merge.source, r)?;
769            out.join_condition = bind_expr(&merge.join_condition, r)?;
770            out.when_clauses = merge
771                .when_clauses
772                .iter()
773                .map(|w| bind_merge_when(w, r))
774                .collect::<Result<Vec<_>>>()?;
775            out.returning = bind_projections(&merge.returning, r)?;
776            Statement::Merge(out)
777        }
778        Statement::Call { name, args } => Statement::Call {
779            name: name.clone(),
780            args: bind_exprs(args, r)?,
781        },
782        other => other.clone(),
783    })
784}
785
786pub(super) fn bind_merge_when(when: &MergeWhen, r: &mut dyn VariableResolver) -> Result<MergeWhen> {
787    Ok(match when {
788        MergeWhen::UpdateMatched {
789            condition,
790            assignments,
791        } => MergeWhen::UpdateMatched {
792            condition: bind_opt_expr(condition.as_ref(), r)?,
793            assignments: bind_assignments(assignments, r)?,
794        },
795        MergeWhen::DeleteMatched { condition } => MergeWhen::DeleteMatched {
796            condition: bind_opt_expr(condition.as_ref(), r)?,
797        },
798        MergeWhen::UpdateNotMatchedBySource {
799            condition,
800            assignments,
801        } => MergeWhen::UpdateNotMatchedBySource {
802            condition: bind_opt_expr(condition.as_ref(), r)?,
803            assignments: bind_assignments(assignments, r)?,
804        },
805        MergeWhen::DeleteNotMatchedBySource { condition } => MergeWhen::DeleteNotMatchedBySource {
806            condition: bind_opt_expr(condition.as_ref(), r)?,
807        },
808        MergeWhen::InsertNotMatched {
809            condition,
810            columns,
811            overriding,
812            values,
813        } => MergeWhen::InsertNotMatched {
814            condition: bind_opt_expr(condition.as_ref(), r)?,
815            columns: columns
816                .iter()
817                .map(|target| bind_assignment_target(target, r))
818                .collect::<Result<_>>()?,
819            overriding: *overriding,
820            values: bind_exprs(values, r)?,
821        },
822        MergeWhen::NothingMatched { condition } => MergeWhen::NothingMatched {
823            condition: bind_opt_expr(condition.as_ref(), r)?,
824        },
825        MergeWhen::NothingNotMatched { condition } => MergeWhen::NothingNotMatched {
826            condition: bind_opt_expr(condition.as_ref(), r)?,
827        },
828        MergeWhen::NothingNotMatchedBySource { condition } => {
829            MergeWhen::NothingNotMatchedBySource {
830                condition: bind_opt_expr(condition.as_ref(), r)?,
831            }
832        }
833    })
834}