From 95a461b8241585c018db48ac1d95e527c569c343 Mon Sep 17 00:00:00 2001 From: Vladimir Mihailenco Date: Sat, 3 Sep 2022 09:38:20 +0300 Subject: [PATCH] chore: use unhex to append bytes --- ch/chschema/append.go | 13 ++++++++++--- ch/db_test.go | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/ch/chschema/append.go b/ch/chschema/append.go index 9781113..93b97e0 100644 --- a/ch/chschema/append.go +++ b/ch/chschema/append.go @@ -2,12 +2,11 @@ package chschema import ( "database/sql/driver" + "encoding/hex" "fmt" "math" "strconv" "time" - - "github.com/uptrace/go-clickhouse/ch/internal" ) func Append(fmter Formatter, b []byte, v any) []byte { @@ -117,5 +116,13 @@ func AppendBytes(b []byte, bytes []byte) []byte { if bytes == nil { return AppendNull(b) } - return AppendString(b, internal.String(bytes)) + + tmp := make([]byte, hex.EncodedLen(len(bytes))) + hex.Encode(tmp, bytes) + + b = append(b, "unhex('"...) + b = append(b, tmp...) + b = append(b, "')"...) + + return b } diff --git a/ch/db_test.go b/ch/db_test.go index 27e3f5d..01a2c83 100644 --- a/ch/db_test.go +++ b/ch/db_test.go @@ -3,6 +3,7 @@ package ch_test import ( "context" "database/sql" + "encoding/hex" "fmt" "os" "reflect" @@ -337,6 +338,44 @@ type EventColumnar struct { CreatedAt []time.Time } +func TestClickhouse(t *testing.T) { + ctx := context.Background() + + db := chDB() + defer db.Close() + + tests := []func(ctx context.Context, t *testing.T, db *ch.DB){ + testWhereBytes, + } + for _, fn := range tests { + t.Run(funcName(fn), func(t *testing.T) { + fn(ctx, t, db) + }) + } +} + +func testWhereBytes(ctx context.Context, t *testing.T, db *ch.DB) { + type Data struct { + Bytes []byte + } + + err := db.ResetModel(ctx, (*Data)(nil)) + require.NoError(t, err) + + src, _ := hex.DecodeString("5C00CC") + data := &Data{Bytes: src} + + _, err = db.NewInsert().Model(data).Exec(context.Background()) + require.NoError(t, err) + + got := new(Data) + err = db.NewSelect().Model(got). + Where("bytes = ?", data.Bytes). + Scan(ctx) + require.NoError(t, err) + require.Equal(t, data.Bytes, got.Bytes) +} + func TestORM(t *testing.T) { ctx := context.Background()