sea_orm/executor/
delete.rs

1use crate::{error::*, ActiveModelTrait, ConnectionTrait, DeleteMany, DeleteOne, EntityTrait};
2use sea_query::DeleteStatement;
3use std::future::Future;
4
5/// Handles DELETE operations in a ActiveModel using [DeleteStatement]
6#[derive(Clone, Debug)]
7pub struct Deleter {
8    query: DeleteStatement,
9}
10
11/// The result of a DELETE operation
12#[derive(Clone, Debug, PartialEq, Eq)]
13pub struct DeleteResult {
14    /// The number of rows affected by the DELETE operation
15    pub rows_affected: u64,
16}
17
18impl<'a, A: 'a> DeleteOne<A>
19where
20    A: ActiveModelTrait,
21{
22    /// Execute a DELETE operation on one ActiveModel
23    pub fn exec<C>(self, db: &'a C) -> impl Future<Output = Result<DeleteResult, DbErr>> + 'a
24    where
25        C: ConnectionTrait,
26    {
27        // so that self is dropped before entering await
28        exec_delete_only(self.query, db)
29    }
30}
31
32impl<'a, E> DeleteMany<E>
33where
34    E: EntityTrait,
35{
36    /// Execute a DELETE operation on many ActiveModels
37    pub fn exec<C>(self, db: &'a C) -> impl Future<Output = Result<DeleteResult, DbErr>> + 'a
38    where
39        C: ConnectionTrait,
40    {
41        // so that self is dropped before entering await
42        exec_delete_only(self.query, db)
43    }
44}
45
46impl Deleter {
47    /// Instantiate a new [Deleter] by passing it a [DeleteStatement]
48    pub fn new(query: DeleteStatement) -> Self {
49        Self { query }
50    }
51
52    /// Execute a DELETE operation
53    pub fn exec<C>(self, db: &C) -> impl Future<Output = Result<DeleteResult, DbErr>> + '_
54    where
55        C: ConnectionTrait,
56    {
57        exec_delete(self.query, db)
58    }
59}
60
61async fn exec_delete_only<C>(query: DeleteStatement, db: &C) -> Result<DeleteResult, DbErr>
62where
63    C: ConnectionTrait,
64{
65    Deleter::new(query).exec(db).await
66}
67
68async fn exec_delete<C>(query: DeleteStatement, db: &C) -> Result<DeleteResult, DbErr>
69where
70    C: ConnectionTrait,
71{
72    let builder = db.get_database_backend();
73    let statement = builder.build(&query);
74
75    let result = db.execute(statement).await?;
76    Ok(DeleteResult {
77        rows_affected: result.rows_affected(),
78    })
79}