问题描述
我收到一个插入到 Vec<T>
中的 JSON 数组。我正在使用 serde 进行解析。我想将向量插入到数据库表中。 JSON 数组解析良好。字段 publication_time
带有时区,因此我使用 my_date_format
使用 serde 提供的 example 解析它。当我添加(派生)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
的 this 类似问题,但我的问题是 DateTime<Local>
。我在另一个项目中使用了 chrono::NaiveDateTime
,我也在其中将数据插入到表中。在这个答案中,柴油使用的特定版本有 linked。当我将类型更改为 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,如 here 所述。时间戳使用 NaiveDateTime。这解决了我的问题。