use std::collections::HashMap;
use std::thread;
use json::{JsonValue};
use lazy_static::lazy_static;
use crate::config::Config;
use crate::connect::Connect;
use std::sync::Mutex;
mod comm;
mod packet;
mod config;
mod server;
mod character_set;
mod client;
mod response;
mod connect;
lazy_static! {
pub static ref POOL: Mutex<HashMap<String, Connect>> = Mutex::new(HashMap::new());
pub static ref CONNECT: Mutex<Vec<Connect>> = Mutex::new(Vec::new());
}
#[derive(Clone, Debug)]
pub struct Mysql {
pub config: Config,
}
impl Mysql {
pub fn new(config: JsonValue) -> Result<Self, String> {
let config = match Config::new(config) {
Ok(e) => e,
Err(e) => return Err(format!("配置文件错误: {e}")),
};
Ok(Self { config })
}
pub fn get_conn(&mut self, thread_id: &str) -> Result<Connect, String> {
let thread_id = if thread_id.is_empty() {
format!("{:?}", thread::current().id())
} else {
thread_id.to_string()
};
let none = POOL.lock().unwrap().get(&*thread_id).is_none();
if !none {
let connect = POOL.lock().unwrap().get(&*thread_id).unwrap().clone();
return Ok(connect);
}
let conn = self.push_connect()?;
POOL.lock().unwrap().insert(thread_id.clone(), conn);
let connect = POOL.lock().unwrap().get(&*thread_id).unwrap().clone();
Ok(connect)
}
fn push_connect(&mut self) -> Result<Connect, String> {
let mut s = POOL.lock().unwrap().len();
let mut k = CONNECT.lock().unwrap().len();
let i = self.config.pool_max as usize;
if s == i {
loop {
if s < i {
break;
}
s = POOL.lock().unwrap().len();
}
}
if i > s + k {
match Connect::connect(self.config.clone()) {
Ok(e) => CONNECT.lock().unwrap().push(e),
Err(e) => return Err(e)
};
k = CONNECT.lock().unwrap().len();
}
let conn = CONNECT.lock().unwrap().remove(0);
Ok(conn)
}
}