13 releases (breaking)
| 0.24.0 | Jul 2, 2025 |
|---|---|
| 0.22.0 | Oct 4, 2024 |
| 0.21.0 | Sep 28, 2024 |
| 0.20.0 | Jun 2, 2024 |
| 0.16.2 | Jul 30, 2023 |
#2525 in Database interfaces
594 downloads per month
86KB
2.5K
SLoC
sql
sql 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 (
sql::Schema), calculate differences between schemas (sql::Migration), and generate SQL to apply the migration (sql::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:
- Postgres:
sql_sqlx - OpenAPI v3:
sql_openapi
If you need another source, you should define a way to build a sql::Schema from your data source, then use sql
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 sql_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, &sql::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
~2.8–4MB
~71K SLoC