【问题标题】:Rust diesel facing error when trying to get total count from table尝试从表中获取总数时,Rust 柴油面临错误
【发布时间】:2022-01-07 21:57:18
【问题描述】:

我正在使用 rust diesel 实现一个数据库。我想使用带有filter 条件的查询来获取表中存在的总计数或总列数。下面是我的表结构和查询代码。我的表结构中没有使用任何BIGINT, big 小数。

trait bound i32: FromSql<BigInt, Pg> 不满足 找到了以下实现: > 需要,因为对 diesel::Queryable<BigInt, Pg> 的 impl 的要求 i32 因为对LoadQuery<PooledConnection<ConnectionManager<PgConnection>>, i32> 的实现有要求,所以需要

#Emplyee table

| employee-id  | employee_name | empolyee_email|       
| -----------  | --------------|-------------  |
| 1            | ABC           |abc@mail.com   |
| 2            | xyz           |xyz@mail.com   |


# Account table

| account  | employee-id    | account-balnce | created_at|
| -------- | ----------     |--------------- |-----------|
| 1        | 1              |   2000         | 22/10/2021|
| 2        | 2              |   5000         | 01/09/2021|

fn get_total_accounts(&self, employee_id: &str) -> anyhow::Result<Option<i32>> {
        let res: i32 = employee::table
            .inner_join(account::table)
            .filter(employee::dsl::employee_id.eq(employee_id))
            .count()
            .get_result(&self.pool.get()?)?;  //get_result through error
               
 }

【问题讨论】:

  • 根据其documentationget_result函数返回一个QueryResult&lt;U&gt;,不能直接赋值给i32的变量。我认为这就是原因。
  • 正如错误所说,查询将返回一个BigInt,它无法转换为i32 (i32: FromSql&lt;BigInt, Pg&gt; not satisfied)。您需要使用u64 而不是i32。该查询将返回BigInt,因为您正在执行.count() 查询,该查询将返回匹配的行数,这可能是一个很大的数字,而不管是否在任何表中使用了类似BigInt 的类型。
  • u64 也同样的错误the trait bound u64: FromSql` is not compatible because of the impl of diesel::Queryable&lt;BigInt, Pg&gt; for u64 required 因为对LoadQuery&lt;PooledConnection&lt;ConnectionManager&lt;PgConnection&gt;&gt;, u64&gt; 的 `
  • 使用 I64 解决了我的问题。

标签: rust rust-diesel


【解决方案1】:

使用 I64 解决了我的问题。

fn get_total_accounts(&self, employee_id: &str) -> anyhow::Result<Option<i32>> {
        let res: i64 = employee::table
            .inner_join(account::table)
            .filter(employee::dsl::employee_id.eq(employee_id))
            .count()
            .get_result(&self.pool.get()?)?;  //get_result through error
               
 }

【讨论】:

    猜你喜欢
    • 2020-10-23
    • 2021-07-25
    • 2022-01-19
    • 2021-09-26
    • 2021-03-10
    • 2022-01-03
    • 1970-01-01
    • 2013-04-12
    • 1970-01-01
    相关资源
    最近更新 更多