What is the best way to resolve Rails orphaned migrations?
Solution 1:
I ended up solving the problem like this:
(1) Go to the branches that has the migration files and roll them back. This is not trivial when you have many branches which are will result in many conflicts if you try to merge them. So I use this commands to find out the branches of each orphan migration belongs to.
So, I need to find commit of the last time the migration was modified.
git log --all --reverse --stat | grep <LASTEST_ORPHAN_MIGRATION_ID> -C 10
I take the commit hash and determine which branch it belongs like this:
git branch --contains <COMMIT_HASH>
Then I can go back to that branch, do a rollback and repeat this process for all the missing files.
(2) Run migrations: checkout the branch you finally want to work on and run the migrations and you should be good to go.
Troubleshooting
I also ran in some cases where orphaned migrations where on deleted branches.
To solve this I created dummy migration files with the same migration_id of the missing files and roll them back. After that, I was able to delete they dummy migrations and have a clean migration status :)
Another alternative is deleting the missing files from the database directly:
delete from schema_migrations where version='<MIGRATION_ID>';
Solution 2:
Migrations are stored in your database. If you want to remove the abandoned migrations, remove them from the db.
Example for Postgres:
-
Open psql:
psql
-
Connect to your db:
\c your_database
-
If you're curious, display schema_migrations:
SELECT * FROM schema_migrations;
-
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');
-
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.
Solution 3:
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]';