简体   繁体   English

Rust Diesel Library 使用 Timestamptz 反序列化 Postgres DateTIme,

[英]Rust Diesel Library Deserialising Postgres DateTIme with Timestamptz,

Error is:-错误是:-

  > src/lib.rs:45:14
       |
    45 |             .load::<Store>(&conn)
       |              ^^^^ the trait 

`diesel::deserialize::FromSql<diesel::sql_types::Timestamptz, _>` is not implemented for `bool`

My up.sql is:--我的 up.sql 是:--

CREATE TABLE store (
    id SERIAL PRIMARY KEY,
    name VARCHAR(500) NOT NULL,
    description VARCHAR(2000) NOT NULL,
    created_at timestamp with TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at timestamp with TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
    is_active boolean DEFAULT 'f' NOT NULL,
    created_by integer NOT NULL,
    address_id integer NOT NULL
);

SELECT diesel_manage_updated_at('store');

My model file: -我的 model 文件:-

use diesel::{Insertable, Queryable};
use serde::{Deserialize, Serialize};
use chrono::{ DateTime, Utc };

use crate::schema::{store, item, store_item};

use std::convert::From;

#[derive(Deserialize, Serialize, Queryable)]
pub struct Store {
    pub id: i32,
    pub name: String,
    pub description: String,
    pub is_active: bool,
    pub created_by: i32,
    pub address_id: i32,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

My test file:-我的测试文件:-

#[macro_use]
extern crate diesel;
extern crate dotenv;

pub mod schema;
pub mod models;



#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {

        use diesel::prelude::*;
        use diesel::pg::PgConnection;
        use dotenv::dotenv;
        use std::env;

        dotenv().ok();

        let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
        let conn = PgConnection::establish(&database_url).expect(&format!("Error connecting to {}", database_url));

        let sid: i32 = 1;
        use crate::models::{Store, NewStore};
        use crate::schema::store::dsl::*;

        let new_store = NewStore {
            name: "Top in town stores".to_owned(),
            description: "this is top in town stores".to_owned(),
            is_active: true,
            created_by: 22,
            address_id: 3322
        };

        let sam: usize = diesel::insert_into(store).values(&new_store).execute(&conn).unwrap();

        let user = store
            .filter(id.eq(sid))
            .limit(1)
            .load::<Store>(&conn)
            .expect("Error loading posts");

        assert_eq!(1, 1);
    }
}

My Cargo file:-我的货物文件:-

[package]
name = "database"
version = "0.1.0"
authors = ["spiderman"]
edition = "2018"


# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
diesel = { version="1.4.5", features = ["postgres", "extras", "chrono"] }

chrono = { version = "0.4", features = ["serde", "rustc-serialize"] }

serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
dotenv = "*"

My auto generated schema from diesel cli:-我从 diesel cli 自动生成的架构:-

table! {
    item (id) {
        id -> Int4,
        name -> Varchar,
        description -> Varchar,
        created_at -> Timestamptz,
        updated_at -> Timestamptz,
        is_active -> Bool,
        created_by -> Int4,
    }
}

table! {
    store (id) {
        id -> Int4,
        name -> Varchar,
        description -> Varchar,
        created_at -> Timestamptz,
        updated_at -> Timestamptz,
        is_active -> Bool,
        created_by -> Int4,
        address_id -> Int4,
    }
}

table! {
    store_item (id) {
        id -> Int4,
        store_id -> Nullable<Int4>,
        item_id -> Nullable<Int4>,
        created_at -> Timestamptz,
        updated_at -> Timestamptz,
        is_active -> Bool,
        created_by -> Int4,
    }
}

joinable!(store_item -> item (item_id));
joinable!(store_item -> store (store_id));

allow_tables_to_appear_in_same_query!(
    item,
    store,
    store_item,
);

Problem only when I add datetimefield, If I remove it from sql and models, than it is not giving problem,仅当我添加日期时间字段时出现问题,如果我将其从 sql 和模型中删除,则不会出现问题,

I think your problem is due to field order.我认为你的问题是由于现场订单。 The order of fields in your SQL does not match your model structs.您的 SQL 中的字段顺序与您的 model 结构不匹配。

From Diesel Getting Started柴油入门

Using #[derive(Queryable)] assumes that the order of fields on the Post struct matches the columns in the posts table, so make sure to define them in the order seen in the schema.rs file.使用#[derive(Queryable)] 假定 Post 结构上的字段顺序与 posts 表中的列匹配,因此请确保按照 schema.rs 文件中看到的顺序定义它们。

The error message said it couldn't convert a Bool to a timestamp, so that's why I think it mixed up your is_active with one of the date fields.错误消息说它无法将Bool转换为时间戳,所以这就是为什么我认为它混淆了您的is_active与日期字段之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM