Skip to content

Instantly share code, notes, and snippets.

@Loschcode
Created April 25, 2022 20:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Loschcode/a20a873fc2939313d29a551ff0377dab to your computer and use it in GitHub Desktop.
Save Loschcode/a20a873fc2939313d29a551ff0377dab to your computer and use it in GitHub Desktop.
class MigrateConcurrently
def initialize; end
def perform
# migration taken directly
# from ActiveRecord
ActiveRecord::Base.connection.migration_context.migrate
rescue ActiveRecord::ConcurrentMigrationError
# we log the details of the migrations
# through our logger
Logger.info(
message: "Migration is already running, waiting to try again",
type: "infrastructure_run_migrate",
delay_between_cycles_in_seconds: 3,
cycle: current_cycle,
max_cycles: max_cycle,
)
sleep 3
# when we reach the cycles limit
# we should stop the process
# and raise an error
if max_cycle?
raise Exception, """
Max cycles reached after trying #{@cycles.current} times.
Something might be wrong with the migration process.
"""
end
# let's increment
# and try again
next_cycle
perform
end
def current_cycle
@current_cycle ||= 1
end
def max_cycle
@max_cycle ||= 2
end
def next_cycle
@current_cycle += 1
end
def max_cycle?
@current_cycle >= @max_cycle
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment