DEV Community

Turbo Panumarch
Turbo Panumarch

Posted on • Edited on

4

Rust: Using DateTime in Diesel with MySQL

Problem:

When I tried to map the model with date and time field, I got this compiler error:

error[E0277]: the trait bound `(Integer, Datetime): 
load_dsl::private::CompatibleType<myapp::models::MyModel, _>` 
is not satisfied
Enter fullscreen mode Exit fullscreen mode

From this set of model and schema:

// models.rs
pub struct MyModel {
    pub id: i32,
    pub created_at: NaiveDateTime,
}
Enter fullscreen mode Exit fullscreen mode
// schema.rs
diesel::table! {
    my_table (id) {
        id -> Integer,
        created_at -> Datetime,
    }
}
Enter fullscreen mode Exit fullscreen mode

Solution:

Fortunately, I found the document mentioned about the DateTime field.

Image description

So we just need to put the feature "chrono" to enable it.

# Cargo.toml
diesel = { version = "2.0.0", features = ["mysql", "chrono"] }
Enter fullscreen mode Exit fullscreen mode

And it works! ✅ 🎉

Tips:

For JSON field, you will also need the serde_json feature in Cargo.toml.

diesel = { version = "2.0.0", features = ["mysql", "chrono", "serde_json"] }
Enter fullscreen mode Exit fullscreen mode

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (1)

Collapse
 
jrpcdev profile image
jason

love how simple and quickly you explained this. As someone doing this for first time it was great to find your post

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay