diff --git a/docs/data-types.mdx b/docs/data-types.mdx index ea1d5c3c6b..eec46667ee 100644 --- a/docs/data-types.mdx +++ b/docs/data-types.mdx @@ -786,6 +786,12 @@ fmt.Printf("Col1: %v, Col2: %v\n", col1, col2) [Full Example](https://github.com/ClickHouse/clickhouse-go/blob/main/examples/clickhouse_api/bfloat16.go) +### JSON and Dynamic {#json-dynamic} + +With the legacy V1 Native format, the driver returns a decode error if `JSON` paths exceed `max_dynamic_paths` and use shared storage, or if a `Dynamic` value uses `SharedVariant` storage. This includes `Dynamic` values inside `JSON` columns. The error can occur on either the Native or HTTP transport. + +On ClickHouse 25.6 and later, set `output_format_native_use_flattened_dynamic_and_json_serialization=1` in `Options.Settings` or for the query to read these values. For a `readonly=1` user, an administrator can enable the setting in the user's settings profile. On earlier servers, use `CAST(json_column AS String)` to read `JSON` as a Go `string`, or cast `Dynamic` values to a concrete type in the query. ClickHouse 24.10 and later also supports `output_format_native_write_json_as_string=1` for `JSON` columns. + ### QBit {#qbit} `QBit` is an experimental column type for storing vector embeddings in bit-sliced format, optimized for vector similarity search. It requires the `allow_experimental_qbit_type` setting to be enabled. diff --git a/lib/column/dynamic_deprecated.go b/lib/column/dynamic_deprecated.go index b22c9d4158..5126c44b92 100644 --- a/lib/column/dynamic_deprecated.go +++ b/lib/column/dynamic_deprecated.go @@ -176,5 +176,8 @@ func (c *Dynamic) decodeData_v1(reader *proto.Reader, rows int) error { } } + if sharedIndex, ok := c.columnIndexByType["SharedVariant"]; ok && rowCountByType[sharedIndex] != 0 { + return unsupportedSharedDataError("Dynamic SharedVariant") + } return nil } diff --git a/lib/column/json_deprecated.go b/lib/column/json_deprecated.go index bf9ba21886..9ee422408b 100644 --- a/lib/column/json_deprecated.go +++ b/lib/column/json_deprecated.go @@ -1,6 +1,7 @@ package column import ( + "encoding/binary" "fmt" "github.com/ClickHouse/ch-go/proto" @@ -114,11 +115,38 @@ func (c *JSON) decodeObjectData_v1(reader *proto.Reader, rows int) error { } } - // SharedData per row, ignored for now. May cause stream offset issues if present - _, err := reader.ReadRaw(8 * rows) // one UInt64 per row - if err != nil { - return fmt.Errorf("failed to read shared data for json column: %w", err) + if err := c.decodeSharedData_v1(reader, rows); err != nil { + return err } return nil } + +func (c *JSON) decodeSharedData_v1(reader *proto.Reader, rows int) error { + if rows == 0 { + return nil + } + if rows < 0 || rows > int(^uint(0)>>1)/8 { + return fmt.Errorf("invalid json row count %d", rows) + } + offsets, err := reader.ReadRaw(8 * rows) + if err != nil { + return fmt.Errorf("failed to read shared data offsets for json column: %w", err) + } + var total uint64 + for i := 0; i < rows; i++ { + offset := binary.LittleEndian.Uint64(offsets[8*i:]) + if offset < total { + return fmt.Errorf("invalid shared data offsets for json column") + } + total = offset + } + if total == 0 { + return nil + } + return unsupportedSharedDataError("JSON shared data") +} + +func unsupportedSharedDataError(storage string) error { + return fmt.Errorf("cannot decode %s: on ClickHouse 25.6 or later, enable output_format_native_use_flattened_dynamic_and_json_serialization=1; for readonly=1, an administrator must set it to 1 in the settings profile or mark it changeable_in_readonly; on earlier servers, use CAST(json_column AS String) for JSON or cast Dynamic values to a concrete type in the query", storage) +} diff --git a/lib/column/json_deprecated_test.go b/lib/column/json_deprecated_test.go new file mode 100644 index 0000000000..5484c3e401 --- /dev/null +++ b/lib/column/json_deprecated_test.go @@ -0,0 +1,87 @@ +package column + +import ( + "bytes" + "encoding/binary" + "testing" + + "github.com/ClickHouse/ch-go/proto" + "github.com/stretchr/testify/require" + + "github.com/ClickHouse/clickhouse-go/v2/lib/chcol" +) + +func encodeSharedData(t *testing.T, rows [][][2]string) []byte { + t.Helper() + col, err := Type("Array(Tuple(String, String))").Column("", nil) + require.NoError(t, err) + for _, row := range rows { + pairs := make([][]any, len(row)) + for i, p := range row { + pairs[i] = []any{p[0], p[1]} + } + require.NoError(t, col.AppendRow(pairs)) + } + var buf proto.Buffer + col.Encode(&buf) + return buf.Buf +} + +func TestJSONDeprecatedSharedDataError(t *testing.T) { + for _, rows := range [][][][2]string{ + {{{"overflow", "\x0a\x0d\x00\x00\x00\x00\x00\x00\x00"}, {"other", "unreadable"}}}, + {{}, {{"overflow", "unreadable"}}}, + } { + payload := encodeSharedData(t, rows) + col := newTestJSONColumn(t) + col.serializationVersion = JSONDeprecatedObjectSerializationVersion + reader := proto.NewReader(bytes.NewReader(payload)) + err := col.Decode(reader, len(rows)) + require.ErrorContains(t, err, "cannot decode JSON shared data") + require.ErrorContains(t, err, "25.6") + require.ErrorContains(t, err, "output_format_native_use_flattened_dynamic_and_json_serialization=1") + require.ErrorContains(t, err, "changeable_in_readonly") + } +} + +func TestJSONDeprecatedSharedDataEmptyRoundtrip(t *testing.T) { + src := newTestJSONColumn(t) + require.NoError(t, src.AppendRow(map[string]any{"kept": int64(7)})) + + var buf proto.Buffer + require.NoError(t, src.WriteStatePrefix(&buf)) + src.Encode(&buf) + + dst := newTestJSONColumn(t) + reader := proto.NewReader(bytes.NewReader(buf.Buf)) + require.NoError(t, dst.ReadStatePrefix(reader)) + require.NoError(t, dst.Decode(reader, 1)) + + obj, ok := dst.Row(0, false).(*chcol.JSON) + require.True(t, ok) + kept, ok := chcol.ExtractJSONPathAs[int64](obj, "kept") + require.True(t, ok) + require.Equal(t, int64(7), kept) +} + +func TestJSONDeprecatedSharedDataMalformed(t *testing.T) { + var offsets [16]byte + binary.LittleEndian.PutUint64(offsets[:], 2) + binary.LittleEndian.PutUint64(offsets[8:], 1) + col := newTestJSONColumn(t) + require.ErrorContains(t, col.decodeSharedData_v1(proto.NewReader(bytes.NewReader(offsets[:])), 2), "invalid shared data offsets") + for _, payload := range [][]byte{nil, offsets[:7]} { + require.ErrorContains(t, col.decodeSharedData_v1(proto.NewReader(bytes.NewReader(payload)), 1), "failed to read shared data offsets") + } +} + +func TestDynamicDeprecatedSharedVariantError(t *testing.T) { + for _, raw := range []string{"", "unreadable", "\x0a\x0d\x00\x00\x00\x00\x00\x00\x00"} { + var buf proto.Buffer + buf.PutByte(0) + buf.PutString(raw) + col := &Dynamic{columns: []Interface{&SharedVariant{}}, columnIndexByType: map[string]int{"SharedVariant": 0}} + reader := proto.NewReader(bytes.NewReader(buf.Buf)) + require.ErrorContains(t, col.decodeData_v1(reader, 1), "cannot decode Dynamic SharedVariant") + } +} diff --git a/tests/issues/issue_1854_test.go b/tests/issues/issue_1854_test.go new file mode 100644 index 0000000000..5fa51570a2 --- /dev/null +++ b/tests/issues/issue_1854_test.go @@ -0,0 +1,96 @@ +package issues + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/ClickHouse/clickhouse-go/v2" + "github.com/ClickHouse/clickhouse-go/v2/lib/chcol" + clickhouse_tests "github.com/ClickHouse/clickhouse-go/v2/tests" + clickhouse_std_tests "github.com/ClickHouse/clickhouse-go/v2/tests/std" +) + +func TestIssue1854(t *testing.T) { + env, err := GetIssuesTestEnvironment() + require.NoError(t, err) + clickhouse_tests.TestProtocols(t, func(t *testing.T, protocol clickhouse.Protocol) { + settings := clickhouse.Settings{ + "allow_experimental_json_type": 1, + "allow_experimental_dynamic_type": 1, + "allow_experimental_variant_type": 1, + } + opts := clickhouse_tests.ClientOptionsFromEnv(env, settings, protocol == clickhouse.HTTP) + opts.MaxOpenConns, opts.MaxIdleConns = 1, 1 + t.Run("ClickHouse", func(t *testing.T) { + conn, err := clickhouse.Open(&opts) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, conn.Close()) }) + if !clickhouse_tests.CheckMinServerServerVersion(conn, 24, 8, 0) { + t.Skip("JSON requires ClickHouse 24.8") + } + checkIssue1854(t, clickhouse_tests.CheckMinServerServerVersion(conn, 25, 6, 0), func(ctx context.Context, q string, dest ...any) error { + return conn.QueryRow(ctx, q).Scan(dest...) + }) + }) + t.Run("database_sql", func(t *testing.T) { + db := clickhouse.OpenDB(&opts) + db.SetMaxOpenConns(1) + t.Cleanup(func() { require.NoError(t, db.Close()) }) + if !clickhouse_std_tests.CheckMinServerVersion(db, 24, 8, 0) { + t.Skip("JSON requires ClickHouse 24.8") + } + checkIssue1854(t, clickhouse_std_tests.CheckMinServerVersion(db, 25, 6, 0), func(ctx context.Context, q string, dest ...any) error { + return db.QueryRowContext(ctx, q).Scan(dest...) + }) + }) + }) +} + +func checkIssue1854(t *testing.T, supportsFlattened bool, scan func(context.Context, string, ...any) error) { + t.Helper() + const setting = "output_format_native_use_flattened_dynamic_and_json_serialization" + legacy := context.Background() + if supportsFlattened { + legacy = clickhouse.Context(legacy, clickhouse.WithSettings(clickhouse.Settings{setting: 0})) + } + for _, tc := range []struct{ name, expr, storage string }{ + {"JSON", `'{"x":13,"y":"east"}'::JSON(max_dynamic_paths=0)`, "JSON shared data"}, + {"JSON_Dynamic", `'{"x":13,"y":"east"}'::JSON(max_dynamic_types=0)`, "Dynamic SharedVariant"}, + {"Dynamic", `toInt64(13)::Dynamic(max_types=0)`, "Dynamic SharedVariant"}, + } { + t.Run(tc.name, func(t *testing.T) { + query := "SELECT " + tc.expr + ", 'tail'" + var doc chcol.JSON + var value chcol.Dynamic + var dest any = &doc + if tc.name == "Dynamic" { + dest = &value + } + var tail string + err := scan(legacy, query, dest, &tail) + require.ErrorContains(t, err, "cannot decode "+tc.storage) + require.ErrorContains(t, err, setting+"=1") + var one uint8 + require.NoError(t, scan(context.Background(), "SELECT toUInt8(1)", &one)) + require.Equal(t, uint8(1), one) + if !supportsFlattened { + return + } + flattened := clickhouse.Context(context.Background(), clickhouse.WithSettings(clickhouse.Settings{setting: 1})) + require.NoError(t, scan(flattened, query, dest, &tail)) + require.Equal(t, "tail", tail) + if tc.name == "Dynamic" { + require.Equal(t, int64(13), value.Any()) + return + } + x, ok := chcol.ExtractJSONPathAs[int64](&doc, "x") + require.True(t, ok) + require.Equal(t, int64(13), x) + y, ok := chcol.ExtractJSONPathAs[string](&doc, "y") + require.True(t, ok) + require.Equal(t, "east", y) + }) + } +}