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
/*
This file is part of serde-odbc.

serde-odbc is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

serde-odbc is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with serde-odbc.  If not, see <http://www.gnu.org/licenses/>.
*/
use std::ptr::null_mut;

use odbc_sys::{
    SQLAllocHandle, SQLDriverConnect, SQLEndTran, SQLFreeHandle, SQLSetConnectAttr, SQLSetEnvAttr,
    SqlCompletionType, SQLHANDLE, SQLHDBC, SQLHENV, SQLSMALLINT, SQL_ATTR_AUTOCOMMIT,
    SQL_ATTR_CONNECTION_POOLING, SQL_ATTR_ODBC_VERSION, SQL_COMMIT, SQL_DRIVER_COMPLETE_REQUIRED,
    SQL_HANDLE_DBC, SQL_HANDLE_ENV, SQL_OV_ODBC3, SQL_ROLLBACK,
};

use crate::error::{OdbcResult, Result};

pub struct Environment(SQLHENV);

impl Environment {
    pub fn new() -> Result<Self> {
        let mut env: SQLHANDLE = null_mut();

        unsafe { SQLAllocHandle(SQL_HANDLE_ENV, null_mut(), &mut env) }.check()?;

        let env = env as SQLHENV;

        unsafe { SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, SQL_OV_ODBC3.into(), 0) }.check()?;
        unsafe { SQLSetEnvAttr(env, SQL_ATTR_CONNECTION_POOLING, null_mut(), 0) }.check()?;

        Ok(Environment(env))
    }

    pub fn handle(&self) -> SQLHANDLE {
        self.0 as SQLHANDLE
    }
}

impl Drop for Environment {
    fn drop(&mut self) {
        let _ = unsafe { SQLFreeHandle(SQL_HANDLE_ENV, self.handle()) };
    }
}

pub struct Connection(SQLHDBC);

impl Connection {
    pub fn new(env: &Environment, conn_str: &str) -> Result<Self> {
        let mut dbc: SQLHANDLE = null_mut();

        unsafe { SQLAllocHandle(SQL_HANDLE_DBC, env.handle(), &mut dbc) }.check()?;

        let dbc = dbc as SQLHDBC;

        unsafe {
            SQLDriverConnect(
                dbc,
                null_mut(),
                conn_str.as_ptr(),
                conn_str.len() as SQLSMALLINT,
                null_mut(),
                0,
                null_mut(),
                SQL_DRIVER_COMPLETE_REQUIRED,
            )
        }
        .check()?;

        unsafe { SQLSetConnectAttr(dbc, SQL_ATTR_AUTOCOMMIT, null_mut(), 0) }.check()?;

        Ok(Connection(dbc))
    }

    pub fn handle(&self) -> SQLHANDLE {
        self.0 as SQLHANDLE
    }

    pub fn begin(&self) -> Transaction {
        Transaction(Some(self))
    }
}

impl Drop for Connection {
    fn drop(&mut self) {
        let _ = unsafe { SQLFreeHandle(SQL_HANDLE_DBC, self.handle()) };
    }
}

pub struct Transaction<'conn>(Option<&'conn Connection>);

impl<'conn> Transaction<'conn> {
    pub fn commit(mut self) -> Result<()> {
        Self::end(self.0.take().unwrap(), SQL_COMMIT)
    }

    pub fn rollback(mut self) -> Result<()> {
        Self::end(self.0.take().unwrap(), SQL_ROLLBACK)
    }

    fn end(conn: &'conn Connection, completion_type: SqlCompletionType) -> Result<()> {
        unsafe { SQLEndTran(SQL_HANDLE_DBC, conn.handle(), completion_type) }.check()
    }
}

impl<'conn> Drop for Transaction<'conn> {
    fn drop(&mut self) {
        if let Some(conn) = self.0.take() {
            let _ = Self::end(conn, SQL_ROLLBACK);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use crate::tests::CONN_STR;

    #[test]
    fn make_env() {
        Environment::new().unwrap();
    }

    #[test]
    fn make_conn() {
        let env = Environment::new().unwrap();
        Connection::new(&env, CONN_STR).unwrap();
    }

    #[test]
    fn commit_trans() {
        let env = Environment::new().unwrap();
        let conn = Connection::new(&env, CONN_STR).unwrap();

        let trans = conn.begin();
        trans.commit().unwrap();
    }
}