SQLX migrator
A Rust library for writing SQLX migrations using Rust instead of SQL.
License | Crates Version | Docs |
---|---|---|
Supported Databases:
- PostgreSQL
- SQLite
- MySql
- Any
Installation
Add sqlx_migrator
to your Cargo.toml
with the appropriate database feature:
= { = "0.18.0", =["postgres"] }
OR
= { = "0.18.0", =["mysql"] }
OR
= { = "0.18.0", =["sqlite"] }
OR
= { = "0.18.0", =[
"any",
# Plus any one of above database driver
] }
Usage
To use sqlx_migrator
, implement the Operation
trait to define your migration logic. Here's an example using PostgreSQL:
use Error;
use Operation;
pub ;
After defining your operations, you can create a migration:
use Error;
use Migration;
use Operation;
pub ;
This migration can be represented in a simpler form using macros:
use vec_box;
migration!;
// OR
postgres_migration!;
If your up and down queries are simple strings, you can simplify the implementation:
!;
postgres_migration
Finally, create a migrator to run your migrations:
use ;
use Postgres;
async
Running Migrations
You can run migrations directly or integrate them into a CLI:
Programmatic Execution
use Plan;
let mut conn = pool.acquire.await?;
// use apply all to apply all pending migration
migrator.run.await.unwrap;
// or use revert all to revert all applied migrations
migrator.run.await.unwrap;
// If you need to apply or revert to certain stage than see `Plan` docs
CLI Integration
To integrate sqlx_migrator into your CLI, you can either use the built-in
MigrationCommand
or extend your own CLI with migrator support. Below are
examples of both approaches:
Built-in Migration Command
use MigrationCommand;
parse_and_run.await.unwrap;
Extending Your Own CLI with Migrator Support
Migrate from old migrator migration to sqlx_migrator
migration
To transition from your old migration system to sqlx_migrator
, follow these steps:
1. Create Corresponding Migrations
For each migration in your old system, create an equivalent migration in sqlx_migrator
format. This ensures all historical migrations are properly represented in the new system.
2. Implement the OldMigrator Trait
The OldMigrator
trait allows you to bridge between your old migration system and sqlx_migrator
. Here's a implementation example for sqlx sql:
use OldMigator;
use Database
;
3. Run sync
Before running your main migration code, execute the sync operation
use Synchronize;
let sqlx_sql_migrator = SqlxMigrator;
migrator.sync.await?;
You can also implement above functionality for other migrator such as diesel
, seaorm
etc as well as for renaming table name of sqlx_migrator