koibumi_node/
db.rs

1//! Provides wrappers for database interfaces.
2
3use futures::join;
4use sqlx::{Connection, Database, Error, Pool, Sqlite};
5
6/// Writer and reader connection pools for SQLite.
7#[derive(Clone, Debug)]
8pub struct SqlitePool {
9    writer: Pool<Sqlite>,
10    reader: Pool<Sqlite>,
11}
12
13impl SqlitePool {
14    /// Returns the reader pool.
15    pub fn read(&self) -> &Pool<Sqlite> {
16        &self.reader
17    }
18
19    /// Returns the writer pool.
20    pub fn write(&self) -> &Pool<Sqlite> {
21        &self.writer
22    }
23
24    /// Creates a new connection pool with a default pool configuration and the given connection options;
25    /// and, immediately establishes one connection.
26    pub async fn connect_with(
27        options: <<Sqlite as Database>::Connection as Connection>::Options,
28    ) -> Result<Self, Error> {
29        let writer = sqlx::pool::PoolOptions::new()
30            .max_connections(1)
31            .connect_with(options.clone())
32            .await?;
33        let reader = sqlx::Pool::connect_with(options.read_only(true)).await?;
34        Ok(Self { writer, reader })
35    }
36
37    /// Ends the use of a connection pool.
38    /// Prevents any new connections and will close all active connections when they are returned to the pool.
39    ///
40    /// Does not resolve until all connections are closed.
41    pub async fn close(&'_ self) -> ((), ()) {
42        join!(self.writer.close(), self.reader.close())
43    }
44}