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 {
227                        "__place_holder_column_for_syntax_checking".to_string()
228                    };
229                return Some((table_to_alter, column_name));
230            }
231        }
232    }
233    None
234}
235
236impl Drop for Connection {
237    fn drop(&mut self) {
238        unsafe { sqlite3_close(self.sqlite3) };
239    }
240}
241
242#[cfg(test)]
243mod test {
244    use anyhow::Result;
245    use indoc::indoc;
246
247    use crate::connection::Connection;
248
249    #[test]
250    fn string_round_trips() -> Result<()> {
251        let connection = Connection::open_memory(Some("string_round_trips"));
252        connection
253            .exec(indoc! {"
254            CREATE TABLE text (
255                text TEXT
256            );"})
257            .unwrap()()
258        .unwrap();
259
260        let text = "Some test text";
261
262        connection
263            .exec_bound("INSERT INTO text (text) VALUES (?);")
264            .unwrap()(text)
265        .unwrap();
266
267        assert_eq!(
268            connection.select_row("SELECT text FROM text;").unwrap()().unwrap(),
269            Some(text.to_string())
270        );
271
272        Ok(())
273    }
274
275    #[test]
276    fn tuple_round_trips() {
277        let connection = Connection::open_memory(Some("tuple_round_trips"));
278        connection
279            .exec(indoc! {"
280                CREATE TABLE test (
281                    text TEXT,
282                    integer INTEGER,
283                    blob BLOB
284                );"})
285            .unwrap()()
286        .unwrap();
287
288        let tuple1 = ("test".to_string(), 64, vec![0, 1, 2, 4, 8, 16, 32, 64]);
289        let tuple2 = ("test2".to_string(), 32, vec![64, 32, 16, 8, 4, 2, 1, 0]);
290
291        let mut insert = connection
292            .exec_bound::<(String, usize, Vec<u8>)>(
293                "INSERT INTO test (text, integer, blob) VALUES (?, ?, ?)",
294            )
295            .unwrap();
296
297        insert(tuple1.clone()).unwrap();
298        insert(tuple2.clone()).unwrap();
299
300        assert_eq!(
301            connection
302                .select::<(String, usize, Vec<u8>)>("SELECT * FROM test")
303                .unwrap()()
304            .unwrap(),
305            vec![tuple1, tuple2]
306        );
307    }
308
309    #[test]
310    fn bool_round_trips() {
311        let connection = Connection::open_memory(Some("bool_round_trips"));
312        connection
313            .exec(indoc! {"
314                CREATE TABLE bools (
315                    t INTEGER,
316                    f INTEGER
317                );"})
318            .unwrap()()
319        .unwrap();
320
321        connection
322            .exec_bound("INSERT INTO bools(t, f) VALUES (?, ?)")
323            .unwrap()((true, false))
324        .unwrap();
325
326        assert_eq!(
327            connection
328                .select_row::<(bool, bool)>("SELECT * FROM bools;")
329                .unwrap()()
330            .unwrap(),
331            Some((true, false))
332        );
333    }
334
335    #[test]
336    fn backup_works() {
337        let connection1 = Connection::open_memory(Some("backup_works"));
338        connection1
339            .exec(indoc! {"
340                CREATE TABLE blobs (
341                    data BLOB
342                );"})
343            .unwrap()()
344        .unwrap();
345        let blob = vec![0, 1, 2, 4, 8, 16, 32, 64];
346        connection1
347            .exec_bound::<Vec<u8>>("INSERT INTO blobs (data) VALUES (?);")
348            .unwrap()(blob.clone())
349        .unwrap();
350
351        // Backup connection1 to connection2
352        let connection2 = Connection::open_memory(Some("backup_works_other"));
353        connection1.backup_main(&connection2).unwrap();
354
355        // Delete the added blob and verify its deleted on the other side
356        let read_blobs = connection1
357            .select::<Vec<u8>>("SELECT * FROM blobs;")
358            .unwrap()()
359        .unwrap();
360        assert_eq!(read_blobs, vec![blob]);
361    }
362
363    #[test]
364    fn multi_step_statement_works() {
365        let connection = Connection::open_memory(Some("multi_step_statement_works"));
366
367        connection
368            .exec(indoc! {"
369                CREATE TABLE test (
370                    col INTEGER
371                )"})
372            .unwrap()()
373        .unwrap();
374
375        connection
376            .exec(indoc! {"
377            INSERT INTO test(col) VALUES (2)"})
378            .unwrap()()
379        .unwrap();
380
381        assert_eq!(
382            connection
383                .select_row::<usize>("SELECT * FROM test")
384                .unwrap()()
385            .unwrap(),
386            Some(2)
387        );
388    }
389
390    #[test]
391    fn test_sql_has_syntax_errors() {
392        let connection = Connection::open_memory(Some("test_sql_has_syntax_errors"));
393        let first_stmt =
394            "CREATE TABLE kv_store(key TEXT PRIMARY KEY, value TEXT NOT NULL) STRICT ;";
395        let second_stmt = "SELECT FROM";
396
397        let second_offset = connection.sql_has_syntax_error(second_stmt).unwrap().1;
398
399        let res = connection
400            .sql_has_syntax_error(&format!("{}\n{}", first_stmt, second_stmt))
401            .map(|(_, offset)| offset);
402
403        assert_eq!(res, Some(first_stmt.len() + second_offset + 1));
404    }
405
406    #[test]
407    fn test_alter_table_syntax() {
408        let connection = Connection::open_memory(Some("test_alter_table_syntax"));
409
410        assert!(connection
411            .sql_has_syntax_error("ALTER TABLE test ADD x TEXT")
412            .is_none());
413
414        assert!(connection
415            .sql_has_syntax_error("ALTER TABLE test AAD x TEXT")
416            .is_some());
417    }
418}