Skip to content

Instantly share code, notes, and snippets.

@mgiacomini
Created May 9, 2018 14:21
Show Gist options
  • Save mgiacomini/944dc6bede7ae2e5390a54129998852b to your computer and use it in GitHub Desktop.
Save mgiacomini/944dc6bede7ae2e5390a54129998852b to your computer and use it in GitHub Desktop.
export query for ecto
def build_export_query(user, batch_size \\ 500)
columns = ~w(id name amount amount_currency cycle first_bill_date type type_description)
query = """
COPY (
SELECT #{Enum.join(columns, ",")}
FROM subscriptions
WHERE archived = false
AND user_id = #{user.id}
) to STDOUT WITH CSV DELIMITER ',';
"""
csv_header = [Enum.join(columns, ","), "\n"]
Ecto.Adapters.SQL.stream(Repo, query, [], max_rows: batch_size)
|> Stream.map(&(&1.rows))
|> (fn stream -> Stream.concat(csv_header, stream) end).()
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment