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 collectable #162

Merged
merged 1 commit into from
Jan 29, 2024
Merged

make Ch.stream collectable #162

merged 1 commit into from
Jan 29, 2024

Conversation

ruslandoga
Copy link
Contributor

@ruslandoga ruslandoga commented Jan 29, 2024

This PR makes Ch.Stream.t collectable, meaning it can be Enum.intoed or Stream.intoed with iodata and that iodata will be sent as an HTTP chunk.

Example from plausible/analytics#3692:

  @doc """
  Creates a collectable stream which pipes the data to an `imported_*` table.

  Example usage:

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

      DBConnection.run(pool, fn conn ->
        File.stream!("imported_browsers.csv", _64kb = 64000)
        |> Stream.into(import_stream(conn, _site_id = 12, _table = "imported_browsers", _format = "CSVWithNames"))
        |> Stream.run()
      end)

  """
  @spec import_stream(DBConnection.t(), pos_integer, String.t(), String.t(), [Ch.query_option()]) ::
          Ch.Stream.t()
  def import_stream(conn, site_id, table, format, opts \\ []) do
    :ok = ensure_supported_format(format)

    statement =
      [
        "INSERT INTO {table:Identifier} SELECT {site_id:UInt64} AS site_id, * FROM input('",
        input_structure(table),
        "') FORMAT ",
        format
      ]

    Ch.stream(conn, statement, %{"table" => table, "site_id" => site_id}, opts)
  end

@ruslandoga ruslandoga merged commit 987332f into master Jan 29, 2024
9 checks passed
@ruslandoga ruslandoga deleted the collectable-stream branch January 29, 2024 04:07
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.

1 participant