toasty_core/stmt/
insert.rs

1use super::{InsertTarget, Node, Query, Returning, Statement, Visit, VisitMut};
2use crate::stmt;
3
4#[derive(Debug, Clone, PartialEq)]
5pub struct Insert {
6    /// Where to insert the values
7    pub target: InsertTarget,
8
9    /// Source of values to insert
10    pub source: Query,
11
12    /// Optionally return data from the insertion
13    pub returning: Option<Returning>,
14}
15
16impl Insert {
17    pub fn merge(&mut self, other: Self) {
18        match (&self.target, &other.target) {
19            (InsertTarget::Model(a), InsertTarget::Model(b)) if a == b => {}
20            _ => todo!("handle this case"),
21        }
22
23        match (&mut self.source.body, other.source.body) {
24            (stmt::ExprSet::Values(self_values), stmt::ExprSet::Values(other_values)) => {
25                for expr in other_values.rows {
26                    self_values.rows.push(expr);
27                }
28            }
29            (self_source, other) => todo!("self={:#?}; other={:#?}", self_source, other),
30        }
31    }
32}
33
34impl Statement {
35    pub fn is_insert(&self) -> bool {
36        matches!(self, Statement::Insert(..))
37    }
38
39    /// Attempts to return a reference to an inner [`Insert`].
40    ///
41    /// * If `self` is a [`Statement::Insert`], a reference to the inner [`Insert`] is
42    ///   returned wrapped in [`Some`].
43    /// * Else, [`None`] is returned.
44    pub fn as_insert(&self) -> Option<&Insert> {
45        match self {
46            Self::Insert(insert) => Some(insert),
47            _ => None,
48        }
49    }
50
51    /// Consumes `self` and attempts to return the inner [`Insert`].
52    ///
53    /// * If `self` is a [`Statement::Insert`], inner [`Insert`] is returned wrapped in
54    ///   [`Some`].
55    /// * Else, [`None`] is returned.
56    pub fn into_insert(self) -> Option<Insert> {
57        match self {
58            Self::Insert(insert) => Some(insert),
59            _ => None,
60        }
61    }
62
63    /// Consumes `self` and returns the inner [`Insert`].
64    ///
65    /// # Panics
66    ///
67    /// If `self` is not a [`Statement::Insert`].
68    pub fn unwrap_insert(self) -> Insert {
69        match self {
70            Self::Insert(insert) => insert,
71            v => panic!("expected `Insert`, found {v:#?}"),
72        }
73    }
74}
75
76impl From<Insert> for Statement {
77    fn from(src: Insert) -> Self {
78        Self::Insert(src)
79    }
80}
81
82impl Node for Insert {
83    fn visit<V: Visit>(&self, mut visit: V) {
84        visit.visit_stmt_insert(self);
85    }
86
87    fn visit_mut<V: VisitMut>(&mut self, mut visit: V) {
88        visit.visit_stmt_insert_mut(self);
89    }
90}