1use 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#[derive(Clone)]
22pub struct CopyTo {
23 pub input: Arc<LogicalPlan>,
25 pub output_url: String,
27 pub partition_by: Vec<String>,
29 pub file_type: Arc<dyn FileType>,
31 pub options: HashMap<String, String>,
33 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
50impl PartialEq for CopyTo {
52 fn eq(&self, other: &Self) -> bool {
53 self.input == other.input && self.output_url == other.output_url
54 }
55}
56
57impl Eq for CopyTo {}
59
60impl 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 .filter(|cmp| *cmp != Ordering::Equal || self == other)
76 }
77}
78
79impl 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 output_schema: make_count_schema(),
103 }
104 }
105}
106
107#[derive(Clone)]
130pub struct DmlStatement {
131 pub table_name: TableReference,
133 pub target: Arc<dyn TableSource>,
135 pub op: WriteOp,
137 pub input: Arc<LogicalPlan>,
139 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 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 output_schema: make_count_schema(),
192 }
193 }
194
195 pub fn name(&self) -> &str {
197 self.op.name()
198 }
199
200 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
211impl 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 .filter(|cmp| *cmp != Ordering::Equal || self == other)
224 }
225}
226
227#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
234#[non_exhaustive]
235pub enum WriteOp {
236 Insert(InsertOp),
238 Delete,
240 Update,
242 Ctas,
244 Truncate,
246 MergeInto(Box<MergeIntoOp>),
248}
249
250impl WriteOp {
251 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 Append,
275 Overwrite,
278 Replace,
282}
283
284impl InsertOp {
285 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#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
307#[non_exhaustive]
308pub struct MergeIntoOp {
309 pub on: Expr,
311 pub clauses: Vec<MergeIntoClause>,
313 target_qualifier: TableReference,
315}
316
317impl MergeIntoOp {
318 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 pub fn target_qualifier(&self) -> &TableReference {
333 &self.target_qualifier
334 }
335
336 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 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 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 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 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#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
485pub struct MergeIntoClause {
486 pub kind: MergeIntoClauseKind,
488 pub predicate: Option<Expr>,
490 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#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Hash)]
517pub enum MergeIntoClauseKind {
518 Matched,
520 NotMatched,
523 NotMatchedByTarget,
526 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 pub fn is_not_matched_by_target(&self) -> bool {
550 matches!(self, Self::NotMatched | Self::NotMatchedByTarget)
551 }
552
553 pub fn canonical(self) -> Self {
563 match self {
564 Self::NotMatched => Self::NotMatchedByTarget,
565 other => other,
566 }
567 }
568}
569
570#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
572pub enum MergeIntoAction {
573 Update(Vec<(String, Expr)>),
576 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}