connection.rs

  1use std::{
  2    cell::RefCell,
  3    ffi::{CStr, CString},
  4    marker::PhantomData,
  5    path::Path,
  6    ptr,
  7};
  8
  9use anyhow::{anyhow, Result};
 10use libsqlite3_sys::*;
 11
 12pub struct Connection {
 13    pub(crate) sqlite3: *mut sqlite3,
 14    persistent: bool,
 15    pub(crate) write: RefCell<bool>,
 16    _sqlite: PhantomData<sqlite3>,
 17}
 18unsafe impl Send for Connection {}
 19
 20impl Connection {
 21    pub(crate) fn open(uri: &str, persistent: bool) -> Result<Self> {
 22        let mut connection = Self {
 23            sqlite3: ptr::null_mut(),
 24            persistent,
 25            write: RefCell::new(true),
 26            _sqlite: PhantomData,
 27        };
 28
 29        let flags = SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_READWRITE;
 30        unsafe {
 31            sqlite3_open_v2(
 32                CString::new(uri)?.as_ptr(),
 33                &mut connection.sqlite3,
 34                flags,
 35                ptr::null(),
 36            );
 37
 38            // Turn on extended error codes
 39            sqlite3_extended_result_codes(connection.sqlite3, 1);
 40
 41            connection.last_error()?;
 42        }
 43
 44        Ok(connection)
 45    }
 46
 47    /// Attempts to open the database at uri. If it fails, a shared memory db will be opened
 48    /// instead.
 49    pub fn open_file(uri: &str) -> Self {
 50        Self::open(uri, true).unwrap_or_else(|_| Self::open_memory(Some(uri)))
 51    }
 52
 53    pub fn open_memory(uri: Option<&str>) -> Self {
 54        let in_memory_path = if let Some(uri) = uri {
 55            format!("file:{}?mode=memory&cache=shared", uri)
 56        } else {
 57            ":memory:".to_string()
 58        };
 59
 60        Self::open(&in_memory_path, false).expect("Could not create fallback in memory db")
 61    }
 62
 63    pub fn persistent(&self) -> bool {
 64        self.persistent
 65    }
 66
 67    pub fn can_write(&self) -> bool {
 68        *self.write.borrow()
 69    }
 70
 71    pub fn backup_main(&self, destination: &Connection) -> Result<()> {
 72        unsafe {
 73            let backup = sqlite3_backup_init(
 74                destination.sqlite3,
 75                CString::new("main")?.as_ptr(),
 76                self.sqlite3,
 77                CString::new("main")?.as_ptr(),
 78            );
 79            sqlite3_backup_step(backup, -1);
 80            sqlite3_backup_finish(backup);
 81            destination.last_error()
 82        }
 83    }
 84
 85    pub fn backup_main_to(&self, destination: impl AsRef<Path>) -> Result<()> {
 86        let destination = Self::open_file(destination.as_ref().to_string_lossy().as_ref());
 87        self.backup_main(&destination)
 88    }
 89
 90    pub fn sql_has_syntax_error(&self, sql: &str) -> Option<(String, usize)> {
 91        let sql = CString::new(sql).unwrap();
 92        let mut remaining_sql = sql.as_c_str();
 93        let sql_start = remaining_sql.as_ptr();
 94
 95        unsafe {
 96            let mut alter_table = None;
 97            while {
 98                let remaining_sql_str = remaining_sql.to_str().unwrap().trim();
 99                let any_remaining_sql = remaining_sql_str != ";" && !remaining_sql_str.is_empty();
100                if any_remaining_sql {
101                    alter_table = parse_alter_table(remaining_sql_str);
102                }
103                any_remaining_sql
104            } {
105                let mut raw_statement = ptr::null_mut::<sqlite3_stmt>();
106                let mut remaining_sql_ptr = ptr::null();
107
108                let (res, offset, message, _conn) =
109                    if let Some((table_to_alter, column)) = alter_table {
110                        // ALTER TABLE is a weird statement. When preparing the statement the table's
111                        // existence is checked *before* syntax checking any other part of the statement.
112                        // Therefore, we need to make sure that the table has been created before calling
113                        // prepare. As we don't want to trash whatever database this is connected to, we
114                        // create a new in-memory DB to test.
115
116                        let temp_connection = Connection::open_memory(None);
117                        //This should always succeed, if it doesn't then you really should know about it
118                        temp_connection
119                            .exec(&format!("CREATE TABLE {table_to_alter}({column})"))
120                            .unwrap()()
121                        .unwrap();
122
123                        sqlite3_prepare_v2(
124                            temp_connection.sqlite3,
125                            remaining_sql.as_ptr(),
126                            -1,
127                            &mut raw_statement,
128                            &mut remaining_sql_ptr,
129                        );
130
131                        (
132                            sqlite3_errcode(temp_connection.sqlite3),
133                            sqlite3_error_offset(temp_connection.sqlite3),
134                            sqlite3_errmsg(temp_connection.sqlite3),
135                            Some(temp_connection),
136                        )
137                    } else {
138                        sqlite3_prepare_v2(
139                            self.sqlite3,
140                            remaining_sql.as_ptr(),
141                            -1,
142                            &mut raw_statement,
143                            &mut remaining_sql_ptr,
144                        );
145                        (
146                            sqlite3_errcode(self.sqlite3),
147                            sqlite3_error_offset(self.sqlite3),
148                            sqlite3_errmsg(self.sqlite3),
149                            None,
150                        )
151                    };
152
153                sqlite3_finalize(raw_statement);
154
155                if res == 1 && offset >= 0 {
156                    let sub_statement_correction =
157                        remaining_sql.as_ptr() as usize - sql_start as usize;
158                    let err_msg =
159                        String::from_utf8_lossy(CStr::from_ptr(message as *const _).to_bytes())
160                            .into_owned();
161
162                    return Some((err_msg, offset as usize + sub_statement_correction));
163                }
164                remaining_sql = CStr::from_ptr(remaining_sql_ptr);
165                alter_table = None;
166            }
167        }
168        None
169    }
170
171    pub(crate) fn last_error(&self) -> Result<()> {
172        unsafe {
173            let code = sqlite3_errcode(self.sqlite3);
174            const NON_ERROR_CODES: &[i32] = &[SQLITE_OK, SQLITE_ROW];
175            if NON_ERROR_CODES.contains(&code) {
176                return Ok(());
177            }
178
179            let message = sqlite3_errmsg(self.sqlite3);
180            let message = if message.is_null() {
181                None
182            } else {
183                Some(
184                    String::from_utf8_lossy(CStr::from_ptr(message as *const _).to_bytes())
185                        .into_owned(),
186                )
187            };
188
189            Err(anyhow!(
190                "Sqlite call failed with code {} and message: {:?}",
191                code as isize,
192                message
193            ))
194        }
195    }
196
197    pub(crate) fn with_write<T>(&self, callback: impl FnOnce(&Connection) -> T) -> T {
198        *self.write.borrow_mut() = true;
199        let result = callback(self);
200        *self.write.borrow_mut() = false;
201        result
202    }
203}
204
205fn parse_alter_table(remaining_sql_str: &str) -> Option<(String, String)> {
206    let remaining_sql_str = remaining_sql_str.to_lowercase();
207    if remaining_sql_str.starts_with("alter") {
208        if let Some(table_offset) = remaining_sql_str.find("table") {
209            let after_table_offset = table_offset + "table".len();
210            let table_to_alter = remaining_sql_str
211                .chars()
212                .skip(after_table_offset)
213                .skip_while(|c| c.is_whitespace())
214                .take_while(|c| !c.is_whitespace())
215                .collect::<String>();
216            if !table_to_alter.is_empty() {
217                let column_name =
218                    if let Some(rename_offset) = remaining_sql_str.find("rename column") {
219                        let after_rename_offset = rename_offset + "rename column".len();
220                        remaining_sql_str
221                            .chars()
222                            .skip(after_rename_offset)
223                            .skip_while(|c| c.is_whitespace())
224                            .take_while(|c| !c.is_whitespace())
225                            .collect::<String>()
226                    } else if let Some(drop_offset) = remaining_sql_str.find("drop column") {
227                        let after_drop_offset = drop_offset + "drop column".len();
228                        remaining_sql_str
229                            .chars()
230                            .skip(after_drop_offset)
231                            .skip_while(|c| c.is_whitespace())
232                            .take_while(|c| !c.is_whitespace())
233                            .collect::<String>()
234                    } else {
235                        "__place_holder_column_for_syntax_checking".to_string()
236                    };
237                return Some((table_to_alter, column_name));
238            }
239        }
240    }
241    None
242}
243
244impl Drop for Connection {
245    fn drop(&mut self) {
246        unsafe { sqlite3_close(self.sqlite3) };
247    }
248}
249
250#[cfg(test)]
251mod test {
252    use anyhow::Result;
253    use indoc::indoc;
254
255    use crate::connection::Connection;
256
257    #[test]
258    fn string_round_trips() -> Result<()> {
259        let connection = Connection::open_memory(Some("string_round_trips"));
260        connection
261            .exec(indoc! {"
262            CREATE TABLE text (
263                text TEXT
264            );"})
265            .unwrap()()
266        .unwrap();
267
268        let text = "Some test text";
269
270        connection
271            .exec_bound("INSERT INTO text (text) VALUES (?);")
272            .unwrap()(text)
273        .unwrap();
274
275        assert_eq!(
276            connection.select_row("SELECT text FROM text;").unwrap()().unwrap(),
277            Some(text.to_string())
278        );
279
280        Ok(())
281    }
282
283    #[test]
284    fn tuple_round_trips() {
285        let connection = Connection::open_memory(Some("tuple_round_trips"));
286        connection
287            .exec(indoc! {"
288                CREATE TABLE test (
289                    text TEXT,
290                    integer INTEGER,
291                    blob BLOB
292                );"})
293            .unwrap()()
294        .unwrap();
295
296        let tuple1 = ("test".to_string(), 64, vec![0, 1, 2, 4, 8, 16, 32, 64]);
297        let tuple2 = ("test2".to_string(), 32, vec![64, 32, 16, 8, 4, 2, 1, 0]);
298
299        let mut insert = connection
300            .exec_bound::<(String, usize, Vec<u8>)>(
301                "INSERT INTO test (text, integer, blob) VALUES (?, ?, ?)",
302            )
303            .unwrap();
304
305        insert(tuple1.clone()).unwrap();
306        insert(tuple2.clone()).unwrap();
307
308        assert_eq!(
309            connection
310                .select::<(String, usize, Vec<u8>)>("SELECT * FROM test")
311                .unwrap()()
312            .unwrap(),
313            vec![tuple1, tuple2]
314        );
315    }
316
317    #[test]
318    fn bool_round_trips() {
319        let connection = Connection::open_memory(Some("bool_round_trips"));
320        connection
321            .exec(indoc! {"
322                CREATE TABLE bools (
323                    t INTEGER,
324                    f INTEGER
325                );"})
326            .unwrap()()
327        .unwrap();
328
329        connection
330            .exec_bound("INSERT INTO bools(t, f) VALUES (?, ?)")
331            .unwrap()((true, false))
332        .unwrap();
333
334        assert_eq!(
335            connection
336                .select_row::<(bool, bool)>("SELECT * FROM bools;")
337                .unwrap()()
338            .unwrap(),
339            Some((true, false))
340        );
341    }
342
343    #[test]
344    fn backup_works() {
345        let connection1 = Connection::open_memory(Some("backup_works"));
346        connection1
347            .exec(indoc! {"
348                CREATE TABLE blobs (
349                    data BLOB
350                );"})
351            .unwrap()()
352        .unwrap();
353        let blob = vec![0, 1, 2, 4, 8, 16, 32, 64];
354        connection1
355            .exec_bound::<Vec<u8>>("INSERT INTO blobs (data) VALUES (?);")
356            .unwrap()(blob.clone())
357        .unwrap();
358
359        // Backup connection1 to connection2
360        let connection2 = Connection::open_memory(Some("backup_works_other"));
361        connection1.backup_main(&connection2).unwrap();
362
363        // Delete the added blob and verify its deleted on the other side
364        let read_blobs = connection1
365            .select::<Vec<u8>>("SELECT * FROM blobs;")
366            .unwrap()()
367        .unwrap();
368        assert_eq!(read_blobs, vec![blob]);
369    }
370
371    #[test]
372    fn multi_step_statement_works() {
373        let connection = Connection::open_memory(Some("multi_step_statement_works"));
374
375        connection
376            .exec(indoc! {"
377                CREATE TABLE test (
378                    col INTEGER
379                )"})
380            .unwrap()()
381        .unwrap();
382
383        connection
384            .exec(indoc! {"
385            INSERT INTO test(col) VALUES (2)"})
386            .unwrap()()
387        .unwrap();
388
389        assert_eq!(
390            connection
391                .select_row::<usize>("SELECT * FROM test")
392                .unwrap()()
393            .unwrap(),
394            Some(2)
395        );
396    }
397
398    #[test]
399    fn test_sql_has_syntax_errors() {
400        let connection = Connection::open_memory(Some("test_sql_has_syntax_errors"));
401        let first_stmt =
402            "CREATE TABLE kv_store(key TEXT PRIMARY KEY, value TEXT NOT NULL) STRICT ;";
403        let second_stmt = "SELECT FROM";
404
405        let second_offset = connection.sql_has_syntax_error(second_stmt).unwrap().1;
406
407        let res = connection
408            .sql_has_syntax_error(&format!("{}\n{}", first_stmt, second_stmt))
409            .map(|(_, offset)| offset);
410
411        assert_eq!(res, Some(first_stmt.len() + second_offset + 1));
412    }
413
414    #[test]
415    fn test_alter_table_syntax() {
416        let connection = Connection::open_memory(Some("test_alter_table_syntax"));
417
418        assert!(connection
419            .sql_has_syntax_error("ALTER TABLE test ADD x TEXT")
420            .is_none());
421
422        assert!(connection
423            .sql_has_syntax_error("ALTER TABLE test AAD x TEXT")
424            .is_some());
425    }
426}