我正在尝试对数据库实施查询以获取所有产品:
这是模型:
#[derive(Serialize, Deserialize, Debug, FromRow)]
pub struct Product {
pub id: Uuid,
pub name: String,
pub category_id: String,
pub kvp: Value,
pub date: NaiveDateTime,
}
这是查询:
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)
}
编译时,抛出的错误是:
"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>`"`
我使用的数据库是PSQL,其中产品表中的日期定义为:
timestamp(0) without time zone
我尝试了不同的日期类型,例如 NaiveDateTime 和 DateTime。
在标题 Cargo Feature Flags 下,sqlx 自述文件指出(添加了强调):
:添加对chrono
中的日期和时间类型的支持。chrono
:添加对来自time
箱的日期和时间类型的支持(替代time
,这是chrono
宏的首选,如果两者都启用)query!
显然您已启用两者,因此
time
板条箱中的类型(即,在本例中为 PrimitiveDateTime
)优于 chrono
板条箱中的类型(即,在本例中为 NaiveDateTime
)
)。
请改用
PrimitiveDateTime
,或禁用 time
功能。