SQLX migrator
Migrator library for writing sqlx migration using Rust instead of SQL
License | Crates Version | Docs |
---|---|---|
Supported Databases:
- PostgreSQL
- SQLite
- MySql
- Any
Installation
To use sqlx migrator you can configure Cargo.toml as shown below according to your requirements
= { = "0.14.0", =["postgres"] }
OR
= { = "0.14.0", =["mysql"] }
OR
= { = "0.14.0", =["sqlite"] }
OR
= { = "0.14.0", =[
"any",
# Plus any one of above database driver
] }
Usage
To use sqlx_migrator first you need to implement Operation trait to write your sqlx operation below are examples for using postgres based migration
use Error;
use Operation;
// Its better to use sqlx imported from sqlx_migrator
use sqlx;
pub ;
After creation of operation you can implement Migration struct to create single migration
use Error;
use Migration;
use Operation;
use sqlx;
pub ;
Which can be represented in simple form as
use vec_box;
migration!;
// OR
postgres_migration!;
If your up and down query are simple string only than you can directly uses (U,D) where U: AsRef<str>, D: AsRef<str>
to implement Operation
trait
So above example can be further simplified as
!;
postgres_migration
Now at last you need to create migrator for your database to run migrations
use ;
use Postgres;
async
Now you can use two ways to run migrator either directly running migration or creating cli from migrator For direct run
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;
Or you can create cli using
use MigrationCommand;
parse_and_run.await.unwrap;
If you want to extend your own clap based cli then you can add migrator to sub command enum and then run migrator
Migrate from sqlx default sql based migration
To migrate from sqlx sql based migration you have two alternative:
- Write all sql migration as rust operation
- Write single rust based operation which apply and revert all sqlx sql based migration
Option: 1
Can be easily applied by following above usage docs where you only need to write your sql based migration as sqlx query Then you can create cli for migrator
use MigrationCommand;
parse_and_run.await.unwrap;
and run fake apply cli command
<COMMAND_NAME> apply --fake
which actually doesn't apply migration query but only update migration table
Option: 2
To run all sqlx sql based migration as single command create new operation
use Error;
use Operation;
use sqlx;
pub ;