9个版本
0.1.8 | 2019年12月27日 |
---|---|
0.1.7 | 2019年12月27日 |
0.1.5 | 2019年11月21日 |
#999在数据库接口
每月27次下载
33KB
781 行
db-derive
db-derive是PostgreSQL和SQLite的包装器,使用r2d2、postgres和rusqlite,专为stry故事托管服务器制作。
MSRV: 1.40.0
警告
在db-derive升级到v0.1.
之前,API可能会更改。这可能会发生。
示例
模式
#[derive(db_derive::Table)]
#[table(exists, schema)]
struct Tag {
#[table(rename = "Id", primary, length = 10)]
id: String,
#[table(rename = "Name", unique, length = 256)]
name: Option<String>,
}
fn main() -> Result<(), db_derive::Error> {
let pool = Pool::sqlite("example.db")?;
pool.transaction(|mut trans| {
trans.schema::<Tag>()?;
Ok(())
})?;
Ok(())
}
执行
#[derive(db_derive::Execute)]
#[execute(sql = "INSERT INTO Tag (Id, Name) VALUES ($id, $name);")]
struct AddTag<'a> {
id: &'a str,
name: Option<&'a str>,
}
fn main() -> Result<(), db_derive::Error> {
let pool = Pool::sqlite("example.db")?;
pool.transaction(|trans| {
let add = AddTag {
id: "example",
name: Some("Example"),
};
add.execute(trans)?;
Ok(())
})?;
Ok(())
}
查询
#[derive(db_derive::Query)]
#[query(sql = "SELECT Id, Name FROM Tag WHERE Id = $id;")]
struct GetTagById<'a> {
id: &'a str,
}
fn main() -> Result<(), db_derive::Error> {
let pool = Pool::sqlite("example.db")?;
let get = GetTagById { id: "example" };
let tag = get.query_row::<_, Tag>(&pool)?;
println!("Tag Name: {}", tag.name);
Ok(())
}
表
#[derive(db_derive::Execute)]
#[execute(sql = "SELECT Id, Name FROM Tag WHERE Id = $id;")]
struct GetTagById<'a> {
id: &'a str,
}
fn main() -> Result<(), db_derive::Error> {
let pool = Pool::sqlite("example.db")?;
let get = GetTagById { id: "example" };
let tag = get.query_row::<_, Tag>(&pool)?;
println!("Tag Name: {}", tag.name);
Ok(())
}
类型
#[derive(db_derive::Kind)]
enum State {
#[kind(rename = "running")]
Running,
#[kind(rename = "stopped")]
Stopped,
}
依赖
~2–13MB
781 行