SQL Where-in clause with tokio-postgres

2020-10-22

I spent nearly an hour searching for this information, so I thought I'd share. Suppose you have a SQL query like the following:

SELECT username, full_name FROM users
WHERE username IN ($1)

And you try to access it with some rust code, like so:

let users = vec!["mary", "bob"];
let rows = pg_client.query(
    r#"SELECT username, full_name FROM users WHERE username IN ($1)"#,
    &[&users]
).await.expect("failed to query users");

If you were to prepare this query with tokio-postgres you would find that passing in a vector does not work as expected. Vectors can be serialized, but they can't be serialized into that particular format. Instead, you need to re-write your query to use the ANY keyword. Like so:

SELECT username, full_name FROM users
WHERE username = ANY($1)

Doing so will allow tokio-postgres to properly parameterize your vector. Hopefully this helps someone find the answer more readily :)