use crate::{ConnectionRef, DbError, current_connection};
use futures::{
Stream, StreamExt, TryStreamExt,
stream::{self, BoxStream},
};
use sqlx::{
ColumnIndex, Database as SqlxDatabase, Decode, Either, Executor, FromRow, IntoArguments, Type,
query::{Query, QueryAs, QueryScalar},
};
use std::{future::Future, pin::Pin};
type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T, DbError>> + Send + 'a>>;
pub type ScopedStream<'q, T> = Pin<Box<dyn Stream<Item = Result<T, DbError>> + Send + 'q>>;
fn buffered_stream<'q, T: Send + 'q>(future: BoxFuture<'q, Vec<T>>) -> ScopedStream<'q, T> {
Box::pin(
stream::once(future).flat_map(|result| -> BoxStream<'q, Result<T, DbError>> {
match result {
Ok(items) => stream::iter(items.into_iter().map(Ok)).boxed(),
Err(error) => stream::iter([Err(error)]).boxed(),
}
}),
)
}
pub trait ScopedQuery<'q, DB: SqlxDatabase>: Sized + Send {
fn execute_scoped(self) -> BoxFuture<'q, DB::QueryResult>;
fn fetch_one_scoped(self) -> BoxFuture<'q, DB::Row>;
fn fetch_optional_scoped(self) -> BoxFuture<'q, Option<DB::Row>>;
fn fetch_all_scoped(self) -> BoxFuture<'q, Vec<DB::Row>>;
fn fetch_scoped(self) -> ScopedStream<'q, DB::Row>;
#[allow(deprecated)]
fn execute_many_scoped(self) -> BoxFuture<'q, Vec<DB::QueryResult>>;
#[allow(deprecated)]
fn fetch_many_scoped(self) -> BoxFuture<'q, Vec<Either<DB::QueryResult, DB::Row>>>;
}
impl<'q, DB, A> ScopedQuery<'q, DB> for Query<'q, DB, A>
where
DB: SqlxDatabase + 'static,
A: IntoArguments<'q, DB> + Send + 'q,
DB::QueryResult: Send + 'q,
for<'c> &'c mut DB::Connection: Executor<'c, Database = DB>,
{
fn execute_scoped(self) -> BoxFuture<'q, DB::QueryResult> {
Box::pin(async move {
match current_connection::<DB>()? {
ConnectionRef::Pool(pool) => Ok(self.execute(pool.as_ref()).await?),
ConnectionRef::Transaction(transaction) => {
let mut guard = transaction.lock().await?;
Ok(self
.execute(&mut **guard.as_mut().expect("checked by lock"))
.await?)
}
}
})
}
fn fetch_one_scoped(self) -> BoxFuture<'q, DB::Row> {
Box::pin(async move {
match current_connection::<DB>()? {
ConnectionRef::Pool(pool) => Ok(self.fetch_one(pool.as_ref()).await?),
ConnectionRef::Transaction(transaction) => {
let mut guard = transaction.lock().await?;
Ok(self
.fetch_one(&mut **guard.as_mut().expect("checked by lock"))
.await?)
}
}
})
}
fn fetch_optional_scoped(self) -> BoxFuture<'q, Option<DB::Row>> {
Box::pin(async move {
match current_connection::<DB>()? {
ConnectionRef::Pool(pool) => Ok(self.fetch_optional(pool.as_ref()).await?),
ConnectionRef::Transaction(transaction) => {
let mut guard = transaction.lock().await?;
Ok(self
.fetch_optional(&mut **guard.as_mut().expect("checked by lock"))
.await?)
}
}
})
}
fn fetch_all_scoped(self) -> BoxFuture<'q, Vec<DB::Row>> {
Box::pin(async move {
match current_connection::<DB>()? {
ConnectionRef::Pool(pool) => Ok(self.fetch_all(pool.as_ref()).await?),
ConnectionRef::Transaction(transaction) => {
let mut guard = transaction.lock().await?;
Ok(self
.fetch_all(&mut **guard.as_mut().expect("checked by lock"))
.await?)
}
}
})
}
fn fetch_scoped(self) -> ScopedStream<'q, DB::Row> {
buffered_stream(self.fetch_all_scoped())
}
#[allow(deprecated)]
fn execute_many_scoped(self) -> BoxFuture<'q, Vec<DB::QueryResult>> {
Box::pin(async move {
match current_connection::<DB>()? {
ConnectionRef::Pool(pool) => {
Ok(self.execute_many(pool.as_ref()).await.try_collect().await?)
}
ConnectionRef::Transaction(transaction) => {
let mut guard = transaction.lock().await?;
Ok(self
.execute_many(&mut **guard.as_mut().expect("checked by lock"))
.await
.try_collect()
.await?)
}
}
})
}
#[allow(deprecated)]
fn fetch_many_scoped(self) -> BoxFuture<'q, Vec<Either<DB::QueryResult, DB::Row>>> {
Box::pin(async move {
match current_connection::<DB>()? {
ConnectionRef::Pool(pool) => {
Ok(self.fetch_many(pool.as_ref()).try_collect().await?)
}
ConnectionRef::Transaction(transaction) => {
let mut guard = transaction.lock().await?;
Ok(self
.fetch_many(&mut **guard.as_mut().expect("checked by lock"))
.try_collect()
.await?)
}
}
})
}
}
pub trait ScopedQueryAs<'q, DB: SqlxDatabase, O>: Sized + Send {
fn fetch_one_scoped(self) -> BoxFuture<'q, O>;
fn fetch_optional_scoped(self) -> BoxFuture<'q, Option<O>>;
fn fetch_all_scoped(self) -> BoxFuture<'q, Vec<O>>;
fn fetch_scoped(self) -> ScopedStream<'q, O>;
#[allow(deprecated)]
fn fetch_many_scoped(self) -> BoxFuture<'q, Vec<Either<DB::QueryResult, O>>>;
}
impl<'q, DB, O, A> ScopedQueryAs<'q, DB, O> for QueryAs<'q, DB, O, A>
where
DB: SqlxDatabase + 'static,
A: IntoArguments<'q, DB> + Send + 'q,
O: Send + Unpin + for<'r> FromRow<'r, DB::Row> + 'q,
for<'c> &'c mut DB::Connection: Executor<'c, Database = DB>,
{
fn fetch_one_scoped(self) -> BoxFuture<'q, O> {
Box::pin(async move {
match current_connection::<DB>()? {
ConnectionRef::Pool(p) => Ok(self.fetch_one(p.as_ref()).await?),
ConnectionRef::Transaction(t) => {
let mut g = t.lock().await?;
Ok(self
.fetch_one(&mut **g.as_mut().expect("checked by lock"))
.await?)
}
}
})
}
fn fetch_optional_scoped(self) -> BoxFuture<'q, Option<O>> {
Box::pin(async move {
match current_connection::<DB>()? {
ConnectionRef::Pool(p) => Ok(self.fetch_optional(p.as_ref()).await?),
ConnectionRef::Transaction(t) => {
let mut g = t.lock().await?;
Ok(self
.fetch_optional(&mut **g.as_mut().expect("checked by lock"))
.await?)
}
}
})
}
fn fetch_all_scoped(self) -> BoxFuture<'q, Vec<O>> {
Box::pin(async move {
match current_connection::<DB>()? {
ConnectionRef::Pool(p) => Ok(self.fetch_all(p.as_ref()).await?),
ConnectionRef::Transaction(t) => {
let mut g = t.lock().await?;
Ok(self
.fetch_all(&mut **g.as_mut().expect("checked by lock"))
.await?)
}
}
})
}
fn fetch_scoped(self) -> ScopedStream<'q, O> {
buffered_stream(self.fetch_all_scoped())
}
#[allow(deprecated)]
fn fetch_many_scoped(self) -> BoxFuture<'q, Vec<Either<DB::QueryResult, O>>> {
Box::pin(async move {
match current_connection::<DB>()? {
ConnectionRef::Pool(pool) => {
Ok(self.fetch_many(pool.as_ref()).try_collect().await?)
}
ConnectionRef::Transaction(transaction) => {
let mut guard = transaction.lock().await?;
Ok(self
.fetch_many(&mut **guard.as_mut().expect("checked by lock"))
.try_collect()
.await?)
}
}
})
}
}
pub trait ScopedScalarQuery<'q, DB: SqlxDatabase, O>: Sized + Send {
fn fetch_one_scoped(self) -> BoxFuture<'q, O>;
fn fetch_optional_scoped(self) -> BoxFuture<'q, Option<O>>;
fn fetch_all_scoped(self) -> BoxFuture<'q, Vec<O>>;
fn fetch_scoped(self) -> ScopedStream<'q, O>;
#[allow(deprecated)]
fn fetch_many_scoped(self) -> BoxFuture<'q, Vec<Either<DB::QueryResult, O>>>;
}
impl<'q, DB, O, A> ScopedScalarQuery<'q, DB, O> for QueryScalar<'q, DB, O, A>
where
DB: SqlxDatabase + 'static,
A: IntoArguments<'q, DB> + Send + 'q,
O: Send + Unpin + for<'r> Decode<'r, DB> + Type<DB> + 'q,
usize: ColumnIndex<DB::Row>,
for<'r> (O,): FromRow<'r, DB::Row>,
for<'c> &'c mut DB::Connection: Executor<'c, Database = DB>,
{
fn fetch_one_scoped(self) -> BoxFuture<'q, O> {
Box::pin(async move {
match current_connection::<DB>()? {
ConnectionRef::Pool(p) => Ok(self.fetch_one(p.as_ref()).await?),
ConnectionRef::Transaction(t) => {
let mut g = t.lock().await?;
Ok(self
.fetch_one(&mut **g.as_mut().expect("checked by lock"))
.await?)
}
}
})
}
fn fetch_optional_scoped(self) -> BoxFuture<'q, Option<O>> {
Box::pin(async move {
match current_connection::<DB>()? {
ConnectionRef::Pool(p) => Ok(self.fetch_optional(p.as_ref()).await?),
ConnectionRef::Transaction(t) => {
let mut g = t.lock().await?;
Ok(self
.fetch_optional(&mut **g.as_mut().expect("checked by lock"))
.await?)
}
}
})
}
fn fetch_all_scoped(self) -> BoxFuture<'q, Vec<O>> {
Box::pin(async move {
match current_connection::<DB>()? {
ConnectionRef::Pool(p) => Ok(self.fetch_all(p.as_ref()).await?),
ConnectionRef::Transaction(t) => {
let mut g = t.lock().await?;
Ok(self
.fetch_all(&mut **g.as_mut().expect("checked by lock"))
.await?)
}
}
})
}
fn fetch_scoped(self) -> ScopedStream<'q, O> {
buffered_stream(self.fetch_all_scoped())
}
#[allow(deprecated)]
fn fetch_many_scoped(self) -> BoxFuture<'q, Vec<Either<DB::QueryResult, O>>> {
Box::pin(async move {
match current_connection::<DB>()? {
ConnectionRef::Pool(pool) => {
Ok(self.fetch_many(pool.as_ref()).try_collect().await?)
}
ConnectionRef::Transaction(transaction) => {
let mut guard = transaction.lock().await?;
Ok(self
.fetch_many(&mut **guard.as_mut().expect("checked by lock"))
.try_collect()
.await?)
}
}
})
}
}