story-kit: merge 260_refactor_upgrade_libsqlite3_sys

This commit is contained in:
Dave
2026-03-17 13:39:08 +00:00
parent b0e4e04c9d
commit ea062400e5
73 changed files with 23405 additions and 10 deletions

View File

@@ -0,0 +1,23 @@
//! Ensure `loadable_extension.rs` works.
use rusqlite::{Connection, Result};
use std::env::consts::{DLL_PREFIX, DLL_SUFFIX};
fn main() -> Result<()> {
let db = Connection::open_in_memory()?;
unsafe {
db.load_extension_enable()?;
db.load_extension(
format!("target/debug/examples/{DLL_PREFIX}loadable_extension{DLL_SUFFIX}"),
None::<&str>,
)?;
db.load_extension_disable()?;
}
let str = db.query_row("SELECT rusqlite_test_function()", [], |row| {
row.get::<_, String>(0)
})?;
assert_eq!(&str, "Rusqlite extension loaded correctly!");
Ok(())
}

View File

@@ -0,0 +1,49 @@
//! Adaptation of https://sqlite.org/loadext.html#programming_loadable_extensions
//!
//! # build
//! ```sh
//! cargo build --example loadable_extension --features "loadable_extension functions trace"
//! ```
//!
//! # test
//! ```sh
//! sqlite> .log on
//! sqlite> .load target/debug/examples/libloadable_extension.so
//! (28) Rusqlite extension initialized
//! sqlite> SELECT rusqlite_test_function();
//! Rusqlite extension loaded correctly!
//! ```
use std::os::raw::{c_char, c_int};
use rusqlite::ffi;
use rusqlite::functions::FunctionFlags;
use rusqlite::types::{ToSqlOutput, Value};
use rusqlite::{Connection, Result};
/// Entry point for SQLite to load the extension.
/// See <https://sqlite.org/c3ref/load_extension.html> on this function's name and usage.
/// # Safety
/// This function is called by SQLite and must be safe to call.
#[no_mangle]
pub unsafe extern "C" fn sqlite3_extension_init(
db: *mut ffi::sqlite3,
pz_err_msg: *mut *mut c_char,
p_api: *mut ffi::sqlite3_api_routines,
) -> c_int {
Connection::extension_init2(db, pz_err_msg, p_api, extension_init)
}
fn extension_init(db: Connection) -> Result<bool> {
db.create_scalar_function(
c"rusqlite_test_function",
0,
FunctionFlags::SQLITE_DETERMINISTIC,
|_ctx| {
Ok(ToSqlOutput::Owned(Value::Text(
"Rusqlite extension loaded correctly!".to_string(),
)))
},
)?;
rusqlite::trace::log(ffi::SQLITE_WARNING, "Rusqlite extension initialized");
Ok(false)
}

27
vendor/rusqlite/examples/owning_rows.rs vendored Normal file
View File

@@ -0,0 +1,27 @@
extern crate rusqlite;
use rusqlite::{CachedStatement, Connection, Result, Rows};
use self_cell::{self_cell, MutBorrow};
type RowsRef<'a> = Rows<'a>;
self_cell!(
struct OwningRows<'conn> {
owner: MutBorrow<CachedStatement<'conn>>,
#[covariant]
dependent: RowsRef,
}
);
fn main() -> Result<()> {
let conn = Connection::open_in_memory()?;
let stmt = conn.prepare_cached("SELECT 1")?;
let mut or = OwningRows::try_new(MutBorrow::new(stmt), |s| s.borrow_mut().query([]))?;
or.with_dependent_mut(|_stmt, rows| -> Result<()> {
while let Some(row) = rows.next()? {
assert_eq!(Ok(1), row.get(0));
}
Ok(())
})?;
Ok(())
}

View File

@@ -0,0 +1,30 @@
extern crate rusqlite;
use rusqlite::{CachedStatement, Connection, Result, Rows};
use self_cell::{self_cell, MutBorrow};
type CachedStatementRef<'a> = CachedStatement<'a>;
// Caveat: single statement at a time for one connection.
// But if you need multiple statements, you can still create your own struct
// with multiple fields (one for each statement).
self_cell!(
struct OwningStatement {
owner: MutBorrow<Connection>,
#[covariant]
dependent: CachedStatementRef,
}
);
fn main() -> Result<()> {
let conn = Connection::open_in_memory()?;
let mut os = OwningStatement::try_new(MutBorrow::new(conn), |s| {
s.borrow_mut().prepare_cached("SELECT 1")
})?;
let mut rows = os.with_dependent_mut(|_conn, stmt| -> Result<Rows<'_>> { stmt.query([]) })?;
while let Some(row) = rows.next()? {
assert_eq!(Ok(1), row.get(0));
}
Ok(())
}

View File

@@ -0,0 +1,48 @@
# Persons example
## Run
```
$ cargo run --example persons
```
## Run (wasm32-wasi)
### Requisites
- [wasi-sdk](https://github.com/WebAssembly/wasi-sdk)
- [wasmtime](https://wasmtime.dev/)
```
# Set to wasi-sdk directory
$ export WASI_SDK_PATH=`<wasi-sdk-path>`
$ export CC_wasm32_wasi="${WASI_SDK_PATH}/bin/clang --sysroot=${WASI_SDK_PATH}/share/wasi-sysroot"
# Build
$ cargo build --example persons --target wasm32-wasi --release --features bundled
# Run
$ wasmtime target/wasm32-wasi/release/examples/persons.wasm
Found persons:
ID: 1, Name: Steven
ID: 2, Name: John
ID: 3, Name: Alex
```
## Run (wasm32-unknown-unknown)
### Requisites
- [emscripten](https://emscripten.org/docs/getting_started/downloads.html)
- [wasm-bindgen-cli](https://github.com/wasm-bindgen/wasm-bindgen)
```
# Build
$ cargo build --example persons --target wasm32-unknown-unknown --release
# Bindgen
$ wasm-bindgen target/wasm32-unknown-unknown/release/examples/persons.wasm --out-dir target/pkg --nodejs
# Run
$ node target/pkg/persons.js
Found persons:
ID: 1, Name: Steven
ID: 2, Name: John
ID: 3, Name: Alex
```

View File

@@ -0,0 +1,57 @@
use rusqlite::{Connection, Result};
#[cfg(all(target_family = "wasm", target_os = "unknown"))]
use wasm_bindgen::prelude::wasm_bindgen;
#[cfg(all(target_family = "wasm", target_os = "unknown"))]
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = console)]
fn log(s: &str);
}
#[cfg(all(target_family = "wasm", target_os = "unknown"))]
macro_rules! println {
($($t:tt)*) => (log(&format_args!($($t)*).to_string()))
}
struct Person {
id: i32,
name: String,
}
#[cfg_attr(all(target_family = "wasm", target_os = "unknown"), wasm_bindgen(main))]
fn main() -> Result<()> {
let conn = Connection::open_in_memory()?;
conn.execute(
"CREATE TABLE IF NOT EXISTS persons (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
)",
(), // empty list of parameters.
)?;
conn.execute(
"INSERT INTO persons (name) VALUES (?1), (?2), (?3)",
["Steven", "John", "Alex"].map(|n| n.to_string()),
)?;
let mut stmt = conn.prepare("SELECT id, name FROM persons")?;
let rows = stmt.query_map([], |row| {
Ok(Person {
id: row.get(0)?,
name: row.get(1)?,
})
})?;
println!("Found persons:");
for person in rows {
match person {
Ok(p) => println!("ID: {}, Name: {}", p.id, p.name),
Err(e) => eprintln!("Error: {e:?}"),
}
}
Ok(())
}