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
use dbui_core::database::conn::ConnectionParams;
use dbui_core::{Error, Result, ResultExt};

use postgres::Client;
use r2d2_postgres::PostgresConnectionManager;
use tokio_postgres::types::FromSql;

/// Wrapper class containing a url and an [r2d2](r2d2_postgres) connection pool
#[derive(Debug)]
pub struct ConnectionPool {
  url: String,
  pool: r2d2::Pool<PostgresConnectionManager>
}

impl ConnectionPool {
  pub fn new(conn: &ConnectionParams) -> Result<ConnectionPool> {
    let url = get_url(conn)?;
    let manager =
      PostgresConnectionManager::new(url.clone(), r2d2_postgres::TlsMode::None).chain_err(|| "Can't create database manager")?;
    let pool = r2d2::Pool::new(manager).chain_err(|| "Can't create database pool")?;
    Ok(ConnectionPool { url, pool })
  }

  pub fn open(&self) -> Result<Client> {
    Client::connect(&self.url, postgres::NoTls).chain_err(|| format!("Unable to connect to [{}]", self.url))
  }
}

pub(crate) fn get<'a, T: FromSql<'a>>(row: &'a postgres::row::Row, key: &str) -> Result<T> {
  let o: Result<T> = row
    .try_get(key)
    .map_err(|e| Error::from(format!("Unable to read [{}]: {}", key, e)));
  o
}

pub(crate) fn get_idx<'a, T: FromSql<'a>>(row: &'a postgres::row::Row, idx: usize) -> Result<T> {
  let o: Result<T> = row
    .try_get(idx)
    .map_err(|e| Error::from(format!("Unable to read [{}]: {}", idx, e)));
  o
}

fn get_url(conn: &ConnectionParams) -> Result<String> {
  let port_str = conn.port().map(|x| format!(":{}", x)).unwrap_or_else(|| "".to_string());
  let password = match conn.password() {
    Some(pw) if pw.starts_with("=/=") => Some(crate::crypto::decrypt("dbui", &pw[3..])?),
    Some(pw) => Some(pw.into()),
    None => None
  };
  let user_pass = password
    .as_ref()
    .map(|p| format!("{}:{}", &conn.user(), p))
    .unwrap_or_else(|| conn.user().to_string());
  Ok(format!("postgres://{}@{}{}", &user_pass, &conn.server(), &port_str))
}