quackdb_internal/handles/
connection.rs

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
use std::{
    ops::Deref,
    sync::{Arc, Mutex},
};

use crate::ffi;

use super::{DatabaseHandle, TableFunctionHandle};

#[derive(Debug)]
pub struct ConnectionHandle {
    raw: ffi::duckdb_connection,
    _parent: Arc<DatabaseHandle>,
    table_functions: Mutex<Vec<Arc<TableFunctionHandle>>>,
}

pub struct ConnectionHandleError;

impl ConnectionHandle {
    /// # Safety
    /// * Takes ownership of `raw`
    pub unsafe fn from_raw(raw: ffi::duckdb_connection, parent: Arc<DatabaseHandle>) -> Arc<Self> {
        Arc::new(Self {
            raw,
            _parent: parent,
            table_functions: Mutex::new(vec![]),
        })
    }
    pub fn register_table_function(
        &self,
        function: Arc<TableFunctionHandle>,
    ) -> Result<(), ConnectionHandleError> {
        let r = unsafe { ffi::duckdb_register_table_function(self.raw, **function) };
        match r {
            ffi::DuckDBSuccess => {
                self.table_functions.lock().unwrap().push(function);
                Ok(())
            }
            ffi::DuckDBError => Err(ConnectionHandleError),
            _ => unreachable!(),
        }
    }
}

impl Deref for ConnectionHandle {
    type Target = ffi::duckdb_connection;

    fn deref(&self) -> &Self::Target {
        &self.raw
    }
}

impl Drop for ConnectionHandle {
    fn drop(&mut self) {
        unsafe { ffi::duckdb_disconnect(&mut self.raw) }
    }
}