Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .claude/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ Follow [Go Code Review Comments](https://go.dev/wiki/CodeReviewComments) in full

**Goroutines**
- Always document when a goroutine exits and how it is stopped.
- Prefer synchronous APIs. Async variants (e.g., `WithAsync`) are opt-in through context, not the default path.
- Prefer synchronous APIs. If an API needs an async variant, make it opt-in through context, not the default path.

**Imports**
- Three groups separated by blank lines: stdlib → external → internal (`github.com/ClickHouse/clickhouse-go`).
Expand Down
15 changes: 11 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ Both support TCP and HTTP transport. When in doubt, use the native interface.
* Failover and load balancing
* [Bulk write support](examples/clickhouse_api/batch.go) (for `database/sql` [use](examples/std/batch.go) `begin->prepare->(in loop exec)->commit`)
* [PrepareBatch options](#preparebatch-options)
* [AsyncInsert](benchmark/v2/write-async/main.go) (more details in [Async insert](#async-insert) section)
* [Async insert](benchmark/v2/write-async/main.go) (more details in [Async insert](#async-insert) section)
* Named and numeric placeholders support
* LZ4/ZSTD/LZ4HC/GZIP/Deflate/Brotli compression support
* External data
Expand Down Expand Up @@ -505,17 +505,24 @@ The `Debug` and `Debugf` fields in `Options` are deprecated in favour of `Logger

## Async insert

[Async insert](https://clickhouse.com/docs/concepts/features/operations/insert/asyncinserts) is supported via `WithAsync()` helper on both Native and HTTP protocols. You can use it for both Go standard interface `OpenDB` and also ClickHouse interface `Open()`.
[Async insert](https://clickhouse.com/docs/concepts/features/operations/insert/asyncinserts) is controlled by the `async_insert` and `wait_for_async_insert` server settings. Set them with `WithSettings()` on both Native and HTTP protocols, for both Go standard interface `OpenDB` and ClickHouse interface `Open()`:

**NOTE**: You can use `WithSettings()` manually to add any async related settings. `WithAsync()` is just a simple wrapper that does that for you.
```go
ctx = clickhouse.Context(ctx, clickhouse.WithSettings(clickhouse.Settings{
"async_insert": 1,
"wait_for_async_insert": 1,
}))
```

We have the following examples to show Async Insert in action.
1. [Native with Open](examples/clickhouse_api/async_native.go)
1. [HTTP with Open](examples/clickhouse_api/async_http.go)
1. [Native with OpenDB](examples/std/async_native.go)
1. [HTTP with OpenDB](examples/std/async_http.go)

**NOTE**: The old `AsyncInsert()` api is deprecated and will be removed in future versions. We highly recommend using the `WithAsync()` api for all the Async Insert use cases.
**NOTE**: ClickHouse 26.2 and later enable async insert by default. Thus, with a low insert rate, each `INSERT` takes 50 ms or more, with all clients. If you insert one row at a time, send many rows in one batch, or disable async insert with `WithSettings(clickhouse.Settings{"async_insert": 0})`. For more information, see [Async insert is the default on ClickHouse 26.2 and later](https://clickhouse.com/docs/integrations/language-clients/go/clickhouse-api#async-insert-default).

**NOTE**: `WithAsync()`, `WithStdAsync()` and `AsyncInsert()` are deprecated and will be removed in the next major version. `WithAsync(false)` does not disable async insert: it sets `async_insert=1` and `wait_for_async_insert=0`. Use `WithSettings()` instead. For the replacements, see [`WithAsync` and `AsyncInsert` are deprecated](https://clickhouse.com/docs/integrations/language-clients/go/clickhouse-api#async-insert-deprecated).

## Arbitrary input/output formats (experimental)

Expand Down
2 changes: 1 addition & 1 deletion benchmark/v2/write-async-std/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ CREATE TABLE benchmark_async (
func benchmark(conn *sql.DB) error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
ctx = clickhouse.Context(ctx, clickhouse.WithStdAsync(false))
ctx = clickhouse.Context(ctx, clickhouse.WithSettings(clickhouse.Settings{"async_insert": 1, "wait_for_async_insert": 0}))
{
for i := 0; i < 10_000; i++ {
_, err := conn.ExecContext(ctx, fmt.Sprintf(`INSERT INTO benchmark_async VALUES (
Expand Down
2 changes: 1 addition & 1 deletion benchmark/v2/write-async/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ func benchmark(conn clickhouse.Conn) error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

ctx = clickhouse.Context(ctx, clickhouse.WithAsync(true))
ctx = clickhouse.Context(ctx, clickhouse.WithSettings(clickhouse.Settings{"async_insert": 1, "wait_for_async_insert": 1}))
for i := 0; i < 10_000; i++ {
err := conn.Exec(ctx, fmt.Sprintf(`INSERT INTO benchmark_async VALUES (
%d, '%s', [1, 2, 3, 4, 5, 6, 7, 8, 9], now()
Expand Down
3 changes: 2 additions & 1 deletion clickhouse.go
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,8 @@ func getPrepareBatchOptions(opts ...driver.PrepareBatchOption) driver.PrepareBat
return options
}

// Deprecated: use context aware `WithAsync()` for any async operations
// Deprecated: use Exec with WithSettings, with `async_insert` and
// `wait_for_async_insert`, instead. See WithAsync.
func (ch *clickhouse) AsyncInsert(ctx context.Context, query string, wait bool, args ...any) error {
conn, err := ch.acquire(ctx)
if err != nil {
Expand Down
15 changes: 14 additions & 1 deletion context.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,14 +185,27 @@ func WithExternalTable(t ...*ext.Table) QueryOption {
// A batch uses only the context that you give to PrepareBatch. With database/sql, a
// batch uses only the context that you give to PrepareContext. The context that you
// give to Stmt.ExecContext has no effect on the batch.
//
// Deprecated: ClickHouse 26.2 and later enable async insert by default, so with the
// default server settings WithAsync(true) has no effect. WithAsync(false) does not
// disable async insert: it only stops the client from waiting for the server, so the
// client does not get insert errors. Use WithSettings instead:
//
// WithSettings(Settings{"async_insert": 0}) // disable async insert
// WithSettings(Settings{"async_insert": 1, "wait_for_async_insert": 1}) // WithAsync(true)
// WithSettings(Settings{"async_insert": 1, "wait_for_async_insert": 0}) // WithAsync(false)
//
// WithSettings replaces the settings of an earlier WithSettings. If you already use
// WithSettings, add the async insert settings to the same Settings map.
func WithAsync(wait bool) QueryOption {
return func(o *QueryOptions) error {
o.async.ok, o.async.wait = true, wait
return nil
}
}

// Deprecated: use `WithAsync` instead.
// Deprecated: use WithSettings with `async_insert` and `wait_for_async_insert`
// instead. See WithAsync.
func WithStdAsync(wait bool) QueryOption {
return func(o *QueryOptions) error {
o.async.ok, o.async.wait = true, wait
Expand Down
101 changes: 71 additions & 30 deletions docs/clickhouse-api.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -235,50 +235,40 @@ Finally, note the ability to pass a `Context` to the `Query` and `QueryRow` meth

## Async insert {#async-insert}

Asynchronous inserts are supported through the Async method. This allows the user to specify whether the client should wait for the server to complete the insert or respond once the data has been received. This effectively controls the parameter [wait_for_async_insert](/reference/settings/session-settings#wait_for_async_insert).
With [async insert](https://clickhouse.com/docs/concepts/features/operations/insert/asyncinserts), the server keeps the data of many small inserts in a buffer and writes them together. Two server settings control it:

* [`async_insert`](/reference/settings/session-settings#async_insert): `1` enables async insert. `0` disables it.
* [`wait_for_async_insert`](/reference/settings/session-settings#wait_for_async_insert): `1` makes the server send the response after it writes the data. `0` makes the server send the response when it receives the data.

Set these settings with `WithSettings`. They apply to `Exec` and to batches from `PrepareBatch`, on the Native and HTTP protocols.

```go
conn, err := GetNativeConnection(nil, nil, nil)
if err != nil {
return err
}
ctx := context.Background()
if err := clickhouse_tests.CheckMinServerServerVersion(conn, 21, 12, 0); err != nil {
return nil
}
defer func() {
conn.Exec(ctx, "DROP TABLE example")
}()
conn.Exec(ctx, `DROP TABLE IF EXISTS example`)
const ddl = `
CREATE TABLE example (
Col1 UInt64
, Col2 String
, Col3 Array(UInt8)
, Col4 DateTime
) ENGINE = Memory
`
if err := conn.Exec(ctx, ddl); err != nil {
return err
}
ctx := clickhouse.Context(context.Background(), clickhouse.WithSettings(clickhouse.Settings{
"async_insert": 1,
"wait_for_async_insert": 1,
}))
for i := 0; i < 100; i++ {
if err := conn.AsyncInsert(ctx, fmt.Sprintf(`INSERT INTO example VALUES (
%d, '%s', [1, 2, 3, 4, 5, 6, 7, 8, 9], now()
)`, i, "Golang SQL database driver"), false); err != nil {
if err := conn.Exec(ctx, `INSERT INTO example VALUES (?, ?, [1, 2, 3, 4, 5, 6, 7, 8, 9], now())`,
i, "Golang SQL database driver"); err != nil {
return err
Comment thread
github-actions[bot] marked this conversation as resolved.
Resolved
}
}
```

[Full Example](https://github.com/ClickHouse/clickhouse-go/blob/main/examples/clickhouse_api/async_native.go)

If `wait_for_async_insert` is `0`, the insert is fast, but the client does not get insert errors. Look for errors in `system.asynchronous_insert_log`.

### Async insert with a batch {#async-insert-batch}

`WithAsync` also applies to batch inserts on the Native and HTTP protocols. A batch uses only the context that you give to `PrepareBatch`. `Send` sends the batch with the settings from that context.
A batch uses only the context that you give to `PrepareBatch`. `Send` sends the batch with the settings from that context.

```go
ctx := clickhouse.Context(context.Background(), clickhouse.WithAsync(true))
batch, err := conn.PrepareBatch(ctx, "INSERT INTO example") // WithAsync must be on this context
ctx := clickhouse.Context(context.Background(), clickhouse.WithSettings(clickhouse.Settings{
"async_insert": 1,
"wait_for_async_insert": 1,
}))
batch, err := conn.PrepareBatch(ctx, "INSERT INTO example") // the settings must be on this context
if err != nil {
return err
}
Expand All @@ -292,6 +282,57 @@ return batch.Send()

[Full Example](https://github.com/ClickHouse/clickhouse-go/blob/main/examples/clickhouse_api/async_native.go)

### Async insert is the default on ClickHouse 26.2 and later {#async-insert-default}

ClickHouse 26.2 and later set `async_insert=1` and `wait_for_async_insert=1` by default. Thus the server does not write an `INSERT` immediately. It keeps the data in a buffer for at least `async_insert_busy_timeout_min_ms` (50 ms by default). If inserts arrive frequently, the server increases this time up to `async_insert_busy_timeout_max_ms` (200 ms by default). Then it writes the buffer and sends the response.

With a low insert rate, each `INSERT` takes 50 ms or more. This occurs on the Native and HTTP protocols and with all clients. The delay occurs one time for each `INSERT`, not for each row.

If you send one row in each `Exec` call, one goroutine can do only approximately 5 to 20 inserts each second. To prevent this, do one of these steps:

* Send many rows in one `INSERT` with `PrepareBatch`.
* Disable async insert for the query:

```go
ctx := clickhouse.Context(context.Background(), clickhouse.WithSettings(clickhouse.Settings{
"async_insert": 0,
}))
if err := conn.Exec(ctx, "INSERT INTO example VALUES (1)"); err != nil {
return err
}
```

To disable async insert for all queries, set `"async_insert": 0` in `Options.Settings`.
* Set `wait_for_async_insert` to `0`. The insert is fast, but the client does not get insert errors.

### `WithAsync` and `AsyncInsert` are deprecated {#async-insert-deprecated}

`WithAsync`, `WithStdAsync` and `Conn.AsyncInsert` are deprecated. They will be removed in the next major version. They only set the two settings above, and `WithAsync(false)` does not disable async insert. It sets `async_insert=1` and `wait_for_async_insert=0`, so the client does not get insert errors.

| Deprecated | Replacement |
|---|---|
| `WithAsync(true)` | `WithSettings(clickhouse.Settings{"async_insert": 1, "wait_for_async_insert": 1})`. On ClickHouse 26.2 and later with the default server settings, you can remove it. |
| `WithAsync(false)`, `WithStdAsync(false)` | `WithSettings(clickhouse.Settings{"async_insert": 1, "wait_for_async_insert": 0})` |
| `conn.AsyncInsert(ctx, query, wait)` | `conn.Exec(ctx, query)` with the settings above on `ctx` |

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Nit — nit: migration table omits args and WithStdAsync(true)

The table does not show two forms that a caller can have, so the caller must guess the replacement.

  • AsyncInsert also takes args ...any. The replacement is conn.Exec(ctx, query, args...).
  • The first row lists WithAsync(true) only. WithStdAsync(true) has the same replacement.
Suggested change
| `conn.AsyncInsert(ctx, query, wait)` | `conn.Exec(ctx, query)` with the settings above on `ctx` |
| `conn.AsyncInsert(ctx, query, wait, args...)` | `conn.Exec(ctx, query, args...)` with the settings above on `ctx` |

| No replacement before: disable async insert | `WithSettings(clickhouse.Settings{"async_insert": 0})` |

`WithSettings` replaces the settings of an earlier `WithSettings`. It does not merge them. If you already use `WithSettings`, add the async insert settings to the same `Settings` map. If you use two `WithSettings` options, the server does not get the settings of the first one:

```go
// Incorrect: the second WithSettings removes async_insert and wait_for_async_insert.
ctx = clickhouse.Context(ctx,
clickhouse.WithSettings(clickhouse.Settings{"async_insert": 1, "wait_for_async_insert": 1}),
clickhouse.WithSettings(clickhouse.Settings{"log_comment": "import"}),
)

// Correct: all settings are in one map.
ctx = clickhouse.Context(ctx, clickhouse.WithSettings(clickhouse.Settings{
"async_insert": 1,
"wait_for_async_insert": 1,
"log_comment": "import",
}))
```

## Columnar insert {#columnar-insert}

Inserts can be inserted in column format. This can provide performance benefits if the data is already orientated in this structure by avoiding the need to pivot to rows.
Expand Down
2 changes: 1 addition & 1 deletion docs/config-reference.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -323,7 +323,7 @@ If the context has a deadline > 1s, `max_execution_time` is automatically set to
| `WithJWT` | `string` | `""` | HTTPS only | Per-query JWT override for ClickHouse Cloud. *(Since v2.35.0)* | Use for per-request auth in multi-tenant proxies. | Without TLS: ignored, falls back to connection auth. Expired: `"Token has expired"`. |
| `WithSettings` | `Settings` | Inherits connection | Both | Per-query server settings. Merged with connection settings; context wins on conflict. | Override `max_execution_time` or `max_rows_to_read` per query type. | Same as connection-level `Settings`. |
| `WithParameters` | `Parameters` (`map[string]string`) | `nil` | Both | Server-side parameterized query values. Query syntax: `{param_name:Type}`. Values use ClickHouse's [`Escaped` parameter text format](/integrations/language-clients/go/clickhouse-api#query-parameter-escaping). | Use instead of string concatenation for SQL injection safety. | Missing param: `"Substitution {param_name:Type} isn't set"`. Wrong type: `"Cannot parse string 'abc' as UInt64"`. |
| `WithAsync` | `bool` (wait) | Sync | Both | Async insert mode. Sets `async_insert=1`. `wait=true` adds `wait_for_async_insert=1`. Requires ClickHouse 21.11+. *(Since v2.41.0; supersedes the older `WithStdAsync`.)* | Use for high-throughput inserts. | `wait=false`: errors may be async -- check `system.asynchronous_insert_log`. With SELECT: ignored. Old server: `"Unknown setting async_insert"`. |
| `WithAsync` | `bool` (wait) | Sync | Both | **Deprecated.** Async insert mode. Sets `async_insert=1`. `wait=true` adds `wait_for_async_insert=1`. Requires ClickHouse 21.11+. *(Since v2.41.0; supersedes the older `WithStdAsync`.)* | Use `WithSettings` with `async_insert` and `wait_for_async_insert` instead. See [`WithAsync` and `AsyncInsert` are deprecated](/integrations/language-clients/go/clickhouse-api#async-insert-deprecated). | `wait=false`: errors may be async -- check `system.asynchronous_insert_log`. With SELECT: ignored. Old server: `"Unknown setting async_insert"`. Cannot disable async insert, which is on by default in ClickHouse 26.2+: use `WithSettings(Settings{"async_insert": 0})`. |
| `WithLogs` | `func(*Log)` | `nil` | Native only | Server log entries callback during query execution. | Keep fast -- blocks execution. Use goroutines for heavy processing. | On HTTP: silently never called. |
| `WithProgress` | `func(*Progress)` | `nil` | Native only | Query progress updates (rows/bytes processed). | Keep fast -- blocks execution. | On HTTP: silently never called. |
| `WithProfileInfo` | `func(*ProfileInfo)` | `nil` | Native only | Query execution statistics callback. | Keep fast -- blocks execution. | On HTTP: silently never called. |
Expand Down
Loading
Loading