#table #generate-table #macro #binding #rusqlite #column #id

macro impl_table

Generate table binding and utils for rust-postgres and rusqlite

4 releases

0.1.3 May 22, 2019
0.1.2 May 22, 2019
0.1.1 May 5, 2019
0.1.0 Apr 29, 2019

#15 in #generate-table

MIT license

32KB
711 lines

impl_table: generated database binding and utils

![impl_table on docs.rs][docsrs-image] [docsrs-image]: https://docs.rs/chrono/badge.svg

Example

extern crate chrono;

use chrono::{DateTime, NaiveDate, TimeZone, Utc};
use impl_table::{impl_table, Table};

// Optionally generate an id column and two timestamp columns: created_at and
// updated_at.
#[impl_table(name = "books", adaptor = rusqlite, with_columns(id, timestamps))]
#[derive(Table)]
struct Book {
    #[column] pub name: String,
    #[column] published_at: NaiveDate,
    #[column(name = "author_name")] author: String,
}

let book = Book {
    id: 1,
    name: "The Man in the High Castle".into(),
    published_at: NaiveDate::from_ymd(1962, 10, 1),
    author: "Philip K. Dick".into(),

    created_at: Utc.ymd(2019, 5, 22).and_hms(8, 0, 0),
    updated_at: Utc.ymd(2019, 5, 22).and_hms(8, 0, 0),
};

The above code generates an implementation like the following:

extern crate chrono;

use chrono::{DateTime, NaiveDate, TimeZone, Utc};

struct Book {
    id: i64,
    pub name: String,
    published_at: NaiveDate,
    author: i64,

    created_at: DateTime<Utc>,
    updated_at: DateTime<Utc>,
}

impl Book {
    pub const TABLE_NAME: &'static str = "books";
    pub const ADAPTOR_NAME: &'static str = "rusqlite";

    fn table_name() -> &'static str {
        Self::TABLE_NAME
    }

    fn all_columns() -> &'static [&'static str] {
        &["id", "name", "published_at", "author_name", "created_at", "updated_at"]
    }

    fn from_row(row: &rusqlite::Row) -> rusqlite::Result<Self> {
        Ok(Self {
            id: row.get(0)?,
            name: row.get(1)?,
            published_at: row.get(2)?,
            author: row.get(3)?,
            created_at: row.get(4)?,
            updated_at: row.get(5)?,
        })
    }
}

For more examples see test/sample.rs.

Dependencies

~2MB
~46K SLoC