1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
use {
    crate::{table::Schema, Error, Transaction},
    std::path::Path,
};

#[derive(Clone, Debug)]
pub enum Pool {
    #[cfg(feature = "postgresql")]
    PostgreSQL(r2d2::Pool<self::postgres::PostgresConnectionManager<::postgres::NoTls>>),
    #[cfg(feature = "sqlite")]
    SQLite(r2d2::Pool<self::sqlite::SqliteConnectionManager>),
}

impl Pool {
    #[cfg(feature = "postgresql")]
    pub fn postgres(config: ::postgres::Config) -> Result<Self, Error> {
        let conn = Pool::PostgreSQL(r2d2::Pool::new(
            crate::pool::postgres::PostgresConnectionManager::new(config, ::postgres::NoTls),
        )?);

        Ok(conn)
    }

    #[cfg(feature = "sqlite")]
    pub fn sqlite(path: impl AsRef<Path>) -> Result<Self, Error> {
        let conn = Pool::SQLite(r2d2::Pool::new(
            crate::pool::sqlite::SqliteConnectionManager::file(path),
        )?);

        Ok(conn)
    }

    pub fn as_kind(&self) -> PoolKind {
        match self {
            #[cfg(feature = "postgresql")]
            Pool::PostgreSQL(_) => PoolKind::PostgreSQL,
            #[cfg(feature = "sqlite")]
            Pool::SQLite(_) => PoolKind::SQLite,
        }
    }

    pub fn batch_execute(&self, exec: impl AsRef<str>) -> Result<(), Error> {
        match self {
            #[cfg(feature = "postgresql")]
            Pool::PostgreSQL(pool) => {
                let mut conn = pool.get()?;

                conn.batch_execute(exec.as_ref())?;
            }
            #[cfg(feature = "sqlite")]
            Pool::SQLite(pool) => {
                let conn = pool.get()?;

                conn.execute_batch(exec.as_ref())?;
            }
        }

        Ok(())
    }

    pub fn transaction(
        &self,
        run: impl FnOnce(Transaction<'_>) -> Result<(), Error>,
    ) -> Result<(), Error> {
        match self {
            #[cfg(feature = "postgresql")]
            Pool::PostgreSQL(pool) => {
                let mut conn = pool.get()?;

                let trans = conn.transaction()?;

                let inner = Transaction::PostgreSQL(trans);

                run(inner)?;
            }
            #[cfg(feature = "sqlite")]
            Pool::SQLite(pool) => {
                let mut conn = pool.get()?;

                let trans = conn.transaction()?;

                let inner = Transaction::SQLite(trans);

                run(inner)?;
            }
        }

        Ok(())
    }

    pub fn schema<T: Schema>(&self) -> Result<(), Error> {
        match self {
            #[cfg(feature = "postgresql")]
            Pool::PostgreSQL(pool) => {
                let mut conn = pool.get()?;

                conn.batch_execute(T::schema_postgres())?;
            }
            #[cfg(feature = "sqlite")]
            Pool::SQLite(pool) => {
                let conn = pool.get()?;

                conn.execute_batch(T::schema_sqlite())?;
            }
        }

        Ok(())
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum PoolKind {
    #[cfg(feature = "postgresql")]
    PostgreSQL,
    #[cfg(feature = "sqlite")]
    SQLite,
}

impl From<Pool> for PoolKind {
    fn from(pool: Pool) -> PoolKind {
        pool.as_kind()
    }
}

impl<'a> From<&'a Pool> for PoolKind {
    fn from(pool: &'a Pool) -> PoolKind {
        pool.as_kind()
    }
}

#[cfg(feature = "postgresql")]
pub mod postgres {
    use {
        postgres::{
            tls::{MakeTlsConnect, TlsConnect},
            Client, Config, Error, Socket,
        },
        r2d2::ManageConnection,
    };

    #[derive(Debug)]
    pub struct PostgresConnectionManager<T> {
        config: Config,
        tls_connector: T,
    }

    impl<T> PostgresConnectionManager<T>
    where
        T: MakeTlsConnect<Socket> + Clone + 'static + Sync + Send,
        T::TlsConnect: Send,
        T::Stream: Send,
        <T::TlsConnect as TlsConnect<Socket>>::Future: Send,
    {
        /// Creates a new `PostgresConnectionManager`.
        pub fn new(config: Config, tls_connector: T) -> PostgresConnectionManager<T> {
            PostgresConnectionManager {
                config,
                tls_connector,
            }
        }
    }

    impl<T> ManageConnection for PostgresConnectionManager<T>
    where
        T: MakeTlsConnect<Socket> + Clone + 'static + Sync + Send,
        T::TlsConnect: Send,
        T::Stream: Send,
        <T::TlsConnect as TlsConnect<Socket>>::Future: Send,
    {
        type Connection = Client;
        type Error = Error;

        fn connect(&self) -> Result<Client, Error> {
            self.config.connect(self.tls_connector.clone())
        }

        fn is_valid(&self, client: &mut Client) -> Result<(), Error> {
            client.simple_query("").map(|_| ())
        }

        fn has_broken(&self, client: &mut Client) -> bool {
            client.is_closed()
        }
    }
}

#[cfg(feature = "sqlite")]
pub mod sqlite {
    use {
        rusqlite::{Connection, Error, OpenFlags},
        std::{
            fmt,
            path::{Path, PathBuf},
        },
    };

    pub struct SqliteConnectionManager {
        path: PathBuf,
    }

    impl fmt::Debug for SqliteConnectionManager {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            let mut builder = f.debug_struct("SqliteConnectionManager");
            let _ = builder.field("path", &self.path);
            builder.finish()
        }
    }

    impl SqliteConnectionManager {
        pub fn file<P: AsRef<Path>>(path: P) -> Self {
            Self {
                path: path.as_ref().to_path_buf(),
            }
        }
    }

    impl r2d2::ManageConnection for SqliteConnectionManager {
        type Connection = Connection;
        type Error = rusqlite::Error;

        fn connect(&self) -> Result<Connection, Error> {
            Connection::open_with_flags(&self.path, OpenFlags::default()).map_err(Into::into)
        }

        fn is_valid(&self, conn: &mut Connection) -> Result<(), Error> {
            conn.execute_batch("").map_err(Into::into)
        }

        fn has_broken(&self, _: &mut Connection) -> bool {
            false
        }
    }
}