Skip to content

Instantly share code, notes, and snippets.

@bf4
Forked from njakobsen/live_database_dump.rb
Last active June 19, 2019 19:22
Show Gist options
  • Select an option

  • Save bf4/7e02f97b60c9e0bd09ce0f2ae8bdb662 to your computer and use it in GitHub Desktop.

Select an option

Save bf4/7e02f97b60c9e0bd09ce0f2ae8bdb662 to your computer and use it in GitHub Desktop.
Live stream a database dump (or any other STDOUT) using Rails 4. Why would you want this? If you have a large database dump and want to avoid storing it in memory as Rails streams it. This allows pipe the dump directly into the http response instead of storing it as a file, sending it, and then deleting it. Let me know what you think! I've teste…
include ActionController::Live
def database_dump
database = Rails.configuration.database_configuration[Rails.env]["database"]
send_file_headers!(:type => 'application/octet-stream', :filename => "#{database}_#{Time.now.to_s(:human)}.backup")
pipe = IO.popen("pg_dump '#{database}' -F c")
while (line = pipe.gets)
response.stream.write line
end
response.stream.close
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment