Rust Diesel编译错误:f64未实现AppearsOnTable trait问题解决
解决Diesel ORM中
trait AppearsOnTable编译错误的问题 问题场景
用Rust开发带PostgreSQL 13后端的REST API,采用actix-web构建路由、Diesel作为ORM。编译时出现错误:
trait AppearsOnTable<schema::cost_items::table> is not implement for ‘f64’
数据库表中price字段为numeric类型,查阅文档确认应映射为Rust的f64,尝试改用BigDecimal后仍报类似错误,最终排查出真正原因:数据库中允许为NULL的字段,在Rust结构体中必须用Option<T>包裹。
数据库表结构
CREATE TABLE IF NOT EXISTS public.cost_items ( id bigserial NOT NULL, "name" varchar(64) NOT NULL, price numeric NOT NULL, notes text NULL, CONSTRAINT cost_items_pk PRIMARY KEY (id), CONSTRAINT cost_items_un UNIQUE ("name") );
原错误结构体
这里的问题并非price字段的类型映射,而是notes字段未用Option<String>包裹,导致Diesel无法为结构体生成正确的trait实现,报错信息指向f64属于编译检查的连锁误导:
#[derive(Serialize, Deserialize, AsChangeset, Insertable)] #[diesel(table_name = cost_items)] pub struct CostItem { pub name: String, pub price: f64, pub notes: String, // 错误:数据库中该字段可空,需用Option<String> } #[derive(Serialize, Deserialize, Queryable, Insertable, ToSchema)] #[diesel(table_name = cost_items)] pub struct CostItems { pub id: i64, pub name: String, pub price: f64, pub notes: String, // 错误:数据库中该字段可空,需用Option<String> }
Diesel自动生成的Schema
Schema中明确标记notes为Nullable<Text>,对应Rust类型必须是Option<String>:
diesel::table! { cost_items (id) { id -> Int8, name -> Varchar, price -> Numeric, notes -> Nullable<Text>, } }
修正后的结构体
将notes字段改为Option<String>后,编译错误消失:
#[derive(Serialize, Deserialize, Queryable, Insertable, ToSchema)] #[diesel(table_name = cost_items)] pub struct CostItems { pub id: i64, pub name: String, pub price: f64, pub notes: Option<String>, // 正确:匹配数据库可空字段 }
内容的提问来源于stack exchange,提问作者Chester C.
相关产品推荐
相关产品推荐

