-
-
Save khoan/cc6028949e37594cc94fb1c4d34036be to your computer and use it in GitHub Desktop.
Stream PostgreSQL query with potentially huge result set as CSV using gzip compression in Rails and low memory overhead
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
headers['X-Accel-Buffering'] = 'no' | |
headers['Cache-Control'] = 'no-cache' | |
headers['Content-Type'] = 'text/csv; charset=utf-8' | |
headers['Content-Disposition'] = 'inline; filename="data.csv"' | |
headers['Content-Encoding'] = 'gzip' | |
sql = "select * from something;" | |
self.response_body = SqlToCsvStreamer.new(sql) |
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
class SqlToCsvStreamer | |
def initialize(sql) | |
@sql = sql | |
end | |
def each(&block) | |
@block = block | |
begin | |
gz = Zlib::GzipWriter.new(self) | |
conn = ActiveRecord::Base.connection.raw_connection | |
conn.copy_data("COPY (#{@sql.chomp(';')}) TO STDOUT WITH (FORMAT CSV, HEADER TRUE, FORCE_QUOTE *, ESCAPE E'\\\\');") do | |
while row = conn.get_copy_data | |
gz.write row | |
end | |
end | |
ensure | |
gz.close | |
end | |
end | |
def write(row) | |
@block.call row | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment