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
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
//! TDF Config
//! Turbo Development Framework
//!
#[macro_use]
extern crate lazy_static;

pub const MAX_POOL_SIZE: u32 = 64;
pub const MIN_POOL_SIZE: u32 = 8;

pub const REDIS_POOL_SIZE: u32 = 32;

use r2d2::PooledConnection;
use r2d2_redis::RedisConnectionManager;
use sqlx::{Connect, MySqlConnection, MySqlPool, PgConnection, PgPool};
use sqlx_core::postgres::PgCursor;
use sqlx_core::mysql::MySqlCursor;

/// 数据源
pub trait DataSource {
    type C;
    fn get_url(&self) -> String;
    fn get_pool(&mut self) -> sqlx::Pool<Self::C>
    where
        Self::C: Connect;
}

#[derive(Debug, Clone)]
pub struct MySqlDataSource {
    pub url: String,
    pub pool: sqlx::Pool<MySqlConnection>,
}

impl DataSource for MySqlDataSource {
    type C = MySqlConnection;
    fn get_url(&self) -> String {
        self.url.to_string()
    }
    fn get_pool(&mut self) -> sqlx::Pool<Self::C> {
        self.pool.clone()
    }
}

pub async fn mysql_data_source() -> MySqlDataSource {
    dotenv::dotenv().ok();
    let url = std::env::var("MYSQL_URL").expect("MYSQL_URL must be set");
    let max_pool_size: u32 = std::env::var("MYSQL_MAX_POOL_SIZE")
        .unwrap_or_else(|_| MAX_POOL_SIZE.to_string())
        .parse::<u32>()
        .unwrap_or(MAX_POOL_SIZE);
    let min_pool_size: u32 = std::env::var("MYSQL_MIN_POOL_SIZE")
        .unwrap_or_else(|_| MIN_POOL_SIZE.to_string())
        .parse::<u32>()
        .unwrap_or(MIN_POOL_SIZE);

    let pool: sqlx::MySqlPool = sqlx::Pool::builder()
        .max_size(max_pool_size)
        .min_size(min_pool_size)
        .build(&url)
        .await
        .unwrap();
    MySqlDataSource { url, pool }
}

#[derive(Debug, Clone)]
pub struct PgDataSource {
    pub url: String,
    pub pool: sqlx::Pool<PgConnection>,
}

impl DataSource for PgDataSource {
    type C = PgConnection;

    fn get_url(&self) -> String {
        self.url.to_string()
    }

    fn get_pool(&mut self) -> sqlx::Pool<Self::C> {
        self.pool.clone()
    }
}

pub async fn pg_data_source() -> PgDataSource {
    dotenv::dotenv().ok();
    let url = std::env::var("PG_URL").expect("PG_URL must be set");
    let max_pool_size: u32 = std::env::var("PG_MAX_POOL_SIZE")
        .unwrap_or_else(|_| MAX_POOL_SIZE.to_string())
        .parse::<u32>()
        .unwrap_or(MAX_POOL_SIZE);
    let min_pool_size: u32 = std::env::var("PG_MIN_POOL_SIZE")
        .unwrap_or_else(|_| MIN_POOL_SIZE.to_string())
        .parse::<u32>()
        .unwrap_or(MIN_POOL_SIZE);

    let pool: sqlx::PgPool = sqlx::Pool::builder()
        .max_size(max_pool_size)
        .min_size(min_pool_size)
        .build(&url)
        .await
        .unwrap();
    PgDataSource { url, pool }
}

#[derive(Debug, Clone)]
pub struct RedisDataSource {
    pub url: String,
    pub pool: r2d2::Pool<RedisConnectionManager>,
}

impl RedisDataSource {
    pub fn get_url(&self) -> String {
        self.url.to_string()
    }
    pub fn get_pool(self) -> r2d2::Pool<RedisConnectionManager> {
        self.pool.clone()
    }
}

#[cfg(feature = "with-redis")]
lazy_static! {
    pub static ref REDIS_POOL: r2d2::Pool<r2d2_redis::RedisConnectionManager> = {
        dotenv::dotenv().ok();
        let redis_url = std::env::var("REDIS_URL").expect("REDIS_URL must be set");
        let manager = r2d2_redis::RedisConnectionManager::new(redis_url).unwrap();
        r2d2::Pool::builder()
            .max_size(REDIS_POOL_SIZE)
            .build(manager)
            .expect("Failed to create redis pool.")
    };

    // Used to update core data into redis master, such as person, role and dept etc.
    // pub static ref MASTER_REDIS_POOL: Pool<r2d2_redis::RedisConnectionManager> = {
    //     dotenv().ok();
    //     let redis_url = env::var("MASTER_REDIS_URL").expect("MASTER_REDIS_URL must be set");
    //     let manager = r2d2_redis::RedisConnectionManager::new(redis_url).unwrap();
    //     r2d2::Pool::builder()
    //         .max_size(REDIS_POOL_SIZE)
    //         .build(manager)
    //         .expect("Failed to create master redis pool.")
    // };

}

#[cfg(feature = "with-redis")]
pub fn get_redis_connection() -> PooledConnection<r2d2_redis::RedisConnectionManager> {
    REDIS_POOL.clone().get().unwrap()
}

#[cfg(feature = "with-redis")]
pub fn redis_data_source() -> RedisDataSource {
    dotenv::dotenv().ok();
    let url = std::env::var("REDIS_URL").expect("REDIS_URL must be set");
    let pool = REDIS_POOL.clone();
    RedisDataSource { url, pool }
}

#[cfg(feature = "with-mysql")]
pub type TdfDataSource = MySqlDataSource;
#[cfg(feature = "with-postgres")]
pub type TdfDataSource = PgDataSource;
#[cfg(feature = "with-mysql")]

#[cfg(feature = "with-mysql")]
pub async fn data_source() -> TdfDataSource {
    mysql_data_source().await
}
#[cfg(feature = "with-postgres")]
pub async fn data_source() -> TdfDataSource {
    pg_data_source().await
}


#[cfg(feature = "with-mysql")]
pub type TdfPool = MySqlPool;
#[cfg(feature = "with-postgres")]
pub type TdfPool = PgPool;


#[cfg(feature = "with-mysql")]
pub type TdfCursor<'c, 'q> = MySqlCursor<'c, 'q>;
#[cfg(feature = "with-postgres")]
pub type TdfCursor<'c, 'q> = PgCursor<'c, 'q>;

#[cfg(test)]
mod tests {
    use crate::{mysql_data_source, pg_data_source, redis_data_source, DataSource};
    use r2d2::PooledConnection;
    use r2d2_redis::RedisConnectionManager;
    use sqlx::prelude::*;
    use std::ops::Deref;

    #[tokio::test]
    async fn test_data_source() {
        let redis_data_source = redis_data_source();
        println!("{:?}", redis_data_source);
        let pool = redis_data_source.get_pool();
        let mut conn: PooledConnection<RedisConnectionManager> = pool.get().unwrap();
        let reply = redis::cmd("PING").query::<String>(&mut *conn).unwrap();

        assert_eq!("PONG", reply);

        let mut my_data_source = mysql_data_source().await;
        println!("{:?}", my_data_source);
        let pool = my_data_source.get_pool();
        println!("{:?}", pool);

        let mut cursor = sqlx::query(r#"SELECT version() v"#).fetch(&pool);
        let row = cursor.next().await.unwrap().unwrap();
        let version = row.get::<&str, &str>("v").to_string();
        println!("{:?}", version);

        let mut pg_data_source = pg_data_source().await;
        println!("{:?}", pg_data_source);
        let pool = pg_data_source.get_pool();
        println!("{:?}", pool);

        let mut cursor = sqlx::query(r#"SELECT version() v"#).fetch(&pool);
        let row = cursor.next().await.unwrap().unwrap();
        let version = row.get::<&str, &str>("v").to_string();
        println!("{:?}", version);
        assert!(version.len() > 0);
        // let version = my_data_source.get_version().await;
        // assert_eq!(version.is_ok(), true);
    }
}

// impl MySqlDataSource {
//     async fn get_version(&mut self) -> std::result::Result<String, Box<dyn std::error::Error>> {
//         use sqlx::mysql::MySqlRow;
//         use sqlx::prelude::*;
//         use sqlx_core::mysql::MySqlCursor;
//
//         let mut cursor: MySqlCursor = sqlx::query(r#"SELECT version() v"#).fetch(&self.pool);
//         //        let row: MySqlRow = cursor.next().await.unwrap().unwrap();
//         let row = cursor.next().await;
//         match row {
//             Ok(r) => {
//                 let version = r.unwrap().get::<&str, &str>("v").to_string();
//                 Ok(version)
//             }
//             Err(e) => Err(Box::<dyn std::error::Error>::from(e)),
//         }
//     }
// }