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
79
80
81
82
use std::collections::HashMap;

#[derive(Debug)]
pub struct Pool {
    default: String,
    connections: HashMap<String, crate::Connection>,
}

impl Pool {
    pub fn new(url: &str) -> crate::Result<Self> {
        Self::default().add_default("default", url)
    }

    pub fn from_config(config: &crate::Config) -> crate::Result<Self> {
        Self::default().add_default("default", &config.to_string())
    }

    pub fn add_default(self, name: &str, url: &str) -> crate::Result<Self> {
        self.add(name, url, true)
    }

    pub fn add_connection(self, name: &str, url: &str) -> crate::Result<Self> {
        self.add(name, url, false)
    }

    fn add(
        mut self,
        name: &str,
        url: &str,
        default: bool,
    ) -> crate::Result<Self> {
        self.connections
            .insert(name.to_string(), crate::Connection::new(url)?);

        if default {
            self.set_default(name);
        }

        Ok(self)
    }

    pub fn get_default(&self) -> Option<&crate::Connection> {
        self.connections.get(&self.default)
    }

    pub fn set_default(&mut self, name: &str) {
        self.default = name.to_string();
    }

    pub fn get(&self, name: &str) -> Option<&crate::Connection> {
        self.connections.get(&name.to_string())
    }

    pub fn remove(&mut self, name: &str) {
        self.connections.remove(&name.to_string());
    }
}

impl Default for Pool {
    fn default() -> Self {
        Self {
            default: String::new(),
            connections: HashMap::new(),
        }
    }
}

impl std::ops::Index<&str> for Pool {
    type Output = crate::Connection;

    fn index(&self, index: &str) -> &Self::Output {
        self.get(index).unwrap()
    }
}

impl std::ops::Deref for Pool {
    type Target = crate::Connection;

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