Skip to main content

datafusion_expr/logical_plan/
dml.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use std::cmp::Ordering;
6use std::collections::HashMap;
7use std::fmt::{self, Debug, Display, Formatter};
8use std::hash::{Hash, Hasher};
9use std::sync::Arc;
10
11use arrow::datatypes::{DataType, Field, Schema};
12use datafusion_common::file_options::file_type::FileType;
13use datafusion_common::utils::quote_identifier;
14use datafusion_common::{
15    DFSchema, DFSchemaRef, Result, TableReference, internal_err, plan_err,
16};
17
18use crate::{Expr, LogicalPlan, TableSource};
19
20/// Operator that copies the contents of a database to file(s)
21#[derive(Clone)]
22pub struct CopyTo {
23    /// The relation that determines the tuples to write to the output file(s)
24    pub input: Arc<LogicalPlan>,
25    /// The location to write the file(s)
26    pub output_url: String,
27    /// Determines which, if any, columns should be used for hive-style partitioned writes
28    pub partition_by: Vec<String>,
29    /// File type trait
30    pub file_type: Arc<dyn FileType>,
31    /// SQL Options that can affect the formats
32    pub options: HashMap<String, String>,
33    /// The schema of the output (a single column "count")
34    pub output_schema: DFSchemaRef,
35}
36
37impl Debug for CopyTo {
38    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
39        f.debug_struct("CopyTo")
40            .field("input", &self.input)
41            .field("output_url", &self.output_url)
42            .field("partition_by", &self.partition_by)
43            .field("file_type", &"...")
44            .field("options", &self.options)
45            .field("output_schema", &self.output_schema)
46            .finish_non_exhaustive()
47    }
48}
49
50// Implement PartialEq manually
51impl PartialEq for CopyTo {
52    fn eq(&self, other: &Self) -> bool {
53        self.input == other.input && self.output_url == other.output_url
54    }
55}
56
57// Implement Eq (no need for additional logic over PartialEq)
58impl Eq for CopyTo {}
59
60// Manual implementation needed because of `file_type` and `options` fields.
61// Comparison excludes these field.
62impl PartialOrd for CopyTo {
63    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
64        match self.input.partial_cmp(&other.input) {
65            Some(Ordering::Equal) => match self.output_url.partial_cmp(&other.output_url)
66            {
67                Some(Ordering::Equal) => {
68                    self.partition_by.partial_cmp(&other.partition_by)
69                }
70                cmp => cmp,
71            },
72            cmp => cmp,
73        }
74        // TODO (https://github.com/apache/datafusion/issues/17477) avoid recomparing all fields
75        .filter(|cmp| *cmp != Ordering::Equal || self == other)
76    }
77}
78
79// Implement Hash manually
80impl Hash for CopyTo {
81    fn hash<H: Hasher>(&self, state: &mut H) {
82        self.input.hash(state);
83        self.output_url.hash(state);
84    }
85}
86
87impl CopyTo {
88    pub fn new(
89        input: Arc<LogicalPlan>,
90        output_url: String,
91        partition_by: Vec<String>,
92        file_type: Arc<dyn FileType>,
93        options: HashMap<String, String>,
94    ) -> Self {
95        Self {
96            input,
97            output_url,
98            partition_by,
99            file_type,
100            options,
101            // The output schema is always a single column "count" with the number of rows copied
102            output_schema: make_count_schema(),
103        }
104    }
105}
106
107/// Modifies the content of a database
108///
109/// This operator is used to perform DML operations such as INSERT, DELETE,
110/// UPDATE, and CTAS (CREATE TABLE AS SELECT).
111///
112/// * `INSERT` - Appends new rows to the existing table. Calls
113///   [`TableProvider::insert_into`]
114///
115/// * `DELETE` - Removes rows from the table. Calls [`TableProvider::delete_from`]
116///
117/// * `UPDATE` - Modifies existing rows in the table. Calls [`TableProvider::update`]
118///
119/// * `CREATE TABLE AS SELECT` - Creates a new table and populates it with data
120///   from a query. This is similar to the `INSERT` operation, but it creates a new
121///   table instead of modifying an existing one.
122///
123/// Note that the structure is adapted from substrait WriteRel)
124///
125/// [`TableProvider`]: https://docs.rs/datafusion/latest/datafusion/datasource/trait.TableProvider.html
126/// [`TableProvider::insert_into`]: https://docs.rs/datafusion/latest/datafusion/datasource/trait.TableProvider.html#method.insert_into
127/// [`TableProvider::delete_from`]: https://docs.rs/datafusion/latest/datafusion/datasource/trait.TableProvider.html#method.delete_from
128/// [`TableProvider::update`]: https://docs.rs/datafusion/latest/datafusion/datasource/trait.TableProvider.html#method.update
129#[derive(Clone)]
130pub struct DmlStatement {
131    /// The table name
132    pub table_name: TableReference,
133    /// this is target table to insert into
134    pub target: Arc<dyn TableSource>,
135    /// The type of operation to perform
136    pub op: WriteOp,
137    /// The relation that determines the tuples to add/remove/modify the schema must match with table_schema
138    pub input: Arc<LogicalPlan>,
139    /// The schema of the output relation
140    pub output_schema: DFSchemaRef,
141}
142impl Eq for DmlStatement {}
143impl Hash for DmlStatement {
144    fn hash<H: Hasher>(&self, state: &mut H) {
145        self.table_name.hash(state);
146        self.target.schema().hash(state);
147        self.op.hash(state);
148        self.input.hash(state);
149        self.output_schema.hash(state);
150    }
151}
152
153impl PartialEq for DmlStatement {
154    fn eq(&self, other: &Self) -> bool {
155        self.table_name == other.table_name
156            && self.target.schema() == other.target.schema()
157            && self.op == other.op
158            && self.input == other.input
159            && self.output_schema == other.output_schema
160    }
161}
162
163impl Debug for DmlStatement {
164    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
165        f.debug_struct("DmlStatement")
166            .field("table_name", &self.table_name)
167            .field("target", &"...")
168            .field("target_schema", &self.target.schema())
169            .field("op", &self.op)
170            .field("input", &self.input)
171            .field("output_schema", &self.output_schema)
172            .finish()
173    }
174}
175
176impl DmlStatement {
177    /// Creates a new DML statement with the output schema set to a single `count` column.
178    pub fn new(
179        table_name: TableReference,
180        target: Arc<dyn TableSource>,
181        op: WriteOp,
182        input: Arc<LogicalPlan>,
183    ) -> Self {
184        Self {
185            table_name,
186            target,
187            op,
188            input,
189
190            // The output schema is always a single column with the number of rows affected
191            output_schema: make_count_schema(),
192        }
193    }
194
195    /// Return a descriptive name of this [`DmlStatement`]
196    pub fn name(&self) -> &str {
197        self.op.name()
198    }
199
200    /// Build the target-plus-source schema used by MERGE expressions.
201    pub fn merge_schema(&self) -> Result<DFSchema> {
202        let WriteOp::MergeInto(merge_op) = &self.op else {
203            return internal_err!(
204                "DmlStatement::merge_schema requires a MERGE operation"
205            );
206        };
207        merge_op.expression_schema(&self.target.schema(), self.input.schema())
208    }
209}
210
211// Manual implementation needed because of `table_schema` and `output_schema` fields.
212// Comparison excludes these fields.
213impl PartialOrd for DmlStatement {
214    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
215        match self.table_name.partial_cmp(&other.table_name) {
216            Some(Ordering::Equal) => match self.op.partial_cmp(&other.op) {
217                Some(Ordering::Equal) => self.input.partial_cmp(&other.input),
218                cmp => cmp,
219            },
220            cmp => cmp,
221        }
222        // TODO (https://github.com/apache/datafusion/issues/17477) avoid recomparing all fields
223        .filter(|cmp| *cmp != Ordering::Equal || self == other)
224    }
225}
226
227/// The type of DML operation to perform.
228///
229/// See [`DmlStatement`] for more details.
230///
231/// Marked `#[non_exhaustive]` so adding new variants in future releases is
232/// not a SemVer break for downstream matchers.
233#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
234#[non_exhaustive]
235pub enum WriteOp {
236    /// `INSERT INTO` operation
237    Insert(InsertOp),
238    /// `DELETE` operation
239    Delete,
240    /// `UPDATE` operation
241    Update,
242    /// `CREATE TABLE AS SELECT` operation
243    Ctas,
244    /// `TRUNCATE` operation
245    Truncate,
246    /// `MERGE INTO` operation
247    MergeInto(Box<MergeIntoOp>),
248}
249
250impl WriteOp {
251    /// Return a descriptive name of this [`WriteOp`]
252    pub fn name(&self) -> &str {
253        match self {
254            WriteOp::Insert(insert) => insert.name(),
255            WriteOp::Delete => "Delete",
256            WriteOp::Update => "Update",
257            WriteOp::Ctas => "Ctas",
258            WriteOp::Truncate => "Truncate",
259            WriteOp::MergeInto(_) => "MergeInto",
260        }
261    }
262}
263
264impl Display for WriteOp {
265    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
266        write!(f, "{}", self.name())
267    }
268}
269
270#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Hash)]
271pub enum InsertOp {
272    /// Appends new rows to the existing table without modifying any
273    /// existing rows. This corresponds to the SQL `INSERT INTO` query.
274    Append,
275    /// Overwrites all existing rows in the table with the new rows.
276    /// This corresponds to the SQL `INSERT OVERWRITE` query.
277    Overwrite,
278    /// If any existing rows collides with the inserted rows (typically based
279    /// on a unique key or primary key), those existing rows are replaced.
280    /// This corresponds to the SQL `REPLACE INTO` query and its equivalents.
281    Replace,
282}
283
284impl InsertOp {
285    /// Return a descriptive name of this [`InsertOp`]
286    pub fn name(&self) -> &str {
287        match self {
288            InsertOp::Append => "Insert Into",
289            InsertOp::Overwrite => "Insert Overwrite",
290            InsertOp::Replace => "Replace Into",
291        }
292    }
293}
294
295impl Display for InsertOp {
296    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
297        write!(f, "{}", self.name())
298    }
299}
300
301/// Describes a MERGE INTO operation's parameters.
302///
303/// [`Self::target_qualifier`] is the SQL-visible relation name used by
304/// expressions. The target's catalog/provider identity remains in
305/// [`DmlStatement::table_name`].
306#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
307#[non_exhaustive]
308pub struct MergeIntoOp {
309    /// The join condition from `ON <expr>`.
310    pub on: Expr,
311    /// The WHEN clauses, in the order they appeared in the SQL.
312    pub clauses: Vec<MergeIntoClause>,
313    /// The target relation name visible to expressions in the MERGE scope.
314    target_qualifier: TableReference,
315}
316
317impl MergeIntoOp {
318    /// Create a MERGE operation.
319    pub fn new(
320        target_qualifier: impl Into<TableReference>,
321        on: Expr,
322        clauses: Vec<MergeIntoClause>,
323    ) -> Self {
324        Self {
325            target_qualifier: target_qualifier.into(),
326            on,
327            clauses,
328        }
329    }
330
331    /// Return the target relation name visible to MERGE expressions.
332    pub fn target_qualifier(&self) -> &TableReference {
333        &self.target_qualifier
334    }
335
336    /// Build the schema used to resolve expressions owned by this operation.
337    ///
338    /// Target fields precede source fields. The visible target qualifier must
339    /// not also identify a source relation in the outer MERGE scope.
340    pub fn expression_schema(
341        &self,
342        target_schema: &Schema,
343        source_schema: &DFSchema,
344    ) -> Result<DFSchema> {
345        Self::expression_schema_for(&self.target_qualifier, target_schema, source_schema)
346    }
347
348    /// Build a MERGE expression schema before constructing the operation.
349    pub fn expression_schema_for(
350        target_qualifier: &TableReference,
351        target_schema: &Schema,
352        source_schema: &DFSchema,
353    ) -> Result<DFSchema> {
354        if source_schema.iter().any(|(qualifier, _)| {
355            qualifier.is_some_and(|qualifier| qualifier.resolved_eq(target_qualifier))
356        }) {
357            return plan_err!(
358                "MERGE target qualifier '{}' conflicts with a source qualifier",
359                target_qualifier
360            );
361        }
362
363        DFSchema::try_from_qualified_schema(target_qualifier.clone(), target_schema)?
364            .join(source_schema)
365    }
366
367    /// Count of top-level [`Expr`]s owned by this operation (no allocation).
368    ///
369    /// Matches the length of [`Self::exprs`] and the `exprs` vec consumed by
370    /// [`Self::with_new_exprs`].
371    fn expr_count(&self) -> usize {
372        1 + self
373            .clauses
374            .iter()
375            .map(|c| {
376                c.predicate.is_some() as usize
377                    + match &c.action {
378                        MergeIntoAction::Update(a) => a.len(),
379                        MergeIntoAction::Insert { values, .. } => values.len(),
380                        MergeIntoAction::Delete => 0,
381                    }
382            })
383            .sum::<usize>()
384    }
385
386    /// Top-level [`Expr`]s in stable order: `on`, then per-clause predicate
387    /// (if any) and action value expressions.
388    pub fn exprs(&self) -> Vec<&Expr> {
389        let mut out = Vec::with_capacity(self.expr_count());
390        out.push(&self.on);
391        for clause in &self.clauses {
392            if let Some(predicate) = &clause.predicate {
393                out.push(predicate);
394            }
395            match &clause.action {
396                MergeIntoAction::Update(assignments) => {
397                    out.extend(assignments.iter().map(|(_, value)| value));
398                }
399                MergeIntoAction::Insert { values, .. } => {
400                    out.extend(values.iter());
401                }
402                MergeIntoAction::Delete => {}
403            }
404        }
405        out
406    }
407
408    /// Rebuild this `MergeIntoOp` from a flat vector of new expressions, in
409    /// the same order produced by [`Self::exprs`]. The clause kinds, action
410    /// kinds, column lists, and presence/absence of each predicate are
411    /// preserved from `self`.
412    pub fn with_new_exprs(&self, exprs: Vec<Expr>) -> Result<Self> {
413        let expected = self.expr_count();
414        if exprs.len() != expected {
415            return internal_err!(
416                "MergeIntoOp::with_new_exprs expected {expected} expressions, got {}",
417                exprs.len()
418            );
419        }
420        let mut iter = exprs.into_iter();
421        let on = iter.next().expect("non-empty by length check");
422        let clauses = self
423            .clauses
424            .iter()
425            .map(|clause| {
426                let predicate = clause
427                    .predicate
428                    .is_some()
429                    .then(|| iter.next().expect("non-empty by length check"));
430                let action = match &clause.action {
431                    MergeIntoAction::Update(assignments) => {
432                        let assignments = assignments
433                            .iter()
434                            .map(|(name, _)| {
435                                (
436                                    name.clone(),
437                                    iter.next().expect("non-empty by length check"),
438                                )
439                            })
440                            .collect();
441                        MergeIntoAction::Update(assignments)
442                    }
443                    MergeIntoAction::Insert { columns, values } => {
444                        let values = values
445                            .iter()
446                            .map(|_| iter.next().expect("non-empty by length check"))
447                            .collect();
448                        MergeIntoAction::Insert {
449                            columns: columns.clone(),
450                            values,
451                        }
452                    }
453                    MergeIntoAction::Delete => MergeIntoAction::Delete,
454                };
455                MergeIntoClause {
456                    kind: clause.kind,
457                    predicate,
458                    action,
459                }
460            })
461            .collect();
462        Ok(Self {
463            target_qualifier: self.target_qualifier.clone(),
464            on,
465            clauses,
466        })
467    }
468}
469
470impl Display for MergeIntoOp {
471    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
472        write!(f, "on=[{}] clauses=[", self.on)?;
473        for (i, clause) in self.clauses.iter().enumerate() {
474            if i > 0 {
475                write!(f, ", ")?;
476            }
477            write!(f, "{clause}")?;
478        }
479        write!(f, "]")
480    }
481}
482
483/// A single WHEN clause within a MERGE INTO statement.
484#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
485pub struct MergeIntoClause {
486    /// Whether this fires on matched or unmatched rows.
487    pub kind: MergeIntoClauseKind,
488    /// Optional additional predicate (`AND <expr>`).
489    pub predicate: Option<Expr>,
490    /// The action to take.
491    pub action: MergeIntoAction,
492}
493
494impl Display for MergeIntoClause {
495    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
496        write!(f, "WHEN {}", self.kind)?;
497        if let Some(predicate) = &self.predicate {
498            write!(f, " AND {predicate}")?;
499        }
500        write!(f, " THEN {}", self.action)
501    }
502}
503
504/// Which rows a MERGE WHEN clause applies to.
505///
506/// Mirrors `sqlparser::ast::MergeClauseKind` so that the SQL spelling is
507/// preserved through the logical plan.
508///
509/// **Note on `NotMatched` vs `NotMatchedByTarget`:** these two variants are
510/// semantically identical — both describe a source row that has no matching
511/// target row. `NotMatched` is the SQL standard short form (used by
512/// Snowflake, Postgres, SQL Server); `NotMatchedByTarget` is BigQuery's
513/// explicit form added for symmetry with `NotMatchedBySource`. Downstream
514/// consumers (planners, table providers, optimizers) MUST treat the two
515/// variants identically.
516#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Hash)]
517pub enum MergeIntoClauseKind {
518    /// `WHEN MATCHED`
519    Matched,
520    /// `WHEN NOT MATCHED` — see type-level note for the equivalence with
521    /// [`NotMatchedByTarget`](Self::NotMatchedByTarget).
522    NotMatched,
523    /// `WHEN NOT MATCHED BY TARGET` — see type-level note for the
524    /// equivalence with [`NotMatched`](Self::NotMatched).
525    NotMatchedByTarget,
526    /// `WHEN NOT MATCHED BY SOURCE`
527    NotMatchedBySource,
528}
529
530impl Display for MergeIntoClauseKind {
531    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
532        match self {
533            Self::Matched => write!(f, "MATCHED"),
534            Self::NotMatched => write!(f, "NOT MATCHED"),
535            Self::NotMatchedByTarget => write!(f, "NOT MATCHED BY TARGET"),
536            Self::NotMatchedBySource => write!(f, "NOT MATCHED BY SOURCE"),
537        }
538    }
539}
540
541impl MergeIntoClauseKind {
542    /// True if this clause fires on a source row that has no matching target
543    /// row. Returns `true` for both [`NotMatched`](Self::NotMatched) and
544    /// [`NotMatchedByTarget`](Self::NotMatchedByTarget) (see the type-level
545    /// note explaining why those two variants are semantically identical).
546    ///
547    /// Prefer this predicate over hand-written `matches!` arms so the
548    /// `NotMatched`/`NotMatchedByTarget` equivalence is enforced in one place.
549    pub fn is_not_matched_by_target(&self) -> bool {
550        matches!(self, Self::NotMatched | Self::NotMatchedByTarget)
551    }
552
553    /// Collapse the SQL-spelling variants into the canonical three semantic
554    /// categories: [`Matched`](Self::Matched),
555    /// [`NotMatchedByTarget`](Self::NotMatchedByTarget) (covering both
556    /// "NOT MATCHED" spellings), and
557    /// [`NotMatchedBySource`](Self::NotMatchedBySource).
558    ///
559    /// Use this in downstream `match` expressions when the SQL spelling
560    /// distinction does not matter — e.g. in planners, optimizers, or
561    /// table-provider dispatch.
562    pub fn canonical(self) -> Self {
563        match self {
564            Self::NotMatched => Self::NotMatchedByTarget,
565            other => other,
566        }
567    }
568}
569
570/// The action for a single WHEN clause.
571#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
572pub enum MergeIntoAction {
573    /// `UPDATE SET col1 = expr1, col2 = expr2, ...`, stored as
574    /// `(column_name, value_expr)` pairs.
575    Update(Vec<(String, Expr)>),
576    /// `INSERT (col1, col2, ...) VALUES (expr1, expr2, ...)`. `columns` may
577    /// be empty, meaning all columns.
578    Insert {
579        columns: Vec<String>,
580        values: Vec<Expr>,
581    },
582    Delete,
583}
584
585impl Display for MergeIntoAction {
586    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
587        match self {
588            Self::Update(assignments) => {
589                write!(f, "UPDATE SET ")?;
590                for (i, (column, value)) in assignments.iter().enumerate() {
591                    if i > 0 {
592                        write!(f, ", ")?;
593                    }
594                    write!(f, "{} = {value}", quote_identifier(column))?;
595                }
596                Ok(())
597            }
598            Self::Insert { columns, values } => {
599                write!(f, "INSERT")?;
600                if !columns.is_empty() {
601                    write!(
602                        f,
603                        " ({})",
604                        columns
605                            .iter()
606                            .map(|column| quote_identifier(column))
607                            .collect::<Vec<_>>()
608                            .join(", ")
609                    )?;
610                }
611                write!(f, " VALUES (")?;
612                for (i, value) in values.iter().enumerate() {
613                    if i > 0 {
614                        write!(f, ", ")?;
615                    }
616                    write!(f, "{value}")?;
617                }
618                write!(f, ")")
619            }
620            Self::Delete => write!(f, "DELETE"),
621        }
622    }
623}
624
625fn make_count_schema() -> DFSchemaRef {
626    Arc::new(
627        Schema::new(vec![Field::new("count", DataType::UInt64, false)])
628            .try_into()
629            .unwrap(),
630    )
631}
632
633#[cfg(test)]
634mod tests {
635    use super::*;
636    use crate::{col, lit};
637
638    #[test]
639    fn write_op_merge_into_name_and_display() {
640        let op = WriteOp::MergeInto(Box::new(MergeIntoOp::new(
641            "target",
642            col("id").eq(col("source_id")),
643            vec![MergeIntoClause {
644                kind: MergeIntoClauseKind::Matched,
645                predicate: Some(col("qty").gt(lit(0_i64))),
646                action: MergeIntoAction::Update(vec![(
647                    "qty".to_string(),
648                    col("source_qty"),
649                )]),
650            }],
651        )));
652        assert_eq!(op.name(), "MergeInto");
653        assert_eq!(format!("{op}"), "MergeInto");
654        let WriteOp::MergeInto(merge_op) = &op else {
655            unreachable!("constructed as MergeInto")
656        };
657        assert_eq!(
658            merge_op.to_string(),
659            "on=[id = source_id] clauses=[WHEN MATCHED AND qty > Int64(0) THEN UPDATE SET qty = source_qty]"
660        );
661
662        let empty = MergeIntoOp::new("target", lit(true), vec![]);
663        assert_eq!(empty.to_string(), "on=[Boolean(true)] clauses=[]");
664
665        let update = MergeIntoAction::Update(vec![("a, b".to_string(), lit(1_i64))]);
666        assert_eq!(update.to_string(), r#"UPDATE SET "a, b" = Int64(1)"#);
667        let insert = MergeIntoAction::Insert {
668            columns: vec!["id".to_string(), "a\"b".to_string()],
669            values: vec![lit(1_i64), lit(2_i64)],
670        };
671        assert_eq!(
672            insert.to_string(),
673            r#"INSERT (id, "a""b") VALUES (Int64(1), Int64(2))"#
674        );
675    }
676
677    #[test]
678    fn merge_into_clause_kind_is_not_matched_by_target() {
679        assert!(!MergeIntoClauseKind::Matched.is_not_matched_by_target());
680        assert!(MergeIntoClauseKind::NotMatched.is_not_matched_by_target());
681        assert!(MergeIntoClauseKind::NotMatchedByTarget.is_not_matched_by_target());
682        assert!(!MergeIntoClauseKind::NotMatchedBySource.is_not_matched_by_target());
683    }
684
685    #[test]
686    fn merge_into_clause_kind_canonical_collapses_not_matched() {
687        assert_eq!(
688            MergeIntoClauseKind::NotMatched.canonical(),
689            MergeIntoClauseKind::NotMatchedByTarget
690        );
691        assert_eq!(
692            MergeIntoClauseKind::NotMatchedByTarget.canonical(),
693            MergeIntoClauseKind::NotMatchedByTarget
694        );
695        assert_eq!(
696            MergeIntoClauseKind::Matched.canonical(),
697            MergeIntoClauseKind::Matched
698        );
699        assert_eq!(
700            MergeIntoClauseKind::NotMatchedBySource.canonical(),
701            MergeIntoClauseKind::NotMatchedBySource
702        );
703    }
704
705    #[test]
706    fn merge_into_op_exprs_round_trip() {
707        let op = MergeIntoOp::new(
708            "target",
709            col("id").eq(col("source_id")),
710            vec![
711                MergeIntoClause {
712                    kind: MergeIntoClauseKind::Matched,
713                    predicate: Some(col("qty").gt(lit(0_i64))),
714                    action: MergeIntoAction::Update(vec![
715                        ("qty".to_string(), col("source_qty")),
716                        ("price".to_string(), col("source_price")),
717                    ]),
718                },
719                MergeIntoClause {
720                    kind: MergeIntoClauseKind::NotMatched,
721                    predicate: None,
722                    action: MergeIntoAction::Insert {
723                        columns: vec!["id".to_string(), "qty".to_string()],
724                        values: vec![col("source_id"), col("source_qty")],
725                    },
726                },
727                MergeIntoClause {
728                    kind: MergeIntoClauseKind::NotMatchedBySource,
729                    predicate: Some(col("active").eq(lit(true))),
730                    action: MergeIntoAction::Delete,
731                },
732            ],
733        );
734        let exprs = op.exprs();
735        assert_eq!(exprs.len(), 7);
736
737        let owned: Vec<Expr> = exprs.into_iter().cloned().collect();
738        let rebuilt = op.with_new_exprs(owned).unwrap();
739        assert_eq!(op, rebuilt);
740    }
741
742    #[test]
743    fn merge_into_op_with_new_exprs_length_mismatch() {
744        let op = MergeIntoOp::new("target", col("id").eq(col("source_id")), vec![]);
745        let err = op.with_new_exprs(vec![]).unwrap_err();
746        assert!(
747            err.to_string().contains("expected 1 expressions, got 0"),
748            "unexpected error: {err}"
749        );
750    }
751
752    #[test]
753    fn merge_into_schema_uses_visible_qualifier_as_outer_scope_binding() -> Result<()> {
754        let target_schema = Schema::new(vec![Field::new("id", DataType::Int32, false)]);
755        let source_schema =
756            Schema::new(vec![Field::new("source_id", DataType::Int32, false)]);
757        let op = MergeIntoOp::new("t", col("t.id").eq(col("target.source_id")), vec![]);
758
759        let source = DFSchema::try_from_qualified_schema("target", &source_schema)?;
760        let schema = op.expression_schema(&target_schema, &source)?;
761        assert!(schema.has_column(&datafusion_common::Column::new(Some("t"), "id")));
762        assert!(
763            schema
764                .has_column(&datafusion_common::Column::new(Some("target"), "source_id"))
765        );
766
767        let colliding_source = DFSchema::try_from_qualified_schema("t", &source_schema)?;
768        let err = op
769            .expression_schema(&target_schema, &colliding_source)
770            .unwrap_err();
771        assert!(
772            err.to_string()
773                .contains("target qualifier 't' conflicts with a source qualifier")
774        );
775        Ok(())
776    }
777}