Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

chore: impl Query2 for clickhouse (#6357)

rebelicef51c0d209bcb
diff --git a/backend/plugin/db/clickhouse/clickhouse.go b/backend/plugin/db/clickhouse/clickhouse.go
index 6c93a89d0f..164335e106 100644
--- a/backend/plugin/db/clickhouse/clickhouse.go
+++ b/backend/plugin/db/clickhouse/clickhouse.go
@@ -5,12 +5,19 @@ import (
"context"
"database/sql"
"fmt"
+ "math/big"
+ "reflect"
"strings"
"time"
clickhouse "github.com/ClickHouse/clickhouse-go/v2"
+ "github.com/google/uuid"
+ "github.com/paulmach/orb"
+ "github.com/paulmach/orb/encoding/wkt"
"github.com/pkg/errors"
+ "github.com/shopspring/decimal"
"go.uber.org/zap"
+ "google.golang.org/protobuf/types/known/structpb"
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/common/log"
@@ -160,6 +167,287 @@ func (driver *Driver) QueryConn(ctx context.Context, conn *sql.Conn, statement s
}
// QueryConn2 queries a SQL statement in a given connection.
-func (*Driver) QueryConn2(_ context.Context, _ *sql.Conn, _ string, _ *db.QueryContext) ([]*v1pb.QueryResult, error) {
- return nil, errors.New("not implemented")
+func (driver *Driver) QueryConn2(ctx context.Context, conn *sql.Conn, statement string, queryContext *db.QueryContext) ([]*v1pb.QueryResult, error) {
+ // TODO(rebelice): implement multi-statement query
+ var results []*v1pb.QueryResult
+
+ result, err := driver.querySingleSQL(ctx, conn, statement, queryContext)
+ if err != nil {
+ results = append(results, &v1pb.QueryResult{
+ Error: err.Error(),
+ })
+ } else {
+ results = append(results, result)
+ }
+
+ return results, nil
+}
+
+func getStatementWithResultLimit(stmt string, limit int) string {
+ return fmt.Sprintf("WITH result AS (%s) SELECT * FROM result LIMIT %d;", stmt, limit)
+}
+
+func (*Driver) querySingleSQL(ctx context.Context, conn *sql.Conn, statement string, queryContext *db.QueryContext) (*v1pb.QueryResult, error) {
+ statement = strings.TrimRight(statement, " \n\t;")
+
+ if !strings.HasPrefix(statement, "EXPLAIN") && queryContext.Limit > 0 {
+ statement = getStatementWithResultLimit(statement, queryContext.Limit)
+ }
+
+ // Clickhouse doesn't support READ ONLY transactions (Error: sql: driver does not support read-only transactions).
+ if queryContext.ReadOnly {
+ queryContext.ReadOnly = false
+ }
+
+ tx, err := conn.BeginTx(ctx, &sql.TxOptions{ReadOnly: queryContext.ReadOnly})
+ if err != nil {
+ return nil, err
+ }
+ defer tx.Rollback()
+
+ rows, err := tx.QueryContext(ctx, statement)
+ if err != nil {
+ return nil, util.FormatErrorWithQuery(err, statement)
+ }
+ defer rows.Close()
+
+ columnNames, err := rows.Columns()
+ if err != nil {
+ return nil, err
+ }
+
+ columnTypes, err := rows.ColumnTypes()
+ if err != nil {
+ return nil, err
+ }
+
+ var columnTypeNames []string
+ for _, v := range columnTypes {
+ // DatabaseTypeName returns the database system name of the column type.
+ // refer: https://pkg.go.dev/database/sql#ColumnType.DatabaseTypeName
+ columnTypeNames = append(columnTypeNames, strings.ToUpper(v.DatabaseTypeName()))
+ }
+
+ data, err := readRowsForClickhouse(rows, columnTypes, columnTypeNames)
+ if err != nil {
+ return nil, err
+ }
+
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+
+ return &v1pb.QueryResult{
+ ColumnNames: columnNames,
+ ColumnTypeNames: columnTypeNames,
+ Rows: data,
+ }, nil
+}
+
+func readRowsForClickhouse(rows *sql.Rows, columnTypes []*sql.ColumnType, columnTypeNames []string) ([]*v1pb.QueryRow, error) {
+ var data []*v1pb.QueryRow
+
+ for rows.Next() {
+ cols := make([]any, len(columnTypes))
+ for i, name := range columnTypeNames {
+ // The ClickHouse driver uses *Type rather than sql.NullType to scan nullable fields
+ // as described in https://github.com/ClickHouse/clickhouse-go/issues/754
+ // TODO: remove this workaround once fixed.
+ if strings.HasPrefix(name, "TUPLE") || strings.HasPrefix(name, "ARRAY") || strings.HasPrefix(name, "MAP") {
+ // For TUPLE, ARRAY, MAP type in ClickHouse, we pass any and the driver will do the rest.
+ var it any
+ cols[i] = &it
+ } else {
+ // We use ScanType to get the correct *Type and then do type assertions
+ // following https://github.com/ClickHouse/clickhouse-go/blob/main/TYPES.md
+ cols[i] = reflect.New(columnTypes[i].ScanType()).Interface()
+ }
+ }
+
+ if err := rows.Scan(cols...); err != nil {
+ return nil, err
+ }
+
+ var rowData *v1pb.QueryRow
+ for i := range cols {
+ // handle TUPLE ARRAY MAP
+ if v, ok := cols[i].(*any); ok && v != nil {
+ value, err := structpb.NewValue(*v)
+ if err != nil {
+ return nil, errors.Errorf("failed to convert value to structpb.Value: %v", err)
+ }
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_ValueValue{ValueValue: value}})
+ continue
+ }
+
+ // not nullable
+ if v, ok := cols[i].(*int); ok && v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_Int64Value{Int64Value: int64(*v)}})
+ continue
+ }
+ if v, ok := cols[i].(*int8); ok && v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_Int32Value{Int32Value: int32(*v)}})
+ continue
+ }
+ if v, ok := cols[i].(*int16); ok && v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_Int32Value{Int32Value: int32(*v)}})
+ continue
+ }
+ if v, ok := cols[i].(*int32); ok && v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_Int32Value{Int32Value: *v}})
+ continue
+ }
+ if v, ok := cols[i].(*int64); ok && v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_Int64Value{Int64Value: *v}})
+ continue
+ }
+ if v, ok := cols[i].(*uint); ok && v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_Uint64Value{Uint64Value: uint64(*v)}})
+ continue
+ }
+ if v, ok := cols[i].(*uint8); ok && v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_Uint32Value{Uint32Value: uint32(*v)}})
+ continue
+ }
+ if v, ok := cols[i].(*uint16); ok && v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_Uint32Value{Uint32Value: uint32(*v)}})
+ continue
+ }
+ if v, ok := cols[i].(*uint32); ok && v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_Uint32Value{Uint32Value: *v}})
+ continue
+ }
+ if v, ok := cols[i].(*uint64); ok && v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_Uint64Value{Uint64Value: *v}})
+ continue
+ }
+ if v, ok := cols[i].(*float32); ok && v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_FloatValue{FloatValue: *v}})
+ continue
+ }
+ if v, ok := cols[i].(*float64); ok && v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_DoubleValue{DoubleValue: *v}})
+ continue
+ }
+ if v, ok := cols[i].(*string); ok && v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_StringValue{StringValue: *v}})
+ continue
+ }
+ if v, ok := cols[i].(*bool); ok && v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_BoolValue{BoolValue: *v}})
+ continue
+ }
+ if v, ok := cols[i].(*time.Time); ok && v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_StringValue{StringValue: v.Format(time.RFC3339Nano)}})
+ continue
+ }
+ if v, ok := cols[i].(*big.Int); ok && v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_StringValue{StringValue: v.String()}})
+ continue
+ }
+ if v, ok := cols[i].(*decimal.Decimal); ok && v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_StringValue{StringValue: v.String()}})
+ continue
+ }
+ if v, ok := cols[i].(*uuid.UUID); ok && v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_StringValue{StringValue: v.String()}})
+ continue
+ }
+ if v, ok := cols[i].(*orb.Point); ok && v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_StringValue{StringValue: wkt.MarshalString(*v)}})
+ continue
+ }
+ if v, ok := cols[i].(*orb.Polygon); ok && v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_StringValue{StringValue: wkt.MarshalString(*v)}})
+ continue
+ }
+ if v, ok := cols[i].(*orb.Ring); ok && v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_StringValue{StringValue: wkt.MarshalString(*v)}})
+ continue
+ }
+ if v, ok := cols[i].(*orb.MultiPolygon); ok && v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_StringValue{StringValue: wkt.MarshalString(*v)}})
+ continue
+ }
+
+ // nullable
+ if v, ok := cols[i].(**int); ok && *v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_Int64Value{Int64Value: int64(**v)}})
+ continue
+ }
+ if v, ok := cols[i].(**int8); ok && *v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_Int32Value{Int32Value: int32(**v)}})
+ continue
+ }
+ if v, ok := cols[i].(**int16); ok && *v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_Int32Value{Int32Value: int32(**v)}})
+ continue
+ }
+ if v, ok := cols[i].(**int32); ok && *v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_Int32Value{Int32Value: **v}})
+ continue
+ }
+ if v, ok := cols[i].(**int64); ok && *v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_Int64Value{Int64Value: **v}})
+ continue
+ }
+ if v, ok := cols[i].(**uint); ok && *v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_Uint64Value{Uint64Value: uint64(**v)}})
+ continue
+ }
+ if v, ok := cols[i].(**uint8); ok && *v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_Uint32Value{Uint32Value: uint32(**v)}})
+ continue
+ }
+ if v, ok := cols[i].(**uint16); ok && *v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_Uint32Value{Uint32Value: uint32(**v)}})
+ continue
+ }
+ if v, ok := cols[i].(**uint32); ok && *v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_Uint32Value{Uint32Value: **v}})
+ continue
+ }
+ if v, ok := cols[i].(**uint64); ok && *v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_Uint64Value{Uint64Value: **v}})
+ continue
+ }
+ if v, ok := cols[i].(**float32); ok && *v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_FloatValue{FloatValue: **v}})
+ continue
+ }
+ if v, ok := cols[i].(**float64); ok && *v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_DoubleValue{DoubleValue: **v}})
+ continue
+ }
+ if v, ok := cols[i].(**string); ok && *v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_StringValue{StringValue: **v}})
+ continue
+ }
+ if v, ok := cols[i].(**bool); ok && *v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_BoolValue{BoolValue: **v}})
+ continue
+ }
+ if v, ok := cols[i].(**time.Time); ok && *v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_StringValue{StringValue: (*v).Format(time.RFC3339Nano)}})
+ continue
+ }
+ if v, ok := cols[i].(**big.Int); ok && *v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_StringValue{StringValue: (*v).String()}})
+ continue
+ }
+ if v, ok := cols[i].(**decimal.Decimal); ok && *v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_StringValue{StringValue: (*v).String()}})
+ continue
+ }
+ if v, ok := cols[i].(**uuid.UUID); ok && *v != nil {
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_StringValue{StringValue: (*v).String()}})
+ continue
+ }
+ rowData.Values = append(rowData.Values, &v1pb.RowValue{Kind: &v1pb.RowValue_NullValue{NullValue: structpb.NullValue_NULL_VALUE}})
+ }
+
+ data = append(data, rowData)
+ }
+
+ return data, nil
}
diff --git a/backend/plugin/db/util/driverutil.go b/backend/plugin/db/util/driverutil.go
index 37d37f98da..fd6a4ff9c1 100644
--- a/backend/plugin/db/util/driverutil.go
+++ b/backend/plugin/db/util/driverutil.go
@@ -261,7 +261,7 @@ func Query2(ctx context.Context, dbType db.Type, conn *sql.Conn, statement strin
columnTypeNames = append(columnTypeNames, strings.ToUpper(v.DatabaseTypeName()))
}
- data, err := readRows2(rows, dbType, columnTypes, columnTypeNames, fieldList)
+ data, err := readRows2(rows, columnTypes, columnTypeNames, fieldList)
if err != nil {
return nil, err
}
@@ -323,11 +323,7 @@ func queryAdmin(ctx context.Context, dbType db.Type, conn *sql.Conn, statement s
}
// TODO(rebelice): remove the readRows and rename readRows2 to readRows if legacy API is deprecated.
-func readRows2(rows *sql.Rows, dbType db.Type, columnTypes []*sql.ColumnType, columnTypeNames []string, fieldList []db.SensitiveField) ([]*v1pb.QueryRow, error) {
- if dbType == db.ClickHouse {
- // TODO(rebelice): implement clickhouse support
- return nil, errors.New("clickhouse is not supported")
- }
+func readRows2(rows *sql.Rows, columnTypes []*sql.ColumnType, columnTypeNames []string, fieldList []db.SensitiveField) ([]*v1pb.QueryRow, error) {
var data []*v1pb.QueryRow
for rows.Next() {
scanArgs := make([]any, len(columnTypes))
diff --git a/frontend/src/types/proto/v1/sql_service.ts b/frontend/src/types/proto/v1/sql_service.ts
index a40933b4ca..f9774d21b8 100644
--- a/frontend/src/types/proto/v1/sql_service.ts
+++ b/frontend/src/types/proto/v1/sql_service.ts
@@ -66,7 +66,7 @@ export interface RowValue {
uint64Value?:
| number
| undefined;
- /** value_value is used for Spanner only. */
+ /** value_value is used for Spanner and TUPLE ARRAY MAP in Clickhouse only. */
valueValue?: any;
}
diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.md
index 2a4636158c..7c7d4f1f2f 100644
--- a/proto/gen/grpc-doc/v1/README.md
+++ b/proto/gen/grpc-doc/v1/README.md
@@ -7462,7 +7462,7 @@ The sheet's `name` field is used to identify the sheet to update. Format: pr
| string_value | [string](#string) | | |
| uint32_value | [uint32](#uint32) | | |
| uint64_value | [uint64](#uint64) | | |
-| value_value | [google.protobuf.Value](#google-protobuf-Value) | | value_value is used for Spanner only. |
+| value_value | [google.protobuf.Value](#google-protobuf-Value) | | value_value is used for Spanner and TUPLE ARRAY MAP in Clickhouse only. |
diff --git a/proto/generated-go/v1/sql_service.pb.go b/proto/generated-go/v1/sql_service.pb.go
index fb77215aaf..a473a5f6e5 100644
--- a/proto/generated-go/v1/sql_service.pb.go
+++ b/proto/generated-go/v1/sql_service.pb.go
@@ -525,7 +525,7 @@ type RowValue_Uint64Value struct {
}
type RowValue_ValueValue struct {
- // value_value is used for Spanner only.
+ // value_value is used for Spanner and TUPLE ARRAY MAP in Clickhouse only.
ValueValue *structpb.Value `protobuf:"bytes,11,opt,name=value_value,json=valueValue,proto3,oneof"`
}
diff --git a/proto/v1/sql_service.proto b/proto/v1/sql_service.proto
index 7aff77f72a..76c130f694 100644
--- a/proto/v1/sql_service.proto
+++ b/proto/v1/sql_service.proto
@@ -84,7 +84,7 @@ message RowValue {
string string_value = 8;
uint32 uint32_value = 9;
uint64 uint64_value = 10;
- // value_value is used for Spanner only.
+ // value_value is used for Spanner and TUPLE ARRAY MAP in Clickhouse only.
google.protobuf.Value value_value = 11;
}
}