QueryBuilder, how to combine push_bind() with separated push_bind() in complex query? #3930
-
| I need to build some query like this in MySQL So I tried something like this with QueryBuilder pub async fn demo_query() -> Result<()> {
    let db = get_db_connection().await?;
    let mut query_builder: QueryBuilder<MySql> = QueryBuilder::new(
        r#"
        SELECT 
            *
        FROM users
        WHERE
            user_status = ?
            AND user_age > ?
            AND role_id IN ("#,
    );
    query_builder.push_bind("active");
    query_builder.push_bind(18);
    let mut separated = query_builder.separated(",");
    [1, 2, 3].iter().for_each(|id| {
        separated.push_bind(id);
    });
    separated.push_unseparated(")");
    let query = query_builder.build();
    log::info!("Query: {}", query.sql());
    let _ = query.fetch_all(db).await?;
    Ok(())
}But the generated query looks weird: SELECT 
            *
        FROM users
        WHERE
            user_status = ?
            AND user_age > ?
            AND role_id IN (???,?,?)Did I do something wrong? | 
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
| It's these calls to  query_builder.push_bind("active");
query_builder.push_bind(18);You push and bind an argument placeholder. That's why there are two extra bind markers ( Not sure why but it looks like the query builder doesn't have a  pub async fn demo_query() -> sqlx::Result<()> {
    let mut arguments = MySqlArguments::default();
    // `add` requires `sqlx::Arguments` to be in scope.
    arguments.add("active").map_err(sqlx::Error::Encode)?;
    arguments.add(18).map_err(sqlx::Error::Encode)?;
    let mut query_builder = QueryBuilder::with_arguments(
        r#"
        SELECT
            *
        FROM users
        WHERE
            user_status = ?
            AND user_age > ?
            AND role_id IN ("#,
        arguments,
    );
    let mut separated = query_builder.separated(",");
    [1, 2, 3].iter().for_each(|id| {
        separated.push_bind(id);
    });
    separated.push_unseparated(")");
    let query = query_builder.build();
    let _ = query.fetch_all(pool).await?;
    Ok(())
} | 
Beta Was this translation helpful? Give feedback.
-
| Thank you. I expected  | 
Beta Was this translation helpful? Give feedback.
It's these calls to
push_bind:You push and bind an argument placeholder. That's why there are two extra bind markers (
??) in the query.Not sure why but it looks like the query builder doesn't have a
bindmethod. Here's a solution I came up with.