Skip to content
Draft
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
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,7 @@ conn.SetConnMaxLifetime(time.Hour)
* 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`)
* disable_auto_flattened_json_output - disable the automatic flattened output setting for `JSON` and `Dynamic` and its connection probe (default `false`). See [JSON and Dynamic serialization](https://clickhouse.com/docs/integrations/language-clients/go/config-reference#json-serialization).

## Connection Settings Reference

Expand Down Expand Up @@ -621,6 +622,10 @@ For `clickhouse.Conn.PrepareBatch` (native interface):
- Use `Send` to flush any remaining rows and finalize the INSERT. After `Send`, the batch is considered sent and should not be reused.
- Use `defer batch.Close()` to ensure resources are released if `Send` is not reached.

## JSON and Dynamic results

On ClickHouse 25.6 and later, the driver requests flattened output for `JSON` and `Dynamic` by default when the connection probe confirms that the user's settings profile permits it. This applies to both APIs and both protocols. See [JSON and Dynamic serialization](https://clickhouse.com/docs/integrations/language-clients/go/config-reference#json-serialization) for probe failures, explicit overrides, `Options.DisableAutoFlattenedJSONOutput`, and session behavior, and [read limitations](https://clickhouse.com/docs/integrations/language-clients/go/data-types#json-dynamic) for older servers and restricted profiles.

## JSON columns: append contract

The ClickHouse Native protocol requires **one serialization version per `JSON` column per block** — a column cannot mix `object` rows and `string` rows on the wire. The driver enforces this at append time.
Expand Down
13 changes: 13 additions & 0 deletions clickhouse_options.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,14 @@ type Options struct {
// instead of Logger.
Logger *slog.Logger

// DisableAutoFlattenedJSONOutput disables the automatic flattened JSON and Dynamic
// output setting and its connection probe on ClickHouse 25.6 and later.
// Explicit settings still apply.
// Sessions that change readonly, profiles, or roles after connecting can receive
// READONLY or SETTING_CONSTRAINT_VIOLATION errors from this default. Set this
// option to true to avoid the automatic default.
DisableAutoFlattenedJSONOutput bool

Settings Settings
Compression *Compression
DialTimeout time.Duration // default 30 second
Expand Down Expand Up @@ -232,6 +240,11 @@ func (o *Options) fromDSN(in string) error {

for v := range params {
switch v {
case "disable_auto_flattened_json_output":
o.DisableAutoFlattenedJSONOutput, err = strconv.ParseBool(params.Get(v))
if err != nil {
return fmt.Errorf("clickhouse [dsn parse]: invalid disable_auto_flattened_json_output: %w", err)
}
case "hosts":
o.Addr = append(parseHostList(params.Get(v)), o.Addr...)
case "alt_hosts":
Expand Down
25 changes: 22 additions & 3 deletions conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,14 @@ func dial(ctx context.Context, addr string, num int, opt *Options) (*connect, er
return nil, err
}
}
if opt.useFlattenedJSON(supportsFlattenedJSON(connect.server.Version), nil) {
if err := connect.probeJSONSerialization(ctx); err != nil {
if closeErr := conn.Close(); closeErr != nil {
connect.logger.Debug("failed to close connection after JSON settings probe", slog.Any("error", closeErr))
}
return nil, err
}
}

// warn only on the first connection in the pool
if num == 1 && !proto.CheckMinVersion(resources.MinSupportedVersion, connect.server.Version) {
Expand Down Expand Up @@ -135,6 +143,9 @@ type connect struct {
readTimeout time.Duration
blockBufferSize uint8
maxCompressionBuffer int
flattenedJSON bool
automaticJSON bool
jsonSerialization jsonSerializationState
readerMutex sync.Mutex
closeMutex sync.Mutex
// clusterSalt signs queries on this connection.
Expand Down Expand Up @@ -168,7 +179,7 @@ func (c *connect) serverVersion() (*ServerVersion, error) {
return &c.server, nil
}

func (c *connect) settings(querySettings Settings) []proto.Setting {
func (c *connect) settings(querySettings Settings) ([]proto.Setting, bool) {
settingToProtoSetting := func(k string, v any) proto.Setting {
isCustom := false
if cv, ok := v.(CustomSetting); ok {
Expand All @@ -184,16 +195,24 @@ func (c *connect) settings(querySettings Settings) []proto.Setting {
}
}

settings := make([]proto.Setting, 0, len(c.opt.Settings)+len(querySettings))
useFlattenedJSON := c.opt.useFlattenedJSON(c.flattenedJSON && !c.jsonSerialization.disabled.Load(), querySettings)
capacity := len(c.opt.Settings) + len(querySettings)
if useFlattenedJSON {
capacity++
}
settings := make([]proto.Setting, 0, capacity)
for k, v := range c.opt.Settings {
settings = append(settings, settingToProtoSetting(k, v))
}

for k, v := range querySettings {
settings = append(settings, settingToProtoSetting(k, v))
}
if useFlattenedJSON {
settings = append(settings, settingToProtoSetting(flattenedJSONSetting, 1))
}

return settings
return settings, useFlattenedJSON
}

func (c *connect) healthCheck() error {
Expand Down
32 changes: 29 additions & 3 deletions conn_http.go
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,14 @@ func dialHttp(ctx context.Context, addr string, num int, opt *Options) (*httpCon
}
conn.handshake = handshake
conn.revision = conn.handshake.Revision
if opt.useFlattenedJSON(supportsFlattenedJSON(conn.handshake.Version), nil) {
if err := conn.probeJSONSerialization(ctx); err != nil {
if closeErr := conn.close(); closeErr != nil {
conn.logger.Debug("failed to close connection after JSON settings probe", slog.Any("error", closeErr))
}
return nil, err
}
}

return &conn, nil
}
Expand Down Expand Up @@ -291,6 +299,8 @@ type httpConnect struct {
// it stays false for a user with readonly = 1, because the server rejects a request
// that changes a setting for such a user.
compressionSettings bool
flattenedJSON bool
jsonSerialization jsonSerializationState
}

func (h *httpConnect) serverVersion() (*ServerVersion, error) {
Expand Down Expand Up @@ -662,7 +672,7 @@ func (h *httpConnect) sendStreamQuery(ctx context.Context, r io.Reader, options
return nil, err
}

res, err := h.executeRequest(req)
res, err := h.executeRequest(req, options != nil && options.autoJSON)
if err != nil {
return nil, err
}
Expand All @@ -676,7 +686,7 @@ func (h *httpConnect) sendQuery(ctx context.Context, query string, options *Quer
return nil, err
}

res, err := h.executeRequest(req)
res, err := h.executeRequest(req, options != nil && options.autoJSON)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -732,6 +742,21 @@ func (h *httpConnect) createRequest(ctx context.Context, requestUrl string, read
var query url.Values
if options != nil {
query = req.URL.Query()
if options.settingsProbe {
for key := range h.opt.Settings {
switch key {
case "session_id", "session_timeout", "session_check":
default:
query.Del(key)
Comment thread
polyglotAI-bot marked this conversation as resolved.
Resolved
}
}
query.Set("default_format", "Native")
query.Set("client_protocol_version", strconv.Itoa(ClientTCPProtocolVersion))
}
options.autoJSON = !options.settingsProbe && !options.rawFormat && h.opt.useFlattenedJSON(h.flattenedJSON && !h.jsonSerialization.disabled.Load(), options.settings)
if options.autoJSON {
query.Set(flattenedJSONSetting, "1")
}
if options.queryID != "" {
query.Set(queryIDParamName, options.queryID)
}
Expand Down Expand Up @@ -806,7 +831,8 @@ func (h *httpConnect) createRequestWithExternalTables(ctx context.Context, query
return h.createRequest(ctx, currentUrl.String(), bytes.NewReader(payload.Bytes()), options, headers)
}

func (h *httpConnect) executeRequest(req *http.Request) (*http.Response, error) {
func (h *httpConnect) executeRequest(req *http.Request, automaticJSON bool) (_ *http.Response, err error) {
defer func() { h.jsonSerialization.observeError(automaticJSON, err) }()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The server checks settings before it writes the status line, so a 164 or 452 for this setting comes back as a non-200 response and executeRequest sees it. CI shows it as HTTP 500. Leaving this as is.

if h.client == nil {
return nil, sqldriver.ErrBadConn
}
Expand Down
4 changes: 3 additions & 1 deletion conn_http_format.go
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,7 @@ func (s *httpFormatStream) Close() error {
func (h *httpConnect) queryFormat(ctx context.Context, release nativeTransportRelease, formatName string, query string, args ...any) (io.ReadCloser, error) {
h.logger.Debug("HTTP format query", slog.String("sql", query), slog.String("format", formatName))
options := queryOptions(ctx)
options.rawFormat = true
query, err := bindQueryOrAppendParameters(true, &options, query, h.handshake.Timezone, args...)
if err != nil {
err = fmt.Errorf("bindQueryOrAppendParameters: %w", err)
Expand Down Expand Up @@ -316,7 +317,7 @@ func (h *httpConnect) queryFormat(ctx context.Context, release nativeTransportRe
q.Set("default_format", formatName)
req.URL.RawQuery = q.Encode()

res, err := h.executeRequest(req) //nolint:bodyclose // closed via httpFormatStream.Close
res, err := h.executeRequest(req, false) //nolint:bodyclose // closed via httpFormatStream.Close
if err != nil {
release(h, err)
return nil, err
Expand Down Expand Up @@ -369,6 +370,7 @@ func (h *httpConnect) insertFormat(ctx context.Context, release nativeTransportR
}

options := queryOptions(ctx)
options.rawFormat = true
headers := make(map[string]string)
body := data
switch h.compression {
Expand Down
148 changes: 148 additions & 0 deletions conn_json.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
package clickhouse

import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"strings"
"sync/atomic"

chproto "github.com/ClickHouse/ch-go/proto"

"github.com/ClickHouse/clickhouse-go/v2/lib/proto"
)

const flattenedJSONSetting = "output_format_native_use_flattened_dynamic_and_json_serialization"
const jsonSerializationProbe = `SELECT toUInt8(countIf(
readonly = 0 AND (max IS NULL OR max = '1')
) = 1) FROM system.settings WHERE name = '` + flattenedJSONSetting + `'`

type jsonSerializationState struct{ disabled atomic.Bool }

func (s *jsonSerializationState) observeError(automatic bool, err error) {
var exception *Exception
if automatic && errors.As(err, &exception) && (exception.Code == 164 || exception.Code == 452) && strings.Contains(exception.Message, flattenedJSONSetting) {
s.disabled.Store(true)
}
}

func supportsFlattenedJSON(version proto.Version) bool {
return proto.CheckMinVersion(proto.Version{Major: 25, Minor: 6}, version)
}

func (o *Options) useFlattenedJSON(enabled bool, querySettings Settings) bool {
if !enabled || o.DisableAutoFlattenedJSONOutput {
return false
}
if _, ok := o.Settings[flattenedJSONSetting]; ok {
return false
}
_, ok := querySettings[flattenedJSONSetting]
return !ok
}

func readJSONSerializationSettings(block *proto.Block) (bool, error) {
if block.Rows() != 1 || len(block.Columns) != 1 {
return false, errors.New("unexpected json settings probe result")
}
var allowed uint8
if err := block.Columns[0].ScanRow(&allowed, 0); err != nil {
return false, err
}
return allowed == 1, nil
}

func (c *connect) probeJSONSerialization(ctx context.Context) (err error) {
ctx, cancel := context.WithTimeout(ctx, c.opt.DialTimeout)
defer cancel()
defer func() {
if ctx.Err() != nil {
err = fmt.Errorf("json settings probe: %w", ctx.Err())
return
}
var exception *Exception
if errors.As(err, &exception) {
c.flattenedJSON = false
c.logger.Warn("JSON settings probe failed, automatic "+flattenedJSONSetting+" disabled, set DisableAutoFlattenedJSONOutput to skip the probe", slog.Any("error", err))
err = nil
}
}()
if ctx.Err() != nil {
return ctx.Err()
}
c.startReadWriteTimeout(ctx)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This is the same as every other Native query path, which also ignores this error. Returning it here would fail the dial for connections that cannot take deadlines, like SSH tunnels. We track the general fix for writes on such connections separately, so I'm leaving it out of this PR.

defer c.clearReadWriteTimeout(ctx)
options := QueryOptions{settingsProbe: true}
on := options.onProcess()
var enabled bool
scanErr := errors.New("no rows returned for json settings probe")
on.data = func(block *proto.Block) {
if block.Packet == proto.ServerData && scanErr != nil {
enabled, scanErr = readJSONSerializationSettings(block)
}
}
if err = c.sendQuery(jsonSerializationProbe, &options); err == nil {
err = c.process(ctx, on)
}
if err != nil {
return fmt.Errorf("json settings probe: %w", err)
}
if scanErr != nil {
return fmt.Errorf("json settings probe: %w", scanErr)
}
c.flattenedJSON = enabled
return nil
}

func (h *httpConnect) probeJSONSerialization(ctx context.Context) (err error) {
ctx, cancel := context.WithTimeout(ctx, h.opt.DialTimeout)
defer cancel()
defer func() {
if ctx.Err() != nil {
err = fmt.Errorf("json settings probe: %w", ctx.Err())
return
}
var exception *Exception
if errors.As(err, &exception) {
h.flattenedJSON = false
h.logger.Warn("JSON settings probe failed, automatic "+flattenedJSONSetting+" disabled, set DisableAutoFlattenedJSONOutput to skip the probe", slog.Any("error", err))
err = nil
}
}()
options := QueryOptions{settingsProbe: true, settings: make(Settings)}
h.applyNativeCompressionSettings(options.settings, false)
res, err := h.sendQuery(ctx, jsonSerializationProbe, &options, nil) //nolint:bodyclose // closed below
if err != nil {
return fmt.Errorf("json settings probe: %w", err)
}
defer discardAndClose(res.Body)
rw := h.compressionPool.Get()
defer h.compressionPool.Put(rw)
reader, err := rw.NewReader(res)
if err != nil {
return fmt.Errorf("json settings probe: %w", err)
}
captured := &capturingReader{reader: reader}
chReader := chproto.NewReader(captured)
scanErr := errors.New("no rows returned for json settings probe")
var enabled bool
for {
block, err := h.readData(chReader, nil, &captured.buffer)
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return fmt.Errorf("json settings probe: %w", err)
}
if block.Rows() != 0 && scanErr != nil {
enabled, scanErr = readJSONSerializationSettings(block)
}
}
if scanErr != nil {
return fmt.Errorf("json settings probe: %w", scanErr)
}
h.flattenedJSON = enabled
return nil
}
Loading
Loading