Skip to main content

rbatis_plus_macros/
lib.rs

1//! Procedural macros for RBatis-Plus.
2//!
3//! 核心宏:`#[derive(TableName)]` — 一次性生成所有元数据:
4//! 表名、列访问器、主键、乐观锁、逻辑删除、字段填充。
5
6use proc_macro::TokenStream;
7use quote::quote;
8use syn::{parse_macro_input, DeriveInput, Meta, Fields};
9
10/// `#[derive(TableName)]` — 表级元数据 + 列访问器 + 字段注解处理。
11///
12/// # struct 属性
13/// - `#[table_name = "sys_user"]` — 表名
14///
15/// # 字段属性
16/// - `#[table_id]` — 主键
17/// - `#[table_id(type = "auto")]` — 主键生成策略(auto/input/assign_id/assign_uuid/none)
18/// - `#[table_field(column = "db_name")]` — 自定义列名
19/// - `#[version]` — 乐观锁版本列
20/// - `#[table_logic]` — 逻辑删除列
21/// - `#[table_logic(value = "1", not_value = "0")]` — 逻辑删除值
22/// - `#[field_fill = "insert"]` — 自动填充(default/insert/update/insert_update)
23/// - `#[encrypted(algorithm = "AES", column = "enc_name")]` — 加密字段
24/// - `#[signature(order = 1, stored = true)]` — 签名字段
25/// - `#[i18n(key = "user.name")]` — 国际化字段
26#[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    // ── 只支持 struct,enum/union 直接报错 ──
36    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    // ── 提取 struct 级属性 ──
44    let table_name = extract_string_attr(&input.attrs, "table_name")
45        .unwrap_or_else(|| to_snake_case(&name.to_string()));
46
47    // ── 扫描字段 ──
48    let mut column_methods = Vec::new();
49    let mut column_consts = Vec::new();
50
51    // 主键信息
52    let mut id_column = "id".to_string();
53    let mut id_type_str = "none".to_string();
54
55    // 乐观锁
56    let mut has_version = false;
57    let mut version_column = String::new();
58
59    // 逻辑删除
60    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                // 生成列访问器
73                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                // ── 检查字段属性 ──
91
92                // #[table_id] 或 #[table_id(type = "auto")]
93                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                // #[version]
101                if has_attr(&field.attrs, "version") {
102                    has_version = true;
103                    version_column = db_column.clone();
104                }
105
106                // #[table_logic] 或 #[table_logic(value = "1", not_value = "0")]
107                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    // ── 生成 IdType 枚举匹配 ──
122    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    // ── 生成 TableName impl ──
131    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    // ── 生成 TableId impl ──
138    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    // ── 生成 Version impl ──
147    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    // ── 生成 TableLogic impl ──
159    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    // ── 组装 ──
179    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
193// ═══════════════════════════════════════════════════════════════════════════
194// 辅助函数
195// ═══════════════════════════════════════════════════════════════════════════
196
197/// 提取 `#[attr_name = "value"]`。
198fn 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
211/// 检查字段是否有某个属性(`#[attr_name]` 或 `#[attr_name(...)]`)。
212fn has_attr(attrs: &[syn::Attribute], attr_name: &str) -> bool {
213    attrs.iter().any(|a| a.path().is_ident(attr_name))
214}
215
216/// 提取嵌套属性 `#[attr_name(key = "value")]`。
217fn 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                    // 无论是否匹配 key,都需要消耗值以正确前进到下一个参数
224                    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                        // 跳过不匹配的值(消耗掉以继续解析下一个参数)
232                        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
245/// 从字段提取数据库列名(`#[table_field(column = "xxx")]` 或字段名原样)。
246fn 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
251/// PascalCase → snake_case。
252fn 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}