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
pub mod error;
pub mod connect_info;

use mongodb::{Client as MongoClient,options::ClientOptions as MongoClientOptions};
use mysql::{Pool as MysqlPool};
use connect_info::ConnectInfo;
use error::UnsupportedTypeError;
use neo4rs::Graph;
use std::sync::Arc;


pub enum ConnectPool {
    MysqlPool(MysqlPool),
    MongoPool(MongoClient),
    Neo4jPool(Arc<Graph>),
    Error(UnsupportedTypeError),
}

pub async fn get_pool(connect_info: &ConnectInfo) -> ConnectPool {
    if connect_info.dialect == "mysql" {
        let url = format!("mysql://{}:{}@{}:{}/{}",
                          connect_info.user,
                          connect_info.password,
                          connect_info.host,
                          connect_info.port,
                          connect_info.db);
        let pool = MysqlPool::new(url.as_str()).unwrap();
        return ConnectPool::MysqlPool(pool);
    } else if connect_info.dialect == "mongo" {
        let mut url = format!("mongodb://{}:{}@{}:{}", connect_info.user,
                              connect_info.password, connect_info.host, connect_info.port);
        let mut auth_type = "Password";
        match connect_info.params.get("auth_type") {
            Some(value) => {
                auth_type = value;
            }
            _ => {
                auth_type = "Password";
            }
        }
        match auth_type {
            "Password" => url = format!("{}/?authSource=admin", url),
            "LDAP" => url = format!("{}/?authMechanism=PLAIN", url),
            "X509" => url = format!("{}/?authMechanism=MONGODB-X509", url),
            _ => url = url
        }
        let mut client_options = MongoClientOptions::parse(url).await.unwrap();
        client_options.app_name = Some("My App".to_string());
        let client = MongoClient::with_options(client_options).unwrap();

        return ConnectPool::MongoPool(client);
    } else if connect_info.dialect == "neo4j" {
        let uri = format!("{}:{}", connect_info.host, connect_info.port);
        let graph = Arc::new(Graph::new(uri, connect_info.user.as_str(), connect_info.password.as_str()).await.unwrap());
        return ConnectPool::Neo4jPool(graph);
    } else {
        return ConnectPool::Error(UnsupportedTypeError {
            code: String::from("4001"),
            message: String::from("unsupported database tye"),
        });
    }
}