Search code examples
ruby-on-railsherokuforeman

Using foreman, can we run db migration once the database is started?


I want to run both the database and migration in foreman. However, I found that they usually run at the same time when I start foreman. Since at the time I run migration the database has not fully started yet, it causes the migration to fail.

Heroku using Procfile could facilitate a release phase. The phase would be run after all the commands are run. Can I do the same using foreman in my computer?


Solution

  • Heroku does not rely to Procfile to maintain the release process. The Heroku build stack does.

    Since the foreman provides us the way to run multiple processes at the same time, not running processes in order, so your problem is not the responsibility of foreman

    However, you have some other ways to do so.

    1. Simple: since foreman can start your process with shell command, you can use basic shell command sleep (in seconds) for delaying your process

      db_process: start_db_script.sh
      migrarion_process: sleep 5; bundle exec rake db:migrate --trace
      
    2. Full control: Instead of run default migration rake task, you can write another rake task which check the connection to database before execute the migration ( refer to this answer)

      retried = 0
      begin
        # Establishes connection
        ActiveRecord::Base.establish_connection
        # Try to reconnect
        # It will raise error if cannot reach your database
        ActiveRecord::Base.connection.reconnect! 
        Rake::Task["db:migrate"].invoke if ActiveRecord::Base.connected?
      rescue => e 
        retried += 1
        if retried <= 5 # Retry only 5 times
          sleep 1       # Wait 1 seconds before retry
          retry
        end
        puts "#{e} Cannot connect to your database with 5 seconds"
      end