Created
August 20, 2021 02:13
-
-
Save eoinkelly/8fb59047d6b9193f09bf34714822f2e5 to your computer and use it in GitHub Desktop.
This file contains 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 ThingyExporter | |
SQL_QUERY_PATH = Rails.root.join("app/services/thingy_exporter/query.sql") | |
SQL_QUERY = File.read(SQL_QUERY_PATH) | |
HEADERS = %w[ | |
thingy_id | |
tag_id | |
thingy_filename | |
survey_question_token | |
tag_name | |
tag_number | |
quote | |
start_char | |
end_char | |
tagger | |
tagtime | |
].freeze | |
def initialize(thingy) | |
@thingy = thingy | |
@name = thingy.name.parameterize | |
end | |
def export | |
log "Start DB query" | |
pg_conn = ActiveRecord::Base.connection.raw_connection # :: PG::Connection | |
pg_result = pg_conn.exec_params(SQL_QUERY, [@thingy.id]) # :: PG::Result | |
log "Start generating CSV" | |
csv_data = CSV.generate(encoding: "UTF-8", headers: HEADERS, write_headers: true, force_quotes: true) do |csv| | |
pg_result.each do |result_hash| | |
csv << result_hash | |
end | |
end | |
log "Finished generating CSV" | |
csv_data | |
ensure | |
# Clear the memory associated with the PG::Result | |
log "Cleaning up PG::Result memory" | |
pg_result.clear if pg_result | |
end | |
def log(msg) | |
Rails.logger.info("ThingyExporter: #{msg}") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment