Reputation: 15722
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?
Upvotes: 3
Views: 4608
Reputation: 3895
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};
Upvotes: 2
Reputation: 1356
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.)
Upvotes: 1