auto_field_macros is a procedural macro library developed in Rust, designed specifically for the auto_field_trait library, providing macro support for automatic field processing. This library simplifies the code writing for developers when using the auto_field_trait library by automatically generating the required trait implementations and field processing logic through macro definitions.
- Automatic ActiveModelBehavior Implementation: Automatically handles field filling logic
- Automatic QueryExtensions Implementation: Provides convenient query methods
- Automatic CustomizationExt Implementation: Supports soft delete and batch operations
- Flexible Configuration Options: Select required features through attribute configuration
- Supports Multiple Field Types:
- Snowflake ID generation
- Timestamp management
- Audit logging
- Tenant support
- Version control
- Soft delete
- Language: Rust
- Core Dependencies:
proc-macro2:Procedural macro supportquote:Rust code generationsyn:Rust syntax analysis
Add dependencies to your Cargo.toml file:
dependencies =
auto_field_trait = { version = "0.1.3", git = "https://github.com/tttq/auto_field_trait.git", features = ["postgres", "with-web"] }
sea-orm = "0.12"
proc-macro-dependencies =
auto_field_macros = { version = "0.1.3", git = "https://github.com/tttq/auto_field_macros.git" }The auto_field_macros library does not require additional configuration files, only need to be configured through attributes when using it.
- Import Dependencies:
use auto_field_macros::AutoField;
use auto_field_trait::QueryExtensions;
use auto_field_trait::CustomizationExt;- Define Entity and Use Macro:
use sea_orm::entity::prelude::*;
use auto_field_macros::AutoField;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, AutoField)]
#[sea_orm(table_name = "users")]
#[auto_field(snowflake_id, timestamps, audit, tenant, version, soft_delete)]
pub struct Model {
#[sea_orm(primary_key)]
pub id: String,
pub name: String,
pub email: String,
pub create_time: Option<DateTime<Utc>>,
pub update_time: Option<DateTime<Utc>>,
pub create_by: Option<String>,
pub create_id: Option<String>,
pub update_by: Option<String>,
pub update_id: Option<String>,
pub tenant_id: Option<String>,
pub tenant_name: Option<String>,
pub version: Option<i32>,
pub delete_flag: Option<i32>,
}- Macro Configuration Options:
The auto_field macro supports the following configuration options:
snowflake_id:Enable snowflake ID automatic generationtimestamps:Enable timestamp automatic fillingaudit:Enable audit field automatic fillingtenant:Enable tenant field automatic fillingversion:Enable version number automatic managementsoft_delete:Enable soft delete functionality
You can configure it in the following ways:
// Way 1: Enable all features
#[auto_field(snowflake_id, timestamps, audit, tenant, version, soft_delete)]
// Way 2: Enable partial features
#[auto_field(timestamps, audit)]
// Way 3: Use key-value form
#[auto_field(snowflake_id = true, timestamps = true)]- Use Automatically Generated Functions:
// Use QueryExtensions
let users = User::find_not_deleted().all(db).await?;
let users = User::find_by_tenant_id("tenant_123").all(db).await?;
// Use CustomizationExt
User::soft_delete(db, "user_789").await?;
User::soft_delete_many(db, &["user_101", "user_102"]).await?;
// Use batch_update
let update_many = User::batch_update()
.col_expr(User::Column::Name, Expr::value("new_name"))
.filter(User::Column::Id.eq("user_123"))
.exec(db)
.await?;
// Use batch_insert_many
let users = vec![
UserActiveModel {
name: ActiveValue::Set("user_1".to_string()),
email: ActiveValue::Set("user_1@example.com".to_string()),
..Default::default()
},
UserActiveModel {
name: ActiveValue::Set("user_2".to_string()),
email: ActiveValue::Set("user_2@example.com".to_string()),
..Default::default()
},
];
let insert_result = User::batch_insert_many(users)
.exec(db)
.await?;- Conditional Configuration:
You can select the features you need according to your requirements, for example, only enable timestamps and soft delete:
#[auto_field(timestamps, soft_delete)]- Validation Configuration:
The macro will automatically validate the validity of the configuration, for example, if you enable the audit feature, you must also enable the timestamps feature, otherwise a compilation error will occur.
- Custom Field Names:
Currently, the auto_field_macros library uses fixed field names, such as:
create_time:Creation timeupdate_time:Update timecreate_by:Creatorcreate_id:Creator IDupdate_by:Updaterupdate_id:Updater IDtenant_id:Tenant IDtenant_name:Tenant nameversion:Version numberdelete_flag:Delete flag
If you need to customize field names, you can modify the source code of the auto_field_trait library.
- Rust Version: 1.65.0 or higher
- SeaORM Version: 0.12.x
- auto_field_trait Version: Matching the
auto_field_macrosversion
- Currently only supports SeaORM framework
- Only supports fixed field names, does not support custom field names
- Must be used with the
auto_field_traitlibrary - Some features have dependencies, for example, the
auditfeature depends on thetimestampsfeature
-
Issue: Compilation error, missing dependencies Solution: Ensure that all dependencies are correctly installed, including
auto_field_traitandsea-orm -
Issue: Compilation error, invalid configuration Solution: Check if the macro configuration is correct, for example, the
auditfeature must also enable thetimestampsfeature -
Issue: Auto fields are not being filled correctly Solution: Ensure that the
HookedSeaOrmPluginplugin and context getter are correctly registered
auto_field_macros/
├── src/
│ └── lib.rs # Library entry file, containing macro definitions
├── Cargo.toml # Dependency configuration
└── README.md # Project documentation
| File/Folder | Purpose |
|---|---|
src/lib.rs |
Library entry point, containing the definition and implementation of the AutoField macro |
Cargo.toml |
Project dependencies and build configuration |
README.md |
Project documentation, including usage instructions and API reference |
#[derive(Debug, Clone, Default)]
struct AutoFieldConfig {
pub snowflake_id: bool,
pub timestamps: bool,
pub audit: bool,
pub tenant: bool,
pub version: bool,
pub soft_delete: bool,
}- Parse Attribute Configuration: Parse the
#[auto_field(...)]attribute and generate a configuration structure - Validate Configuration: Validate the validity of the configuration, for example, the
auditfeature must also enable thetimestampsfeature - Generate ActiveModelBehavior Implementation: Automatically handle field filling logic
- Generate QueryExtensions Implementation: Provide convenient query methods
- Generate CustomizationExt Implementation: Support soft delete and batch operations