如何将UUID与diesel::sql_query一起使用?我得到“特征绑定 `uuid::Uuid: ToSql<uuid::Uuid, _>` 不满足”

问题描述 投票:0回答:2

我正在 Diesel 中发出原始 SQL。没有参数,代码可以编译。但是,当我使用

sql_query
将参数添加到
.bind()
时,代码将无法编译。

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

当我添加行

.bind::<Uuid, _>(session_id)
时,它失败了:

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 中的依赖项:

[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"] }

带有一些绑定示例的 diesel-doc

postgresql rust uuid rust-diesel
2个回答
1
投票

发布后,我尝试将绑定中的 Uuid 类型更改为

diesel::sql_types::Uuid
。现在代码可以编译了。因此,如果其他人遇到类似问题,请发布答案。

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

1
投票

遇到此问题,通过使用这些导入解决:

[dependencies]
postgres = { version = "0.19.4", features = ["with-uuid-1"] }
uuid = "1.0"
© www.soinside.com 2019 - 2024. All rights reserved.