如何在Rust的Diesel ORM中定义带自增列的Queryable和Insertable结构体
解决方案
方法1:通过#[diesel(skip_inserting)]跳过自增字段
在id字段上添加#[diesel(skip_inserting)]属性,让Insertable trait生成插入语句时忽略该字段,同时保留Queryable/Selectable对非空id字段的支持:
#[derive(Queryable, Debug, Selectable, Insertable)] #[diesel(table_name = super::schema::users)] pub struct User { #[diesel(skip_inserting)] pub id: i32, pub name: String, }
插入时只需为id填充任意值(比如0),该值会被Diesel自动忽略,数据库将使用自增逻辑生成真实ID:
let new_user = User { id: 0, // 插入时此字段会被跳过 name: "Alice".to_string(), }; diesel::insert_into(schema::users::table) .values(&new_user) .execute(&conn)?;
方法2:插入后获取自动生成的ID
如果需要获取插入成功后的自增ID,可结合returning方法直接返回完整的User结构体:
let inserted_user = diesel::insert_into(schema::users::table) .values(&User { id: 0, name: "Bob".to_string() }) .returning(User::as_select()) .get_result(&conn)?; // inserted_user.id 即为数据库生成的自增ID
关于Option<i32>的问题说明
SQLite中你的id字段是NOT NULL AUTO_INCREMENT,对应Diesel的NotNull<Integer>类型。Option<i32>只能映射到可空的SQL类型,因此无法满足Queryable对非空字段的类型要求,这就是你之前报错的原因。
内容的提问来源于stack exchange,提问作者goose_lake
相关产品推荐
相关产品推荐

