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