You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求Diesel SQL类型与Rust原生类型映射文档及编译错误解决方法

解决Diesel ORM中f64无法实现diesel::Expression的问题

一、Diesel SQL与Rust类型核心映射

先明确你可能踩的类型匹配误区:

  • 数据库double precision → Diesel schema类型Float8 → Rust类型f64(仅在启用对应feature时支持)
  • 数据库numeric/decimal → Diesel schema类型Numeric → Rust类型BigDecimal(不能用f64,Diesel对f64的Expression支持不覆盖精确数值类型)
  • 数据库money → 需依赖diesel_money crate,对应RustMoney类型或BigDecimal

二、编译错误的具体解决步骤

  1. 修正结构体字段类型
    如果用的是NUMERIC或money列,把结构体中的f64替换为BigDecimal,同时在Cargo.toml添加依赖:

    bigdecimal = "0.4"
    diesel = { version = "2.1", features = ["postgres", "numeric", "float8"] } # 根据你的数据库替换postgres为mysql/sqlite
    

    结构体示例:

    use bigdecimal::BigDecimal;
    use diesel::Queryable;
    
    #[derive(Queryable)]
    #[diesel(table_name = cost_items)]
    struct CostItems {
        price: BigDecimal,
    }
    
  2. 确保查询中类型匹配
    若使用double precision+f64组合,查询时不要直接传递裸f64值,确保Diesel能识别其类型:

    let target_price = 19.99f64;
    let matching_items = cost_items::table
        .filter(cost_items::price.eq(target_price))
        .load::<CostItems>(&db_conn)?;
    

    若仍报错,显式转换类型:

    use diesel::dsl::cast;
    use diesel::sql_types::Float8;
    
    let items = cost_items::table
        .filter(cost_items::price.eq(cast(19.99f64, Float8)))
        .load::<CostItems>(&db_conn)?;
    
  3. 检查Diesel feature启用情况
    确保Cargo.toml中Diesel启用了对应类型的feature:

    • 支持double precision:添加float8 feature
    • 支持numeric:添加numeric feature
    • 支持money:添加money feature(或使用diesel_money crate)

三、类型映射的官方参考逻辑

Diesel的类型映射遵循精确匹配原则:

  • 原生浮点类型仅对应数据库的浮点列(double precision/real),且需启用对应feature
  • 精确数值(如金额、价格)必须用BigDecimal对应numeric列,避免浮点精度丢失,同时Diesel的Expression trait对BigDecimal有完整支持
  • 货币类型需借助第三方扩展,因为不同数据库的money实现差异大

内容的提问来源于stack exchange,提问作者Chester C.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 15:00:21