Skip to main content

rusqlite/
load_extension_guard.rs

1use crate::{Connection, Result};
2
3/// RAII guard temporarily enabling SQLite extensions to be loaded.
4///
5/// ## Example
6///
7/// ```rust,no_run
8/// # use rusqlite::{Connection, DEFAULT_NAME, Result, LoadExtensionGuard};
9/// # use std::path::{Path};
10/// fn load_my_extension(conn: &Connection) -> Result<()> {
11///     unsafe {
12///         let _guard = LoadExtensionGuard::new(conn)?;
13///         conn.load_extension("trusted/sqlite/extension", DEFAULT_NAME)
14///     }
15/// }
16/// ```
17pub struct LoadExtensionGuard<'conn> {
18    conn: &'conn Connection,
19}
20
21impl LoadExtensionGuard<'_> {
22    /// Attempt to enable loading extensions. Loading extensions will be
23    /// disabled when this guard goes out of scope. Cannot be meaningfully
24    /// nested.
25    ///
26    /// # Safety
27    ///
28    /// You must not run untrusted queries while extension loading is enabled.
29    ///
30    /// See the safety comment on [`Connection::load_extension_enable`] for more
31    /// details.
32    #[inline]
33    pub unsafe fn new(conn: &Connection) -> Result<LoadExtensionGuard<'_>> {
34        unsafe {
35            conn.load_extension_enable()
36                .map(|()| LoadExtensionGuard { conn })
37        }
38    }
39}
40
41#[expect(unused_must_use)]
42impl Drop for LoadExtensionGuard<'_> {
43    #[inline]
44    fn drop(&mut self) {
45        self.conn.load_extension_disable();
46    }
47}