#database-migrations #auto-generate #sql #primitive #postgresql #sql-table #auto-generating

sqlmo

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

45 releases (15 breaking)

0.24.1 Jul 2, 2025
0.23.2 Jul 2, 2025
0.23.1 Jan 26, 2025
0.22.7 Nov 20, 2024
0.11.2 Mar 27, 2023

#763 in Database interfaces

Download history 832/week @ 2025-08-06 669/week @ 2025-08-13 820/week @ 2025-08-20 644/week @ 2025-08-27 664/week @ 2025-09-03 751/week @ 2025-09-10 2555/week @ 2025-09-17 1959/week @ 2025-09-24 1241/week @ 2025-10-01 1328/week @ 2025-10-08 1952/week @ 2025-10-15 2090/week @ 2025-10-22 1269/week @ 2025-10-29 1530/week @ 2025-11-05 2175/week @ 2025-11-12 1786/week @ 2025-11-19

7,077 downloads per month
Used in 8 crates (7 directly)

MIT license

78KB
2.5K 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

~135–415KB