Skip to content

Instantly share code, notes, and snippets.

@zorab47
Created December 6, 2017 01:09
Show Gist options
  • Save zorab47/f6754d95ab5fb8a7aeea9d24d486aa45 to your computer and use it in GitHub Desktop.
Save zorab47/f6754d95ab5fb8a7aeea9d24d486aa45 to your computer and use it in GitHub Desktop.
Postgres CSV
module PostgresCopyCsv
extend ActiveSupport::Concern
module ClassMethods
# Performs a database query to copy results as CSV to an IO object.
#
# CSV is created directly in PostgreSQL with less overhead then written to
# the provided IO object.
#
# Example
#
# File.open("leads.csv", "wb") do |file|
# Lead.where.not(lead_sfdc_id: nil).copy_csv(io: file)
# end
#
# Returns nil
def copy_csv(io:, relation: all)
query = <<-SQL
COPY (#{ relation.to_sql }) TO STDOUT WITH DELIMITER ',' CSV HEADER ENCODING 'UTF-8' QUOTE '"'
SQL
raw = connection.raw_connection
raw.copy_data(query) do
while (row = raw.get_copy_data)
io.puts row
end
end
nil
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment