Rust tokio_postgres 行到对象的映射失败,时间戳列为 serde_postgres

Rust tokio_postgres row to object mapping fails with serde_postgres for timestamp column

我有 rust actix-web rest 项目,它使用 tokio_postgres 和 serde_postgres。

Table

acme=# \d job
                                             Table "public.job"
     Column      |            Type             | Collation | Nullable |               Default               
-----------------+-----------------------------+-----------+----------+-------------------------------------
 created_at      | timestamp without time zone |           | not null | CURRENT_TIMESTAMP

结构体

#[derive(Debug, Deserialize, Serialize)]
pub struct Job {
    pub created_at: NaiveDateTime,
}

函数

pub async fn get_all_jobs(&self) -> Result<Vec<Job>, Error> {
        let client = self.pool.get_conn().await?;
        let query = "SELECT created_at FROM job";

        let rows = &client.query(query, &[]).await?;
        // ------------ Following line throws error --------------
        let jobs: Vec<Job> = from_rows(rows)?;

        // ------------ Following lines works fine ---------------
        // let mut jobs: Vec<Job> = Vec::new();
        // for row in rows {
        //    jobs.push(Job {
        //        created_at: row.get(0)
        //    })
        // }

        Ok(jobs)
    }

Cargo.toml

tokio = { version = "0.3", features = ["full"] }
serde = "1.0.117"
serde_derive = "1.0.117"
serde_json = "1.0.60"
serde_postgres = "0.2.0"
thiserror = "1.0.22"
tokio-postgres = { version = "0.5", features = ["with-uuid-0_8", "with-chrono-0_4"] }

当我遍历 rows 并手动将每一行映射到 Job 结构时,上面的代码完美执行。我不喜欢这种手动方法,其中 serde_postgres::from_rows 专为同一任务而设计,但仅对 timestamp without time zone 类型的列无效。

我怀疑这是版本不匹配的问题,如果不是,我就漏掉了什么。如果有人可以分享一些东西,那将是一个很大的帮助 ideas/solutions

似乎serde_postgres crate 不支持日期时间。参考 this

所以我实现了 from_rows 喜欢这个

impl From<&Row> for Job {
    fn from(row: &Row) -> Self {
        Self {
            created_at: row.get("created_at")
        }
    }
}

这有效。