Skip to content

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

feat: handle cosmosdb query result (#14943)

h3n4lbbaa9247a2f3
diff --git a/backend/plugin/db/cosmosdb/cosmosdb.go b/backend/plugin/db/cosmosdb/cosmosdb.go
index f206d09892..27741138ef 100644
--- a/backend/plugin/db/cosmosdb/cosmosdb.go
+++ b/backend/plugin/db/cosmosdb/cosmosdb.go
@@ -6,6 +6,8 @@ import (
"database/sql"
"encoding/json"
"io"
+ "log/slog"
+ "sort"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
@@ -14,6 +16,7 @@ import (
"github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
"github.com/pkg/errors"
+ "github.com/bytebase/bytebase/backend/common/log"
"github.com/bytebase/bytebase/backend/plugin/db"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
v1pb "github.com/bytebase/bytebase/proto/generated-go/v1"
@@ -95,40 +98,169 @@ func (driver *Driver) QueryConn(ctx context.Context, _ *sql.Conn, statement stri
return nil, status.Error(codes.Internal, errors.Wrapf(err, "failed to create container").Error())
}
pager := container.NewCrossPartitionQueryItemsPager(statement, nil)
- result := &v1pb.QueryResult{
- ColumnNames: []string{"id", "category"},
- ColumnTypeNames: []string{"string", "string"},
- }
+ var items [][]byte
for pager.More() {
response, err := pager.NextPage(ctx)
if err != nil {
return nil, status.Error(codes.Internal, errors.Wrapf(err, "failed to read more items").Error())
}
- // TODO(zp): test only.
- type Item struct {
- ID string `json:"id"`
- Category string `json:"category"`
- }
- for _, bytes := range response.Items {
- var item Item
- if err := json.Unmarshal(bytes, &item); err != nil {
- return nil, status.Error(codes.Internal, errors.Wrapf(err, "failed to unmarshal JSON").Error())
- }
+ items = append(items, response.Items...)
+ }
+
+ columns, columnTypeMap, columnIndexMap, valid := getColumns(items)
+ result := &v1pb.QueryResult{
+ ColumnNames: columns,
+ }
+ for _, column := range columns {
+ result.ColumnTypeNames = append(result.ColumnTypeNames, columnTypeMap[column])
+ }
+
+ for _, item := range items {
+ if !valid {
result.Rows = append(result.Rows, &v1pb.QueryRow{
Values: []*v1pb.RowValue{
- {
- Kind: &v1pb.RowValue_StringValue{
- StringValue: item.ID,
- },
- },
- {
- Kind: &v1pb.RowValue_StringValue{
- StringValue: item.Category,
- },
- },
+ {Kind: &v1pb.RowValue_StringValue{StringValue: string(item)}},
},
})
+ continue
}
+
+ var m map[string]any
+ if err := json.Unmarshal(item, &m); err != nil {
+ return nil, status.Error(codes.Internal, errors.Wrapf(err, "failed to unmarshal JSON").Error())
+ }
+ values := make([]*v1pb.RowValue, len(columns))
+ for k, v := range m {
+ switch v := v.(type) {
+ case string:
+ values[columnIndexMap[k]] = &v1pb.RowValue{Kind: &v1pb.RowValue_StringValue{StringValue: v}}
+ case float64:
+ // Decide the target type for float64
+ if v == float64(int32(v)) {
+ values[columnIndexMap[k]] = &v1pb.RowValue{Kind: &v1pb.RowValue_Int32Value{Int32Value: int32(v)}}
+ } else if v == float64(int64(v)) {
+ values[columnIndexMap[k]] = &v1pb.RowValue{Kind: &v1pb.RowValue_Int64Value{Int64Value: int64(v)}}
+ } else if v >= 0 && v == float64(uint32(v)) {
+ values[columnIndexMap[k]] = &v1pb.RowValue{Kind: &v1pb.RowValue_Uint32Value{Uint32Value: uint32(v)}}
+ } else if v >= 0 && v == float64(uint64(v)) {
+ values[columnIndexMap[k]] = &v1pb.RowValue{Kind: &v1pb.RowValue_Uint64Value{Uint64Value: uint64(v)}}
+ } else {
+ // Default to DoubleValue if it's not an integer type
+ values[columnIndexMap[k]] = &v1pb.RowValue{Kind: &v1pb.RowValue_DoubleValue{DoubleValue: v}}
+ }
+ case bool:
+ values[columnIndexMap[k]] = &v1pb.RowValue{Kind: &v1pb.RowValue_BoolValue{BoolValue: v}}
+ case map[string]any:
+ // Handle nested objects if necessary
+ // Convert to JSON string representation for example
+ jsonBytes, _ := json.Marshal(v)
+ values[columnIndexMap[k]] = &v1pb.RowValue{Kind: &v1pb.RowValue_StringValue{StringValue: string(jsonBytes)}}
+ case []any:
+ // Handle arrays if necessary
+ // Convert to JSON string representation for example
+ jsonBytes, _ := json.Marshal(v)
+ values[columnIndexMap[k]] = &v1pb.RowValue{Kind: &v1pb.RowValue_StringValue{StringValue: string(jsonBytes)}}
+ case nil:
+ values[columnIndexMap[k]] = &v1pb.RowValue{Kind: &v1pb.RowValue_NullValue{}}
+ default:
+ // Handle unknown types
+ values[columnIndexMap[k]] = &v1pb.RowValue{Kind: &v1pb.RowValue_StringValue{StringValue: "unknow"}}
+ }
+ for i := 0; i < len(values); i++ {
+ if values[i] == nil {
+ values[i] = &v1pb.RowValue{Kind: &v1pb.RowValue_NullValue{}}
+ }
+ }
+ }
+ result.Rows = append(result.Rows, &v1pb.QueryRow{
+ Values: values,
+ })
}
return []*v1pb.QueryResult{result}, nil
}
+
+func getColumns(rawItems [][]byte) (columnNames []string, columnTypes map[string]string, columnIndexMap map[string]int, valid bool) {
+ columnNamesSet := make(map[string]bool)
+ columnTypes = make(map[string]string)
+
+ for _, item := range rawItems {
+ var m map[string]any
+ if err := json.Unmarshal(item, &m); err != nil {
+ slog.Warn("failed to unmarshal JSON", slog.String("item", string(item)), log.BBError(err))
+ return []string{"result"}, map[string]string{"result": "TEXT"}, map[string]int{"result": 0}, false
+ }
+ for k, v := range m {
+ if _, ok := columnNamesSet[k]; ok {
+ continue
+ }
+ columnNamesSet[k] = true
+ columnTypes[k] = getType(v)
+ }
+ }
+ columnNames, columnIndexMap = getOrderedColumns(columnNamesSet)
+ return columnNames, columnTypes, columnIndexMap, true
+}
+
+func getOrderedColumns(columnSet map[string]bool) ([]string, map[string]int) {
+ var columns []string
+ for k := range columnSet {
+ columns = append(columns, k)
+ }
+ // Put built-in columns at the end.
+ builtInColumns := map[string]bool{
+ "_rid": true,
+ "_self": true,
+ "_etag": true,
+ "_attachments": true,
+ "_ts": true,
+ }
+ // TODO(zp): Put id and parititon key columns at the front.
+ sort.SliceStable(columns, func(i, j int) bool {
+ // "id" should come first
+ if columns[i] == "id" {
+ return true
+ }
+ if columns[j] == "id" {
+ return false
+ }
+
+ // Built-in columns should come last
+ _, isIBuiltIn := builtInColumns[columns[i]]
+ _, isJBuiltIn := builtInColumns[columns[j]]
+
+ if isIBuiltIn && !isJBuiltIn {
+ return false
+ }
+ if !isIBuiltIn && isJBuiltIn {
+ return true
+ }
+
+ // Otherwise, sort lexicographically
+ return columns[i] < columns[j]
+ })
+ columnIndexMap := make(map[string]int)
+
+ for i, column := range columns {
+ columnIndexMap[column] = i
+ }
+ return columns, columnIndexMap
+}
+
+func getType(v any) string {
+ switch v.(type) {
+ case map[string]any:
+ return "object"
+ case []any:
+ return "array"
+ case string:
+ return "string"
+ case float64:
+ return "number" // JSON numbers are unmarshalled as float64
+ case bool:
+ return "boolean"
+ case nil:
+ return "null"
+ default:
+ return "unknown"
+ }
+}
diff --git a/go.mod b/go.mod
index ca58b2eb81..9a7e152e60 100644
--- a/go.mod
+++ b/go.mod
@@ -371,4 +371,4 @@ replace github.com/microsoft/go-mssqldb => github.com/bytebase/go-mssqldb v0.0.0
replace github.com/youmark/pkcs8 => github.com/bytebase/pkcs8 v0.0.0-20240612095628-fcd0a7484c94
-replace github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos => github.com/bytebase/azure-sdk-for-go/sdk/data/azcosmos v0.0.0-20250107031355-540f7300ab93
+replace github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos => github.com/bytebase/azure-sdk-for-go/sdk/data/azcosmos v0.0.0-20250109032656-87cf24d45689
diff --git a/go.sum b/go.sum
index 685136bc1d..0139e0573e 100644
--- a/go.sum
+++ b/go.sum
@@ -815,8 +815,8 @@ github.com/buger/jsonparser v1.1.1 h1:2PnMjfWD7wBILjqQbt530v576A/cAbQvEW9gGIpYMU
github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
github.com/bytebase/antlr/v4 v4.0.0-20240827034948-8c385f108920 h1:IfmPt5o5R70NKtOrs+QHOoCgViYZelZysGxVBvV4ybA=
github.com/bytebase/antlr/v4 v4.0.0-20240827034948-8c385f108920/go.mod h1:ykhjIPiv0IWpu3OGXCHdz2eUSe8UNGGD6baqjs8jSuU=
-github.com/bytebase/azure-sdk-for-go/sdk/data/azcosmos v0.0.0-20250107031355-540f7300ab93 h1:6lr7MhgFFWzZ5E3grbpkzJKd9bDuclYNFHfFC/CKk5c=
-github.com/bytebase/azure-sdk-for-go/sdk/data/azcosmos v0.0.0-20250107031355-540f7300ab93/go.mod h1:YwUyrNUtcZcibA99JcfCP6UUp95VVQKO2MJfBzgJDwA=
+github.com/bytebase/azure-sdk-for-go/sdk/data/azcosmos v0.0.0-20250109032656-87cf24d45689 h1:tTxTI91JlBuvbX5JPDJSvCje9TxSUoXOzsbRp8qtcPs=
+github.com/bytebase/azure-sdk-for-go/sdk/data/azcosmos v0.0.0-20250109032656-87cf24d45689/go.mod h1:YwUyrNUtcZcibA99JcfCP6UUp95VVQKO2MJfBzgJDwA=
github.com/bytebase/gh-ost2 v0.0.0-20240731091141-e7a12a9401ab h1:hJ3tfjfm5D63QwCH+znK1ZQQzk9/rG4Jjz7CSxVtSrQ=
github.com/bytebase/gh-ost2 v0.0.0-20240731091141-e7a12a9401ab/go.mod h1:VRPqaDM7UYxJbcCtQkjBcNkxW17p6LJJdkM/nYwQhqg=
github.com/bytebase/go-lsp v0.0.0-20240130071507-c04b5c75010c h1:W832GNANCst4C6TgYbQnKKxbuMZKQxTD4++b3HOuzBo=