db_dsl 0.1.0

A simple DSL for creating database objects.
Documentation

db_dsl

A set of structs (Table, Column, Index, ForeignKey) to convert to sql, via a ToSql trait. Meant to be used by rigz-db and migrations.

pub trait ToSql {
    fn to_sqlite(&self) -> Option<String> {
        None
    }

    fn to_sql(&self, dialect: Dialect) -> Option<String> {
        match dialect {
            Dialect::Sqlite => self.to_sqlite(),
        }
    }
}

Usage

use db_dsl::{Table, Column, Index, ForeignKey, Dialect, ToSql};

pub fn main() {
    let table = Table {
        name: "users".to_string(),
        columns: vec![
            Column {
                name: "name".to_string(),
                ..Default::default()
            },
        ],
        indexes: vec![
            Index {
                name: "idx_users_name".to_string(),
                columns: vec!["name".to_string()],
                is_unique: true,
            },
        ],
        foreign_keys: vec![
            ForeignKey {
                name: Some("fk_users_id".to_string()),
                columns: vec!["id".to_string()],
                foreign_table: "other_table".to_string(),
                foreign_columns: vec!["id".to_string()],
            },
        ],
    };
    let sql = table.to_sql(Dialect::Sqlite).unwrap();
    println!("{}", sql);
    /**
     * CREATE TABLE users (
     *     id BIGINT PRIMARY KEY AUTOINCREMENT,
     *     name TEXT
     * );
     * CREATE UNIQUE INDEX idx_users_name ON users (name);
     * CREATE FOREIGN KEY fk_users_id (id) REFERENCES other_table (id);
     */
}

TODO

  • Support Postgres, MySQL, and SQL Server
  • Add query builder