Sha256: 20572e5b22899198340a14c4230dabd22b8d3f166c660cfb4f957e4d829b4857

Contents?: true

Size: 1.53 KB

Versions: 5

Compression:

Stored size: 1.53 KB

Contents

# frozen_string_literal: true

require_relative "../../app/command"
require_relative "structure/dump"

module Hanami
  module CLI
    module Commands
      module App
        module DB
          class Rollback < App::Command
            desc "Rollback database to a previous migration"

            option :target, desc: "Target migration number", aliases: ["-t"]
            option :dump, desc: "Dump structure after rolling back"

            def call(target: nil, dump: true, **)
              migration_code, migration_name = find_migration(target)

              if migration_name.nil?
                out.puts "==> migration file for target #{target} was not found"
                return
              end

              measure "database #{database.name} rolled back to #{migration_name}" do
                database.run_migrations(target: Integer(migration_code))
              end

              run_command Structure::Dump if dump
            end

            private

            def find_migration(code)
              migration = database.applied_migrations.then { |migrations|
                if code
                  migrations.detect { |m| m.split("_").first == code }
                else
                  migrations.last
                end
              }

              return unless migration

              migration_code = code || migration.split("_").first
              migration_name = File.basename(migration, ".*")

              [migration_code, migration_name]
            end
          end
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
hanami-cli-2.0.0.rc1 lib/hanami/cli/commands/app/db/rollback.rb
hanami-cli-2.0.0.beta4 lib/hanami/cli/commands/app/db/rollback.rb
hanami-cli-2.0.0.beta3 lib/hanami/cli/commands/app/db/rollback.rb
hanami-cli-2.0.0.beta2 lib/hanami/cli/commands/app/db/rollback.rb
hanami-cli-2.0.0.beta1 lib/hanami/cli/commands/app/db/rollback.rb