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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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::{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)
    }
    // 累加连接
    // 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)
    // }
}