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
use std::{ops::Deref, time::Duration};

use mithril_common::{
    resource_pool::{Reset, ResourcePool, ResourcePoolItem},
    StdResult,
};

use crate::sqlite::SqliteConnection;

/// SqliteConnection wrapper for a pooled connection
pub struct SqlitePooledConnection(SqliteConnection);

impl SqlitePooledConnection {
    /// Create a new SqlitePooledConnection
    pub fn new(connection: SqliteConnection) -> Self {
        Self(connection)
    }
}

impl Deref for SqlitePooledConnection {
    type Target = SqliteConnection;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl Reset for SqlitePooledConnection {}

/// Pool of Sqlite connections
pub struct SqliteConnectionPool {
    connection_pool: ResourcePool<SqlitePooledConnection>,
}

impl SqliteConnectionPool {
    /// Create a new pool with the given size by calling the given builder function
    pub fn build(
        size: usize,
        builder: impl Fn() -> StdResult<SqliteConnection>,
    ) -> StdResult<Self> {
        let mut connections: Vec<SqlitePooledConnection> = Vec::with_capacity(size);
        for _count in 0..size {
            connections.push(SqlitePooledConnection::new(builder()?));
        }

        Ok(Self {
            connection_pool: ResourcePool::new(connections.len(), connections),
        })
    }

    /// Get a connection from the pool
    pub fn connection(&self) -> StdResult<ResourcePoolItem<SqlitePooledConnection>> {
        let timeout = Duration::from_millis(1000);
        let connection = self.connection_pool.acquire_resource(timeout)?;

        Ok(connection)
    }

    /// Returns a single resource pool connection
    pub fn build_from_connection(connection: SqliteConnection) -> Self {
        let connection_pool = ResourcePool::new(1, vec![SqlitePooledConnection::new(connection)]);

        Self { connection_pool }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::database::test_helper::cardano_tx_db_connection;

    #[test]
    fn can_build_pool_of_given_size() {
        let pool = SqliteConnectionPool::build(10, cardano_tx_db_connection).unwrap();

        assert_eq!(pool.connection_pool.size(), 10);
    }
}