Derive Macro wb_sqlite::CreateTableSql

source ·
#[derive(CreateTableSql)]
{
    // Attributes available to this derive:
    #[sql]
}
Expand description

const CREATE_TABLE_SQL: &’static str = “CREATE TABLE …”

"CREATE TABLE IF NOT EXISTS {tab_name} ({col_defs}{tab_constraint}) STRICT{tab_option};"
col_defs = {field_name} {col_typ} {col_constraint},

§Struct attributes

#[sql( constraint = “table constraint”, option = “table option” )]

§Field attributes

#[sql( typ = “datatype”, constraint = “column constraint” )]

§Table Name creation: PascalCase with digits as lowercase to snake_case

struct MyDog {
"CREATE TABLE IF NOT EXISTS my_dog (name TEXT NOT NULL) STRICT;"

struct M2yDog {
"CREATE TABLE IF NOT EXISTS m2y_dog (name TEXT NOT NULL) STRICT;"

struct My2Dog {
"CREATE TABLE IF NOT EXISTS my2_dog (name TEXT NOT NULL) STRICT;"

struct MyD2og {
"CREATE TABLE IF NOT EXISTS my_d2og (name TEXT NOT NULL) STRICT;"

struct MyDo2g {
"CREATE TABLE IF NOT EXISTS my_do2g (name TEXT NOT NULL) STRICT;"

§Example

#[derive(CreateTableSql)]
#[sql(constraint = "UNIQUE(vendor,brand)")]
struct WineBottle {
   #[sql(constraint = "PRIMARY KEY")]
   id: i64,
   #[sql(constraint = "UNIQUE")]
   serial_no: Option<String>,
   #[sql(constraint = "REFERENCES vendor(id) ON UPDATE RESTRICT ON DELETE RESTRICT")]
   vendor: i64,
   #[sql(constraint = "CHECK(volume > 0)")]
   volume: f64,
   #[sql(constraint = "DEFAULT 'red'")]
   color: String,
   brand: Option<String>,
   #[sql(typ = "ANY")]
   data: Option<Vec<u8>>
}
assert_eq!(
WineBottle::CREATE_TABLE_SQL,
concat!(
"CREATE TABLE IF NOT EXISTS wine_bottle (id INTEGER NOT NULL PRIMARY KEY, ",
"serial_no TEXT UNIQUE, ",
"vendor INTEGER NOT NULL REFERENCES vendor(id) ON UPDATE RESTRICT ON DELETE RESTRICT, ",
"volume REAL NOT NULL CHECK(volume > 0), ",
"color TEXT NOT NULL DEFAULT 'red', ",
"brand TEXT, data ANY, UNIQUE(vendor,brand)) STRICT;",
));

§SQLite / Rust type mapping

INTEGER NOT NULL = bool, u8, u16, u32, i8, i16, i32, i64
REAL NOT NULL = f32, f64
TEXT NOT NULL = &str, String
BLOB NOT NULL = &[u8], Vec<u8>
INTEGER = Option<bool>, Option<u8>, Option<u16> ... Option<i64>
REAL = Option<f32>, Option<f64>
TEXT = Option<String>
BLOB = Option<Vec<u8>>
ANY = all other