Skip to main content

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> ConnectionExt for DbConnection<C>
29where
30    C: ConnectionExt,
31{
32    fn raw_query<T, F>(&self, fun: F) -> Result<T, crate::ConnectionError>
33    where
34        F: FnOnce(&mut SqliteConnection) -> Result<T, diesel::result::Error>,
35        Self: Sized,
36    {
37        self.conn.raw_query(fun)
38    }
39
40    fn disconnect(&self) -> Result<(), crate::ConnectionError> {
41        self.conn.disconnect()
42    }
43
44    fn reconnect(&self) -> Result<(), crate::ConnectionError> {
45        self.conn.reconnect()
46    }
47}
48
49// Forces a move for conn
50// This is an important distinction from deriving `Clone` on `DbConnection`.
51// This way, conn will be moved into XmtpOpenMlsProvider. This forces codepaths to
52// use a connection from the provider, rather than pulling a new one from the pool, resulting
53// in two connections in the same scope.
54impl<C: ConnectionExt> From<DbConnection<C>> for XmtpOpenMlsProvider<SqlKeyStore<C>> {
55    fn from(db: DbConnection<C>) -> XmtpOpenMlsProvider<SqlKeyStore<C>> {
56        XmtpOpenMlsProvider::new(SqlKeyStore::new(db.conn))
57    }
58}
59
60impl<C> fmt::Debug for DbConnection<C> {
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        f.debug_struct("DbConnection")
63            .field("wrapped_conn", &"DbConnection")
64            .finish()
65    }
66}