Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enumeration - 2 #261

Merged
merged 17 commits into from
Oct 27, 2021
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ futures-util = { version = "^0.3" }
log = { version = "^0.4", optional = true }
rust_decimal = { version = "^1", optional = true }
sea-orm-macros = { version = "^0.3.0", path = "sea-orm-macros", optional = true }
sea-query = { version = "^0.18.0", features = ["thread-safe"] }
sea-query = { version = "^0.18.0", git = "https://github.com/SeaQL/sea-query.git", branch = "sea-orm/active-enum-1", features = ["thread-safe"] }
sea-strum = { version = "^0.21", features = ["derive", "sea-orm"] }
serde = { version = "^1.0", features = ["derive"] }
serde_json = { version = "^1", optional = true }
Expand Down
12 changes: 12 additions & 0 deletions src/entity/column.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ pub enum ColumnType {
JsonBinary,
Custom(String),
Uuid,
Enum(String, Vec<String>),
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And I defined the new column type Enum not only with enum name but enum variants.

}

macro_rules! bind_oper {
Expand Down Expand Up @@ -241,6 +242,14 @@ impl ColumnType {
indexed: false,
}
}

pub(crate) fn get_enum_name(&self) -> Option<&String> {
match self {
// FIXME: How to get rid of this feature gate?
ColumnType::Enum(s, _) if cfg!(feature = "sqlx-postgres") => Some(s),
_ => None,
}
}
billy1624 marked this conversation as resolved.
Show resolved Hide resolved
}

impl ColumnDef {
Expand Down Expand Up @@ -295,6 +304,9 @@ impl From<ColumnType> for sea_query::ColumnType {
sea_query::ColumnType::Custom(sea_query::SeaRc::new(sea_query::Alias::new(&s)))
}
ColumnType::Uuid => sea_query::ColumnType::Uuid,
ColumnType::Enum(s, _) => {
sea_query::ColumnType::Custom(sea_query::SeaRc::new(sea_query::Alias::new(&s)))
}
}
}
}
Expand Down
19 changes: 14 additions & 5 deletions src/query/insert.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use crate::{
ActiveModelTrait, EntityName, EntityTrait, IntoActiveModel, Iterable, PrimaryKeyTrait,
QueryTrait,
ActiveModelTrait, ColumnTrait, EntityName, EntityTrait, IntoActiveModel, Iterable,
PrimaryKeyTrait, QueryTrait,
};
use core::marker::PhantomData;
use sea_query::{InsertStatement, ValueTuple};
use sea_query::{Alias, Expr, Func, InsertStatement, ValueTuple};

#[derive(Debug)]
pub struct Insert<A>
Expand Down Expand Up @@ -124,18 +124,27 @@ where
for (idx, col) in <A::Entity as EntityTrait>::Column::iter().enumerate() {
let av = am.take(col);
let av_has_val = av.is_set() || av.is_unchanged();
let col_def = col.def();
let enum_name = col_def.get_column_type().get_enum_name();

if columns_empty {
self.columns.push(av_has_val);
} else if self.columns[idx] != av_has_val {
panic!("columns mismatch");
}
if av_has_val {
columns.push(col);
values.push(av.into_value().unwrap());
let val = av.into_value().unwrap();
let expr = if let Some(enum_name) = enum_name {
Func::cast_as(val, Alias::new(enum_name))
} else {
Expr::val(val).into()
};
billy1624 marked this conversation as resolved.
Show resolved Hide resolved
values.push(expr);
}
}
self.query.columns(columns);
self.query.values_panic(values);
self.query.exprs_panic(values);
self
}

Expand Down
19 changes: 15 additions & 4 deletions src/query/select.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::{ColumnTrait, EntityTrait, Iterable, QueryFilter, QueryOrder, QuerySe
use core::fmt::Debug;
use core::marker::PhantomData;
pub use sea_query::JoinType;
use sea_query::{DynIden, IntoColumnRef, SeaRc, SelectStatement, SimpleExpr};
use sea_query::{Alias, DynIden, Expr, Func, IntoColumnRef, SeaRc, SelectStatement, SimpleExpr};

#[derive(Clone, Debug)]
pub struct Select<E>
Expand Down Expand Up @@ -109,13 +109,24 @@ where
}

fn prepare_select(mut self) -> Self {
self.query.columns(self.column_list());
self.query.exprs(self.column_list());
self
}

fn column_list(&self) -> Vec<(DynIden, E::Column)> {
fn column_list(&self) -> Vec<SimpleExpr> {
let table = SeaRc::new(E::default()) as DynIden;
E::Column::iter().map(|col| (table.clone(), col)).collect()
E::Column::iter()
.map(|col| {
let col_def = col.def();
let enum_name = col_def.get_column_type().get_enum_name();
let col_expr = Expr::tbl(table.clone(), col);
if enum_name.is_some() {
Func::cast_expr_as(col_expr, Alias::new("text"))
} else {
col_expr.into()
}
billy1624 marked this conversation as resolved.
Show resolved Hide resolved
})
.collect()
}

fn prepare_from(mut self) -> Self {
Expand Down
12 changes: 10 additions & 2 deletions src/query/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use crate::{
QueryTrait,
};
use core::marker::PhantomData;
use sea_query::{IntoIden, SimpleExpr, UpdateStatement};
use sea_query::{Alias, Expr, Func, IntoIden, SimpleExpr, UpdateStatement};

#[derive(Clone, Debug)]
pub struct Update;
Expand Down Expand Up @@ -104,9 +104,17 @@ where
if <A::Entity as EntityTrait>::PrimaryKey::from_column(col).is_some() {
continue;
}
let col_def = col.def();
let enum_name = col_def.get_column_type().get_enum_name();
let av = self.model.get(col);
if av.is_set() {
self.query.value(col, av.unwrap());
let val = av.into_value().unwrap();
let expr = if let Some(enum_name) = enum_name {
Func::cast_as(val, Alias::new(enum_name))
} else {
Expr::val(val).into()
};
billy1624 marked this conversation as resolved.
Show resolved Hide resolved
self.query.value_expr(col, expr);
}
}
self
Expand Down
27 changes: 19 additions & 8 deletions src/schema/entity.rs
Original file line number Diff line number Diff line change
@@ -1,27 +1,37 @@
use crate::{
unpack_table_ref, ColumnTrait, EntityTrait, Identity, Iterable, PrimaryKeyToColumn,
PrimaryKeyTrait, RelationTrait, Schema,
unpack_table_ref, ColumnTrait, ColumnType, DbBackend, EntityTrait, Identity, Iterable,
PrimaryKeyToColumn, PrimaryKeyTrait, RelationTrait, Schema,
};
use sea_query::{ColumnDef, ForeignKeyCreateStatement, Iden, Index, TableCreateStatement};

impl Schema {
pub fn create_table_from_entity<E>(entity: E) -> TableCreateStatement
pub fn create_table_from_entity<E>(entity: E, db_backend: DbBackend) -> TableCreateStatement
where
E: EntityTrait,
{
create_table_from_entity(entity)
create_table_from_entity(entity, db_backend)
}
}

pub(crate) fn create_table_from_entity<E>(entity: E) -> TableCreateStatement
pub(crate) fn create_table_from_entity<E>(entity: E, db_backend: DbBackend) -> TableCreateStatement
where
E: EntityTrait,
{
let mut stmt = TableCreateStatement::new();

for column in E::Column::iter() {
let orm_column_def = column.def();
let types = orm_column_def.col_type.into();
let types = match orm_column_def.col_type {
ColumnType::Enum(s, variants) => match db_backend {
DbBackend::MySql => {
ColumnType::Custom(format!("ENUM('{}')", variants.join("', '")))
}
DbBackend::Postgres => ColumnType::Custom(s),
DbBackend::Sqlite => ColumnType::Text,
}
.into(),
_ => orm_column_def.col_type.into(),
};
let mut column_def = ColumnDef::new_with_type(column, types);
if !orm_column_def.null {
column_def.not_null();
Expand Down Expand Up @@ -121,13 +131,14 @@ where

#[cfg(test)]
mod tests {
use crate::{sea_query::*, tests_cfg::*, Schema};
use crate::{sea_query::*, tests_cfg::*, DbBackend, Schema};
use pretty_assertions::assert_eq;

#[test]
fn test_create_table_from_entity() {
assert_eq!(
Schema::create_table_from_entity(CakeFillingPrice).to_string(MysqlQueryBuilder),
Schema::create_table_from_entity(CakeFillingPrice, DbBackend::MySql)
.to_string(MysqlQueryBuilder),
Table::create()
.table(CakeFillingPrice)
.col(
Expand Down
15 changes: 10 additions & 5 deletions tests/active_enum_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ pub async fn insert_active_enum(db: &DatabaseConnection) -> Result<(), DbErr> {
let am = ActiveModel {
category: Set(None),
color: Set(None),
// tea: Set(None),
tea: Set(None),
..Default::default()
}
.insert(db)
Expand All @@ -36,14 +36,14 @@ pub async fn insert_active_enum(db: &DatabaseConnection) -> Result<(), DbErr> {
id: 1,
category: None,
color: None,
// tea: None,
tea: None,
}
);

ActiveModel {
let am = ActiveModel {
category: Set(Some(Category::Big)),
color: Set(Some(Color::Black)),
// tea: Set(Some(Tea::EverydayTea)),
tea: Set(Some(Tea::EverydayTea)),
..am
}
.save(db)
Expand All @@ -55,9 +55,14 @@ pub async fn insert_active_enum(db: &DatabaseConnection) -> Result<(), DbErr> {
id: 1,
category: Some(Category::Big),
color: Some(Color::Black),
// tea: Some(Tea::EverydayTea),
tea: Some(Tea::EverydayTea),
}
);

let res = am.delete(db).await?;

assert_eq!(res.rows_affected, 1);
assert_eq!(Entity::find().one(db).await?, None);

Ok(())
}
7 changes: 5 additions & 2 deletions tests/common/features/active_enum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ pub struct Model {
pub id: i32,
pub category: Option<Category>,
pub color: Option<Color>,
// pub tea: Option<Tea>,
pub tea: Option<Tea>,
}

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
Expand All @@ -34,7 +34,10 @@ pub enum Color {
}

#[derive(Debug, Clone, PartialEq, DeriveActiveEnum)]
#[sea_orm(rs_type = "String", db_type = r#"Custom("tea".to_owned())"#)]
#[sea_orm(
rs_type = "String",
db_type = r#"Enum("tea".to_owned(), vec!["EverydayTea".to_owned(), "BreakfastTea".to_owned()])"#
)]
Comment on lines +37 to +40
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Which is quite verbose when using it...

pub enum Tea {
#[sea_orm(string_value = "EverydayTea")]
EverydayTea,
Expand Down
48 changes: 45 additions & 3 deletions tests/common/features/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,13 @@ pub use super::super::bakery_chain::*;

use super::*;
use crate::common::setup::create_table;
use sea_orm::{error::*, sea_query, DatabaseConnection, DbConn, ExecResult};
use sea_query::{ColumnDef, ForeignKeyCreateStatement};
use sea_orm::{
error::*, sea_query, ConnectionTrait, DatabaseConnection, DbBackend, DbConn, ExecResult,
Statement,
};
use sea_query::{
extension::postgres::Type, Alias, ColumnDef, ForeignKeyCreateStatement, PostgresQueryBuilder,
};

pub async fn create_tables(db: &DatabaseConnection) -> Result<(), DbErr> {
create_log_table(db).await?;
Expand Down Expand Up @@ -103,6 +108,16 @@ pub async fn create_self_join_table(db: &DbConn) -> Result<ExecResult, DbErr> {
}

pub async fn create_active_enum_table(db: &DbConn) -> Result<ExecResult, DbErr> {
let db_backend = db.get_database_backend();
let tea_enum = Alias::new("tea");

let mut tea_col = ColumnDef::new(active_enum::Column::Tea);
match db_backend {
DbBackend::MySql => tea_col.custom(Alias::new("ENUM('EverydayTea', 'BreakfastTea')")),
DbBackend::Postgres => tea_col.custom(tea_enum.clone()),
DbBackend::Sqlite => tea_col.text(),
};

let stmt = sea_query::Table::create()
.table(active_enum::Entity)
.col(
Expand All @@ -114,8 +129,35 @@ pub async fn create_active_enum_table(db: &DbConn) -> Result<ExecResult, DbErr>
)
.col(ColumnDef::new(active_enum::Column::Category).string_len(1))
.col(ColumnDef::new(active_enum::Column::Color).integer())
// .col(ColumnDef::new(active_enum::Column::Tea).custom(Alias::new("tea")))
.col(&mut tea_col)
.to_owned();

if db_backend == DbBackend::Postgres {
let drop_type_stmt = Type::drop()
.name(tea_enum.clone())
.cascade()
.if_exists()
.to_owned();
let (sql, values) = drop_type_stmt.build(PostgresQueryBuilder);
let stmt = Statement::from_sql_and_values(db.get_database_backend(), &sql, values);
db.execute(stmt).await?;

let create_type_stmt = Type::create()
.as_enum(tea_enum)
.values(vec![Alias::new("EverydayTea"), Alias::new("BreakfastTea")])
.to_owned();
// FIXME: This is not working
{
let (sql, values) = create_type_stmt.build(PostgresQueryBuilder);
let _stmt = Statement::from_sql_and_values(db.get_database_backend(), &sql, values);
}
// But this is working...
let stmt = Statement::from_string(
db.get_database_backend(),
create_type_stmt.to_string(PostgresQueryBuilder),
);
db.execute(stmt).await?;
}

create_table(db, &stmt, ActiveEnum).await
}
5 changes: 4 additions & 1 deletion tests/common/setup/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,10 @@ where

let stmt = builder.build(create);
assert_eq!(
builder.build(&Schema::create_table_from_entity(entity)),
builder.build(&Schema::create_table_from_entity(
entity,
db.get_database_backend()
)),
stmt
);
db.execute(stmt).await
Expand Down