rbatis_plus_macros/
lib.rs1use proc_macro::TokenStream;
7use quote::quote;
8use syn::{parse_macro_input, DeriveInput, Meta, Fields};
9
10#[proc_macro_derive(TableName, attributes(
27 table_name, table_id, table_field, version, table_logic,
28 field_fill, encrypted, signature, i18n
29))]
30pub fn derive_table_name(input: TokenStream) -> TokenStream {
31 let input = parse_macro_input!(input as DeriveInput);
32 let name = &input.ident;
33 let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
34
35 match &input.data {
37 syn::Data::Struct(_) => {},
38 _ => return syn::Error::new_spanned(name, "derive(TableName) 仅支持 struct,不支持 enum 或 union")
39 .to_compile_error()
40 .into(),
41 }
42
43 let table_name = extract_string_attr(&input.attrs, "table_name")
45 .unwrap_or_else(|| to_snake_case(&name.to_string()));
46
47 let mut column_methods = Vec::new();
49 let mut column_consts = Vec::new();
50
51 let mut id_column = "id".to_string();
53 let mut id_type_str = "none".to_string();
54
55 let mut has_version = false;
57 let mut version_column = String::new();
58
59 let mut has_logic = false;
61 let mut logic_column = String::new();
62 let mut logic_value = "0".to_string();
63 let mut not_logic_value = "1".to_string();
64
65 if let syn::Data::Struct(ref data_struct) = input.data {
66 if let Fields::Named(ref fields) = data_struct.fields {
67 for field in fields.named.iter() {
68 let field_name = field.ident.as_ref().unwrap();
69 let field_type = &field.ty;
70 let db_column = extract_field_column(field);
71
72 let method_name = syn::Ident::new(
74 &format!("column_{}", field_name), field_name.span(),
75 );
76 let const_name = syn::Ident::new(
77 &format!("COLUMN_{}", field_name.to_string().to_uppercase()),
78 field_name.span(),
79 );
80
81 column_methods.push(quote! {
82 pub fn #method_name() -> rbatis_plus_core::conditions::query::Column<#field_type> {
83 rbatis_plus_core::conditions::query::Column::new(#db_column)
84 }
85 });
86 column_consts.push(quote! {
87 pub const #const_name: &'static str = #db_column;
88 });
89
90 if has_attr(&field.attrs, "table_id") {
94 id_column = db_column.clone();
95 if let Some(t) = extract_nested_string(&field.attrs, "table_id", "type") {
96 id_type_str = t;
97 }
98 }
99
100 if has_attr(&field.attrs, "version") {
102 has_version = true;
103 version_column = db_column.clone();
104 }
105
106 if has_attr(&field.attrs, "table_logic") {
108 has_logic = true;
109 logic_column = db_column.clone();
110 if let Some(v) = extract_nested_string(&field.attrs, "table_logic", "value") {
111 logic_value = v;
112 }
113 if let Some(v) = extract_nested_string(&field.attrs, "table_logic", "not_value") {
114 not_logic_value = v;
115 }
116 }
117 }
118 }
119 }
120
121 let id_type_expr = match id_type_str.to_lowercase().as_str() {
123 "auto" => quote! { rbatis_plus_core::derive::IdType::Auto },
124 "input" => quote! { rbatis_plus_core::derive::IdType::Input },
125 "assign_id" => quote! { rbatis_plus_core::derive::IdType::AssignId },
126 "assign_uuid" => quote! { rbatis_plus_core::derive::IdType::AssignUuid },
127 _ => quote! { rbatis_plus_core::derive::IdType::None },
128 };
129
130 let table_name_impl = quote! {
132 impl #impl_generics rbatis_plus_core::derive::TableName for #name #ty_generics #where_clause {
133 fn table_name() -> &'static str { #table_name }
134 }
135 };
136
137 let id_col_str = id_column.clone();
139 let table_id_impl = quote! {
140 impl #impl_generics rbatis_plus_core::derive::TableId for #name #ty_generics #where_clause {
141 fn id_type() -> rbatis_plus_core::derive::IdType { #id_type_expr }
142 fn id_column() -> &'static str { #id_col_str }
143 }
144 };
145
146 let version_impl = if has_version {
148 let vc = version_column.clone();
149 quote! {
150 impl #impl_generics rbatis_plus_core::derive::Version for #name #ty_generics #where_clause {
151 fn version_column() -> &'static str { #vc }
152 }
153 }
154 } else {
155 quote! {}
156 };
157
158 let logic_impl = if has_logic {
160 let lc = logic_column.clone();
161 let lv = logic_value.clone();
162 let nlv = not_logic_value.clone();
163 quote! {
164 impl #impl_generics rbatis_plus_core::derive::TableLogic for #name #ty_generics #where_clause {
165 fn logic_column() -> &'static str { #lc }
166 fn logic_delete_value() -> Option<&'static str> {
167 if #lv.is_empty() { None } else { Some(#lv) }
168 }
169 fn logic_not_delete_value() -> Option<&'static str> {
170 if #nlv.is_empty() { None } else { Some(#nlv) }
171 }
172 }
173 }
174 } else {
175 quote! {}
176 };
177
178 let expanded = quote! {
180 #table_name_impl
181 #table_id_impl
182 #version_impl
183 #logic_impl
184
185 impl #impl_generics #name #ty_generics #where_clause {
186 #(#column_methods)*
187 #(#column_consts)*
188 }
189 };
190 expanded.into()
191}
192
193fn extract_string_attr(attrs: &[syn::Attribute], attr_name: &str) -> Option<String> {
199 for attr in attrs {
200 if attr.path().is_ident(attr_name) {
201 if let Meta::NameValue(mnv) = &attr.meta {
202 if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(s), .. }) = &mnv.value {
203 return Some(s.value());
204 }
205 }
206 }
207 }
208 None
209}
210
211fn has_attr(attrs: &[syn::Attribute], attr_name: &str) -> bool {
213 attrs.iter().any(|a| a.path().is_ident(attr_name))
214}
215
216fn extract_nested_string(attrs: &[syn::Attribute], attr_name: &str, key: &str) -> Option<String> {
218 for attr in attrs {
219 if attr.path().is_ident(attr_name) {
220 if let Meta::List(list) = &attr.meta {
221 let mut result = None;
222 let _ = list.parse_nested_meta(|meta| {
223 if meta.path.is_ident(key) {
225 if let Ok(value) = meta.value() {
226 if let Ok(lit) = value.parse::<syn::LitStr>() {
227 result = Some(lit.value());
228 }
229 }
230 } else {
231 let _ = meta.value().and_then(|v| v.parse::<syn::Expr>());
233 }
234 Ok(())
235 });
236 if result.is_some() {
237 return result;
238 }
239 }
240 }
241 }
242 None
243}
244
245fn extract_field_column(field: &syn::Field) -> String {
247 extract_nested_string(&field.attrs, "table_field", "column")
248 .unwrap_or_else(|| field.ident.as_ref().unwrap().to_string())
249}
250
251fn to_snake_case(s: &str) -> String {
253 let mut result = String::new();
254 for (i, c) in s.chars().enumerate() {
255 if c.is_uppercase() {
256 if i > 0 { result.push('_'); }
257 result.extend(c.to_lowercase());
258 } else {
259 result.push(c);
260 }
261 }
262 result
263}