r2d2_testconnection/
lib.rs1extern crate r2d2;
2
3use r2d2::ManageConnection;
4
5use std::sync::Mutex;
6use std::sync::Arc;
7use std::fmt;
8
9pub struct TestManager<C> {
10 connection: Arc<Mutex<Option<C>>>,
11}
12
13unsafe impl<T: Send + 'static> Sync for TestManager<T> {
14}
15
16impl<C> TestManager<C> {
17 pub fn new(connection: C) -> Self {
18 Self { connection: Arc::new(Mutex::new(Some(connection))) }
19 }
20}
21
22#[derive(Debug)]
23pub struct Error;
24
25impl std::error::Error for Error {
26 fn description(&self) -> &str {
27 "There can be only one test connection!"
28 }
29}
30
31impl fmt::Display for Error {
32 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
33 use std::error::Error;
34 self.description().fmt(f)
35 }
36}
37
38impl<T> ManageConnection for TestManager<T> where
39 T: Send + 'static,
40{
41 type Connection = T;
42 type Error = Error;
43
44 fn connect(&self) -> Result<T, Self::Error> {
45 let conn = self.connection
46 .lock()
47 .map_err(|_| Error)?
48 .take()
49 .ok_or(Error)?;
50 Ok(conn)
51 }
52
53 fn is_valid(&self, _conn: &mut T) -> Result<(), Self::Error> {
54 Ok(())
55 }
56
57 fn has_broken(&self, _conn: &mut T) -> bool {
58 false
59 }
60}