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
use postgres::config::Config as PsqlConfig;
use postgres::Client as PsqlClient;

use crate::common::types::ResultAnyError;

#[derive(thiserror::Error, Debug)]
pub enum PsqlConnectionError {
  #[error("Error when initialization connection {0}")]
  InitializeConnectionError(String),
}

pub struct PsqlConnection {
  client: PsqlClient,
}

pub struct PsqlCreds {
  pub host: String,
  pub database_name: String,
  pub username: String,
  pub password: Option<String>,
}

impl PsqlConnection {
  pub fn new(creds: &PsqlCreds) -> ResultAnyError<PsqlConnection> {
    return Ok(PsqlConnection {
      client: PsqlConfig::new()
        .user(&creds.username)
        .password(
          creds
            .password
            .as_ref()
            .or(Some(&String::from("")))
            .as_ref()
            .unwrap(),
        )
        .host(&creds.host)
        .dbname(&creds.database_name)
        .connect(postgres::NoTls)
        .map_err(|err| {
          return PsqlConnectionError::InitializeConnectionError(err.to_string());
        })?,
    });
  }
}

impl PsqlConnection {
  pub fn get(&mut self) -> &mut PsqlClient {
    return &mut self.client;
  }
}