use crate::{Exception, Object, SqlCrud};
use mysql::prelude::*;
use mysql::*;
use std::collections::HashMap;
#[deprecated]
pub struct MySqlClient {
pub pool: Pool,
}
impl MySqlClient {
pub fn new(host: String, port: i32, user: String, password: String, db: String) -> Result<Self, Exception> {
let url = format!("mysql://{user}:{password}@{host}:{port}/{db}");
let opts = Opts::from_url(&url)?;
let pool = Pool::new(opts)?;
Ok(MySqlClient { pool })
}
}
impl SqlCrud for MySqlClient {
fn insert(&self, sql: &str) -> std::result::Result<bool, Exception> {
todo!()
}
fn update(&self, sql: &str) -> std::result::Result<bool, Exception> {
todo!()
}
fn delete(&self, sql: &str) -> std::result::Result<bool, Exception> {
todo!()
}
fn select_one(&self, sql: &str) -> std::result::Result<HashMap<String, Object>, Exception> {
todo!()
}
fn select(&self, sql: &str) -> std::result::Result<Vec<HashMap<String, Object>>, Exception> {
let mut conn = self.pool.get_conn()?;
let rows = conn.query_iter(sql)?;
let mut results = vec![];
for row in rows.into_iter().map(|row| row.unwrap()) {
let mut item: HashMap<String, Object> = HashMap::new();
let columns = row.columns().clone();
let values = row.unwrap();
for (i, column) in columns.iter().enumerate() {
item.insert(column.name_str().to_string(), values.get(i).unwrap().clone().try_into().unwrap());
}
results.push(item);
}
Ok(results)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Exception;
#[test]
fn it_works() -> Result<(), Exception> {
let client = MySqlClient::new("127.0.0.1".into(), 3306, "root".into(), "123456".into(), "test".into())?;
let results = client.select("select * from sys_region where region_id = 2")?;
println!("{:?}", results);
Ok(())
}
}