Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make Ch.stream emit Ch.Result.t #161

Merged
merged 1 commit into from Jan 29, 2024
Merged

make Ch.stream emit Ch.Result.t #161

merged 1 commit into from Jan 29, 2024

Conversation

ruslandoga
Copy link
Contributor

@ruslandoga ruslandoga commented Jan 29, 2024

This PR makes Ch.stream emit Ch.Result.t structs. This makes it possible to Stream.into or Enum.into it into files and stuff (Collectable implementations).

Example from plausible/analytics#3692

  @doc """
  Creates a streamable Zip archive from the provided (named) Ecto queries.

  Example usage:

      {:ok, pool} = Ch.start_link(pool_size: 1)

      DBConnection.run(pool, fn conn ->
        conn
        |> stream_archive(export_queries(_site_id = 1), format: "CSVWithNames")
        |> Stream.into(File.stream!("export.zip"))
        |> Stream.run()
      end)

  """
  @spec stream_archive(DBConnection.conn(), %{String.t() => Ecto.Query.t()}, [Ch.query_option()]) ::
          Enumerable.t()
  def stream_archive(conn, named_queries, opts \\ []) do
    entries =
      Enum.map(named_queries, fn {name, query} ->
        {sql, params} = Plausible.ClickhouseRepo.to_sql(:all, query)

        datastream =
          conn
          |> Ch.stream(sql, params, opts)
          |> Stream.map(fn %Ch.Result{data: data} -> data end)

        Zstream.entry(name, datastream, coder: Zstream.Coder.Stored)
      end)

    Zstream.zip(entries)
  end

@ruslandoga ruslandoga merged commit 1a9f362 into master Jan 29, 2024
9 checks passed
@ruslandoga ruslandoga deleted the improve-stream branch January 29, 2024 03:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant