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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
extern crate r2d2;
extern crate r2d2_odbc;

use r2d2_odbc::ODBCConnectionManager;
use r2d2::{Pool, PooledConnection};
use parking_lot::{ RwLock};
use std::time::Duration;
use unidb::get_db_properties;

#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;

lazy_static!{

    static ref ODBC_POOL: RwLock<Pool<ODBCConnectionManager>> = {
        RwLock::new(create_odbc_connection_manager())
    };
}
pub fn connect_db() -> Result<PooledConnection <ODBCConnectionManager>, r2d2::Error> {

    let conn = ODBC_POOL.read();
    return match conn.get() {
        Ok(t) => Ok(t),
        Err(e) => {
            error!("==> {:?}", e);

            drop(conn);

            let mut conn = ODBC_POOL.write();
            *conn = create_odbc_connection_manager();
            conn.get()
        }
    };
}
pub fn create_odbc_connection_manager() -> Pool<ODBCConnectionManager> {

    let dsn = match get_db_properties().get("db.odbc.dsn") {
        Some(v) => v,
        _ => panic!("No such property: db.odbc.dsn"),
    };
    let uid = match get_db_properties().get("db.odbc.uid") {
        Some(v) => v,
        _ => panic!("No such property: db.odbc.uid"),
    };
    let pwd = match get_db_properties().get("db.odbc.pwd") {
        Some(v) => v,
        _ => panic!("No such property: db.odbc.pwd"),
    };
    let database = match get_db_properties().get("db.odbc.database") {
        Some(v) => v,
        _ => panic!("No such property: db.odbc.database"),
    };
    let pool_size = match get_db_properties().get("db.odbc.pool_size") {
        Some(t) =>   t.parse::<u32>().unwrap(),
        None => panic!("No such property: db.oracle.pool_size")
    };

    let idle_timeout_sec = match get_db_properties().get("db.odbc.idle_timeout_sec") {
        Some(t) =>   t.parse::<u64>().unwrap_or(15),
        None => 15,
    };

    let connection_string = format!("DSN={};UID={};PWD={};DB={}",dsn, uid, pwd, database);
    let manager = ODBCConnectionManager::new(connection_string);

    let pool = r2d2::Pool::builder()
        .idle_timeout(Some(Duration::from_secs(idle_timeout_sec)))
        .max_size(pool_size)
        .build(manager).unwrap();
    pool

}


#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }
}