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

Unknown types could be a newtypes instead of ActiveEnum #324

Merged
merged 4 commits into from
Nov 17, 2021
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ jobs:
strategy:
matrix:
os: [ubuntu-latest]
path: [86, 249, 262, 319]
path: [86, 249, 262, 319, 324]
steps:
- uses: actions/checkout@v2

Expand Down
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.1", path = "sea-orm-macros", optional = true }
sea-query = { version = "^0.18.0", git = "https://github.com/SeaQL/sea-query.git", features = ["thread-safe"] }
sea-query = { version = "^0.18.0", git = "https://github.com/SeaQL/sea-query.git", branch = "enum-column-type", 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
11 changes: 11 additions & 0 deletions issues/324/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[workspace]
# A separate workspace

[package]
name = "sea-orm-issues-324"
version = "0.1.0"
edition = "2021"
publish = false

[dependencies]
sea-orm = { path = "../../", features = [ "sqlx-mysql", "runtime-async-std-native-tls" ]}
3 changes: 3 additions & 0 deletions issues/324/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
mod model;

pub fn main() {}
83 changes: 83 additions & 0 deletions issues/324/src/model.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
use sea_orm::entity::prelude::*;

#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "model")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: AccountId,
pub name: String,
}

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

impl ActiveModelBehavior for ActiveModel {}

#[derive(Clone, Debug, PartialEq)]
pub struct AccountId(Uuid);

impl From<AccountId> for Uuid {
fn from(account_id: AccountId) -> Self {
account_id.0
}
}

macro_rules! impl_try_from_u64_err {
($newtype: ident) => {
impl sea_orm::TryFromU64 for $newtype {
fn try_from_u64(_n: u64) -> Result<Self, sea_orm::DbErr> {
Err(sea_orm::DbErr::Exec(format!(
"{} cannot be converted from u64",
stringify!($newtype)
)))
}
}
};
}

macro_rules! into_sea_query_value {
($newtype: ident: Box($name: ident)) => {
impl From<$newtype> for sea_orm::Value {
fn from(source: $newtype) -> Self {
sea_orm::Value::$name(Some(Box::new(source.into())))
}
}

impl sea_orm::TryGetable for $newtype {
fn try_get(
res: &sea_orm::QueryResult,
pre: &str,
col: &str,
) -> Result<Self, sea_orm::TryGetError> {
let val: $name = res.try_get(pre, col).map_err(sea_orm::TryGetError::DbErr)?;
Ok($newtype(val))
}
}

impl sea_orm::sea_query::Nullable for $newtype {
fn null() -> sea_orm::Value {
sea_orm::Value::$name(None)
}
}

impl sea_orm::sea_query::ValueType for $newtype {
fn try_from(v: sea_orm::Value) -> Result<Self, sea_orm::sea_query::ValueTypeErr> {
match v {
sea_orm::Value::$name(Some(x)) => Ok($newtype(*x)),
_ => Err(sea_orm::sea_query::ValueTypeErr),
}
}

fn type_name() -> String {
stringify!($newtype).to_owned()
}

fn column_type() -> sea_orm::sea_query::ColumnType {
sea_orm::sea_query::ColumnType::$name
}
}
};
}

into_sea_query_value!(AccountId: Box(Uuid));
impl_try_from_u64_err!(AccountId);
5 changes: 4 additions & 1 deletion sea-orm-macros/src/derives/entity_model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,10 @@ pub fn expand_derive_entity_model(data: Data, attrs: Vec<Attribute>) -> syn::Res
let field_span = field.span();
let ty = format_ident!("{}", temp);
let def = quote_spanned! { field_span => {
<#ty as ActiveEnum>::db_type()
std::convert::Into::<sea_orm::ColumnType>::into(
<#ty as sea_orm::sea_query::ValueType>::column_type()
)
.def()
}};
quote! { #def }
} else {
Expand Down
4 changes: 3 additions & 1 deletion src/entity/column.rs
Original file line number Diff line number Diff line change
Expand Up @@ -364,10 +364,11 @@ impl From<ColumnType> for sea_query::ColumnType {
ColumnType::Money(s) => sea_query::ColumnType::Money(s),
ColumnType::Json => sea_query::ColumnType::Json,
ColumnType::JsonBinary => sea_query::ColumnType::JsonBinary,
ColumnType::Custom(s) | ColumnType::Enum(s, _) => {
ColumnType::Custom(s) => {
sea_query::ColumnType::Custom(sea_query::SeaRc::new(sea_query::Alias::new(&s)))
}
ColumnType::Uuid => sea_query::ColumnType::Uuid,
ColumnType::Enum(name, variants) => sea_query::ColumnType::Enum(name, variants),
}
}
}
Expand Down Expand Up @@ -398,6 +399,7 @@ impl From<sea_query::ColumnType> for ColumnType {
sea_query::ColumnType::JsonBinary => Self::JsonBinary,
sea_query::ColumnType::Custom(s) => Self::Custom(s.to_string()),
sea_query::ColumnType::Uuid => Self::Uuid,
sea_query::ColumnType::Enum(name, variants) => Self::Enum(name, variants),
_ => unimplemented!(),
}
}
Expand Down
14 changes: 5 additions & 9 deletions tests/common/features/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,24 +127,17 @@ pub async fn create_byte_primary_key_table(db: &DbConn) -> Result<ExecResult, Db

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 create_enum_stmts = match db_backend {
DbBackend::MySql | DbBackend::Sqlite => Vec::new(),
DbBackend::Postgres => vec![Type::create()
.as_enum(tea_enum.clone())
.as_enum(Alias::new("tea"))
.values(vec![Alias::new("EverydayTea"), Alias::new("BreakfastTea")])
.to_owned()],
};

create_enum(db, &create_enum_stmts, ActiveEnum).await?;

let mut tea_col = ColumnDef::new(active_enum::Column::Tea);
match db_backend {
DbBackend::MySql => tea_col.custom(Alias::new("ENUM('EverydayTea', 'BreakfastTea')")),
DbBackend::Sqlite => tea_col.text(),
DbBackend::Postgres => tea_col.custom(tea_enum),
};
let create_table_stmt = sea_query::Table::create()
.table(active_enum::Entity)
.col(
Expand All @@ -156,7 +149,10 @@ 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(&mut tea_col)
.col(
ColumnDef::new(active_enum::Column::Tea)
.enumeration("tea", vec!["EverydayTea", "BreakfastTea"]),
)
.to_owned();

create_table(db, &create_table_stmt, ActiveEnum).await
Expand Down