zino_orm/
executor.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
use zino_core::error::Error;

/// Executing queries against the database.
pub trait Executor {
    /// A type for the database row.
    type Row;

    /// A type for the query result.
    type QueryResult;

    /// Executes the query and return the total number of rows affected.
    async fn execute(self, sql: &str) -> Result<Self::QueryResult, Error>;

    /// Executes the query with arguments and return the total number of rows affected.
    async fn execute_with<T: ToString>(
        self,
        sql: &str,
        arguments: &[T],
    ) -> Result<Self::QueryResult, Error>;

    /// Executes the query and return all the generated results.
    async fn fetch(self, sql: &str) -> Result<Vec<Self::Row>, Error>;

    /// Executes the query with arguments and return all the generated results.
    async fn fetch_with<T: ToString>(
        self,
        sql: &str,
        arguments: &[T],
    ) -> Result<Vec<Self::Row>, Error>;

    /// Executes the query and returns exactly one row.
    async fn fetch_one(self, sql: &str) -> Result<Self::Row, Error>;

    /// Executes the query and returns at most one row.
    async fn fetch_optional(self, sql: &str) -> Result<Option<Self::Row>, Error>;

    /// Executes the query with arguments and returns at most one row.
    async fn fetch_optional_with<T: ToString>(
        self,
        sql: &str,
        arguments: &[T],
    ) -> Result<Option<Self::Row>, Error>;
}

#[cfg(feature = "orm-sqlx")]
macro_rules! impl_sqlx_executor {
    () => {
        type Row = super::DatabaseRow;
        type QueryResult = <super::DatabaseDriver as sqlx::Database>::QueryResult;

        async fn execute(self, sql: &str) -> Result<Self::QueryResult, Error> {
            match sqlx::query(sql).execute(self).await {
                Ok(result) => Ok(result),
                Err(err) => {
                    if matches!(err, sqlx::error::Error::PoolTimedOut) {
                        super::GlobalPool::connect_all().await;
                    }
                    Err(err.into())
                }
            }
        }

        async fn execute_with<T: ToString>(
            self,
            sql: &str,
            arguments: &[T],
        ) -> Result<Self::QueryResult, Error> {
            let mut query = sqlx::query(sql);
            for arg in arguments {
                query = query.bind(arg.to_string());
            }
            match query.execute(self).await {
                Ok(result) => Ok(result),
                Err(err) => {
                    if matches!(err, sqlx::error::Error::PoolTimedOut) {
                        super::GlobalPool::connect_all().await;
                    }
                    Err(err.into())
                }
            }
        }

        async fn fetch(self, sql: &str) -> Result<Vec<Self::Row>, Error> {
            use futures::StreamExt;
            use std::sync::atomic::Ordering::Relaxed;

            let mut stream = sqlx::query(sql).fetch(self);
            let mut max_rows = super::MAX_ROWS.load(Relaxed);
            let mut rows = Vec::with_capacity(stream.size_hint().0.min(max_rows));
            while let Some(result) = stream.next().await {
                match result {
                    Ok(row) if max_rows > 0 => {
                        rows.push(row);
                        max_rows -= 1;
                    }
                    Err(err) => {
                        if matches!(err, sqlx::error::Error::PoolTimedOut) {
                            super::GlobalPool::connect_all().await;
                        }
                        return Err(err.into());
                    }
                    _ => break,
                }
            }
            Ok(rows)
        }

        async fn fetch_with<T: ToString>(
            self,
            sql: &str,
            arguments: &[T],
        ) -> Result<Vec<Self::Row>, Error> {
            use futures::StreamExt;
            use std::sync::atomic::Ordering::Relaxed;

            let mut query = sqlx::query(sql);
            for arg in arguments {
                query = query.bind(arg.to_string());
            }

            let mut stream = query.fetch(self);
            let mut max_rows = super::MAX_ROWS.load(Relaxed);
            let mut rows = Vec::with_capacity(stream.size_hint().0.min(max_rows));
            while let Some(result) = stream.next().await {
                match result {
                    Ok(row) if max_rows > 0 => {
                        rows.push(row);
                        max_rows -= 1;
                    }
                    Err(err) => {
                        if matches!(err, sqlx::error::Error::PoolTimedOut) {
                            super::GlobalPool::connect_all().await;
                        }
                        return Err(err.into());
                    }
                    _ => break,
                }
            }
            Ok(rows)
        }

        async fn fetch_one(self, sql: &str) -> Result<Self::Row, Error> {
            match sqlx::query(sql).fetch_one(self).await {
                Ok(row) => Ok(row),
                Err(err) => {
                    if matches!(err, sqlx::error::Error::PoolTimedOut) {
                        super::GlobalPool::connect_all().await;
                    }
                    Err(err.into())
                }
            }
        }

        async fn fetch_optional(self, sql: &str) -> Result<Option<Self::Row>, Error> {
            match sqlx::query(sql).fetch_optional(self).await {
                Ok(row) => Ok(row),
                Err(err) => {
                    if matches!(err, sqlx::error::Error::PoolTimedOut) {
                        super::GlobalPool::connect_all().await;
                    }
                    Err(err.into())
                }
            }
        }

        async fn fetch_optional_with<T: ToString>(
            self,
            sql: &str,
            arguments: &[T],
        ) -> Result<Option<Self::Row>, Error> {
            let mut query = sqlx::query(sql);
            for arg in arguments {
                query = query.bind(arg.to_string());
            }
            match query.fetch_optional(self).await {
                Ok(row) => Ok(row),
                Err(err) => {
                    if matches!(err, sqlx::error::Error::PoolTimedOut) {
                        super::GlobalPool::connect_all().await;
                    }
                    Err(err.into())
                }
            }
        }
    };
}

#[cfg(feature = "orm-sqlx")]
impl<'c> Executor for &'c sqlx::Pool<super::DatabaseDriver> {
    impl_sqlx_executor!();
}

#[cfg(feature = "orm-sqlx")]
impl<'c> Executor for &'c mut super::DatabaseConnection {
    impl_sqlx_executor!();
}