DEV Community

mmyoji
mmyoji

Posted on • Edited on

How to use different MySQL database per pull-request with Heroku Review Apps (Rails)

Prerequisites

  • Rails v5.2.x
  • Ruby v2.6.x
  • Heroku
  • MySQL (ClearDB)

Summary

Use CLEARDB_<colorname>_URL for each Heroku Review Apps

The sample code is here:

GitHub logo mmyoji / hreviewapp

sample Rails app running on Heroku with ClearDB(MySQL)

Sample Rails app running on Heroku

  • Rails v5.2.3
  • Ruby v2.6.3
  • MySQL (ClearDB)
  • Heroku

Heroku setup

  1. Create an app on Heroku
  2. Connect GitHub and repository
  3. Add ClearDB Addons
  4. Add DATABASE_URL environment variable
  1. Deploy manually
  2. Run database migration and etc. w/ heroku CLI
    • e.g.) $ heroku run rails db:create -a <app_name>

Heroku Review Apps

  1. Create a pipiline (if you don't have it)
  2. Follow the instruction: https://devcenter.heroku.com/articles/github-integration-review-apps
  3. If you wanna use different database per pull-request, see this commit
    • ClearDB issues unique database URL per review apps like CLEARDB_PURPLE_URL or CLEARDB_NAVY_URL
    • If it exists, use the URL for the review apps.

In PostgreSQL, I don't know whether this kind of database URL is issued or not.




Background

Some of my developer teams want to have a different app environment through their development process. Some use their own staging environment, others don't have that and just use local environments.

Heroku Review Apps is a very good choice for that situation, but I didn't know whether it can use different database per pull-request. You might know Rails app development often has database migrations and separating database per pull-request makes developers happier :)

If you use MySQL (sorry I didn't research PostgreSQL case), YOU CAN DO IT and I explain this in this post.

Setup

I don't talk about setup the heroku app, creating a pipeline and setup review apps here.

They're not difficult, just talk about ClearDB useful feature.

CLEARDB_XXX_URL

I found that ClearDB issues unique database URL per review app.

It is like CLEARDB_NAVY_URL, CLEARDB_PURPLE_URL, etc.

And I thought I could use this if it is set in the environment and the dirty script is here:

https://github.com/mmyoji/hreviewapp/blob/master/config/database.yml#L54

production:
  # ...
  url: <%= ((key = ENV.keys.find { |k| k =~ /^CLEARDB_([A-Z]+)_URL$/ && k != "CLEARDB_DATABASE_URL" }) && ENV[key].sub("mysql://", "mysql2://")) || ENV.fetch('DATABASE_URL') %>
Enter fullscreen mode Exit fullscreen mode

This code sucks, but you know what is done here.

If CLEARDB_XXX_URL exists, replace string in proper format, or use DATABASE_URL like as a normal app.

Don't forget to run rails db:schema:load or db:migrate after review app deployment.

see: https://github.com/mmyoji/hreviewapp/blob/master/app.json#L44

That's it 👋

Top comments (0)