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
83
/**
 * Connection configuration.
 */
#[derive(Clone, Debug)]
pub struct Config {
    pub host: Option<String>,
    pub user: Option<String>,
    pub dbname: Option<String>,
    pub port: Option<String>,
    pub password: Option<String>,
}

macro_rules! get {
    ($config:ident . $field:ident, $env:expr, $default:expr) => {
        $config
            .$field
            .clone()
            .or(std::env::var($env).ok())
            .unwrap_or_else(|| $default)
    };
}

impl Config {
    pub fn new() -> Self {
        Config {
            host: None,
            dbname: None,
            user: None,
            port: None,
            password: None,
        }
    }

    pub fn user(&self) -> String {
        get!(self.user, "PGUSER", std::env::var("USER").unwrap())
    }

    pub fn host(&self) -> String {
        get!(self.host, "PGHOST", "/run/postgresql".to_string())
    }

    pub fn dbname(&self) -> String {
        get!(self.dbname, "PGDATABASE", self.user())
    }

    pub fn port(&self) -> String {
        get!(self.port, "PGPORT", "5432".to_string())
    }

    pub fn password(&self) -> Option<String> {
        self.password
            .clone()
            .or_else(|| std::env::var("PGPASSWORD").ok())
            .or_else(|| {
                let pgpass = crate::PgPass::from_file();
                pgpass.find(
                    &self.host(),
                    &self.port(),
                    &self.dbname(),
                    &self.user(),
                )
            })
    }
}

impl Default for Config {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Display for Config {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(password) = self.password() {
            write!(f, "password={} ", password)?;
        }

        write!(f, "host={} ", self.host())?;
        write!(f, "user={} ", self.user())?;
        write!(f, "dbname={} ", self.dbname())?;
        write!(f, "port={} ", self.port())
    }
}