surrealdb/method/
transaction.rs1use 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#[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 pub fn commit(self) -> Commit<C> {
23 Commit::from_transaction(self)
24 }
25
26 pub fn cancel(self) -> Cancel<C> {
28 Cancel::from_transaction(self)
29 }
30
31 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 pub fn select<O>(&'_ self, resource: impl IntoResource<O>) -> Select<'_, C, O> {
38 self.client.select(resource).with_transaction(self.id)
39 }
40
41 pub fn create<R>(&'_ self, resource: impl CreateResource<R>) -> Create<'_, C, R> {
43 self.client.create(resource).with_transaction(self.id)
44 }
45
46 pub fn insert<O>(&'_ self, resource: impl IntoResource<O>) -> Insert<'_, C, O> {
48 self.client.insert(resource).with_transaction(self.id)
49 }
50
51 pub fn upsert<O>(&'_ self, resource: impl IntoResource<O>) -> Upsert<'_, C, O> {
53 self.client.upsert(resource).with_transaction(self.id)
54 }
55
56 pub fn update<O>(&'_ self, resource: impl IntoResource<O>) -> Update<'_, C, O> {
58 self.client.update(resource).with_transaction(self.id)
59 }
60
61 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}