Software Development
Tomasz Kowalewski


Developing an app does not only mean implementing new functions or patching it. Sometimes you have to reverse the changes and go back to the previous stage of a project. A frequent issue that can come up while working on multiple branches is connected to maintaining the appropriate version of a database structure. Programmers, who use rails, have ready-made solutions at their disposal. These solutions support the implementation and control of database changes - these are migrations. I will not describe how it works and what possibilities it brings - I would like to focus on the problem of maintaining the appropriate version of a database structure while switching branches.

The database layer of an app is a separate being and is controlled only by migrations. While creating new migrations, remember to make the planned transformation of a database structure reversible. Of course, in extreme cases, we can raise IrreversibleMigration in the down method. This will also inform us about the fact that the migration cannot be reversed. There are different types of changes that we make in the migration - creating, modifying and removing tables, columns or indexes. Deleting and modifying operations are the most sensitive to change. Why? Let’s consider the following scenario:We are working with the master branch, which is our main working path. Currently we have one table:

class CreateArticles < ActiveRecord::Migration
  def change
    create_table :articles do |t|
      t.string :name
      t.text :description
      t.string :status, null: false
      t.timestamps null: false

Our Article model has such validations which require the presence of name, description and status attributes.

class Article < ActiveRecord::Base
  validates :name, presence: true
  validates :description, presence: true
  validates :status, presence: true

We are implementing changes into our articles table on feature development branch and we delete the status column.

class RemoveStatusColumnFromArticles < ActiveRecord::Migration
  def change
    remove_column :articles, :status, :string

We execute the migration:

$ [example/feature]: bundle exec rake db:migrate
== 20150605120955 RemoveStatusColumnFromArticles: migrating ===================
-- remove_column(:articles, :status, :string)
  -> 0.0717s
== 20150605120955 RemoveStatusColumnFromArticles: migrated (0.0718s) ==========

The schema for a database changes:

diff --git a/db/schema.rb b/db/schema.rb
index 2a100a9..76438c1 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -11,14 +11,13 @@ #
# It's strongly recommended that you check this file into your version control system.

-ActiveRecord::Schema.define(version: 20150605120350) do
+ActiveRecord::Schema.define(version: 20150605120955) do
  create_table "articles", force: :cascade do |t|
    t.string   "name"
    t.text     "description"
-    t.string   "status",      null: false     t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false


Next, we commit the changes to the feature branch. To simulate this issue we switch the current branch to master. The base structure was changed by migration, which deletes the status column on the feature branch. Let’s try to use the following command:

Article.create!(name: "Kaboom", description: "Lorem ipsum...", status: "active")

What will happen after executing the above mentioned code? The error: ActiveRecord::UnknownAttributeError: unknown attribute 'status' for Article will be raised and that’s because of the incompatible structure version of a database. Before changing the branch to master we should roll back the a migration that deletes the status column from the Article table.

What can we do in order to check if we have to roll back some migrations before switching the branches? With the use of the version control system (here it is git) we can check our work by creating a helpful alias:

 migrations = "!f() { git diff --name-only $1..$2 db/migrate | tr -d '[A-Za-z/_.]'; }; f"

Executing the git migrations master feature command will result in the list of migration versions, which are located on feature branches, and which cannot be found on master.

$ [example/feature]: git migrations master feature

Thanks to this information we can easily roll back the changes done in the database structure before switching to master.

$ [example/feature]: bundle exec rake db:migrate:down VERSION=20150605120955
== 20150605120955 RemoveStatusColumnFromArticles: reverting ===================
-- add_column(:articles, :status, :string)
  -> 0.0009s
== 20150605120955 RemoveStatusColumnFromArticles: reverted (0.0045s) ==========

One more thing that we should do after rolling back the migration is to restore the status of a database schema.

$ [example/feature]: git status
On branch feature
Changes not staged for commit:
 (use "git add <file>..." to update what will be committed)
 (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   db/schema.rb

no changes added to commit (use "git add" and/or "git commit -a")
$ [example/feature]: git checkout db/schema.rb
$ [example/feature]: git status
On branch feature
nothing to commit, working directory clean

Now we can easily switch to the master branch.

The given example is not a complicated problem to solve but it should help you realize how important it is to maintain the structure of a database during the change in the work context.