MCPcopy
hub / github.com/ClickHouse/clickhouse-go

github.com/ClickHouse/clickhouse-go @v2.47.0 sqlite

repository ↗ · DeepWiki ↗ · release v2.47.0 ↗
2,707 symbols 15,605 edges 450 files 287 documented · 11%
README

ClickHouse run-tests Go Reference

Golang SQL database client for ClickHouse.

Install

go get github.com/ClickHouse/clickhouse-go/v2

Which interface should I use?

clickhouse.Open (native) sql.Open / clickhouse.OpenDB (std)
Performance Faster (direct column encoding) Slower (see benchmark)
API driver.Conn — ClickHouse-specific Standard database/sql
Use when new code, performance-sensitive work existing database/sql tooling, ORMs

Both support TCP and HTTP transport. When in doubt, use the native interface.

Key features

  • Uses ClickHouse native format for optimal performance. Utilises low level ch-go client for encoding/decoding and compression (versions >= 2.3.0).
  • Supports both native ClickHouse TCP and HTTP client-server protocols
  • Compatibility with database/sql (slower than native interface!)
  • database/sql supports both native TCP and HTTP protocols for transport.
  • Marshal rows into structs (ScanStruct, Select)
  • Unmarshal struct to row (AppendStruct)
  • Connection pool (for both TCP-Native and HTTP)
  • Failover and load balancing
  • Bulk write support (for database/sql use begin->prepare->(in loop exec)->commit)
  • PrepareBatch options
  • AsyncInsert (more details in Async insert section)
  • Named and numeric placeholders support
  • LZ4/ZSTD/LZ4HC/GZIP/Deflate/Brotli compression support
  • External data
  • Query parameters
  • Structured logging via log/slog (Logger option)
  • JWT authentication support
  • Wide type support: BFloat16, QBit, Dynamic, Variant, Time, Time64, LineString, MultiLineString, and more

Support for the ClickHouse protocol advanced features using Context:

  • Query ID
  • Quota Key
  • Settings
  • Query parameters
  • OpenTelemetry
  • Execution events:
    • Logs
    • Progress
    • Profile info
    • Profile events

Supported ClickHouse Versions

The client is tested against the currently supported versions of ClickHouse

Supported Golang Versions

Client Version Golang Versions
>= 2.0 <= 2.2 1.17, 1.18
>= 2.3 1.18.4+, 1.19
>= 2.14 1.20, 1.21
>= 2.19 1.21, 1.22
>= 2.28 1.22, 1.23
>= 2.29 1.21, 1.22, 1.23, 1.24
>= 2.41 1.24, 1.25

Documentation

https://clickhouse.com/docs/en/integrations/go

clickhouse interface (formerly native interface)

    conn, err := clickhouse.Open(&clickhouse.Options{
        Addr: []string{"127.0.0.1:9000"},
        Auth: clickhouse.Auth{
            Database: "default",
            Username: "default",
            Password: "",
        },
        DialContext: func(ctx context.Context, addr string) (net.Conn, error) {
            dialCount++
            var d net.Dialer
            return d.DialContext(ctx, "tcp", addr)
        },
        // Logger is the recommended way to enable logging (see Logging section).
        // Debug and Debugf are deprecated in favour of Logger.
        Logger: slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
            Level: slog.LevelDebug,
        })),
        Settings: clickhouse.Settings{
            "max_execution_time": 60,
        },
        Compression: &clickhouse.Compression{
            Method: clickhouse.CompressionLZ4,
        },
        DialTimeout:      time.Second * 30,
        MaxOpenConns:     5,
        MaxIdleConns:     5,
        ConnMaxLifetime:  time.Duration(10) * time.Minute,
        ConnOpenStrategy: clickhouse.ConnOpenInOrder,
        BlockBufferSize: 10,
        MaxCompressionBuffer: 10240,
        ClientInfo: clickhouse.ClientInfo{ // optional, please see Client info section in the README.md
            Products: []struct {
                Name    string
                Version string
            }{
                {Name: "my-app", Version: "0.1"},
            },
        },
    })
    if err != nil {
        return err
    }
    return conn.Ping(context.Background())

database/sql interface

OpenDB

conn := clickhouse.OpenDB(&clickhouse.Options{
    Addr: []string{"127.0.0.1:9999"},
    Auth: clickhouse.Auth{
        Database: "default",
        Username: "default",
        Password: "",
    },
    TLS: &tls.Config{
        InsecureSkipVerify: true,
    },
    Settings: clickhouse.Settings{
        "max_execution_time": 60,
    },
    DialTimeout: time.Second * 30,
    Compression: &clickhouse.Compression{
        Method: clickhouse.CompressionLZ4,
    },
    // Debug is deprecated; use Logger instead (see Logging section).
    BlockBufferSize: 10,
    MaxCompressionBuffer: 10240,
    ClientInfo: clickhouse.ClientInfo{ // optional, please see Client info section in the README.md
        Products: []struct {
            Name    string
            Version string
        }{
            {Name: "my-app", Version: "0.1"},
        },
    },
})
conn.SetMaxIdleConns(5)
conn.SetMaxOpenConns(10)
conn.SetConnMaxLifetime(time.Hour)

DSN

  • hosts - comma-separated list of single address hosts for load-balancing and failover
  • username/password - auth credentials
  • database - select the current default database
  • dial_timeout - a duration string is a possibly signed sequence of decimal numbers, each with optional fraction and a unit suffix such as "300ms", "1s". Valid time units are "ms", "s", "m". (default 30s)
  • connection_open_strategy - random/round_robin/in_order (default in_order).
    • random - choose random server from the set
    • round_robin - choose a round-robin server from the set
    • in_order - first live server is chosen in specified order
  • debug - enable debug output (boolean value)
  • compress - specify the compression algorithm: none (default), zstd, lz4, lz4hc, gzip, deflate, br. If set to true, lz4 will be used. For HTTP connections, gzip/deflate/br use HTTP web compression, while lz4/zstd use ClickHouse native block compression over HTTP (lz4hc is native-only).
  • compress_level - Level of compression (algorithm-specific, default is 3 when compression is enabled):
  • gzip/deflate: -2 (Best Speed) to 9 (Best Compression)
  • br: 0 (Best Speed) to 11 (Best Compression)
  • zstd/lz4/lz4hc: ignored
  • block_buffer_size - size of block buffer (default 2)
  • read_timeout - a duration string is a possibly signed sequence of decimal numbers, each with optional fraction and a unit suffix such as "300ms", "1s". Valid time units are "ms", "s", "m" (default 5m).
  • max_compression_buffer - max size (bytes) of compression buffer during column by column compression (default 10MiB)
  • client_info_product - optional list (comma separated) of product name and version pair separated with /. This value will be pass a part of client info. e.g. client_info_product=my_app/1.0,my_module/0.1 More details in Client info section.
  • http_proxy - HTTP proxy address
  • http_path - URL path for HTTP requests (e.g. for proxies or custom endpoints that require a specific path)
  • tls_server_name - set TLS SNI/verification name (sets tls.Config.ServerName when secure=true)

Connection Settings Reference

The following connection settings are available in both DSN strings and the clickhouse.Options struct:

Timeout Settings

  • dial_timeout - Connection timeout for establishing a connection to the server (default: 30s)
  • read_timeout - Timeout for reading server responses (default: 5m)

Connection Pool Settings

  • max_open_conns - Maximum number of open connections to the database (default: MaxIdleConns + 5)
  • max_idle_conns - Maximum number of idle connections in the pool (default: 5)
  • conn_max_lifetime - Maximum amount of time a connection may be reused (default: 1h)

Connection Strategy

  • connection_open_strategy - Strategy for selecting servers from the connection pool:
  • in_order - Choose the first available server in the specified order (default)
  • round_robin - Choose servers in a round-robin fashion
  • random - Choose a random server from the pool

Compression Settings

  • compress - Enable compression with a specific algorithm: none, zstd, lz4, lz4hc, gzip, deflate, br. If set to true, lz4 will be used (default: none). For HTTP connections, gzip/deflate/br use HTTP web compression, while lz4/zstd use ClickHouse native block compression over HTTP (lz4hc is native-only).
  • compress_level - Compression level (algorithm-specific):
  • gzip/deflate: -2 (Best Speed) to 9 (Best Compression)
  • br: 0 (Best Speed) to 11 (Best Compression)
  • zstd/lz4: ignored
  • max_compression_buffer - Maximum size of compression buffer in bytes (default: 10MiB)

Buffer Settings

  • block_buffer_size - Size of block buffer (default: 2)

Debug Settings

  • debug - Enable debug output (boolean value)

SSL/TLS Settings

  • secure - Establish secure connection (default: false)
  • skip_verify - Skip certificate verification (default: false)

Client Information

  • client_info_product - Comma-separated list of product name and version pairs (e.g., my_app/1.0,my_module/0.1)

HTTP Settings

  • http_proxy - HTTP proxy address for HTTP protocol connections

Example:

clickhouse://username:password@host1:9000,host2:9000/database?dial_timeout=200ms&read_timeout=30s&max_execution_time=60

HTTP Support

The native format can be used over the HTTP protocol. This is useful in scenarios where users need to proxy traffic e.g. using ChProxy or via load balancers.

This can be achieved by modifying the DSN to specify the HTTP protocol.

http://host1:8123,host2:8123/database?dial_timeout=200ms&max_execution_time=60

Alternatively, use OpenDB and specify the interface type.

conn := clickhouse.OpenDB(&clickhouse.Options{
    Addr: []string{"127.0.0.1:8123"},
    Auth: clickhouse.Auth{
        Database: "default",
        Username: "default",
        Password: "",
    },
    Settings: clickhouse.Settings{
        "max_execution_time": 60,
    },
    DialTimeout: 30 * time.Second,
    Compression: &clickhouse.Compression{
        Method: clickhouse.CompressionLZ4,
    },
    Protocol:  clickhouse.HTTP,
})

Proxy support

HTTP proxy can be set in the DSN string by specifying the http_proxy parameter. (make sure to URL encode the proxy address)

http://host1:8123,host2:8123/database?dial_timeout=200ms&max_execution_time=60&http_proxy=http%3A%2F%2Fproxy%3A8080

If you are using clickhouse.OpenDB, set the HTTPProxyURL field in the clickhouse.Options.

An alternative way is to enable proxy by setting the HTTP_PROXY (for HTTP) or HTTPS_PROXY (for HTTPS) environment variables. See more details in the Go documentation.

Compression

Compression is supported over native and HTTP protocols.

Native protocol supports lz4, lz4hc, and zstd.

HTTP protocol supports lz4 and zstd via ClickHouse native block compression over HTTP, and gzip, deflate, and br via HTTP web compression.

HTTP: Web Compression vs Native Block Compression

When using the HTTP protocol there are two independent compression layers:

  1. HTTP web compression (whole request/response body). This uses HTTP headers (Accept-Encoding and Content-Encoding). In ClickHouse, response compression is controlled by the enable_http_compression setting (pass it via Options.Settings or DSN query params). In clickhouse-go this mode is used when Compression.Method is gzip, deflate, or br.

  2. ClickHouse native block compression over HTTP (Native format blocks). This uses ClickHouse HTTP query parameters: compress=1 (server compresses response blocks) and decompress=1 (server expects a compressed request body). In clickhouse-go this mode is used when Compression.Method is lz4 or zstd.

Avoid enabling both at the same time unless you've measured it, as it can waste CPU by compressing already-compressed native blocks.

Note: you normally don't need to set compress=1 or decompress=1 yourself when using clickhouse-go; selecting an appropriate Compression.Method will configure the HTTP request correctly.

When using a DSN, compression can be enabled via the compress parameter. Set it to a specific algorithm name (zstd, lz4, lz4hc, gzip, deflate, br) or to true as shorthand for lz4. See the DSN section for details.

TLS/SSL

At a low level all client connect methods (DSN/OpenDB/Open) will use the Go tls package to establish a secure connection. The client knows to use TLS if the Options struct contains a non-nil tls.Config pointer.

Setting secure in the DSN creates a minimal tls.Config struct with only the InsecureSkipVerify field set (either true or false). It is equivalent to this code:

conn := clickhouse.OpenDB(&clickhouse.Options{
    ...
    TLS: &tls.Config{
            InsecureSkipVerify: false
    }
    ...
    })

This minimal tls.Config is normally all that is necessary to connect to the secure native port (normally 9440) on a ClickHouse server. If the ClickHouse server does not have a valid certificate (expired, wrong host name, not signed by a publicly recognized root Certificate Authority), InsecureSkipVerify can be to true, but that

Extension points exported contracts — how you extend this code

Interface (Interface)
(no doc) [46 implementers]
lib/column/column.go
BatchColumn (Interface)
(no doc) [47 implementers]
lib/driver/driver.go
JSONSerializer (Interface)
JSONSerializer interface allows a struct to be manually converted to an optimized JSON structure instead of relying on r [2 …
lib/chcol/json.go
Dial (FuncType)
(no doc)
clickhouse_options.go
QueryOption (FuncType)
(no doc)
context.go
CustomSerialization (Interface)
(no doc) [10 implementers]
lib/column/column.go
Batch (Interface)
Batch represents a prepared INSERT that buffers rows client-side and sends them to ClickHouse. Typical usage: batch, [2 …
lib/driver/driver.go
JSONDeserializer (Interface)
JSONDeserializer interface allows a struct to load its data from an optimized JSON structure instead of relying on recur [2 …
lib/chcol/json.go

Core symbols most depended-on inside this repo

Exec
called by 1043
lib/driver/driver.go
Scan
called by 583
lib/driver/driver.go
Append
called by 500
lib/driver/driver.go
Append
called by 385
lib/column/column.go
PrepareBatch
called by 366
lib/driver/driver.go
Send
called by 338
lib/driver/driver.go
QueryRow
called by 308
lib/driver/driver.go
Close
called by 306
lib/driver/driver.go

Shape

Function 1,275
Method 1,168
Struct 211
TypeAlias 28
Interface 17
FuncType 8

Languages

Go100%

Modules by API surface

lib/column/column_gen.go133 symbols
tests/utils.go62 symbols
lib/driver/driver.go48 symbols
examples/clickhouse_api/main_test.go48 symbols
clickhouse_std.go45 symbols
clickhouse.go43 symbols
lib/column/json.go42 symbols
conn_http.go36 symbols
lib/column/geo_test.go35 symbols
conn_pool_test.go34 symbols
context.go33 symbols
examples/std/main_test.go31 symbols

Dependencies from manifests, versioned

dario.cat/mergov1.0.2 · 1×
github.com/Azure/go-ansitermv0.0.0-2025010203350 · 1×
github.com/ClickHouse/ch-gov0.73.0 · 1×
github.com/Microsoft/go-winiov0.6.2 · 1×
github.com/andybalholm/brotliv1.2.1 · 1×
github.com/cespare/xxhash/v2v2.3.0 · 1×
github.com/containerd/errdefsv1.0.0 · 1×
github.com/containerd/errdefs/pkgv0.3.0 · 1×
github.com/containerd/logv0.1.0 · 1×
github.com/containerd/platformsv0.2.1 · 1×
github.com/cpuguy83/dockercfgv0.3.2 · 1×

For agents

$ claude mcp add clickhouse-go \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact