rustsqlxrust-sqlx

the trait bound `NaiveDateTime: From<PrimitiveDateTime>` is not satisfied the trait `From<NaiveDate>`


I am trying to implement a query to the database to get all products:

Here is the model:

#[derive(Serialize, Deserialize, Debug, FromRow)]
pub struct Product {
    pub id: Uuid,
    pub name: String,
    pub category_id: String,
    pub kvp: Value,
    pub date: NaiveDateTime,
}

and here is the query:

pub async fn get_products(db_pool: &PgPool) -> Result<Vec<Product>, CustomError> {
    let products = sqlx::query_as!(
        Product,
        "SELECT id, name, category_id, kvp, date FROM products"
    )
    .fetch_all(db_pool)
    .await
    .map_err(|e| match e {
        sqlx::Error::RowNotFound => CustomError::new_not_found("No products found".to_string()),
        sqlx::Error::Database(_) => CustomError::new_bad_request("Bad query".to_string()),
        _ => CustomError::new_internal(format!("Failed to fetch products: {}", e)),
    })?;

    Ok(products)
}

at compilation, the thrown error is:

"the trait bound `NaiveDateTime: From<PrimitiveDateTime>` is not satisfied\nthe trait `From<NaiveDate>` is implemented for `NaiveDateTime`\nfor that trait implementation, expected `NaiveDate`, found `PrimitiveDateTime`\nrequired for `PrimitiveDateTime` to implement `Into<NaiveDateTime>`"`

The database I am using is PSQL, where in the products table the date is defined as:

timestamp(0) without time zone

I tried with different date types, like NaiveDateTime and DateTime.


Solution

  • Under the heading Cargo Feature Flags, the sqlx README states (emphasis added):

    • chrono: Add support for date and time types from chrono.

    • time: Add support for date and time types from time crate (alternative to chrono, which is preferred by query! macro, if both enabled)

    Apparently you have both enabled, and therefore the types from the time crate (namely, in this case, PrimitiveDateTime) are preferred over the types from the chrono crate (namely, in this case, NaiveDateTime).

    Either use PrimitiveDateTime instead, or disable the time feature.