use core::marker::PhantomData;
use super::{AsyncBatchLoad, BatchError};
use crate::{
graphql::SqlDoor,
query::sql::{SqlQuery, rows},
transform::Identifiable,
};
pub struct SqlRows<Row, Db>
where
Db: sqlx::Database,
{
door: SqlDoor<Db>,
row: PhantomData<fn() -> Row>,
}
impl<Row, Db> SqlRows<Row, Db>
where
Db: sqlx::Database,
{
#[must_use]
#[inline]
pub const fn new(door: SqlDoor<Db>) -> Self {
Self {
door,
row: PhantomData,
}
}
#[must_use]
#[inline]
pub const fn door(&self) -> &SqlDoor<Db> {
&self.door
}
}
impl<Row, Db> Clone for SqlRows<Row, Db>
where
Db: sqlx::Database,
{
#[inline]
fn clone(&self) -> Self {
Self {
door: self.door.clone(),
row: PhantomData,
}
}
}
impl<Row, Db> core::fmt::Debug for SqlRows<Row, Db>
where
Db: sqlx::Database,
{
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("SqlRows")
.field("row", &core::any::type_name::<Row>())
.field("door", &self.door)
.finish()
}
}
impl<Row, Db> AsyncBatchLoad<<Row::Record as Identifiable>::Id> for SqlRows<Row, Db>
where
Row: SqlQuery<Db> + for<'r> sqlx::FromRow<'r, Db::Row> + Send + Sync,
Db: crate::query::sql::SqlDialect,
Db::Arguments: sqlx::IntoArguments<Db>,
for<'e> &'e mut Db::Connection: sqlx::Executor<'e, Database = Db>,
for<'p> &'p sqlx::Pool<Db>: crate::query::sql::BeginRead,
<Row::Record as Identifiable>::Id: Send + Sync,
{
type Value = Row;
#[allow(
clippy::manual_async_fn,
reason = "the seam declares `+ Send` and an `async fn`'s future does not prove it from outside \
— the engine spawns this one"
)]
fn load(
&self,
keys: &[<Row::Record as Identifiable>::Id],
) -> impl core::future::Future<
Output = Result<Vec<(<Row::Record as Identifiable>::Id, Row)>, BatchError>,
> + Send {
async move {
let gathered = rows::<Row, Db, _>(self.door.pool(), keys)
.await
.map_err(BatchError::new)?;
gathered
.into_iter()
.map(|row| {
let id = row
.id()
.map_err(|refusal| BatchError::new(crate::query::sql::SqlQueryError::from(refusal)))?;
Ok((id, row))
})
.collect()
}
}
}