rust - 为自定义类型实现 AsExpression 和 FromSqlRow
问题描述
我在用:
diesel = { version = "1.3.0", features = ["postgres", "chrono"] }
该结构Payment
包含一个自定义类型CentAmount
。为了使包含结构可插入,我实现了
AsExpression
FromSqlRow
如简化自定义类型的支持中所述:
use diesel::expression::AsExpression;
use diesel::helper_types::AsExprOf;
use diesel::pg::Pg;
use diesel::row::Row;
use diesel::sql_types::{Integer, Nullable};
use diesel::types::FromSqlRow;
use std::error::Error;
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone, Copy)]
pub struct CentAmount {
cents: i32,
}
impl CentAmount {
pub fn new(cents: i32) -> Self {
assert!(cents >= 0);
CentAmount { cents: cents }
}
}
impl<'a> AsExpression<Nullable<Integer>> for &'a CentAmount {
type Expression = AsExprOf<i32, Nullable<Integer>>;
fn as_expression(self) -> Self::Expression {
AsExpression::<Nullable<Integer>>::as_expression(self.cents)
}
}
impl FromSqlRow<Integer, Pg> for CentAmount {
fn build_from_row<R: Row<Pg>>(row: &mut R) -> Result<Self, Box<Error + Send + Sync>> {
let cents = i32::build_from_row(row)?;
Ok(CentAmount { cents })
}
}
结构体在这里使用
#[derive(Queryable, Debug, Getters, Serialize, Deserialize, PartialEq, Insertable)]
#[table_name = "payments"]
pub struct Payment {
pub id: Option<i32>,
amount: CentAmount,
leistung_id: i32,
beschaeftiger_id: i32,
payment_state: PaymentState,
approval_date: Option<DateTime<Local>>,
}
我仍然收到错误:
the trait `diesel::Expression` is not implemented for `model::cent_amount::CentAmount`
我错过了什么?
解决方案
推荐阅读
- reactjs - ReactJS - 通过默认道具和状态生成唯一ID之间的区别
- r - select/filter rows with R: identify values with the same variable or attribute a code to different consecutive cycles
- python - JSON的嵌套序列化
- sql - Postgres:从csv同时在两个表中插入值
- python - 使用文本数据和其他预测变量构建预测模型
- c# - Remove the selected item in a ListView from a SQL database
- javascript - How to use Vueitfy combo box in a v-for loop
- android - 如何在osmdroid的mapview上将jpg文件叠加为位图文件
- django - 表单提交后Django初始化值更改
- python - Tensorflow 2 摘要与渴望禁用