Rbatis 4.6 - High-Performance Rust ORM Framework Upgrade

⚓ rust    📅 2025-05-25    👤 surdeus    👁️ 3      

surdeus

Warning

This post was published 35 days ago. The information described in this article may have changed.

Rbatis 4.6 - High-Performance Rust ORM Framework Upgrade

Rbatis 4.6 brings a more concise API design, improved performance, and additional practical features, aiming to be the most efficient and user-friendly ORM framework in the Rust ecosystem. As a compile-time code generation ORM tool, Rbatis perfectly balances development efficiency, runtime performance, and stability, while supporting multiple databases and connection pool implementations.

Core Advantages

1. Outstanding Performance

  • Compile-time Dynamic SQL Generation: Converts SQL statements to Rust code during compilation, avoiding runtime overhead
  • Based on Tokio Async Model: Fully utilizes Rust's async features to enhance concurrency performance
  • Efficient Connection Pools: Built-in multiple connection pool implementations, optimizing

2. Reliability Guarantees

  • Rust Safety Features: Leverages Rust's ownership and borrowing checks to ensure memory and thread safety
  • Unified Parameter Placeholders: Uses ? as a unified placeholder, supporting all drivers
  • Two Replacement Modes: Precompiled #{arg} and direct replacement ${arg}, meeting different scenario requirements

3. Development Efficiency Improvements(doc)

  • Minimal CRUD API: Version 4.6 redesigned the API, requiring only one line of code to generate common CRUD operations
  • Multiple SQL Building Methods:
    • py_sql: Python-style dynamic SQL with support for if, for, choose/when/otherwise, bind, trim structures and collection operations
    • html_sql: MyBatis-like XML templates with familiar tag structure, declarative SQL building
    • Raw SQL: Direct use of SQL statements
  • Powerful Mapping Functionality: Automatic mapping between database tables and Rust structures
  • Interceptor Plugin: Extensible interceptor mechanism supporting logging, read/write separation, and more
  • Table Sync Plugin: Automatically create/update table structures

4. Ultimate Extensibility

  • Multiple Database Support: MySQL, PostgreSQL, SQLite, MSSQL, MariaDB, TiDB, CockroachDB, Oracle, TDengine, and more
  • Custom Driver Interface: Implement a simple interface to add support for new databases
  • Multiple Connection Pools: FastPool (default), Deadpool, MobcPool
  • Compatible with Various Web Frameworks: Seamlessly integrates with ntex, actix-web, axum, hyper, rocket, tide, warp, salvo, and more

Important Updates in Version 4.6

  1. Simplified CRUD API:

    • Version 4.6 greatly simplifies the CRUD macro API, now requiring only one line of code to generate all common CRUD methods
    • Previously separate methods have been consolidated into more flexible and intuitive methods
    // Generate all CRUD operations with just one line of code
    crud!(BizActivity{});
    
    // Or specify a table name
    crud!(BizActivity{}, "activity");
    
  2. More Flexible Query Conditions:

    • Use the value! macro to quickly build query conditions
    • Support for various complex conditions: equality queries, fuzzy queries, range queries, IN queries, etc.
    // Equality query
    let data = BizActivity::select_by_map(&rb, value!{"id":"2","name":"Activity 2"}).await;
    
    // Fuzzy query
    let data = BizActivity::select_by_map(&rb, value!{"name like ":"%Activity%"}).await;
    
    // Greater than query
    let data = BizActivity::select_by_map(&rb, value!{"id > ":"2"}).await;
    
    // IN query
    let data = BizActivity::select_by_map(&rb, value!{"id": &["1", "2", "3"]}).await;
    

    Important: When using an empty array with IN queries, Rbatis intelligently handles this case. Instead of generating invalid SQL like select * from biz_activity where id in [], it will generate a clean query without the IN condition: select * from biz_activity. This prevents SQL syntax errors and ensures your application continues to function correctly even with empty array inputs.

  3. Enhanced Plugin System:

    • Interceptor plugins: Support for logging, read/write separation, returning IDs, and other advanced features
    • Table sync plugin: Automatically create and update table structures, simplifying the development process
  4. Optimized Performance:

    • More efficient connection pool management
    • Improved memory usage and SQL building process

Quick Start

  1. Add Dependencies
[dependencies]
rbs = { version = "4.6"}
rbatis = { version = "4.6"}
# Choose database driver
rbdc-sqlite = { version = "4.6" }
# rbdc-mysql = { version = "4.6" }
# rbdc-pg = { version = "4.6" }
# rbdc-mssql = { version = "4.6" }

# Other dependencies
serde = { version = "1", features = ["derive"] }
tokio = { version = "1", features = ["full"] }
log = "0.4"
fast_log = "1.6"
  1. Define Entity
use rbatis::rbdc::datetime::DateTime;
use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BizActivity {
    pub id: Option<String>,
    pub name: Option<String>,
    pub status: Option<i32>,
    pub create_time: Option<DateTime>,
    pub additional_field: Option<String>,
}

// Automatically generate CRUD methods
crud!(BizActivity{});
  1. Initialize and Use
#[tokio::main]
async fn main() {
    // Configure logging
    fast_log::init(fast_log::Config::new().console()).expect("rbatis init fail");
    
    // Initialize rbatis
    let rb = RBatis::new();
    
    // Connect to database
    rb.init(SqliteDriver {}, "sqlite://target/sqlite.db").unwrap();
    
    // Insert data
    let activity = BizActivity {
        id: Some("1".into()),
        name: Some("Test Activity".into()),
        status: Some(1),
        create_time: Some(DateTime::now()),
        additional_field: Some("Additional Information".into()),
    };
    let data = BizActivity::insert(&rb, &activity).await;

    // Query using map conditions
    let data = BizActivity::select_by_map(&rb, value!{"name like ":"%Activity%"}).await;
    
    // Batch delete
    let data = BizActivity::delete_by_map(&rb, value!{"id": &["1", "2", "3"]}).await;
    
    // Empty array handling demonstration
    let empty_ids: Vec<String> = vec![];
    let data = BizActivity::select_by_map(&rb, value!{"id": &empty_ids}).await;
    // This generates: "SELECT * FROM biz_activity" instead of invalid SQL
}
  1. Using Dynamic SQL
// HTML style
#[html_sql(r#"
<select id="select_by_condition">
    `select * from activity`
    <where>
        <if test="name != ''">
            ` and name like #{name}`
        </if>
        <choose>
            <when test="status >= 0">
                ` and status = #{status}`
            </when>
            <otherwise>
                ` and status = 0`
            </otherwise>
        </choose>
    </where>
</select>"#)]
async fn select_by_condition(
    rb: &dyn Executor,
    name: &str,
    status: i32,
) -> rbatis::Result<Vec<Activity>> {
    impled!()
}

// Python style
#[py_sql(r#"
`select * from activity where delete_flag = 0`
if name != '':
  ` and name=#{name}`
if !ids.is_empty():
  ` and id in `
  ${ids.sql()}"#)]
async fn py_select(rb: &dyn Executor, name: &str, ids: &[i32]) -> Result<Vec<Activity>, Error> {
    impled!()
}

Supported Database Drivers

Rbatis 4.6 supports multiple databases, including:

  • MySQL / MariaDB / TiDB: rbdc-mysql
  • PostgreSQL / CockroachDB: rbdc-pg
  • SQLite: rbdc-sqlite
  • Microsoft SQL Server: rbdc-mssql
  • Oracle: rbdc-oracle
  • TDengine: rbdc-tdengine

Conclusion

Rbatis 4.6 maintains high performance while further optimizing API design, making the development experience smoother and more intuitive. Whether it's simple CRUD operations or complex dynamic SQL building, Rbatis provides elegant and efficient solutions. As an important ORM framework in the Rust ecosystem, Rbatis continues to evolve and improve, providing Rust developers with better database access tools.

Start using Rbatis 4.6 now and experience a new way of Rust ORM development!

1 post - 1 participant

Read full topic

🏷️ rust_feed