Reputation: 334
I'm trying to create a rake task so that I can simply type "rake db:sync" in order to update my local DB to match production.
This solution leverages code provided by the Heroku team here: Importing and Exporting Heroku Postgres Databases with PG Backups
When I use curl --output /tmp/latest.dump #{url} I'm getting the following error in my latest.dump file:
<?xml version="1.0" encoding="UTF-8"?>
<Error><Code>AuthorizationQueryParametersError</Code><Message>Query-string authentication version 4 requires the X-Amz-Algorithm, X-Amz-Credential, X-Amz-Signature, X-Amz-Date, X-Amz-SignedHeaders, and X-Amz-Expires parameters.</Message><RequestId>421FEFF763870123</RequestId><HostId>vlVr/ihmQiDgYIpdFFkuCgEP8Smvr2ks0wRkf89fJ8NfHfsBb92EVv40Q0NZuQIC</HostId></Error>
Here is the code I'm using.
#lib/tasks/db_sync.rake
namespace :db do
desc 'Pull production db to development'
task :sync => [:backup, :dump, :restore]
task :backup do
Bundler.with_clean_env {
puts 'Backup started...'
system "heroku pg:backups capture --app YOUR_APP_NAME"
puts 'Backup complete!'
}
end
task :dump do
dumpfile = "#{Rails.root}/tmp/latest.dump"
puts 'Fetching url and file...'
Bundler.with_clean_env {
url = `heroku pg:backups public-url --app YOUR_APP_NAME | cat`
system "curl --output #{dumpfile} #{url}"
}
puts 'Fetching complete!'
end
task :restore do
dev = Rails.application.config.database_configuration['development']
dumpfile = "#{Rails.root}/tmp/latest.dump"
puts 'PG_RESTORE on development database...'
system "pg_restore --verbose --clean --no-acl --no-owner -h localhost -U #{dev['username']} -d #{dev['database']} #{dumpfile}"
puts 'PG_RESTORE Complete!'
end
end
Upvotes: 3
Views: 753
Reputation: 11900
Check out the Parity gem. It offers several commands to do the following Heroku Rails tasks easily -
rails console
You're of course primarily looking for the first two.
After installation, it expects that you have two git remote
values set named staging
and production
. development
isn't needed as it is assumed to be your local machine.
You can get the git url for the other two environments from your Heroku dashboard -> (your app) -> Settings -> Info
After you have that set up, it's as simple as
production backup
development restore production
The code is pretty simple, so I encourage you to read it. But it's essentially doing exactly what your rake code attempts to do by getting a public URL and restoring it.
Upvotes: 3