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
11impl MysqlConn {
15 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
40pub 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 log::info!("parsing database uri ");
59 std::env::set_var("DATABASE_URL", &mysql_cn.to_sql());
60 let cn = create_connection(mysql_cn).await;
62 assert_eq!(cn.is_ok(), true);
63 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}