将数据解析为 Vec<T> 并将向量插入 postgresql

Parse data into Vec<T> and insert vector into postgresql

我收到一个 JSON 数组,它被插入到 Vec<T> 中。我正在使用 serde 进行解析。我想将向量插入数据库 table。 JSON 数组被解析得很好。 publication_time 字段带有时区,因此我使用 serde 提供的 example 使用 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"

我看到 similar question regarding BigDecimal, but my issue is with DateTime<Local>. I have used chrono::NaiveDateTime in another project where I also insert data to a table. In this answer there is 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 按照 here 所述使用 DateTime。时间戳使用 NaiveDateTime。这解决了我的问题。