Skip to content

Instantly share code, notes, and snippets.

@sfilatov
Created July 7, 2011 14:26
Show Gist options
  • Save sfilatov/1069621 to your computer and use it in GitHub Desktop.
Save sfilatov/1069621 to your computer and use it in GitHub Desktop.
Active Record postgres copy
connection = ActiveRecord::Base.connection
query = "COPY ( SELECT '#{header}' UNION ALL #{sql_query}) TO 'file.csv' WITH DELIMITER AS ',' CSV"
connection.execute query
connection = ActiveRecord::Base.connection.raw_connection
query = "COPY ( SELECT '#{header}' UNION ALL #{sql query}) TO STDOUT WITH DELIMITER AS ',' CSV"
connection.exec query
while (copy_data = connection.get_copy_data) do
# write data to file.csv
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment