Last active
May 29, 2020 09:00
-
-
Save sue445/e82bbc8b626e4681f87182aa5981b68d to your computer and use it in GitHub Desktop.
A monkey patch to switch the connection destination from pgbouncer to PostgreSQL only when `rake db:migrate`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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