I have an SQL table that I want to work with through Diesel:
CREATE TABLE records (
id BIGSERIAL PRIMARY KEY,
record_type SMALLINT NOT NULL,
value DECIMAL(10, 10) NOT NULL
)
This table generates the following schema:
table! {
records (id) {
id -> Int8,
record_type -> Int2,
value -> Numeric,
}
}
Diesel exports decimals as bigdecimal::BigDecimal
, but I'd like to work with decimal::d128
instead. I also want to map record_type
to an enum, so I declare my model like this:
use decimal::d128;
pub enum RecordType {
A,
B,
}
pub struct Record {
pub id: i64,
pub record_type: RecordType,
pub value: d128,
}
I can't use #derive(Queryable, Insertable)
because of non-standard type mapping, so I try to implement these traits myself:
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)),
}
}
}
I can't figure out how to implement Insertable
. What is the Values
associated type? Diesel's documentation is not very clear on this.
Maybe there's a better way to achieve what I'm trying to do?
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"
See Question&Answers more detail:
os