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

Parses and transforms ClickHouse gRPC Result messages.

## Row values

`rows` holds one list per row, values in column order. How values are typed
depends on the output format (see `parse_output/3`):

  * `TabSeparated`/`TSV` and `CSV`/`CSVWithNames` - every field is a binary,
    with ClickHouse escaping undone. `NULL` decodes to `nil`. Bytes are kept
    as-is, so `String` columns that hold non-UTF-8 data decode to raw
    binaries.
  * `JSONEachRow`, `JSONCompactEachRow` (and their `Strings` variants) - JSON
    types (`nil`, numbers, booleans, binaries, lists, maps).
  * Any other format - the whole output is returned as a single row holding
    the raw bytes: `[[output]]`.

# `column`

```elixir
@type column() :: %{name: String.t(), type: String.t()}
```

# `log_entry`

```elixir
@type log_entry() :: %{
  time: non_neg_integer(),
  level: atom(),
  source: String.t(),
  text: String.t()
}
```

# `progress`

```elixir
@type progress() :: %{
  read_rows: non_neg_integer(),
  read_bytes: non_neg_integer(),
  total_rows_to_read: non_neg_integer(),
  written_rows: non_neg_integer(),
  written_bytes: non_neg_integer()
}
```

# `row`

```elixir
@type row() :: [value()]
```

# `stats`

```elixir
@type stats() :: %{
  rows: non_neg_integer(),
  blocks: non_neg_integer(),
  allocated_bytes: non_neg_integer(),
  rows_before_limit: non_neg_integer()
}
```

# `t`

```elixir
@type t() :: %Huginn.Clickhouse.Result{
  columns: [column()],
  logs: [log_entry()],
  output_format: String.t(),
  progress: progress() | nil,
  query_id: String.t(),
  rows: [row()],
  stats: stats() | nil,
  time_zone: String.t()
}
```

# `value`

```elixir
@type value() :: binary() | nil | number() | boolean() | list() | map()
```

A decoded field. See the module docs for which types each format yields.

# `from_grpc`

```elixir
@spec from_grpc(term(), keyword()) :: {:ok, t()} | {:error, Huginn.Error.t()}
```

Converts a gRPC Result message to a `Huginn.Clickhouse.Result` struct.

`defaults` lets a streaming caller inherit `:format` and `:columns` from an
earlier message in the same response.

ClickHouse populates `output_format` and `output_columns` only on the *first*
`Result` of a stream; later chunks leave both empty. Parsing such a chunk in
isolation would fall through to the unknown-format clause of `parse_output/3`
and collapse the whole chunk into a single opaque row, so streaming callers
thread the values established by the first chunk.

Returns `{:error, %Huginn.Error{}}` when the message carries a ClickHouse
exception (`reason: :server`), is not a `Result` at all
(`reason: :unexpected_reply`), or its output cannot be decoded in the declared
format (`reason: :decode`).

# `parse_output`

```elixir
@spec parse_output(binary() | nil, String.t() | nil, [column()]) ::
  {:ok, [row()]} | {:error, Huginn.Error.t()}
```

Parses raw output bytes based on format.

Supported formats:

  * `TabSeparated`/`TSV` - rows end at `\n`, fields at `\t`. ClickHouse
    escape sequences are undone exactly as the server's own reader does:
    `\b \f \r \n \t \0 \a \e \v` decode to control bytes, `\xHH` to
    the byte `0xHH`, a backslash before `\ ' " / =`, a backtick or a control
    byte decodes to that byte, and any other `\c` stays as the two bytes
    `\c`. A field that is exactly `\N` is `NULL` and decodes to `nil`.
  * `CSV`/`CSVWithNames` - RFC 4180 style over the whole buffer: quoted fields
    may contain `,`, `\n`, `\r\n` and doubled quotes; rows end at `\n` or
    `\r\n`. An unquoted `\N` decodes to `nil` (a quoted `"\N"` is the
    two-byte string). `CSVWithNames` returns the header line as the first row.
  * `JSONEachRow`/`JSONStringsEachRow` - one JSON object per line. With
    `columns`, values are extracted in column order (JSON key order is not
    guaranteed to match it) and a missing key yields `nil`; without columns
    the values come in `Map.values/1` order.
  * `JSONCompactEachRow`/`JSONCompactStringsEachRow` - one JSON array per line.
  * anything else - `[[output]]`, the raw bytes as a single row.

Decoding works on bytes, so non-UTF-8 `String` data never crashes the
parser. Malformed output returns `{:error, %Huginn.Error{reason: :decode}}`.

## Examples

    iex> Huginn.Clickhouse.Result.parse_output("a\\tb\t\\N\n", "TabSeparated")
    {:ok, [["a\tb", nil]]}

    iex> Huginn.Clickhouse.Result.parse_output(~s("x,""y"" z",\\N\r\n), "CSV")
    {:ok, [[~s(x,"y" z), nil]]}

# `to_maps`

```elixir
@spec to_maps(t()) :: [map()]
```

Converts rows to a list of maps using column names as keys.

## Examples

    iex> result = %Huginn.Clickhouse.Result{
    ...>   columns: [%{name: "name", type: "String"}, %{name: "age", type: "UInt8"}],
    ...>   rows: [["alice", "25"]]
    ...> }
    iex> Huginn.Clickhouse.Result.to_maps(result)
    [%{"name" => "alice", "age" => "25"}]

---

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