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
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::thread;
use json::{JsonValue};
// use lazy_static::lazy_static;
use crate::config::Config;
use crate::connect::Connect;
// use std::sync::{Arc, Mutex};

mod comm;
mod packet;
mod config;
mod server;
mod character_set;
mod client;
mod response;
pub mod connect;

// lazy_static! {
//     /// 连接池
//    pub static ref POOL: Arc<Mutex<HashMap<String, Connect>>> = Arc::new(Mutex::new(HashMap::new()));
//    pub static ref CONNECT: Mutex<Vec<Connect>> = Mutex::new(Vec::new());
// }

#[derive(Clone, Debug)]
pub struct Mysql {
    /// 基础配置
    pub config: Config,
    pub pool: HashMap<String, Connect>,
}

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, pool: HashMap::new() })
    }
    /// 获取连接
    pub fn get_conn(&mut self, thread_id: &str) -> Result<&mut Connect, String> {
        let thread_id = if thread_id.is_empty() {
            format!("{:?}", thread::current().id())
        } else {
            thread_id.to_string()
        };
        if self.pool.get_mut(&*thread_id).is_none() {
            let conn = match Connect::connect(self.config.clone()) {
                Ok(e) => e,
                Err(e) => return Err(e)
            };
            self.pool.insert(thread_id.clone(), conn);
        }
        let connect = self.pool.get_mut(&*thread_id).unwrap();
        Ok(connect)
    }
}

// impl Drop for Mysql {
//     fn drop(&mut self) {
//         let thread_id = format!("{:?}", thread::current().id());
//         println!("{} {}", thread_id,self.pool.len());
//     }
// }