pub trait Params: Sealed { }Expand description
Trait used for sets of parameter passed into SQL statements/queries.
Note: Currently, this trait can only be implemented inside this crate.
Additionally, its methods (which are doc(hidden)) should currently not be
considered part of the stable API, although it’s possible they will
stabilize in the future.
§Passing parameters to DuckDB
Many functions in this library let you pass parameters to DuckDB. Doing this
lets you avoid any risk of SQL injection, and is simpler than escaping
things manually. Aside from deprecated functions and a few helpers, this is
indicated by the function taking a generic argument that implements Params
(this trait).
§Positional parameters
For cases where you want to pass a list of parameters where the number of parameters is known at compile time, this can be done in one of the following ways:
-
Using the
duckdb::params!macro, e.g.thing.query(duckdb::params![1, "foo", bar]). This is mostly useful for heterogeneous lists of parameters, or lists where the number of parameters exceeds 32. -
For small heterogeneous lists of parameters, they can either be passed as:
-
an array, as in
thing.query([1i32, 2, 3, 4])orthing.query(["foo", "bar", "baz"]). -
a reference to an array of references, as in
thing.query(&["foo", "bar", "baz"])orthing.query(&[&1i32, &2, &3]).(Note: in this case we don’t implement this for slices for coherence reasons, so it really is only for the “reference to array” types — hence why the number of parameters must be <= 32 or you need to reach for
duckdb::params!) -
a tuple of mixed types (up to 16 elements), as in
thing.execute((1i32, "foo", 3.14f64)). This is the most ergonomic way to pass heterogeneous parameters.
Unfortunately, in the current design it’s not possible to allow this for references to arrays of non-references (e.g.
&[1i32, 2, 3]). Code like this should instead either useparams!, an array literal, a&[&dyn ToSql]or if none of those work,ParamsFromIter. -
-
As a slice of
ToSqltrait object references, e.g.&[&dyn ToSql]. This is mostly useful for passing parameter lists around as arguments without having every function take a genericP: Params.
§Example (positional)
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(())
}§Named parameters
Named parameters can be passed using duckdb::named_params!
or a manually constructed &[(&str, &dyn ToSql)] for heterogeneous values,
or as any HashMap whose keys borrow as str and whose values implement a
single concrete ToSql type, including maps with custom hashers. The keys
must not include the $ prefix. Named-parameter APIs must be used with
named SQL placeholders such as $name, not positional placeholders such as
? or ?1.
Returns Error::InvalidParameterName
if a SQL placeholder has no matching key, a provided key is not present in
the SQL, slice parameters contain duplicate keys, or positional placeholders
are used with named-parameter APIs.
§Example (named parameters with a HashMap)
use std::collections::HashMap;
use duckdb::{Connection, Result};
fn execute_query(conn: &Connection) -> Result<Vec<String>> {
let params = HashMap::from([("min", 23), ("max", 42)]);
let mut stmt = conn.prepare("SELECT name FROM people WHERE age BETWEEN $min AND $max")?;
let rows = stmt.query_map(¶ms, |row| row.get::<_, String>(0))?;
rows.collect()
}§Example (named parameters with mixed types)
use duckdb::{Connection, Result, named_params};
fn execute_query(conn: &Connection, min_age: i32, name: &str) -> Result<bool> {
conn.query_row(
"SELECT $name = 'Alice' AND $age >= 18",
named_params! {
"name": name,
"age": min_age,
},
|row| row.get(0),
)
}§No parameters
You can use an empty array literal or the empty tuple for no params.
§Example (no parameters)
fn delete_all_users(conn: &Connection) -> Result<()> {
// Empty array:
conn.execute("DELETE FROM users", [])?;
// Or empty tuple:
conn.execute("DELETE FROM users", ())?;
Ok(())
}§Dynamic parameter list
If you have a number of parameters which is unknown at compile time (for example, building a dynamic query at runtime), you have two choices:
- Use a
&[&dyn ToSql], which is nice if you have one otherwise might be annoying. - Use the
ParamsFromItertype. This essentially lets you wrap an iterator someT: ToSqlwith something that implementsParams.
A lot of the considerations here are similar either way, so you should see
the ParamsFromIter documentation for more info / examples.
Dyn Compatibility§
This trait is dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".