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
//! Provides wrappers for database interfaces.

use futures::join;
use sqlx::{Connection, Database, Error, Pool, Sqlite};

/// Writer and reader connection pools for SQLite.
#[derive(Clone, Debug)]
pub struct SqlitePool {
    writer: Pool<Sqlite>,
    reader: Pool<Sqlite>,
}

impl SqlitePool {
    /// Returns the reader pool.
    pub fn read(&self) -> &Pool<Sqlite> {
        &self.reader
    }

    /// Returns the writer pool.
    pub fn write(&self) -> &Pool<Sqlite> {
        &self.writer
    }

    /// Creates a new connection pool with a default pool configuration and the given connection options;
    /// and, immediately establishes one connection.
    pub async fn connect_with(
        options: <<Sqlite as Database>::Connection as Connection>::Options,
    ) -> Result<Self, Error> {
        let writer = sqlx::pool::PoolOptions::new()
            .max_connections(1)
            .connect_with(options.clone())
            .await?;
        let reader = sqlx::Pool::connect_with(options.read_only(true)).await?;
        Ok(Self { writer, reader })
    }

    /// Ends the use of a connection pool.
    /// Prevents any new connections and will close all active connections when they are returned to the pool.
    ///
    /// Does not resolve until all connections are closed.
    pub async fn close(&'_ self) -> ((), ()) {
        join!(self.writer.close(), self.reader.close())
    }
}