Получить дату и время из базы данных MySQL с помощью Diesel

Я не могу получить дату и время из заполненной базы данных MySQL, используя Rocket и Diesel.

Вот моя модель:

extern crate chrono;

use diesel::prelude::*;
use diesel::mysql::MysqlConnection;
use schema::chrisms;
use diesel::sql_types::Datetime;
use self::chrono::{DateTime, Duration, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, Utc};

#[derive(Serialize, Deserialize, Queryable)]
pub struct Chrisms {
    pub entity_ekklesia_location_id: i32,
    pub serie_number: Option<String>,
    pub seat_number: Option<String>,
    pub date: Datetime,
    pub year: i32,
    pub deleted: bool,
    pub entity_chrism_location_id: Option<i32>,
    pub entity_chrism_location_description: Option<String>,
    pub entity_rel_mec_id: Option<i32>,
    pub entity_rel_mec_description: Option<String>,
    pub created_by_user_id: Option<i32>,
    pub updated_by_user_id: Option<i32>,
    pub deleted_by_user_id: Option<i32>,
    pub created_at: Datetime,
    pub updated_at: Datetime,
    pub id: i32,
}

impl Chrisms {
    pub fn read(connection: &MysqlConnection) -> Vec<Chrisms> {
        chrisms::table.load::<Chrisms>(connection).unwrap()
    }
}

Моя схема:

table! {
    chrisms (id) {
        entity_ekklesia_location_id -> Integer,
        serie_number -> Nullable<Varchar>,
        seat_number -> Nullable<Varchar>,
        date -> Datetime,
        year -> Integer,
        deleted -> Bool,
        entity_chrism_location_id -> Nullable<Integer>,
        entity_chrism_location_description -> Nullable<Varchar>,
        entity_rel_mec_id -> Nullable<Integer>,
        entity_rel_mec_description -> Nullable<Varchar>,
        created_by_user_id -> Nullable<Integer>,
        updated_by_user_id -> Nullable<Integer>,
        deleted_by_user_id -> Nullable<Integer>,
        created_at -> Datetime,
        updated_at -> Datetime,
        id -> Integer,
    }
}

Это приводит к ошибкам:

1. the trait `_IMPL_SERIALIZE_FOR_TemplateContext::_serde::Serialize` is not 
implemented for `diesel::sql_types::Datetime`
-required by `_IMPL_SERIALIZE_FOR_TemplateContext::_serde::ser::SerializeStruct::serialize_field`

2. the trait `_IMPL_SERIALIZE_FOR_TemplateContext::_serde::Deserialize<'_>` is 
not implemented for `diesel::sql_types::Datetime`
- required by `_IMPL_SERIALIZE_FOR_TemplateContext::_serde::de::SeqAccess::next_element`
- required by `_IMPL_SERIALIZE_FOR_TemplateContext::_serde::de::MapAccess::next_value`

3. the trait `diesel::Queryable<diesel::sql_types::Datetime, 
diesel::mysql::Mysql>` is not implemented for `diesel::sql_types::Datetime`
- required because of the requirements on the impl of `diesel::query_dsl::LoadQuery<_, models::chrisms::Chrisms>` for `schema::chrisms::table`

Как это исправить? Я проверил кучу применений, таких как diesel:mysql_types, rocket:config и так далее, похоже, не в этом проблема.

0 ответов

Вот пример сопоставления типа datetime mysql с ржавчиной.

ссылка - дизель / примеры / mysql

Cargo.toml:

[dependencies]
dotenv = "*"
diesel = { version = "*", features = ["mysql", "chrono"] }
chrono = { version = "*", features = ["serde"] }

Схема таблицы mysql:

CREATE TABLE IF NOT EXISTS orders(
    id SERIAL PRIMARY KEY,
    created_at DATETIME NOT NULL
)
mysql> desc orders;
+------------+---------------------+------+-----+---------+----------------+
| Field      | Type                | Null | Key | Default | Extra          |
+------------+---------------------+------+-----+---------+----------------+
| id         | bigint(20) unsigned | NO   | PRI | NULL    | auto_increment |
| created_at | datetime            | NO   |     | NULL    |                |
+------------+---------------------+------+-----+---------+----------------+

src / schema.rs:

table! {
    orders (id) {
        id -> Unsigned<Bigint>,
        created_at -> Datetime, // or Timestamp
    }
}

src / model.rs:

use crate::schema::orders;
use crate::schema::orders::dsl::orders as orders_dsl;
use diesel::{MysqlConnection, RunQueryDsl, QueryDsl, ExpressionMethods};

#[derive(Queryable, Debug)]
pub struct Order {
    pub id: u64,
    pub created_at: chrono::NaiveDateTime
}

#[derive(Insertable)]
#[table_name = "orders"]
pub struct NewOrder {
    pub created_at: chrono::NaiveDateTime
}

pub fn create_order(ref_db_connection: &MysqlConnection) {
    diesel::insert_into(orders::table)
        .values(&NewOrder{created_at: chrono::Utc::now().naive_local()})
        .execute(ref_db_connection)
        .unwrap();
}

pub fn last_order(ref_db_connection: &MysqlConnection) -> Order {
    orders_dsl.order(orders::id.desc()).first(ref_db_connection).unwrap()
}

src /main.rs

#[macro_use]
extern crate diesel;
use diesel::{Connection, MysqlConnection};
mod model;
mod schema;

pub fn establish_connection() -> MysqlConnection {
    dotenv::dotenv().ok();

    let database_url = std::env::var("DATABASE_URL")
        .expect("DATABASE_URL must be set in .env file");
    MysqlConnection::establish(&database_url).unwrap()
}

fn main() {
    let db_conn = establish_connection();
    model::create_order(&db_conn);
    let order = model::last_order(&db_conn);
    println!("{:?}", order);
}

Пример вывода:

Order { id: 2, created_at: 2020-05-06T21:54:25 }
Другие вопросы по тегам