db_dsl

Crates.iodb_dsl
lib.rsdb_dsl
version0.3.3
sourcesrc
created_at2024-06-26 06:03:22.187237
updated_at2024-06-26 17:53:56.379056
descriptionA simple DSL for creating database objects.
homepage
repositoryhttps://gitlab.com/magicfoodhand/db_dsl
max_upload_size
id1284188
size29,686
(inapinch-io)

documentation

README

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
Commit count: 6

cargo fmt