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
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
extern crate rocket_contrib;
extern crate tiberius;
extern crate tokio;
extern crate tokio_util;
extern crate log;
extern crate futures;
extern crate snafu;

use futures::{AsyncRead, AsyncWrite};
use rocket_contrib::{
    databases::{
        r2d2, 
        DbError, 
        DatabaseConfig, 
        Poolable,
    }
};

trait ConnectionImplementation: AsyncRead + AsyncWrite + Unpin + Send {}
impl ConnectionImplementation for tokio_util::compat::Compat<tokio::net::TcpStream> {}

/// A wrapper around the actual Database connection
pub struct Connection {
    inner: tiberius::Client<Box<dyn ConnectionImplementation>>
}

impl Connection {
    /// Utility function providing a blocking way to use the underlying `execute` function
    pub fn execute<'a>(
        &mut self,
        query: impl Into<std::borrow::Cow<'a, str>>,
        params: &[&dyn tiberius::ToSql],
    ) -> tiberius::Result<tiberius::ExecuteResult> {
        tokio::runtime::Runtime::new()
            .unwrap()
            .block_on(async move {
                self
                    .inner
                    .execute(query, params)
                    .await
            })
            
    }


    /// Utility function providing a blocking way to use the underlying `query` function
    pub fn query<'a, 'b>(
        &'a mut self,
        query: impl Into<std::borrow::Cow<'b, str>>,
        params: &'b [&'b dyn tiberius::ToSql],
    ) -> tiberius::Result<Vec<Vec<tiberius::Row>>>
        where 'a: 'b
    {
        tokio::runtime::Runtime::new()
            .unwrap()
            .block_on(async move {
                let qr = self
                    .inner
                    .query(query, params)
                    .await;

                match qr {
                    Err(e) => Err(e),
                    Ok(qr) => {
                        qr
                            .into_results()
                            .await                  
                    }
                }
            })
    }
}

/// The manager for a MSSQL connection pool
pub struct ConnectionManager {
    config: tiberius::Config,
    runtime: tokio::runtime::Runtime,
}

impl ConnectionManager {
    pub fn new(cfg: &DatabaseConfig) -> Result<Self, Error> {
        use tiberius::{
            Config,
            AuthMethod,
        };

        let mut config = Config::new();
        config.host(cfg.url);

        let port = cfg
            .extras
            .get("port")
            .ok_or(MissingConfig { field: "port"}.build())
            .and_then(|s| {
                s
                    .as_integer()                
                    .map(|i| i as u16)
                    .ok_or(InvalidConfig { field: "port" }.build())
            })?;

        config.port(port);

        let user = cfg
            .extras
            .get("user")
            .ok_or(MissingConfig { field: "user" }.build())
            .and_then(|v| {
                v
                    .as_str()
                    .ok_or(InvalidConfig { field: "user" }.build())
            })?;

        let pass = cfg
            .extras
            .get("pwd")
            .ok_or(MissingConfig { field: "pwd" }.build())
            .and_then(|v| {
                v
                    .as_str()
                    .ok_or(InvalidConfig { field: "pwd" }.build())
            })?;

        config.authentication(AuthMethod::sql_server(user, pass));
        config.trust_cert();

        Ok(Self {
            config,
            runtime: tokio::runtime::Runtime::new().unwrap(),
        })
    }
}

#[derive(Debug, snafu::Snafu)]
pub enum Error {
    Tiberius { inner: tiberius::error::Error },
    #[snafu(display("Missing Configuration field [field: {}]", field))]
    MissingConfig { field: String },
    #[snafu(display("Invalid Configuration field value [field: {}]", field))]
    InvalidConfig { field: String },
    ConnectionError {},
}

impl r2d2::ManageConnection for ConnectionManager {
    type Connection = Connection;

    type Error = Error;

    fn connect(&self) -> Result<Self::Connection, Self::Error> {
        use tokio_util::compat::TokioAsyncWriteCompatExt;

        let conn: Result<tiberius::Client<Box<dyn ConnectionImplementation>>, Self::Error> = self.runtime.block_on(async move {
            let tcp = std::net::TcpStream::connect(self.config.get_addr()).map_err(|_| ConnectionError {}.build())?;
            tcp.set_nodelay(true).map_err(|_| ConnectionError {}.build())?;
    
            let compat_stream = tokio::net::TcpStream::from_std(tcp)
                .map_err(|_| ConnectionError {}.build())?
                .compat_write();
    
            let boxed_stream: Box<dyn ConnectionImplementation> = Box::new(compat_stream);

            tiberius::Client::connect(self.config.clone(), boxed_stream)
                .await
                .map_err(|_| ConnectionError {}.build())
        });


        Ok(Self::Connection {
            inner: conn?
        })

    }

    fn is_valid(&self, conn: &mut Self::Connection) -> Result<(), Self::Error> {
        self.runtime.block_on(async move {
            conn
                .inner
                .execute("SELECT 1;", &[])
                .await
                .map(|_| ())
                .map_err(|err| Error::Tiberius {inner: err})
        })
    }

    fn has_broken(&self, _conn: &mut Self::Connection) -> bool {
        false
    }
}

impl Poolable for Connection {
    type Manager = ConnectionManager;
    type Error = DbError<Error>;

    fn pool(config: DatabaseConfig) -> Result<r2d2::Pool<Self::Manager>, Self::Error> {
        let manager = ConnectionManager::new(&config)
            .map_err(DbError::Custom)?;

        r2d2::Pool::builder()
            .max_size(config.pool_size)
            .build(manager)
            .map_err(DbError::PoolError)
    }
}