3

I have a struct that contains a date and I use it with sqlx to retrieve data from my database. So something like:

use sqlx::types::chrono::{DateTime, Utc};

pub struct Account {
    pub id: i32,
    pub primary_email_id: i32,
    pub created: DateTime<Utc>,
}

and

sqlx::query_as!(Account, "select * ...")

This works fine so far. But I also want Account to be serializable via serde. The obvious approach is:

#[derive(Serialize)]
pub struct Account {
    ...

This fails, because the Serialize trait is not implemented for DateTime<Utc>. I tried the same with PrimitiveDateTime from the time crate with the same result. In theory both should support serde as a feature.

I tried to explicitly add time or chrono as dependency, to enable serde as feature and use the type without the sqlx::types prefix. But in that case it fails because some sqlx traits are not implemented.

I assume that I somehow have to enable the serde feature for the classes brought in by sqlx, but I have no idea how to specify a feature for a feature!?

How to I tell sqlx to enable serde for the time/chrono types?

Achim
  • 15,415
  • 15
  • 80
  • 144
  • 5
    chrono is a reexport and recent chrono version have a serde feature so just add chrono as dependancies and add serde feature should work – Stargateur Dec 17 '21 at 23:01
  • 1
    Correct. If you would make it an answer, I could accept it. – Achim Dec 21 '21 at 20:28

2 Answers2

2

I was able to solve it by importing chrono separately from sqlx and enabling serde for it:

Cargo.toml:

sqlx = { version = "0.6.2", features = ["runtime-actix-native-tls", "postgres"] }
chrono = { version = "0.4.23", features = ["serde"] }

And then you will need to change your use declaration from use sqlx::types::chrono::{DateTime, Utc}; to use chrono::{DateTime, Utc};

Enigo
  • 3,685
  • 5
  • 29
  • 54
1

This depends on the time and chrono Cargo features of sqlx. So ensure the [dependencies] section of your Cargo.toml file includes these. As an example:

sqlx = { version = "0.6.0", features = [ "postgres", "runtime-tokio-native-tls", "offline", "time", "chrono" ] }

(This is essentially the comment of @Stargateur above. All credit to them.)

Andrew Straw
  • 1,138
  • 12
  • 15