Skip to content

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

chore(hive): code style (#13226)

Azusain0697521c3d63
diff --git a/backend/plugin/db/hive/dump.go b/backend/plugin/db/hive/dump.go
index eed18ae4f5..bbcbff8ff5 100644
--- a/backend/plugin/db/hive/dump.go
+++ b/backend/plugin/db/hive/dump.go
@@ -6,6 +6,7 @@ import (
"io"
"strings"
+ "github.com/beltran/gohive"
"github.com/pkg/errors"
)
@@ -53,127 +54,124 @@ type MaterializedViewDDLOptions struct {
}
func (d *Driver) Dump(ctx context.Context, out io.Writer) (string, error) {
- instanceMetadata, err := d.SyncInstance(ctx)
+ var builder strings.Builder
+
+ databaseName := d.config.Database
+ database, err := d.SyncDBSchema(ctx)
if err != nil {
- return "", errors.Wrapf(err, "failed to sync instance")
+ return "", err
}
- var builder strings.Builder
+ if len(database.Schemas) == 0 {
+ return "", errors.New("database schemas is empty")
+ }
+ schema := database.Schemas[0]
- for _, database := range instanceMetadata.Databases {
- schema := database.Schemas[0]
+ conn, err := d.connPool.Get()
+ if err != nil {
+ return "", err
+ }
+ defer d.connPool.Put(conn)
+
+ cursor := conn.Cursor()
+ cursor.Exec(ctx, fmt.Sprintf("use %s", databaseName))
+ if cursor.Err != nil {
+ return "", cursor.Err
+ }
- // dump databases.
- databaseDDL, err := d.showCreateSchemaDDL(ctx, "DATABASE", schema.Name, "")
+ // dump managed tables.
+ for _, table := range schema.GetTables() {
+ tableDDL, err := showCreateDDL(ctx, conn, "TABLE", table.Name)
if err != nil {
- return "", errors.Wrapf(err, "failed to dump database %s", schema.Name)
+ return "", errors.Wrapf(err, "failed to dump table %s", table.Name)
}
- _, _ = builder.WriteString(databaseDDL)
- // dump managed tables.
- for _, table := range schema.Tables {
- tabDDL, err := d.showCreateSchemaDDL(ctx, "TABLE", table.Name, schema.Name)
+ // dump indexes.
+ for _, index := range table.GetIndexes() {
+ indexDDL, err := genIndexDDL(&IndexDDLOptions{
+ databaseName: databaseName,
+ indexName: index.Name,
+ tableName: table.Name,
+ indexType: index.Type,
+ colNames: index.Expressions,
+ isWithDeferredRebuild: true,
+ idxProperties: nil,
+ indexTableName: "",
+ rowFmt: "",
+ storedAs: "",
+ storedBy: "",
+ location: "",
+ tableProperties: nil,
+ comment: index.Comment,
+ })
if err != nil {
- return "", errors.Wrapf(err, "failed to dump table %s", table.Name)
+ return "", errors.Wrapf(err, "failed to generate DDL for index %s", index.Name)
}
- // dump indexes.
- for _, index := range table.Indexes {
- indexDDL, err := genIndexDDL(&IndexDDLOptions{
- databaseName: schema.Name,
- indexName: index.Name,
- tableName: table.Name,
- indexType: index.Type,
- colNames: index.Expressions,
- isWithDeferredRebuild: true,
- idxProperties: nil,
- indexTableName: "",
- rowFmt: "",
- storedAs: "",
- storedBy: "",
- location: "",
- tableProperties: nil,
- comment: index.Comment,
- })
- if err != nil {
- return "", errors.Wrapf(err, "failed to generate DDL for index %s", index.Name)
- }
-
- _, _ = builder.WriteString(fmt.Sprintf(schemaStmtFmt, "INDEX", fmt.Sprintf("`%s`", index.Name), indexDDL))
- }
- _, _ = builder.WriteString(tabDDL)
+ _, _ = builder.WriteString(fmt.Sprintf(schemaStmtFmt, "INDEX", fmt.Sprintf("`%s`", index.Name), indexDDL))
}
+ _, _ = builder.WriteString(tableDDL)
+ }
- // dump external tables.
- for _, extTable := range schema.ExternalTables {
- tabDDL, err := d.showCreateSchemaDDL(ctx, "TABLE", extTable.Name, schema.Name)
- if err != nil {
- return "", errors.Wrapf(err, "failed to dump table %s", extTable.Name)
- }
- _, _ = builder.WriteString(tabDDL)
+ // dump external tables.
+ for _, extTable := range schema.GetExternalTables() {
+ tabDDL, err := showCreateDDL(ctx, conn, "TABLE", extTable.Name)
+ if err != nil {
+ return "", errors.Wrapf(err, "failed to dump table %s", extTable.Name)
}
+ _, _ = builder.WriteString(tabDDL)
+ }
- // dump views.
- for _, view := range schema.Views {
- viewDDL, err := d.showCreateSchemaDDL(ctx, "VIEW", view.Name, schema.Name)
- if err != nil {
- return "", errors.Wrapf(err, "failed to dump view %s", view.Name)
- }
- _, _ = builder.WriteString(viewDDL)
+ // dump views.
+ for _, view := range schema.GetViews() {
+ viewDDL, err := showCreateDDL(ctx, conn, "VIEW", view.Name)
+ if err != nil {
+ return "", errors.Wrapf(err, "failed to dump view %s", view.Name)
}
+ _, _ = builder.WriteString(viewDDL)
+ }
- // dump materialized views.
- for _, mtView := range schema.MaterializedViews {
- mtViewDDL, err := genMaterializedViewDDL(&MaterializedViewDDLOptions{
- databaseName: schema.Name,
- mtViewName: mtView.Name,
- disableRewrite: false,
- comment: mtView.Comment,
- partitionedOn: nil,
- clusteredOn: nil,
- distributedOn: nil,
- sortedOn: nil,
- rowFmt: "",
- storedAs: "",
- storedBy: "",
- serdProperties: nil,
- location: "",
- tblProperties: nil,
- as: mtView.Definition,
- })
- if err != nil {
- return "", errors.Wrapf(err, "failed to generate DDL for materialized view %s", mtView.Name)
- }
-
- _, _ = builder.WriteString(fmt.Sprintf(schemaStmtFmt, "MATERIALIZED VIEW", fmt.Sprintf("`%s`.`%s`", schema.Name, mtView.Name), mtViewDDL))
+ // dump materialized views.
+ for _, mtView := range schema.GetMaterializedViews() {
+ mtViewDDL, err := genMaterializedViewDDL(&MaterializedViewDDLOptions{
+ databaseName: databaseName,
+ mtViewName: mtView.Name,
+ disableRewrite: false,
+ comment: mtView.Comment,
+ partitionedOn: nil,
+ clusteredOn: nil,
+ distributedOn: nil,
+ sortedOn: nil,
+ rowFmt: "",
+ storedAs: "",
+ storedBy: "",
+ serdProperties: nil,
+ location: "",
+ tblProperties: nil,
+ as: mtView.Definition,
+ })
+ if err != nil {
+ return "", errors.Wrapf(err, "failed to generate DDL for materialized view %s", mtView.Name)
}
+
+ _, _ = builder.WriteString(fmt.Sprintf(schemaStmtFmt, "MATERIALIZED VIEW", fmt.Sprintf("`%s`.`%s`", databaseName, mtView.Name), mtViewDDL))
}
- _, _ = io.WriteString(out, builder.String())
+ if _, err = io.WriteString(out, builder.String()); err != nil {
+ return "", err
+ }
return builder.String(), nil
}
// This function shows DDLs for creating certain type of schema [VIEW, DATABASE, TABLE].
-func (d *Driver) showCreateSchemaDDL(ctx context.Context, schemaType string, schemaName string, belongTo string) (string, error) {
- schemaName = fmt.Sprintf("`%s`", schemaName)
- originalTableName := schemaName
- // rename table to format: [DatabaseName].[TableName].
- if belongTo != "" {
- belongTo = fmt.Sprintf("`%s`", belongTo)
- schemaName = fmt.Sprintf("%s.%s", belongTo, schemaName)
- }
+func showCreateDDL(ctx context.Context, conn *gohive.Connection, objectType string, objectName string) (string, error) {
+ objectName = fmt.Sprintf("`%s`", objectName)
// 'SHOW CREATE TABLE' can also be used for dumping views.
- queryStatement := fmt.Sprintf("SHOW CREATE %s %s", schemaType, schemaName)
- if schemaType == "VIEW" {
- queryStatement = fmt.Sprintf("SHOW CREATE TABLE %s", schemaName)
+ queryStatement := fmt.Sprintf("SHOW CREATE %s %s", objectType, objectName)
+ if objectType == "VIEW" {
+ queryStatement = fmt.Sprintf("SHOW CREATE TABLE %s", objectName)
}
- conn, err := d.connPool.Get("")
- if err != nil {
- return "", err
- }
- defer d.connPool.Put(conn)
-
schemaDDLResult, err := runSingleStatement(ctx, conn, queryStatement)
if err != nil {
return "", err
@@ -181,14 +179,13 @@ func (d *Driver) showCreateSchemaDDL(ctx context.Context, schemaType string, sch
var schemaDDL string
for _, row := range schemaDDLResult.Rows {
+ if row == nil || len(row.Values) == 0 {
+ return "", errors.New("empty row")
+ }
schemaDDL += fmt.Sprintln(row.Values[0].GetStringValue())
}
- if belongTo != "" {
- schemaDDL = strings.Replace(schemaDDL, originalTableName, schemaName, 1)
- }
-
- return fmt.Sprintf(schemaStmtFmt, schemaType, schemaName, schemaDDL), nil
+ return fmt.Sprintf(schemaStmtFmt, objectType, objectName, schemaDDL), nil
}
func genIndexDDL(opts *IndexDDLOptions) (string, error) {
@@ -228,9 +225,11 @@ func genIndexDDL(opts *IndexDDLOptions) (string, error) {
// stored as or stored by.
if opts.storedAs != "" && opts.storedBy != "" {
return "", errors.New("keywords 'STORED AS' and 'STORED BY' cannot appear at the same time")
- } else if opts.storedAs != "" {
+ }
+ if opts.storedAs != "" {
_, _ = builder.WriteString(fmt.Sprintf("STORED AS %s\n", opts.storedAs))
- } else if opts.storedBy != "" {
+ }
+ if opts.storedBy != "" {
_, _ = builder.WriteString(fmt.Sprintf("STORED BY '%s'\n", opts.storedBy))
}
@@ -279,11 +278,9 @@ func genMaterializedViewDDL(opts *MaterializedViewDDLOptions) (string, error) {
if opts.clusteredOn != nil && opts.distributedOn != nil {
return "", errors.New("keywords 'CLUSTERED ON' and 'DISTRIBUTED ON' cannot appear at the same time")
- } else if opts.clusteredOn != nil {
- // clusteredOn
- _, _ = builder.WriteString("CLUSTERED ON ")
- formatColumn(&builder, opts.clusteredOn)
- } else if opts.distributedOn != nil && opts.sortedOn != nil {
+ }
+ // [CLUSTERED ON (col_name, ...) | DISTRIBUTED ON (col_name, ...) SORTED ON (col_name, ...)].
+ if opts.distributedOn != nil && opts.sortedOn != nil {
// distributed on.
_, _ = builder.WriteString("DISTRIBUTED ON ")
formatColumn(&builder, opts.distributedOn)
@@ -292,13 +289,20 @@ func genMaterializedViewDDL(opts *MaterializedViewDDLOptions) (string, error) {
_, _ = builder.WriteString("SORTED ON ")
formatColumn(&builder, opts.sortedOn)
}
+ if opts.clusteredOn != nil {
+ // clusteredOn
+ _, _ = builder.WriteString("CLUSTERED ON ")
+ formatColumn(&builder, opts.clusteredOn)
+ }
// stored as or stored by.
if opts.storedAs != "" && opts.storedBy != "" {
return "", errors.New("keywords 'STORED AS' and 'STORED BY' cannot appear at the same time")
- } else if opts.storedAs != "" {
+ }
+ if opts.storedAs != "" {
_, _ = builder.WriteString(fmt.Sprintf("STORED AS %s\n", opts.storedAs))
- } else if opts.storedBy != "" {
+ }
+ if opts.storedBy != "" {
_, _ = builder.WriteString(fmt.Sprintf("STORED BY '%s'\n", opts.storedBy))
// if with serde properties.
@@ -339,13 +343,13 @@ func formatColumn(builder *strings.Builder, columnNames []string) {
func formatKVPair(builder *strings.Builder, kvMap map[string]string) {
_, _ = builder.WriteString("(\n")
- index := 0
+ count := 0
for key, value := range kvMap {
+ count++
_, _ = builder.WriteString(fmt.Sprintf(" '%s' = '%s'", key, value))
- if index != len(kvMap)-1 {
+ if count != len(kvMap) {
_, _ = builder.WriteString(",\n")
}
- index++
}
_, _ = builder.WriteString(")\n")
}
diff --git a/backend/plugin/db/hive/hive.go b/backend/plugin/db/hive/hive.go
index 9fff2a0ae4..1d5819c53a 100644
--- a/backend/plugin/db/hive/hive.go
+++ b/backend/plugin/db/hive/hive.go
@@ -13,6 +13,7 @@ import (
"go.uber.org/multierr"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/durationpb"
+ "google.golang.org/protobuf/types/known/structpb"
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/plugin/db"
@@ -63,14 +64,14 @@ func (d *Driver) Open(_ context.Context, _ storepb.Engine, config db.ConnectionC
if !config.SASLConfig.Check() {
return nil, errors.New("SASL settings error")
}
- pool, err := CreateHiveConnPool(numMaxConn, &config)
+ pool, err := createHiveConnPool(numMaxConn, &config)
if err != nil {
return nil, err
}
d.connPool = pool
}
- newConn, err := d.connPool.Get(config.Database)
+ newConn, err := d.connPool.Get()
if err != nil {
err = errors.Wrapf(err, "failed to get connection from pool")
// release resources.
@@ -80,6 +81,14 @@ func (d *Driver) Open(_ context.Context, _ storepb.Engine, config db.ConnectionC
return nil, err
}
+ if config.Database != "" {
+ cursor := newConn.Cursor()
+ cursor.Exec(context.Background(), fmt.Sprintf("use %s", config.Database))
+ if cursor.Err != nil {
+ return nil, multierr.Combine(newConn.Close(), cursor.Err)
+ }
+ }
+
d.conn = newConn
return d, nil
@@ -91,9 +100,6 @@ func (d *Driver) Close(_ context.Context) error {
}
func (d *Driver) Ping(ctx context.Context) error {
- if d.conn == nil {
- return errors.Errorf("no database connection established")
- }
cursor := d.conn.Cursor()
defer cursor.Close()
@@ -112,10 +118,6 @@ func (*Driver) GetDB() *sql.DB {
// Even in Hive's bucketed transaction table, all the statements are committed automatically by
// the Hive server.
func (d *Driver) Execute(ctx context.Context, statementsStr string, _ db.ExecuteOptions) (int64, error) {
- if d.connPool == nil {
- return 0, errors.Errorf("no database connection established")
- }
-
var affectedRows int64
cursor := d.conn.Cursor()
@@ -139,16 +141,12 @@ func (d *Driver) Execute(ctx context.Context, statementsStr string, _ db.Execute
}
func (d *Driver) QueryConn(ctx context.Context, _ *sql.Conn, statement string, queryCtx *db.QueryContext) ([]*v1pb.QueryResult, error) {
- if d.connPool == nil {
- return nil, errors.Errorf("no database connection established")
- }
-
singleSQLs, err := base.SplitMultiSQL(storepb.Engine_HIVE, statement)
if err != nil {
return nil, errors.Wrapf(err, "failed to split statements")
}
- conn, err := d.connPool.Get("")
+ conn, err := d.connPool.Get()
if err != nil {
return nil, err
}
@@ -162,8 +160,8 @@ func (d *Driver) QueryConn(ctx context.Context, _ *sql.Conn, statement string, q
}
result, err := runSingleStatement(ctx, conn, statement)
- if err != nil && result == nil {
- return results, err
+ if err != nil {
+ return nil, err
}
results = append(results, result)
@@ -173,35 +171,29 @@ func (d *Driver) QueryConn(ctx context.Context, _ *sql.Conn, statement string, q
// This function converts basic types to types that have implemented isRowValue_Kind interface.
func parseValueType(value any, gohiveType string) (*v1pb.RowValue, error) {
- var rowValue v1pb.RowValue
if value == nil {
- rowValue.Kind = &v1pb.RowValue_StringValue{StringValue: ""}
- } else {
- switch gohiveType {
- case "BOOLEAN_TYPE":
- rowValue.Kind = &v1pb.RowValue_BoolValue{BoolValue: value.(bool)}
- case "TINYINT_TYPE":
- rowValue.Kind = &v1pb.RowValue_Int32Value{Int32Value: int32(value.(int8))}
- case "SMALLINT_TYPE":
- rowValue.Kind = &v1pb.RowValue_Int32Value{Int32Value: int32(value.(int16))}
- case "INT_TYPE":
- rowValue.Kind = &v1pb.RowValue_Int32Value{Int32Value: value.(int32)}
- case "BIGINT_TYPE":
- rowValue.Kind = &v1pb.RowValue_Int64Value{Int64Value: value.(int64)}
- // dangerous truncation: float64 -> float32.
- case "FLOAT_TYPE":
- rowValue.Kind = &v1pb.RowValue_FloatValue{FloatValue: float32(value.(float64))}
- case "BINARY_TYPE":
- rowValue.Kind = &v1pb.RowValue_BytesValue{BytesValue: value.([]byte)}
- case "DOUBLE_TYPE":
- // convert float64 to string to avoid trancation.
- rowValue.Kind = &v1pb.RowValue_StringValue{StringValue: strconv.FormatFloat(value.(float64), 'f', 20, 64)}
- default:
- // convert all remaining types to string.
- rowValue.Kind = &v1pb.RowValue_StringValue{StringValue: value.(string)}
- }
+ return &v1pb.RowValue{Kind: &v1pb.RowValue_NullValue{NullValue: structpb.NullValue_NULL_VALUE}}, nil
+ }
+ switch gohiveType {
+ case "BOOLEAN_TYPE":
+ return &v1pb.RowValue{Kind: &v1pb.RowValue_BoolValue{BoolValue: value.(bool)}}, nil
+ case "TINYINT_TYPE":
+ return &v1pb.RowValue{Kind: &v1pb.RowValue_Int32Value{Int32Value: int32(value.(int8))}}, nil
+ case "SMALLINT_TYPE":
+ return &v1pb.RowValue{Kind: &v1pb.RowValue_Int32Value{Int32Value: int32(value.(int16))}}, nil
+ case "INT_TYPE":
+ return &v1pb.RowValue{Kind: &v1pb.RowValue_Int32Value{Int32Value: value.(int32)}}, nil
+ case "BIGINT_TYPE":
+ return &v1pb.RowValue{Kind: &v1pb.RowValue_Int64Value{Int64Value: value.(int64)}}, nil
+ case "DOUBLE_TYPE", "FLOAT_TYPE":
+ // convert float64 to string to avoid truncation, because our v1pb.RowValue_FloatValue is float32.
+ return &v1pb.RowValue{Kind: &v1pb.RowValue_StringValue{StringValue: strconv.FormatFloat(value.(float64), 'f', 20, 64)}}, nil
+ case "BINARY_TYPE":
+ return &v1pb.RowValue{Kind: &v1pb.RowValue_BytesValue{BytesValue: value.([]byte)}}, nil
+ default:
+ // convert all remaining types to string.
+ return &v1pb.RowValue{Kind: &v1pb.RowValue_StringValue{StringValue: value.(string)}}, nil
}
- return &rowValue, nil
}
func runSingleStatement(ctx context.Context, conn *gohive.Connection, statement string) (*v1pb.QueryResult, error) {
@@ -223,6 +215,9 @@ func runSingleStatement(ctx context.Context, conn *gohive.Connection, statement
// We will get an error when a certain statement doesn't need returned results.
columnNamesAndTypes := cursor.Description()
for _, row := range columnNamesAndTypes {
+ if len(row) == 0 {
+ return nil, errors.New("description row has zero length")
+ }
result.ColumnNames = append(result.ColumnNames, row[0])
}
@@ -234,7 +229,7 @@ func runSingleStatement(ctx context.Context, conn *gohive.Connection, statement
gohiveTypeStr := columnNamesAndTypes[idx][1]
val, err := parseValueType(rowMap[columnName], gohiveTypeStr)
if err != nil {
- return result, err
+ return nil, err
}
queryRow.Values = append(queryRow.Values, val)
}
diff --git a/backend/plugin/db/hive/hive_conn_pool.go b/backend/plugin/db/hive/hive_conn_pool.go
index 8b9fa7bfec..42bffbe5b0 100644
--- a/backend/plugin/db/hive/hive_conn_pool.go
+++ b/backend/plugin/db/hive/hive_conn_pool.go
@@ -1,8 +1,6 @@
package hive
import (
- "context"
- "fmt"
"strconv"
"sync"
@@ -13,12 +11,6 @@ import (
"github.com/bytebase/bytebase/backend/plugin/db"
)
-type ConnPool interface {
- Get(dbName string) (*gohive.Connection, error)
- Put(*gohive.Connection)
- Destroy() error
-}
-
type FixedConnPool struct {
BasicConfig *db.ConnectionConfig
HiveConfig *gohive.ConnectConfiguration
@@ -29,9 +21,7 @@ type FixedConnPool struct {
NumMaxConns int
}
-var _ ConnPool = &FixedConnPool{}
-
-func CreateHiveConnPool(
+func createHiveConnPool(
numMaxConn int,
config *db.ConnectionConfig,
) (
@@ -94,7 +84,7 @@ func CreateHiveConnPool(
nil
}
-func (pool *FixedConnPool) Get(dbName string) (*gohive.Connection, error) {
+func (pool *FixedConnPool) Get() (*gohive.Connection, error) {
pool.RWMutex.RLock()
if !pool.IsActivated {
pool.RWMutex.RUnlock()
@@ -123,14 +113,6 @@ func (pool *FixedConnPool) Get(dbName string) (*gohive.Connection, error) {
}
}
- if dbName != "" {
- cursor := conn.Cursor()
- cursor.Exec(context.Background(), fmt.Sprintf("use %s", dbName))
- if cursor.Err != nil {
- return nil, multierr.Combine(conn.Close(), cursor.Err)
- }
- }
-
return conn, nil
}
diff --git a/backend/plugin/db/hive/role.go b/backend/plugin/db/hive/role.go
index 1edb096042..225e52607d 100644
--- a/backend/plugin/db/hive/role.go
+++ b/backend/plugin/db/hive/role.go
@@ -29,7 +29,7 @@ func (*Driver) FindRole(_ context.Context, _ string) (*db.DatabaseRoleMessage, e
}
func (d *Driver) ListRole(ctx context.Context) ([]*db.DatabaseRoleMessage, error) {
- conn, err := d.connPool.Get("")
+ conn, err := d.connPool.Get()
if err != nil {
return nil, err
}
@@ -56,7 +56,7 @@ func (d *Driver) DeleteRole(ctx context.Context, roleName string) error {
}
func (d *Driver) GetRoleGrant(ctx context.Context, roleName string) (string, error) {
- conn, err := d.connPool.Get("")
+ conn, err := d.connPool.Get()
if err != nil {
return "", err
}
diff --git a/backend/plugin/db/hive/sync.go b/backend/plugin/db/hive/sync.go
index df4bd080a6..22b116db0d 100644
--- a/backend/plugin/db/hive/sync.go
+++ b/backend/plugin/db/hive/sync.go
@@ -3,22 +3,19 @@ package hive
import (
"context"
"fmt"
+ "log/slog"
"strconv"
"strings"
- "sync"
"time"
"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"
)
func (d *Driver) SyncInstance(ctx context.Context) (*db.InstanceMetadata, error) {
- if d.connPool == nil {
- return nil, errors.New("connection pool not created")
- }
-
var instanceMetadata db.InstanceMetadata
// version.
@@ -33,33 +30,10 @@ func (d *Driver) SyncInstance(ctx context.Context) (*db.InstanceMetadata, error)
return nil, err
}
- var wg sync.WaitGroup
- instanceMetadata.Databases = make([]*storepb.DatabaseSchemaMetadata, len(databaseNames))
- // handler errors from go-routines.
- errChan := make(chan error, len(databaseNames))
- for idx, databaseName := range databaseNames {
- wg.Add(1)
- go func(index int, databaseName string) {
- defer wg.Done()
- databaseSchemaMetadata := new(storepb.DatabaseSchemaMetadata)
- databaseSchemaMetadata.Name = databaseName
-
- schemaMetadata, err := d.getDatabaseInfoByName(ctx, databaseName)
- if err != nil {
- errChan <- err
- return
- }
-
- databaseSchemaMetadata.Schemas = append(databaseSchemaMetadata.Schemas, schemaMetadata)
- instanceMetadata.Databases[index] = databaseSchemaMetadata
- }(idx, databaseName)
- }
- wg.Wait()
- // continue if no errors are in the channel.
- select {
- case err := <-errChan:
- return nil, err
- default:
+ for _, v := range databaseNames {
+ instanceMetadata.Databases = append(instanceMetadata.Databases, &storepb.DatabaseSchemaMetadata{
+ Name: v,
+ })
}
instanceMetadata.Version = version
@@ -72,15 +46,14 @@ func (d *Driver) SyncDBSchema(ctx context.Context) (*storepb.DatabaseSchemaMetad
dbName = "default"
}
- databaseSchemaMetadata := new(storepb.DatabaseSchemaMetadata)
- databaseSchemaMetadata.Name = dbName
schemaMetadata, err := d.getDatabaseInfoByName(ctx, dbName)
if err != nil {
return nil, errors.Wrapf(err, "failed to get info from database %s", dbName)
}
- databaseSchemaMetadata.Schemas = append(databaseSchemaMetadata.Schemas, schemaMetadata)
-
- return databaseSchemaMetadata, nil
+ return &storepb.DatabaseSchemaMetadata{
+ Name: dbName,
+ Schemas: []*storepb.SchemaMetadata{schemaMetadata},
+ }, nil
}
func (*Driver) SyncSlowQuery(_ context.Context, _ time.Time) (map[string]*storepb.SlowQueryStatistics, error) {
@@ -92,7 +65,7 @@ func (*Driver) CheckSlowQueryLogEnabled(_ context.Context) error {
}
func (d *Driver) getVersion(ctx context.Context) (string, error) {
- conn, err := d.connPool.Get("")
+ conn, err := d.connPool.Get()
if err != nil {
return "", err
}
@@ -101,14 +74,22 @@ func (d *Driver) getVersion(ctx context.Context) (string, error) {
if err != nil {
return "", errors.Wrap(err, "failed to get version from instance")
}
- versionRawStr := result.Rows[0].Values[0].GetStringValue()
- version := strings.Split(versionRawStr, " ")[0]
- return version, nil
+
+ if len(result.Rows) == 0 || len(result.Rows[0].Values) == 0 {
+ return "", errors.New("invalid version result")
+ }
+ // rawVersion has the format of "1.2.3 commitID".
+ rawVersion := result.Rows[0].Values[0].GetStringValue()
+ tokens := strings.Split(rawVersion, " ")
+ if len(tokens) == 0 {
+ return "", errors.Errorf("invalid version %q", rawVersion)
+ }
+ return tokens[0], nil
}
func (d *Driver) getDatabaseNames(ctx context.Context) ([]string, error) {
var databaseNames []string
- conn, err := d.connPool.Get("")
+ conn, err := d.connPool.Get()
if err != nil {
return nil, err
}
@@ -118,13 +99,16 @@ func (d *Driver) getDatabaseNames(ctx context.Context) ([]string, error) {
return nil, errors.Wrap(err, "failed to get version from instance")
}
for _, row := range result.Rows {
+ if row == nil || len(row.Values) == 0 {
+ return nil, errors.New("row values have zero length")
+ }
databaseNames = append(databaseNames, row.Values[0].GetStringValue())
}
return databaseNames, nil
}
func (d *Driver) listTablesNames(ctx context.Context, databaseName string) ([]string, error) {
- conn, err := d.connPool.Get("")
+ conn, err := d.connPool.Get()
if err != nil {
return nil, err
}
@@ -134,11 +118,14 @@ func (d *Driver) listTablesNames(ctx context.Context, databaseName string) ([]st
return nil, errors.Wrap(err, "failed to get version from instance")
}
- var tabNames []string
+ var tableNames []string
for _, row := range result.Rows {
- tabNames = append(tabNames, row.Values[0].GetStringValue())
+ if row == nil || len(row.Values) == 0 {
+ return nil, errors.New("row values have zero length")
+ }
+ tableNames = append(tableNames, row.Values[0].GetStringValue())
}
- return tabNames, nil
+ return tableNames, nil
}
// getTables fetches table info and returns structed table data.
@@ -157,77 +144,91 @@ func (d *Driver) getTables(ctx context.Context, databaseName string) (
)
// list tables' names.
- tabNames, err := d.listTablesNames(ctx, databaseName)
+ tableNames, err := d.listTablesNames(ctx, databaseName)
if err != nil {
return nil, nil, nil, nil, errors.Wrapf(err, "failed to list tables")
}
// iterations in tables of certain database.
- for _, tabName := range tabNames {
+ for _, tableName := range tableNames {
// filter out index table names.
- if strings.HasSuffix(tabName, "__") {
+ if strings.HasSuffix(tableName, "__") {
continue
}
- tabInfo, err := d.getTableInfo(ctx, tabName, databaseName)
+ tableInfo, err := d.getTableInfo(ctx, tableName, databaseName)
if err != nil {
- return nil, nil, nil, nil, errors.Wrapf(err, "failed to describe table %s's type", tabName)
+ return nil, nil, nil, nil, errors.Wrapf(err, "failed to describe table %s's type", tableName)
}
// different processing way according to the type of the table.
- if tabInfo.tabType == "MATERIALIZED_VIEW" {
+ switch tableInfo.tableType {
+ case "MATERIALIZED_VIEW":
mtViewMetadatas = append(mtViewMetadatas, &storepb.MaterializedViewMetadata{
- Name: tabName,
- Definition: tabInfo.viewDef,
- Comment: tabInfo.comment,
+ Name: tableName,
+ Definition: tableInfo.viewDef,
+ Comment: tableInfo.comment,
})
- continue
- } else if tabInfo.tabType == "VIRTUAL_VIEW" {
+ case "VIRTUAL_VIEW":
viewMetadatas = append(viewMetadatas, &storepb.ViewMetadata{
- Name: tabName,
- Definition: tabInfo.viewDef,
- Comment: tabInfo.comment,
+ Name: tableName,
+ Definition: tableInfo.viewDef,
+ Comment: tableInfo.comment,
})
- continue
- } else if tabInfo.tabType == "EXTERNAL_TABLE" {
+ case "EXTERNAL_TABLE":
extTableMetadatas = append(extTableMetadatas, &storepb.ExternalTableMetadata{
- Name: tabName,
- Columns: tabInfo.colMetadatas,
+ Name: tableName,
+ Columns: tableInfo.colMetadatas,
})
- continue
- } else if tabInfo.tabType != "MANAGED_TABLE" {
- return nil, nil, nil, nil, errors.Errorf("unsupported table type: %s", tabInfo.tabType)
- }
-
- var tableMetadata storepb.TableMetadata
-
- // partitions.
- conn, err := d.connPool.Get("")
- if err != nil {
- return nil, nil, nil, nil, err
- }
- partitionResult, err := runSingleStatement(ctx, conn, fmt.Sprintf("SHOW PARTITIONS `%s`.`%s`", databaseName, tabName))
- if err == nil {
- for _, row := range partitionResult.Rows {
- tableMetadata.Partitions = append(tableMetadata.Partitions, &storepb.TablePartitionMetadata{
- Name: row.Values[0].GetStringValue(),
- })
+ case "MANAGED_TABLE":
+ partitions, err := d.getPartitions(ctx, databaseName, tableName)
+ if err != nil {
+ return nil, nil, nil, nil, err
}
+ tableMetadatas = append(tableMetadatas, &storepb.TableMetadata{
+ Engine: "HDFS",
+ Comment: tableInfo.comment,
+ Columns: tableInfo.colMetadatas,
+ DataSize: int64(tableInfo.totalSize),
+ RowCount: int64(tableInfo.numRows),
+ Partitions: partitions,
+ Name: tableName,
+ })
+ default:
+ // ignore other types of tables.
}
- d.connPool.Put(conn)
-
- tableMetadata.Engine = "HDFS"
- tableMetadata.Comment = tabInfo.comment
- tableMetadata.Columns = tabInfo.colMetadatas
- tableMetadata.DataSize = int64(tabInfo.totalSize)
- tableMetadata.RowCount = int64(tabInfo.numRows)
- tableMetadata.Name = tabName
- tableMetadatas = append(tableMetadatas, &tableMetadata)
}
return tableMetadatas, extTableMetadatas, viewMetadatas, mtViewMetadatas, nil
}
+func (d *Driver) getPartitions(ctx context.Context, databaseName, tableName string) ([]*storepb.TablePartitionMetadata, error) {
+ // partitions.
+ conn, err := d.connPool.Get()
+ if err != nil {
+ return nil, err
+ }
+ defer d.connPool.Put(conn)
+ partitionResult, err := runSingleStatement(ctx, conn, fmt.Sprintf("SHOW PARTITIONS `%s`.`%s`", databaseName, tableName))
+ if err != nil {
+ slog.Debug("failed to get partitions", log.BBError(err))
+ return nil, nil
+ }
+ if partitionResult == nil {
+ return nil, nil
+ }
+ var partitions []*storepb.TablePartitionMetadata
+ for _, row := range partitionResult.Rows {
+ if row == nil || len(row.Values) == 0 {
+ return nil, errors.New("partitions result row has zero length")
+ }
+ partitions = append(partitions, &storepb.TablePartitionMetadata{
+ Name: row.Values[0].GetStringValue(),
+ })
+ }
+ return partitions, nil
+}
+
// This function gets certain database info by name.
func (d *Driver) getDatabaseInfoByName(ctx context.Context, databaseName string) (*storepb.SchemaMetadata, error) {
// fetch table metadata.
@@ -246,7 +247,7 @@ func (d *Driver) getDatabaseInfoByName(ctx context.Context, databaseName string)
}
type TableInfo struct {
- tabType string
+ tableType string
colMetadatas []*storepb.ColumnMetadata
numRows int
viewDef string
@@ -261,13 +262,12 @@ func (d *Driver) getTableInfo(ctx context.Context, tabName string, databaseName
var (
columnMetadatas []*storepb.ColumnMetadata
comment string
- tabType string
+ tableType string
viewDefination string
totalSize int
numRows int
- hasReadColumns = false
)
- conn, err := d.connPool.Get("")
+ conn, err := d.connPool.Get()
if err != nil {
return nil, err
}
@@ -281,83 +281,82 @@ func (d *Driver) getTableInfo(ctx context.Context, tabName string, databaseName
if cursor.Err != nil {
return nil, errors.Wrapf(cursor.Err, "failed to describe table %s", tabName)
}
-
- for idx := 0; cursor.HasMore(ctx); idx++ {
+ cnt := 0
+ for cursor.HasMore(ctx) {
var (
- typeColStr string
- commentColStr string
- colNameColStr string
- rowMap = cursor.RowMap(ctx)
+ dataTypeValue string
+ commentValue string
+ columnNameValue string
)
-
- if idx < 2 {
+ cnt++
+ // the first two rows contain the metadata of the rowMap.
+ if cnt <= 2 {
continue
}
- if rowMap["data_type"] == nil {
- typeColStr = ""
- } else {
- ok := false
- typeColStr, ok = rowMap["data_type"].(string)
+ // the rowMap contains the metadata for the table and its columns.
+ rowMap := cursor.RowMap(ctx)
+ if rowMap["data_type"] != nil {
+ v, ok := rowMap["data_type"].(string)
if !ok {
return nil, errors.New("type assertions fails: data_type")
}
+ dataTypeValue = v
}
- if rowMap["comment"] == nil {
- commentColStr = ""
- } else {
- commentColStr = strings.TrimRight(rowMap["comment"].(string), " ")
+ if rowMap["comment"] != nil {
+ v, ok := rowMap["comment"].(string)
+ if !ok {
+ return nil, errors.New("type assertion fails: comment")
+ }
+ commentValue = strings.TrimRight(v, " ")
}
- if rowMap["col_name"] == nil {
- colNameColStr = ""
- } else {
- ok := false
- colNameColStr, ok = rowMap["col_name"].(string)
+ if rowMap["col_name"] != nil {
+ v, ok := rowMap["col_name"].(string)
if !ok {
return nil, errors.New("type assertions fails: col_name")
}
+ columnNameValue = v
}
// process table type.
- if strings.Contains(colNameColStr, "Table Type") {
- tabType = strings.ReplaceAll(typeColStr, " ", "")
- } else if colNameColStr == "" {
- hasReadColumns = true
+ if strings.Contains(columnNameValue, "Table Type") {
+ tableType = strings.ReplaceAll(dataTypeValue, " ", "")
}
- if !hasReadColumns {
+
+ if columnNameValue != "" {
// process column.
columnMetadatas = append(columnMetadatas, &storepb.ColumnMetadata{
- Name: colNameColStr,
- Type: typeColStr,
- Comment: commentColStr,
+ Name: columnNameValue,
+ Type: dataTypeValue,
+ Comment: commentValue,
})
+ continue
}
- // get row count.
- if strings.Contains(typeColStr, "numRows") {
- n, err := strconv.Atoi(commentColStr)
+ switch {
+ case strings.Contains(dataTypeValue, "numRows"):
+ n, err := strconv.Atoi(commentValue)
if err != nil {
return nil, errors.Wrapf(err, "failed to parse row count")
}
numRows = n
- }
- if strings.Contains(typeColStr, "totalSize") {
- size, err := strconv.Atoi(commentColStr)
+ case strings.Contains(dataTypeValue, "totalSize"):
+ size, err := strconv.Atoi(commentValue)
if err != nil {
return nil, errors.Wrapf(err, "failed to parse table size")
}
totalSize = size
+ case strings.Contains(dataTypeValue, "comment"):
+ comment = commentValue
}
- if strings.Contains(colNameColStr, "View Original Text") {
+
+ if strings.Contains(columnNameValue, "View Original Text") {
// get view definition if it exists.
- viewDefination = typeColStr
- }
- if strings.Contains(typeColStr, "comment") {
- comment = commentColStr
+ viewDefination = dataTypeValue
}
}
return &TableInfo{
- tabType,
+ tableType,
columnMetadatas,
numRows,
viewDefination,