Search code examples
postgresqlrustuuidrust-diesel

How to use UUID with diesel::sql_query? I get "the trait bound `uuid::Uuid: ToSql<uuid::Uuid, _>` is not satisfied"


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) it 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`

Here are my dependencies in Cargo.toml:

[dependencies]
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.


Solution

  • 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)