Skip to main content

monoio_pg/
pool.rs

1use crate::client::Client;
2use crate::error::Result;
3use std::cell::RefCell;
4use std::collections::VecDeque;
5
6thread_local! {
7    static POOL: RefCell<VecDeque<Client>> = RefCell::new(VecDeque::new());
8}
9
10pub struct Pool {
11    addr: String,
12    user: String,
13    password: Option<String>,
14    database: Option<String>,
15}
16
17impl Pool {
18    pub fn new(addr: &str, user: &str, password: Option<&str>, database: Option<&str>) -> Self {
19        Self {
20            addr: addr.to_string(),
21            user: user.to_string(),
22            password: password.map(|s| s.to_string()),
23            database: database.map(|s| s.to_string()),
24        }
25    }
26
27    pub async fn get(&self) -> Result<Client> {
28        if let Some(client) = POOL.with(|p| p.borrow_mut().pop_front()) {
29            return Ok(client);
30        }
31        Client::connect(
32            &self.addr,
33            &self.user,
34            self.password.as_deref(),
35            self.database.as_deref(),
36        )
37        .await
38    }
39
40    pub fn put(&self, client: Client) {
41        POOL.with(|p| p.borrow_mut().push_back(client));
42    }
43}