DEV Community

Andy Huynh
Andy Huynh

Posted on • Updated on

you committed a dirty schema, eh?

You know when work gets assigned to you - you buckle down and focus, right? All of a sudden, you're hit with a different assignment. UGH! To quote the little voice in my head:

"Context switching is a bitch."

It's a bitch

This is the case for all knowledge workers. We can agree tripping on the floor, getting a scab - that's annoying! Let me introduce you to the scab of context switching: a dirty schema.

Andy's Dictionary:

Dirty schema - a pull request ready for review with changes to the database schema file not related to the pull request.

andysdictionary

I get dirty schemas switching git branches. Typically after switching branches with different migrations files already ran in each branch. It's a common problem dealing with the the nature of migration files.

Here's a solution that's worked for me: migrate your database back to its original state before switching git branches. The state of your database isn't pristine until performing a rollback to the initial state of the branch. After doing so, switching to a different branch with migrations will migrate with a reliable schema.

Tips to switch branches with a clean schema:

  1. Find the branch with the unneeded changes to your schema, find the migration file with the changes... look for the timestamp - db/migrate/20160204222302_add_name_to_user.rb.. so 20160204222302
  2. Run $ bundle exec rails db:migrate:down VERSION=<timestamp>
  3. Run $ git checkout db/schema.rb so git doesn't save the migration changes.
  4. Switch branches to continue working.

If you're savvy, you can automate this with a script. That's a post for another time.

If you fucked up and have a dirty schema, you can still recover. The real question is.. at what cost? My particular solution will wipe out your local database, but you'll have a clean schema to open a pull request. This is convenient when you're meeting deadlines and it's all systems go!

I've since discovered other dirty schema solutions, but this is a beginner post. It's only right I share with you my solution when I was starting out.

Beginner dirty schema solution

$ bundle exec rake db:drop
$ bundle exec rake db:create
$ git rm db/schema.rb
$ bundle exec rake db:migrate
$ bundle exec rake db:seed
Enter fullscreen mode Exit fullscreen mode
  • Drop your database
  • Create a new instance
  • Delete your current schema.
  • Run $ bundle exec rake db:migrate - this creates a new schema reflecting the migration files in db/migrate
  • Run your development seed. You're now at a clean slate. This is only useful if your local data isn't important to you

It's not sexy, but it works.

Top comments (0)