gpt4 book ai didi

rust - 如何在 Diesel 中为自定义字段类型实现可查询和可插入?

转载 作者:行者123 更新时间:2023-11-29 08:32:37 28 4
gpt4 key购买 nike

我有一个 SQL 表,我想通过 Diesel 使用它:

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)),
}
}
}

我不知道如何实现InsertableValues 关联类型是什么? 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"

最佳答案

我发现创建实现 ToSqlFromSql 的新型包装器更方便。然后,您可以使用这些基本 block 构建更大的类型,这些类型可以派生 Queryable/Insertable

此示例仅显示如何执行枚举与 SmallInt 之间的映射,但小数的情况是相同的。唯一的区别在于执行转换的方式:

#[macro_use]
extern crate diesel;

mod types {
use diesel::sql_types::*;
use diesel::backend::Backend;
use diesel::deserialize::{self, FromSql};
use diesel::serialize::{self, ToSql, Output};
use std::io;

table! {
records (id) {
id -> BigInt,
record_type -> SmallInt,
}
}

#[derive(Debug, Copy, Clone, AsExpression, FromSqlRow)]
#[sql_type = "SmallInt"]
pub enum RecordType {
A,
B,
}

impl<DB: Backend> ToSql<SmallInt, DB> for RecordType
where
i16: ToSql<SmallInt, DB>,
{
fn to_sql<W>(&self, out: &mut Output<W, DB>) -> serialize::Result
where
W: io::Write,
{
let v = match *self {
RecordType::A => 1,
RecordType::B => 2,
};
v.to_sql(out)
}
}

impl<DB: Backend> FromSql<SmallInt, DB> for RecordType
where
i16: FromSql<SmallInt, DB>,
{
fn from_sql(bytes: Option<&DB::RawValue>) -> deserialize::Result<Self> {
let v = i16::from_sql(bytes)?;
Ok(match v {
1 => RecordType::A,
2 => RecordType::B,
_ => return Err("replace me with a real error".into()),
})
}
}

#[derive(Insertable, Queryable, Debug)]
#[table_name = "records"]
pub struct Record {
pub id: i64,
pub record_type: RecordType,
}
}

有一个 draft guide describing all the derives and their annotations ,但它还没有提到整个类型的 #[sql_type]。这让 Diesel 知道数据库内部需要什么样的底层存储。

另见 the Diesel tests for custom types .

关于rust - 如何在 Diesel 中为自定义字段类型实现可查询和可插入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50838572/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com