mayhem_db/client/
connector.rs

1use sea_orm::{ConnectOptions, Database, DatabaseConnection, DbErr};
2use serde::{Deserialize, Serialize};
3
4#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
5pub enum DatabaseProtocol {
6    PostgreSQL,
7    SQLite,
8    MySQL,
9}
10
11#[derive(Clone, Debug, Serialize, Deserialize)]
12pub enum Authentication {
13    Password(PasswordAuthentication),
14    User(UserAuthentication),
15    Anonymous,
16}
17
18#[derive(Clone, Debug, Serialize, Deserialize)]
19pub struct PasswordAuthentication {
20    pub user: String,
21    pub pass: String,
22}
23
24impl PasswordAuthentication {
25    pub fn get_auth_string(&self) -> String {
26        return self.user.clone() + ":" + self.pass.clone().as_str() + "@";
27    }
28}
29
30#[derive(Clone, Debug, Serialize, Deserialize)]
31pub struct UserAuthentication {
32    pub user: String,
33}
34
35impl UserAuthentication {
36    pub fn get_auth_string(&self) -> String {
37        return self.user.clone() + "@";
38    }
39}
40
41#[derive(Clone, Debug, Serialize, Deserialize)]
42pub struct ConnectionOptions {
43    pub protocol: DatabaseProtocol,
44
45    pub auth: Authentication,
46    pub host: String,
47    pub port: i32,
48    pub database: String,
49}
50
51impl ConnectionOptions {
52    pub fn get_protocol(&self) -> String {
53        return (match self.protocol {
54            DatabaseProtocol::PostgreSQL => "postgres://",
55            DatabaseProtocol::MySQL => "mysql://",
56            DatabaseProtocol::SQLite => "sqlite://",
57        })
58        .to_string();
59    }
60
61    pub fn get_connection_string(&self) -> String {
62        let auth_str = match self.auth.clone() {
63            Authentication::Password(val) => val.get_auth_string(),
64            Authentication::User(val) => val.get_auth_string(),
65            Authentication::Anonymous => "".to_string(),
66        };
67
68        return self.get_protocol()
69            + auth_str.as_str()
70            + self.host.clone().as_str()
71            + ":"
72            + self.port.clone().to_string().as_str()
73            + "/"
74            + self.database.to_string().as_str();
75    }
76}
77
78pub async fn connect(opts: ConnectionOptions) -> Result<DatabaseConnection, DbErr> {
79    let mut conn = ConnectOptions::new(opts.get_connection_string());
80
81    conn.sqlx_logging(false)
82        .sqlx_logging_level(log::LevelFilter::Error);
83
84    return Database::connect(conn).await;
85}