surrealdb/api/method/
select.rsuse crate::api::conn::Method;
use crate::api::conn::Param;
use crate::api::method::OnceLockExt;
use crate::api::opt::Range;
use crate::api::opt::Resource;
use crate::api::Connection;
use crate::api::Result;
use crate::method::Live;
use crate::sql::Id;
use crate::sql::Value;
use crate::Surreal;
use serde::de::DeserializeOwned;
use std::borrow::Cow;
use std::future::Future;
use std::future::IntoFuture;
use std::marker::PhantomData;
use std::pin::Pin;
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct Select<'r, C: Connection, R, T = ()> {
pub(super) client: Cow<'r, Surreal<C>>,
pub(super) resource: Result<Resource>,
pub(super) range: Option<Range<Id>>,
pub(super) response_type: PhantomData<R>,
pub(super) query_type: PhantomData<T>,
}
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 {
client,
resource,
range,
..
} = self;
Box::pin(async move {
let param = match range {
Some(range) => resource?.with_range(range)?.into(),
None => resource?.into(),
};
let mut conn = Client::new(Method::Select);
conn.$method(client.router.extract()?, Param::new(vec![param])).await
})
}
};
}
impl<'r, Client> IntoFuture for Select<'r, Client, Value>
where
Client: Connection,
{
type Output = Result<Value>;
type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send + Sync + 'r>>;
into_future! {execute_value}
}
impl<'r, Client, R> IntoFuture for Select<'r, Client, Option<R>>
where
Client: Connection,
R: DeserializeOwned,
{
type Output = Result<Option<R>>;
type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send + Sync + 'r>>;
into_future! {execute_opt}
}
impl<'r, Client, R> IntoFuture for Select<'r, Client, Vec<R>>
where
Client: Connection,
R: DeserializeOwned,
{
type Output = Result<Vec<R>>;
type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send + Sync + 'r>>;
into_future! {execute_vec}
}
impl<'r, C> Select<'r, C, Value>
where
C: Connection,
{
pub fn range(mut self, bounds: impl Into<Range<Id>>) -> Self {
self.range = Some(bounds.into());
self
}
}
impl<'r, C, R> Select<'r, C, Vec<R>>
where
C: Connection,
{
pub fn range(mut self, bounds: impl Into<Range<Id>>) -> Self {
self.range = Some(bounds.into());
self
}
}
impl<'r, C, R> Select<'r, C, R>
where
C: Connection,
R: DeserializeOwned,
{
pub fn live(self) -> Select<'r, C, R, Live> {
Select {
client: self.client,
resource: self.resource,
range: self.range,
response_type: self.response_type,
query_type: PhantomData,
}
}
}