# `Huginn.Clickhouse.Client`
[🔗](https://github.com/nyo16/huginn/blob/v0.6.0/lib/huginn/clickhouse/client.ex#L1)

High-level ClickHouse gRPC client.

Every function takes a `:pool` option naming the pool to use (default: the
`:pool_name` of `config :huginn, :clickhouse`, else `:clickhouse_pool`). The
pool's `Huginn.Clickhouse.Config` supplies the database and credentials;
per-call options win. See `Huginn.Clickhouse.Pool` for starting pools.

## gRPC methods

| Method | Function | Use case |
|--------|----------|----------|
| `ExecuteQuery` | `query/2`, `insert/3` | Queries and inserts that fit in one message |
| `ExecuteQueryWithStreamInput` | `insert_stream/3` | Large or continuous inserts |
| `ExecuteQueryWithStreamIO` | `stream_query/2`, `stream_io/3` | Large results; inserts that report back while running |

The streaming functions (`insert_stream/3`, `stream_query/2`,
`stream_io/3`) do not use the pool's connections: each call opens its own
HTTP/2 connection to the pool's server, with the pool's TLS settings and
credentials, and closes it when the call ends. That connection is
flow-controlled in both directions (see "Streaming and memory"), and a slow
consumer stalling it stalls no other query. `stream_query/2` sends its
single `QueryInfo` over `ExecuteQueryWithStreamIO` and closes the input side
right away, which ClickHouse handles exactly like
`ExecuteQueryWithStreamOutput`.

## Errors

Every function returns `{:error, %Huginn.Error{}}` on failure. `query!/2`
raises it, and `stream_rows/2`/`stream_maps/2` raise it during enumeration.
`stream_query/2` and `stream_io/3` yield it as their last element.

## Timeouts

`:timeout` (milliseconds or `:infinity`) is sent to the server as the gRPC
deadline. It defaults to `60_000` for `query/2` and `insert/3`. The streaming
functions (`insert_stream/3`, `stream_query/2`, `stream_io/3`) default to
`:infinity`, because a long ingest or export is not a hung one. Use
ClickHouse settings such as `max_execution_time` to bound them server-side.
A timed-out request returns `%Huginn.Error{reason: :timeout}`.

## Retries

`:retries` (default `0`), `:retry_backoff` and `:retry_max_backoff` retry
`%Huginn.Error{reason: :connection}` failures, see `Huginn.Clickhouse.Retry`.
`query/2` repeats the whole request. Inserts and streams repeat only
acquiring a connection, so nothing that reached the server is ever sent twice.

## Streaming and memory

Streams are lazy and enumerate the call exactly once. Stopping early (e.g.
`Enum.take/2`, `Enum.find/2`, an exception) cancels the call, and so does the
consuming process exiting (it owns the connection), so ClickHouse stops the
query. Memory is bounded in both directions:

  * **Receive side.** The connection is only read when the consumer asks
    for the next element. A consumer slower than the server makes TCP and
    HTTP/2 flow control push back, and ClickHouse waits instead of the
    result piling up in memory. At most what one socket read returns is
    buffered.
  * **Send side.** Input is pulled from the source one message (about
    `:chunk_size` bytes) at a time, and the next message is only pulled once
    the previous one fits in the server's HTTP/2 flow-control window. A
    source faster than the server waits for it.

## Examples

    {:ok, result} = Huginn.Clickhouse.Client.query("SELECT 1")

    {:ok, _} =
      Huginn.Clickhouse.Client.insert_stream(
        "INSERT INTO t FORMAT TabSeparated",
        [["a", 1], ["b", 2]]
      )

    "SELECT * FROM large_table"
    |> Huginn.Clickhouse.Client.stream_rows()
    |> Stream.chunk_every(10_000)
    |> Enum.each(&process_batch/1)

# `query_opts`

```elixir
@type query_opts() :: [
  pool: atom(),
  database: String.t(),
  format: String.t(),
  settings: map(),
  timeout: timeout(),
  query_id: String.t(),
  chunk_size: pos_integer(),
  retries: non_neg_integer(),
  retry_backoff: non_neg_integer(),
  retry_max_backoff: non_neg_integer()
]
```

# `stream_element`

```elixir
@type stream_element() ::
  {:ok, Huginn.Clickhouse.Result.t()} | {:error, Huginn.Error.t()}
```

An element of `stream_query/2` and `stream_io/3`.

# `cancel`

```elixir
@spec cancel(String.t(), query_opts()) :: :ok | {:error, Huginn.Error.t()}
```

Cancels a running query by its query ID.

Uses ClickHouse's `KILL QUERY` command, which returns once the query has
been signalled, before it has necessarily stopped.

## Examples

    query_id = "my-query-123"

    Task.async(fn ->
      Huginn.Clickhouse.Client.query("SELECT sleep(3)", query_id: query_id)
    end)

    :ok = Huginn.Clickhouse.Client.cancel(query_id)

# `cancel_where`

```elixir
@spec cancel_where(String.t(), query_opts()) :: :ok | {:error, Huginn.Error.t()}
```

Cancels all queries matching a condition.

> #### Trusted input only {: .warning}
>
> `condition` is interpolated verbatim into a `KILL QUERY WHERE` statement.
> Never pass untrusted/user-supplied input — build the condition from trusted
> values only. To cancel a single known query id safely, use `cancel/2`.

## Examples

    # Cancel all queries from a specific user
    Huginn.Clickhouse.Client.cancel_where("user = 'admin'")

    # Cancel queries running longer than 60 seconds
    Huginn.Clickhouse.Client.cancel_where("elapsed > 60")

# `insert`

```elixir
@spec insert(String.t(), binary(), query_opts()) ::
  {:ok, Huginn.Clickhouse.Result.t()} | {:error, Huginn.Error.t()}
```

Inserts `data`, an already encoded binary, using the `ExecuteQuery` gRPC
method.

The data format is set by the `FORMAT` clause of `sql`. For large inserts,
or to have rows encoded for you, use `insert_stream/3`.

## Options

All options from `query/2`. `:retries` only retries acquiring a channel.
Once the request has been sent, an insert is never retried, because a
failure after sending (e.g. a timeout) does not tell whether the server
committed the rows. To retry inserts yourself safely, give each one an
`insert_deduplication_token` setting (and enable deduplication on the
table), so the server drops a repeated block.

## Examples

    {:ok, _} =
      Huginn.Clickhouse.Client.insert(
        "INSERT INTO users (name, age) FORMAT TabSeparated",
        "john\t25\njane\t30\n"
      )

    {:ok, _} =
      Huginn.Clickhouse.Client.insert(
        "INSERT INTO users FORMAT JSONEachRow",
        ~s({"name":"john","age":25}\n{"name":"jane","age":30}\n),
        settings: %{"insert_deduplication_token" => "batch-42"}
      )

# `insert_stream`

```elixir
@spec insert_stream(String.t(), Enumerable.t(), query_opts()) ::
  {:ok, Huginn.Clickhouse.Result.t()} | {:error, Huginn.Error.t()}
```

Inserts an enumerable of rows or encoded chunks using the
`ExecuteQueryWithStreamInput` gRPC method.

`data` is enumerated once, lazily, and only as fast as the server ingests
it. Elements are packed into messages of about `:chunk_size` bytes, and one
message at a time is held in memory:

  * binaries are sent verbatim, so they must already be encoded in the
    format named by the `FORMAT` clause of `sql`
  * lists (and maps, for `JSONEachRow`) are encoded as rows according to
    `:format`, see `Huginn.Clickhouse.Stream.input_stream/3`

If enumerating `data` raises, the RPC is cancelled (nothing is committed)
and the exception propagates.

## Options

  * `:chunk_size` - target bytes of input data per message
    (default: `1_048_576`)
  * `:format` - how list/map rows are encoded (default: `"TabSeparated"`).
    It must match the `FORMAT` clause of `sql`.
  * `:timeout` - deadline in milliseconds (default: `:infinity`)
  * All other options from `query/2`. As with `insert/3`, `:retries` only
    retries acquiring a connection.

## Examples

    # Structured rows, encoded for you
    {:ok, _} =
      Huginn.Clickhouse.Client.insert_stream(
        "INSERT INTO t FORMAT TabSeparated",
        [["a", 1], ["b", 2]]
      )

    # A file, streamed as-is (data is the 2nd argument, so pipe through then/2)
    File.stream!("large_data.csv", 65_536)
    |> then(&Huginn.Clickhouse.Client.insert_stream("INSERT INTO logs FORMAT CSV", &1))

    # Rows produced lazily
    Stream.map(events, fn e -> %{"id" => e.id, "kind" => e.kind} end)
    |> then(
      &Huginn.Clickhouse.Client.insert_stream(
        "INSERT INTO events FORMAT JSONEachRow",
        &1,
        format: "JSONEachRow"
      )
    )

# `ping`

```elixir
@spec ping(query_opts()) :: :ok | {:error, Huginn.Error.t()}
```

Pings the ClickHouse server to check connectivity.

## Examples

    case Huginn.Clickhouse.Client.ping() do
      :ok -> IO.puts("Connected!")
      {:error, error} -> IO.puts("Failed: #{Exception.message(error)}")
    end

# `query`

```elixir
@spec query(String.t(), query_opts()) ::
  {:ok, Huginn.Clickhouse.Result.t()} | {:error, Huginn.Error.t()}
```

Executes a query using the `ExecuteQuery` gRPC method.

The whole result is returned in one message, so this suits queries with
bounded results, DDL, and small inserts. Use `stream_query/2` for large
results.

## Options

  * `:pool` - pool name (default: `Huginn.Clickhouse.Config.default_pool/0`)
  * `:database` - database to use (default: the pool's `:database`)
  * `:format` - output format (default: `"TabSeparated"`)
  * `:settings` - map of ClickHouse settings
  * `:timeout` - deadline in milliseconds or `:infinity` (default: `60_000`)
  * `:query_id` - custom query ID, e.g. for `cancel/2`
  * `:retries`, `:retry_backoff`, `:retry_max_backoff` - retry
    `:connection` errors by repeating the whole request, see
    `Huginn.Clickhouse.Retry`. Only use them for statements that are safe
    to run twice. Inserts belong in `insert/3`, which never re-sends.

## Examples

    {:ok, result} = Huginn.Clickhouse.Client.query("SELECT 1")

    {:ok, result} =
      Huginn.Clickhouse.Client.query(
        "SELECT * FROM users",
        database: "mydb",
        format: "JSONEachRow",
        timeout: 30_000
      )

    maps = Huginn.Clickhouse.Result.to_maps(result)

    {:error, %Huginn.Error{reason: :server, code: 62}} =
      Huginn.Clickhouse.Client.query("SELEC 1")

# `query!`

```elixir
@spec query!(String.t(), query_opts()) :: Huginn.Clickhouse.Result.t()
```

Executes a query and raises `Huginn.Error` on failure.

See `query/2` for options.

# `running_queries`

```elixir
@spec running_queries(query_opts()) ::
  {:ok, Huginn.Clickhouse.Result.t()} | {:error, Huginn.Error.t()}
```

Lists currently running queries.

## Examples

    {:ok, result} = Huginn.Clickhouse.Client.running_queries()

    result
    |> Huginn.Clickhouse.Result.to_maps()
    |> Enum.each(fn q -> IO.puts("#{q["query_id"]}: #{q["query"]}") end)

# `stream_io`

```elixir
@spec stream_io(String.t(), Enumerable.t(), query_opts()) ::
  Enumerable.t(stream_element())
```

Runs one query over streamed input and returns the server's replies as a
lazy stream, using the `ExecuteQueryWithStreamIO` gRPC method.

`input` becomes the query's input data. Elements are encoded and packed
exactly as in `insert_stream/3`, and the pool's database and credentials
apply. ClickHouse only reads input data in an `INSERT`, either directly or
through the `input()` table function in `INSERT ... SELECT ... FROM input(...)`,
so `sql` is one of those. Its `FORMAT` clause names the input format.

Unlike `insert_stream/3`, which returns once with the final result, this
yields every `Huginn.Clickhouse.Result` the server sends while the query
runs: `progress` updates, server `logs` (with the `send_logs_level`
setting), and the final `stats`. Elements and cancellation behave as in
`stream_query/2`: a failure is the last element, and stopping early cancels
the query.

`input` is enumerated while the result is consumed: one message is pulled
from it only once the previous one has fit in the server's flow-control
window, and replies are yielded as they arrive in between. `:format`
describes the *input* rows, as in `insert_stream/3`.

## Options

Same as `insert_stream/3`.

## Examples

    "INSERT INTO doubled SELECT x * 2 FROM input('x UInt32') FORMAT TabSeparated"
    |> Huginn.Clickhouse.Client.stream_io(Stream.map(1..1_000_000, &[&1]),
      settings: %{"send_logs_level" => "information"}
    )
    |> Enum.each(fn
      {:ok, result} -> Enum.each(result.logs, &IO.inspect/1)
      {:error, error} -> raise error
    end)

# `stream_maps`

```elixir
@spec stream_maps(String.t(), query_opts()) :: Enumerable.t(map())
```

Streams the rows of a query result as maps keyed by column name.

Raises `Huginn.Error` during enumeration on failure, like `stream_rows/2`.

## Examples

    "SELECT id, name, age FROM users"
    |> Huginn.Clickhouse.Client.stream_maps(format: "JSONEachRow")
    |> Stream.filter(fn %{"age" => age} -> age > 18 end)
    |> Enum.to_list()

# `stream_query`

```elixir
@spec stream_query(String.t(), query_opts()) :: Enumerable.t(stream_element())
```

Executes a query and returns a lazy stream of result chunks.

The query starts when the stream is enumerated, and each enumeration runs
it again. Each element is `{:ok, %Huginn.Clickhouse.Result{}}`, one per
message the server sends. The rows of a chunk are decoded with the format
and columns of the first chunk, because ClickHouse only sends them once.
A failure is yielded as `{:error, %Huginn.Error{}}` and is always the last
element.

Stopping early (`Enum.take/2`, `Stream.take_while/2`, an exception) or the
consuming process exiting cancels the call, and ClickHouse stops the query.
The server is only read as fast as the stream is consumed, so a slow
consumer slows the query down rather than buffering its result, see
"Streaming and memory" in the module docs.

## Options

All options from `query/2`, except that `:timeout` defaults to `:infinity`
and `:retries` only retries acquiring a connection.

## Examples

    "SELECT * FROM large_table"
    |> Huginn.Clickhouse.Client.stream_query()
    |> Enum.each(fn
      {:ok, result} -> process_chunk(result.rows)
      {:error, error} -> Logger.error(Exception.message(error))
    end)

    # Stops (and cancels) the query after the first chunk with rows
    "SELECT * FROM logs"
    |> Huginn.Clickhouse.Client.stream_query()
    |> Enum.find(&match?({:ok, %{rows: [_ | _]}}, &1))

# `stream_rows`

```elixir
@spec stream_rows(String.t(), query_opts()) ::
  Enumerable.t(Huginn.Clickhouse.Result.row())
```

Streams the rows of a query result.

A wrapper around `stream_query/2` that yields each row. Like `File.stream!/2`,
it raises `Huginn.Error` during enumeration if the query fails, so a failure
never looks like an empty or truncated result.

## Examples

    "SELECT id, name FROM users"
    |> Huginn.Clickhouse.Client.stream_rows()
    |> Stream.take(100)
    |> Enum.each(fn [id, name] -> IO.puts("#{id}: #{name}") end)

    # Batches of rows, without holding the whole result
    "SELECT * FROM events"
    |> Huginn.Clickhouse.Client.stream_rows()
    |> Stream.chunk_every(10_000)
    |> Enum.each(&process_batch/1)

---

*Consult [api-reference.md](api-reference.md) for complete listing*
