🍣

RustのORM Rbatisを使ってみる

2023/02/24に公開

RustのDB周りは最近はsqlxを使っていましたが、 RBatisも選択肢の一つとしてありな気がしますね。
ただ、構造体そのものにDBアクセスのコードが生成されるので、Repositoryにまとめたいとか言う場合面倒な気も? 
また、sqlxのようにコンパイル時にSQLをチェックしてくれる機能はなさそうです。

https://github.com/rbatis/rbatis

Cargo.toml

[dependencies]
rbatis = "4"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
rbs = { version = "0.1"}
rbdc-mysql = "0.1.20"
tokio = { version = "1", features = ["full"] }

Example Codes


use rbatis::{impl_select, impl_update, impled, Rbatis, sql};
use rbatis::sql::*;
use rbatis::rbdc::datetime::FastDateTime;
use rbdc_mysql::driver::MysqlDriver;

// extern crate rbs;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Adjust {
    pub id: i64,
    pub site_id: i64,
    pub date: FastDateTime,
    pub ratio: i32,
    pub adjust: i32,
}

pub struct AdjustRepository;

impl AdjustRepository {
    #[sql("select count(*) from adjust")]
    pub async fn count(rb: &Rbatis) -> Result<i32, rbatis::Error> {
        impled!()
    }
    #[sql("select * from adjust")]
    pub async fn get_all(rb: &Rbatis) -> Result<Vec<Adjust>, rbatis::Error> {
        impled!()
    }
}

#[tokio::main]
async fn main() {
    println!("Hello, world!");

    let mut rb = Rbatis::default();
    rb.init(MysqlDriver {}, "mysql://accelia:accelia@10.15.5.24:3306/ad20").expect("mysql rb init failed");
    rbatis::crud!(Adjust{});
    impl_select!(Adjust{select_odd_id() => "` where id % 2 = 1`"});
    impl_update!(Adjust{update_by_id(id:&i64) => "`where id = #{id}`"});
    let all = AdjustRepository::get_all(&mut rb).await.unwrap();
    // all of head
    let mut data = all.get(0).unwrap().clone();
    data.ratio = 30_i32;
    let data2 = Adjust::select_odd_id(&mut rb).await.unwrap();
    println!("{:?}", data);
    Adjust::update_by_id(&mut rb, &data, &data.id).await.unwrap();
    Adjust::update_by_column(&mut rb, &data, "id").await.unwrap();

    println!("{:?}", all);

    println!("{:?}", data2);
    let c = AdjustRepository::count(&mut rb).await;

    println!("Hello, world! {}", c.unwrap());
}


Discussion