Skip to main content

docbox_management/
database.rs

1/// docbox-database re-exports
2pub use docbox_core::database::*;
3
4use crate::config::AdminDatabaseConfiguration;
5
6/// Provider to get database access for the management tool
7///
8/// Expects that the access granted to the database is sufficient
9/// for creation and deletion of tables
10pub trait DatabaseProvider: Send + Sync + 'static {
11    /// Connect to the provided `database` providing back a [DbPool]
12    fn connect(&self, database: &str) -> impl Future<Output = DbResult<DbPool>> + Send;
13}
14
15pub struct CloseOnDrop(DbPool);
16
17pub fn close_pool_on_drop(pool: &DbPool) -> CloseOnDrop {
18    CloseOnDrop(pool.clone())
19}
20
21impl Drop for CloseOnDrop {
22    fn drop(&mut self) {
23        let pool = self.0.clone();
24
25        tokio::spawn(async move {
26            tracing::debug!("closing dropped pool");
27            pool.close().await;
28            tracing::debug!("closed dropped pool");
29        });
30    }
31}
32
33pub struct ServerDatabaseProvider {
34    pub config: AdminDatabaseConfiguration,
35    pub username: String,
36    pub password: String,
37}
38
39impl DatabaseProvider for ServerDatabaseProvider {
40    fn connect(&self, database: &str) -> impl Future<Output = DbResult<DbPool>> + Send {
41        let options = PgConnectOptions::new()
42            .host(&self.config.host)
43            .port(self.config.port)
44            .username(&self.username)
45            .password(&self.password)
46            .database(database);
47
48        PgPool::connect_with(options)
49    }
50}