feat: add number to downgrade command config

This commit is contained in:
Dmitriy Pleshevskiy 2021-02-25 00:03:51 +03:00
parent 413e0040d4
commit fef34be5ac
4 changed files with 22 additions and 16 deletions

View File

@ -1,20 +1,24 @@
use crate::config::Config;
use crate::database::prelude::*;
use crate::database::MigrationManager;
use crate::opts::DowngradeCommandOpt;
use crate::StdResult;
use std::cmp;
use std::convert::TryFrom;
pub(crate) fn downgrade_applied_migrations(config: Config) -> StdResult<()> {
pub(crate) fn rollback_applied_migrations(
config: Config,
opts: DowngradeCommandOpt,
) -> StdResult<()> {
let mut manager = MigrationManager::try_from(&config)?;
let applied_migrations = manager.applied_migration_names()?;
let migrations = config.migrations()?;
if let Some(first_applied_migration) = applied_migrations.first() {
if let Some(migration) = migrations
.iter()
.find(|m| m.name() == first_applied_migration)
{
let rollback_migrations_number = cmp::min(opts.migrations_number, applied_migrations.len());
for migration_name in &applied_migrations[..rollback_migrations_number] {
if let Some(migration) = migrations.iter().find(|m| m.name() == migration_name) {
println!("downgrade {}...", migration.name());
manager.downgrade(&migration)?;
}

View File

@ -35,9 +35,9 @@ fn main() -> StdResult<()> {
let config = Config::read(opt.config)?;
commands::upgrade_pending_migrations(config)?;
}
Command::Downgrade => {
Command::Downgrade(opts) => {
let config = Config::read(opt.config)?;
commands::downgrade_applied_migrations(config)?;
commands::rollback_applied_migrations(config, opts)?;
}
Command::Completions(opts) => {
AppOpt::clap().gen_completions_to(

View File

@ -27,7 +27,7 @@ pub(crate) enum Command {
Upgrade,
#[structopt(name = "downgrade", visible_alias = "down")]
Downgrade,
Downgrade(DowngradeCommandOpt),
Completions(CompletionsShell),
}
@ -44,6 +44,13 @@ pub(crate) struct MakeCommandOpt {
pub migration_name: String,
}
#[derive(Debug, StructOpt)]
pub(crate) struct DowngradeCommandOpt {
/// How many applied migrations do we have to rollback
#[structopt(long = "number", short = "n", default_value = "1")]
pub migrations_number: usize,
}
#[derive(Debug, StructOpt)]
pub(crate) enum CompletionsShell {
Bash,

View File

@ -229,13 +229,8 @@ Pending migrations:
.arg("-c")
.arg(path_to_file("Migra_env.toml"))
.arg("down")
.assert()
.success();
Command::cargo_bin("migra")?
.arg("-c")
.arg(path_to_file("Migra_env.toml"))
.arg("down")
.arg("-n")
.arg("2")
.assert()
.success();