- Notifications
You must be signed in to change notification settings - Fork159
Compile Time Async Dynamic SQL ORM
License
rbatis/rbatis
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
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.
- 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
- 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
- Powerful ORM Capabilities: Automatic mapping between database tables and Rust structures
- Multiple SQL Building Methods:
- py_sql: Python-style dynamic SQL with
if
,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
- py_sql: Python-style dynamic SQL with
- 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
- 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
Connection Pool (crates.io) | GitHub Link |
---|---|
FastPool (default) | rbatis/fast_pool |
Deadpool | rbatis/rbdc-pool-deadpool |
MobcPool | rbatis/rbdc-pool-mobc |
Data Type | Support |
---|---|
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 | ✓ |
crate | GitHub Link |
---|---|
rbdc | rbdc |
rbs | rbs |
Rbatis uses compile-time code generation through therbatis-codegen
crate, which means:
Zero Runtime Overhead: Dynamic SQL is converted to Rust code during compilation, not at runtime. This provides performance similar to handwritten code.
Compilation Process:
- Lexical Analysis: Handled by
func.rs
inrbatis-codegen
using Rust'ssyn
andquote
crates - Syntax Parsing: Performed by
parser_html
andparser_pysql
modules inrbatis-codegen
- Abstract Syntax Tree: Built using structures defined in the
syntax_tree
package inrbatis-codegen
- Intermediate Code Generation: Executed by
func.rs
, which contains all the code generation functions
- Lexical Analysis: Handled by
Build Process Integration: The entire process runs during the
cargo 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.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.
---- 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
# 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"
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;}
To implement a custom database driver for Rbatis:
- 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"] }
- 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();}
WeChat (Please note 'rbatis' when adding as friend)
About
Compile Time Async Dynamic SQL ORM
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.