Skip to main content

diesel/query_builder/delete_statement/
mod.rs

1use crate::backend::DieselReserveSpecialization;
2use crate::dsl::{Filter, IntoBoxed, IntoBoxedClone, OrFilter};
3use crate::expression::{AppearsOnTable, Expression, SelectableExpression};
4use crate::query_builder::returning::{
5    DeleteStmt, NoReturningClause, ReturningClause, ReturningQuerySource,
6};
7use crate::query_builder::where_clause::*;
8use crate::query_builder::*;
9use crate::query_dsl::RunQueryDslSupport;
10use crate::query_dsl::methods::{BoxedCloneDsl, BoxedDsl, FilterDsl, OrFilterDsl};
11use crate::query_source::{QuerySource, Table};
12
13#[must_use = "Queries are only executed when calling `load`, `get_result` or similar."]
14/// Represents a SQL `DELETE` statement.
15///
16/// The type parameters on this struct represent:
17///
18/// - `T`: The table we are deleting from.
19/// - `U`: The `WHERE` clause of this query. The exact types used to represent
20///   this are private, and you should not make any assumptions about them.
21/// - `Ret`: The `RETURNING` clause of this query. The exact types used to
22///   represent this are private. You can safely rely on the default type
23///   representing the lack of a `RETURNING` clause.
24pub struct DeleteStatement<T: QuerySource, U, Ret = NoReturningClause> {
25    from_clause: FromClause<T>,
26    where_clause: U,
27    returning: Ret,
28}
29
30impl<T, U, Ret> Clone for DeleteStatement<T, U, Ret>
31where
32    T: QuerySource,
33    FromClause<T>: Clone,
34    U: Clone,
35    Ret: Clone,
36{
37    fn clone(&self) -> Self {
38        Self {
39            from_clause: self.from_clause.clone(),
40            where_clause: self.where_clause.clone(),
41            returning: self.returning.clone(),
42        }
43    }
44}
45
46impl<T, U, Ret> core::fmt::Debug for DeleteStatement<T, U, Ret>
47where
48    T: QuerySource,
49    FromClause<T>: core::fmt::Debug,
50    U: core::fmt::Debug,
51    Ret: core::fmt::Debug,
52{
53    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
54        f.debug_struct("DeleteStatement")
55            .field("from_clause", &self.from_clause)
56            .field("where_clause", &self.where_clause)
57            .field("returning", &self.returning)
58            .finish()
59    }
60}
61
62impl<T, U, Ret> QueryId for DeleteStatement<T, U, Ret>
63where
64    T: QuerySource + QueryId + 'static,
65    U: QueryId,
66    Ret: QueryId,
67{
68    type QueryId = DeleteStatement<T, U::QueryId, Ret::QueryId>;
69
70    const HAS_STATIC_QUERY_ID: bool =
71        T::HAS_STATIC_QUERY_ID && U::HAS_STATIC_QUERY_ID && Ret::HAS_STATIC_QUERY_ID;
72}
73
74/// A `DELETE` statement with a boxed `WHERE` clause
75pub type BoxedDeleteStatement<'a, DB, T, Ret = NoReturningClause> =
76    DeleteStatement<T, BoxedWhereClause<'a, DB>, Ret>;
77
78/// A `DELETE` statement with a boxed cloneable `WHERE` clause
79pub type BoxedCloneDeleteStatement<'a, DB, T, Ret = NoReturningClause> =
80    DeleteStatement<T, BoxedCloneWhereClause<'a, DB>, Ret>;
81
82impl<T: QuerySource, U> DeleteStatement<T, U, NoReturningClause> {
83    pub(crate) fn new(table: T, where_clause: U) -> Self {
84        DeleteStatement {
85            from_clause: FromClause::new(table),
86            where_clause,
87            returning: NoReturningClause,
88        }
89    }
90
91    /// Adds the given predicate to the `WHERE` clause of the statement being
92    /// constructed.
93    ///
94    /// If there is already a `WHERE` clause, the predicate will be appended
95    /// with `AND`. There is no difference in behavior between
96    /// `delete(table.filter(x))` and `delete(table).filter(x)`.
97    ///
98    /// # Example
99    ///
100    /// ```rust
101    /// # include!("../../doctest_setup.rs");
102    /// #
103    /// # fn main() {
104    /// #     use schema::users::dsl::*;
105    /// #     let connection = &mut establish_connection();
106    /// let deleted_rows = diesel::delete(users)
107    ///     .filter(name.eq("Sean"))
108    ///     .execute(connection);
109    /// assert_eq!(Ok(1), deleted_rows);
110    ///
111    /// let expected_names = vec!["Tess".to_string()];
112    /// let names = users.select(name).load(connection);
113    ///
114    /// assert_eq!(Ok(expected_names), names);
115    /// # }
116    /// ```
117    pub fn filter<Predicate>(self, predicate: Predicate) -> Filter<Self, Predicate>
118    where
119        Self: FilterDsl<Predicate>,
120    {
121        FilterDsl::filter(self, predicate)
122    }
123
124    /// Adds to the `WHERE` clause of a query using `OR`
125    ///
126    /// If there is already a `WHERE` clause, the result will be `(old OR new)`.
127    /// Calling `foo.filter(bar).or_filter(baz)`
128    /// is identical to `foo.filter(bar.or(baz))`.
129    /// However, the second form is much harder to do dynamically.
130    ///
131    /// # Example
132    ///
133    /// ```rust
134    /// # include!("../../doctest_setup.rs");
135    /// #
136    /// # fn main() {
137    /// #     use schema::users::dsl::*;
138    /// #     let connection = &mut establish_connection();
139    /// let deleted_rows = diesel::delete(users)
140    ///     .filter(name.eq("Sean"))
141    ///     .or_filter(name.eq("Tess"))
142    ///     .execute(connection);
143    /// assert_eq!(Ok(2), deleted_rows);
144    ///
145    /// let num_users = users.count().first(connection);
146    ///
147    /// assert_eq!(Ok(0), num_users);
148    /// # }
149    /// ```
150    pub fn or_filter<Predicate>(self, predicate: Predicate) -> OrFilter<Self, Predicate>
151    where
152        Self: OrFilterDsl<Predicate>,
153    {
154        OrFilterDsl::or_filter(self, predicate)
155    }
156
157    /// Boxes the `WHERE` clause of this delete statement.
158    ///
159    /// This is useful for cases where you want to conditionally modify a query,
160    /// but need the type to remain the same. The backend must be specified as
161    /// part of this. It is not possible to box a query and have it be useable
162    /// on multiple backends.
163    ///
164    /// A boxed query will incur a minor performance penalty, as the query builder
165    /// can no longer be inlined by the compiler. For most applications this cost
166    /// will be minimal.
167    ///
168    /// ### Example
169    ///
170    /// ```rust
171    /// # include!("../../doctest_setup.rs");
172    /// #
173    /// # fn main() {
174    /// #     run_test().unwrap();
175    /// # }
176    /// #
177    /// # fn run_test() -> QueryResult<()> {
178    /// #     use std::collections::HashMap;
179    /// #     use schema::users::dsl::*;
180    /// #     let connection = &mut establish_connection();
181    /// #     let mut params = HashMap::new();
182    /// #     params.insert("sean_has_been_a_jerk", true);
183    /// let mut query = diesel::delete(users).into_boxed();
184    ///
185    /// if params["sean_has_been_a_jerk"] {
186    ///     query = query.filter(name.eq("Sean"));
187    /// }
188    ///
189    /// let deleted_rows = query.execute(connection)?;
190    /// assert_eq!(1, deleted_rows);
191    ///
192    /// let expected_names = vec!["Tess"];
193    /// let names = users.select(name).load::<String>(connection)?;
194    ///
195    /// assert_eq!(expected_names, names);
196    /// #     Ok(())
197    /// # }
198    /// ```
199    pub fn into_boxed<'a, DB>(self) -> IntoBoxed<'a, Self, DB>
200    where
201        DB: Backend,
202        Self: BoxedDsl<'a, DB>,
203    {
204        BoxedDsl::internal_into_boxed(self)
205    }
206
207    /// Wraps the `WHERE` clause of this delete statement in an [`Arc`](alloc::sync::Arc).
208    ///
209    /// This is useful for cases where you want to clone and conditionally
210    /// modify a query, but need the type to remain the same. The backend
211    /// must be specified as part of this. It is not possible to box a query
212    /// and have it be useable on multiple backends.
213    ///
214    /// A cloneable boxed query will incur a slightly greater performance penalty
215    /// than a standard boxed query. In both cases, the query builder can no longer
216    /// be inlined by the compiler. For most applications this cost will be minimal.
217    ///
218    /// ### Example
219    ///
220    /// ```rust
221    /// # include!("../../doctest_setup.rs");
222    /// #
223    /// # fn main() {
224    /// #     run_test().unwrap();
225    /// # }
226    /// #
227    /// # fn run_test() -> QueryResult<()> {
228    /// #     use std::collections::HashMap;
229    /// #     use schema::users::dsl::*;
230    /// #     let connection = &mut establish_connection();
231    /// #     let mut params = HashMap::new();
232    /// #     params.insert("sean_has_been_a_jerk", true);
233    /// let query = diesel::delete(users).into_boxed_clone();
234    /// let mut query = query.clone();
235    ///
236    /// if params["sean_has_been_a_jerk"] {
237    ///     query = query.filter(name.eq("Sean"));
238    /// }
239    ///
240    /// let deleted_rows = query.execute(connection)?;
241    /// assert_eq!(1, deleted_rows);
242    ///
243    /// let expected_names = vec!["Tess"];
244    /// let names = users.select(name).load::<String>(connection)?;
245    ///
246    /// assert_eq!(expected_names, names);
247    /// #     Ok(())
248    /// # }
249    /// ```
250    pub fn into_boxed_clone<'a, DB>(self) -> IntoBoxedClone<'a, Self, DB>
251    where
252        DB: Backend,
253        Self: BoxedCloneDsl<'a, DB>,
254    {
255        BoxedCloneDsl::internal_into_boxed_clone(self)
256    }
257}
258
259impl<T, U, Ret, Predicate> FilterDsl<Predicate> for DeleteStatement<T, U, Ret>
260where
261    U: WhereAnd<Predicate>,
262    Predicate: AppearsOnTable<T>,
263    T: QuerySource,
264{
265    type Output = DeleteStatement<T, U::Output, Ret>;
266
267    fn filter(self, predicate: Predicate) -> Self::Output {
268        DeleteStatement {
269            from_clause: self.from_clause,
270            where_clause: self.where_clause.and(predicate),
271            returning: self.returning,
272        }
273    }
274}
275
276impl<T, U, Ret, Predicate> OrFilterDsl<Predicate> for DeleteStatement<T, U, Ret>
277where
278    T: QuerySource,
279    U: WhereOr<Predicate>,
280    Predicate: AppearsOnTable<T>,
281{
282    type Output = DeleteStatement<T, U::Output, Ret>;
283
284    fn or_filter(self, predicate: Predicate) -> Self::Output {
285        DeleteStatement {
286            from_clause: self.from_clause,
287            where_clause: self.where_clause.or(predicate),
288            returning: self.returning,
289        }
290    }
291}
292
293impl<'a, T, U, Ret, DB> BoxedDsl<'a, DB> for DeleteStatement<T, U, Ret>
294where
295    U: Into<BoxedWhereClause<'a, DB>>,
296    T: QuerySource,
297{
298    type Output = BoxedDeleteStatement<'a, DB, T, Ret>;
299
300    fn internal_into_boxed(self) -> Self::Output {
301        DeleteStatement {
302            where_clause: self.where_clause.into(),
303            returning: self.returning,
304            from_clause: self.from_clause,
305        }
306    }
307}
308
309impl<'a, T, U, Ret, DB> BoxedCloneDsl<'a, DB> for DeleteStatement<T, U, Ret>
310where
311    U: Into<BoxedCloneWhereClause<'a, DB>>,
312    T: QuerySource,
313{
314    type Output = BoxedCloneDeleteStatement<'a, DB, T, Ret>;
315
316    fn internal_into_boxed_clone(self) -> Self::Output {
317        DeleteStatement {
318            where_clause: self.where_clause.into(),
319            returning: self.returning,
320            from_clause: self.from_clause,
321        }
322    }
323}
324
325impl<T, U, Ret, DB> QueryFragment<DB> for DeleteStatement<T, U, Ret>
326where
327    DB: Backend + DieselReserveSpecialization,
328    T: Table,
329    FromClause<T>: QueryFragment<DB>,
330    U: QueryFragment<DB>,
331    Ret: QueryFragment<DB>,
332{
333    fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> {
334        out.push_sql("DELETE");
335        self.from_clause.walk_ast(out.reborrow())?;
336        self.where_clause.walk_ast(out.reborrow())?;
337        self.returning.walk_ast(out.reborrow())?;
338        Ok(())
339    }
340}
341
342impl<T, U> AsQuery for DeleteStatement<T, U, NoReturningClause>
343where
344    T: Table,
345    DeleteStatement<T, U, ReturningClause<T::AllColumns>>: Query,
346    T::AllColumns: SelectableExpression<ReturningQuerySource<DeleteStmt, T>>,
347{
348    type SqlType = <Self::Query as Query>::SqlType;
349    type Query = DeleteStatement<T, U, ReturningClause<T::AllColumns>>;
350
351    fn as_query(self) -> Self::Query {
352        self.returning(T::all_columns())
353    }
354}
355
356impl<T, U, Ret> Query for DeleteStatement<T, U, ReturningClause<Ret>>
357where
358    T: Table,
359    Ret: SelectableExpression<ReturningQuerySource<DeleteStmt, T>>,
360{
361    type SqlType = <Ret as Expression>::SqlType;
362}
363
364impl<T, U, Ret> RunQueryDslSupport for DeleteStatement<T, U, Ret> where T: QuerySource {}
365
366impl<T: QuerySource, U> DeleteStatement<T, U, NoReturningClause> {
367    /// Specify what expression is returned after execution of the `delete`.
368    ///
369    /// # Examples
370    ///
371    /// ### Deleting a record:
372    ///
373    /// ```rust
374    /// # include!("../../doctest_setup.rs");
375    /// #
376    /// # #[cfg(feature = "postgres")]
377    /// # fn main() {
378    /// #     use schema::users::dsl::*;
379    /// #     let connection = &mut establish_connection();
380    /// let deleted_name = diesel::delete(users.filter(name.eq("Sean")))
381    ///     .returning(name)
382    ///     .get_result(connection);
383    /// assert_eq!(Ok("Sean".to_string()), deleted_name);
384    /// # }
385    /// # #[cfg(not(feature = "postgres"))]
386    /// # fn main() {}
387    /// ```
388    pub fn returning<E>(self, returns: E) -> DeleteStatement<T, U, ReturningClause<E>>
389    where
390        DeleteStatement<T, U, ReturningClause<E>>: Query,
391    {
392        DeleteStatement {
393            where_clause: self.where_clause,
394            from_clause: self.from_clause,
395            returning: ReturningClause(returns),
396        }
397    }
398}