skip to Main Content

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


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

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search