I am using tokio postgres in a Rust project where I have query parameters.
rows = client.query(QUERY, &[&input1, &input2.unwrap()]).await.expect("error");
where QUERY looks like this
QUERY: &str = "SELECT * FROM Table WHERE Name=$1 AND Address= COALESCE($2, Address);"
input2
is of type Rust option for which I will have to unwrap input2 before inserting it into the query method. Is there a way to make the query method handle "None" directly.
I can write conditional statements outside but that will make the source code unmanageable for the case where I have multiple optional queries.
2
Answers
You work with raw queries, tokio_postgres couldn’t to manage
None
. In my experience best solution will write your own query builder.You do not need to
.unwrap()
at all and can pass&input2
as-is.Option<T>
implementsToSql
whereT: ToSql
, if the value isNone
then it will passNULL
to the database:Full working code that I tested on my local database is available here.