1use crate::{ConnectionRef, DbError, current_connection};
2use futures::{
3 Stream, StreamExt, TryStreamExt,
4 stream::{self, BoxStream},
5};
6use sqlx::{
7 ColumnIndex, Database as SqlxDatabase, Decode, Either, Executor, FromRow, IntoArguments, Type,
8 query::{Query, QueryAs, QueryScalar},
9};
10use std::{future::Future, pin::Pin};
11type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T, DbError>> + Send + 'a>>;
12pub type ScopedStream<'q, T> = Pin<Box<dyn Stream<Item = Result<T, DbError>> + Send + 'q>>;
16
17fn buffered_stream<'q, T: Send + 'q>(future: BoxFuture<'q, Vec<T>>) -> ScopedStream<'q, T> {
18 Box::pin(
19 stream::once(future).flat_map(|result| -> BoxStream<'q, Result<T, DbError>> {
20 match result {
21 Ok(items) => stream::iter(items.into_iter().map(Ok)).boxed(),
22 Err(error) => stream::iter([Err(error)]).boxed(),
23 }
24 }),
25 )
26}
27
28pub trait ScopedQuery<'q, DB: SqlxDatabase>: Sized + Send {
29 fn execute_scoped(self) -> BoxFuture<'q, DB::QueryResult>;
30 fn fetch_one_scoped(self) -> BoxFuture<'q, DB::Row>;
31 fn fetch_optional_scoped(self) -> BoxFuture<'q, Option<DB::Row>>;
32 fn fetch_all_scoped(self) -> BoxFuture<'q, Vec<DB::Row>>;
33 fn fetch_scoped(self) -> ScopedStream<'q, DB::Row>;
34 #[allow(deprecated)]
35 fn execute_many_scoped(self) -> BoxFuture<'q, Vec<DB::QueryResult>>;
36 #[allow(deprecated)]
37 fn fetch_many_scoped(self) -> BoxFuture<'q, Vec<Either<DB::QueryResult, DB::Row>>>;
38}
39impl<'q, DB, A> ScopedQuery<'q, DB> for Query<'q, DB, A>
40where
41 DB: SqlxDatabase + 'static,
42 A: IntoArguments<'q, DB> + Send + 'q,
43 DB::QueryResult: Send + 'q,
44 for<'c> &'c mut DB::Connection: Executor<'c, Database = DB>,
45{
46 fn execute_scoped(self) -> BoxFuture<'q, DB::QueryResult> {
47 Box::pin(async move {
48 match current_connection::<DB>()? {
49 ConnectionRef::Pool(pool) => Ok(self.execute(pool.as_ref()).await?),
50 ConnectionRef::Transaction(transaction) => {
51 let mut guard = transaction.lock().await?;
52 Ok(self
53 .execute(&mut **guard.as_mut().expect("checked by lock"))
54 .await?)
55 }
56 }
57 })
58 }
59 fn fetch_one_scoped(self) -> BoxFuture<'q, DB::Row> {
60 Box::pin(async move {
61 match current_connection::<DB>()? {
62 ConnectionRef::Pool(pool) => Ok(self.fetch_one(pool.as_ref()).await?),
63 ConnectionRef::Transaction(transaction) => {
64 let mut guard = transaction.lock().await?;
65 Ok(self
66 .fetch_one(&mut **guard.as_mut().expect("checked by lock"))
67 .await?)
68 }
69 }
70 })
71 }
72 fn fetch_optional_scoped(self) -> BoxFuture<'q, Option<DB::Row>> {
73 Box::pin(async move {
74 match current_connection::<DB>()? {
75 ConnectionRef::Pool(pool) => Ok(self.fetch_optional(pool.as_ref()).await?),
76 ConnectionRef::Transaction(transaction) => {
77 let mut guard = transaction.lock().await?;
78 Ok(self
79 .fetch_optional(&mut **guard.as_mut().expect("checked by lock"))
80 .await?)
81 }
82 }
83 })
84 }
85 fn fetch_all_scoped(self) -> BoxFuture<'q, Vec<DB::Row>> {
86 Box::pin(async move {
87 match current_connection::<DB>()? {
88 ConnectionRef::Pool(pool) => Ok(self.fetch_all(pool.as_ref()).await?),
89 ConnectionRef::Transaction(transaction) => {
90 let mut guard = transaction.lock().await?;
91 Ok(self
92 .fetch_all(&mut **guard.as_mut().expect("checked by lock"))
93 .await?)
94 }
95 }
96 })
97 }
98 fn fetch_scoped(self) -> ScopedStream<'q, DB::Row> {
99 buffered_stream(self.fetch_all_scoped())
100 }
101 #[allow(deprecated)]
102 fn execute_many_scoped(self) -> BoxFuture<'q, Vec<DB::QueryResult>> {
103 Box::pin(async move {
104 match current_connection::<DB>()? {
105 ConnectionRef::Pool(pool) => {
106 Ok(self.execute_many(pool.as_ref()).await.try_collect().await?)
107 }
108 ConnectionRef::Transaction(transaction) => {
109 let mut guard = transaction.lock().await?;
110 Ok(self
111 .execute_many(&mut **guard.as_mut().expect("checked by lock"))
112 .await
113 .try_collect()
114 .await?)
115 }
116 }
117 })
118 }
119 #[allow(deprecated)]
120 fn fetch_many_scoped(self) -> BoxFuture<'q, Vec<Either<DB::QueryResult, DB::Row>>> {
121 Box::pin(async move {
122 match current_connection::<DB>()? {
123 ConnectionRef::Pool(pool) => {
124 Ok(self.fetch_many(pool.as_ref()).try_collect().await?)
125 }
126 ConnectionRef::Transaction(transaction) => {
127 let mut guard = transaction.lock().await?;
128 Ok(self
129 .fetch_many(&mut **guard.as_mut().expect("checked by lock"))
130 .try_collect()
131 .await?)
132 }
133 }
134 })
135 }
136}
137pub trait ScopedQueryAs<'q, DB: SqlxDatabase, O>: Sized + Send {
138 fn fetch_one_scoped(self) -> BoxFuture<'q, O>;
139 fn fetch_optional_scoped(self) -> BoxFuture<'q, Option<O>>;
140 fn fetch_all_scoped(self) -> BoxFuture<'q, Vec<O>>;
141 fn fetch_scoped(self) -> ScopedStream<'q, O>;
142 #[allow(deprecated)]
143 fn fetch_many_scoped(self) -> BoxFuture<'q, Vec<Either<DB::QueryResult, O>>>;
144}
145impl<'q, DB, O, A> ScopedQueryAs<'q, DB, O> for QueryAs<'q, DB, O, A>
146where
147 DB: SqlxDatabase + 'static,
148 A: IntoArguments<'q, DB> + Send + 'q,
149 O: Send + Unpin + for<'r> FromRow<'r, DB::Row> + 'q,
150 for<'c> &'c mut DB::Connection: Executor<'c, Database = DB>,
151{
152 fn fetch_one_scoped(self) -> BoxFuture<'q, O> {
153 Box::pin(async move {
154 match current_connection::<DB>()? {
155 ConnectionRef::Pool(p) => Ok(self.fetch_one(p.as_ref()).await?),
156 ConnectionRef::Transaction(t) => {
157 let mut g = t.lock().await?;
158 Ok(self
159 .fetch_one(&mut **g.as_mut().expect("checked by lock"))
160 .await?)
161 }
162 }
163 })
164 }
165 fn fetch_optional_scoped(self) -> BoxFuture<'q, Option<O>> {
166 Box::pin(async move {
167 match current_connection::<DB>()? {
168 ConnectionRef::Pool(p) => Ok(self.fetch_optional(p.as_ref()).await?),
169 ConnectionRef::Transaction(t) => {
170 let mut g = t.lock().await?;
171 Ok(self
172 .fetch_optional(&mut **g.as_mut().expect("checked by lock"))
173 .await?)
174 }
175 }
176 })
177 }
178 fn fetch_all_scoped(self) -> BoxFuture<'q, Vec<O>> {
179 Box::pin(async move {
180 match current_connection::<DB>()? {
181 ConnectionRef::Pool(p) => Ok(self.fetch_all(p.as_ref()).await?),
182 ConnectionRef::Transaction(t) => {
183 let mut g = t.lock().await?;
184 Ok(self
185 .fetch_all(&mut **g.as_mut().expect("checked by lock"))
186 .await?)
187 }
188 }
189 })
190 }
191 fn fetch_scoped(self) -> ScopedStream<'q, O> {
192 buffered_stream(self.fetch_all_scoped())
193 }
194 #[allow(deprecated)]
195 fn fetch_many_scoped(self) -> BoxFuture<'q, Vec<Either<DB::QueryResult, O>>> {
196 Box::pin(async move {
197 match current_connection::<DB>()? {
198 ConnectionRef::Pool(pool) => {
199 Ok(self.fetch_many(pool.as_ref()).try_collect().await?)
200 }
201 ConnectionRef::Transaction(transaction) => {
202 let mut guard = transaction.lock().await?;
203 Ok(self
204 .fetch_many(&mut **guard.as_mut().expect("checked by lock"))
205 .try_collect()
206 .await?)
207 }
208 }
209 })
210 }
211}
212pub trait ScopedScalarQuery<'q, DB: SqlxDatabase, O>: Sized + Send {
213 fn fetch_one_scoped(self) -> BoxFuture<'q, O>;
214 fn fetch_optional_scoped(self) -> BoxFuture<'q, Option<O>>;
215 fn fetch_all_scoped(self) -> BoxFuture<'q, Vec<O>>;
216 fn fetch_scoped(self) -> ScopedStream<'q, O>;
217 #[allow(deprecated)]
218 fn fetch_many_scoped(self) -> BoxFuture<'q, Vec<Either<DB::QueryResult, O>>>;
219}
220impl<'q, DB, O, A> ScopedScalarQuery<'q, DB, O> for QueryScalar<'q, DB, O, A>
221where
222 DB: SqlxDatabase + 'static,
223 A: IntoArguments<'q, DB> + Send + 'q,
224 O: Send + Unpin + for<'r> Decode<'r, DB> + Type<DB> + 'q,
225 usize: ColumnIndex<DB::Row>,
226 for<'r> (O,): FromRow<'r, DB::Row>,
227 for<'c> &'c mut DB::Connection: Executor<'c, Database = DB>,
228{
229 fn fetch_one_scoped(self) -> BoxFuture<'q, O> {
230 Box::pin(async move {
231 match current_connection::<DB>()? {
232 ConnectionRef::Pool(p) => Ok(self.fetch_one(p.as_ref()).await?),
233 ConnectionRef::Transaction(t) => {
234 let mut g = t.lock().await?;
235 Ok(self
236 .fetch_one(&mut **g.as_mut().expect("checked by lock"))
237 .await?)
238 }
239 }
240 })
241 }
242 fn fetch_optional_scoped(self) -> BoxFuture<'q, Option<O>> {
243 Box::pin(async move {
244 match current_connection::<DB>()? {
245 ConnectionRef::Pool(p) => Ok(self.fetch_optional(p.as_ref()).await?),
246 ConnectionRef::Transaction(t) => {
247 let mut g = t.lock().await?;
248 Ok(self
249 .fetch_optional(&mut **g.as_mut().expect("checked by lock"))
250 .await?)
251 }
252 }
253 })
254 }
255 fn fetch_all_scoped(self) -> BoxFuture<'q, Vec<O>> {
256 Box::pin(async move {
257 match current_connection::<DB>()? {
258 ConnectionRef::Pool(p) => Ok(self.fetch_all(p.as_ref()).await?),
259 ConnectionRef::Transaction(t) => {
260 let mut g = t.lock().await?;
261 Ok(self
262 .fetch_all(&mut **g.as_mut().expect("checked by lock"))
263 .await?)
264 }
265 }
266 })
267 }
268 fn fetch_scoped(self) -> ScopedStream<'q, O> {
269 buffered_stream(self.fetch_all_scoped())
270 }
271 #[allow(deprecated)]
272 fn fetch_many_scoped(self) -> BoxFuture<'q, Vec<Either<DB::QueryResult, O>>> {
273 Box::pin(async move {
274 match current_connection::<DB>()? {
275 ConnectionRef::Pool(pool) => {
276 Ok(self.fetch_many(pool.as_ref()).try_collect().await?)
277 }
278 ConnectionRef::Transaction(transaction) => {
279 let mut guard = transaction.lock().await?;
280 Ok(self
281 .fetch_many(&mut **guard.as_mut().expect("checked by lock"))
282 .try_collect()
283 .await?)
284 }
285 }
286 })
287 }
288}