sea-orm/tests/time_crate_tests.rs
Billy Chan a0fd72e635
Serialize time types as serde_json::Value (#1042)
* Implement `IntoActiveValue` for `time` types.

I tried to implement a [custom active
model](https://www.sea-ql.org/SeaORM/docs/advanced-query/custom-active-model/),
and one of the columns was `Option<TimeDateTimeWithTimeZone>`. I got a
compiler error:

```
error[E0277]: the trait bound `std::option::Option<sea_orm::prelude::TimeDateTimeWithTimeZone>: IntoActiveValue<_>` is not satisfied
```

Looking into the source code, it seemed a simple oversight that this
trait was implemented for the `chrono` types but not the `time` types,
and it was easy enough to fix since there's already a macro to implement
it for new types.

I also noticed that the `time` types are not accounted for in
`src/query/json.rs` while the `chrono` types are, which I assume is also
an oversight. However, I don't have a need for that at this point and
the fix for that seemed less trivial, so I'm just bringing it to your
attention.

Thanks for SeaORM!

* Implement `IntoActiveValue` for `Vec<u8>` types

* Add tests to double check and prevent it from happening again

* Add docs

* Fixup

* Serialize `time` types as `serde_json::Value`

Co-authored-by: Jimmy Cuadra <jimmy@jimmycuadra.com>
2022-10-18 00:04:03 +08:00

74 lines
1.9 KiB
Rust

pub mod common;
pub use common::{features::*, setup::*, TestContext};
use sea_orm::{entity::prelude::*, DatabaseConnection, IntoActiveModel};
use serde_json::json;
use time::macros::{date, time};
#[sea_orm_macros::test]
#[cfg(any(
feature = "sqlx-mysql",
feature = "sqlx-sqlite",
feature = "sqlx-postgres"
))]
#[cfg_attr(
feature = "sqlx-sqlite",
should_panic(expected = "time::Date unsupported by sqlx-sqlite")
)]
async fn main() {
let ctx = TestContext::new("time_crate_tests").await;
create_tables(&ctx.db).await.unwrap();
create_transaction_log(&ctx.db).await.unwrap();
ctx.delete().await;
}
pub async fn create_transaction_log(db: &DatabaseConnection) -> Result<(), DbErr> {
let transaction_log = transaction_log::Model {
id: 1,
date: date!(2022 - 03 - 13),
time: time!(16:24:00),
date_time: date!(2022 - 03 - 13).with_time(time!(16:24:00)),
date_time_tz: date!(2022 - 03 - 13)
.with_time(time!(16:24:00))
.assume_utc(),
};
let res = TransactionLog::insert(transaction_log.clone().into_active_model())
.exec(db)
.await?;
assert_eq!(transaction_log.id, res.last_insert_id);
assert_eq!(
TransactionLog::find().one(db).await?,
Some(transaction_log.clone())
);
let json = TransactionLog::find().into_json().one(db).await?.unwrap();
#[cfg(feature = "sqlx-postgres")]
assert_eq!(
json,
json!({
"id": 1,
"date": "2022-03-13",
"time": "16:24:00",
"date_time": "2022-03-13T16:24:00",
"date_time_tz": "2022-03-13T16:24:00+00:00",
})
);
#[cfg(feature = "sqlx-mysql")]
assert_eq!(
json,
json!({
"id": 1,
"date": "2022-03-13",
"time": "16:24:00",
"date_time": "2022-03-13T16:24:00",
"date_time_tz": "2022-03-13T16:24:00Z",
})
);
Ok(())
}