Skip to content

Instantly share code, notes, and snippets.

@el-feo
Forked from spalladino/database.yml
Created June 20, 2017 17:58
Show Gist options
  • Save el-feo/a9fdc5084def112927968fc539c215a5 to your computer and use it in GitHub Desktop.
Save el-feo/a9fdc5084def112927968fc539c215a5 to your computer and use it in GitHub Desktop.
Rake task to copy master development database into current database branch
<%
require 'config'
branch = `git rev-parse --abbrev-ref HEAD`.strip rescue nil
use_single_db = !Settings.db_per_branch || !branch || branch == 'master'
branch_spec = (use_single_db ? "" : "_#{branch}").underscore.gsub(/[\.\/\-]/, '_')
%>
development:
<<: *default
database: app_development<%= branch_spec %>
namespace :db do
desc "Copies master development database, or specified by SOURCE env param, into current branch name only if it does not exist"
task :clone do
config = Rails.application.config.database_configuration[Rails.env]
source_db = ENV['SOURCE'].presence || 'app_development'
target_db = config['database']
mysql_opts = "-u #{config['username']} "
mysql_opts << "--password=\"#{config['password']}\" " if config['password'].presence
`mysqlshow #{mysql_opts} #{target_db.gsub('_', '\\\\\_')}`
raise "Target database #{target_db} already exists" if $?.to_i == 0
`mysqlshow #{mysql_opts} #{source_db.gsub('_', '\\\\\_')}`
raise "Source database #{source_db} not found" if $?.to_i != 0
puts "Creating empty database #{target_db}"
`mysql #{mysql_opts} -e "CREATE DATABASE #{target_db}"`
puts "Copying #{source_db} into #{target_db}"
`mysqldump #{mysql_opts} #{source_db} | mysql #{mysql_opts} #{target_db}`
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment