teo_mongodb_connector/connector/
owned_session.rs1use std::sync::Arc;
2use mongodb::ClientSession;
3use teo_result::{Result, Error};
4
5#[derive(Debug)]
6pub struct OwnedSessionInner {
7 session: * mut ClientSession,
8}
9
10impl OwnedSessionInner {
11 pub fn new(session: ClientSession) -> Self {
12 let boxed = Box::new(session);
13 Self { session: Box::into_raw(boxed) }
14 }
15
16 pub fn session_mut(&self) -> &mut ClientSession {
17 unsafe { &mut *self.session }
18 }
19}
20
21impl Drop for OwnedSessionInner {
22 fn drop(&mut self) {
23 let _ = unsafe { Box::from_raw(self.session) };
24 }
25}
26
27unsafe impl Send for OwnedSessionInner { }
28unsafe impl Sync for OwnedSessionInner { }
29
30#[derive(Clone, Debug)]
31pub struct OwnedSession {
32 inner: Arc<OwnedSessionInner>,
33}
34
35impl OwnedSession {
36
37 pub fn new(client_session: ClientSession) -> Self {
38 Self { inner: Arc::new(OwnedSessionInner::new(client_session)) }
39 }
40
41 pub fn client_session(&self) -> &mut ClientSession {
42 self.inner.session_mut()
43 }
44
45 pub async fn start_transaction(&self) -> Result<()> {
46 match self.inner.session_mut().start_transaction(None).await {
47 Ok(_) => Ok(()),
48 Err(e) => Err(Error::new(e.to_string())),
49 }
50 }
51
52 pub async fn commit_transaction(&self) -> Result<()> {
53 match self.inner.session_mut().commit_transaction().await {
54 Ok(_) => Ok(()),
55 Err(e) => Err(Error::new(e.to_string())),
56 }
57 }
58
59 pub async fn abort_transaction(&self) -> Result<()> {
60 match self.inner.session_mut().abort_transaction().await {
61 Ok(_) => Ok(()),
62 Err(e) => Err(Error::new(e.to_string())),
63 }
64 }
65}