11 个版本

0.3.8 2023 年 9 月 29 日
0.3.7 2023 年 9 月 29 日
0.2.9 2023 年 9 月 14 日
0.2.7 2023 年 8 月 31 日
0.0.0 2021 年 11 月 22 日

#291数据库接口

Download history 2/week @ 2024-04-27 1/week @ 2024-05-18 5/week @ 2024-06-01 1/week @ 2024-06-08 18/week @ 2024-07-06 1671/week @ 2024-07-27

1,689 每月下载

MIT/Apache

255KB
6.5K SLoC

Arel  

ci Latest Version downloads

安装

// Cargo.toml
serde = { version = "1.0", features = ["derive"] }
arel = { version = "0.3", features = ["runtime-tokio-native-tls", "sqlite"] } // sqlte | mysql | postgres

示例

use arel::prelude::*;
#[arel]
struct User {
  #[arel(primary_key)]
  id: i64,
  name: String,
  #[arel(rename = "type")]
  r#type: String,
  expired_at: Option<chrono::DateTime<chrono::FixedOffset>>,
}
impl Arel for User {}

// init db from Environment
std::env::set_var("DATABASE_URL", "sqlite::memory:");
arel::db::visitor::init().await?;
// or init db from code
arel::db::visitor::get_or_init(|| Box::pin(async { arel::db::DatabasePoolOptions::new().max_connections(5).connect("sqlite::memory:").await })).await?;

// total count
let count = User::query().select_sql("COUNT(*)").fetch_count().await?;
println!("total: {}", count);

// create
let mut user = User {
  name: Set("n1"),
  ..Default::default()
};
user.save().await?;

// select
let user = User::query().r#where("id", 1).fetch_one().await?;
let uesrs: Vec<User> = User::query().where_range("id", ..=10).fetch_all().await?;

// update
let mut user: User = User::query().fetch_one().await?;
// active_user.name.set("n-1");
user.assign(&User {
    name: Set("n-1"),
    ..Default::default()
});
user.save().await?;

// destroy
user.destroy().await?;

查询

选择
User::query().select(vec!(["id", "name"])).to_sql();
条件
let sql = User::query().r#where("name", "n1").r#where("id", 1).to_sql();
// where_not
let sql = User::query().where_not(id: vec![1, 2, 3]).to_sql();
// where_range
let sql = User::query().where_range("age", 18..25).to_sql();
连接
let sql = User::query().join::<Wallet>(arel::JoinConst::InnerJoin).to_sql();
let sql = User::query().join_sql("INNER JOIN wallet on user.id = wallet.user_id").to_sql();
锁定
// should use in transaction
let user: User = User::query().r#where("name", "n1").lock().fetch_one_with_exec(tx);
分组与条件
let sql = User::query().group(vec!["name"]).having("age", 18..).to_sql();
排序
let sql = User::query().order("created_at", arel::SortConst::Desc).to_sql();
let sql = User::query().order_asc().to_sql();
let sql = User::query().order_desc().to_sql();
限制与偏移
let sql = User::query().limit(10).to_sql();
let sql = User::query().offset(10)();
let sql = User::query().paginate(1, 10).to_sql();

插入

事务
User::with_transaction(|tx| {
  Box::pin(async move {
    // for entry in 1i32..=100 {
    //   sqlx::query("INSERT INTO user (name) VALUES ($1)")
    //       .bind(format!("name-{}", entry))
    //       .bind("Admin")
    //       .execute(tx.as_mut())
    //       .await?;
    // }
    let mut user = User {
      name: Set("n1"),
      r#type: Set("ADMIN"),
      ..Default::default()
    };
    user.save_with_tx(tx).await?;
    Ok(None)
  })
})
.await?;

更新

增加
let user = User::query().r#where("id", 1).fetch_one().await?;
user.increment("lock_version", 5).await?;

依赖

~10–28MB
~465K SLoC