### Begin and Commit a Transaction in Rust Source: https://docs.rs/duckdb/latest/duckdb/struct.Connection.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows how to start a new transaction using `Connection::transaction`. The example illustrates performing multiple queries within the transaction and explicitly committing it. If any part fails, the transaction will be rolled back by default when the `tx` variable is dropped. ```rust fn perform_queries(conn: &mut Connection) -> Result<() as "std::result::Result<(), duckdb::Error>"> { let tx = conn.transaction()?; do_queries_part_1(&tx)?; do_queries_part_2(&tx)?; tx.commit() } ``` -------------------------------- ### Example Searches for Type Conversion Source: https://docs.rs/duckdb/latest/duckdb/vtab/arrow/fn.to_duckdb_logical_type.html?search= These examples illustrate common search patterns for type conversions, such as converting standard library types or handling optional types. ```text std::vec ``` ```text u32 -> bool ``` ```text Option, (T -> U) -> Option ``` -------------------------------- ### Example: Passing Positional Parameters to SQL Statements Source: https://docs.rs/duckdb/latest/duckdb/trait.AppenderParams.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates various ways to pass positional parameters to SQL statements using the `execute` method. Includes examples with `params!`, array literals, and slices of references. ```rust fn update_rows(conn: &Connection) -> Result<()> { let mut stmt = conn.prepare("INSERT INTO test (a, b) VALUES (?, ?)")?; // Using `duckdb::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(()) } ``` -------------------------------- ### Example Search: u32 to bool Conversion Source: https://docs.rs/duckdb/latest/duckdb/constant.MAIN_DB.html?search=u32+-%3E+bool This is an example search query demonstrating a common type conversion pattern in Rust. ```rust u32 -> bool ``` -------------------------------- ### Example: Passing Positional Parameters to DuckDB Source: https://docs.rs/duckdb/latest/duckdb/trait.Params.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates various ways to pass positional parameters to SQL statements using the `execute` method. Includes examples with `duckdb::params!`, array literals (references and non-references), slice literals, and tuples. ```rust fn update_rows(conn: &Connection) -> Result<()> { let mut stmt = conn.prepare("INSERT INTO test (a, b) VALUES (?, ?)")?; // Using `duckdb::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"])?; // Tuple of mixed types: stmt.execute((1i32, "blah"))?; // However, this doesn't work (see above): // stmt.execute(&[1i32, 2i32])?; Ok(()) } ``` -------------------------------- ### Begin an Unchecked Transaction in Rust Source: https://docs.rs/duckdb/latest/duckdb/struct.Connection.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates starting a transaction using `Connection::unchecked_transaction`. This method defers the check for nested transactions until runtime, unlike `Connection::transaction` which checks at compile time. The example shows performing queries and committing the transaction. ```rust fn perform_queries(conn: Rc) -> Result<() as "std::result::Result<(), duckdb::Error>"> { let tx = conn.unchecked_transaction()?; do_queries_part_1(&tx)?; do_queries_part_2(&tx)?; tx.commit() } ``` -------------------------------- ### Example: Get column count Source: https://docs.rs/duckdb/latest/duckdb/struct.CachedStatement.html?search= Demonstrates two ways to get the column count: executing the statement first, or querying rows and then getting the count from the rows. This example requires a `Connection` object and a `Result` type. ```rust fn get_column_count(conn: &Connection) -> Result { let mut stmt = conn.prepare("SELECT id, name FROM people")?; // Option 1: Execute first, then get column count stmt.execute([])?; let count = stmt.column_count(); // Option 2: Get column count from rows (avoids borrowing issues) let mut stmt2 = conn.prepare("SELECT id, name FROM people")?; let rows = stmt2.query([])?; let count2 = rows.as_ref().unwrap().column_count(); Ok(count) } ``` -------------------------------- ### Handling File Metadata with `and_then` Source: https://docs.rs/duckdb/latest/duckdb/type.Result.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Illustrates using `and_then` to chain fallible operations when working with file system metadata. This example shows how to get the modification time of the root directory and handle potential errors like a non-existent path. ```rust use std::{io::ErrorKind, path::Path}; // Note: on Windows "/" maps to "C:\\" let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified()); assert!(root_modified_time.is_ok()); let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified()); assert!(should_fail.is_err()); assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound); ``` -------------------------------- ### Profiling Search Examples Source: https://docs.rs/duckdb/latest/duckdb/profiling/struct.ProfilingInfo.html?search= Examples of how to structure search queries for profiling data. ```APIDOC ## Profiling Search Examples This section provides examples of common search queries used for profiling. ### Example Searches * `std::vec` * `u32 -> bool` * `Option, (T -> U) -> Option` ``` -------------------------------- ### TableFunction Search Examples Source: https://docs.rs/duckdb/latest/duckdb/vtab/struct.TableFunction.html?search= Examples of how to search for table functions. ```APIDOC ## Search Table Functions ### Description Provides examples of search queries for table functions. ### Example Searches * `std::vec` * `u32 -> bool` * `Option, (T -> U) -> Option` ``` -------------------------------- ### Basic usage example Source: https://docs.rs/duckdb/latest/duckdb/struct.AppenderParamsFromIter.html Demonstrates how to use `params_from_iter` with a `BTreeSet` for a dynamic `IN` clause. ```APIDOC ## §Example ### §Basic usage ```rust use duckdb::{Connection, Result, params_from_iter}; 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 (?, ?, ?)")?; let _rows = stmt.query(params_from_iter(ids.iter()))?; // use _rows... Ok(()) } ``` ``` -------------------------------- ### Realistic use case example Source: https://docs.rs/duckdb/latest/duckdb/struct.AppenderParamsFromIter.html Illustrates using `ParamsFromIter` with `Statement::exists` for a dynamic number of parameters. ```APIDOC ### §Realistic use case Here’s how you’d use `ParamsFromIter` to call [`Statement::exists`] with a dynamic number of parameters. ```rust use duckdb::{Connection, Result}; pub fn any_active_users(conn: &Connection, usernames: &[String]) -> Result { if usernames.is_empty() { return Ok(false); } // Note: `repeat_vars` never returns anything attacker-controlled, so // it's fine to use it in a dynamically-built SQL string. let vars = repeat_vars(usernames.len()); let sql = format!( // In practice this would probably be better as an `EXISTS` query. "SELECT 1 FROM user WHERE is_active AND name IN ({}) LIMIT 1", vars, ); let mut stmt = conn.prepare(&sql)?; stmt.exists(duckdb::params_from_iter(usernames)) } // Helper function to return a comma-separated sequence of `?`. // - `repeat_vars(0) => panic!(...) // - `repeat_vars(1) => "?" // - `repeat_vars(2) => "?,"" // - `repeat_vars(3) => "?,?,?" // - ... fn repeat_vars(count: usize) -> String { assert_ne!(count, 0); let mut s = "?,".repeat(count); // Remove trailing comma s.pop(); s } ``` That is fairly complex, and even so would need even more work to be fully production-ready: * production code should ensure `usernames` isn’t so large that it will surpass `conn.limit(Limit::SQLITE_LIMIT_VARIABLE_NUMBER)`), chunking if too large. (Note that the limits api requires duckdb to have the “limits” feature). * `repeat_vars` can be implemented in a way that avoids needing to allocate a String. * Etc… This complexity reflects the fact that `ParamsFromIter` is mainly intended for advanced use cases — most of the time you should know how many parameters you have statically (and if you don’t, you’re either doing something tricky, or should take a moment to think about the design). ``` -------------------------------- ### Example Usage Source: https://docs.rs/duckdb/latest/duckdb/struct.AppenderParamsFromIter.html?search= Demonstrates how to use AppenderParamsFromIter with params_from_iter for dynamic SQL parameter binding. ```APIDOC ## §Example ### §Basic usage ```rust use duckdb::{Connection, Result, params_from_iter}; 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 (?, ?, ?)")?; let _rows = stmt.query(params_from_iter(ids.iter()))?; // use _rows... Ok(()) } ``` ### §Realistic use case Here’s how you’d use `ParamsFromIter` to call [`Statement::exists`] with a dynamic number of parameters. ```rust use duckdb::{Connection, Result}; pub fn any_active_users(conn: &Connection, usernames: &[String]) -> Result { if usernames.is_empty() { return Ok(false); } // Note: `repeat_vars` never returns anything attacker-controlled, so // it's fine to use it in a dynamically-built SQL string. let vars = repeat_vars(usernames.len()); let sql = format!( // In practice this would probably be better as an `EXISTS` query. "SELECT 1 FROM user WHERE is_active AND name IN ({}) LIMIT 1", vars, ); let mut stmt = conn.prepare(&sql)?; stmt.exists(duckdb::params_from_iter(usernames)) } // Helper function to return a comma-separated sequence of `?`. // - `repeat_vars(0) => panic!(...) // - `repeat_vars(1) => "?" // - `repeat_vars(2) => "?,?" // - `repeat_vars(3) => "?,?,?" // - ... fn repeat_vars(count: usize) -> String { assert_ne!(count, 0); let mut s = "?,".repeat(count); // Remove trailing comma s.pop(); s } ``` ``` -------------------------------- ### Basic Usage Example Source: https://docs.rs/duckdb/latest/duckdb/index.html Demonstrates opening an in-memory database, creating a table, inserting data, querying data, and querying data using Arrow RecordBatches. ```APIDOC ## Basic Usage Example This example demonstrates the fundamental operations of the duckdb-rs crate, including database connection, table creation, data manipulation, and querying. ### Code ```rust use duckdb::{params, Connection, Result}; use duckdb::arrow::record_batch::RecordBatch; use duckdb::arrow::util::pretty::print_batches; #[derive(Debug)] struct Person { id: i32, name: String, data: Option>, } fn main() -> Result<()> { let conn = Connection::open_in_memory()?; conn.execute_batch( r"CREATE SEQUENCE seq; CREATE TABLE person ( id INTEGER PRIMARY KEY DEFAULT NEXTVAL('seq'), name TEXT NOT NULL, data BLOB ); ")?; let me = Person { id: 0, name: "Steven".to_string(), data: None, }; conn.execute( "INSERT INTO person (name, data) VALUES (?, ?)", params![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.unwrap()); } // query table by arrow let rbs: Vec = stmt.query_arrow([])?.collect(); print_batches(&rbs); Ok(()) } ``` ``` -------------------------------- ### Get offset and length for a list entry Source: https://docs.rs/duckdb/latest/duckdb/core/struct.ListVector.html?search= Retrieves the offset and length for a given entry index in the list vector. This allows access to the start and size of each list element. ```rust pub fn get_entry(&self, idx: usize) -> (usize, usize) ``` -------------------------------- ### Example: Basic usage Source: https://docs.rs/duckdb/latest/duckdb/struct.AppenderParamsFromIter.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates basic usage of `params_from_iter` with a `BTreeSet` for a prepared statement with a fixed number of parameters. ```APIDOC ## §Example ### §Basic usage ```rust use duckdb::{Connection, Result, params_from_iter}; 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 (?, ?, ?)")?; let _rows = stmt.query(params_from_iter(ids.iter()))?; // use _rows... Ok(()) } ``` ``` -------------------------------- ### Pointable::init Source: https://docs.rs/duckdb/latest/duckdb/struct.Arrow.html?search=std%3A%3Avec Initializes a new instance at a given memory location. ```APIDOC ## unsafe fn init(init: ::Init) -> usize ### Description Initializes a new instance with the given initializer. This function is unsafe as it involves direct memory manipulation. ### Parameters - `init`: The initializer value for the new instance. ### Returns The starting address of the initialized memory as a `usize`. ``` -------------------------------- ### OrderedMap Search Examples Source: https://docs.rs/duckdb/latest/duckdb/types/struct.OrderedMap.html?search= Demonstrates various ways to search for elements within an OrderedMap. ```APIDOC ## Search Examples This section provides examples of how to search within an OrderedMap. ### Example Searches * `std::vec` * `u32 -> bool` * `Option, (T -> U) -> Option` ``` -------------------------------- ### Begin and Commit a Transaction in Rust Source: https://docs.rs/duckdb/latest/duckdb/struct.Connection.html?search=std%3A%3Avec Illustrates how to start a new transaction and ensure its commit. The transaction defaults to rollback on drop, so `commit()` must be explicitly called for persistence. ```rust fn perform_queries(conn: &mut Connection) -> Result<()> { let tx = conn.transaction()?; do_queries_part_1(&tx)?; do_queries_part_2(&tx)?; tx.commit() } ``` -------------------------------- ### Example Search: Option, (T -> U) -> Option Source: https://docs.rs/duckdb/latest/duckdb/constant.MAIN_DB.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Illustrates a common search pattern for function signatures involving Option types and function transformations. ```text Option, (T -> U) -> Option ``` -------------------------------- ### get Source: https://docs.rs/duckdb/latest/duckdb/types/enum.ValueRef.html?search=std%3A%3Avec Gets a reference to the enum key from the given memory location. ```APIDOC ## unsafe fn get<'a>(ptr: *const u8) -> &'a T ### Description Get a reference to the key from the given memory location. ### Method `get` ### Parameters - **ptr** (*const u8): A constant pointer to the memory location. ### Response #### Success Response (&'a T) - **&'a T**: An immutable reference to the key. ``` -------------------------------- ### init Source: https://docs.rs/duckdb/latest/duckdb/struct.Statement.html?search=u32+-%3E+bool Initializes a with the given initializer. ```APIDOC ## init ### Description Initializes a with the given initializer. ### Signature `unsafe fn init(init: ::Init) -> usize` ``` -------------------------------- ### init Source: https://docs.rs/duckdb/latest/duckdb/struct.Polars.html?search=std%3A%3Avec Initializes a with the given initializer. ```APIDOC #### unsafe fn init(init: ::Init) -> usize Initializes a with the given initializer. Read more ``` -------------------------------- ### get Source: https://docs.rs/duckdb/latest/duckdb/types/enum.ValueRef.html Gets a reference to the key from the given memory location. This is an unsafe operation. ```APIDOC ## unsafe fn get<'a>(ptr: *const u8) -> &'a T ### Description Get a reference to the key from the given memory location. ### Method `get` ``` -------------------------------- ### Example: Execute with positional parameters Source: https://docs.rs/duckdb/latest/duckdb/struct.CachedStatement.html?search= Demonstrates executing a prepared statement with positional parameters using the `duckdb::params!` macro or by passing slices or arrays. This is useful for updating or inserting data. ```rust fn update_rows(conn: &Connection) -> Result<()> { let mut stmt = conn.prepare("UPDATE foo SET bar = 'baz' WHERE qux = ?")?; // The `duckdb::params!` macro is mostly useful when the parameters do not // all have the same type, or if there are more than 32 parameters // at once. stmt.execute(params![1i32])?; // However, it's not required, many cases are fine as: stmt.execute(&[&2i32])?; // Or even: stmt.execute([2i32])?; Ok(()) } ``` -------------------------------- ### VScalar Implementation Example Source: https://docs.rs/duckdb/latest/duckdb/vscalar/trait.VScalar.html?search= Example of implementing the VScalar trait for a type T that also implements VArrowScalar. This shows how the State type is derived. ```rust impl VScalar for T where T: VArrowScalar, { type State = ::State ``` -------------------------------- ### unsafe fn get<'a>(ptr: *const u8) -> &'a T Source: https://docs.rs/duckdb/latest/duckdb/enum.ErrorCode.html Gets a reference to the key from the memory location pointed to by `ptr`. This is an unsafe operation. ```APIDOC ## unsafe fn get<'a>(ptr: *const u8) -> &'a T ### Description Get a reference to the key from the given memory location. ### Parameters * **ptr** (*const u8) - A constant pointer to the memory location. ### Returns * &'a T - A reference to the key. ``` -------------------------------- ### init Source: https://docs.rs/duckdb/latest/duckdb/types/enum.ValueRef.html Initializes the key in the given memory location. This is an unsafe operation. ```APIDOC ## unsafe fn init(&self, ptr: *mut u8) ### Description Initialize the key in the given memory location. ### Method `init` ``` -------------------------------- ### Example: Execute without parameters Source: https://docs.rs/duckdb/latest/duckdb/struct.CachedStatement.html?search= Shows how to execute a prepared statement that requires no parameters, such as a DELETE statement affecting all rows. ```rust fn delete_all(conn: &Connection) -> Result<()> { let mut stmt = conn.prepare("DELETE FROM users")?; stmt.execute([])?; Ok(()) } ``` -------------------------------- ### Get Thread-Local Init Data Source: https://docs.rs/duckdb/latest/duckdb/vtab/struct.TableFunctionInfo.html?search= Gets the thread-local init data that was set by `InitInfo::set_init_data` during the `local_init` phase. This returns a raw mutable pointer. ```rust pub fn get_local_init_data(&self) -> *mut T ``` -------------------------------- ### Init Source: https://docs.rs/duckdb/latest/duckdb/struct.Statement.html?search=u32+-%3E+bool The type for initializers. ```APIDOC ## Init ### Description The type for initializers. ### Associated Type `type Init = T` ``` -------------------------------- ### Init Source: https://docs.rs/duckdb/latest/duckdb/struct.Polars.html?search=std%3A%3Avec The type for initializers. ```APIDOC #### type Init = T The type for initializers. ``` -------------------------------- ### Get Bind Data from BindInfo Source: https://docs.rs/duckdb/latest/duckdb/vtab/struct.InitInfo.html Gets the bind data set by `BindInfo::set_bind_data` during the bind. The bind data should be considered read-only; use init data for state tracking. ```rust pub fn get_bind_data(&self) -> *const T ``` -------------------------------- ### ListVector Methods Source: https://docs.rs/duckdb/latest/duckdb/core/struct.ListVector.html?search= Provides methods for interacting with ListVector, including getting its length, checking if it's empty, accessing child vectors, setting and getting entries, and managing nulls and length. ```APIDOC ## ListVector duckdb::core A list vector borrowed from a `DataChunkHandle`. Stores list entry offsets and lengths; elements live in a separate child vector. ### Methods #### `len(&self) -> usize` Returns the number of entries in the list vector. #### `is_empty(&self) -> bool` Returns true if the list vector is empty. #### `child(&self, capacity: usize) -> FlatVector<'a>` Returns the child vector. #### `struct_child(&self, capacity: usize) -> StructVector<'a>` Take the child as StructVector. #### `array_child(&self) -> ArrayVector<'a>` Take the child as ArrayVector. #### `list_child(&self) -> ListVector<'a>` Take the child as ListVector. #### `set_child(&self, data: &[T])` Set primitive data to the child node. #### `set_entry(&mut self, idx: usize, offset: usize, length: usize)` Set offset and length to the entry. #### `get_entry(&self, idx: usize) -> (usize, usize)` Get offset and length for the entry at index. #### `set_null(&mut self, row: usize)` Set row as null #### `set_len(&self, new_len: usize)` Set the length of the list vector. ``` -------------------------------- ### Pointable Init Source: https://docs.rs/duckdb/latest/duckdb/types/enum.ValueRef.html?search= The type for initializers. ```APIDOC ## type Init = T ### Description The type for initializers. ### Method `Init` ``` -------------------------------- ### Basic Usage Example Source: https://docs.rs/duckdb/latest/duckdb/struct.ParamsFromIter.html?search=u32+-%3E+bool Demonstrates a basic usage scenario of `params_from_iter` with a `BTreeSet` to query a database where the number of parameters in the `WHERE` clause is dynamically determined. ```APIDOC ## §Example ### §Basic usage ```rust use duckdb::{Connection, Result, params_from_iter}; 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 (?, ?, ?)")?; let _rows = stmt.query(params_from_iter(ids.iter()))?; // use _rows... Ok(()) } ``` ``` -------------------------------- ### type_id Source: https://docs.rs/duckdb/latest/duckdb/types/enum.ValueRef.html?search=std%3A%3Avec Gets the TypeId of the enum value. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Method `type_id` ### Parameters None ### Response #### Success Response (TypeId) - **TypeId**: The unique identifier for the type. ``` -------------------------------- ### LogicalTypeHandle::id Source: https://docs.rs/duckdb/latest/duckdb/core/struct.LogicalTypeHandle.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets the LogicalTypeId of the handle. ```APIDOC ## LogicalTypeHandle::id ### Description Logical type ID ### Signature `pub fn id(&self) -> LogicalTypeId` ``` -------------------------------- ### Example: Passing Positional Parameters Source: https://docs.rs/duckdb/latest/duckdb/trait.Params.html?search= Demonstrates various ways to pass positional parameters to SQL statements using the `params!` macro, array literals, and tuples. Ensure correct usage based on parameter count and type heterogeneity. ```rust fn update_rows(conn: &Connection) -> Result<()> { let mut stmt = conn.prepare("INSERT INTO test (a, b) VALUES (?, ?)")?; // Using `duckdb::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"])?; // Tuple of mixed types: stmt.execute((1i32, "blah"))?; // However, this doesn't work (see above): // stmt.execute(&[1i32, 2i32])?; Ok(()) } ``` -------------------------------- ### Rows::next Source: https://docs.rs/duckdb/latest/duckdb/struct.Rows.html Attempt to get the next row from the query. Returns `Ok(Some(Row))` if there is another row, `Err(...)` if there was an error getting the next row, and `Ok(None)` if all rows have been retrieved. This method is part of the FallibleStreamingIterator trait. ```APIDOC ## pub fn next(&mut self) -> Result>> ### Description Attempt to get the next row from the query. Returns `Ok(Some(Row))` if there is another row, `Err(...)` if there was an error getting the next row, and `Ok(None)` if all rows have been retrieved. ### Note This interface is not compatible with Rust’s `Iterator` trait, because the lifetime of the returned row is tied to the lifetime of `self`. This is a fallible “streaming iterator”. For a more natural interface, consider using `query_map` or `query_and_then` instead, which return types that implement `Iterator`. ``` -------------------------------- ### Init Source: https://docs.rs/duckdb/latest/duckdb/struct.Row.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Type alias for initializers. ```APIDOC ## type Init = T ### Description The type for initializers. ### Type Alias `Init` ``` -------------------------------- ### size Source: https://docs.rs/duckdb/latest/duckdb/types/enum.ValueRef.html?search=std%3A%3Avec Gets the size of the enum key in bytes. ```APIDOC ## fn size(&self) -> usize ### Description The size of the key in bytes. ### Method `size` ### Parameters None ### Response #### Success Response (usize) - **usize**: The size of the key in bytes. ``` -------------------------------- ### Prepare and Execute SQL Statements Source: https://docs.rs/duckdb/latest/duckdb/struct.Connection.html Prepare a SQL statement once using `prepare` and then execute it multiple times. This is efficient for repeated operations like inserting multiple rows. ```rust fn insert_new_people(conn: &Connection) -> Result<()> { let mut stmt = conn.prepare("INSERT INTO People (name) VALUES (?)")?; stmt.execute(["Joe Smith"])?; stmt.execute(["Bob Jones"])?; Ok(()) } ``` -------------------------------- ### Begin and Commit an Unchecked Transaction Source: https://docs.rs/duckdb/latest/duckdb/struct.Connection.html?search=u32+-%3E+bool Demonstrates starting a transaction that defers runtime checks for nested transactions. This is useful when the compile-time check of `Connection::transaction` is not desired or possible. The transaction rolls back on drop if not committed. ```rust fn perform_queries(conn: Rc) -> Result<() as _> { let tx = conn.unchecked_transaction()?; do_queries_part_1(&tx)?; do_queries_part_2(&tx)?; tx.commit() } ``` -------------------------------- ### align Source: https://docs.rs/duckdb/latest/duckdb/types/enum.ValueRef.html?search=std%3A%3Avec Gets the required alignment for the enum key. ```APIDOC ## fn align() -> usize ### Description The alignment necessary for the key. Must return a power of two. ### Method `align` ### Parameters None ### Response #### Success Response (usize) - **usize**: The alignment value. ``` -------------------------------- ### init Source: https://docs.rs/duckdb/latest/duckdb/struct.Arrow.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initializes a value at a given memory location. ```APIDOC ## unsafe fn init(init: ::Init) -> usize ### Description Initializes a value in memory with the given initializer. This operation is unsafe. ### Parameters - `init`: The initializer value for the type `T`. ### Returns The pointer to the newly initialized value. ``` -------------------------------- ### Type Identification Source: https://docs.rs/duckdb/latest/duckdb/struct.ArrowStream.html Method to get the TypeId of a value. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Method `type_id` ### Response - **TypeId**: The unique identifier for the type of `self`. ``` -------------------------------- ### Basic DuckDB Operations in Rust Source: https://docs.rs/duckdb/latest/duckdb/index.html?search=std%3A%3Avec Demonstrates opening an in-memory database, creating a table, inserting data, querying rows, and retrieving results as Arrow RecordBatches. Ensure you have the necessary dependencies and imports for duckdb and arrow. ```rust use duckdb::{params, Connection, Result}; use duckdb::arrow::record_batch::RecordBatch; use duckdb::arrow::util::pretty::print_batches; #[derive(Debug)] struct Person { id: i32, name: String, data: Option>, } fn main() -> Result<()> { let conn = Connection::open_in_memory()?; conn.execute_batch( r"CREATE SEQUENCE seq; CREATE TABLE person ( id INTEGER PRIMARY KEY DEFAULT NEXTVAL('seq'), name TEXT NOT NULL, data BLOB ); ")?; let me = Person { id: 0, name: "Steven".to_string(), data: None, }; conn.execute( "INSERT INTO person (name, data) VALUES (?, ?)", params![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.unwrap()); } // query table by arrow let rbs: Vec = stmt.query_arrow([])?.collect(); print_batches(&rbs); Ok(()) } ``` -------------------------------- ### DataChunkHandle::num_columns Source: https://docs.rs/duckdb/latest/duckdb/core/struct.DataChunkHandle.html?search=u32+-%3E+bool Gets the number of columns in the DataChunkHandle. ```APIDOC ## DataChunkHandle::num_columns ### Description Get the number of columns in this DataChunkHandle. ### Signature `pub fn num_columns(&self) -> usize` ``` -------------------------------- ### Get Version Source: https://docs.rs/duckdb/latest/duckdb/struct.Connection.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Retrieves the version string of the DuckDB library. ```APIDOC ## pub fn version(&self) -> Result ### Description Returns the version of the DuckDB library ``` -------------------------------- ### impl Any for T Source: https://docs.rs/duckdb/latest/duckdb/struct.ArrowStream.html?search=std%3A%3Avec Provides the `type_id` method to get the `TypeId` of `self`. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Returns - **TypeId**: The unique identifier for the type of `self`. ``` -------------------------------- ### InitInfo Methods Source: https://docs.rs/duckdb/latest/duckdb/vtab/struct.InitInfo.html?search=u32+-%3E+bool This section details the methods available on the InitInfo struct for managing initialization data and configuration. ```APIDOC ## InitInfo An interface to store and retrieve data during the function init stage. ### Methods #### `set_init_data(&self, data: *mut c_void, freeer: Option)` Sets initialization data and a corresponding freeer function. #### `get_column_indices(&self) -> Vec` Returns the column indices of the projected columns at the specified positions. This function must be used if projection pushdown is enabled to figure out which columns to emit. * **Returns**: The column indices at which to get the projected column index. #### `get_extra_info(&self) -> *const T` Retrieves the extra info of the function as set in `TableFunction::set_extra_info`. #### `get_bind_data(&self) -> *const T` Gets the bind data set by `BindInfo::set_bind_data` during the bind. Note that the bind data should be considered as read-only. For tracking state, use the init data instead. * **Returns**: The bind data object. #### `set_max_threads(&self, max_threads: idx_t)` Sets how many threads can process this table function in parallel (default: 1). * **Arguments**: * `max_threads`: The maximum amount of threads that can process this table function. #### `set_error(&self, error: &str)` Report that an error has occurred while calling init. * **Arguments**: * `error`: The error message. ``` -------------------------------- ### from Source: https://docs.rs/duckdb/latest/duckdb/types/enum.ValueRef.html?search=std%3A%3Avec Creates a new instance from a given value. ```APIDOC ## fn from(t: T) -> T ### Description Returns the argument unchanged. ### Method `from` ### Parameters - **t** (T): The value to create the instance from. ### Response #### Success Response (T) - **T**: The newly created instance. ``` -------------------------------- ### deref_mut Source: https://docs.rs/duckdb/latest/duckdb/struct.Arrow.html?search=u32+-%3E+bool Dereferences a pointer to get a mutable reference to the value. ```APIDOC ## unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T ### Description Mutably dereferences the given pointer (`ptr`) to obtain a mutable reference (`&'a mut T`) to the value it points to. ### Parameters - `ptr`: A `usize` representing the pointer to the value. ### Returns - `&'a mut T`: A mutable reference to the value. ### Safety This function is unsafe. The caller must ensure that `ptr` is a valid pointer to a value of type `T` that lives for at least `'a`, and that no other references to the value exist. ``` -------------------------------- ### deref Source: https://docs.rs/duckdb/latest/duckdb/struct.Arrow.html?search=u32+-%3E+bool Dereferences a pointer to get an immutable reference to the value. ```APIDOC ## unsafe fn deref<'a>(ptr: usize) -> &'a T ### Description Dereferences the given pointer (`ptr`) to obtain an immutable reference (`&'a T`) to the value it points to. ### Parameters - `ptr`: A `usize` representing the pointer to the value. ### Returns - `&'a T`: An immutable reference to the value. ### Safety This function is unsafe. The caller must ensure that `ptr` is a valid pointer to a value of type `T` that lives for at least `'a`. ``` -------------------------------- ### deref_mut Source: https://docs.rs/duckdb/latest/duckdb/struct.Arrow.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Dereferences a raw pointer to get a mutable reference. ```APIDOC ## unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T ### Description Dereferences the given raw pointer to obtain a mutable reference to the value. This operation is unsafe. ### Parameters - `ptr`: The raw pointer (as a `usize`) to dereference. ### Returns A mutable reference `&'a mut T` to the value at the pointer. ``` -------------------------------- ### Begin Transaction Source: https://docs.rs/duckdb/latest/duckdb/struct.Connection.html Starts a new deferred transaction. By default, transactions roll back when dropped. Call `commit` or set `DropBehavior::Commit` to persist changes. ```rust fn perform_queries(conn: &mut Connection) -> Result<()> { let tx = conn.transaction()?; do_queries_part_1(&tx)?; do_queries_part_2(&tx)?; tx.commit() } ``` -------------------------------- ### deref Source: https://docs.rs/duckdb/latest/duckdb/struct.Arrow.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Dereferences a raw pointer to get an immutable reference. ```APIDOC ## unsafe fn deref<'a>(ptr: usize) -> &'a T ### Description Dereferences the given raw pointer to obtain an immutable reference to the value. This operation is unsafe. ### Parameters - `ptr`: The raw pointer (as a `usize`) to dereference. ### Returns An immutable reference `&'a T` to the value at the pointer. ``` -------------------------------- ### Basic DuckDB Operations in Rust Source: https://docs.rs/duckdb/latest/duckdb/index.html Demonstrates opening an in-memory database, creating a table, inserting data, querying rows, and querying data as Arrow RecordBatches. Requires the 'arrow' feature flag. ```rust use duckdb::{params, Connection, Result}; use duckdb::arrow::record_batch::RecordBatch; use duckdb::arrow::util::pretty::print_batches; #[derive(Debug)] struct Person { id: i32, name: String, data: Option>, } fn main() -> Result<()> { let conn = Connection::open_in_memory()?; conn.execute_batch( r"CREATE SEQUENCE seq; CREATE TABLE person ( id INTEGER PRIMARY KEY DEFAULT NEXTVAL('seq'), name TEXT NOT NULL, data BLOB ); ")?; let me = Person { id: 0, name: "Steven".to_string(), data: None, }; conn.execute( "INSERT INTO person (name, data) VALUES (?, ?)", params![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.unwrap()); } // query table by arrow let rbs: Vec = stmt.query_arrow([])?.collect(); print_batches(&rbs); Ok(()) } ``` -------------------------------- ### Low-Level Parameter Binding and Query Execution Source: https://docs.rs/duckdb/latest/duckdb/struct.CachedStatement.html?search=u32+-%3E+bool Demonstrates the low-level API for binding parameters individually and then executing a query. Use this for advanced scenarios like gaps in parameters or mixed parameter types. ```rust fn query(conn: &Connection) -> Result<()> { let mut stmt = conn.prepare("SELECT * FROM test WHERE name = ? AND value > ?2")?; stmt.raw_bind_parameter(1, "foo")?; stmt.raw_bind_parameter(2, 100)?; let mut rows = stmt.raw_query(); while let Some(row) = rows.next()? { // ... } Ok(()) } ``` -------------------------------- ### fn type_id(&self) -> TypeId Source: https://docs.rs/duckdb/latest/duckdb/struct.Arrow.html?search= Gets the TypeId of self. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Returns - TypeId: The unique identifier for the type of `self`. ``` -------------------------------- ### init Source: https://docs.rs/duckdb/latest/duckdb/types/enum.ValueRef.html?search=std%3A%3Avec Initializes the enum key in the given memory location. ```APIDOC ## unsafe fn init(&self, ptr: *mut u8) ### Description Initialize the key in the given memory location. ### Method `init` ### Parameters - **ptr** (*mut u8): A mutable pointer to the memory location to initialize. ### Response None ``` -------------------------------- ### LogicalTypeHandle::child Source: https://docs.rs/duckdb/latest/duckdb/core/struct.LogicalTypeHandle.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets a child logical type by its index. ```APIDOC ## LogicalTypeHandle::child ### Description Logical type child by idx ### Signature `pub fn child(&self, idx: usize) -> Self` ``` -------------------------------- ### Example: Realistic use case Source: https://docs.rs/duckdb/latest/duckdb/struct.AppenderParamsFromIter.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Illustrates a more realistic use case for `AppenderParamsFromIter` with dynamically generated SQL, using `Statement::exists` and a dynamic number of parameters. ```APIDOC ## §Realistic use case Here’s how you’d use `ParamsFromIter` to call [`Statement::exists`] with a dynamic number of parameters. ```rust use duckdb::{Connection, Result}; pub fn any_active_users(conn: &Connection, usernames: &[String]) -> Result { if usernames.is_empty() { return Ok(false); } // Note: `repeat_vars` never returns anything attacker-controlled, so // it's fine to use it in a dynamically-built SQL string. let vars = repeat_vars(usernames.len()); let sql = format!( // In practice this would probably be better as an `EXISTS` query. "SELECT 1 FROM user WHERE is_active AND name IN ({}) LIMIT 1", vars, ); let mut stmt = conn.prepare(&sql)?; stmt.exists(duckdb::params_from_iter(usernames)) } // Helper function to return a comma-separated sequence of `?`. // - `repeat_vars(0) => panic!(...) // - `repeat_vars(1) => "?" // - `repeat_vars(2) => "?,"" // - `repeat_vars(3) => "?,?,?" // - ... fn repeat_vars(count: usize) -> String { assert_ne!(count, 0); let mut s = "?,".repeat(count); // Remove trailing comma s.pop(); s } ``` That is fairly complex, and even so would need even more work to be fully production-ready: * production code should ensure `usernames` isn’t so large that it will surpass `conn.limit(Limit::SQLITE_LIMIT_VARIABLE_NUMBER)`), chunking if too large. (Note that the limits api requires duckdb to have the “limits” feature). * `repeat_vars` can be implemented in a way that avoids needing to allocate a String. * Etc… This complexity reflects the fact that `ParamsFromIter` is mainly intended for advanced use cases — most of the time you should know how many parameters you have statically (and if you don’t, you’re either doing something tricky, or should take a moment to think about the design). ``` -------------------------------- ### LogicalTypeHandle::num_children Source: https://docs.rs/duckdb/latest/duckdb/core/struct.LogicalTypeHandle.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets the number of children for the logical type. ```APIDOC ## LogicalTypeHandle::num_children ### Description Logical type children num ### Signature `pub fn num_children(&self) -> usize` ``` -------------------------------- ### InitInfo Methods Source: https://docs.rs/duckdb/latest/duckdb/vtab/struct.InitInfo.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E This section details the public methods available on the InitInfo struct for interacting with initialization data and settings. ```APIDOC ## InitInfo An interface to store and retrieve data during the function init stage. ### Methods #### `set_init_data(&self, data: *mut c_void, freeer: Option)` Sets initialization data and a corresponding freeer function. #### `get_column_indices(&self) -> Vec` Returns the column indices of the projected columns at the specified positions. This function must be used if projection pushdown is enabled to figure out which columns to emit. Returns: The column indices at which to get the projected column index. #### `get_extra_info(&self) -> *const T` Retrieves the extra info of the function as set in `TableFunction::set_extra_info`. #### `get_bind_data(&self) -> *const T` Gets the bind data set by `BindInfo::set_bind_data` during the bind. Note that the bind data should be considered as read-only. For tracking state, use the init data instead. Arguments: * `returns`: The bind data object. #### `set_max_threads(&self, max_threads: idx_t)` Sets how many threads can process this table function in parallel (default: 1). Arguments: * `max_threads`: The maximum amount of threads that can process this table function. #### `set_error(&self, error: &str)` Report that an error has occurred while calling init. Arguments: * `error`: The error message. ``` -------------------------------- ### LogicalTypeHandle::try_id Source: https://docs.rs/duckdb/latest/duckdb/core/struct.LogicalTypeHandle.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Attempts to get the LogicalTypeId, with forward-compatibility awareness. ```APIDOC ## LogicalTypeHandle::try_id ### Description Logical type ID, with forward-compatibility awareness. Returns `Ok(LogicalTypeId)` for all known ids (including `Invalid`), and `Err(raw_id)` when DuckDB returns an id this wrapper does not yet recognize. ### Signature `pub fn try_id(&self) -> Result` ``` -------------------------------- ### Pointable::init Source: https://docs.rs/duckdb/latest/duckdb/struct.AndThenRows.html?search=u32+-%3E+bool Initializes a value in memory at a given alignment. ```APIDOC ## unsafe fn init(init: ::Init) -> usize ### Description Initializes a value of type `T` using the provided initializer and returns the memory address where it was placed. This is an unsafe operation. ### Parameters - `init`: The initializer value for type `T`. ### Returns The memory address (as `usize`) of the initialized value. ``` -------------------------------- ### Get FlatVector Capacity Source: https://docs.rs/duckdb/latest/duckdb/core/struct.FlatVector.html Returns the total capacity of the FlatVector. ```rust pub fn capacity(&self) -> usize ``` -------------------------------- ### DataChunkHandle::get_ptr Source: https://docs.rs/duckdb/latest/duckdb/core/struct.DataChunkHandle.html Gets the raw pointer to the underlying duckdb_data_chunk. ```APIDOC ## DataChunkHandle::get_ptr ### Description Get the ptr of duckdb_data_chunk in this DataChunkHandle. ### Signature ```rust pub fn get_ptr(&self) -> duckdb_data_chunk ``` ``` -------------------------------- ### Realistic Use Case Example Source: https://docs.rs/duckdb/latest/duckdb/struct.ParamsFromIter.html?search=u32+-%3E+bool Illustrates a more realistic use case for `ParamsFromIter` in the `any_active_users` function, which checks for active users by name using a dynamically generated SQL query with a variable number of parameters. ```APIDOC ## §Realistic use case Here’s how you’d use `ParamsFromIter` to call `Statement::exists` with a dynamic number of parameters. ```rust use duckdb::{Connection, Result}; pub fn any_active_users(conn: &Connection, usernames: &[String]) -> Result { if usernames.is_empty() { return Ok(false); } // Note: `repeat_vars` never returns anything attacker-controlled, so // it's fine to use it in a dynamically-built SQL string. let vars = repeat_vars(usernames.len()); let sql = format!( // In practice this would probably be better as an `EXISTS` query. "SELECT 1 FROM user WHERE is_active AND name IN ({}) LIMIT 1", vars, ); let mut stmt = conn.prepare(&sql)?; stmt.exists(duckdb::params_from_iter(usernames)) } // Helper function to return a comma-separated sequence of `?`. // - `repeat_vars(0) => panic!(...) // - `repeat_vars(1) => "?" // - `repeat_vars(2) => "?,"" // - `repeat_vars(3) => "?,?,?" // - ... fn repeat_vars(count: usize) -> String { assert_ne!(count, 0); let mut s = "?,".repeat(count); // Remove trailing comma s.pop(); s } ``` That is fairly complex, and even so would need even more work to be fully production-ready: * production code should ensure `usernames` isn’t so large that it will surpass `conn.limit(Limit::SQLITE_LIMIT_VARIABLE_NUMBER)`), chunking if too large. (Note that the limits api requires duckdb to have the “limits” feature). * `repeat_vars` can be implemented in a way that avoids needing to allocate a String. * Etc… This complexity reflects the fact that `ParamsFromIter` is mainly intended for advanced use cases — most of the time you should know how many parameters you have statically (and if you don’t, you’re either doing something tricky, or should take a moment to think about the design). ```