connection.rs

  1use std::{
  2    cell::RefCell,
  3    ffi::{CStr, CString},
  4    marker::PhantomData,
  5    path::Path,
  6    ptr,
  7};
  8
  9use 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                        #[cfg(not(any(target_os = "linux", target_os = "freebsd")))]
132                        let offset = sqlite3_error_offset(temp_connection.sqlite3);
133
134                        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
135                        let offset = 0;
136
137                        (
138                            sqlite3_errcode(temp_connection.sqlite3),
139                            offset,
140                            sqlite3_errmsg(temp_connection.sqlite3),
141                            Some(temp_connection),
142                        )
143                    } else {
144                        sqlite3_prepare_v2(
145                            self.sqlite3,
146                            remaining_sql.as_ptr(),
147                            -1,
148                            &mut raw_statement,
149                            &mut remaining_sql_ptr,
150                        );
151
152                        #[cfg(not(any(target_os = "linux", target_os = "freebsd")))]
153                        let offset = sqlite3_error_offset(self.sqlite3);
154
155                        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
156                        let offset = 0;
157
158                        (
159                            sqlite3_errcode(self.sqlite3),
160                            offset,
161                            sqlite3_errmsg(self.sqlite3),
162                            None,
163                        )
164                    };
165
166                sqlite3_finalize(raw_statement);
167
168                if res == 1 && offset >= 0 {
169                    let sub_statement_correction =
170                        remaining_sql.as_ptr() as usize - sql_start as usize;
171                    let err_msg =
172                        String::from_utf8_lossy(CStr::from_ptr(message as *const _).to_bytes())
173                            .into_owned();
174
175                    return Some((err_msg, offset as usize + sub_statement_correction));
176                }
177                remaining_sql = CStr::from_ptr(remaining_sql_ptr);
178                alter_table = None;
179            }
180        }
181        None
182    }
183
184    pub(crate) fn last_error(&self) -> Result<()> {
185        unsafe {
186            let code = sqlite3_errcode(self.sqlite3);
187            const NON_ERROR_CODES: &[i32] = &[SQLITE_OK, SQLITE_ROW];
188            if NON_ERROR_CODES.contains(&code) {
189                return Ok(());
190            }
191
192            let message = sqlite3_errmsg(self.sqlite3);
193            let message = if message.is_null() {
194                None
195            } else {
196                Some(
197                    String::from_utf8_lossy(CStr::from_ptr(message as *const _).to_bytes())
198                        .into_owned(),
199                )
200            };
201
202            anyhow::bail!("Sqlite call failed with code {code} and message: {message:?}")
203        }
204    }
205
206    pub(crate) fn with_write<T>(&self, callback: impl FnOnce(&Connection) -> T) -> T {
207        *self.write.borrow_mut() = true;
208        let result = callback(self);
209        *self.write.borrow_mut() = false;
210        result
211    }
212}
213
214fn parse_alter_table(remaining_sql_str: &str) -> Option<(String, String)> {
215    let remaining_sql_str = remaining_sql_str.to_lowercase();
216    if remaining_sql_str.starts_with("alter") {
217        if let Some(table_offset) = remaining_sql_str.find("table") {
218            let after_table_offset = table_offset + "table".len();
219            let table_to_alter = remaining_sql_str
220                .chars()
221                .skip(after_table_offset)
222                .skip_while(|c| c.is_whitespace())
223                .take_while(|c| !c.is_whitespace())
224                .collect::<String>();
225            if !table_to_alter.is_empty() {
226                let column_name =
227                    if let Some(rename_offset) = remaining_sql_str.find("rename column") {
228                        let after_rename_offset = rename_offset + "rename column".len();
229                        remaining_sql_str
230                            .chars()
231                            .skip(after_rename_offset)
232                            .skip_while(|c| c.is_whitespace())
233                            .take_while(|c| !c.is_whitespace())
234                            .collect::<String>()
235                    } else if let Some(drop_offset) = remaining_sql_str.find("drop column") {
236                        let after_drop_offset = drop_offset + "drop column".len();
237                        remaining_sql_str
238                            .chars()
239                            .skip(after_drop_offset)
240                            .skip_while(|c| c.is_whitespace())
241                            .take_while(|c| !c.is_whitespace())
242                            .collect::<String>()
243                    } else {
244                        "__place_holder_column_for_syntax_checking".to_string()
245                    };
246                return Some((table_to_alter, column_name));
247            }
248        }
249    }
250    None
251}
252
253impl Drop for Connection {
254    fn drop(&mut self) {
255        unsafe { sqlite3_close(self.sqlite3) };
256    }
257}
258
259#[cfg(test)]
260mod test {
261    use anyhow::Result;
262    use indoc::indoc;
263
264    use crate::connection::Connection;
265
266    #[test]
267    fn string_round_trips() -> Result<()> {
268        let connection = Connection::open_memory(Some("string_round_trips"));
269        connection
270            .exec(indoc! {"
271            CREATE TABLE text (
272                text TEXT
273            );"})
274            .unwrap()()
275        .unwrap();
276
277        let text = "Some test text";
278
279        connection
280            .exec_bound("INSERT INTO text (text) VALUES (?);")
281            .unwrap()(text)
282        .unwrap();
283
284        assert_eq!(
285            connection.select_row("SELECT text FROM text;").unwrap()().unwrap(),
286            Some(text.to_string())
287        );
288
289        Ok(())
290    }
291
292    #[test]
293    fn tuple_round_trips() {
294        let connection = Connection::open_memory(Some("tuple_round_trips"));
295        connection
296            .exec(indoc! {"
297                CREATE TABLE test (
298                    text TEXT,
299                    integer INTEGER,
300                    blob BLOB
301                );"})
302            .unwrap()()
303        .unwrap();
304
305        let tuple1 = ("test".to_string(), 64, vec![0, 1, 2, 4, 8, 16, 32, 64]);
306        let tuple2 = ("test2".to_string(), 32, vec![64, 32, 16, 8, 4, 2, 1, 0]);
307
308        let mut insert = connection
309            .exec_bound::<(String, usize, Vec<u8>)>(
310                "INSERT INTO test (text, integer, blob) VALUES (?, ?, ?)",
311            )
312            .unwrap();
313
314        insert(tuple1.clone()).unwrap();
315        insert(tuple2.clone()).unwrap();
316
317        assert_eq!(
318            connection
319                .select::<(String, usize, Vec<u8>)>("SELECT * FROM test")
320                .unwrap()()
321            .unwrap(),
322            vec![tuple1, tuple2]
323        );
324    }
325
326    #[test]
327    fn bool_round_trips() {
328        let connection = Connection::open_memory(Some("bool_round_trips"));
329        connection
330            .exec(indoc! {"
331                CREATE TABLE bools (
332                    t INTEGER,
333                    f INTEGER
334                );"})
335            .unwrap()()
336        .unwrap();
337
338        connection
339            .exec_bound("INSERT INTO bools(t, f) VALUES (?, ?)")
340            .unwrap()((true, false))
341        .unwrap();
342
343        assert_eq!(
344            connection
345                .select_row::<(bool, bool)>("SELECT * FROM bools;")
346                .unwrap()()
347            .unwrap(),
348            Some((true, false))
349        );
350    }
351
352    #[test]
353    fn backup_works() {
354        let connection1 = Connection::open_memory(Some("backup_works"));
355        connection1
356            .exec(indoc! {"
357                CREATE TABLE blobs (
358                    data BLOB
359                );"})
360            .unwrap()()
361        .unwrap();
362        let blob = vec![0, 1, 2, 4, 8, 16, 32, 64];
363        connection1
364            .exec_bound::<Vec<u8>>("INSERT INTO blobs (data) VALUES (?);")
365            .unwrap()(blob.clone())
366        .unwrap();
367
368        // Backup connection1 to connection2
369        let connection2 = Connection::open_memory(Some("backup_works_other"));
370        connection1.backup_main(&connection2).unwrap();
371
372        // Delete the added blob and verify its deleted on the other side
373        let read_blobs = connection1
374            .select::<Vec<u8>>("SELECT * FROM blobs;")
375            .unwrap()()
376        .unwrap();
377        assert_eq!(read_blobs, vec![blob]);
378    }
379
380    #[test]
381    fn multi_step_statement_works() {
382        let connection = Connection::open_memory(Some("multi_step_statement_works"));
383
384        connection
385            .exec(indoc! {"
386                CREATE TABLE test (
387                    col INTEGER
388                )"})
389            .unwrap()()
390        .unwrap();
391
392        connection
393            .exec(indoc! {"
394            INSERT INTO test(col) VALUES (2)"})
395            .unwrap()()
396        .unwrap();
397
398        assert_eq!(
399            connection
400                .select_row::<usize>("SELECT * FROM test")
401                .unwrap()()
402            .unwrap(),
403            Some(2)
404        );
405    }
406
407    #[cfg(not(any(target_os = "linux", target_os = "freebsd")))]
408    #[test]
409    fn test_sql_has_syntax_errors() {
410        let connection = Connection::open_memory(Some("test_sql_has_syntax_errors"));
411        let first_stmt =
412            "CREATE TABLE kv_store(key TEXT PRIMARY KEY, value TEXT NOT NULL) STRICT ;";
413        let second_stmt = "SELECT FROM";
414
415        let second_offset = connection.sql_has_syntax_error(second_stmt).unwrap().1;
416
417        let res = connection
418            .sql_has_syntax_error(&format!("{}\n{}", first_stmt, second_stmt))
419            .map(|(_, offset)| offset);
420
421        assert_eq!(res, Some(first_stmt.len() + second_offset + 1));
422    }
423
424    #[test]
425    fn test_alter_table_syntax() {
426        let connection = Connection::open_memory(Some("test_alter_table_syntax"));
427
428        assert!(
429            connection
430                .sql_has_syntax_error("ALTER TABLE test ADD x TEXT")
431                .is_none()
432        );
433
434        assert!(
435            connection
436                .sql_has_syntax_error("ALTER TABLE test AAD x TEXT")
437                .is_some()
438        );
439    }
440}