【发布时间】:2018-08-12 01:03:57
【问题描述】:
我有一个我想通过 Diesel 使用的 SQL 表:
CREATE TABLE records (
id BIGSERIAL PRIMARY KEY,
record_type SMALLINT NOT NULL,
value DECIMAL(10, 10) NOT NULL
)
此表生成以下架构:
table! {
records (id) {
id -> Int8,
record_type -> Int2,
value -> Numeric,
}
}
Diesel 将小数导出为 bigdecimal::BigDecimal,但我想改用 decimal::d128。我还想将record_type 映射到一个枚举,所以我这样声明我的模型:
use decimal::d128;
pub enum RecordType {
A,
B,
}
pub struct Record {
pub id: i64,
pub record_type: RecordType,
pub value: d128,
}
由于非标准类型映射,我无法使用#derive(Queryable, Insertable),所以我尝试自己实现这些特征:
impl Queryable<records::SqlType, Pg> for Record {
type Row = (i64, i16, BigDecimal);
fn build(row: Self::Row) -> Self {
Record {
id: row.0,
record_type: match row.1 {
1 => RecordType::A,
2 => RecordType::B,
_ => panic!("Wrong record type"),
},
value: d128!(format!("{}", row.2)),
}
}
}
我不知道如何实现Insertable。 Values 关联类型是什么? Diesel 的文档对此不是很清楚。
也许有更好的方法来实现我想要做的事情?
Cargo.toml:
[dependencies]
bigdecimal = "0.0.10"
decimal = "2.0.4"
diesel = { version = "1.1.1", features = ["postgres", "bigdecimal", "num-bigint", "num-integer", "num-traits"] }
dotenv = "0.9.0"
【问题讨论】:
标签: rust rust-diesel