1use std::ops::{Deref, DerefMut};
21use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
22use std::sync::{Arc, Mutex};
23use std::time::{Duration, Instant};
24
25use crate::client::ClientConfig;
26use crate::{DmClient, Result};
27
28pub struct Connection {
30 pub(crate) client: DmClient,
31}
32
33impl Connection {
34 pub fn connect(cfg: ClientConfig) -> Result<Self> {
35 let mut client = DmClient::with_config(cfg);
36 client.connect()?;
37 Ok(Connection { client })
38 }
39
40 pub fn cursor(&mut self) -> crate::Cursor<'_> {
41 crate::Cursor::new(&mut self.client)
42 }
43
44 pub fn execute(&mut self, sql: &str, params: &[crate::Param]) -> Result<crate::ExecuteResult> {
45 self.client.execute(sql, params)
46 }
47
48 pub fn begin(&mut self) -> Result<()> {
49 self.client.begin()
50 }
51
52 pub fn commit(&mut self) -> Result<()> {
53 self.client.commit()
54 }
55
56 pub fn rollback(&mut self) -> Result<()> {
57 self.client.rollback()
58 }
59
60 pub fn close(&mut self) {
61 self.client.close();
62 }
63}
64
65pub struct ConnectionPool {
67 cfg: ClientConfig,
68 idle: Mutex<Vec<(Connection, Instant)>>,
69 total: AtomicUsize,
70 max: usize,
71 idle_timeout: Duration,
72 closed: AtomicBool,
73 lazy_check: bool,
75}
76
77impl ConnectionPool {
78 pub fn new(cfg: ClientConfig, min_connections: usize, max_connections: usize) -> Result<Self> {
81 let pool = ConnectionPool {
82 cfg,
83 idle: Mutex::new(Vec::new()),
84 total: AtomicUsize::new(0),
85 max: max_connections.max(1),
86 idle_timeout: Duration::from_secs(300),
87 closed: AtomicBool::new(false),
88 lazy_check: false,
89 };
90 for _ in 0..min_connections.min(max_connections.max(1)) {
91 if let Ok(c) = pool.new_connection() {
92 pool.total.fetch_add(1, Ordering::SeqCst);
93 pool.idle.lock().unwrap().push((c, Instant::now()));
94 }
95 }
96 Ok(pool)
97 }
98
99 pub fn with_lazy_check(mut self, v: bool) -> Self {
103 self.lazy_check = v;
104 self
105 }
106
107 fn new_connection(&self) -> Result<Connection> {
108 Connection::connect(self.cfg.clone())
109 }
110
111 fn check_alive(&self, conn: &mut Connection) -> bool {
112 let mut cur = conn.cursor();
113 cur.execute("SELECT 1", &[]).map(|_| true).unwrap_or(false)
114 }
115
116 pub fn acquire(&self) -> Result<PooledConnection<'_>> {
118 let mut retry = 0;
119 loop {
120 if self.closed.load(Ordering::SeqCst) {
121 return Err(crate::DmError::arg("连接池已关闭"));
122 }
123 {
125 let mut idle = self.idle.lock().unwrap();
126 while let Some((mut conn, _)) = idle.pop() {
127 if !self.lazy_check && !self.check_alive(&mut conn) {
128 conn.close();
130 self.total.fetch_sub(1, Ordering::SeqCst);
131 continue;
132 }
133 return Ok(PooledConnection { pool: self, conn: Some(conn) });
134 }
135 }
136 let total = self.total.load(Ordering::SeqCst);
138 if total < self.max {
139 if self.total.compare_exchange(total, total + 1, Ordering::SeqCst, Ordering::SeqCst).is_ok() {
140 match self.new_connection() {
141 Ok(conn) => return Ok(PooledConnection { pool: self, conn: Some(conn) }),
142 Err(e) => {
143 self.total.fetch_sub(1, Ordering::SeqCst);
144 return Err(e);
145 }
146 }
147 }
148 continue;
149 }
150 if retry >= 600 {
152 return Err(crate::DmError::arg("连接池已满,等待超时"));
154 }
155 retry += 1;
156 std::thread::sleep(Duration::from_millis(50));
157 }
158 }
159
160 pub fn release(&self, mut conn: Connection) {
162 if self.closed.load(Ordering::SeqCst) {
163 conn.close();
164 return;
165 }
166 let alive = self.check_alive(&mut conn);
167 if alive {
168 self.idle.lock().unwrap().push((conn, Instant::now()));
169 } else {
170 conn.close();
171 self.total.fetch_sub(1, Ordering::SeqCst);
172 }
173 }
174
175 pub fn reap_idle(&self) {
177 let now = Instant::now();
178 let mut keep = Vec::new();
179 {
180 let mut idle = self.idle.lock().unwrap();
181 for (mut c, last) in idle.drain(..) {
182 if now.duration_since(last) > self.idle_timeout {
183 c.close();
184 self.total.fetch_sub(1, Ordering::SeqCst);
185 } else {
186 keep.push((c, last));
187 }
188 }
189 }
190 *self.idle.lock().unwrap() = keep;
191 }
192
193 pub fn close(&self) {
194 self.closed.store(true, Ordering::SeqCst);
195 let mut idle = self.idle.lock().unwrap();
196 for (mut c, _) in idle.drain(..) {
197 c.close();
198 self.total.fetch_sub(1, Ordering::SeqCst);
199 }
200 }
201
202 pub fn total(&self) -> usize {
203 self.total.load(Ordering::SeqCst)
204 }
205
206 pub fn idle_count(&self) -> usize {
207 self.idle.lock().unwrap().len()
208 }
209}
210
211pub struct PooledConnection<'a> {
213 pool: &'a ConnectionPool,
214 conn: Option<Connection>,
215}
216
217impl<'a> Deref for PooledConnection<'a> {
218 type Target = Connection;
219 fn deref(&self) -> &Connection {
220 self.conn.as_ref().unwrap()
221 }
222}
223
224impl<'a> DerefMut for PooledConnection<'a> {
225 fn deref_mut(&mut self) -> &mut Connection {
226 self.conn.as_mut().unwrap()
227 }
228}
229
230impl<'a> Drop for PooledConnection<'a> {
231 fn drop(&mut self) {
232 if let Some(conn) = self.conn.take() {
233 self.pool.release(conn);
234 }
235 }
236}
237
238pub type SharedPool = Arc<ConnectionPool>;
240
241impl ConnectionPool {
242 pub fn shared(self) -> Arc<Self> {
244 Arc::new(self)
245 }
246}