Guest User

Untitled

a guest
Oct 18th, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. # lib/tasks/db_import.rake
  2. namespace :db do
  3. namespace :import do
  4. desc 'Import Heroku Staging database locally'
  5. task :staging do
  6. import_db('staging', 'YOUR_STAGING_HEROKU_APP_HERE')
  7. end
  8.  
  9. desc 'Import Heroku Production database locally'
  10. task :production do
  11. import_db('production', 'YOUR_PRODUCTION_HEROKU_APP_HERE')
  12. end
  13.  
  14. # Creates a unique database dump based on the current time and specified environment.
  15. def import_db(environment, heroku_app_name)
  16. puts("Importing #{environment} database locally...")
  17. file = "tmp/#{environment}-#{date}.dump"
  18. dump_local
  19. capture_and_download_heroku_db(heroku_app_name)
  20. `mv latest.dump #{file}`
  21. import_locally(file)
  22. run_migrations
  23. puts("#{environment} database successfully imported")
  24. end
  25.  
  26. # Returns the readable date in YYYY-MM-DD with an
  27. # appended integer time to make the filename unique.
  28. def date
  29. "#{Time.now.to_date.to_s}-#{Time.now.to_i}"
  30. end
  31.  
  32. # Returns the current machine's user for use with PG commands
  33. def user
  34. `whoami`.strip
  35. end
  36.  
  37. # Creates and downloads a Heroku database back-up.
  38. # Requires the Heroku toolchain to be installed and setup.
  39. def capture_and_download_heroku_db(app)
  40. `heroku pg:backups:capture --app #{app}`
  41. `heroku pg:backups:download --app #{app}`
  42. end
  43.  
  44. # Creates a back-up of your current local development
  45. # database in case you want to restore it.
  46. def dump_local
  47. `pg_dump -Fc --no-acl --no-owner -h localhost -U #{user} YOUR_LOCAL_DB_NAME_HERE > tmp/development-#{date}.dump`
  48. end
  49.  
  50. # Imports the downloaded database dump into your local development database.
  51. def import_locally(file)
  52. `pg_restore --verbose --clean --no-acl --no-owner -h localhost -U #{user} -d YOUR_LOCAL_DB_NAME_HERE #{file}`
  53. end
  54.  
  55. # Runs migrations against the just imported database dump from Heroku.
  56. def run_migrations
  57. `bin/rake db:migrate`
  58. end
  59. end
  60. end
Add Comment
Please, Sign In to add comment