Last active
February 13, 2023 23:11
-
-
Save MrTin/6d3b7c2f09e4f3888afba19bc6bc901c to your computer and use it in GitHub Desktop.
Rails: Download and restore database locally from production
This file contains hidden or 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
| namespace :dev do | |
| namespace :db do | |
| desc 'Reset database and import production data' | |
| task restore_from_prod: :environment do | |
| unless Rails.env.development? | |
| puts("This task is only available in development") | |
| next | |
| end | |
| tmp_path = Rails.root.join("tmp") | |
| database_config = ActiveRecord::Base.connection_db_config | |
| activerecord_connection = ActiveRecord::Base.connection | |
| dump_name = "db.production-#{Time.now.to_i}.dump" | |
| puts("Downloading production database to #{tmp_path}/#{dump_name} ...") | |
| Dir.chdir(tmp_path) do | |
| `heroku pg:backups:download -o #{dump_name}` | |
| end | |
| puts "Killing existing connections to database..." | |
| activerecord_connection.execute("SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = '#{database_config.database}' AND pid <> pg_backend_pid();") | |
| Rake::Task['db:drop'].invoke | |
| Rake::Task['db:create'].invoke | |
| puts "Re-establishing connnection to database..." | |
| activerecord_connection.reconnect! | |
| puts "Restoring production database to #{database_config.database} ..." | |
| `pg_restore --verbose --clean --no-acl --no-owner -h localhost -d #{database_config.database} #{tmp_path}/#{dump_name}` | |
| puts "Updating environment ar_internal_metadata.environment to '#{database_config.env_name}'..." | |
| activerecord_connection.execute("UPDATE ar_internal_metadata SET value = '#{database_config.env_name}' WHERE key = 'environment'") | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment