9 releases

0.1.8 Dec 27, 2019
0.1.7 Dec 27, 2019
0.1.5 Nov 18, 2019

#210 in #execute


Used in db-derive

MIT/Apache

35KB
887 lines

db-derive

db-derive is a wrapper around PostgreSQL and SQLite using r2d2, postgres and rusqlite, made for the stry story hosting server.

MSRV: 1.40.0

WARNING

Until db-derive gets out of v0.1.x the api is subject to change. This can and will happen.

Examples

Schema

#[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(())
}

Execute

#[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(())
}

Query

#[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(())
}

Tables

#[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(())
}

Types

#[derive(db_derive::Kind)]
enum State {
    #[kind(rename = "running")]
    Running,

    #[kind(rename = "stopped")]
    Stopped,
}

Dependencies

~2MB
~45K SLoC