yhara.jp

Recent Posts

Capistrano config for sinatra-activerecord

2016-10-26
Tech

This blog is implemented with sinatra-activerecord and deployed with Capistrano 3. Today I needed to add some modification to the DB schema, then I found that DB migration does not works well when I do cap production deploy.

Reason

sinatra-activerecord provides a rake task to run DB migration like rake db:migrate RACK_ENV=production. Note that the envvar is RACK_ENV, not RAILS_ENV. This does make sense because it is not a gem for Rails. However, you cannot run migration with capistrano-rails by this reason.

Solution

So here is my new settings in the config/deploy.rb. This is mostly the same as what capistrano/rails/migrations does, except the envvar is rack_env.

    with rack_env: "production" do
#
# migration
#
set :migration_role, :db
set :migration_servers, -> { primary(fetch(:migration_role)) }
namespace :deploy do
  desc 'Runs rake db:migrate if needed'
  task :migrate do
    on fetch(:migration_servers) do
      if test("diff -q #{release_path}/db/migrate #{current_path}/db/migrate")
        info '[deploy:migrate] Skip `deploy:migrate` (nothing changed in db/migrate)'
      else
        info '[deploy:migrate] Run `rake db:migrate`'
        invoke :'deploy:do_migrate'
      end
    end
  end

  desc 'Runs rake db:migrate'
  task :do_migrate do
    on fetch(:migration_servers) do
      within release_path do
        with rack_env: "production" do
          execute :rake, 'db:migrate'
        end
      end
    end
  end

  after 'deploy:updated', 'deploy:migrate'
end

More posts

Posts

(more...)

Articles

(more...)

Category

Ads

About

About the author