toasty_core/stmt/
delete.rs

1use super::{Node, Query, Returning, Source, Statement, Visit, VisitMut};
2use crate::stmt::{self, Filter};
3
4/// A `DELETE` statement that removes existing records.
5///
6/// Specifies a source to delete from, a filter selecting which records to
7/// delete, and an optional returning clause.
8///
9/// # Examples
10///
11/// ```ignore
12/// use toasty_core::stmt::{Delete, Source, Filter};
13/// use toasty_core::schema::app::ModelId;
14///
15/// let delete = Delete {
16///     from: Source::from(ModelId(0)),
17///     filter: Filter::default(),
18///     returning: None,
19/// };
20/// ```
21#[derive(Debug, Clone, PartialEq)]
22pub struct Delete {
23    /// The source to delete from (`FROM` clause).
24    pub from: Source,
25
26    /// Filter selecting which records to delete (`WHERE` clause).
27    pub filter: Filter,
28
29    /// Optional `RETURNING` clause.
30    pub returning: Option<Returning>,
31}
32
33impl Delete {
34    /// Returns a [`Query`] that selects the records this delete would remove.
35    pub fn selection(&self) -> Query {
36        stmt::Query::new_select(self.from.model_id_unwrap(), self.filter.clone())
37    }
38}
39
40impl Statement {
41    /// Returns `true` if this statement is a [`Delete`].
42    pub fn is_delete(&self) -> bool {
43        matches!(self, Statement::Delete(..))
44    }
45
46    /// Attempts to return a reference to an inner [`Delete`].
47    ///
48    /// * If `self` is a [`Statement::Delete`], a reference to the inner [`Delete`] is
49    ///   returned wrapped in [`Some`].
50    /// * Else, [`None`] is returned.
51    pub fn as_delete(&self) -> Option<&Delete> {
52        match self {
53            Self::Delete(delete) => Some(delete),
54            _ => None,
55        }
56    }
57
58    /// Consumes `self` and attempts to return the inner [`Delete`].
59    ///
60    /// * If `self` is a [`Statement::Delete`], inner [`Delete`] is returned wrapped in
61    ///   [`Some`].
62    /// * Else, [`None`] is returned.
63    pub fn into_delete(self) -> Option<Delete> {
64        match self {
65            Self::Delete(delete) => Some(delete),
66            _ => None,
67        }
68    }
69
70    /// Consumes `self` and returns the inner [`Delete`].
71    ///
72    /// # Panics
73    ///
74    /// If `self` is not a [`Statement::Delete`].
75    pub fn into_delete_unwrap(self) -> Delete {
76        match self {
77            Self::Delete(delete) => delete,
78            v => panic!("expected `Delete`, found {v:#?}"),
79        }
80    }
81}
82
83impl From<Delete> for Statement {
84    fn from(src: Delete) -> Self {
85        Self::Delete(src)
86    }
87}
88
89impl Node for Delete {
90    fn visit<V: Visit>(&self, mut visit: V) {
91        visit.visit_stmt_delete(self);
92    }
93
94    fn visit_mut<V: VisitMut>(&mut self, mut visit: V) {
95        visit.visit_stmt_delete_mut(self);
96    }
97}