### Slice Length Example Source: https://docs.rs/rusqlite/latest/rusqlite/serialize/enum.Data.html Demonstrates getting the number of elements in a slice. ```rust let a = [1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### Example Usage Source: https://docs.rs/rusqlite/latest/rusqlite/vtab/array/index.html Demonstrates how to load the array module and query an array using the 'rarray' table-valued function. ```APIDOC ## Example ### Description This example shows how to load the `rarray` module and then query an array using SQL. ### Code ```rust use rusqlite::{Connection, Result, Value}; use std::rc::Rc; fn example(db: &Connection) -> Result<()> { // Note: This should be done once (usually when opening the DB). rusqlite::vtab::array::load_module(&db)?; let v = [1i64, 2, 3, 4]; // Note: A `Rc>` must be used as the parameter. let values = Rc::new(v.iter().copied().map(Value::from).collect::>()); let mut stmt = db.prepare("SELECT value from rarray(?1);")?; let rows = stmt.query_map([values], |row| row.get::<_, i64>(0))?; for value in rows { println!("{}", value?); } Ok(()) } ``` ### Notes - The `rarray` module must be loaded before it can be used. - Parameters passed to `rarray` must be of type `Rc>`. ``` -------------------------------- ### Begin Transaction Method Source: https://docs.rs/rusqlite/latest/rusqlite/vtab/trait.TransactionVTab.html Starts a new transaction for a virtual table. This method is part of the TransactionVTab trait. ```rust fn begin(&mut self) -> Result<()> { ... } ``` -------------------------------- ### Example of Loading a Trusted Extension Source: https://docs.rs/rusqlite/latest/rusqlite/struct.LoadExtensionGuard.html Demonstrates how to use LoadExtensionGuard to safely load a trusted extension. The guard ensures that extension loading is disabled once the scope is exited. ```rust fn load_my_extension(conn: &Connection) -> Result<()> { unsafe { let _guard = LoadExtensionGuard::new(conn)?; conn.load_extension("trusted/sqlite/extension", None::<&str>) } } ``` -------------------------------- ### Basic Usage of params_from_iter Source: https://docs.rs/rusqlite/latest/rusqlite/struct.ParamsFromIter.html Demonstrates how to use `params_from_iter` with a `BTreeSet` to query users by ID. Assumes an unrealistic fixed number of IDs for the example. ```rust use rusqlite::{params_from_iter, Connection, Result}; use std::collections::BTreeSet; fn query(conn: &Connection, ids: &BTreeSet) -> Result<()> { assert_eq!(ids.len(), 3, "Unrealistic sample code"); let mut stmt = conn.prepare("SELECT * FROM users WHERE id IN (?1, ?2, ?3)")?; let _rows = stmt.query(params_from_iter(ids.iter()))?; // use _rows... Ok(()) } ``` -------------------------------- ### unwrap_or_else Example Source: https://docs.rs/rusqlite/latest/rusqlite/types/type.FromSqlResult.html Demonstrates using unwrap_or_else to provide a default value or execute a closure when the Result is an Err. ```rust assert_eq!(Ok(2).unwrap_or_else(count), 2); assert_eq!(Err("foo").unwrap_or_else(count), 3); ``` -------------------------------- ### Option::map_or_default Example (Nightly) Source: https://docs.rs/rusqlite/latest/rusqlite/functions/type.SubType.html This nightly-only experimental API maps an Option to a value using a function if Some, or returns the default value of the target type if None. ```rust #![feature(result_option_map_or_default)] let x: Option<&str> = Some("hi"); let y: Option<&str> = None; assert_eq!(x.map_or_default(|x| x.len()), 2); assert_eq!(y.map_or_default(|y| y.len()), 0); ``` -------------------------------- ### SQL Example for Loading Extensions Source: https://docs.rs/rusqlite/latest/rusqlite/functions/struct.ConnectionRef.html This SQL query demonstrates how extensions can be loaded directly via SQL when `load_extension_enable` is active. This highlights the safety concerns associated with enabling extension loading. ```sql SELECT load_extension('why_is_this_possible.dll', 'dubious_func'); ``` -------------------------------- ### Iterating over a slice Source: https://docs.rs/rusqlite/latest/rusqlite/serialize/enum.Data.html Use `iter()` to get an iterator that yields all items from start to end of a slice. ```Rust let x = &[1, 2, 4]; let mut iterator = x.iter(); assert_eq!(iterator.next(), Some(&1)); assert_eq!(iterator.next(), Some(&2)); assert_eq!(iterator.next(), Some(&4)); assert_eq!(iterator.next(), None); ``` -------------------------------- ### Creating and Iterating a Batch of SQL Statements Source: https://docs.rs/rusqlite/latest/rusqlite/struct.Batch.html This example demonstrates how to create a Batch from a connection and a multi-statement SQL string. It iterates through each statement, executing it and handling potential errors. Remember to break the loop if an error occurs during iteration. ```rust use fallible_iterator::FallibleIterator; use rusqlite::{Batch, Connection, Result}; fn main() -> Result<()> { let conn = Connection::open_in_memory()?; let sql = r" CREATE TABLE tbl1 (col); CREATE TABLE tbl2 (col); "; let mut batch = Batch::new(&conn, sql); while let Some(mut stmt) = batch.next()? { stmt.execute([])?; } Ok(()) } ``` -------------------------------- ### Rusqlite Blob I/O Example Source: https://docs.rs/rusqlite/latest/rusqlite/blob/index.html This snippet demonstrates creating a table, inserting blobs, and performing read/write operations on them using the rusqlite Blob API. It requires opening a connection to an in-memory database and executing SQL commands. ```rust let db = Connection::open_in_memory()?; db.execute_batch("CREATE TABLE test_table (content BLOB);")?; // Insert a blob into the `content` column of `test_table`. Note that the Blob // I/O API provides no way of inserting or resizing blobs in the DB -- this // must be done via SQL. db.execute("INSERT INTO test_table (content) VALUES (ZEROBLOB(10))", [])?; // Get the row id off the blob we just inserted. let rowid = db.last_insert_rowid(); // Open the blob we just inserted for IO. let mut blob = db.blob_open(MAIN_DB, "test_table", "content", rowid, false)?; // Write some data into the blob. blob.write_at(b"ABCDEF", 2)?; // Read the whole blob into a local buffer. let mut buf = [0u8; 10]; blob.read_at_exact(&mut buf, 0)?; assert_eq!(&buf, b"\0\0ABCDEF\0\0"); // Insert another blob, this time using a parameter passed in from // rust (potentially with a dynamic size). db.execute( "INSERT INTO test_table (content) VALUES (?1)", [ZeroBlob(64)], )?; // given a new row ID, we can reopen the blob on that row let rowid = db.last_insert_rowid(); blob.reopen(rowid)?; assert_eq!(blob.len(), 64); ``` -------------------------------- ### Get SQLite Version Number Source: https://docs.rs/rusqlite/latest/rusqlite/fn.version_number.html Call `version_number()` to retrieve the SQLite version as an integer. For example, version 3.16.2 is returned as 3016002. ```rust use rusqlite::version_number; fn main() { let version = version_number(); println!("SQLite version number: {}", version); } ``` -------------------------------- ### Implementations of FromSql for common types Source: https://docs.rs/rusqlite/latest/rusqlite/types/trait.FromSql.html Examples of how common Rust types implement the FromSql trait, allowing them to be directly read from SQLite. ```APIDOC ### impl FromSql for Arc<[u8]> #### fn column_result(value: ValueRef<'_>) -> FromSqlResult ### impl FromSql for Arc #### fn column_result(value: ValueRef<'_>) -> FromSqlResult ### impl FromSql for Box<[u8]> #### fn column_result(value: ValueRef<'_>) -> FromSqlResult ### impl FromSql for Box #### fn column_result(value: ValueRef<'_>) -> FromSqlResult ### impl FromSql for NonZeroI8 #### fn column_result(value: ValueRef<'_>) -> FromSqlResult ### impl FromSql for NonZeroI16 #### fn column_result(value: ValueRef<'_>) -> FromSqlResult ### impl FromSql for NonZeroI32 #### fn column_result(value: ValueRef<'_>) -> FromSqlResult ### impl FromSql for NonZeroI64 #### fn column_result(value: ValueRef<'_>) -> FromSqlResult ### impl FromSql for NonZeroI128 #### fn column_result(value: ValueRef<'_>) -> FromSqlResult ### impl FromSql for NonZeroIsize #### fn column_result(value: ValueRef<'_>) -> FromSqlResult ### impl FromSql for NonZeroU8 #### fn column_result(value: ValueRef<'_>) -> FromSqlResult ### impl FromSql for NonZeroU16 #### fn column_result(value: ValueRef<'_>) -> FromSqlResult ### impl FromSql for NonZeroU32 #### fn column_result(value: ValueRef<'_>) -> FromSqlResult ### impl FromSql for Rc<[u8]> #### fn column_result(value: ValueRef<'_>) -> FromSqlResult ``` -------------------------------- ### Unsafe unwrap_err_unchecked Example Source: https://docs.rs/rusqlite/latest/rusqlite/types/type.FromSqlResult.html Demonstrates using unwrap_err_unchecked to get the Err value without checking for an Ok. This is unsafe and can lead to undefined behavior if called on an Ok. ```rust let x: Result = Ok(2); unsafe { x.unwrap_err_unchecked() }; // Undefined behavior! ``` ```rust let x: Result = Err("emergency failure"); assert_eq!(unsafe { x.unwrap_err_unchecked() }, "emergency failure"); ``` -------------------------------- ### Unsafe unwrap_unchecked Example Source: https://docs.rs/rusqlite/latest/rusqlite/types/type.FromSqlResult.html Shows how to use unwrap_unchecked to get the Ok value without checking for an Err. This is unsafe and can lead to undefined behavior if called on an Err. ```rust let x: Result = Ok(2); assert_eq!(unsafe { x.unwrap_unchecked() }, 2); ``` ```rust let x: Result = Err("emergency failure"); unsafe { x.unwrap_unchecked() }; // Undefined behavior! ``` -------------------------------- ### PrepFlags::new Source: https://docs.rs/rusqlite/latest/rusqlite/struct.PrepFlags.html Creates a new PrepFlags instance with default values. ```APIDOC ## PrepFlags::new ### Description Creates a new `PrepFlags` instance with default values. ### Method `PrepFlags::new()` ### Parameters None ### Returns A new `PrepFlags` instance. ``` -------------------------------- ### Basic SQLite Operations in Rust Source: https://docs.rs/rusqlite/latest/rusqlite/index.html Demonstrates creating a table, inserting data, and querying records from an in-memory SQLite database using the rusqlite crate. Ensure the rusqlite crate is added as a dependency. ```rust use rusqlite::{params, Connection, Result}; #[derive(Debug)] struct Person { id: i32, name: String, data: Option>, } fn main() -> Result<()> { let conn = Connection::open_in_memory()?; conn.execute( "CREATE TABLE person ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, data BLOB )", (), // empty list of parameters. )?; let me = Person { id: 0, name: "Steven".to_string(), data: None, }; conn.execute( "INSERT INTO person (name, data) VALUES (?1, ?2)", (&me.name, &me.data), )?; let mut stmt = conn.prepare("SELECT id, name, data FROM person")?; let person_iter = stmt.query_map([], |row| { Ok(Person { id: row.get(0)?, name: row.get(1)?, data: row.get(2)?, }) })?; for person in person_iter { println!("Found person {:?}", person?); } Ok(()) } ``` -------------------------------- ### Option::as_deref Example Source: https://docs.rs/rusqlite/latest/rusqlite/functions/type.SubType.html Converts an `Option` to an `Option<&T::Target>` by applying `Deref`. This allows you to get a reference to the inner value's dereferenced type without consuming the Option. ```rust let x: Option = Some("hey".to_owned()); assert_eq!(x.as_deref(), Some("hey")); let x: Option = None; assert_eq!(x.as_deref(), None); ``` -------------------------------- ### Get element offset in a slice Source: https://docs.rs/rusqlite/latest/rusqlite/serialize/enum.Data.html The `element_offset` method returns the index of an element reference within a slice. It uses pointer arithmetic and does not compare elements. It returns `None` if the element reference is not aligned to the start of an element in the slice. This method panics if `T` is zero-sized. ```rust let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` ```rust let arr: &[[u32; 2]] = &[[0, 1], [2, 3]]; let flat_arr: &[u32] = arr.as_flattened(); let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap(); let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap(); assert_eq!(ok_elm, &[0, 1]); assert_eq!(weird_elm, &[1, 2]); assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0 assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1 ``` -------------------------------- ### Savepoint Usage Example Source: https://docs.rs/rusqlite/latest/rusqlite/struct.Savepoint.html Demonstrates how to use savepoints to perform a series of queries. If any query fails, the savepoint causes a rollback. Explicitly commit the savepoint to make changes permanent. ```rust fn perform_queries(conn: &mut Connection) -> Result<()> { let sp = conn.savepoint()?; do_queries_part_1(&sp)?; // sp causes rollback if this fails do_queries_part_2(&sp)?; // sp causes rollback if this fails sp.commit() } ``` -------------------------------- ### get Source: https://docs.rs/rusqlite/latest/rusqlite/vtab/struct.Inserts.html Returns value at `idx`. ```APIDOC ### pub fn get(&self, idx: usize) -> Result Returns value at `idx` ``` -------------------------------- ### Prepare and Execute SQL Statements Source: https://docs.rs/rusqlite/latest/rusqlite/functions/struct.ConnectionRef.html Use `prepare` to create a reusable `Statement` object for executing the same SQL multiple times, which can improve performance. This example shows inserting multiple rows. ```rust fn insert_new_people(conn: &Connection) -> Result<()> { let mut stmt = conn.prepare("INSERT INTO People (name) VALUES (?1)")?; stmt.execute(["Joe Smith"])?; stmt.execute(["Bob Jones"])?; Ok(()) } ``` -------------------------------- ### get_status Source: https://docs.rs/rusqlite/latest/rusqlite/struct.CachedStatement.html Get the value for one of the status counters for this statement. ```APIDOC ## pub fn get_status(&self, status: StatementStatus) -> i32 ### Description Get the value for one of the status counters for this statement. ``` -------------------------------- ### pub fn create_module<'vtab, T: VTab<'vtab>, M: Name>(&self, module_name: M, module: &'static Module<'vtab, T>, aux: Option) -> Result<()> Source: https://docs.rs/rusqlite/latest/rusqlite/vtab/struct.ConnectionRef.html Registers a virtual table implementation. This is Step 3 of Creating New Virtual Table Implementations. ```APIDOC ## pub fn create_module<'vtab, T: VTab<'vtab>, M: Name>(&self, module_name: M, module: &'static Module<'vtab, T>, aux: Option) -> Result<()> ### Description Register a virtual table implementation. Step 3 of Creating New Virtual Table Implementations. ``` -------------------------------- ### pub fn path(&self) -> Option<&str> Source: https://docs.rs/rusqlite/latest/rusqlite/vtab/struct.ConnectionRef.html Returns the path to the database file, if it exists and is known. Returns `Some("")` for temporary or in-memory databases. `PRAGMA database_list` might be more robust in some cases. ```APIDOC ## pub fn path(&self) -> Option<&str> ### Description Returns the path to the database file, if one exists and is known. Returns `Some("")` for a temporary or in-memory database. Note that in some cases PRAGMA database_list is likely to be more robust. ``` -------------------------------- ### impl Any for T Source: https://docs.rs/rusqlite/latest/rusqlite/struct.OpenFlags.html Provides the `type_id` method to get the `TypeId` of an object. ```APIDOC ## fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. ``` -------------------------------- ### Slice Is Empty Example Source: https://docs.rs/rusqlite/latest/rusqlite/serialize/enum.Data.html Checks if a slice has a length of 0. ```rust let a = [1, 2, 3]; assert!(!a.is_empty()); let b: &[i32] = &[]; assert!(b.is_empty()); ``` -------------------------------- ### Run Backup to Completion Source: https://docs.rs/rusqlite/latest/rusqlite/backup/struct.Backup.html Executes the entire backup process, calling `step` repeatedly. It includes an option to pause between steps to allow the source database to process queries, making it suitable for online backups of running databases. A progress callback can be provided. ```rust pub fn run_to_completion( &self, pages_per_step: c_int, pause_between_pages: Duration, progress: Option, ) -> Result<()> ``` -------------------------------- ### Example of Passing Positional Parameters Source: https://docs.rs/rusqlite/latest/rusqlite/trait.Params.html Demonstrates various ways to pass positional parameters to SQL statements using tuples, the `params!` macro, array literals, and slices of references. Ensure correct usage for different parameter types and counts. ```rust fn update_rows(conn: &Connection) -> Result<()> { let mut stmt = conn.prepare("INSERT INTO test (a, b) VALUES (?1, ?2)")?; // Using a tuple: stmt.execute((0, "foobar"))?; // Using `rusqlite::params!`: stmt.execute(params![1i32, "blah"])?; // array literal — non-references stmt.execute([2i32, 3i32])?; // array literal — references stmt.execute(["foo", "bar"])?; // Slice literal, references: stmt.execute(&[&2i32, &3i32])?; // Note: The types behind the references don't have to be `Sized` stmt.execute(&["foo", "bar"])?; // However, this doesn't work (see above): // stmt.execute(&[1i32, 2i32])?; Ok(()) } ``` -------------------------------- ### strip_prefix Source: https://docs.rs/rusqlite/latest/rusqlite/serialize/enum.Data.html Returns a subslice with the prefix removed. If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`. If `prefix` is empty, simply returns the original slice. If `prefix` is equal to the original slice, returns an empty slice. If the slice does not start with `prefix`, returns `None`. ```APIDOC ## strip_prefix

(&self, prefix: &P) -> Option<&[T]> ### Description Returns a subslice with the prefix removed. If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`. If `prefix` is empty, simply returns the original slice. If `prefix` is equal to the original slice, returns an empty slice. If the slice does not start with `prefix`, returns `None`. ### Parameters #### Path Parameters - **prefix** (&P) - Required - The prefix to remove from the slice. `P` must implement `SlicePattern`. ### Return Value Option<&[T]> - An Option containing the subslice with the prefix removed, or None if the slice does not start with the prefix. ``` -------------------------------- ### Limit Management Source: https://docs.rs/rusqlite/latest/rusqlite/struct.Connection.html Methods for getting and setting limits on database operations. ```APIDOC ## limit ### Description Returns the current value of a `Limit`. ### Method `Connection::limit(&self, limit: Limit) -> Result` ### Parameters - **limit** (Limit) - The type of limit to query. ### Response #### Success Response (Result) - Returns the current value of the specified limit. ``` ```APIDOC ## set_limit ### Description Changes the `Limit` to `new_val`, returning the prior value of the limit. ### Method `Connection::set_limit(&self, limit: Limit, new_val: i32) -> Result` ### Parameters - **limit** (Limit) - The type of limit to set. - **new_val** (i32) - The new value for the limit. ### Response #### Success Response (Result) - Returns the prior value of the specified limit. ``` -------------------------------- ### Cloning and Copying PrepFlags Source: https://docs.rs/rusqlite/latest/rusqlite/struct.PrepFlags.html Details on how to clone and copy `PrepFlags` instances. ```APIDOC ## Cloning and Copying PrepFlags This section describes the cloning and copying capabilities of `PrepFlags`. ### `clone(&self) -> PrepFlags` Creates a new `PrepFlags` instance that is a duplicate of the original. ### `clone_from(&mut self, source: &Self)` Copies the value from a source `PrepFlags` instance to the mutable `self` instance. ### `Copy` Trait `PrepFlags` implements the `Copy` trait, meaning instances can be copied implicitly. ``` -------------------------------- ### Get Blob Size Source: https://docs.rs/rusqlite/latest/rusqlite/blob/struct.Blob.html Returns the total size of the BLOB in bytes. ```rust pub fn size(&self) -> i32 ``` -------------------------------- ### Step Through Backup Process Source: https://docs.rs/rusqlite/latest/rusqlite/backup/struct.Backup.html Attempts to back up a specified number of pages. If a negative number is provided, it attempts to back up all remaining pages. This method holds a lock on the source database, which might not be suitable for active databases. ```rust pub fn step(&self, num_pages: c_int) -> Result ``` -------------------------------- ### iter() Source: https://docs.rs/rusqlite/latest/rusqlite/serialize/enum.Data.html Returns an iterator over the slice, yielding all items from start to end. ```APIDOC ## pub fn iter(&self) -> Iter<'_, T> ### Description Returns an iterator over the slice. The iterator yields all items from start to end. ### Examples ```rust let x = &[1, 2, 4]; let mut iterator = x.iter(); assert_eq!(iterator.next(), Some(&1)); assert_eq!(iterator.next(), Some(&2)); assert_eq!(iterator.next(), Some(&4)); assert_eq!(iterator.next(), None); ``` ### Returns - `Iter<'_, T>`: An iterator over the elements of the slice. ``` -------------------------------- ### Basic Binary Search on a Sorted Slice Source: https://docs.rs/rusqlite/latest/rusqlite/serialize/enum.Data.html Demonstrates how to use `binary_search` to find an element in a sorted slice. It shows successful lookups, cases where the element is not found, and how to handle multiple matches. ```rust let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; assert_eq!(s.binary_search(&13), Ok(9)); assert_eq!(s.binary_search(&4), Err(7)); assert_eq!(s.binary_search(&100), Err(13)); let r = s.binary_search(&1); assert!(match r { Ok(1..=4) => true, _ => false, }); ``` -------------------------------- ### Get Parameter Count Source: https://docs.rs/rusqlite/latest/rusqlite/struct.CachedStatement.html Returns the total number of parameters that can be bound to this statement. ```rust fn example(conn: &Connection) -> Result<()> { let stmt = conn.prepare("SELECT * FROM test WHERE name = :example AND value > ?2")?; assert_eq!(stmt.parameter_count(), 2); Ok(()) } ``` -------------------------------- ### Get database configuration Source: https://docs.rs/rusqlite/latest/rusqlite/struct.Savepoint.html Retrieves the current value of a specified database configuration option. ```APIDOC ## pub fn db_config(&self, config: DbConfig) -> Result ### Description Returns the current value of a `config`. ### Parameters #### Path Parameters - `config` (DbConfig): The database configuration option to query. * `SQLITE_DBCONFIG_ENABLE_FKEY`: return `false` or `true` to indicate whether FK enforcement is off or on * `SQLITE_DBCONFIG_ENABLE_TRIGGER`: return `false` or `true` to indicate whether triggers are disabled or enabled * `SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER`: return `false` or `true` to indicate whether `fts3_tokenizer` are disabled or enabled * `SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE`: return `false` to indicate checkpoints-on-close are not disabled or `true` if they are * `SQLITE_DBCONFIG_ENABLE_QPSG`: return `false` or `true` to indicate whether the QPSG is disabled or enabled * `SQLITE_DBCONFIG_TRIGGER_EQP`: return `false` to indicate output-for-trigger are not disabled or `true` if it is ### Returns - `Result`: Returns `Ok(true)` or `Ok(false)` based on the configuration value. Returns `Err` if the configuration cannot be retrieved. ``` -------------------------------- ### Backup::run_to_completion Source: https://docs.rs/rusqlite/latest/rusqlite/backup/struct.Backup.html Executes the entire backup process, iteratively calling `step` with a configurable number of pages per step and an optional pause between steps. It can also report progress via a callback function. ```APIDOC ## Backup::run_to_completion ### Description Attempts to run the entire backup. Will call `step(pages_per_step)` as many times as necessary, sleeping for `pause_between_pages` between each call to give the source database time to process any pending queries. This is a direct implementation of “Example 2: Online Backup of a Running Database” from SQLite’s Online Backup API documentation. If `progress` is not `None`, it will be called after each step with the current progress of the backup. Note that is possible the progress may not change if the step returns `Busy` or `Locked` even though the backup is still running. ### Signature ```rust pub fn run_to_completion( &self, pages_per_step: c_int, pause_between_pages: Duration, progress: Option, ) -> Result<()> ``` ### Failure Will return `Err` if any of the calls to `step` return `Err`. ``` -------------------------------- ### Get Database Name Source: https://docs.rs/rusqlite/latest/rusqlite/hooks/struct.Wal.html Retrieves the name of the database that was written to, associated with the Wal instance. ```APIDOC ## `name()` ### Description Name of the database that was written to. ### Method `&self.name() -> &CStr` ``` -------------------------------- ### Rc::weak_count Source: https://docs.rs/rusqlite/latest/rusqlite/vtab/array/type.Array.html Gets the number of Weak pointers to this allocation. This count does not include the strong count. ```APIDOC ## Rc::weak_count ### Description Gets the number of `Weak` pointers to this allocation. This count does not include the strong count. ### Method `weak_count` ### Parameters #### Path Parameters - **this** (&Rc) - Required - A reference to the `Rc` to get the weak count from. ### Request Example ```rust use std::rc::Rc; let five = Rc::new(5); let _weak_five = Rc::downgrade(&five); assert_eq!(1, Rc::weak_count(&five)); ``` ### Response #### Success Response (usize) - **Returns**: The number of `Weak` pointers to the allocation. ### Response Example ```json { "example": 1 } ``` ``` -------------------------------- ### Any Trait Implementation Source: https://docs.rs/rusqlite/latest/rusqlite/struct.Row.html The `Any` trait is implemented for all types `T`, providing a `type_id` method to get the `TypeId` of `self`. ```APIDOC ## impl Any for T ### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. ``` -------------------------------- ### Begin a new transaction with specified behavior Source: https://docs.rs/rusqlite/latest/rusqlite/struct.Connection.html Starts a new transaction with a specified behavior, allowing control over when the transaction becomes active (e.g., IMMEDIATE, EXCLUSIVE). -------------------------------- ### Rc::strong_count Source: https://docs.rs/rusqlite/latest/rusqlite/vtab/array/type.Array.html Gets the number of strong (Rc) pointers to this allocation. This count does not include the weak count. ```APIDOC ## Rc::strong_count ### Description Gets the number of strong (`Rc`) pointers to this allocation. This count does not include the weak count. ### Method `strong_count` ### Parameters #### Path Parameters - **this** (&Rc) - Required - A reference to the `Rc` to get the strong count from. ### Request Example ```rust use std::rc::Rc; let five = Rc::new(5); let _also_five = Rc::clone(&five); assert_eq!(2, Rc::strong_count(&five)); ``` ### Response #### Success Response (usize) - **Returns**: The number of strong (`Rc`) pointers to the allocation. ### Response Example ```json { "example": 2 } ``` ``` -------------------------------- ### Enable and Load SQLite Extensions Source: https://docs.rs/rusqlite/latest/rusqlite/functions/struct.ConnectionRef.html Use `load_extension_enable` to allow loading SQLite extensions. Ensure `load_extension_disable` is called afterward, or use `LoadExtensionGuard` for automatic management. This example demonstrates loading a trusted extension. ```rust fn load_my_extension(conn: &Connection) -> Result<()> { // Safety: We fully trust the loaded extension and execute no untrusted SQL // while extension loading is enabled. unsafe { conn.load_extension_enable()?; let r = conn.load_extension("my/trusted/extension", None::<&str>); conn.load_extension_disable()?; r } } ``` -------------------------------- ### Begin a New Savepoint with Name Source: https://docs.rs/rusqlite/latest/rusqlite/struct.Savepoint.html Initiates a new savepoint with a user-defined name. This allows for more specific referencing and management of savepoints. ```rust pub fn with_name>( conn: &mut Connection, name: T, ) -> Result> ``` -------------------------------- ### get Source: https://docs.rs/rusqlite/latest/rusqlite/serialize/enum.Data.html Returns a reference to an element or subslice depending on the type of index. Returns `None` if the index is out of bounds. ```APIDOC ## pub fn get(&self, index: I) -> Option<&>::Output> where I: SliceIndex<[T]> ### Description Returns a reference to an element or subslice depending on the type of index. If given a position, returns a reference to the element at that position or `None` if out of bounds. If given a range, returns the subslice corresponding to that range, or `None` if out of bounds. ### Examples ```rust let v = [10, 40, 30]; assert_eq!(Some(&40), v.get(1)); assert_eq!(Some(&[10, 40][..]), v.get(0..2)); assert_eq!(None, v.get(3)); assert_eq!(None, v.get(0..4)); ``` ``` -------------------------------- ### Implementations of FromSql for Date and Time types Source: https://docs.rs/rusqlite/latest/rusqlite/types/trait.FromSql.html Demonstrates how various date and time types from different crates (like `chrono` and `time`) can be converted from SQLite values, often requiring specific feature flags. ```APIDOC ### impl FromSql for Date (crate feature`jiff`) Available on **crate feature`jiff`** only. “YYYY-MM-DD” => Gregorian calendar date. #### fn column_result(value: ValueRef<'_>) -> FromSqlResult ### impl FromSql for Date (crate feature`time`) Available on **crate feature`time`** only. “YYYY-MM-DD” => ISO 8601 calendar date without timezone. #### fn column_result(value: ValueRef<'_>) -> FromSqlResult ### impl FromSql for DateTime (crate feature`jiff`) Available on **crate feature`jiff`** only. “YYYY-MM-DDTHH:MM:SS.SSS” => Gregorian datetime. #### fn column_result(value: ValueRef<'_>) -> FromSqlResult ### impl FromSql for DateTime (crate feature`chrono`) Available on **crate feature`chrono`** only. RFC3339 (“YYYY-MM-DD HH:MM:SS.SSS[+-]HH:MM”) into `DateTime`. #### fn column_result(value: ValueRef<'_>) -> FromSqlResult ### impl FromSql for DateTime (crate feature`chrono`) Available on **crate feature`chrono`** only. RFC3339 (“YYYY-MM-DD HH:MM:SS.SSS[+-]HH:MM”) or unix timestamp (in seconds) into `DateTime`. #### fn column_result(value: ValueRef<'_>) -> FromSqlResult ### impl FromSql for DateTime (crate feature`chrono`) Available on **crate feature`chrono`** only. RFC3339 (“YYYY-MM-DD HH:MM:SS.SSS[+-]HH:MM”) or unix timestamp (in seconds) into `DateTime`. #### fn column_result(value: ValueRef<'_>) -> FromSqlResult ### impl FromSql for NaiveDate (crate feature`chrono`) Available on **crate feature`chrono`** only. “YYYY-MM-DD” => ISO 8601 calendar date without timezone. #### fn column_result(value: ValueRef<'_>) -> FromSqlResult ### impl FromSql for NaiveDateTime (crate feature`chrono`) Available on **crate feature`chrono`** only. “YYYY-MM-DD HH:MM:SS”/“YYYY-MM-DD HH:MM:SS.SSS” => ISO 8601 combined date and time without timezone. (“YYYY-MM-DDTHH:MM:SS”/“YYYY-MM-DDTHH:MM:SS.SSS” also supported) #### fn column_result(value: ValueRef<'_>) -> FromSqlResult ### impl FromSql for NaiveTime (crate feature`chrono`) Available on **crate feature`chrono`** only. “HH:MM”/“HH:MM:SS”/“HH:MM:SS.SSS” => ISO 8601 time without timezone. #### fn column_result(value: ValueRef<'_>) -> FromSqlResult ### impl FromSql for OffsetDateTime (crate feature`time`) Available on **crate feature`time`** only. #### fn column_result(value: ValueRef<'_>) -> FromSqlResult ### impl FromSql for PrimitiveDateTime (crate feature`time`) Available on **crate feature`time`** only. YYYY-MM-DD HH:MM YYYY-MM-DDTHH:MM YYYY-MM-DD HH:MM:SS YYYY-MM-DDTHH:MM:SS YYYY-MM-DD HH:MM:SS.SSS YYYY-MM-DDTHH:MM:SS.SSS => ISO 8601 combined date and time with timezone #### fn column_result(value: ValueRef<'_>) -> FromSqlResult ``` -------------------------------- ### PrepFlags Initialization and Conversion Source: https://docs.rs/rusqlite/latest/rusqlite/struct.PrepFlags.html Methods for creating and converting PrepFlags values. Use `empty` for no flags, `all` for all known flags, and `from_bits` variants for conversion from raw integer values. ```rust pub const fn empty() -> Self ``` ```rust pub const fn all() -> Self ``` ```rust pub const fn bits(&self) -> c_uint ``` ```rust pub const fn from_bits(bits: c_uint) -> Option ``` ```rust pub const fn from_bits_truncate(bits: c_uint) -> Self ``` ```rust pub const fn from_bits_retain(bits: c_uint) -> Self ``` ```rust pub fn from_name(name: &str) -> Option ``` -------------------------------- ### Slice Last Element Example Source: https://docs.rs/rusqlite/latest/rusqlite/serialize/enum.Data.html Retrieves the last element of a slice, returning None if the slice is empty. ```rust let v = [10, 40, 30]; assert_eq!(Some(&30), v.last()); let w: &[i32] = &[]; assert_eq!(None, w.last()); ``` -------------------------------- ### Slice First Element Example Source: https://docs.rs/rusqlite/latest/rusqlite/serialize/enum.Data.html Retrieves the first element of a slice, returning None if the slice is empty. ```rust let v = [10, 40, 30]; assert_eq!(Some(&10), v.first()); let w: &[i32] = &[]; assert_eq!(None, w.first()); ``` -------------------------------- ### Begin a new savepoint (DEFERRED) Source: https://docs.rs/rusqlite/latest/rusqlite/struct.Connection.html Starts a new savepoint with default DEFERRED behavior. Savepoints allow for partial rollbacks within a larger transaction. They roll back when dropped unless commit is called or drop behavior is set to Commit. ```rust fn perform_queries(conn: &mut Connection) -> Result<()> { let sp = conn.savepoint()?; do_queries_part_1(&sp)?; do_queries_part_2(&sp)?; sp.commit() } ``` -------------------------------- ### Load and Query Array Module Source: https://docs.rs/rusqlite/latest/rusqlite/vtab/array/index.html Demonstrates how to load the `rarray` module and query it with an array of values. Ensure `Rc>` is used for array parameters. ```rust fn example(db: &Connection) -> Result<()> { // Note: This should be done once (usually when opening the DB). rusqlite::vtab::array::load_module(&db)?; let v = [1i64, 2, 3, 4]; // Note: A `Rc>` must be used as the parameter. let values = Rc::new(v.iter().copied().map(Value::from).collect::>()); let mut stmt = db.prepare("SELECT value from rarray(?1);")?; let rows = stmt.query_map([values], |row| row.get::<_, i64>(0))?; for value in rows { println!("{}", value?); } Ok(()) } ``` -------------------------------- ### Begin a New Savepoint Source: https://docs.rs/rusqlite/latest/rusqlite/struct.Savepoint.html Initiates a new savepoint on the database connection. This can be nested within existing savepoints or transactions. ```rust pub fn new(conn: &mut Connection) -> Result> ``` -------------------------------- ### Get IN constraint values Source: https://docs.rs/rusqlite/latest/rusqlite/vtab/struct.Filters.html Retrieves all elements on the right-hand side of an IN constraint. This method requires the 'modern_sqlite' crate feature. ```rust pub fn in_values(&self, idx: usize) -> Result> ``` -------------------------------- ### Get Database Filename Source: https://docs.rs/rusqlite/latest/rusqlite/trace/struct.ConnRef.html Retrieves the path to the database file if it is known and exists. Returns `None` if the filename is not available. ```rust pub fn db_filename(&self) -> Option<&str> ``` -------------------------------- ### Equality and Extension for PrepFlags Source: https://docs.rs/rusqlite/latest/rusqlite/struct.PrepFlags.html Details on equality comparison and extending `PrepFlags`. ```APIDOC ## Equality and Extension for PrepFlags This section outlines equality checks and extension methods for `PrepFlags`. ### `Eq` Trait `PrepFlags` implements the `Eq` trait, allowing for equality comparisons between instances. ### `Extend` Trait #### `extend>(&mut self, iterator: T)` Extends the `PrepFlags` instance by performing a bitwise OR with all flags from the provided iterator. #### `extend_one(&mut self, item: A)` (Nightly-only) Extends the collection with a single `PrepFlags` item. #### `extend_reserve(&mut self, additional: usize)` (Nightly-only) Reserves capacity for additional elements. ``` -------------------------------- ### open_with_flags_and_vfs Source: https://docs.rs/rusqlite/latest/rusqlite/struct.Connection.html Opens a new connection to a SQLite database using specific flags and a VFS name. Returns an Err if the path or VFS name cannot be converted to C-compatible strings or if the underlying SQLite open call fails. ```APIDOC ## open_with_flags_and_vfs, V: Name>(path: P, flags: OpenFlags, vfs: V) -> Result ### Description Open a new connection to a SQLite database using the specific flags and vfs name. ### Parameters #### Path Parameters - **path** (P: AsRef) - Required - The path to the SQLite database file. - **flags** (OpenFlags) - Required - Flags to control database opening behavior. - **vfs** (V: Name) - Required - The name of the VFS to use. ### Failure Will return `Err` if either `path` or `vfs` cannot be converted to a C-compatible string or if the underlying SQLite open call fails. ``` -------------------------------- ### Option::iter Example Source: https://docs.rs/rusqlite/latest/rusqlite/functions/type.SubType.html Returns an iterator that yields a reference to the contained value if the Option is Some, or is empty if the Option is None. ```rust let x = Some(4); assert_eq!(x.iter().next(), Some(&4)); ``` -------------------------------- ### init_auto_extension Source: https://docs.rs/rusqlite/latest/rusqlite/auto_extension/index.html Bridges the gap between raw and managed auto-extension initialization routines. ```APIDOC ## Function: init_auto_extension ### Description Provides a bridge between `RawAutoExtension` and `AutoExtension` for initializing automatic extensions. ### Parameters None ``` -------------------------------- ### rchunks_exact Source: https://docs.rs/rusqlite/latest/rusqlite/serialize/enum.Data.html Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end of the slice. The chunks are slices and do not overlap. ```APIDOC ## pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T> ### Description Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end of the slice. The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved from the `remainder` function of the iterator. Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the resulting code better than in the case of `rchunks`. See `rchunks` for a variant of this iterator that also returns the remainder as a smaller chunk, and `chunks_exact` for the same iterator but starting at the beginning of the slice. If your `chunk_size` is a constant, consider using `as_rchunks` instead, which will give references to arrays of exactly that length, rather than slices. ### Panics Panics if `chunk_size` is zero. ### Examples ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.rchunks_exact(2); assert_eq!(iter.next().unwrap(), &['e', 'm']); assert_eq!(iter.next().unwrap(), &['o', 'r']); assert!(iter.next().is_none()); assert_eq!(iter.remainder(), &['l']); ``` ``` -------------------------------- ### rchunks Source: https://docs.rs/rusqlite/latest/rusqlite/serialize/enum.Data.html Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end of the slice. The chunks are slices and do not overlap. ```APIDOC ## pub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T> ### Description Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end of the slice. The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the slice, then the last chunk will not have length `chunk_size`. See `rchunks_exact` for a variant of this iterator that returns chunks of always exactly `chunk_size` elements, and `chunks` for the same iterator but starting at the beginning of the slice. If your `chunk_size` is a constant, consider using `as_rchunks` instead, which will give references to arrays of exactly that length, rather than slices. ### Panics Panics if `chunk_size` is zero. ### Examples ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.rchunks(2); assert_eq!(iter.next().unwrap(), &['e', 'm']); assert_eq!(iter.next().unwrap(), &['o', 'r']); assert_eq!(iter.next().unwrap(), &['l']); assert!(iter.next().is_none()); ``` ``` -------------------------------- ### Connection::open Source: https://docs.rs/rusqlite/latest/rusqlite/struct.Connection.html Opens a new connection to a SQLite database file. If the database file does not exist, it will be created. ```APIDOC ## Connection::open ### Description Open a new connection to a SQLite database. If a database does not exist at the path, one is created. ### Method `open>(path: P) -> Result` ### Example ```rust fn open_my_db() -> Result<()> { let path = "./my_db.db3"; let db = Connection::open(path)?; // Use the database somehow... println!("{}", db.is_autocommit()); Ok(()) } ``` ### Flags `Connection::open(path)` is equivalent to using `Connection::open_with_flags` with the default `OpenFlags`. That is, it’s equivalent to: ```rust Connection::open_with_flags( path, OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_CREATE | OpenFlags::SQLITE_OPEN_URI | OpenFlags::SQLITE_OPEN_NO_MUTEX, ) ``` ``` -------------------------------- ### Get Number of Changes Source: https://docs.rs/rusqlite/latest/rusqlite/vtab/struct.ConnectionRef.html Returns the count of rows affected by the most recent INSERT, UPDATE, or DELETE statement executed on the connection. ```rust let changes = conn.changes(); ``` -------------------------------- ### and Source: https://docs.rs/rusqlite/latest/rusqlite/functions/type.SubType.html Returns `None` if the option is `None`, otherwise returns the provided `optb`. Arguments are eagerly evaluated. ```APIDOC ## and ### Description Returns `None` if the option is `None`, otherwise returns `optb`. Arguments passed to `and` are eagerly evaluated. ### Method `and(self, optb: Option) -> Option` ### Parameters - **optb** (Option) - The option to return if `self` is `Some`. ### Request Example ```rust let x = Some(2); let y: Option<&str> = None; assert_eq!(x.and(y), None); let x: Option = None; let y = Some("foo"); assert_eq!(x.and(y), None); let x = Some(2); let y = Some("foo"); assert_eq!(x.and(y), Some("foo")); let x: Option = None; let y: Option<&str> = None; assert_eq!(x.and(y), None); ``` ### Response #### Success Response Returns `Some(optb)` if `self` is `Some`, otherwise returns `None`. #### Response Example (Option) ```