1 个不稳定版本
使用旧的 Rust 2015
0.1.0 | 2017年4月12日 |
---|
#62 在 #row
5KB
65 行
mysql-repo
一个轻量级库,通过公开一个Repository
特质(和一些辅助特质)来结构化一些 CRUD SQL 代码模板。
目前仅适用于rust-mysql-simple。
只需实现库的一些特质
pub enum Users {}
impl Repository for Users {}
impl<'a> Insertable<Users> for &'a NewUser {
fn sql() -> &'static str { "INSERT INTO users(email, data) VALUES (?, ?)" }
fn to_params(&self) -> ::mysql::Params {
(&self.email, &self.data).into()
}
}
impl<'a> Updatable<Users> for &'a User {
fn sql() -> &'static str { "UPDATE users SET email = ?, data = ? WHERE id = ?" }
fn to_params(&self) -> ::mysql::Params {
(&self.email, &self.data, &self.id).into()
}
}
impl Findable<Users> for User {
fn sql() -> &'static str { "SELECT id, email, data FROM users WHERE id = ? LIMIT 1" }
fn from_row(row: ::mysql::Row) -> Result<Self, ::mysql::Error> {
let (id, email, data) = ::mysql::from_row_opt(row)?;
Ok(User { id, email, data, ..Default::default() })
}
}
impl Whereable<Users> for User {
fn wrapped_sql(sql: &str) -> String {
["SELECT id, email, data FROM users WHERE ", sql].concat()
}
fn from_row(row: ::mysql::Row) -> Result<Self, ::mysql::Error> {
<Self as Findable<Users>>::from_row(row)
}
}
impl Deletable<Users> for User {
fn sql() -> &'static str { "DELETE FROM users WHERE id = ?" }
fn to_params(&self) -> ::mysql::Params {
(&self.id,).into()
}
}
然后你可以做
let mut user: User = Repository::find(&mut conn, 1)?.ok_or("No users")?;
user.email = "[email protected]";
Repository::update(&mut conn, &user)?;
let user: User = Repository::where_one("email = ?", ("[email protected]",))?.ok_or("No users")?;
等等。
依赖
~11MB
~232K SLoC