Debian Codegraph @

third_party/rust/rusqlite/examples/loadable_extension.rs

raw
1 //! Adaptation of https://sqlite.org/loadext.html#programming_loadable_extensions
2 //!
3 //! # build
4 //! ```sh
5 //! cargo build --example loadable_extension --features "loadable_extension functions trace"
6 //! ```
7 //!
8 //! # test
9 //! ```sh
10 //! sqlite> .log on
11 //! sqlite> .load target/debug/examples/libloadable_extension.so
12 //! (28) Rusqlite extension initialized
13 //! sqlite> SELECT rusqlite_test_function();
14 //! Rusqlite extension loaded correctly!
15 //! ```
16 use std::os::raw::{c_char, c_int};
17
18 use rusqlite::ffi;
19 use rusqlite::functions::FunctionFlags;
20 use rusqlite::types::{ToSqlOutput, Value};
21 use rusqlite::{Connection, Result};
22
23 /// Entry point for SQLite to load the extension.
24 /// See <https://sqlite.org/c3ref/load_extension.html> on this function's name and usage.
25 /// # Safety
26 /// This function is called by SQLite and must be safe to call.
27 #[expect(clippy::not_unsafe_ptr_arg_deref)]
28 #[no_mangle]
29 pub unsafe extern "C" fn sqlite3_extension_init(
30 db: *mut ffi::sqlite3,
31 pz_err_msg: *mut *mut c_char,
32 p_api: *mut ffi::sqlite3_api_routines,
33 ) -> c_int {
34 Connection::extension_init2(db, pz_err_msg, p_api, extension_init)
35 }
36
37 fn extension_init(db: Connection) -> Result<bool> {
38 db.create_scalar_function(
39 "rusqlite_test_function",
40 0,
41 FunctionFlags::SQLITE_DETERMINISTIC,
42 |_ctx| {
43 Ok(ToSqlOutput::Owned(Value::Text(
44 "Rusqlite extension loaded correctly!".to_string(),
45 )))
46 },
47 )?;
48 rusqlite::trace::log(ffi::SQLITE_WARNING, "Rusqlite extension initialized");
49 Ok(false)
50 }