Skip to content

Instantly share code, notes, and snippets.

@michaelbarton
Created October 2, 2008 10:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaelbarton/14333 to your computer and use it in GitHub Desktop.
Save michaelbarton/14333 to your computer and use it in GitHub Desktop.
# Given the location of an SQL query file, this method will
# execute the query on the database, and print each line to
# the supplied target file.
# This method relies on the MySQL adapter for the fetch_fields
# method, but should not suffer in performance from pulling
# large amounts of data into memory.
public
def export_csv_from_sql(sql_file,target_file)
raise ArgumentError, "SQL file not found : #{sql_file}" unless File.exists?(sql_file)
# Result of the SQL query, but does not put all data in memory
data = ActiveRecord::Base.connection.execute(File.open(sql_file).read)
# CSV header
keys = data.fetch_fields.map(&:name)
FasterCSV.open(target_file,'w') do |csv|
csv << keys
# This line fetches the data a row at a time from query result
data.each { |row| csv << row }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment