Task for waiting until migrations are complete

When we deploy a new version of a Rails app to Kubernetes, we need to wait to start the pods until the migration of the db schema is complete.

Currently we use an initContainer which runs this command:

rake db:abort_if_pending_migrations

Then the initContainer fails and restarts several times until the migrations are complete. Finally our application is started.

Is there any better command for that? In particular I am looking for a command that, instead of failing, waits the completion of the db migration.

Example:

rake db:wait_for_pending_migrations

There isn’t a better task for that, and I don’t know of any included tasks that wait. You could write your own. It would probably look something like

namespace :db do
  task wait_for_pending_migrations: :load_config do
    pending_migrations = proc do
      ActiveRecord::Base.configurations.configs_for(env_name: ActiveRecord::Tasks::DatabaseTasks.env).flat_map do |db_config|
        ActiveRecord::Base.establish_connection(db_config)

        ActiveRecord::Base.connection.migration_context.open.pending_migrations
      end
    end

    while pending_migrations.call.any?
      # maybe you put a counter here to avoid this running forever
      sleep(0.5)
    end
  end
end