Coverage Report

Created: 2024-02-20 21:15

/builds/xfbs/cindy/src/database.rs
Line
Count
Source
1
use crate::{
2
    hash::{BoxHash, Hash},
3
    tag::Tag,
4
};
5
use anyhow::Result;
6
use rusqlite::{Connection, Error, Transaction};
7
use std::{collections::BTreeSet, ops::Deref};
8
9
pub const SQLITE_SCHEMA: &str = include_str!("database/schema.sql");
10
11
mod handlers;
12
#[cfg(test)]
13
mod tests;
14
15
/// Handle to database.
16
pub trait Handle {
17
    /// Provide a connection to the database.
18
    fn connection(&self) -> &Connection;
19
}
20
21
impl Handle for Connection {
22
97.3k
    fn connection(&self) -> &Connection {
23
97.3k
        self
24
97.3k
    }
25
}
26
27
impl<'a> Handle for Transaction<'a> {
28
261
    fn connection(&self) -> &Connection {
29
261
        self.deref()
30
261
    }
31
}
32
33
/// Database wrapper.
34
///
35
/// Dereferences to a [`Connection`], but provides additional methods.
36
1
#[derive(Debug)]
37
pub struct Database<T = Connection>(T);
38
39
impl Database<Connection> {
40
26
    pub fn transaction(&mut self) -> Result<Database<Transaction<'_>>, Error> {
41
26
        self.0.transaction().map(Database)
42
26
    }
43
}
44
45
impl Database<Transaction<'_>> {
46
25
    pub fn commit(self) -> Result<(), Error> {
47
25
        self.0.commit()
48
25
    }
49
50
1
    pub fn abort(self) -> Result<()> {
51
1
        Ok(())
52
1
    }
53
}
54
55
impl<T: Handle> From<T> for Database<T> {
56
29
    fn from(backend: T) -> Self {
57
29
        Self(backend)
58
29
    }
59
}
60
61
impl<T: Handle> Deref for Database<T> {
62
    type Target = Connection;
63
64
97.5k
    fn deref(&self) -> &Self::Target {
65
97.5k
        self.0.connection()
66
97.5k
    }
67
}
68
69
1
#[test]
70
1
fn test_transaction() {
71
1
    let mut connection: Database = Connection::open_in_memory().unwrap().into();
72
1
    format!("{connection:?}");
73
1
    connection.execute("PRAGMA foreign_keys=ON", ()).unwrap();
74
1
    let transaction = connection.transaction().unwrap();
75
1
    transaction.abort().unwrap();
76
1
    let transaction = connection.transaction().unwrap();
77
1
    transaction.execute("PRAGMA foreign_keys=ON", ()).unwrap();
78
1
    transaction.commit().unwrap();
79
1
}