Skip to content

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

refactor(hive): query with connection pool (#11417)

Azusain90dc9abad539
diff --git a/backend/plugin/db/hive/dump.go b/backend/plugin/db/hive/dump.go
index b4fd65aac0..3d0c7d03dc 100644
--- a/backend/plugin/db/hive/dump.go
+++ b/backend/plugin/db/hive/dump.go
@@ -53,24 +53,26 @@ type MaterializedViewDDLOptions struct {
}
func (d *Driver) Dump(ctx context.Context, _ io.Writer, _ bool) (string, error) {
- // TODO(tommy): hard code.
instanceMetadata, err := d.SyncInstance(ctx)
if err != nil {
return "", errors.Wrapf(err, "failed to sync instance")
}
var dumpStrBuilder strings.Builder
- for _, database := range instanceMetadata.Databases[0].Schemas {
+
+ for _, database := range instanceMetadata.Databases {
+ schema := database.Schemas[0]
+
// dump databases.
- databaseDDL, err := d.showCreateSchemaDDL(ctx, "DATABASE", database.Name, "")
+ databaseDDL, err := d.showCreateSchemaDDL(ctx, "DATABASE", schema.Name, "")
if err != nil {
- return "", errors.Wrapf(err, "failed to dump database %s", database.Name)
+ return "", errors.Wrapf(err, "failed to dump database %s", schema.Name)
}
_, _ = dumpStrBuilder.WriteString(databaseDDL)
// dump managed tables.
- for _, table := range database.Tables {
- tabDDL, err := d.showCreateSchemaDDL(ctx, "TABLE", table.Name, database.Name)
+ for _, table := range schema.Tables {
+ tabDDL, err := d.showCreateSchemaDDL(ctx, "TABLE", table.Name, schema.Name)
if err != nil {
return "", errors.Wrapf(err, "failed to dump table %s", table.Name)
}
@@ -79,7 +81,7 @@ func (d *Driver) Dump(ctx context.Context, _ io.Writer, _ bool) (string, error)
for _, index := range table.Indexes {
// TODO(tommy): get more index size from SyncInstance.
indexDDL, err := genIndexDDL(&IndexDDLOptions{
- databaseName: database.Name,
+ databaseName: schema.Name,
indexName: index.Name,
tableName: table.Name,
indexType: index.Type,
@@ -104,8 +106,8 @@ func (d *Driver) Dump(ctx context.Context, _ io.Writer, _ bool) (string, error)
}
// dump external tables.
- for _, extTable := range database.ExternalTables {
- tabDDL, err := d.showCreateSchemaDDL(ctx, "TABLE", extTable.Name, database.Name)
+ 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)
}
@@ -113,8 +115,8 @@ func (d *Driver) Dump(ctx context.Context, _ io.Writer, _ bool) (string, error)
}
// dump views.
- for _, view := range database.Views {
- viewDDL, err := d.showCreateSchemaDDL(ctx, "VIEW", view.Name, database.Name)
+ 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)
}
@@ -122,9 +124,9 @@ func (d *Driver) Dump(ctx context.Context, _ io.Writer, _ bool) (string, error)
}
// dump materialized views.
- for _, mtView := range database.MaterializedViews {
+ for _, mtView := range schema.MaterializedViews {
mtViewDDL, err := genMaterializedViewDDL(&MaterializedViewDDLOptions{
- databaseName: database.Name,
+ databaseName: schema.Name,
mtViewName: mtView.Name,
disableRewrite: false,
comment: mtView.Comment,
@@ -144,7 +146,7 @@ func (d *Driver) Dump(ctx context.Context, _ io.Writer, _ bool) (string, error)
return "", errors.Wrapf(err, "failed to generate DDL for materialized view %s", mtView.Name)
}
- _, _ = dumpStrBuilder.WriteString(fmt.Sprintf(schemaStmtFmt, "MATERIALIZED VIEW", fmt.Sprintf("`%s`.`%s`", database.Name, mtView.Name), mtViewDDL))
+ _, _ = dumpStrBuilder.WriteString(fmt.Sprintf(schemaStmtFmt, "MATERIALIZED VIEW", fmt.Sprintf("`%s`.`%s`", schema.Name, mtView.Name), mtViewDDL))
}
}
diff --git a/backend/plugin/db/hive/hive.go b/backend/plugin/db/hive/hive.go
index 39cb6f38ce..84aa3c5aa8 100644
--- a/backend/plugin/db/hive/hive.go
+++ b/backend/plugin/db/hive/hive.go
@@ -32,7 +32,7 @@ func init() {
type Driver struct {
config db.ConnectionConfig
ctx db.ConnectionContext
- dbClient *gohive.Connection
+ ConnPool *FixedConnPool
}
var (
@@ -58,19 +58,24 @@ func (d *Driver) Open(_ context.Context, _ storepb.Engine, config db.ConnectionC
if err != nil {
return nil, errors.Errorf("conversion failure for 'port' [string -> int]")
}
+
// TODO(tommy): actually there are various kinds of authentication to choose among [SASL, KERBEROS, NOSASL, PLAIN SASL]
// "NONE" refers to PLAIN SASL that doesn't need authentication.
- authMethods := "NONE"
- conn, errConn := gohive.Connect(config.Host, port, authMethods, configuration)
- if errConn != nil {
- return nil, errors.Errorf("failed to establish connection")
+ pool, err := CreateHiveConnPool(5, ConnPoolConfig{
+ Host: config.Host,
+ Port: port,
+ Config: configuration,
+ }, PlainSASLConnFactory)
+ if err != nil {
+ return nil, err
}
- d.dbClient = conn
+ d.ConnPool = pool
+
return d, nil
}
func (d *Driver) Close(_ context.Context) error {
- err := d.dbClient.Close()
+ err := d.ConnPool.Destroy()
if err != nil {
return errors.Errorf("faild to close connection")
}
@@ -78,7 +83,7 @@ func (d *Driver) Close(_ context.Context) error {
}
func (d *Driver) Ping(ctx context.Context) error {
- if d.dbClient == nil {
+ if d.ConnPool == nil {
return errors.Errorf("no database connection established")
}
if _, err := d.QueryConn(ctx, nil, "SELECT 1", &db.QueryContext{}); err != nil {
@@ -99,15 +104,21 @@ 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.dbClient == nil {
+ if d.ConnPool == nil {
return 0, errors.Errorf("no database connection established")
}
- var (
- affectedRows int64
- cursor = d.dbClient.Cursor()
- )
- defer cursor.Close()
+ var affectedRows int64
+
+ conn, err := d.ConnPool.Get()
+ if err != nil {
+ return 0, err
+ }
+ cursor := conn.Cursor()
+ defer func() {
+ cursor.Close()
+ d.ConnPool.Put(conn)
+ }()
statements, err := base.SplitMultiSQL(storepb.Engine_HIVE, statementsStr)
if err != nil {
@@ -126,9 +137,8 @@ func (d *Driver) Execute(ctx context.Context, statementsStr string, _ db.Execute
return affectedRows, nil
}
-// TODO(tommy): run query asynchronously.
func (d *Driver) QueryConn(ctx context.Context, _ *sql.Conn, statementsStr string, queryCtx *db.QueryContext) ([]*v1pb.QueryResult, error) {
- if d.dbClient == nil {
+ if d.ConnPool == nil {
return nil, errors.Errorf("no database connection established")
}
@@ -139,29 +149,32 @@ func (d *Driver) QueryConn(ctx context.Context, _ *sql.Conn, statementsStr strin
return nil, errors.Wrapf(err, "failed to split statements")
}
+ isAdminMode := false
+ if queryCtx != nil && !queryCtx.ReadOnly {
+ isAdminMode = true
+ }
+
for _, statement := range statements {
statementStr := strings.TrimRight(statement.Text, ";")
if queryCtx != nil && queryCtx.Limit > 0 {
statementStr = fmt.Sprintf("%s LIMIT %d", statementStr, queryCtx.Limit)
}
- result, err := d.runSingleQuery(ctx, statementStr)
+ result, err := d.runSingleStatement(ctx, statementStr, isAdminMode)
if err != nil {
result.Error = err.Error()
return nil, err
}
+
results = append(results, result)
}
return results, nil
}
-// TODO(tommy): this func is used for admin mode.
+// this func is used for admin mode in SQL Editor.
func (d *Driver) RunStatement(ctx context.Context, _ *sql.Conn, statement string) ([]*v1pb.QueryResult, error) {
- if err := d.SetRole(ctx, "admin"); err != nil {
- return nil, errors.Wrapf(err, "failed to switch role to admin")
- }
- results, err := d.QueryConn(ctx, nil, statement, nil)
+ results, err := d.QueryConn(ctx, nil, statement, &db.QueryContext{ReadOnly: false})
if err != nil {
return nil, errors.Wrapf(err, "")
}
@@ -201,13 +214,27 @@ func parseValueType(value any, gohiveType string) (*v1pb.RowValue, error) {
return &rowValue, nil
}
-func (d *Driver) runSingleQuery(ctx context.Context, statement string) (*v1pb.QueryResult, error) {
+func (d *Driver) runSingleStatement(ctx context.Context, statement string, readOnly bool) (*v1pb.QueryResult, error) {
var (
result = v1pb.QueryResult{}
startTime = time.Now()
)
- cursor := d.dbClient.Cursor()
- defer cursor.Close()
+
+ conn, err := d.ConnPool.Get()
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to get connection from pool")
+ }
+ cursor := conn.Cursor()
+ defer func() {
+ cursor.Close()
+ d.ConnPool.Put(conn)
+ }()
+
+ if readOnly {
+ if err := SetRole(ctx, conn, "admin"); err != nil {
+ return nil, err
+ }
+ }
// run query.
cursor.Execute(ctx, statement, false)
@@ -218,7 +245,7 @@ func (d *Driver) runSingleQuery(ctx context.Context, statement string) (*v1pb.Qu
// Statement.
result.Statement = statement
if cursor.Err != nil {
- return &result, errors.Wrapf(cursor.Err, "failed to execute statement")
+ return &result, errors.Wrapf(cursor.Err, "failed to execute statement %s", statement)
}
columnNamesAndTypes := cursor.Description()
diff --git a/backend/plugin/db/hive/hive_conn_pool.go b/backend/plugin/db/hive/hive_conn_pool.go
new file mode 100644
index 0000000000..a3c298c568
--- /dev/null
+++ b/backend/plugin/db/hive/hive_conn_pool.go
@@ -0,0 +1,99 @@
+package hive
+
+import (
+ "sync"
+
+ "github.com/beltran/gohive"
+ "github.com/pkg/errors"
+)
+
+type ConnPool interface {
+ Get() (*gohive.Connection, error)
+ Put(*gohive.Connection)
+ Destroy() error
+}
+
+type FixedConnPool struct {
+ RWMutex sync.RWMutex
+ Connections chan *gohive.Connection
+ IsActivated bool
+ NumMaxConns int
+}
+
+var _ ConnPool = &FixedConnPool{}
+
+type ConnPoolConfig struct {
+ Config *gohive.ConnectConfiguration
+ Host string
+ Port int
+}
+
+func PlainSASLConnFactory(poolConfig ConnPoolConfig) (*gohive.Connection, error) {
+ conn, err := gohive.Connect(poolConfig.Host, poolConfig.Port, "NONE", poolConfig.Config)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to establish Hive connection")
+ }
+ return conn, nil
+}
+
+func CreateHiveConnPool(
+ numMaxConn int,
+ poolConfig ConnPoolConfig,
+ hiveConnFactory func(ConnPoolConfig) (*gohive.Connection, error),
+) (
+ *FixedConnPool, error,
+) {
+ conns := make(chan *gohive.Connection, numMaxConn)
+
+ for i := 0; i < numMaxConn; i++ {
+ conn, err := hiveConnFactory(poolConfig)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to create Hive connection pool")
+ }
+ conns <- conn
+ }
+
+ return &FixedConnPool{
+ RWMutex: sync.RWMutex{},
+ Connections: conns,
+ IsActivated: true,
+ NumMaxConns: numMaxConn,
+ },
+ nil
+}
+
+func (pool *FixedConnPool) Get() (*gohive.Connection, error) {
+ pool.RWMutex.RLock()
+ if !pool.IsActivated {
+ return nil, errors.New("connection pool has been closed")
+ }
+ pool.RWMutex.RUnlock()
+ return <-pool.Connections, nil
+}
+
+func (pool *FixedConnPool) Put(conn *gohive.Connection) {
+ pool.RWMutex.RLock()
+ if !pool.IsActivated {
+ conn.Close()
+ return
+ }
+ pool.RWMutex.RUnlock()
+ pool.Connections <- conn
+}
+
+func (pool *FixedConnPool) Destroy() error {
+ pool.RWMutex.Lock()
+ if pool.IsActivated {
+ pool.IsActivated = false
+ close(pool.Connections)
+ } else {
+ return errors.New("connection pool has been closed already")
+ }
+ pool.RWMutex.Unlock()
+
+ for conn := range pool.Connections {
+ conn.Close()
+ }
+
+ return nil
+}
diff --git a/backend/plugin/db/hive/role.go b/backend/plugin/db/hive/role.go
index 3a6624fc77..fb517cfc4c 100644
--- a/backend/plugin/db/hive/role.go
+++ b/backend/plugin/db/hive/role.go
@@ -5,6 +5,7 @@ import (
"fmt"
"strings"
+ "github.com/beltran/gohive"
"github.com/pkg/errors"
"github.com/bytebase/bytebase/backend/plugin/db"
@@ -29,7 +30,7 @@ func (*Driver) FindRole(_ context.Context, _ string) (*db.DatabaseRoleMessage, e
}
func (d *Driver) ListRole(ctx context.Context) ([]*db.DatabaseRoleMessage, error) {
- roleResults, err := d.QueryConn(ctx, nil, "SHOW ROLES", nil)
+ roleResults, err := d.QueryConn(ctx, nil, "SHOW ROLES", &db.QueryContext{ReadOnly: false})
var roleMessages []*db.DatabaseRoleMessage
if err != nil {
return nil, errors.Wrapf(err, "failed to get roles")
@@ -53,16 +54,20 @@ func (d *Driver) DeleteRole(ctx context.Context, roleName string) error {
}
// some DMLs need admin role.
-func (d *Driver) SetRole(ctx context.Context, roleName string) error {
- _, err := d.Execute(ctx, fmt.Sprintf("SET ROLE %s", roleName), db.ExecuteOptions{})
- if err != nil {
- return errors.Wrapf(err, "failed to set role to %s", roleName)
+func SetRole(ctx context.Context, conn *gohive.Connection, roleName string) error {
+ cursor := conn.Cursor()
+ defer cursor.Close()
+
+ cursor.Exec(ctx, fmt.Sprintf("SET ROLE %s", roleName))
+ if cursor.Err != nil {
+ return errors.Wrapf(cursor.Err, "failed to set role to %s", roleName)
}
+
return nil
}
func (d *Driver) GetRoleGrant(ctx context.Context, roleName string) (string, error) {
- grantResults, err := d.QueryConn(ctx, nil, fmt.Sprintf("SHOW GRANT ROLE %s", roleName), nil)
+ grantResults, err := d.QueryConn(ctx, nil, fmt.Sprintf("SHOW GRANT ROLE %s", roleName), &db.QueryContext{ReadOnly: false})
if err != nil {
return "", errors.Wrapf(err, "failed to get grant from %s", roleName)
}
diff --git a/backend/plugin/db/hive/sync.go b/backend/plugin/db/hive/sync.go
index c2fd789171..208760f538 100644
--- a/backend/plugin/db/hive/sync.go
+++ b/backend/plugin/db/hive/sync.go
@@ -5,6 +5,7 @@ import (
"fmt"
"strconv"
"strings"
+ "sync"
"time"
"github.com/pkg/errors"
@@ -14,13 +15,6 @@ import (
)
func (d *Driver) SyncInstance(ctx context.Context) (*db.InstanceMetadata, error) {
- // roles.
- // TODO(tommy): hard code 'SetRole()'.
- adminRoleName := "admin"
- if err := d.SetRole(ctx, adminRoleName); err != nil {
- return nil, errors.Wrapf(err, "failed to switch role to %s", adminRoleName)
- }
-
var instanceMetadata db.InstanceMetadata
// version.
@@ -35,16 +29,25 @@ func (d *Driver) SyncInstance(ctx context.Context) (*db.InstanceMetadata, error)
return nil, err
}
- for _, databaseName := range databaseNames {
- databaseSchemaMetadata := new(storepb.DatabaseSchemaMetadata)
- databaseSchemaMetadata.Name = databaseName
- schemaMetadata, err := d.getDatabaseInfoByName(ctx, databaseName)
- if err != nil {
- return nil, errors.Wrapf(err, "failed to sync database %s", databaseName)
- }
- databaseSchemaMetadata.Schemas = append(databaseSchemaMetadata.Schemas, schemaMetadata)
- instanceMetadata.Databases = append(instanceMetadata.Databases, databaseSchemaMetadata)
+ var wg sync.WaitGroup
+ instanceMetadata.Databases = make([]*storepb.DatabaseSchemaMetadata, len(databaseNames))
+ for idx, databaseName := range databaseNames {
+ wg.Add(1)
+ go func(index int, databaseName string) {
+ databaseSchemaMetadata := new(storepb.DatabaseSchemaMetadata)
+ databaseSchemaMetadata.Name = databaseName
+
+ schemaMetadata, err := d.getDatabaseInfoByName(ctx, databaseName)
+ if err != nil {
+ return
+ }
+
+ databaseSchemaMetadata.Schemas = append(databaseSchemaMetadata.Schemas, schemaMetadata)
+ instanceMetadata.Databases[index] = databaseSchemaMetadata
+ wg.Done()
+ }(idx, databaseName)
}
+ wg.Wait()
rolesMetadata, err := d.getRoles(ctx)
if err != nil {
@@ -60,10 +63,6 @@ func (d *Driver) SyncDBSchema(ctx context.Context) (*storepb.DatabaseSchemaMetad
if dbName == "" {
dbName = "default"
}
- adminRoleName := "admin"
- if err := d.SetRole(ctx, adminRoleName); err != nil {
- return nil, errors.Wrapf(err, "failed to switch role to %s", adminRoleName)
- }
databaseSchemaMetadata := new(storepb.DatabaseSchemaMetadata)
databaseSchemaMetadata.Name = dbName
@@ -231,9 +230,15 @@ func (d *Driver) getRoles(ctx context.Context) ([]*storepb.InstanceRoleMetadata,
func (d *Driver) getIndexesByTableName(ctx context.Context, tableName string, databaseName string) ([]*storepb.IndexMetadata, error) {
var (
indexMetadata []*storepb.IndexMetadata
- cursor = d.dbClient.Cursor()
)
+
+ conn, err := d.ConnPool.Get()
+ if err != nil {
+ return nil, err
+ }
+ cursor := conn.Cursor()
defer cursor.Close()
+ defer d.ConnPool.Put(conn)
cursor.Execute(ctx, fmt.Sprintf("use %s", databaseName), false)
if cursor.Err != nil {
@@ -296,9 +301,16 @@ func (d *Driver) getTableInfo(ctx context.Context, tabName string, databaseName
totalSize int
numRows int
hasReadColumns = false
- cursor = d.dbClient.Cursor()
)
- defer cursor.Close()
+ conn, err := d.ConnPool.Get()
+ if err != nil {
+ return nil, err
+ }
+ cursor := conn.Cursor()
+ defer func() {
+ cursor.Close()
+ d.ConnPool.Put(conn)
+ }()
cursor.Exec(ctx, fmt.Sprintf("DESCRIBE FORMATTED `%s`.`%s`", databaseName, tabName))
if cursor.Err != nil {
@@ -309,8 +321,8 @@ func (d *Driver) getTableInfo(ctx context.Context, tabName string, databaseName
var (
typeColStr string
commentColStr string
+ colNameColStr string
rowMap = cursor.RowMap(ctx)
- colName = rowMap["col_name"].(string)
)
if idx < 2 {
@@ -322,7 +334,7 @@ func (d *Driver) getTableInfo(ctx context.Context, tabName string, databaseName
ok := false
typeColStr, ok = rowMap["data_type"].(string)
if !ok {
- return nil, errors.New("type assertions fails")
+ return nil, errors.New("type assertions fails: data_type")
}
}
if rowMap["comment"] == nil {
@@ -330,17 +342,26 @@ func (d *Driver) getTableInfo(ctx context.Context, tabName string, databaseName
} else {
commentColStr = strings.TrimRight(rowMap["comment"].(string), " ")
}
+ if rowMap["col_name"] == nil {
+ colNameColStr = ""
+ } else {
+ ok := false
+ colNameColStr, ok = rowMap["col_name"].(string)
+ if !ok {
+ return nil, errors.New("type assertions fails: col_name")
+ }
+ }
// process table type.
- if strings.Contains(colName, "Table Type") {
+ if strings.Contains(colNameColStr, "Table Type") {
tabType = strings.ReplaceAll(typeColStr, " ", "")
- } else if colName == "" {
+ } else if colNameColStr == "" {
hasReadColumns = true
}
if !hasReadColumns {
// process column.
columnMetadatas = append(columnMetadatas, &storepb.ColumnMetadata{
- Name: colName,
+ Name: colNameColStr,
Type: typeColStr,
Comment: commentColStr,
})
@@ -361,7 +382,7 @@ func (d *Driver) getTableInfo(ctx context.Context, tabName string, databaseName
}
totalSize = size
}
- if strings.Contains(colName, "View Original Text") {
+ if strings.Contains(colNameColStr, "View Original Text") {
// get view definition if it exists.
viewDefination = typeColStr
}