Skip to main content

lockbook_server_lib/
guard.rs

1use db_rs::View;
2use db_rs::errors::Result;
3use db_rs::guard::WriteTx;
4use std::ops::{Deref, DerefMut};
5
6use crate::schema::{ServerDb, ServerV6};
7
8#[must_use]
9pub struct ServerTx<'a> {
10    db: &'a mut ServerDb,
11    tx: Option<WriteTx>,
12}
13
14impl<'a> ServerTx<'a> {
15    pub fn begin(db: &'a mut ServerDb) -> Result<Self> {
16        let tx = db.write_tx()?;
17        Ok(Self { db, tx: Some(tx) })
18    }
19
20    pub fn end(mut self) -> Result<()> {
21        self.tx.take().unwrap().end_tx(self.db).map(|_| ())
22    }
23}
24
25impl Deref for ServerTx<'_> {
26    type Target = ServerV6;
27
28    fn deref(&self) -> &Self::Target {
29        &self.db.schema
30    }
31}
32
33impl DerefMut for ServerTx<'_> {
34    fn deref_mut(&mut self) -> &mut Self::Target {
35        &mut self.db.schema
36    }
37}
38
39impl Drop for ServerTx<'_> {
40    fn drop(&mut self) {
41        if let Some(tx) = self.tx.take() {
42            if let Err(error) = tx.end_tx(self.db) {
43                tracing::error!(?error, "failed to flush database transaction on drop");
44            }
45        }
46    }
47}