Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rake db:migrate updating schema.rb with dropped tables

I have several branches on git, the schema across these branches are on different versions. After switching to a branch lets say new_feature(with pending migration) if I do rake db:setup then it advice me to run the pending migration.

Once I do that my schema gets updated with tables those were deleted in the same branch.

If I do rake db:reset then it works fine.

I know the difference between db:setup and db:reset. The later one does db:drop and then db:setup

But am wondering why the schema shows up those dropped tables on rake db:migrate

Am sure am missing some rails knowledge w.r.t. schema loading and migration process

Any insights would be of great help. Thanks in advance

like image 310
swapab Avatar asked Oct 16 '13 14:10

swapab


1 Answers

It sounds like your schema.rb is checked into git, which is a good thing. So when you switch branches, your schema.rb is different than your actual db schema.

rake db:migrate will only check the schema version in the schema.rb and if the database version is younger then it will run all "pending" migrations. It only regenerates the schema.rb file if a migration is run.

In the case where your actual schema is at a higher version than the version reported in the schema.rb it does the only safe thing, which is nothing. The rationale is that there may not be a migration file to bring it up to date, or the database operations may force recreate the table/truncate or something equally nasty. There are other edge cases of mismatched versions but I think you get the idea.

So you have a few options to work in the migration mentality, if you want to keep the data between branches.

A) Any data you need between branches keep in the db seeds file. Then you can drop/create your db without any concerns

B) Before switching branches roll back the migrations that are different. In the new branch roll them forward again.

C) Cheat, and delete the schema.rb and re-run rake db:migrate. This is cheating because, it could easily cause dataloss, inconsitent schema.rb in your version control, and a headache for other team members because your migrations don't make any sense.

And a word of advice. If you have committed it to git, don't change an old migration file. just make a new one. They form a logical stack and are meant to sequentially alter your schema.

like image 57
waiting4op2deliver Avatar answered Oct 26 '22 08:10

waiting4op2deliver