我收到一个插入到Vec<T>
中的JSON数组。我正在使用serde进行解析。我想把矢量插入数据库表中。JSON数组解析良好。字段publication_time
带有时区,因此我使用serde提供的示例使用my_date_format
对其进行解析。当我将Insertable
添加(派生(到结构体cargo build
时,失败
error[E0277]: the trait bound `DateTime<Local>: diesel::Expression` is not satisfied
--> src/models.rs:5:23
|
5 | #[derive(Deserialize, Insertable)]
| ^^^^^^^^^^ the trait `diesel::Expression` is not implemented for `DateTime<Local>`
|
= note: required because of the requirements on the impl of `AsExpression<diesel::sql_types::Nullable<diesel::sql_types::Timestamp>>` for `DateTime<Local>`
= note: this error originates in a derive macro (in Nightly builds, run with -Z macro-backtrace for more info)
models.rs:
use serde::{Deserialize};
use chrono::{DateTime, Local};
use crate::schema::readings;
#[derive(Deserialize, Insertable)]
struct Reading {
#[serde(with = "my_date_format")]
publication_time: DateTime<Local>,
id: i32,
index: i32,
field_description: String,
measurement: f32,
}
schema.rs:
table! {
readings {
measurement_time_default -> Nullable<Timestamp>,
id -> Nullable<Integer>,
index -> Nullable<Integer>,
field_description -> Nullable<Text>,
measurement -> Nullable<Float>,
}
}
Cargo.toml:
serde = "1"
serde_json = "1"
serde-datetime = "0.1.0"
diesel = { version = "1.4.4", features = ["postgres", "chrono"] }
chrono = "0.4.19"
我看到了关于BigDecimal
的类似问题,但我的问题是关于DateTime<Local>
的。我在另一个项目中使用了chrono::NaiveDateTime
,在该项目中我还将数据插入到表中。在这个答案中,有链接到柴油机使用的特定版本。当我将类型更改为NaiveDateTime
时,serde无法编译,并出现以下错误:
error[E0308]: mismatched types
--> src/models.rs:5:10
|
5 | #[derive(Deserialize, Insertable)]
| ^^^^^^^^^^^ expected struct `NaiveDateTime`, found struct `DateTime`
|
= note: expected struct `NaiveDateTime`
found struct `DateTime<Local>`
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
weiznich对schema.rs的评论为我指明了正确的方向。我将Timestamp更改为Timestamptz。
schema.rs:
table! {
readings {
measurement_time_default -> Nullable<Timestamptz>,
id -> Nullable<Integer>,
index -> Nullable<Integer>,
field_description -> Nullable<Text>,
measurement -> Nullable<Float>,
}
}
Timestamptz使用DateTime,如下所述。时间戳使用NaiveDateTime。这解决了我的问题。