surrealdb/api/method/
begin.rs

1use std::future::IntoFuture;
2use std::ops::Deref;
3
4use crate::api::method::{BoxFuture, Cancel, Commit};
5use crate::api::{Connection, Result, Surreal};
6use crate::core::expr::TopLevelExpr;
7
8/// A beginning of a transaction
9#[derive(Debug)]
10#[must_use = "futures do nothing unless you `.await` or poll them"]
11pub struct Begin<C: Connection> {
12	pub(super) client: Surreal<C>,
13}
14
15impl<C> IntoFuture for Begin<C>
16where
17	C: Connection,
18{
19	type Output = Result<Transaction<C>>;
20	type IntoFuture = BoxFuture<'static, Self::Output>;
21
22	fn into_future(self) -> Self::IntoFuture {
23		Box::pin(async move {
24			self.client.query(TopLevelExpr::Begin).await?;
25			Ok(Transaction {
26				client: self.client,
27			})
28		})
29	}
30}
31
32/// An ongoing transaction
33#[derive(Debug)]
34#[must_use = "transactions must be committed or cancelled to complete them"]
35pub struct Transaction<C: Connection> {
36	client: Surreal<C>,
37}
38
39impl<C> Transaction<C>
40where
41	C: Connection,
42{
43	/// Creates a commit future
44	pub fn commit(self) -> Commit<C> {
45		Commit {
46			client: self.client,
47		}
48	}
49
50	/// Creates a cancel future
51	pub fn cancel(self) -> Cancel<C> {
52		Cancel {
53			client: self.client,
54		}
55	}
56}
57
58impl<C> Deref for Transaction<C>
59where
60	C: Connection,
61{
62	type Target = Surreal<C>;
63
64	fn deref(&self) -> &Self::Target {
65		&self.client
66	}
67}