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
203
204
205
206
207
208
209
210
211
212
use {
    crate::{
        database_call,
        rdfox_api::{
            CServerConnection,
            CServerConnection_createDataStore,
            CServerConnection_deleteDataStore,
            CServerConnection_destroy,
            CServerConnection_getMemoryUse,
            CServerConnection_getNumberOfThreads,
            CServerConnection_getVersion,
            CServerConnection_newDataStoreConnection,
            CServerConnection_setNumberOfThreads,
        },
        DataStore,
        DataStoreConnection,
        RoleCreds,
        Server,
    },
    rdf_store_rs::consts::LOG_TARGET_DATABASE,
    std::{
        ffi::{CStr, CString},
        ptr,
        sync::Arc,
    },
};

/// A connection to a given [`Server`].
#[derive(Debug)]
pub struct ServerConnection {
    #[allow(dead_code)]
    role_creds: RoleCreds,
    server:     Arc<Server>,
    inner:      *mut CServerConnection,
}

unsafe impl Sync for ServerConnection {}

unsafe impl Send for ServerConnection {}

impl Drop for ServerConnection {
    fn drop(&mut self) {
        assert!(
            !self.inner.is_null(),
            "Could not drop ServerConnection"
        );
        unsafe {
            CServerConnection_destroy(self.inner);
        }
        self.inner = ptr::null_mut();
        tracing::debug!(target: LOG_TARGET_DATABASE, "Dropped {self:}");
    }
}

impl std::fmt::Display for ServerConnection {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "connection to {:}", self.server)
    }
}

impl ServerConnection {
    pub(crate) fn new(
        role_creds: RoleCreds,
        server: Arc<Server>,
        server_connection_ptr: *mut CServerConnection,
    ) -> Self {
        assert!(!server_connection_ptr.is_null());
        assert!(
            server.is_running(),
            "cannot connect to an RDFox server that is not running"
        );
        let connection = Self { role_creds, server, inner: server_connection_ptr };
        tracing::debug!(
            target: LOG_TARGET_DATABASE,
            "Established {connection:}"
        );
        connection
    }

    /// Return the version number of the underlying database engine
    ///
    /// CRDFOX const CException*
    /// CServerConnection_getVersion(
    ///     CServerConnection* serverConnection,
    ///     const char** version
    /// );
    pub fn get_version(&self) -> Result<String, rdf_store_rs::RDFStoreError> {
        let mut c_buf: *const std::os::raw::c_char = ptr::null();
        database_call!(
            "Getting the version",
            CServerConnection_getVersion(self.inner, &mut c_buf)
        )?;
        let c_version = unsafe { CStr::from_ptr(c_buf) };
        Ok(c_version.to_str().unwrap().to_owned())
    }

    pub fn get_number_of_threads(&self) -> Result<u32, rdf_store_rs::RDFStoreError> {
        let mut number_of_threads = 0_usize;
        database_call!(
            format!(
                "Getting the number of server-threads via {}",
                self
            )
            .as_str(),
            CServerConnection_getNumberOfThreads(self.inner, &mut number_of_threads)
        )?;
        tracing::debug!(
            target: LOG_TARGET_DATABASE,
            "Number of threads is {}",
            number_of_threads
        );
        Ok(number_of_threads as u32)
    }

    pub fn set_number_of_threads(
        &self,
        number_of_threads: usize,
    ) -> Result<(), rdf_store_rs::RDFStoreError> {
        assert!(!self.inner.is_null());
        let msg = format!(
            "Setting the number of threads to {}",
            number_of_threads
        );
        database_call!(
            msg.as_str(),
            CServerConnection_setNumberOfThreads(self.inner, number_of_threads)
        )
    }

    pub fn get_memory_use(&self) -> Result<(usize, usize), rdf_store_rs::RDFStoreError> {
        let mut max_used_bytes = 0_usize;
        let mut available_bytes = 0_usize;
        database_call!(CServerConnection_getMemoryUse(
            self.inner,
            &mut max_used_bytes,
            &mut available_bytes
        ))?;
        Ok((max_used_bytes, available_bytes))
    }

    pub fn delete_data_store(
        &self,
        data_store: &DataStore,
    ) -> Result<(), rdf_store_rs::RDFStoreError> {
        assert!(!self.inner.is_null());
        let msg = format!("Deleting {data_store}");
        let c_name = CString::new(data_store.name.as_str()).unwrap();
        database_call!(
            msg.as_str(),
            CServerConnection_deleteDataStore(self.inner, c_name.as_ptr())
        )
    }

    pub fn create_data_store(
        &self,
        data_store: &DataStore,
    ) -> Result<(), rdf_store_rs::RDFStoreError> {
        tracing::trace!(
            target: LOG_TARGET_DATABASE,
            "Creating {data_store:}"
        );
        assert!(!self.inner.is_null());
        let c_name = CString::new(data_store.name.as_str()).unwrap();
        database_call!(
            "creating a datastore",
            CServerConnection_createDataStore(
                self.inner,
                c_name.as_ptr(),
                data_store.parameters.inner.cast_const(),
            )
        )?;
        tracing::debug!(
            target: LOG_TARGET_DATABASE,
            "Created {data_store:}"
        );
        Ok(())
    }

    pub fn connect_to_data_store(
        self: &Arc<Self>,
        data_store: &Arc<DataStore>,
    ) -> Result<Arc<DataStoreConnection>, rdf_store_rs::RDFStoreError> {
        tracing::debug!(
            target: LOG_TARGET_DATABASE,
            "Connecting to {}",
            data_store
        );
        assert!(!self.inner.is_null());
        let mut ds_connection = DataStoreConnection::new(self, data_store, ptr::null_mut());
        let c_name = CString::new(data_store.name.as_str()).unwrap();
        tracing::debug!(
            target: LOG_TARGET_DATABASE,
            conn = ds_connection.number,
            "Creating datastore connection #{}",
            ds_connection.number
        );
        database_call!(
            "Creating datastore connection",
            CServerConnection_newDataStoreConnection(
                self.inner,
                c_name.as_ptr(),
                &mut ds_connection.inner,
            )
        )?;
        tracing::info!(
            target: LOG_TARGET_DATABASE,
            "Connected to {}",
            data_store
        );
        Ok(Arc::new(ds_connection))
    }
}