What is the best way to resolve Rails orphaned migrations?

后端 未结 10 951
陌清茗
陌清茗 2020-12-22 22:29

I have been switching between branches in a project and each of them have different migrations... This is the scenario:

$ rake db:migrate:status

<
相关标签:
10条回答
  • 2020-12-22 23:24

    Here's a rake task I wrote for this purpose. It invokes the same method that the db:migrate:status uses under the hood, ActiveRecord::Base.connection.migration_context.migrations_status

    # lib/tasks/cleanup_migration_entries.rake
    
    desc 'Removes schema_migration entries for removed migration files'
    task 'db:migrate:cleanup': :environment do
      migration_context = ActiveRecord::Base.connection.migration_context
      versions_to_delete =
        migration_context.migrations_status
                         .filter_map { |_status, version, name| version if name.include?('NO FILE') }
    
      migration_context.schema_migration.delete_by(version: versions_to_delete)
    
      puts "Cleaned up #{versions_to_delete.size} orphaned migrations."
    end
    
    0 讨论(0)
  • 2020-12-22 23:28

    Here is a rake version of the psql answer from @medik, which won't erase your db or do anything crazy:

    1) Find your orphaned migration versions:

    rails db:migrate:status
    

    2) Note the versions of the missing migrations and head into the db console:

    rails dbconsole
    

    3) Now remove the versions from the migration table manually:

    delete from schema_migrations where version='[version_number]';
    
    0 讨论(0)
  • 2020-12-22 23:32

    Migrations are stored in your database. If you want to remove the abandoned migrations, remove them from the db.

    Example for Postgres:

    1. Open psql:

      psql
      
    2. Connect to your db:

      \c your_database
      
    3. If you're curious, display schema_migrations:

      SELECT * FROM schema_migrations;
      
    4. If you're curious, check if the abandoned migrations are present:

      SELECT version FROM schema_migrations WHERE version IN 
      ('20130320144219', '20130320161939', '20130320184628', '20130403190042',
       '20130403195300', '20130403214000', '20130410194222');
      
    5. Delete them:

      DELETE FROM schema_migrations WHERE version IN (<version list as above>);
      

    Now if you run bundle exec rake db:migrate:status, you'll see the orphaned migrations have been successfully removed.

    0 讨论(0)
  • 2020-12-22 23:35

    You could merge the two branches back into the master so that you have all migrations available. If you really don't want those migrations there, but want to be able to roll back, you could edit the schema_migrations table in your database to remove the rows corresponding to the migrations for which you don't have files. However, this will cause problems if you then switch to another branch with different migrations.

    0 讨论(0)
提交回复
热议问题