DEV Community

Turbo Panumarch
Turbo Panumarch

Posted on • Updated on

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

Top comments (0)