surrealdb/api/method/
begin.rs

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