Skip to content

Commit

Permalink
Support MySQL / SQLite
Browse files Browse the repository at this point in the history
  • Loading branch information
tyt2y3 authored and chris-cantor committed Oct 16, 2023
1 parent 201d6fe commit 93623f0
Show file tree
Hide file tree
Showing 8 changed files with 109 additions and 43 deletions.
11 changes: 11 additions & 0 deletions sea-orm-macros/src/derives/try_getable_from_json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@ use proc_macro2::{Ident, TokenStream};
use quote::quote;

pub fn expand_derive_from_json_query_result(ident: Ident) -> syn::Result<TokenStream> {
let impl_not_u8 = if cfg!(feature = "postgres-array") {
quote!(
#[automatically_derived]
impl sea_orm::sea_query::value::with_array::NotU8 for #ident {}
)
} else {
quote!()
};

Ok(quote!(
#[automatically_derived]
impl sea_orm::TryGetableFromJson for #ident {}
Expand Down Expand Up @@ -43,5 +52,7 @@ pub fn expand_derive_from_json_query_result(ident: Ident) -> syn::Result<TokenSt
sea_orm::Value::Json(None)
}
}

#impl_not_u8
))
}
39 changes: 36 additions & 3 deletions src/entity/column.rs
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,7 @@ pub trait ColumnTrait: IdenStatic + Iterable + FromStr {
}

/// Cast value of an enum column as enum type; do nothing if `self` is not an enum.
/// Will also transform `Array(Vec<Json>)` into `Json(Vec<Json>)` if the column type is `Json`.
fn save_enum_as(&self, val: Expr) -> SimpleExpr {
cast_enum_as(val, self, |col, enum_name, col_type| {
let type_name = match col_type {
Expand Down Expand Up @@ -412,9 +413,41 @@ where
{
let col_def = col.def();
let col_type = col_def.get_column_type();
match col_type.get_enum_name() {
Some(enum_name) => f(expr, SeaRc::clone(enum_name), col_type),
None => expr.into(),

match col_type {
#[cfg(all(feature = "with-json", feature = "postgres-array"))]
ColumnType::Json | ColumnType::JsonBinary => {
use sea_query::ArrayType;
use serde_json::Value as Json;

#[allow(clippy::boxed_local)]
fn unbox<T>(boxed: Box<T>) -> T {
*boxed
}

let expr = expr.into();
match expr {
SimpleExpr::Value(Value::Array(ArrayType::Json, Some(json_vec))) => {
// flatten Array(Vec<Json>) into Json
let json_vec: Vec<Json> = json_vec
.into_iter()
.filter_map(|val| match val {
Value::Json(Some(json)) => Some(unbox(json)),
_ => None,
})
.collect();
SimpleExpr::Value(Value::Json(Some(Box::new(json_vec.into()))))
}
SimpleExpr::Value(Value::Array(ArrayType::Json, None)) => {
SimpleExpr::Value(Value::Json(None))
}
_ => expr,
}
}
_ => match col_type.get_enum_name() {
Some(enum_name) => f(expr, SeaRc::clone(enum_name), col_type),
None => expr.into(),
},
}
}

Expand Down
6 changes: 3 additions & 3 deletions tests/active_enum_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,12 @@ async fn main() -> Result<(), DbErr> {
insert_active_enum(&ctx.db).await?;
insert_active_enum_child(&ctx.db).await?;

if cfg!(feature = "sqlx-postgres") {
insert_active_enum_vec(&ctx.db).await?;
}
#[cfg(feature = "sqlx-postgres")]
insert_active_enum_vec(&ctx.db).await?;

find_related_active_enum(&ctx.db).await?;
find_linked_active_enum(&ctx.db).await?;

ctx.delete().await;

Ok(())
Expand Down
21 changes: 9 additions & 12 deletions tests/common/features/json_vec_derive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,35 +4,27 @@ pub mod json_string_vec {
use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "json_vec")]
#[sea_orm(table_name = "json_string_vec")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub str_vec: Option<StringVec>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, FromJsonQueryResult)]
pub struct StringVec(pub Vec<String>);

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}

impl ActiveModelBehavior for ActiveModel {}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, FromJsonQueryResult)]
pub struct StringVec(pub Vec<String>);
}

pub mod json_struct_vec {
use sea_orm::entity::prelude::*;
use sea_orm_macros::FromJsonQueryResult;
use sea_query::with_array::NotU8;
use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, FromJsonQueryResult)]
pub struct JsonColumn {
pub value: String,
}

impl NotU8 for JsonColumn {}

#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "json_struct_vec")]
pub struct Model {
Expand All @@ -42,6 +34,11 @@ pub mod json_struct_vec {
pub struct_vec: Vec<JsonColumn>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, FromJsonQueryResult)]
pub struct JsonColumn {
pub value: String,
}

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}

Expand Down
1 change: 1 addition & 0 deletions tests/common/features/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ pub use event_trigger::Entity as EventTrigger;
pub use insert_default::Entity as InsertDefault;
pub use json_struct::Entity as JsonStruct;
pub use json_vec::Entity as JsonVec;
pub use json_vec_derive::json_string_vec::Entity as JsonStringVec;
pub use json_vec_derive::json_struct_vec::Entity as JsonStructVec;
pub use metadata::Entity as Metadata;
pub use pi::Entity as Pi;
Expand Down
57 changes: 37 additions & 20 deletions tests/common/features/schema.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use super::*;
use crate::common::features::json_vec_derive::json_struct_vec;
use crate::common::setup::{create_enum, create_table, create_table_without_asserts};
use sea_orm::{
error::*, sea_query, ConnectionTrait, DatabaseConnection, DbBackend, DbConn, EntityName,
Expand All @@ -20,7 +19,6 @@ pub async fn create_tables(db: &DatabaseConnection) -> Result<(), DbErr> {
create_byte_primary_key_table(db).await?;
create_satellites_table(db).await?;
create_transaction_log_table(db).await?;
create_json_struct_table(db).await?;

let create_enum_stmts = match db_backend {
DbBackend::MySql | DbBackend::Sqlite => Vec::new(),
Expand Down Expand Up @@ -51,12 +49,15 @@ pub async fn create_tables(db: &DatabaseConnection) -> Result<(), DbErr> {
create_dyn_table_name_lazy_static_table(db).await?;
create_value_type_table(db).await?;

create_json_vec_table(db).await?;
create_json_struct_table(db).await?;
create_json_string_vec_table(db).await?;
create_json_struct_vec_table(db).await?;

if DbBackend::Postgres == db_backend {
create_value_type_postgres_table(db).await?;
create_collection_table(db).await?;
create_event_trigger_table(db).await?;
create_json_vec_table(db).await?;
create_json_struct_vec_table(db).await?;
create_categories_table(db).await?;
}

Expand Down Expand Up @@ -323,46 +324,62 @@ pub async fn create_json_vec_table(db: &DbConn) -> Result<ExecResult, DbErr> {
create_table(db, &create_table_stmt, JsonVec).await
}

pub async fn create_json_struct_vec_table(db: &DbConn) -> Result<ExecResult, DbErr> {
let create_table_stmt = sea_query::Table::create()
.table(json_struct_vec::Entity.table_ref())
pub async fn create_json_struct_table(db: &DbConn) -> Result<ExecResult, DbErr> {
let stmt = sea_query::Table::create()
.table(json_struct::Entity)
.col(
ColumnDef::new(json_struct_vec::Column::Id)
ColumnDef::new(json_struct::Column::Id)
.integer()
.not_null()
.auto_increment()
.primary_key(),
)
.col(ColumnDef::new(json_struct::Column::Json).json().not_null())
.col(
ColumnDef::new(json_struct_vec::Column::StructVec)
.json_binary()
ColumnDef::new(json_struct::Column::JsonValue)
.json()
.not_null(),
)
.col(ColumnDef::new(json_struct::Column::JsonValueOpt).json())
.to_owned();

create_table(db, &create_table_stmt, JsonStructVec).await
create_table(db, &stmt, JsonStruct).await
}

pub async fn create_json_struct_table(db: &DbConn) -> Result<ExecResult, DbErr> {
let stmt = sea_query::Table::create()
.table(json_struct::Entity)
pub async fn create_json_string_vec_table(db: &DbConn) -> Result<ExecResult, DbErr> {
let create_table_stmt = sea_query::Table::create()
.table(JsonStringVec.table_ref())
.col(
ColumnDef::new(json_struct::Column::Id)
ColumnDef::new(json_vec_derive::json_string_vec::Column::Id)
.integer()
.not_null()
.auto_increment()
.primary_key(),
)
.col(ColumnDef::new(json_struct::Column::Json).json().not_null())
.col(ColumnDef::new(json_vec_derive::json_string_vec::Column::StrVec).json())
.to_owned();

create_table(db, &create_table_stmt, JsonStringVec).await
}

pub async fn create_json_struct_vec_table(db: &DbConn) -> Result<ExecResult, DbErr> {
let create_table_stmt = sea_query::Table::create()
.table(JsonStructVec.table_ref())
.col(
ColumnDef::new(json_struct::Column::JsonValue)
.json()
ColumnDef::new(json_vec_derive::json_struct_vec::Column::Id)
.integer()
.not_null()
.auto_increment()
.primary_key(),
)
.col(
ColumnDef::new(json_vec_derive::json_struct_vec::Column::StructVec)
.json_binary()
.not_null(),
)
.col(ColumnDef::new(json_struct::Column::JsonValueOpt).json())
.to_owned();

create_table(db, &stmt, JsonStruct).await
create_table(db, &create_table_stmt, JsonStructVec).await
}

pub async fn create_collection_table(db: &DbConn) -> Result<ExecResult, DbErr> {
Expand Down
9 changes: 6 additions & 3 deletions tests/common/setup/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use pretty_assertions::assert_eq;
use sea_orm::{
ColumnTrait, ColumnType, ConnectionTrait, Database, DatabaseBackend, DatabaseConnection,
DbBackend, DbConn, DbErr, EntityTrait, ExecResult, Iterable, Schema, Statement,
ColumnTrait, ColumnType, ConnectOptions, ConnectionTrait, Database, DatabaseBackend,
DatabaseConnection, DbBackend, DbConn, DbErr, EntityTrait, ExecResult, Iterable, Schema,
Statement,
};
use sea_query::{
extension::postgres::{Type, TypeCreateStatement},
Expand Down Expand Up @@ -48,7 +49,9 @@ pub async fn setup(base_url: &str, db_name: &str) -> DatabaseConnection {
let url = format!("{base_url}/{db_name}");
Database::connect(&url).await.unwrap()
} else {
Database::connect(base_url).await.unwrap()
let mut options: ConnectOptions = base_url.into();
options.sqlx_logging(false);
Database::connect(options).await.unwrap()
}
}

Expand Down
8 changes: 6 additions & 2 deletions tests/json_vec_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,17 @@ use pretty_assertions::assert_eq;
use sea_orm::{entity::prelude::*, entity::*, DatabaseConnection};

#[sea_orm_macros::test]
#[cfg(feature = "sqlx-postgres")]
#[cfg(any(
feature = "sqlx-mysql",
feature = "sqlx-sqlite",
feature = "sqlx-postgres"
))]
async fn main() -> Result<(), DbErr> {
let ctx = TestContext::new("json_vec_tests").await;
create_tables(&ctx.db).await?;
insert_json_vec(&ctx.db).await?;

insert_json_string_vec_derive(&ctx.db).await?;
insert_json_struct_vec_derive(&ctx.db).await?;

ctx.delete().await;

Expand Down

0 comments on commit 93623f0

Please sign in to comment.