Skip to content

Allow binding list of options in query! macro #1938

@frxstrem

Description

@frxstrem

I'm using sqlx 0.6.0 against a Postgres database.

If I try to bind to a Vec<Option<_>>, then the query! macro fails to compile:

let inputs: Vec<Option<i32>> = vec![Some(1), Some(2), None];

sqlx::query!(
        r#"
            SELECT * FROM UNNEST($1::int[])
        "#,
// error[E0308]: mismatched types
        &inputs,
//      ^
//      |
//      expected slice `[i32]`, found struct `Vec`
//      expected due to the type of this binding
//
// = note: expected reference `&[i32]`
//            found reference `&Vec<Option<i32>>`
);

If I instead use a Vec<_>, the code compiles without any issue.

If I instead use the sqlx::query function, the code compiles and runs without issue, however this obviously comes with the downside of no compile-time query validation:

let inputs: Vec<Option<i32>> = vec![Some(1), Some(2), None];

let results = sqlx::query(
        r#"
            SELECT * FROM UNNEST($1::int[])
        "#,
    )
    .bind(&inputs)
    .fetch_all(&pool)
    .await?
    .into_iter()
    .map(|row| row.try_get::<Option<i32>, _>(0))
    .collect::<Result<Vec<_>, _>>()?;

println!("{results:?"); // [Some(1), Some(2), None]

Would it be possible to fix this so that the query! macro can also accept vectors of options?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions