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