skip to Main Content

I am issuing a raw sql in diesel. Without parameters the code compiles. But when I add parameters to the sql_query using bind the code won’t compile.

pub fn find(session_id: Uuid) -> Result<Vec<Summary>, CustomError> {
    let q = "select product, sum(price) as price from items where session_id = $1 group by product order by product";
    let mut conn = db::connection()?;
    let item = diesel::sql_query(q)
        //.bind::<Uuid, _>(session_id) <-- won't compile
        .get_results(&mut conn)?;
    Ok(item)
}

When I add the line .bind::<Uuid, _>(session_id) cargo build fails with

error[E0277]: the trait bound `uuid::Uuid: ToSql<uuid::Uuid, _>` is not satisfied
    --> src/items/models.rs:52:14
     |
52   |             .get_results(&mut conn)?;
     |              ^^^^^^^^^^^ the trait `ToSql<uuid::Uuid, _>` is not implemented for `uuid::Uuid`
     |
     = help: the following other types implement trait `ToSql<A, DB>`:
               <uuid::Uuid as ToSql<Nullable<diesel::sql_types::Uuid>, __DB>>
               <uuid::Uuid as ToSql<diesel::sql_types::Uuid, Pg>>
     = note: required because of the requirements on the impl of `QueryFragment<_>` for `query_builder::sql_query::UncheckedBind<SqlQuery, uuid::Uuid, uuid::Uuid>`
     = note: required because of the requirements on the impl of `LoadQuery<'_, _, _>` for `query_builder::sql_query::UncheckedBind<SqlQuery, uuid::Uuid, uuid::Uuid>`
note: required by a bound in `get_results`
    --> /Users/claus/.cargo/registry/src/github.com-1ecc6299db9ec823/diesel-2.0.2/src/query_dsl/mod.rs:1695:15
     |
1695 |         Self: LoadQuery<'query, Conn, U>,
     |               ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `get_results`

Cargo.toml:

actix-web = "4.2.1"
actix-rt = "2.7.0"
diesel = { version = "2.0.2", features = ["postgres", "r2d2", "uuid", "chrono", "numeric", "serde_json"] }
serde = { version = "1.0.148", features = ["derive"] }
uuid = { version = "1.2.2", features = ["serde", "v4"] }
bigdecimal = { version = "0.3.0", features = ["serde"] }

The diesel-doc with some bind-examples.

2

Answers


  1. Chosen as BEST ANSWER

    Just after posting I tried changing the Uuid-type in bind to diesel::sql_types::Uuid. And now the code compiles. So posting an answer in case others are having a similar issue.

    .bind::<diesel::sql_types::Uuid, _>(session_id)
    

  2. Had this issue, resolved by using these imports:

    [dependencies]
    postgres = { version = "0.19.4", features = ["with-uuid-1"] }
    uuid = "1.0"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search