Rust使用比较多的ORM是SeaORM和Diesel,本文介绍两个轻量级的。
Cherry
https://github.com/bitlabx/cherry
use cherry::{DataSource, PoolConfig};
pub async fn setup() -> Result<(), Box<dyn Error>> {
let conn = PoolConfig {
url: "mysql://root:12345678@localhost:3306/foo".to_owned(),
..Default::default()
};
Foo::setup(conn).await?;
let result: Option<User> = Foo::select()
.and_where_eq("id", 123)
.fetch()
.await?;
Ok(())
}
pub struct Foo;
impl DataSource for Foo {}
// You can setup more than one DataSources if you need.
// pub struct Bar;
// impl DataSource for Bar {}
Akita
https://github.com/wslongchen/akita
fn main() {
let cfg = AkitaConfig::new(String::from("mysql://root:password@localhost:3306/akita"))
.set_connection_timeout(Duration::from_secs(6))
.set_log_level(LogLevel::Info).set_max_size(6);
let akita = Akita::new(cfg).expect("must be ok");
// CRUD with Entity
let model = User::default();
// insert
let insert_id = model.insert::<Option<i32>, _>(&akita).unwrap();
// update
let res = model.update_by_id::<_>(&akita).unwrap();
// delete
let res = model.delete_by_id::<i32,_>(&akita, 1).unwrap();
// list
let list = User::list::<_>(Wrapper::new().eq("name", "Jack"), &akita).unwrap();
// page
let page = User::page::<_>(pageNo, pageSize, Wrapper::new().eq("name", "Jack"), &akita).unwrap();
}