xmtp_db/encrypted_store/
db_connection.rs

1use diesel::SqliteConnection;
2
3use crate::{sql_key_store::SqlKeyStore, xmtp_openmls_provider::XmtpOpenMlsProvider};
4use std::fmt;
5
6use super::ConnectionExt;
7
8/// A wrapper for RawDbConnection that houses all XMTP DB operations.
9#[derive(Clone)]
10pub struct DbConnection<C> {
11    pub(super) conn: C,
12}
13
14impl<C> DbConnection<C> {
15    pub fn new(conn: C) -> Self {
16        Self { conn }
17    }
18}
19
20impl<C: ConnectionExt> crate::IntoConnection for DbConnection<C> {
21    type Connection = C;
22
23    fn into_connection(self) -> Self::Connection {
24        self.conn
25    }
26}
27
28impl<C> DbConnection<C>
29where
30    C: ConnectionExt,
31{
32    pub fn raw_query_read<T, F>(&self, fun: F) -> Result<T, crate::ConnectionError>
33    where
34        F: FnOnce(&mut SqliteConnection) -> Result<T, diesel::result::Error>,
35    {
36        <Self as ConnectionExt>::raw_query_read::<_, _>(self, fun)
37    }
38
39    pub fn raw_query_write<T, F>(&self, fun: F) -> Result<T, crate::ConnectionError>
40    where
41        F: FnOnce(&mut SqliteConnection) -> Result<T, diesel::result::Error>,
42    {
43        <Self as ConnectionExt>::raw_query_write::<_, _>(self, fun)
44    }
45}
46
47impl<C> ConnectionExt for DbConnection<C>
48where
49    C: ConnectionExt,
50{
51    fn raw_query_read<T, F>(&self, fun: F) -> Result<T, crate::ConnectionError>
52    where
53        F: FnOnce(&mut SqliteConnection) -> Result<T, diesel::result::Error>,
54        Self: Sized,
55    {
56        self.conn.raw_query_read(fun)
57    }
58
59    fn raw_query_write<T, F>(&self, fun: F) -> Result<T, crate::ConnectionError>
60    where
61        F: FnOnce(&mut SqliteConnection) -> Result<T, diesel::result::Error>,
62        Self: Sized,
63    {
64        self.conn.raw_query_write(fun)
65    }
66
67    fn disconnect(&self) -> Result<(), crate::ConnectionError> {
68        self.conn.disconnect()
69    }
70
71    fn reconnect(&self) -> Result<(), crate::ConnectionError> {
72        self.conn.reconnect()
73    }
74}
75
76// Forces a move for conn
77// This is an important distinction from deriving `Clone` on `DbConnection`.
78// This way, conn will be moved into XmtpOpenMlsProvider. This forces codepaths to
79// use a connection from the provider, rather than pulling a new one from the pool, resulting
80// in two connections in the same scope.
81impl<C: ConnectionExt> From<DbConnection<C>> for XmtpOpenMlsProvider<SqlKeyStore<C>> {
82    fn from(db: DbConnection<C>) -> XmtpOpenMlsProvider<SqlKeyStore<C>> {
83        XmtpOpenMlsProvider::new(SqlKeyStore::new(db.conn))
84    }
85}
86
87impl<C> fmt::Debug for DbConnection<C> {
88    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89        f.debug_struct("DbConnection")
90            .field("wrapped_conn", &"DbConnection")
91            .finish()
92    }
93}