Repository navigation
fix: request flattened JSON and Dynamic output by default #2149
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
9f373e7
32584f7
3cb33ca
ee0a887
40a6e7e
9167710
a348b54
53d2608
c16c412
a557a61
4db09d1
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 | ||
| } | ||
|
|
@@ -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) { | ||
|
|
@@ -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 | ||
| } | ||
|
|
@@ -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 | ||
| } | ||
|
|
@@ -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) | ||
| } | ||
| } | ||
| 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) | ||
| } | ||
|
|
@@ -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) }() | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
| } | ||
|
|
||
| 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) | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.