novax_sqlx_mysql/
lib.rs

1use sqlx::mysql::MySqlPool;
2
3pub struct MysqlConn {
4    port:   i16,
5    user:   String,
6    pwd:    String,
7    host:   String,
8    db:     String
9}
10
11/// Define mysql connection
12/// parameters
13/// 
14impl MysqlConn {
15    /// new create an new 
16    /// instance for MysqlConn
17    /// Paramter sequence:
18    /// * String (user)
19    /// * String (pwd)
20    /// * String (host)
21    /// * String (database)
22    /// * i16    (port)
23    pub fn new(param: (String, String, String, String, i16)) -> Self {
24        let (user, pwd, host, db, port) = param;
25        Self {
26            port, user, pwd, host, db
27        }
28    }
29    fn to_sql(&self) -> String {
30        format!("mysql://{}:{}@{}:{}/{}",
31            self.user, self.pwd, self.host, self.port, self.db)
32    }
33}
34
35pub async fn create_connection(my_conn: MysqlConn) -> Result<MySqlPool, sqlx::Error> {
36    let database_url = my_conn.to_sql();
37    MySqlPool::connect(&database_url).await
38}
39
40// re-export
41pub use sqlx;
42
43#[cfg(test)]
44mod tests {
45    use super::*;
46    use env_logger;
47    use log;
48    use sqlx::Row;
49
50    #[tokio::test]
51    async fn should_mysql_connection_ok() -> Result<(), sqlx::Error> {
52        env_logger::init();
53        let mysql_cn = MysqlConn::new(
54            ("myuser".to_string(), "mypassword".to_string(), 
55            "localhost".to_string(), "mydatabase".to_string(), 3306)
56        );
57        // ensure application run
58        log::info!("parsing database uri ");
59        std::env::set_var("DATABASE_URL", &mysql_cn.to_sql());
60        // ensure application run
61        let cn = create_connection(mysql_cn).await;
62        assert_eq!(cn.is_ok(), true);
63        // check simple sql
64        let row = sqlx::query(r#"select 1 as id"#).fetch_one(&cn?).await?;
65        assert_eq!(row.get::<'_, i32, _>("id") == 1, true);
66        Ok(())
67
68    } 
69
70}