Skip to content

Instantly share code, notes, and snippets.

@silasjmatson
Last active June 14, 2017 18:37
Show Gist options
  • Save silasjmatson/a783d9c457dd0fc3275dde199a7172ee to your computer and use it in GitHub Desktop.
Save silasjmatson/a783d9c457dd0fc3275dde199a7172ee to your computer and use it in GitHub Desktop.
Ruby Module to stream a SQL query to standard out, and yield each row to a block
module DatabaseQueryStreaming
def stream_query_rows(sql_query, options="WITH CSV HEADER")
conn = ActiveRecord::Base.connection.raw_connection
conn.copy_data "COPY (#{sql_query}) TO STDOUT #{options};" do
while row = conn.get_copy_data
yield row
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment