在官方的getting-started有个例子是diesel-demo,运行完还想研究Mysql的Datetime使用。
up.sql文件内容:
CREATE TABLE `posts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`body` text NOT NULL,
`published` tinyint(1) NOT NULL DEFAULT '0',
`create_time` DATETIME default NOW(),
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4;
自动生成的schema.rs
(命令是diesel migration run
)
table! {
posts (id) {
id -> Integer,
title -> Varchar,
body -> Text,
published -> Bool,
create_time -> Nullable<Datetime>,
}
}
models.rs
#[derive(Queryable, Deserialize, Serialize, Debug)]
// #[derive(Queryable)]
pub struct Post {
pub id: i32,
pub title: String,
pub body: String,
pub published: bool,
pub create_time: Option<chrono::NaiveDateTime>,
}
相应需添加的依赖:
[dependencies]
...
chrono = { version = "0.4.19", features = ["serde"] } // 用于时间类型
serde = { version = "1.0.123", features = ["derive"] } // 用于序列化
serde_json = "*"
如果遇到下面的错误,是因为struct和schema table类型不一致,不能转换。(联想以前写Java,也需要有Converter才能转换,从这一点上逻辑是一样的)
the trait `FromSql<diesel::sql_types::Nullable<diesel::sql_types::Datetime>, Mysql>` is not implemented for `chrono::naive::datetime::NaiveDateTime`
比如下面的例子,就会抛出上面的错误,因为字段在struct里是“必选的”,而schema是“可选的”
pub create_time: <chrono::NaiveDateTime> // struct,该字段必须有值
create_time -> Nullable<Datetime> //schema,该字段可为空
此外,Mysql的Datetime和Timestamp类型,都可以和chrono::NaiveDateTime绑定。因此下面的例子,是合法的:
pub create_time: <chrono::NaiveDateTime> // struct
create_time -> Timestamp //schema
刚开始学,挺有意思
参考资料
https://github.com/pymongo/diesel_crud/blob/main/src/main.rs
https://www.bilibili.com/video/BV1KK4y1n77Z/
https://stackoverflow.com/questions/49412797/retrieve-datetime-from-mysql-database-using-diesel
https://kotiri.com/2018/01/31/postgresql-diesel-rust-types.html
虽然是PG的,但是MySQL有些重复的类型可以参考