header image

Code Snippets

Check if Ruby On Rails Database Exists Using Rake

| Last updated:
namespace :db do
  desc "Check if database connection exists"
  task :exists do
    begin
      Rake::Task['environment'].invoke
      ActiveRecord::Base.connection
    rescue
      exit 1
    else
      exit 0
    end
  end
end

Rake task to check if an ActiveRecord database connection exists.

Usage

Add snippet to a project using ActiveRecord (Ruby on Rails) in tasks directory, e.g. lib/tasks/db_exists.rake

Run using bundle exec rake db:exists

Use Case

I find the task useful for performing conditional Ruby on Rails database setup and migration in container start scripts.

For example:

#!/bin/bash

until pg_isready -U "$DATABASE_USERNAME" -h "$DATBASE_HOST" ; do
  echo 'waiting for database...'
  sleep 1
done

if bundle exec rails db:exists ; then
  bundle exec rails db:migrate
else
  bundle exec rails db:create
  bundle exec rails db:migrate
  bundle exec rails db:seed
fi

bundle exec rails server