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