Fixing and testing into_json of various field types (#539)

* Fixing and testing `into_json` of various types

* Support `into_json` for UUID

* Testing `into_json` for UUID

* Fixup
This commit is contained in:
Billy Chan 2022-03-24 22:38:45 +08:00 committed by GitHub
parent ea5b0b1073
commit c504f42cb3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 140 additions and 21 deletions

View File

@ -4,12 +4,21 @@ pub use serde_json::Value as JsonValue;
impl FromQueryResult for JsonValue {
fn from_query_result(res: &QueryResult, pre: &str) -> Result<Self, DbErr> {
let mut map = Map::new();
#[allow(unused_macros)]
macro_rules! try_get_type {
( $type: ty, $col: ident ) => {
if let Ok(v) = res.try_get::<Option<$type>>(pre, &$col) {
map.insert($col.to_owned(), json!(v));
continue;
}
};
}
match &res.row {
#[cfg(feature = "sqlx-mysql")]
QueryResultRow::SqlxMySql(row) => {
use serde_json::json;
use sqlx::{Column, MySql, Row, Type};
let mut map = Map::new();
for column in row.columns() {
let col = if !column.name().starts_with(pre) {
continue;
@ -20,11 +29,7 @@ impl FromQueryResult for JsonValue {
macro_rules! match_mysql_type {
( $type: ty ) => {
if <$type as Type<MySql>>::type_info().eq(col_type) {
map.insert(
col.to_owned(),
json!(res.try_get::<Option<$type>>(pre, &col)?),
);
continue;
try_get_type!($type, col)
}
};
}
@ -40,6 +45,22 @@ impl FromQueryResult for JsonValue {
match_mysql_type!(f32);
match_mysql_type!(f64);
match_mysql_type!(String);
#[cfg(feature = "with-chrono")]
match_mysql_type!(chrono::NaiveDate);
#[cfg(feature = "with-chrono")]
match_mysql_type!(chrono::NaiveTime);
#[cfg(feature = "with-chrono")]
match_mysql_type!(chrono::NaiveDateTime);
#[cfg(feature = "with-chrono")]
match_mysql_type!(chrono::DateTime<chrono::Utc>);
#[cfg(feature = "with-rust_decimal")]
match_mysql_type!(rust_decimal::Decimal);
#[cfg(feature = "with-json")]
try_get_type!(serde_json::Value, col);
try_get_type!(String, col);
#[cfg(feature = "with-uuid")]
try_get_type!(uuid::Uuid, col);
try_get_type!(Vec<u8>, col);
}
Ok(JsonValue::Object(map))
}
@ -47,7 +68,6 @@ impl FromQueryResult for JsonValue {
QueryResultRow::SqlxPostgres(row) => {
use serde_json::json;
use sqlx::{Column, Postgres, Row, Type};
let mut map = Map::new();
for column in row.columns() {
let col = if !column.name().starts_with(pre) {
continue;
@ -58,11 +78,7 @@ impl FromQueryResult for JsonValue {
macro_rules! match_postgres_type {
( $type: ty ) => {
if <$type as Type<Postgres>>::type_info().eq(col_type) {
map.insert(
col.to_owned(),
json!(res.try_get::<Option<$type>>(pre, &col)?),
);
continue;
try_get_type!($type, col)
}
};
}
@ -77,7 +93,22 @@ impl FromQueryResult for JsonValue {
// match_postgres_type!(u64); // unsupported by SQLx Postgres
match_postgres_type!(f32);
match_postgres_type!(f64);
match_postgres_type!(String);
#[cfg(feature = "with-chrono")]
match_postgres_type!(chrono::NaiveDate);
#[cfg(feature = "with-chrono")]
match_postgres_type!(chrono::NaiveTime);
#[cfg(feature = "with-chrono")]
match_postgres_type!(chrono::NaiveDateTime);
#[cfg(feature = "with-chrono")]
match_postgres_type!(chrono::DateTime<chrono::FixedOffset>);
#[cfg(feature = "with-rust_decimal")]
match_postgres_type!(rust_decimal::Decimal);
#[cfg(feature = "with-json")]
try_get_type!(serde_json::Value, col);
try_get_type!(String, col);
#[cfg(feature = "with-uuid")]
try_get_type!(uuid::Uuid, col);
try_get_type!(Vec<u8>, col);
}
Ok(JsonValue::Object(map))
}
@ -85,7 +116,6 @@ impl FromQueryResult for JsonValue {
QueryResultRow::SqlxSqlite(row) => {
use serde_json::json;
use sqlx::{Column, Row, Sqlite, Type};
let mut map = Map::new();
for column in row.columns() {
let col = if !column.name().starts_with(pre) {
continue;
@ -96,11 +126,7 @@ impl FromQueryResult for JsonValue {
macro_rules! match_sqlite_type {
( $type: ty ) => {
if <$type as Type<Sqlite>>::type_info().eq(col_type) {
map.insert(
col.to_owned(),
json!(res.try_get::<Option<$type>>(pre, &col)?),
);
continue;
try_get_type!($type, col)
}
};
}
@ -115,13 +141,21 @@ impl FromQueryResult for JsonValue {
// match_sqlite_type!(u64); // unsupported by SQLx Sqlite
match_sqlite_type!(f32);
match_sqlite_type!(f64);
match_sqlite_type!(String);
#[cfg(feature = "with-chrono")]
match_sqlite_type!(chrono::NaiveDate);
#[cfg(feature = "with-chrono")]
match_sqlite_type!(chrono::NaiveTime);
#[cfg(feature = "with-chrono")]
match_sqlite_type!(chrono::NaiveDateTime);
try_get_type!(String, col);
#[cfg(feature = "with-uuid")]
try_get_type!(uuid::Uuid, col);
try_get_type!(Vec<u8>, col);
}
Ok(JsonValue::Object(map))
}
#[cfg(feature = "mock")]
QueryResultRow::Mock(row) => {
let mut map = Map::new();
for (column, value) in row.clone().into_column_value_tuples() {
let col = if !column.starts_with(pre) {
continue;

View File

@ -1,6 +1,8 @@
pub mod common;
pub use common::{features::*, setup::*, TestContext};
use pretty_assertions::assert_eq;
use sea_orm::{entity::prelude::*, DatabaseConnection, IntoActiveModel};
use serde_json::json;
#[sea_orm_macros::test]
#[cfg(any(
@ -34,6 +36,37 @@ pub async fn create_applog(db: &DatabaseConnection) -> Result<(), DbErr> {
assert_eq!(log.id, res.last_insert_id);
assert_eq!(Applog::find().one(db).await?, Some(log.clone()));
#[cfg(feature = "sqlx-sqlite")]
assert_eq!(
Applog::find().into_json().one(db).await?,
Some(json!({
"id": 1,
"action": "Testing",
"json": r#""HI""#,
"created_at": "2021-09-17 09:50:20",
}))
);
#[cfg(feature = "sqlx-mysql")]
assert_eq!(
Applog::find().into_json().one(db).await?,
Some(json!({
"id": 1,
"action": "Testing",
"json": "HI",
"created_at": "2021-09-17T09:50:20Z",
}))
);
#[cfg(feature = "sqlx-postgres")]
assert_eq!(
Applog::find().into_json().one(db).await?,
Some(json!({
"id": 1,
"action": "Testing",
"json": "HI",
"created_at": "2021-09-17T09:50:20+00:00",
}))
);
Ok(())
}
@ -52,5 +85,36 @@ pub async fn create_satellites_log(db: &DatabaseConnection) -> Result<(), DbErr>
assert_eq!(archive.id, res.last_insert_id);
assert_eq!(Satellite::find().one(db).await?, Some(archive.clone()));
#[cfg(feature = "sqlx-sqlite")]
assert_eq!(
Satellite::find().into_json().one(db).await?,
Some(json!({
"id": 1,
"satellite_name": "Sea-00001-2022",
"launch_date": "2022-01-07 12:11:23",
"deployment_date": "2022-01-07 12:11:23",
}))
);
#[cfg(feature = "sqlx-mysql")]
assert_eq!(
Satellite::find().into_json().one(db).await?,
Some(json!({
"id": 1,
"satellite_name": "Sea-00001-2022",
"launch_date": "2022-01-07T12:11:23Z",
"deployment_date": "2022-01-07T12:11:23Z",
}))
);
#[cfg(feature = "sqlx-postgres")]
assert_eq!(
Satellite::find().into_json().one(db).await?,
Some(json!({
"id": 1,
"satellite_name": "Sea-00001-2022",
"launch_date": "2022-01-07T12:11:23+00:00",
"deployment_date": "2022-01-07T12:11:23+00:00",
}))
);
Ok(())
}

View File

@ -1,7 +1,9 @@
pub mod common;
pub use common::{features::*, setup::*, TestContext};
use pretty_assertions::assert_eq;
use sea_orm::{entity::prelude::*, entity::*, DatabaseConnection};
use serde_json::json;
#[sea_orm_macros::test]
#[cfg(any(
@ -34,6 +36,25 @@ pub async fn insert_metadata(db: &DatabaseConnection) -> Result<(), DbErr> {
assert_eq!(result, metadata);
let json = metadata::Entity::find()
.filter(metadata::Column::Uuid.eq(metadata.uuid))
.into_json()
.one(db)
.await?;
assert_eq!(
json,
Some(json!({
"uuid": metadata.uuid,
"type": metadata.ty,
"key": metadata.key,
"value": metadata.value,
"bytes": metadata.bytes,
"date": metadata.date,
"time": metadata.time,
}))
);
Ok(())
}