use std::borrow::Cow;
use std::future::IntoFuture;
use std::marker::PhantomData;
use uuid::Uuid;
use super::transaction::WithTransaction;
use crate::conn::Command;
use crate::method::{BoxFuture, Live, OnceLockExt};
use crate::opt::Resource;
use crate::types::{RecordIdKeyRange, SurrealValue, Value, Variables};
use crate::{Connection, Result, Surreal};
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct Select<'r, C: Connection, R, T = ()> {
pub(super) txn: Option<Uuid>,
pub(super) client: Cow<'r, Surreal<C>>,
pub(super) resource: Result<Resource>,
pub(super) response_type: PhantomData<R>,
pub(super) query_type: PhantomData<T>,
}
impl<C, R, T> WithTransaction for Select<'_, C, R, T>
where
C: Connection,
{
fn with_transaction(mut self, id: Uuid) -> Self {
self.txn = Some(id);
self
}
}
impl<C, R, T> Select<'_, C, R, T>
where
C: Connection,
{
pub fn into_owned(self) -> Select<'static, C, R, T> {
Select {
client: Cow::Owned(self.client.into_owned()),
..self
}
}
}
macro_rules! into_future {
($method:ident) => {
fn into_future(self) -> Self::IntoFuture {
let Select {
txn,
client,
resource,
..
} = self;
Box::pin(async move {
let router = client.inner.router.extract()?;
let what = resource?;
let mut variables = Variables::new();
let what = what.for_sql_query(&mut variables)?;
router
.$method(
client.session_id,
Command::Query {
txn,
query: Cow::Owned(format!("SELECT * FROM {what}")),
variables,
},
)
.await
})
}
};
}
impl<'r, Client> IntoFuture for Select<'r, Client, Value>
where
Client: Connection,
{
type Output = Result<Value>;
type IntoFuture = BoxFuture<'r, Self::Output>;
into_future! {execute_value}
}
impl<'r, Client, R> IntoFuture for Select<'r, Client, Option<R>>
where
Client: Connection,
R: SurrealValue,
{
type Output = Result<Option<R>>;
type IntoFuture = BoxFuture<'r, Self::Output>;
into_future! {execute_opt}
}
impl<'r, Client, R> IntoFuture for Select<'r, Client, Vec<R>>
where
Client: Connection,
R: SurrealValue,
{
type Output = Result<Vec<R>>;
type IntoFuture = BoxFuture<'r, Self::Output>;
into_future! {execute_vec}
}
impl<C> Select<'_, C, Value>
where
C: Connection,
{
pub fn range(mut self, range: impl Into<RecordIdKeyRange>) -> Self {
self.resource = self.resource.and_then(|x| x.with_range(range.into()));
self
}
}
impl<C, R> Select<'_, C, Vec<R>>
where
C: Connection,
{
pub fn range(mut self, range: impl Into<RecordIdKeyRange>) -> Self {
self.resource = self.resource.and_then(|x| x.with_range(range.into()));
self
}
}
impl<'r, C, R> Select<'r, C, R>
where
C: Connection,
R: SurrealValue,
{
pub fn live(self) -> Select<'r, C, R, Live> {
Select {
txn: self.txn,
client: self.client,
resource: self.resource,
response_type: self.response_type,
query_type: PhantomData,
}
}
}