Skip to content

Instantly share code, notes, and snippets.

@blackjid
Last active February 23, 2022 01:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blackjid/ee22cf2eea05b794410caef0f322a87b to your computer and use it in GitHub Desktop.
Save blackjid/ee22cf2eea05b794410caef0f322a87b to your computer and use it in GitHub Desktop.
Rails abort if pending migrations with data

Abort if pending migrations with data

We use the awesome gem data-migrate with comes with a handy rake task to check if you have migrations pending. The task is really and extention to the task built in on rails but that also check for pending data migrations.

That rake task is available since version 6.3.0 of data-migrate. If you are stuck in an older version like I was here is a version of the rake task you can put in your project.

rake db:abort_if_pending_migrations:with_data

Kubernetes

You can use this rake task in an init container to halt your deployments until you migrations are ready.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-deployment
spec:
  template:
    spec:
      initContainers:
      - name: migrations-check
        image: my-rails-app
        args:
        - rake
        - db:abort_if_pending_migrations:with_data
      containers:
      - name: my-app
        image: my-rails-app
        ...
namespace :db do
namespace :abort_if_pending_migrations do
task with_data: :environment do
migrations_paths = DataMigrate::DataMigrator.migrations_paths
data_migration_path = DataMigrate::DataMigrator.migrations_path
migrations_paths.push data_migration_path
if DataMigrate::DataMigrator.needs_migration?
message = %{Run `rake db:migrate:with_data` to update your database then try again.}
migrations = DataMigrate::DataMigrator.migrations_status migrations_paths
migrations = migrations.select { |m| m[0] == 'down' }
puts "You have #{migrations.size} pending migration#{migrations.size > 1 ? 's' : ''}:"
migrations.each do |pending_migration|
puts " #{pending_migration[1]} #{pending_migration[2]}"
end
abort message
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment