#sql-query #sql-database #database-schema #database-migrations #postgresql #orm #auto-generate

sqlmo

SQL data primitives. Use it to generate SQL queries, auto-generate SQL migrations, and more.

39 releases

0.22.6 Oct 19, 2024
0.21.0 Sep 28, 2024
0.17.0 Jun 2, 2024
0.16.3 Nov 11, 2023
0.11.2 Mar 27, 2023

#430 in Database interfaces

Download history 19/week @ 2024-07-07 40/week @ 2024-07-14 18/week @ 2024-07-21 288/week @ 2024-07-28 23/week @ 2024-08-04 40/week @ 2024-08-11 237/week @ 2024-08-18 76/week @ 2024-08-25 65/week @ 2024-09-01 20/week @ 2024-09-08 41/week @ 2024-09-15 160/week @ 2024-09-22 542/week @ 2024-09-29 564/week @ 2024-10-06 259/week @ 2024-10-13 77/week @ 2024-10-20

1,562 downloads per month
Used in 13 crates (11 directly)

MIT license

68KB
2K SLoC

GitHub Contributors Stars Build Status Downloads Crates.io

sqlmo

sqlmo is a set of primitives to represent SQL tables and queries. Use these primitives to:

  • Auto-generate migrations: Load SQL representations in a standardized form (sqlmo::Schema), calculate differences between schemas (sqlmo::Migration), and generate SQL to apply the migration (sqlmo::Migration::to_sql).
  • Build SQL queries: Represent SQL queries in a data model, to create APIs for query generation. Then, generate the SQL query. Note: this library does not support parsing SQL queries (yet).

For auto-generating migrations, there are a few built-in schema sources:

If you need another source, you should define a way to build a sqlmo::Schema from your data source, then use sqlmo to auto-generate migrations.

Current tools that support this:

If you use this library, submit a PR to be added to this list.

Usage

This example reads the schema from a postgres database, defines an empty schema (which should be filled in), and then computes the migration to apply to the database.

use sqlmo_sqlx::FromPostgres;

#[tokio::main]
async fn main() {
    let url = std::env::var("DATABASE_URL").unwrap();
    let mut conn = sqlx::postgres::PgConnection::connect(&url).await?;
    let current = Schema::try_from_postgres(&mut conn, schema_name).await?;
    let end_state = Schema::default(); // Load your end-state by manually defining it, or building it from another source
    let migration = current.migrate_to(end_state, &sqlmo::Options::default());
    
    for statement in migration.statements {
        let statement = statement.to_sql(Dialect::Postgres);
        println!("{}", statement);
    }
}

Roadmap

  • When calculating migrations, create commented out lines for column deletion
  • ? When calculating migrations, do alter column by calculating word distance between column names

Dependencies

~105–380KB