Search code examples
rustrust-sqlx

Why this ORDER BY with push_bind doesn't work?


I'm using the below code but the ORDER BY is not respected, I would like to understand why:

let mut query = QueryBuilder::new("SELECT * FROM player WHERE tenant_id = ");

query.push_bind(tenant_id);

if let Some(order_by) = &input.order_by {
    for order in order_by {
        query.push(" ORDER BY ");

        let ordering: Ordering<String> = order.into();

        match ordering {
            Ordering::Asc(col) => query.push_bind(col).push(" ASC"),
            Ordering::Desc(col) => query.push_bind(col).push(" DESC"),
        };
    }
}

let nodes = query
    .build_query_as::<PgPlayer>()
    .fetch_all(&*self.pool)
    .await?;

dbg!(nodes);

The order of nodes is the same whether direction (ASC/DESC) changes or not.

If I use query.push(col) instead of query.push_bind(col) it works.

Shouldn't I use push_bind()?


Solution

  • The push_bind() method pushes a placeholder (? or $N) and binds a value to it.

    Calling push() appends an SQL fragment to the query. In your case that's exactly what you need. ASC and DESC are keywords and you cannot pass them as variables.