6 releases

0.3.3 Jun 26, 2024
0.3.2 Jun 26, 2024
0.2.0 Jun 26, 2024
0.1.0 Jun 26, 2024

#488 in Database interfaces


Used in migrations

MIT license

30KB
828 lines

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};
use db_dsl::TableDefinition::{column, index, foreign_key, primary_key};

pub fn main() {
    let table = Table::new("users", vec![
        column(Column::new("name", DataType::String)),
        index(Index::unique(vec!["name"])),
        foreign_key(ForeignKey::new("accounts")),
    ]);
    let sql = table.sql_up(Dialect::Sqlite).unwrap();
    println!("{}", sql);
    /**
     * CREATE TABLE IF NOT EXISTS users (
     *     id BIGINT PRIMARY KEY AUTOINCREMENT,
     *     name TEXT,
     *     account_id BIGINT NOT NULL,
     * );
     * CREATE UNIQUE INDEX idx_users_name ON users (name);
     * CREATE FOREIGN KEY fk_users_id (account_id) REFERENCES accounts (id);
     */
}

TODO

  • Better support for references/foreign keys, currently you'd have to add the accounts column manually
  • Support Postgres, MySQL, and SQL Server
  • Add query builder

Dependencies

~0.7–1.4MB
~28K SLoC