Skip to content

Instantly share code, notes, and snippets.

@ricardopadua
Forked from tngan/stream_csv.ex
Last active May 4, 2023 11:20
Show Gist options
  • Save ricardopadua/1340527ca5faea4cd312c83066576b1b to your computer and use it in GitHub Desktop.
Save ricardopadua/1340527ca5faea4cd312c83066576b1b to your computer and use it in GitHub Desktop.
Streaming CSV straight out of the database to the client using Elixir, Phoenix, Ecto and PostgreSQL.
def index(conn, _params) do
conn = conn
|> put_resp_content_type("text/csv")
|> put_resp_header("content-disposition", "attachment; filename=export.csv")
|> send_chunked(200)
Repo.transaction fn ->
Ecto.Adapters.SQL.stream(Repo, "COPY expensive_report TO STDOUT CSV HEADER")
|> Stream.map(&(chunk(conn, &1.rows)))
|> Stream.run
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment