当前位置: 首页 > 工具软件 > Rust-Rbatis > 使用案例 >

十四、Rust ORM 框架

农鸿德
2023-12-01

       Rust 下的 orm,之前笔者介绍过 sqlx ,但使用中发现 sqlx 在进行参数绑定时,使用的是 宏,在当前的 IDE 生态环境下,有时不能很好的进行代码提示,或代码跟踪,所以今天再介绍另一款 rust 下的 orm 工具 “rbatis”

       同时,感谢作者 “杰哥在学习” 为我们带来这么好用的工具!~

初始化

       引入依赖:

[dependencies]
rbson = "2.0"
rbatis = { version = "^3", default-features = false, features = ["postgres", "runtime-async-std-rustls"] }
lazy_static = "1"

       初始化 全局数据源 实例对象 RB:

lazy_static! {
    pub static ref RB: Rbatis = Rbatis::new();
    pub static ref RE: Regex = Regex::new(r"(?x)//(.+):(?P<anchor>[^@\s]+)@").unwrap();
}

/// 脱敏处理
fn desensitive(input: &str) -> String {
    RE.captures(input).and_then(|cap| {
        cap.name("anchor").map(|anchor| {
            input.replace(anchor.as_str(), "*******")
        })
    }).unwrap()
}

pub async fn init_rbatis() {
    if let Some(db) = &crate::boot::global().postgres {
        let db_pool_options = DBPoolOptions {
            max_connections: db.max,
            min_connections: db.min,
            ..Default::default()
        };
        RB.link_opt(&db.dsn, db_pool_options).await.unwrap();
        log::info!("rbatis::datasource {}   {} ~ {}", desensitive(&db.dsn), db.min, db.max)
    }
}

       RB 为线程安全对象,后续的所有方法中可以直接使用。

一些例子

/// 新增(跳过 None 值)
pub async fn save(files: Files) -> u64 {
    let rb_resp = RB.save(&files, &[Skip::Value(Bson::Null)]).await;
    rb_resp.unwrap().rows_affected
}

/// 查询
pub async fn search(name: &str) -> Vec<Files> {
    RB.fetch_list_by_wrapper(
        RB.new_wrapper().like("name", name)
            .order_bys(&[("kind", false), ("path", true)])
    ).await.unwrap()
}

/// 修改(跳过 None 值)
pub async fn update(id: i64, ifile: Files) -> u64 {
    RB.update_by_wrapper(&ifile, RB.new_wrapper()
        .eq("id", id), &[Skip::Column("id"), Skip::Value(Bson::Null)]
    ).await.unwrap()
}

/// 删除
pub async fn delete(ids: Vec<i64>) -> u64 {
    RB.remove_by_wrapper::<Files>(
        RB.new_wrapper().r#in("id", &ids)
    ).await.unwrap()
}

系统初始化时建表

pub async fn decide_to_init() {
    let tables: i64 = RB.fetch("select count(*) from pg_tables where tablename = 'files';", vec![]).await.unwrap();
    if tables == 0 {
        let sql = std::fs::read_to_string("scripts/create.sql").unwrap();
        let _ = RB.exec(sql.as_str(), vec![]).await;
    }
}

       使用半年多以来,不得不说,其wrapper式的api,在熟悉以后,不管是首次书写,还是未来的阅读,体验都要好很多,很高效!~

       更多内容,可以参考作者官方文档:https://rbatis.github.io/rbatis.io/#/

       拜了个,拜 !~

 类似资料: