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

Remove sea-query's Iden macro; introduce DeriveIden #1755

Merged
merged 3 commits into from
Jul 13, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
28 changes: 28 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -548,6 +548,34 @@ impl ColumnTrait for Column {
* Replace the use of `SeaRc<T>` where `T` isn't `dyn Iden` with `RcOrArc<T>` https://github.com/SeaQL/sea-orm/pull/1661
* Enabled `hashable-value` feature in SeaQuery, thus `Value::Float(NaN) == Value::Float(NaN)` would be true https://github.com/SeaQL/sea-orm/pull/1728, https://github.com/SeaQL/sea-orm/pull/1743
* The `DeriveActiveEnum` derive macro no longer provide `std::fmt::Display` implementation for the enum. You need to derive an extra `DeriveDisplay` macro alongside with `DeriveActiveEnum` derive macro. https://github.com/SeaQL/sea-orm/pull/1726
* `sea-query/derive` is no longer enabled by `sea-orm`, as such, `Iden` no longer works as a derive macro (it's still a trait). Instead, we are shipping a new macro `DeriveIden`:
```rust
// then:

#[derive(Iden)]
#[iden = "category"]
pub struct CategoryEnum;

#[derive(Iden)]
pub enum Tea {
Table,
#[iden = "EverydayTea"]
EverydayTea,
}

// now:

#[derive(DeriveIden)]
#[sea_orm(iden = "category")]
pub struct CategoryEnum;

#[derive(DeriveIden)]
pub enum Tea {
Table,
#[sea_orm(iden = "EverydayTea")]
EverydayTea,
}
```

## 0.11.3 - 2023-04-24

Expand Down
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ tracing = { version = "0.1", default-features = false, features = ["attributes",
rust_decimal = { version = "1", default-features = false, optional = true }
bigdecimal = { version = "0.3", default-features = false, optional = true }
sea-orm-macros = { version = "0.12.0-rc.4", path = "sea-orm-macros", default-features = false, features = ["strum"] }
sea-query = { version = "0.29.0-rc.2", features = ["thread-safe", "hashable-value"] }
sea-query = { version = "0.29.0", default-features = false, features = ["thread-safe", "hashable-value", "backend-mysql", "backend-postgres", "backend-sqlite"] }
sea-query-binder = { version = "0.4.0-rc.2", default-features = false, optional = true }
strum = { version = "0.25", default-features = false }
serde = { version = "1.0", default-features = false }
Expand Down Expand Up @@ -74,7 +74,7 @@ default = [
"with-uuid",
"with-time",
]
macros = ["sea-orm-macros/derive", "sea-query/derive"]
macros = ["sea-orm-macros/derive"]
mock = []
with-json = ["serde_json", "sea-query/with-json", "chrono?/serde", "time?/serde", "uuid?/serde", "sea-query-binder?/with-json", "sqlx?/json"]
with-chrono = ["chrono", "sea-query/with-chrono", "sea-query-binder?/with-chrono", "sqlx?/chrono"]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ impl MigrationTrait for Migration {
}
}

/// Learn more at https://docs.rs/sea-query#iden
#[derive(Iden)]
#[derive(DeriveIden)]
enum Posts {
Table,
Id,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ impl MigrationTrait for Migration {
}
}

/// Learn more at https://docs.rs/sea-query#iden
#[derive(Iden)]
#[derive(DeriveIden)]
enum Posts {
Table,
Id,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ impl MigrationTrait for Migration {
}
}

/// Learn more at https://docs.rs/sea-query#iden
#[derive(Iden)]
#[derive(DeriveIden)]
enum Posts {
Table,
Id,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ impl MigrationTrait for Migration {
}
}

/// Learn more at https://docs.rs/sea-query#iden
#[derive(Iden)]
#[derive(DeriveIden)]
enum Notes {
Table,
Id,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ impl MigrationTrait for Migration {
}
}

/// Learn more at https://docs.rs/sea-query#iden
#[derive(Iden)]
#[derive(DeriveIden)]
enum Posts {
Table,
Id,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ impl MigrationTrait for Migration {
}
}

/// Learn more at https://docs.rs/sea-query#iden
#[derive(Iden)]
#[derive(DeriveIden)]
enum Posts {
Table,
Id,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ impl MigrationTrait for Migration {
}
}

/// Learn more at https://docs.rs/sea-query#iden
#[derive(Iden)]
#[derive(DeriveIden)]
enum Posts {
Table,
Id,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ impl MigrationTrait for Migration {
}
}

/// Learn more at https://docs.rs/sea-query#iden
#[derive(Iden)]
#[derive(DeriveIden)]
enum Posts {
Table,
Id,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ impl MigrationTrait for Migration {
}
}

/// Learn more at https://docs.rs/sea-query#iden
#[derive(Iden)]
#[derive(DeriveIden)]
enum Posts {
Table,
Id,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ impl MigrationTrait for Migration {
}
}

/// Learn more at https://docs.rs/sea-query#iden
#[derive(Iden)]
#[derive(DeriveIden)]
enum Posts {
Table,
Id,
Expand Down
13 changes: 13 additions & 0 deletions issues/1473/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[workspace]
# A separate workspace

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

[dependencies.sea-orm]
path = "../../"
default-features = false
features = ["macros", "runtime-tokio-native-tls"]
16 changes: 16 additions & 0 deletions issues/1473/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
use sea_orm::{DeriveIden, Iden};

#[derive(DeriveIden)]
enum Character {
Table,
Id,
}

#[derive(DeriveIden)]
struct Glyph;

fn main() {
assert_eq!(Character::Table.to_string(), "character");
assert_eq!(Character::Id.to_string(), "id");
assert_eq!(Glyph.to_string(), "glyph");
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,7 @@ impl MigrationTrait for Migration {
}
}

/// Learn more at https://docs.rs/sea-query#iden
#[derive(Iden)]
#[derive(DeriveIden)]
enum Post {
Table,
Id,
Expand Down
151 changes: 151 additions & 0 deletions sea-orm-macros/src/derives/derive_iden.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
use heck::ToSnakeCase;
use proc_macro2::{self, TokenStream};
use quote::{quote, quote_spanned};
use syn::{
punctuated::Punctuated, DataEnum, DataStruct, DeriveInput, Expr, Fields, LitStr, Variant,
};

fn must_be_valid_iden(name: &str) -> bool {
// can only begin with [a-z_]
name.chars()
.take(1)
.all(|c| c == '_' || c.is_ascii_alphabetic())
&& name.chars().all(|c| c == '_' || c.is_ascii_alphanumeric())
}

fn impl_iden_for_unit_struct(
ident: &proc_macro2::Ident,
new_iden: &str,
) -> proc_macro2::TokenStream {
let prepare = if must_be_valid_iden(new_iden) {
quote! {
fn prepare(&self, s: &mut dyn ::std::fmt::Write, q: sea_orm::sea_query::Quote) {
write!(s, "{}", q.left()).unwrap();
self.unquoted(s);
write!(s, "{}", q.right()).unwrap();
}
}
} else {
quote! {}
};
quote! {
impl sea_orm::sea_query::Iden for #ident {
#prepare

fn unquoted(&self, s: &mut dyn ::std::fmt::Write) {
write!(s, #new_iden).unwrap();
}
}
}
}

fn impl_iden_for_enum(
ident: &proc_macro2::Ident,
variants: Punctuated<Variant, syn::token::Comma>,
) -> proc_macro2::TokenStream {
let variants = variants.iter();
let mut all_valid = true;

let match_pair: Vec<TokenStream> = variants
.map(|v| {
let var_ident = &v.ident;
let var_name = if var_ident == "Table" {
ident
} else {
var_ident
};
let mut var_name = var_name.to_string().to_snake_case();
v.attrs
.iter()
.filter(|attr| attr.path().is_ident("sea_orm"))
.try_for_each(|attr| {
attr.parse_nested_meta(|meta| {
if meta.path.is_ident("iden") {
let litstr: LitStr = meta.value()?.parse()?;
var_name = litstr.value();
all_valid &= must_be_valid_iden(var_name.as_str());
} else {
// Reads the value expression to advance the parse stream.
// Some parameters do not have any value,
// so ignoring an error occurred here.
let _: Option<Expr> = meta.value().and_then(|v| v.parse()).ok();
}
Ok(())
})
})
.expect("something something");
quote! { Self::#var_ident => write!(s, "{}", #var_name).unwrap() }
})
.collect();

let match_arms: TokenStream = quote! { #(#match_pair),* };

let prepare = if all_valid {
quote! {
fn prepare(&self, s: &mut dyn ::std::fmt::Write, q: sea_orm::sea_query::Quote) {
write!(s, "{}", q.left()).unwrap();
self.unquoted(s);
write!(s, "{}", q.right()).unwrap();
}
}
} else {
quote! {}
};

quote! {
impl sea_orm::sea_query::Iden for #ident {
#prepare

fn unquoted(&self, s: &mut dyn ::std::fmt::Write) {
match self {
#match_arms
};
}
}
}
}

pub fn expand_derive_iden(input: DeriveInput) -> syn::Result<TokenStream> {
let DeriveInput { ident, data, .. } = input;

let mut new_iden: TokenStream = ident.to_string().to_snake_case().parse().unwrap();
input
.attrs
.iter()
.filter(|attr| attr.path().is_ident("sea_orm"))
.try_for_each(|attr| {
attr.parse_nested_meta(|meta| {
if meta.path.is_ident("iden") {
let litstr: LitStr = meta.value()?.parse()?;
new_iden = syn::parse_str::<TokenStream>(&litstr.value())?;
} else {
// Reads the value expression to advance the parse stream.
// Some parameters do not have any value,
// so ignoring an error occurred here.
let _: Option<Expr> = meta.value().and_then(|v| v.parse()).ok();
}
Ok(())
})
})?;

// Currently we only support enums and unit structs
match data {
syn::Data::Enum(DataEnum { variants, .. }) => {
if variants.is_empty() {
Ok(TokenStream::new())
} else {
Ok(impl_iden_for_enum(&ident, variants))
}
}
syn::Data::Struct(DataStruct {
fields: Fields::Unit,
..
}) => Ok(impl_iden_for_unit_struct(
&ident,
new_iden.to_string().as_str(),
)),
_ => Ok(quote_spanned! {
ident.span() => compile_error!("you can only derive DeriveIden on unit struct or enum");
}),
}
}
2 changes: 2 additions & 0 deletions sea-orm-macros/src/derives/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ mod active_model;
mod active_model_behavior;
mod attributes;
mod column;
mod derive_iden;
mod entity;
mod entity_model;
mod from_query_result;
Expand All @@ -24,6 +25,7 @@ pub use active_enum_display::*;
pub use active_model::*;
pub use active_model_behavior::*;
pub use column::*;
pub use derive_iden::*;
pub use entity::*;
pub use entity_model::*;
pub use from_query_result::*;
Expand Down
Loading