Passing None into tokio postgres sql client query method

533 Views Asked by At

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

There are 2 best solutions below

0
Ruslan On BEST ANSWER

You work with raw queries, tokio_postgres couldn't to manage None. In my experience best solution will write your own query builder.

0
kmdreko On

You do not need to .unwrap() at all and can pass &input2 as-is. Option<T> implements ToSql where T: ToSql, if the value is None then it will pass NULL to the database:

let rows = client.query(
    "SELECT * FROM Table WHERE Name=$1 AND Address=COALESCE($2, Address)",
    &[&input1, &input2],
).await?;

Full working code that I tested on my local database is available here.