From 3b575c3b4ae3e64bcb71f34e373fd156e15b6b1e Mon Sep 17 00:00:00 2001 From: gwenn Date: Tue, 25 Apr 2017 20:58:22 +0200 Subject: [PATCH 1/7] Implementation of sqlite3_update_hook #260 First draft (no tested and a memory leak) --- .travis.yml | 9 +-- Cargo.toml | 1 + appveyor.yml | 8 +-- src/hooks.rs | 158 +++++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 2 + 5 files changed, 170 insertions(+), 8 deletions(-) create mode 100644 src/hooks.rs diff --git a/.travis.yml b/.travis.yml index dd9573f..d6a8990 100644 --- a/.travis.yml +++ b/.travis.yml @@ -30,13 +30,14 @@ script: - cargo test --features backup - cargo test --features blob - cargo test --features functions + - cargo test --features hooks - cargo test --features limits - cargo test --features load_extension - cargo test --features trace - cargo test --features chrono - cargo test --features serde_json - cargo test --features bundled - - cargo test --features "backup blob chrono functions limits load_extension serde_json trace" - - cargo test --features "backup blob chrono functions limits load_extension serde_json trace buildtime_bindgen" - - cargo test --features "backup blob chrono functions limits load_extension serde_json trace bundled" - - cargo test --features "backup blob chrono functions limits load_extension serde_json trace bundled buildtime_bindgen" + - cargo test --features "backup blob chrono functions hooks limits load_extension serde_json trace" + - cargo test --features "backup blob chrono functions hooks limits load_extension serde_json trace buildtime_bindgen" + - cargo test --features "backup blob chrono functions hooks limits load_extension serde_json trace bundled" + - cargo test --features "backup blob chrono functions hooks limits load_extension serde_json trace bundled buildtime_bindgen" diff --git a/Cargo.toml b/Cargo.toml index 6e9fd53..65aa744 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,6 +26,7 @@ trace = ["libsqlite3-sys/min_sqlite_version_3_6_23"] bundled = ["libsqlite3-sys/bundled"] buildtime_bindgen = ["libsqlite3-sys/buildtime_bindgen"] limits = [] +hooks = [] [dependencies] time = "0.1.0" diff --git a/appveyor.yml b/appveyor.yml index 2d7a1c3..d7801eb 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -20,10 +20,10 @@ build: false test_script: - cargo test --lib --verbose - cargo test --lib --verbose --features bundled - - cargo test --lib --features "backup blob chrono functions limits load_extension serde_json trace" - - cargo test --lib --features "backup blob chrono functions limits load_extension serde_json trace buildtime_bindgen" - - cargo test --lib --features "backup blob chrono functions limits load_extension serde_json trace bundled" - - cargo test --lib --features "backup blob chrono functions limits load_extension serde_json trace bundled buildtime_bindgen" + - cargo test --lib --features "backup blob chrono functions hooks limits load_extension serde_json trace" + - cargo test --lib --features "backup blob chrono functions hooks limits load_extension serde_json trace buildtime_bindgen" + - cargo test --lib --features "backup blob chrono functions hooks limits load_extension serde_json trace bundled" + - cargo test --lib --features "backup blob chrono functions hooks limits load_extension serde_json trace bundled buildtime_bindgen" cache: - C:\Users\appveyor\.cargo diff --git a/src/hooks.rs b/src/hooks.rs new file mode 100644 index 0000000..88b08d8 --- /dev/null +++ b/src/hooks.rs @@ -0,0 +1,158 @@ +//! Data Change Notification Callbacks +#![allow(non_camel_case_types)] + +use std::mem; +use std::ptr; +use std::os::raw::{c_int, c_char, c_void}; + +use ffi; + +use {Connection, InnerConnection}; + +// Commit And Rollback Notification Callbacks +// http://sqlite.org/c3ref/commit_hook.html +/* +void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); +void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); +*/ + +/// Authorizer Action Codes +pub enum Action { + UNKNOWN = -1, + SQLITE_CREATE_INDEX = ffi::SQLITE_CREATE_INDEX as isize, + SQLITE_CREATE_TABLE = ffi::SQLITE_CREATE_TABLE as isize, + SQLITE_CREATE_TEMP_INDEX = ffi::SQLITE_CREATE_TEMP_INDEX as isize, + SQLITE_CREATE_TEMP_TABLE = ffi::SQLITE_CREATE_TEMP_TABLE as isize, + SQLITE_CREATE_TEMP_TRIGGER = ffi::SQLITE_CREATE_TEMP_TRIGGER as isize, + SQLITE_CREATE_TEMP_VIEW = ffi::SQLITE_CREATE_TEMP_VIEW as isize, + SQLITE_CREATE_TRIGGER = ffi::SQLITE_CREATE_TRIGGER as isize, + SQLITE_CREATE_VIEW = ffi::SQLITE_CREATE_VIEW as isize, + SQLITE_DELETE = ffi::SQLITE_DELETE as isize, + SQLITE_DROP_INDEX = ffi::SQLITE_DROP_INDEX as isize, + SQLITE_DROP_TABLE = ffi::SQLITE_DROP_TABLE as isize, + SQLITE_DROP_TEMP_INDEX = ffi::SQLITE_DROP_TEMP_INDEX as isize, + SQLITE_DROP_TEMP_TABLE = ffi::SQLITE_DROP_TEMP_TABLE as isize, + SQLITE_DROP_TEMP_TRIGGER = ffi::SQLITE_DROP_TEMP_TRIGGER as isize, + SQLITE_DROP_TEMP_VIEW = ffi::SQLITE_DROP_TEMP_VIEW as isize, + SQLITE_DROP_TRIGGER = ffi::SQLITE_DROP_TRIGGER as isize, + SQLITE_DROP_VIEW = ffi::SQLITE_DROP_VIEW as isize, + SQLITE_INSERT = ffi::SQLITE_INSERT as isize, + SQLITE_PRAGMA = ffi::SQLITE_PRAGMA as isize, + SQLITE_READ = ffi::SQLITE_READ as isize, + SQLITE_SELECT = ffi::SQLITE_SELECT as isize, + SQLITE_TRANSACTION = ffi::SQLITE_TRANSACTION as isize, + SQLITE_UPDATE = ffi::SQLITE_UPDATE as isize, + SQLITE_ATTACH = ffi::SQLITE_ATTACH as isize, + SQLITE_DETACH = ffi::SQLITE_DETACH as isize, + SQLITE_ALTER_TABLE = ffi::SQLITE_ALTER_TABLE as isize, + SQLITE_REINDEX = ffi::SQLITE_REINDEX as isize, + SQLITE_ANALYZE = ffi::SQLITE_ANALYZE as isize, + SQLITE_CREATE_VTABLE = ffi::SQLITE_CREATE_VTABLE as isize, + SQLITE_DROP_VTABLE = ffi::SQLITE_DROP_VTABLE as isize, + SQLITE_FUNCTION = ffi::SQLITE_FUNCTION as isize, + SQLITE_SAVEPOINT = ffi::SQLITE_SAVEPOINT as isize, + SQLITE_COPY = ffi::SQLITE_COPY as isize, + SQLITE_RECURSIVE = ffi::SQLITE_RECURSIVE as isize, +} + +impl From for Action { + fn from(code: i32) -> Action { + match code { + ffi::SQLITE_CREATE_INDEX => Action::SQLITE_CREATE_INDEX, + ffi::SQLITE_CREATE_TABLE => Action::SQLITE_CREATE_TABLE, + ffi::SQLITE_CREATE_TEMP_INDEX => Action::SQLITE_CREATE_TEMP_INDEX, + ffi::SQLITE_CREATE_TEMP_TABLE => Action::SQLITE_CREATE_TEMP_TABLE, + ffi::SQLITE_CREATE_TEMP_TRIGGER => Action::SQLITE_CREATE_TEMP_TRIGGER, + ffi::SQLITE_CREATE_TEMP_VIEW => Action::SQLITE_CREATE_TEMP_VIEW, + ffi::SQLITE_CREATE_TRIGGER => Action::SQLITE_CREATE_TRIGGER, + ffi::SQLITE_CREATE_VIEW => Action::SQLITE_CREATE_VIEW, + ffi::SQLITE_DELETE => Action::SQLITE_DELETE, + ffi::SQLITE_DROP_INDEX => Action::SQLITE_DROP_INDEX, + ffi::SQLITE_DROP_TABLE => Action::SQLITE_DROP_TABLE, + ffi::SQLITE_DROP_TEMP_INDEX => Action::SQLITE_DROP_TEMP_INDEX, + ffi::SQLITE_DROP_TEMP_TABLE => Action::SQLITE_DROP_TEMP_TABLE, + ffi::SQLITE_DROP_TEMP_TRIGGER => Action::SQLITE_DROP_TEMP_TRIGGER, + ffi::SQLITE_DROP_TEMP_VIEW => Action::SQLITE_DROP_TEMP_VIEW, + ffi::SQLITE_DROP_TRIGGER => Action::SQLITE_DROP_TRIGGER, + ffi::SQLITE_DROP_VIEW => Action::SQLITE_DROP_VIEW, + ffi::SQLITE_INSERT => Action::SQLITE_INSERT, + ffi::SQLITE_PRAGMA => Action::SQLITE_PRAGMA, + ffi::SQLITE_READ => Action::SQLITE_READ, + ffi::SQLITE_SELECT => Action::SQLITE_SELECT, + ffi::SQLITE_TRANSACTION => Action::SQLITE_TRANSACTION, + ffi::SQLITE_UPDATE => Action::SQLITE_UPDATE, + ffi::SQLITE_ATTACH => Action::SQLITE_ATTACH, + ffi::SQLITE_DETACH => Action::SQLITE_DETACH, + ffi::SQLITE_ALTER_TABLE => Action::SQLITE_ALTER_TABLE, + ffi::SQLITE_REINDEX => Action::SQLITE_REINDEX, + ffi::SQLITE_ANALYZE => Action::SQLITE_ANALYZE, + ffi::SQLITE_CREATE_VTABLE => Action::SQLITE_CREATE_VTABLE, + ffi::SQLITE_DROP_VTABLE => Action::SQLITE_DROP_VTABLE, + ffi::SQLITE_FUNCTION => Action::SQLITE_FUNCTION, + ffi::SQLITE_SAVEPOINT => Action::SQLITE_SAVEPOINT, + ffi::SQLITE_COPY => Action::SQLITE_COPY, + ffi::SQLITE_RECURSIVE => Action::SQLITE_RECURSIVE, + _ => Action::UNKNOWN, + } + } +} + +impl Connection { + pub fn update_hook(&self, hook: Option) + where F: FnMut(Action, &str, &str, i64) + { + self.db.borrow_mut().update_hook(hook); + } +} + +impl InnerConnection { + // TODO self.update_hook(None) must be called in InnerConnection#close to free any hook + fn update_hook(&mut self, hook: Option) + where F: FnMut(Action, &str, &str, i64) + { + unsafe extern "C" fn call_boxed_closure(p_arg: *mut c_void, + action_code: c_int, + db_str: *const c_char, + tbl_str: *const c_char, + row_id: i64) + where F: FnMut(Action, &str, &str, i64) + { + use std::ffi::CStr; + use std::str; + + let boxed_hook: *mut F = mem::transmute(p_arg); + assert!(!boxed_hook.is_null(), + "Internal error - null function pointer"); + + let action = Action::from(action_code); + let db_name = { + let c_slice = CStr::from_ptr(db_str).to_bytes(); + str::from_utf8_unchecked(c_slice) + }; + let tbl_name = { + let c_slice = CStr::from_ptr(tbl_str).to_bytes(); + str::from_utf8_unchecked(c_slice) + }; + + (*boxed_hook)(action, db_name, tbl_name, row_id); + } + + let previous_hook = if let Some(hook) = hook { + let boxed_hook: *mut F = Box::into_raw(Box::new(hook)); + unsafe { + ffi::sqlite3_update_hook(self.db(), + Some(call_boxed_closure::), + mem::transmute(boxed_hook)) + } + } else { + unsafe { ffi::sqlite3_update_hook(self.db(), None, ptr::null_mut()) } + }; + // TODO Validate: what happens if the previous hook has been set from C ? + if !previous_hook.is_null() { + // free_boxed_value + unsafe { + let _: Box = Box::from_raw(mem::transmute(previous_hook)); + } + } + } +} diff --git a/src/lib.rs b/src/lib.rs index 9c0f45a..4e0d741 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -121,6 +121,8 @@ pub mod functions; pub mod blob; #[cfg(feature = "limits")] pub mod limits; +#[cfg(feature = "hooks")] +pub mod hooks; // Number of cached prepared statements we'll hold on to. const STATEMENT_CACHE_DEFAULT_CAPACITY: usize = 16; From 6eb98afd67c4f2c4a82973a37e56d54c73cdcede Mon Sep 17 00:00:00 2001 From: gwenn Date: Tue, 25 Apr 2017 21:08:41 +0200 Subject: [PATCH 2/7] SQLITE_RECURSIVE is not available with SQLite 3.6.8 --- src/hooks.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/hooks.rs b/src/hooks.rs index 88b08d8..7b5fee9 100644 --- a/src/hooks.rs +++ b/src/hooks.rs @@ -52,7 +52,7 @@ pub enum Action { SQLITE_FUNCTION = ffi::SQLITE_FUNCTION as isize, SQLITE_SAVEPOINT = ffi::SQLITE_SAVEPOINT as isize, SQLITE_COPY = ffi::SQLITE_COPY as isize, - SQLITE_RECURSIVE = ffi::SQLITE_RECURSIVE as isize, + SQLITE_RECURSIVE = 33, } impl From for Action { From 63a444a95f5b8345ecb68c5bbb83cb0d929c736c Mon Sep 17 00:00:00 2001 From: gwenn Date: Wed, 26 Apr 2017 20:12:48 +0200 Subject: [PATCH 3/7] Fix memory leak and add test --- src/hooks.rs | 82 +++++++++++++++++++++++++++++++++++++++------------- src/lib.rs | 5 ++++ 2 files changed, 67 insertions(+), 20 deletions(-) diff --git a/src/hooks.rs b/src/hooks.rs index 7b5fee9..42f88b6 100644 --- a/src/hooks.rs +++ b/src/hooks.rs @@ -16,7 +16,9 @@ void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); */ + /// Authorizer Action Codes +#[derive(Debug, PartialEq)] pub enum Action { UNKNOWN = -1, SQLITE_CREATE_INDEX = ffi::SQLITE_CREATE_INDEX as isize, @@ -91,23 +93,31 @@ impl From for Action { ffi::SQLITE_FUNCTION => Action::SQLITE_FUNCTION, ffi::SQLITE_SAVEPOINT => Action::SQLITE_SAVEPOINT, ffi::SQLITE_COPY => Action::SQLITE_COPY, - ffi::SQLITE_RECURSIVE => Action::SQLITE_RECURSIVE, + 33 => Action::SQLITE_RECURSIVE, _ => Action::UNKNOWN, } } } impl Connection { - pub fn update_hook(&self, hook: Option) + /// Register a callback function to be invoked whenever a row is updated, inserted or deleted in a rowid table. + pub fn update_hook(&self, hook: F) where F: FnMut(Action, &str, &str, i64) { self.db.borrow_mut().update_hook(hook); } + + pub fn remove_update_hook(&self) { + self.db.borrow_mut().remove_update_hook(); + } } impl InnerConnection { - // TODO self.update_hook(None) must be called in InnerConnection#close to free any hook - fn update_hook(&mut self, hook: Option) + pub fn remove_hooks(&mut self) { + self.remove_update_hook(); + } + + fn update_hook(&mut self, hook: F) where F: FnMut(Action, &str, &str, i64) { unsafe extern "C" fn call_boxed_closure(p_arg: *mut c_void, @@ -120,9 +130,7 @@ impl InnerConnection { use std::ffi::CStr; use std::str; - let boxed_hook: *mut F = mem::transmute(p_arg); - assert!(!boxed_hook.is_null(), - "Internal error - null function pointer"); + let boxed_hook: &mut Box = mem::transmute(p_arg); let action = Action::from(action_code); let db_name = { @@ -134,25 +142,59 @@ impl InnerConnection { str::from_utf8_unchecked(c_slice) }; - (*boxed_hook)(action, db_name, tbl_name, row_id); + boxed_hook(action, db_name, tbl_name, row_id); } - let previous_hook = if let Some(hook) = hook { - let boxed_hook: *mut F = Box::into_raw(Box::new(hook)); + let previous_hook = { + let boxed_hook: Box> = Box::new(Box::new(hook)); unsafe { ffi::sqlite3_update_hook(self.db(), Some(call_boxed_closure::), - mem::transmute(boxed_hook)) + Box::into_raw(boxed_hook) as *mut _) } - } else { - unsafe { ffi::sqlite3_update_hook(self.db(), None, ptr::null_mut()) } }; - // TODO Validate: what happens if the previous hook has been set from C ? - if !previous_hook.is_null() { - // free_boxed_value - unsafe { - let _: Box = Box::from_raw(mem::transmute(previous_hook)); - } - } + free_boxed_update_hook(previous_hook); + } + + fn remove_update_hook(&mut self) { + let previous_hook = unsafe { ffi::sqlite3_update_hook(self.db(), None, ptr::null_mut()) }; + free_boxed_update_hook(previous_hook); + } + +} + +fn free_boxed_update_hook(hook: *mut c_void) { + /* + http://stackoverflow.com/questions/32270030/how-do-i-convert-a-rust-closure-to-a-c-style-callback + Double indirection (i.e. Box>) is necessary + because Box ..> is a trait object and therefore a fat pointer, + incompatible with *mut c_void because of different size. + */ + if !hook.is_null() { + let _: Box> = unsafe { Box::from_raw(hook as *mut _) }; + } +} + +#[cfg(test)] +mod test { + use super::Action; + use Connection; + + #[test] + fn test_update_hook() { + let db = Connection::open_in_memory().unwrap(); + + let mut called = false; + db.update_hook(|action, db, tbl, row_id| { + assert_eq!(Action::SQLITE_INSERT, action); + assert_eq!("main", db); + assert_eq!("foo", tbl); + assert_eq!(1, row_id); + called = true; + }); + db.execute_batch("CREATE TABLE foo (t TEXT)").unwrap(); + db.execute_batch("INSERT INTO foo VALUES ('lisa')") + .unwrap(); + assert!(called); } } diff --git a/src/lib.rs b/src/lib.rs index 4e0d741..a55cd9b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -781,6 +781,7 @@ impl InnerConnection { } fn close(&mut self) -> Result<()> { + self.remove_hooks(); unsafe { let r = ffi::sqlite3_close(self.db()); let r = self.decode_result(r); @@ -857,6 +858,10 @@ impl InnerConnection { fn changes(&mut self) -> c_int { unsafe { ffi::sqlite3_changes(self.db()) } } + + #[cfg(not(feature = "hooks"))] + fn remove_hooks(&mut self) { + } } impl Drop for InnerConnection { From 3e6fffaf94e181ddb93ada2ed1961bf191b836db Mon Sep 17 00:00:00 2001 From: gwenn Date: Thu, 27 Apr 2017 18:05:12 +0200 Subject: [PATCH 4/7] Due to rust monophormisation, there is no need for double indirection --- src/blob.rs | 5 ++--- src/hooks.rs | 18 +++++++----------- src/lib.rs | 3 +++ 3 files changed, 12 insertions(+), 14 deletions(-) diff --git a/src/blob.rs b/src/blob.rs index 4361366..06457d6 100644 --- a/src/blob.rs +++ b/src/blob.rs @@ -50,7 +50,6 @@ //! ``` use std::io; use std::cmp::min; -use std::mem; use std::ptr; use super::ffi; @@ -155,7 +154,7 @@ impl<'conn> io::Read for Blob<'conn> { return Ok(0); } let rc = - unsafe { ffi::sqlite3_blob_read(self.blob, mem::transmute(buf.as_ptr()), n, self.pos) }; + unsafe { ffi::sqlite3_blob_read(self.blob, buf.as_ptr() as *mut _, n, self.pos) }; self.conn .decode_result(rc) .map(|_| { @@ -184,7 +183,7 @@ impl<'conn> io::Write for Blob<'conn> { return Ok(0); } let rc = unsafe { - ffi::sqlite3_blob_write(self.blob, mem::transmute(buf.as_ptr()), n, self.pos) + ffi::sqlite3_blob_write(self.blob, buf.as_ptr() as *mut _, n, self.pos) }; self.conn .decode_result(rc) diff --git a/src/hooks.rs b/src/hooks.rs index 42f88b6..0f3b359 100644 --- a/src/hooks.rs +++ b/src/hooks.rs @@ -130,7 +130,8 @@ impl InnerConnection { use std::ffi::CStr; use std::str; - let boxed_hook: &mut Box = mem::transmute(p_arg); + let boxed_hook: *mut F = mem::transmute(p_arg); + assert!(!boxed_hook.is_null(), "Internal error - null function pointer"); let action = Action::from(action_code); let db_name = { @@ -142,15 +143,15 @@ impl InnerConnection { str::from_utf8_unchecked(c_slice) }; - boxed_hook(action, db_name, tbl_name, row_id); + (*boxed_hook)(action, db_name, tbl_name, row_id); } let previous_hook = { - let boxed_hook: Box> = Box::new(Box::new(hook)); + let boxed_hook: *mut F = Box::into_raw(Box::new(hook)); unsafe { ffi::sqlite3_update_hook(self.db(), Some(call_boxed_closure::), - Box::into_raw(boxed_hook) as *mut _) + boxed_hook as *mut _) } }; free_boxed_update_hook(previous_hook); @@ -164,14 +165,9 @@ impl InnerConnection { } fn free_boxed_update_hook(hook: *mut c_void) { - /* - http://stackoverflow.com/questions/32270030/how-do-i-convert-a-rust-closure-to-a-c-style-callback - Double indirection (i.e. Box>) is necessary - because Box ..> is a trait object and therefore a fat pointer, - incompatible with *mut c_void because of different size. - */ if !hook.is_null() { - let _: Box> = unsafe { Box::from_raw(hook as *mut _) }; + // TODO make sure that size_of::<*mut F>() is always equal to size_of::<*mut c_void>() + let _: Box<*mut c_void> = unsafe { Box::from_raw(hook as *mut _) }; } } diff --git a/src/lib.rs b/src/lib.rs index a55cd9b..949271a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -781,6 +781,9 @@ impl InnerConnection { } fn close(&mut self) -> Result<()> { + if self.db.is_null() { + return Ok(()); + } self.remove_hooks(); unsafe { let r = ffi::sqlite3_close(self.db()); From 466b8aab2fdaa3352ac605ade4d8eb5e4e1047b4 Mon Sep 17 00:00:00 2001 From: gwenn Date: Fri, 12 May 2017 19:12:10 +0200 Subject: [PATCH 5/7] Rename `row` parameter to `row_id` --- src/blob.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/blob.rs b/src/blob.rs index 06457d6..85364a6 100644 --- a/src/blob.rs +++ b/src/blob.rs @@ -64,7 +64,7 @@ pub struct Blob<'conn> { } impl Connection { - /// Open a handle to the BLOB located in `row`, `column`, `table` in database `db`. + /// Open a handle to the BLOB located in `row_id`, `column`, `table` in database `db`. /// /// # Failure /// @@ -74,7 +74,7 @@ impl Connection { db: DatabaseName, table: &str, column: &str, - row: i64, + row_id: i64, read_only: bool) -> Result> { let mut c = self.db.borrow_mut(); @@ -87,7 +87,7 @@ impl Connection { db.as_ptr(), table.as_ptr(), column.as_ptr(), - row, + row_id, if read_only { 0 } else { 1 }, &mut blob) }; From dfdd42fd09474686402ce12bba95205d35ddd164 Mon Sep 17 00:00:00 2001 From: gwenn Date: Fri, 12 May 2017 19:14:34 +0200 Subject: [PATCH 6/7] Bind sqlite3_commit_hook and sqlite3_rollback_hook --- src/hooks.rs | 134 ++++++++++++++++++++++++++++++++++++++++++++++----- src/lib.rs | 4 +- 2 files changed, 125 insertions(+), 13 deletions(-) diff --git a/src/hooks.rs b/src/hooks.rs index 0f3b359..3c6bb0b 100644 --- a/src/hooks.rs +++ b/src/hooks.rs @@ -1,4 +1,4 @@ -//! Data Change Notification Callbacks +//! Commit, Data Change and Rollback Notification Callbacks #![allow(non_camel_case_types)] use std::mem; @@ -9,14 +9,6 @@ use ffi; use {Connection, InnerConnection}; -// Commit And Rollback Notification Callbacks -// http://sqlite.org/c3ref/commit_hook.html -/* -void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); -void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); -*/ - - /// Authorizer Action Codes #[derive(Debug, PartialEq)] pub enum Action { @@ -100,21 +92,105 @@ impl From for Action { } impl Connection { + /// Register a callback function to be invoked whenever a transaction is committed. + /// + /// The callback returns `true` to rollback. + pub fn commit_hook(&self, hook: F) + where F: FnMut() -> bool + { + self.db.borrow_mut().commit_hook(hook); + } + + /// Register a callback function to be invoked whenever a transaction is committed. + /// + /// The callback returns `true` to rollback. + pub fn rollback_hook(&self, hook: F) + where F: FnMut() + { + self.db.borrow_mut().rollback_hook(hook); + } + /// Register a callback function to be invoked whenever a row is updated, inserted or deleted in a rowid table. + /// + /// The callback parameters are: + /// + /// - the type of database update (SQLITE_INSERT, SQLITE_UPDATE or SQLITE_DELETE), + /// - the name of the database ("main", "temp", ...), + /// - the name of the table that is updated, + /// - the ROWID of the row that is updated. pub fn update_hook(&self, hook: F) where F: FnMut(Action, &str, &str, i64) { self.db.borrow_mut().update_hook(hook); } + /// Remove hook installed by `update_hook`. pub fn remove_update_hook(&self) { self.db.borrow_mut().remove_update_hook(); } + + /// Remove hook installed by `commit_hook`. + pub fn remove_commit_hook(&self) { + self.db.borrow_mut().remove_commit_hook(); + } + + /// Remove hook installed by `rollback_hook`. + pub fn remove_rollback_hook(&self) { + self.db.borrow_mut().remove_rollback_hook(); + } } impl InnerConnection { pub fn remove_hooks(&mut self) { self.remove_update_hook(); + self.remove_commit_hook(); + self.remove_rollback_hook(); + } + + fn commit_hook(&self, hook: F) + where F: FnMut() -> bool + { + unsafe extern "C" fn call_boxed_closure(p_arg: *mut c_void) -> c_int + where F: FnMut() -> bool + { + let boxed_hook: *mut F = mem::transmute(p_arg); + assert!(!boxed_hook.is_null(), "Internal error - null function pointer"); + + if (*boxed_hook)() { 1 } else { 0 } + } + + let previous_hook = { + let boxed_hook: *mut F = Box::into_raw(Box::new(hook)); + unsafe { + ffi::sqlite3_commit_hook(self.db(), + Some(call_boxed_closure::), + boxed_hook as *mut _) + } + }; + free_boxed_hook(previous_hook); + } + + fn rollback_hook(&self, hook: F) + where F: FnMut() + { + unsafe extern "C" fn call_boxed_closure(p_arg: *mut c_void) + where F: FnMut() + { + let boxed_hook: *mut F = mem::transmute(p_arg); + assert!(!boxed_hook.is_null(), "Internal error - null function pointer"); + + (*boxed_hook)(); + } + + let previous_hook = { + let boxed_hook: *mut F = Box::into_raw(Box::new(hook)); + unsafe { + ffi::sqlite3_rollback_hook(self.db(), + Some(call_boxed_closure::), + boxed_hook as *mut _) + } + }; + free_boxed_hook(previous_hook); } fn update_hook(&mut self, hook: F) @@ -154,17 +230,26 @@ impl InnerConnection { boxed_hook as *mut _) } }; - free_boxed_update_hook(previous_hook); + free_boxed_hook(previous_hook); } fn remove_update_hook(&mut self) { let previous_hook = unsafe { ffi::sqlite3_update_hook(self.db(), None, ptr::null_mut()) }; - free_boxed_update_hook(previous_hook); + free_boxed_hook(previous_hook); } + fn remove_commit_hook(&mut self) { + let previous_hook = unsafe { ffi::sqlite3_commit_hook(self.db(), None, ptr::null_mut()) }; + free_boxed_hook(previous_hook); + } + + fn remove_rollback_hook(&mut self) { + let previous_hook = unsafe { ffi::sqlite3_rollback_hook(self.db(), None, ptr::null_mut()) }; + free_boxed_hook(previous_hook); + } } -fn free_boxed_update_hook(hook: *mut c_void) { +fn free_boxed_hook(hook: *mut c_void) { if !hook.is_null() { // TODO make sure that size_of::<*mut F>() is always equal to size_of::<*mut c_void>() let _: Box<*mut c_void> = unsafe { Box::from_raw(hook as *mut _) }; @@ -176,6 +261,31 @@ mod test { use super::Action; use Connection; + #[test] + fn test_commit_hook() { + let db = Connection::open_in_memory().unwrap(); + + let mut called = false; + db.commit_hook(|| { + called = true; + false + }); + db.execute_batch("BEGIN; CREATE TABLE foo (t TEXT); COMMIT;").unwrap(); + assert!(called); + } + + #[test] + fn test_rollback_hook() { + let db = Connection::open_in_memory().unwrap(); + + let mut called = false; + db.rollback_hook(|| { + called = true; + }); + db.execute_batch("BEGIN; CREATE TABLE foo (t TEXT); ROLLBACK;").unwrap(); + assert!(called); + } + #[test] fn test_update_hook() { let db = Connection::open_in_memory().unwrap(); diff --git a/src/lib.rs b/src/lib.rs index 949271a..1b568a8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -122,7 +122,9 @@ pub mod blob; #[cfg(feature = "limits")] pub mod limits; #[cfg(feature = "hooks")] -pub mod hooks; +mod hooks; +#[cfg(feature = "hooks")] +pub use hooks::*; // Number of cached prepared statements we'll hold on to. const STATEMENT_CACHE_DEFAULT_CAPACITY: usize = 16; From 94670c0119baca5fc55c40f5a9820910787d9dba Mon Sep 17 00:00:00 2001 From: gwenn Date: Fri, 12 May 2017 19:18:42 +0200 Subject: [PATCH 7/7] Rustfmt --- src/hooks.rs | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/src/hooks.rs b/src/hooks.rs index 3c6bb0b..4bf0a59 100644 --- a/src/hooks.rs +++ b/src/hooks.rs @@ -110,7 +110,8 @@ impl Connection { self.db.borrow_mut().rollback_hook(hook); } - /// Register a callback function to be invoked whenever a row is updated, inserted or deleted in a rowid table. + /// Register a callback function to be invoked whenever a row is updated, + /// inserted or deleted in a rowid table. /// /// The callback parameters are: /// @@ -154,7 +155,8 @@ impl InnerConnection { where F: FnMut() -> bool { let boxed_hook: *mut F = mem::transmute(p_arg); - assert!(!boxed_hook.is_null(), "Internal error - null function pointer"); + assert!(!boxed_hook.is_null(), + "Internal error - null function pointer"); if (*boxed_hook)() { 1 } else { 0 } } @@ -177,7 +179,8 @@ impl InnerConnection { where F: FnMut() { let boxed_hook: *mut F = mem::transmute(p_arg); - assert!(!boxed_hook.is_null(), "Internal error - null function pointer"); + assert!(!boxed_hook.is_null(), + "Internal error - null function pointer"); (*boxed_hook)(); } @@ -186,8 +189,8 @@ impl InnerConnection { let boxed_hook: *mut F = Box::into_raw(Box::new(hook)); unsafe { ffi::sqlite3_rollback_hook(self.db(), - Some(call_boxed_closure::), - boxed_hook as *mut _) + Some(call_boxed_closure::), + boxed_hook as *mut _) } }; free_boxed_hook(previous_hook); @@ -207,7 +210,8 @@ impl InnerConnection { use std::str; let boxed_hook: *mut F = mem::transmute(p_arg); - assert!(!boxed_hook.is_null(), "Internal error - null function pointer"); + assert!(!boxed_hook.is_null(), + "Internal error - null function pointer"); let action = Action::from(action_code); let db_name = { @@ -270,7 +274,8 @@ mod test { called = true; false }); - db.execute_batch("BEGIN; CREATE TABLE foo (t TEXT); COMMIT;").unwrap(); + db.execute_batch("BEGIN; CREATE TABLE foo (t TEXT); COMMIT;") + .unwrap(); assert!(called); } @@ -279,10 +284,9 @@ mod test { let db = Connection::open_in_memory().unwrap(); let mut called = false; - db.rollback_hook(|| { - called = true; - }); - db.execute_batch("BEGIN; CREATE TABLE foo (t TEXT); ROLLBACK;").unwrap(); + db.rollback_hook(|| { called = true; }); + db.execute_batch("BEGIN; CREATE TABLE foo (t TEXT); ROLLBACK;") + .unwrap(); assert!(called); } @@ -299,8 +303,7 @@ mod test { called = true; }); db.execute_batch("CREATE TABLE foo (t TEXT)").unwrap(); - db.execute_batch("INSERT INTO foo VALUES ('lisa')") - .unwrap(); + db.execute_batch("INSERT INTO foo VALUES ('lisa')").unwrap(); assert!(called); } }