surrealdb/api/method/
content.rs

1use crate::api::conn::Command;
2use crate::api::method::BoxFuture;
3use crate::api::Connection;
4use crate::api::Result;
5use crate::method::OnceLockExt;
6use crate::sql::Value;
7use crate::Surreal;
8use serde::de::DeserializeOwned;
9use std::borrow::Cow;
10use std::future::IntoFuture;
11use std::marker::PhantomData;
12
13/// A content future
14///
15/// Content inserts or replaces the contents of a record entirely
16#[derive(Debug)]
17#[must_use = "futures do nothing unless you `.await` or poll them"]
18pub struct Content<'r, C: Connection, R> {
19	pub(super) client: Cow<'r, Surreal<C>>,
20	pub(super) command: Result<Command>,
21	pub(super) response_type: PhantomData<R>,
22}
23
24impl<'r, C, R> Content<'r, C, R>
25where
26	C: Connection,
27{
28	pub(crate) fn from_closure<F>(client: Cow<'r, Surreal<C>>, f: F) -> Self
29	where
30		F: FnOnce() -> Result<Command>,
31	{
32		Content {
33			client,
34			command: f(),
35			response_type: PhantomData,
36		}
37	}
38
39	/// Converts to an owned type which can easily be moved to a different thread
40	pub fn into_owned(self) -> Content<'static, C, R> {
41		Content {
42			client: Cow::Owned(self.client.into_owned()),
43			..self
44		}
45	}
46}
47
48macro_rules! into_future {
49	($method:ident) => {
50		fn into_future(self) -> Self::IntoFuture {
51			let Content {
52				client,
53				command,
54				..
55			} = self;
56			Box::pin(async move {
57				let router = client.router.extract()?;
58				router.$method(command?).await
59			})
60		}
61	};
62}
63
64impl<'r, Client> IntoFuture for Content<'r, Client, Value>
65where
66	Client: Connection,
67{
68	type Output = Result<Value>;
69	type IntoFuture = BoxFuture<'r, Self::Output>;
70
71	into_future! {execute_value}
72}
73
74impl<'r, Client, R> IntoFuture for Content<'r, Client, Option<R>>
75where
76	Client: Connection,
77	R: DeserializeOwned,
78{
79	type Output = Result<Option<R>>;
80	type IntoFuture = BoxFuture<'r, Self::Output>;
81
82	into_future! {execute_opt}
83}
84
85impl<'r, Client, R> IntoFuture for Content<'r, Client, Vec<R>>
86where
87	Client: Connection,
88	R: DeserializeOwned,
89{
90	type Output = Result<Vec<R>>;
91	type IntoFuture = BoxFuture<'r, Self::Output>;
92
93	into_future! {execute_vec}
94}