Skip to main content

rusqlite/hooks/
mod.rs

1//! Commit, Data Change and Rollback Notification Callbacks
2#![expect(non_camel_case_types)]
3
4use std::ffi::{CStr, c_char, c_int, c_void};
5use std::panic::catch_unwind;
6
7use crate::ffi;
8
9use crate::{Connection, InnerConnection, Result, error::decode_result_raw};
10
11#[cfg(feature = "preupdate_hook")]
12pub use preupdate_hook::*;
13
14#[cfg(feature = "preupdate_hook")]
15mod preupdate_hook;
16
17/// Action Codes
18#[derive(Clone, Copy, Debug, Eq, PartialEq)]
19#[repr(i32)]
20#[non_exhaustive]
21pub enum Action {
22    /// Unsupported / unexpected action
23    UNKNOWN = -1,
24    /// DELETE command
25    SQLITE_DELETE = ffi::SQLITE_DELETE,
26    /// INSERT command
27    SQLITE_INSERT = ffi::SQLITE_INSERT,
28    /// UPDATE command
29    SQLITE_UPDATE = ffi::SQLITE_UPDATE,
30}
31
32impl From<i32> for Action {
33    #[inline]
34    fn from(code: i32) -> Self {
35        match code {
36            ffi::SQLITE_DELETE => Self::SQLITE_DELETE,
37            ffi::SQLITE_INSERT => Self::SQLITE_INSERT,
38            ffi::SQLITE_UPDATE => Self::SQLITE_UPDATE,
39            _ => Self::UNKNOWN,
40        }
41    }
42}
43
44/// The context received by an authorizer hook.
45///
46/// See <https://sqlite.org/c3ref/set_authorizer.html> for more info.
47#[derive(Clone, Copy, Debug, Eq, PartialEq)]
48pub struct AuthContext<'c> {
49    /// The action to be authorized.
50    pub action: AuthAction<'c>,
51
52    /// The database name, if applicable.
53    pub database_name: Option<&'c str>,
54
55    /// The inner-most trigger or view responsible for the access attempt.
56    /// `None` if the access attempt was made by top-level SQL code.
57    pub accessor: Option<&'c str>,
58}
59
60/// Actions and arguments found within a statement during
61/// preparation.
62///
63/// See <https://sqlite.org/c3ref/c_alter_table.html> for more info.
64#[derive(Clone, Copy, Debug, Eq, PartialEq)]
65#[non_exhaustive]
66#[allow(missing_docs)]
67pub enum AuthAction<'c> {
68    /// This variant is not normally produced by SQLite. You may encounter it
69    // if you're using a different version than what's supported by this library.
70    Unknown {
71        /// The unknown authorization action code.
72        code: i32,
73        /// The third arg to the authorizer callback.
74        arg1: Option<&'c str>,
75        /// The fourth arg to the authorizer callback.
76        arg2: Option<&'c str>,
77    },
78    CreateIndex {
79        index_name: &'c str,
80        table_name: &'c str,
81    },
82    CreateTable {
83        table_name: &'c str,
84    },
85    CreateTempIndex {
86        index_name: &'c str,
87        table_name: &'c str,
88    },
89    CreateTempTable {
90        table_name: &'c str,
91    },
92    CreateTempTrigger {
93        trigger_name: &'c str,
94        table_name: &'c str,
95    },
96    CreateTempView {
97        view_name: &'c str,
98    },
99    CreateTrigger {
100        trigger_name: &'c str,
101        table_name: &'c str,
102    },
103    CreateView {
104        view_name: &'c str,
105    },
106    Delete {
107        table_name: &'c str,
108    },
109    DropIndex {
110        index_name: &'c str,
111        table_name: &'c str,
112    },
113    DropTable {
114        table_name: &'c str,
115    },
116    DropTempIndex {
117        index_name: &'c str,
118        table_name: &'c str,
119    },
120    DropTempTable {
121        table_name: &'c str,
122    },
123    DropTempTrigger {
124        trigger_name: &'c str,
125        table_name: &'c str,
126    },
127    DropTempView {
128        view_name: &'c str,
129    },
130    DropTrigger {
131        trigger_name: &'c str,
132        table_name: &'c str,
133    },
134    DropView {
135        view_name: &'c str,
136    },
137    Insert {
138        table_name: &'c str,
139    },
140    Pragma {
141        pragma_name: &'c str,
142        /// The pragma value, if present (e.g., `PRAGMA name = value;`).
143        pragma_value: Option<&'c str>,
144    },
145    Read {
146        table_name: &'c str,
147        column_name: &'c str,
148    },
149    Select,
150    Transaction {
151        operation: TransactionOperation,
152    },
153    Update {
154        table_name: &'c str,
155        column_name: &'c str,
156    },
157    Attach {
158        filename: &'c str,
159    },
160    Detach {
161        database_name: &'c str,
162    },
163    AlterTable {
164        database_name: &'c str,
165        table_name: &'c str,
166    },
167    Reindex {
168        index_name: &'c str,
169    },
170    Analyze {
171        table_name: &'c str,
172    },
173    CreateVtable {
174        table_name: &'c str,
175        module_name: &'c str,
176    },
177    DropVtable {
178        table_name: &'c str,
179        module_name: &'c str,
180    },
181    Function {
182        function_name: &'c str,
183    },
184    Savepoint {
185        operation: TransactionOperation,
186        savepoint_name: &'c str,
187    },
188    Recursive,
189}
190
191impl<'c> AuthAction<'c> {
192    fn from_raw(code: i32, arg1: Option<&'c str>, arg2: Option<&'c str>) -> Self {
193        match (code, arg1, arg2) {
194            (ffi::SQLITE_CREATE_INDEX, Some(index_name), Some(table_name)) => Self::CreateIndex {
195                index_name,
196                table_name,
197            },
198            (ffi::SQLITE_CREATE_TABLE, Some(table_name), _) => Self::CreateTable { table_name },
199            (ffi::SQLITE_CREATE_TEMP_INDEX, Some(index_name), Some(table_name)) => {
200                Self::CreateTempIndex {
201                    index_name,
202                    table_name,
203                }
204            }
205            (ffi::SQLITE_CREATE_TEMP_TABLE, Some(table_name), _) => {
206                Self::CreateTempTable { table_name }
207            }
208            (ffi::SQLITE_CREATE_TEMP_TRIGGER, Some(trigger_name), Some(table_name)) => {
209                Self::CreateTempTrigger {
210                    trigger_name,
211                    table_name,
212                }
213            }
214            (ffi::SQLITE_CREATE_TEMP_VIEW, Some(view_name), _) => {
215                Self::CreateTempView { view_name }
216            }
217            (ffi::SQLITE_CREATE_TRIGGER, Some(trigger_name), Some(table_name)) => {
218                Self::CreateTrigger {
219                    trigger_name,
220                    table_name,
221                }
222            }
223            (ffi::SQLITE_CREATE_VIEW, Some(view_name), _) => Self::CreateView { view_name },
224            (ffi::SQLITE_DELETE, Some(table_name), None) => Self::Delete { table_name },
225            (ffi::SQLITE_DROP_INDEX, Some(index_name), Some(table_name)) => Self::DropIndex {
226                index_name,
227                table_name,
228            },
229            (ffi::SQLITE_DROP_TABLE, Some(table_name), _) => Self::DropTable { table_name },
230            (ffi::SQLITE_DROP_TEMP_INDEX, Some(index_name), Some(table_name)) => {
231                Self::DropTempIndex {
232                    index_name,
233                    table_name,
234                }
235            }
236            (ffi::SQLITE_DROP_TEMP_TABLE, Some(table_name), _) => {
237                Self::DropTempTable { table_name }
238            }
239            (ffi::SQLITE_DROP_TEMP_TRIGGER, Some(trigger_name), Some(table_name)) => {
240                Self::DropTempTrigger {
241                    trigger_name,
242                    table_name,
243                }
244            }
245            (ffi::SQLITE_DROP_TEMP_VIEW, Some(view_name), _) => Self::DropTempView { view_name },
246            (ffi::SQLITE_DROP_TRIGGER, Some(trigger_name), Some(table_name)) => Self::DropTrigger {
247                trigger_name,
248                table_name,
249            },
250            (ffi::SQLITE_DROP_VIEW, Some(view_name), _) => Self::DropView { view_name },
251            (ffi::SQLITE_INSERT, Some(table_name), _) => Self::Insert { table_name },
252            (ffi::SQLITE_PRAGMA, Some(pragma_name), pragma_value) => Self::Pragma {
253                pragma_name,
254                pragma_value,
255            },
256            (ffi::SQLITE_READ, Some(table_name), Some(column_name)) => Self::Read {
257                table_name,
258                column_name,
259            },
260            (ffi::SQLITE_SELECT, ..) => Self::Select,
261            (ffi::SQLITE_TRANSACTION, Some(operation_str), _) => Self::Transaction {
262                operation: TransactionOperation::from_str(operation_str),
263            },
264            (ffi::SQLITE_UPDATE, Some(table_name), Some(column_name)) => Self::Update {
265                table_name,
266                column_name,
267            },
268            (ffi::SQLITE_ATTACH, Some(filename), _) => Self::Attach { filename },
269            (ffi::SQLITE_DETACH, Some(database_name), _) => Self::Detach { database_name },
270            (ffi::SQLITE_ALTER_TABLE, Some(database_name), Some(table_name)) => Self::AlterTable {
271                database_name,
272                table_name,
273            },
274            (ffi::SQLITE_REINDEX, Some(index_name), _) => Self::Reindex { index_name },
275            (ffi::SQLITE_ANALYZE, Some(table_name), _) => Self::Analyze { table_name },
276            (ffi::SQLITE_CREATE_VTABLE, Some(table_name), Some(module_name)) => {
277                Self::CreateVtable {
278                    table_name,
279                    module_name,
280                }
281            }
282            (ffi::SQLITE_DROP_VTABLE, Some(table_name), Some(module_name)) => Self::DropVtable {
283                table_name,
284                module_name,
285            },
286            (ffi::SQLITE_FUNCTION, _, Some(function_name)) => Self::Function { function_name },
287            (ffi::SQLITE_SAVEPOINT, Some(operation_str), Some(savepoint_name)) => Self::Savepoint {
288                operation: TransactionOperation::from_str(operation_str),
289                savepoint_name,
290            },
291            (ffi::SQLITE_RECURSIVE, ..) => Self::Recursive,
292            (code, arg1, arg2) => Self::Unknown { code, arg1, arg2 },
293        }
294    }
295}
296
297/// A transaction operation.
298#[derive(Clone, Copy, Debug, Eq, PartialEq)]
299#[non_exhaustive]
300#[allow(missing_docs)]
301pub enum TransactionOperation {
302    Unknown,
303    Begin,
304    Release,
305    Rollback,
306}
307
308impl TransactionOperation {
309    fn from_str(op_str: &str) -> Self {
310        match op_str {
311            "BEGIN" => Self::Begin,
312            "RELEASE" => Self::Release,
313            "ROLLBACK" => Self::Rollback,
314            _ => Self::Unknown,
315        }
316    }
317}
318
319/// [`authorizer`](Connection::authorizer) return code
320#[derive(Clone, Copy, Debug, Eq, PartialEq)]
321#[non_exhaustive]
322pub enum Authorization {
323    /// Authorize the action.
324    Allow,
325    /// Don't allow access, but don't trigger an error either.
326    Ignore,
327    /// Trigger an error.
328    Deny,
329}
330
331impl Authorization {
332    fn into_raw(self) -> c_int {
333        match self {
334            Self::Allow => ffi::SQLITE_OK,
335            Self::Ignore => ffi::SQLITE_IGNORE,
336            Self::Deny => ffi::SQLITE_DENY,
337        }
338    }
339}
340
341impl Connection {
342    /// Register a callback function to be invoked whenever
343    /// a transaction is committed.
344    ///
345    /// The callback returns `true` to rollback.
346    #[inline]
347    pub fn commit_hook<F>(&mut self, hook: Option<F>) -> Result<()>
348    where
349        F: FnMut() -> bool + Send + 'static,
350    {
351        self.db.borrow_mut().commit_hook(hook)
352    }
353
354    /// Register a callback function to be invoked whenever
355    /// a transaction is rolled back.
356    #[inline]
357    pub fn rollback_hook<F>(&mut self, hook: Option<F>) -> Result<()>
358    where
359        F: FnMut() + Send + 'static,
360    {
361        self.db.borrow_mut().rollback_hook(hook)
362    }
363
364    /// Register a callback function to be invoked whenever
365    /// a row is updated, inserted or deleted in a rowid table.
366    ///
367    /// The callback parameters are:
368    ///
369    /// - the type of database update (`SQLITE_INSERT`, `SQLITE_UPDATE` or
370    ///   `SQLITE_DELETE`),
371    /// - the name of the database ("main", "temp", ...),
372    /// - the name of the table that is updated,
373    /// - the ROWID of the row that is updated.
374    #[inline]
375    pub fn update_hook<F>(&mut self, hook: Option<F>) -> Result<()>
376    where
377        F: FnMut(Action, &str, &str, i64) + Send + 'static,
378    {
379        self.db.borrow_mut().update_hook(hook)
380    }
381
382    /// Register a callback that is invoked each time data is committed to a database in wal mode.
383    ///
384    /// A single database handle may have at most a single write-ahead log callback registered at one time.
385    /// Calling `wal_hook` replaces any previously registered write-ahead log callback.
386    /// Note that the `sqlite3_wal_autocheckpoint()` interface and the `wal_autocheckpoint` pragma
387    /// both invoke `sqlite3_wal_hook()` and will overwrite any prior `sqlite3_wal_hook()` settings.
388    pub fn wal_hook<F>(&mut self, hook: Option<F>) -> Result<()>
389    where
390        F: FnMut(&Wal, c_int) -> Result<()> + Send + 'static,
391    {
392        unsafe extern "C" fn wal_hook_callback<F>(
393            client_data: *mut c_void,
394            db: *mut ffi::sqlite3,
395            db_name: *const c_char,
396            pages: c_int,
397        ) -> c_int
398        where
399            F: FnMut(&Wal, c_int) -> Result<()>,
400        {
401            unsafe {
402                let wal = Wal { db, db_name };
403                catch_unwind(|| {
404                    let hook_fn: *mut F = client_data.cast::<F>();
405                    match (*hook_fn)(&wal, pages) {
406                        Ok(()) => ffi::SQLITE_OK,
407                        Err(e) => e
408                            .sqlite_error()
409                            .map_or(ffi::SQLITE_ERROR, |x| x.extended_code),
410                    }
411                })
412                .unwrap_or_default()
413            }
414        }
415        let x = hook.as_ref().map(|_| wal_hook_callback::<F> as _);
416        let mut c = self.db.borrow_mut();
417        c.set_clientdata(c"sqlite3_wal_hook", hook, |db, bh| unsafe {
418            ffi::sqlite3_wal_hook(db, x, bh);
419            ffi::SQLITE_OK
420        })?;
421        Ok(())
422    }
423
424    /// Register a query progress callback.
425    ///
426    /// The parameter `num_ops` is the approximate number of virtual machine
427    /// instructions that are evaluated between successive invocations of the
428    /// `handler`. If `num_ops` is less than one then the progress handler
429    /// is disabled.
430    ///
431    /// If the progress callback returns `true`, the operation is interrupted.
432    pub fn progress_handler<F>(&mut self, num_ops: c_int, handler: Option<F>) -> Result<()>
433    where
434        F: FnMut() -> bool + Send + 'static,
435    {
436        self.db.borrow_mut().progress_handler(num_ops, handler)
437    }
438
439    /// Register an authorizer callback that's invoked
440    /// as a statement is being prepared.
441    #[inline]
442    pub fn authorizer<F>(&mut self, hook: Option<F>) -> Result<()>
443    where
444        F: for<'r> FnMut(AuthContext<'r>) -> Authorization + Send + 'static,
445    {
446        self.db.borrow_mut().authorizer(hook)
447    }
448}
449
450/// Checkpoint mode
451#[derive(Clone, Copy)]
452#[repr(i32)]
453#[non_exhaustive]
454pub enum CheckpointMode {
455    /// Do as much as possible w/o blocking
456    PASSIVE = ffi::SQLITE_CHECKPOINT_PASSIVE,
457    /// Wait for writers, then checkpoint
458    FULL = ffi::SQLITE_CHECKPOINT_FULL,
459    /// Like FULL but wait for readers
460    RESTART = ffi::SQLITE_CHECKPOINT_RESTART,
461    /// Like RESTART but also truncate WAL
462    TRUNCATE = ffi::SQLITE_CHECKPOINT_TRUNCATE,
463    /// Do no work at all
464    #[cfg(feature = "modern_sqlite")] // 3.51.0
465    NOOP = -1, //ffi::SQLITE_CHECKPOINT_NOOP,
466}
467
468/// Write-Ahead Log
469pub struct Wal {
470    db: *mut ffi::sqlite3,
471    db_name: *const c_char,
472}
473
474impl Wal {
475    /// Checkpoint a database
476    pub fn checkpoint(&self) -> Result<()> {
477        unsafe { decode_result_raw(self.db, ffi::sqlite3_wal_checkpoint(self.db, self.db_name)) }
478    }
479
480    /// Checkpoint a database
481    pub fn checkpoint_v2(&self, mode: CheckpointMode) -> Result<(c_int, c_int)> {
482        let mut n_log = 0;
483        let mut n_ckpt = 0;
484        unsafe {
485            decode_result_raw(
486                self.db,
487                ffi::sqlite3_wal_checkpoint_v2(
488                    self.db,
489                    self.db_name,
490                    mode as c_int,
491                    &raw mut n_log,
492                    &raw mut n_ckpt,
493                ),
494            )?;
495        };
496        Ok((n_log, n_ckpt))
497    }
498
499    /// Name of the database that was written to
500    #[must_use]
501    pub fn name(&self) -> &CStr {
502        unsafe { CStr::from_ptr(self.db_name) }
503    }
504}
505
506impl InnerConnection {
507    /// ```compile_fail
508    /// use rusqlite::{Connection, Result};
509    /// fn main() -> Result<()> {
510    ///     let mut db = Connection::open_in_memory()?;
511    ///     {
512    ///         let mut called = std::sync::atomic::AtomicBool::new(false);
513    ///         db.commit_hook(Some(|| {
514    ///             called.store(true, std::sync::atomic::Ordering::Relaxed);
515    ///             true
516    ///         }));
517    ///     }
518    ///     assert!(db
519    ///         .execute_batch(
520    ///             "BEGIN;
521    ///         CREATE TABLE foo (t TEXT);
522    ///         COMMIT;",
523    ///         )
524    ///         .is_err());
525    ///     Ok(())
526    /// }
527    /// ```
528    fn commit_hook<F>(&mut self, hook: Option<F>) -> Result<()>
529    where
530        F: FnMut() -> bool + Send + 'static,
531    {
532        unsafe extern "C" fn call_boxed_closure<F>(p_arg: *mut c_void) -> c_int
533        where
534            F: FnMut() -> bool,
535        {
536            unsafe {
537                let r = catch_unwind(|| {
538                    let boxed_hook: *mut F = p_arg.cast::<F>();
539                    (*boxed_hook)()
540                });
541                c_int::from(r.unwrap_or_default())
542            }
543        }
544        let x = hook.as_ref().map(|_| call_boxed_closure::<F> as _);
545        self.set_clientdata(c"sqlite3_commit_hook", hook, |db, bh| unsafe {
546            ffi::sqlite3_commit_hook(db, x, bh);
547            ffi::SQLITE_OK
548        })?;
549        Ok(())
550    }
551
552    /// ```compile_fail
553    /// use rusqlite::{Connection, Result};
554    /// fn main() -> Result<()> {
555    ///     let mut db = Connection::open_in_memory()?;
556    ///     {
557    ///         let mut called = std::sync::atomic::AtomicBool::new(false);
558    ///         db.rollback_hook(Some(|| {
559    ///             called.store(true, std::sync::atomic::Ordering::Relaxed);
560    ///         }));
561    ///     }
562    ///     assert!(db
563    ///         .execute_batch(
564    ///             "BEGIN;
565    ///         CREATE TABLE foo (t TEXT);
566    ///         ROLLBACK;",
567    ///         )
568    ///         .is_err());
569    ///     Ok(())
570    /// }
571    /// ```
572    fn rollback_hook<F>(&mut self, hook: Option<F>) -> Result<()>
573    where
574        F: FnMut() + Send + 'static,
575    {
576        unsafe extern "C" fn call_boxed_closure<F>(p_arg: *mut c_void)
577        where
578            F: FnMut(),
579        {
580            unsafe {
581                drop(catch_unwind(|| {
582                    let boxed_hook: *mut F = p_arg.cast::<F>();
583                    (*boxed_hook)();
584                }));
585            }
586        }
587
588        let x = hook.as_ref().map(|_| call_boxed_closure::<F> as _);
589        self.set_clientdata(c"sqlite3_rollback_hook", hook, |db, bh| unsafe {
590            ffi::sqlite3_rollback_hook(db, x, bh);
591            ffi::SQLITE_OK
592        })?;
593        Ok(())
594    }
595
596    /// ```compile_fail
597    /// use rusqlite::{Connection, Result};
598    /// fn main() -> Result<()> {
599    ///     let mut db = Connection::open_in_memory()?;
600    ///     {
601    ///         let mut called = std::sync::atomic::AtomicBool::new(false);
602    ///         db.update_hook(Some(|_, _: &str, _: &str, _| {
603    ///             called.store(true, std::sync::atomic::Ordering::Relaxed);
604    ///         }));
605    ///     }
606    ///     db.execute_batch("CREATE TABLE foo AS SELECT 1 AS bar;")
607    /// }
608    /// ```
609    fn update_hook<F>(&mut self, hook: Option<F>) -> Result<()>
610    where
611        F: FnMut(Action, &str, &str, i64) + Send + 'static,
612    {
613        unsafe extern "C" fn call_boxed_closure<F>(
614            p_arg: *mut c_void,
615            action_code: c_int,
616            p_db_name: *const c_char,
617            p_table_name: *const c_char,
618            row_id: i64,
619        ) where
620            F: FnMut(Action, &str, &str, i64),
621        {
622            let action = Action::from(action_code);
623            unsafe {
624                drop(catch_unwind(|| {
625                    let boxed_hook: *mut F = p_arg.cast::<F>();
626                    (*boxed_hook)(
627                        action,
628                        expect_utf8(p_db_name, "database name"),
629                        expect_utf8(p_table_name, "table name"),
630                        row_id,
631                    );
632                }));
633            }
634        }
635
636        let x = hook.as_ref().map(|_| call_boxed_closure::<F> as _);
637        self.set_clientdata(c"sqlite3_update_hook", hook, |db, bh| unsafe {
638            ffi::sqlite3_update_hook(db, x, bh);
639            ffi::SQLITE_OK
640        })?;
641        Ok(())
642    }
643
644    /// ```compile_fail
645    /// use rusqlite::{Connection, Result};
646    /// fn main() -> Result<()> {
647    ///     let mut db = Connection::open_in_memory()?;
648    ///     {
649    ///         let mut called = std::sync::atomic::AtomicBool::new(false);
650    ///         db.progress_handler(
651    ///             1,
652    ///             Some(|| {
653    ///                 called.store(true, std::sync::atomic::Ordering::Relaxed);
654    ///                 true
655    ///             }),
656    ///         );
657    ///     }
658    ///     assert!(db
659    ///         .execute_batch("BEGIN; CREATE TABLE foo (t TEXT); COMMIT;")
660    ///         .is_err());
661    ///     Ok(())
662    /// }
663    /// ```
664    fn progress_handler<F>(&mut self, num_ops: c_int, handler: Option<F>) -> Result<()>
665    where
666        F: FnMut() -> bool + Send + 'static,
667    {
668        unsafe extern "C" fn call_boxed_closure<F>(p_arg: *mut c_void) -> c_int
669        where
670            F: FnMut() -> bool,
671        {
672            unsafe {
673                let r = catch_unwind(|| {
674                    let boxed_handler: *mut F = p_arg.cast::<F>();
675                    (*boxed_handler)()
676                });
677                c_int::from(r.unwrap_or_default())
678            }
679        }
680
681        let x = handler.as_ref().map(|_| call_boxed_closure::<F> as _);
682        self.set_clientdata(c"sqlite3_progress_handler", handler, |db, bh| unsafe {
683            ffi::sqlite3_progress_handler(db, num_ops, x, bh);
684            ffi::SQLITE_OK
685        })?;
686        Ok(())
687    }
688
689    /// ```compile_fail
690    /// use rusqlite::{Connection, Result};
691    /// fn main() -> Result<()> {
692    ///     let mut db = Connection::open_in_memory()?;
693    ///     {
694    ///         let mut called = std::sync::atomic::AtomicBool::new(false);
695    ///         db.authorizer(Some(|_: rusqlite::hooks::AuthContext<'_>| {
696    ///             called.store(true, std::sync::atomic::Ordering::Relaxed);
697    ///             rusqlite::hooks::Authorization::Deny
698    ///         }));
699    ///     }
700    ///     assert!(db
701    ///         .execute_batch("BEGIN; CREATE TABLE foo (t TEXT); COMMIT;")
702    ///         .is_err());
703    ///     Ok(())
704    /// }
705    /// ```
706    fn authorizer<'c, F>(&'c mut self, authorizer: Option<F>) -> Result<()>
707    where
708        F: for<'r> FnMut(AuthContext<'r>) -> Authorization + Send + 'static,
709    {
710        unsafe extern "C" fn call_boxed_closure<'c, F>(
711            p_arg: *mut c_void,
712            action_code: c_int,
713            param1: *const c_char,
714            param2: *const c_char,
715            db_name: *const c_char,
716            trigger_or_view_name: *const c_char,
717        ) -> c_int
718        where
719            F: FnMut(AuthContext<'c>) -> Authorization + Send + 'static,
720        {
721            unsafe {
722                catch_unwind(|| {
723                    let action = AuthAction::from_raw(
724                        action_code,
725                        expect_optional_utf8(param1, "authorizer param 1"),
726                        expect_optional_utf8(param2, "authorizer param 2"),
727                    );
728                    let auth_ctx = AuthContext {
729                        action,
730                        database_name: expect_optional_utf8(db_name, "database name"),
731                        accessor: expect_optional_utf8(
732                            trigger_or_view_name,
733                            "accessor (inner-most trigger or view)",
734                        ),
735                    };
736                    let boxed_hook: *mut F = p_arg.cast::<F>();
737                    (*boxed_hook)(auth_ctx)
738                })
739                .map_or_else(|_| ffi::SQLITE_ERROR, Authorization::into_raw)
740            }
741        }
742
743        let x_auth = authorizer
744            .as_ref()
745            .map(|_| call_boxed_closure::<'c, F> as _);
746        self.set_clientdata(c"sqlite3_set_authorizer", authorizer, |db, bh| unsafe {
747            ffi::sqlite3_set_authorizer(db, x_auth, bh)
748        })?;
749        Ok(())
750    }
751}
752
753unsafe fn expect_utf8<'a>(p_str: *const c_char, description: &'static str) -> &'a str {
754    unsafe {
755        expect_optional_utf8(p_str, description)
756            .unwrap_or_else(|| panic!("received empty {description}"))
757    }
758}
759
760unsafe fn expect_optional_utf8<'a>(
761    p_str: *const c_char,
762    description: &'static str,
763) -> Option<&'a str> {
764    if p_str.is_null() {
765        return None;
766    }
767    unsafe {
768        CStr::from_ptr(p_str)
769            .to_str()
770            .unwrap_or_else(|_| panic!("received non-utf8 string as {description}"))
771            .into()
772    }
773}
774
775#[cfg(all(test, not(miri)))]
776mod test {
777    #[cfg(all(target_family = "wasm", target_os = "unknown"))]
778    use wasm_bindgen_test::wasm_bindgen_test as test;
779
780    use super::Action;
781    use crate::{Connection, Result};
782    use std::sync::atomic::{AtomicBool, Ordering};
783
784    #[test]
785    fn test_commit_hook() -> Result<()> {
786        let mut db = Connection::open_in_memory()?;
787
788        static CALLED: AtomicBool = AtomicBool::new(false);
789        db.commit_hook(Some(|| {
790            CALLED.store(true, Ordering::Relaxed);
791            false
792        }))?;
793        db.execute_batch("BEGIN; CREATE TABLE foo (t TEXT); COMMIT;")?;
794        assert!(CALLED.load(Ordering::Relaxed));
795        Ok(())
796    }
797
798    #[test]
799    fn test_fn_commit_hook() -> Result<()> {
800        let mut db = Connection::open_in_memory()?;
801
802        fn hook() -> bool {
803            true
804        }
805
806        db.commit_hook(Some(hook))?;
807        db.execute_batch("BEGIN; CREATE TABLE foo (t TEXT); COMMIT;")
808            .unwrap_err();
809        Ok(())
810    }
811
812    #[test]
813    fn test_rollback_hook() -> Result<()> {
814        let mut db = Connection::open_in_memory()?;
815
816        static CALLED: AtomicBool = AtomicBool::new(false);
817        db.rollback_hook(Some(|| {
818            CALLED.store(true, Ordering::Relaxed);
819        }))?;
820        db.execute_batch("BEGIN; CREATE TABLE foo (t TEXT); ROLLBACK;")?;
821        assert!(CALLED.load(Ordering::Relaxed));
822        Ok(())
823    }
824
825    #[test]
826    fn test_update_hook() -> Result<()> {
827        let mut db = Connection::open_in_memory()?;
828
829        static CALLED: AtomicBool = AtomicBool::new(false);
830        db.update_hook(Some(|action, db: &str, tbl: &str, row_id| {
831            assert_eq!(Action::SQLITE_INSERT, action);
832            assert_eq!("main", db);
833            assert_eq!("foo", tbl);
834            assert_eq!(1, row_id);
835            CALLED.store(true, Ordering::Relaxed);
836        }))?;
837        db.execute_batch("CREATE TABLE foo (t TEXT)")?;
838        db.execute_batch("INSERT INTO foo VALUES ('lisa')")?;
839        assert!(CALLED.load(Ordering::Relaxed));
840        Ok(())
841    }
842
843    #[test]
844    fn test_progress_handler() -> Result<()> {
845        let mut db = Connection::open_in_memory()?;
846
847        static CALLED: AtomicBool = AtomicBool::new(false);
848        db.progress_handler(
849            1,
850            Some(|| {
851                CALLED.store(true, Ordering::Relaxed);
852                false
853            }),
854        )?;
855        db.execute_batch("BEGIN; CREATE TABLE foo (t TEXT); COMMIT;")?;
856        assert!(CALLED.load(Ordering::Relaxed));
857        Ok(())
858    }
859
860    #[test]
861    fn test_progress_handler_interrupt() -> Result<()> {
862        let mut db = Connection::open_in_memory()?;
863
864        fn handler() -> bool {
865            true
866        }
867
868        db.progress_handler(1, Some(handler))?;
869        db.execute_batch("BEGIN; CREATE TABLE foo (t TEXT); COMMIT;")
870            .unwrap_err();
871        Ok(())
872    }
873
874    #[test]
875    fn test_authorizer() -> Result<()> {
876        use super::{AuthAction, AuthContext, Authorization};
877
878        let mut db = Connection::open_in_memory()?;
879        db.execute_batch("CREATE TABLE foo (public TEXT, private TEXT)")?;
880
881        let authorizer = move |ctx: AuthContext<'_>| match ctx.action {
882            AuthAction::Read {
883                column_name: "private",
884                ..
885            } => Authorization::Ignore,
886            AuthAction::DropTable { .. } => Authorization::Deny,
887            AuthAction::Pragma { .. } => panic!("shouldn't be called"),
888            _ => Authorization::Allow,
889        };
890
891        db.authorizer(Some(authorizer))?;
892        db.execute_batch(
893            "BEGIN TRANSACTION; INSERT INTO foo VALUES ('pub txt', 'priv txt'); COMMIT;",
894        )?;
895        db.query_row_and_then("SELECT * FROM foo", [], |row| -> Result<()> {
896            assert_eq!(row.get::<_, String>("public")?, "pub txt");
897            assert!(row.get::<_, Option<String>>("private")?.is_none());
898            Ok(())
899        })?;
900        db.execute_batch("DROP TABLE foo").unwrap_err();
901
902        db.authorizer(None::<fn(AuthContext<'_>) -> Authorization>)?;
903        db.execute_batch("PRAGMA user_version=1")?; // Disallowed by first authorizer, but it's now removed.
904
905        Ok(())
906    }
907
908    #[test]
909    fn test_non_owning_hooks_cleanup() -> Result<()> {
910        let mut conn = Connection::open_in_memory()?;
911
912        static CALLED: AtomicBool = AtomicBool::new(false);
913        CALLED.store(false, Ordering::Relaxed);
914        conn.commit_hook(Some(|| {
915            CALLED.store(true, Ordering::Relaxed);
916            false
917        }))?;
918
919        let non_owning_conn = unsafe { Connection::from_handle(conn.handle()) }?;
920        drop(non_owning_conn);
921
922        conn.execute_batch("CREATE TABLE test(value)")?;
923        assert!(CALLED.load(Ordering::Relaxed));
924        Ok(())
925    }
926}