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
extern crate postgres;
extern crate serde;

use postgres::{Connection, TlsMode};
use serde::{Deserialize, Serialize};

#[derive(Debug, Deserialize, Serialize)]
pub struct ConnectionParams {
  pub server: String,
  pub port: Option<i32>,
  pub database: String,
  pub user: String,
  pub password: Option<String>,
  pub tls: bool
}

impl ConnectionParams {
  fn url(&self) -> String {
    let port = self.port.map(|x| format!(":{}", x)).unwrap_or_else(|| "".to_string());
    let user_pass = self.password.as_ref().map(|p| format!("{}:{}", &self.user, p)).unwrap_or_else(|| self.user.to_string());
    format!("postgres://{}@{}{}", &user_pass, &self.server, &port)
  }
}

impl Default for ConnectionParams {
  fn default() -> ConnectionParams {
    ConnectionParams {
      server: String::from("localhost"),
      port: None,
      database: String::from("postgres"),
      user: String::from("postgres"),
      password: None,
      tls: false
    }
  }
}

pub fn open(conn: ConnectionParams) -> Connection {
  Connection::connect(conn.url(), TlsMode::None).unwrap()
}

pub fn test() -> Connection {
    let conn = ConnectionParams {
    database: String::from("dbui"),
    user: String::from("dbui"),
    password: Some(String::from("dbui")),
    ..Default::default()
  };

  open(conn)
}