0

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 Answers2

2

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

Ruslan
  • 58
  • 7
1

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.

kmdreko
  • 42,554
  • 6
  • 57
  • 106