繁体   English   中英

如何使用生锈柴油获得柱的平均值?

[英]How to get average of a column using rust diesel?

我正在尝试使用生锈柴油获取列的平均值,但遇到类型错误。

错误:

the trait bound `f64: FromSql<Numeric, _>` is not satisfied
the following other types implement trait `FromSql<A, DB>`:
  <f32 as FromSql<diesel::sql_types::Float, DB>>
  <f64 as FromSql<Double, DB>>
  <i16 as FromSql<SmallInt, DB>>
  <i32 as FromSql<Integer, DB>>
  <i64 as FromSql<BigInt, DB>>
  <u32 as FromSql<Oid, Pg>>
required because of the requirements on the impl of `diesel::Queryable<Numeric, _>` for `f64`

代码:

   let new_avg: Option<f64> = fruits
                .select(avg(weight))
                .filter(fruit_name.eq(&fruit_name))
                .get_result::<Option<f64>>(&self.postgres.get().unwrap())
                .unwrap();

使用 bigdecimal 类型

经过数小时的调试,我发现柴油返回一种 Bigdecimal 并且您必须为柴油箱启用“数字”功能,我希望这可以记录在案。

新代码:

let new_avg: Option<BigDecimal> = fruits
                .select(avg(weight))
                .filter(fruit_name.eq(&fruit_name))
                .get_result(&self.postgres.get().unwrap())
                .unwrap();

问题似乎是您试图在 Rust 中将类型 Numeric 从 postgres 转换为 f64,它没有实现。

我试图重现你的情况,所以我创建了这样的表:

CREATE TABLE fruits (
    id SERIAL PRIMARY KEY,
    value NUMERIC NOT NULL
)

在模式中为我生成的柴油:

table! {
    fruits (id) {
        id -> Int4,
        value -> Numeric,
    }
}

在模型中我创建了 Fruit:

#[derive(Queryable, Debug)]
pub struct Fruit {
    pub id: i32,
    pub value: f64
}

现在,当我尝试运行它时:

let results = fruits.load::<Fruit>(&pg_connection).expect("");

我遇到了和你一样的错误,我们可以通过几种方式解决。

如果您想在 Rust 中保留 f64 类型,那么您可以在表创建中更改该值应该具有DOUBLE PRECISION类型,在运行柴油迁移后将在模式中生成 Float8 类型,其实现在错误中提到:

= help: the following implementations were found:
    <f64 as FromSql<Double, DB>>

如果你想在 postgres 表中保留类型 Numeric,你可以尝试使用bigecimal::BigDecimaldiesel::pg::data_types::PgNumeric作为 Fruit 结构中的值类型,因为还有将 Numeric 转换为 PgNumeric 的实现。

如果你想保留两者,你可能必须自己实现它

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM