Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A monkey patch to switch the connection destination from pgbouncer to PostgreSQL only when `rake db:migrate`
# A monkey patch to switch the connection destination from pgbouncer to PostgreSQL only when `rake db:migrate`
#
# Usage: Put this file to `lib/tasks/db_migrate_monkey_patch.rake`
#
# https://gist.github.com/sue445/e82bbc8b626e4681f87182aa5981b68d
require "tmpdir"
require "fileutils"
module DbMigrateMonkeyPatch
module InvokeWithChangeConnection
def invoke(*args)
Dir.mktmpdir("gitlab") do |dir|
current_database_yml = "config/database.yml"
backup_database_yml = "#{dir}/database.yml"
FileUtils.cp(current_database_yml, backup_database_yml)
create_database_yml(current_database_yml)
FileUtils.cp(current_database_yml, "config/database.yml.migrate")
super
ensure
FileUtils.cp(backup_database_yml, current_database_yml)
end
end
private
def create_database_yml(path)
db_config = {
production: {
adapter: "postgresql",
encoding: "unicode",
database: ENV["DB_NAME"],
host: ENV["MASTER_DB_HOST"],
port: ENV["MASTER_DB_PORT"].to_i,
username: ENV["MASTER_DB_USER"],
password: ENV["MASTER_DB_PASS"],
pool: (ENV["DB_POOL"] || 10).to_i,
}
}
File.open(path, "wb") do |f|
f.write(db_config.deep_stringify_keys.to_yaml)
end
end
end
end
Rake::Task["db:migrate"].singleton_class.prepend(DbMigrateMonkeyPatch::InvokeWithChangeConnection)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment