sfackler / rust-postgres

Native PostgreSQL driver for the Rust programming language
Apache License 2.0
3.43k stars 436 forks source link

Question: How do I create a Vec so that I can dynamically add params to pass into the query method? #1049

Closed spencerbart closed 1 year ago

spencerbart commented 1 year ago

This is the vector that I initialize.

let mut pg_args: Vec<Box<dyn ToSql + Sync>> = Vec::new();

I then add params dynamically to the vector at runtime (it's a weird use case where I don't know how many or what params are being passed in).

I then create a slice and then pass it into the query method.

let params_slice: Vec<&(dyn ToSql + Sync)> = pg_args.iter().map(|b| &**b).collect();
let value = conn
        .query(&statement.to_string(), &params_slice[..])
        .await?;

This would work but I am using it in Axum and this is the error that comes up.

future is not `Send` as this value is used across an await

I try to add Send but that doesn't work because of query's signature

pub async fn query<T>(&self, statement: &T, params: &[&dyn ToSql + Sync]) -> Result<Vec<Row>, Error>
where
    T: ?Sized + ToStatement,

How do I go about creating a vector that can be dynamically allocated to and passed into query?

sfackler commented 1 year ago

One option is to use query_raw instead of query: https://docs.rs/tokio-postgres/latest/tokio_postgres/struct.Client.html#method.query_raw

decapo01 commented 11 months ago

@spencerbart Can you show how you are calling it in an Axum handler? I just tried something like this in an Actix handler and am not getting any errors.