Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Compile Time Async Dynamic SQL ORM

License

NotificationsYou must be signed in to change notification settings

rbatis/rbatis

Repository files navigation

Website |Showcase |Examples

Build Statusdoc.rsunsafe forbiddencodecovGitHub releasediscussions

Introduction

Rbatis is a high-performance ORM framework for Rust based on compile-time code generation. It perfectly balances development efficiency, performance, and stability, functioning as both an ORM and a dynamic SQL compiler.

AI-support

Core Advantages

1. High 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 database connection management

2. Reliability

  • 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

  • Powerful ORM Capabilities: Automatic mapping between database tables and Rust structures
  • Multiple SQL Building Methods:
    • py_sql: Python-style dynamic SQL withif,for,choose/when/otherwise,bind,trim structures and collection operations (.sql(),.csv())
    • html_sql: MyBatis-like XML templates with familiar tag structure (<if>,<where>,<set>,<foreach>), declarative SQL building, and automatic handling of SQL fragments without requiring CDATA
    • Raw SQL: Direct SQL statements
  • CRUD Macros: Generate common CRUD operations with a single line of code
  • Interceptor Plugin:Custom extension functionality
  • Table Sync Plugin:Automatically create/update table structures

4. Extensibility

  • Multiple Database Support: MySQL, PostgreSQL, SQLite, MSSQL, MariaDB, TiDB, CockroachDB, Oracle, TDengine, etc.
  • 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

Supported Database Drivers

Database (crates.io)GitHub Link
MySQLrbatis/rbdc-mysql
PostgreSQLrbatis/rbdc-pg
SQLiterbatis/rbdc-sqlite
MSSQLrbatis/rbdc-mssql
MariaDBrbatis/rbdc-mysql
TiDBrbatis/rbdc-mysql
CockroachDBrbatis/rbdc-pg
Oraclechenpengfan/rbdc-oracle
TDenginetdcare/rbdc-tdengine

Supported Connection Pools

Connection Pool (crates.io)GitHub Link
FastPool (default)rbatis/fast_pool
Deadpoolrbatis/rbdc-pool-deadpool
MobcPoolrbatis/rbdc-pool-mobc

Supported Data Types

Data TypeSupport
Option
Vec
HashMap
i32, i64, f32, f64, bool, String, and other Rust base types
rbatis::rbdc::types::{Bytes, Date, DateTime, Time, Timestamp, Decimal, Json}
rbatis::plugin::page::{Page, PageRequest}
rbs::Value
serde_json::Value and other serde types
Driver-specific types from rbdc-mysql, rbdc-pg, rbdc-sqlite, rbdc-mssql

Member crates

crateGitHub Link
rbdcrbdc
rbsrbs

How Rbatis Works

Rbatis uses compile-time code generation through therbatis-codegen crate, which means:

  1. Zero Runtime Overhead: Dynamic SQL is converted to Rust code during compilation, not at runtime. This provides performance similar to handwritten code.

  2. Compilation Process:

    • Lexical Analysis: Handled byfunc.rs inrbatis-codegen using Rust'ssyn andquote crates
    • Syntax Parsing: Performed byparser_html andparser_pysql modules inrbatis-codegen
    • Abstract Syntax Tree: Built using structures defined in thesyntax_tree package inrbatis-codegen
    • Intermediate Code Generation: Executed byfunc.rs, which contains all the code generation functions
  3. Build Process Integration: The entire process runs during thecargo build phase as part of Rust's procedural macro compilation. The generated code is returned to the Rust compiler for LLVM compilation to produce machine code.

  4. Dynamic SQL Without Runtime Cost: Unlike most ORMs that interpret dynamic SQL at runtime, Rbatis performs all this work at compile-time, resulting in efficient and type-safe code.

Performance Benchmarks

---- bench_raw stdout ----(windows/SingleThread)Time: 52.4187ms ,each:524 ns/opQPS: 1906435 QPS/s---- bench_select stdout ----(macos-M1Cpu/SingleThread)Time: 112.927916ms ,each:1129 ns/opQPS: 885486 QPS/s---- bench_insert stdout ----(macos-M1Cpu/SingleThread)Time: 346.576666ms ,each:3465 ns/opQPS: 288531 QPS/s

Quick Start

Dependencies

# Cargo.toml[dependencies]rbs = {version ="4.6"}rbatis = {version ="4.6"}#driversrbdc-sqlite = {version ="4.6" }# rbdc-mysql = { version = "4.6" }# rbdc-pg = { version = "4.6" }# rbdc-mssql = { version = "4.6" }# Other dependenciesserde = {version ="1",features = ["derive"] }tokio = {version ="1",features = ["full"] }log ="0.4"fast_log ="1.6"

Basic Usage

use rbatis::rbdc::datetime::DateTime;use rbs::value;use rbatis::RBatis;use rbdc_sqlite::driver::SqliteDriver;use serde::{Deserialize,Serialize};use serde_json::json;#[derive(Clone,Debug,Serialize,Deserialize)]pubstructBizActivity{pubid:Option<String>,pubname:Option<String>,pubstatus:Option<i32>,pubcreate_time:Option<DateTime>,pubadditional_field:Option<String>,}// Automatically generate CRUD methodscrud!(BizActivity{});#[tokio::main]asyncfnmain(){// Configure logging    fast_log::init(fast_log::Config::new().console()).expect("rbatis init fail");// Initialize rbatislet rb =RBatis::new();// Connect to database    rb.init(SqliteDriver{},"sqlite://target/sqlite.db").unwrap();// Or other databases// rb.init(MysqlDriver{}, "mysql://root:123456@localhost:3306/test").unwrap();// rb.init(PgDriver{}, "postgres://postgres:123456@localhost:5432/postgres").unwrap();// Create datalet activity =BizActivity{id:Some("1".into()),name:Some("Test Activity".into()),status:Some(1),create_time:Some(DateTime::now()),additional_field:Some("Extra Information".into()),};// Insert datalet data =BizActivity::insert(&rb,&activity).await;// Batch insertlet data =BizActivity::insert_batch(&rb,&vec![BizActivity{            id:Some("2".into()),            name:Some("Activity 2".into()),            status:Some(1),            create_time:Some(DateTime::now()),            additional_field:Some("Info 2".into()),},BizActivity{            id:Some("3".into()),            name:Some("Activity 3".into()),            status:Some(1),            create_time:Some(DateTime::now()),            additional_field:Some("Info 3".into()),},],10).await;// Update by map conditionlet data =BizActivity::update_by_map(&rb,&activity,value!{"id":"1"}).await;// Query by map conditionlet data =BizActivity::select_by_map(&rb,value!{"id":"2","name":"Activity 2"}).await;// LIKE querylet data =BizActivity::select_by_map(&rb,value!{"name like ":"%Activity%"}).await;// Greater than querylet data =BizActivity::select_by_map(&rb,value!{"id > ":"2"}).await;// IN querylet data =BizActivity::select_by_map(&rb,value!{"id":&["1","2","3"]}).await;// Delete by map conditionlet data =BizActivity::delete_by_map(&rb,value!{"id":&["1","2","3"]}).await;}

Creating a Custom Database Driver

To implement a custom database driver for Rbatis:

  1. Define your driver project with dependencies:
[features]default = ["tls-rustls"]tls-rustls=["rbdc/tls-rustls"]tls-native-tls=["rbdc/tls-native-tls"][dependencies]rbs = {version ="4.6"}rbdc = {version ="4.6",default-features =false,optional =true }fastdate = {version ="0.3" }tokio = {version ="1",features = ["full"] }
  1. Implement the required traits:
use rbdc::db::{Driver,MetaData,Row,Connection,ConnectOptions,Placeholder};pubstructYourDriver{}implDriverforYourDriver{}pubstructYourMetaData{}implMetaDataforYourMetaData{}pubstructYourRow{}implRowforYourRow{}pubstructYourConnection{}implConnectionforYourConnection{}pubstructYourConnectOptions{}implConnectOptionsforYourConnectOptions{}pubstructYourPlaceholder{}implPlaceholderforYourPlaceholder{}// Then use your driver:#[tokio::main]asyncfnmain(){let rb = rbatis::RBatis::new();  rb.init(YourDatabaseDriver{},"database://username:password@host:port/dbname").unwrap();}

More Information

Contact Us

discussions

Donations or Contact

zxj347284221

WeChat (Please note 'rbatis' when adding as friend)

zxj347284221


[8]ページ先頭

©2009-2025 Movatter.jp