Skip to main content

surrealdb/method/
transaction.rs

1use std::borrow::Cow;
2
3use uuid::Uuid;
4
5use crate::method::{Cancel, Commit, Create, Delete, Insert, Query, Select, Update, Upsert};
6use crate::opt::{CreateResource, IntoResource};
7use crate::{Connection, Surreal};
8
9/// An ongoing transaction
10#[derive(Debug)]
11#[must_use = "transactions must be committed or cancelled to complete them"]
12pub struct Transaction<C: Connection> {
13	pub(crate) id: Uuid,
14	pub(crate) client: Surreal<C>,
15}
16
17impl<C> Transaction<C>
18where
19	C: Connection,
20{
21	/// Creates a commit future
22	pub fn commit(self) -> Commit<C> {
23		Commit::from_transaction(self)
24	}
25
26	/// Creates a cancel future
27	pub fn cancel(self) -> Cancel<C> {
28		Cancel::from_transaction(self)
29	}
30
31	/// See [Surreal::query]
32	pub fn query<'client>(&'client self, query: impl Into<Cow<'client, str>>) -> Query<'client, C> {
33		self.client.query(query).with_transaction(self.id)
34	}
35
36	/// See [Surreal::select]
37	pub fn select<O>(&'_ self, resource: impl IntoResource<O>) -> Select<'_, C, O> {
38		self.client.select(resource).with_transaction(self.id)
39	}
40
41	/// See [Surreal::create]
42	pub fn create<R>(&'_ self, resource: impl CreateResource<R>) -> Create<'_, C, R> {
43		self.client.create(resource).with_transaction(self.id)
44	}
45
46	/// See [Surreal::insert]
47	pub fn insert<O>(&'_ self, resource: impl IntoResource<O>) -> Insert<'_, C, O> {
48		self.client.insert(resource).with_transaction(self.id)
49	}
50
51	/// See [Surreal::upsert]
52	pub fn upsert<O>(&'_ self, resource: impl IntoResource<O>) -> Upsert<'_, C, O> {
53		self.client.upsert(resource).with_transaction(self.id)
54	}
55
56	/// See [Surreal::update]
57	pub fn update<O>(&'_ self, resource: impl IntoResource<O>) -> Update<'_, C, O> {
58		self.client.update(resource).with_transaction(self.id)
59	}
60
61	/// See [Surreal::delete]
62	pub fn delete<O>(&'_ self, resource: impl IntoResource<O>) -> Delete<'_, C, O> {
63		self.client.delete(resource).with_transaction(self.id)
64	}
65}
66
67pub(super) trait WithTransaction {
68	fn with_transaction(self, id: Uuid) -> Self;
69}