Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: implement PostgreSQL AI-based index advisor (#5885)
rebelice37045a851918
diff --git a/backend/api/v1/database_service.go b/backend/api/v1/database_service.goindex 40f6572440..0450c0eada 100644--- a/backend/api/v1/database_service.go+++ b/backend/api/v1/database_service.go@@ -12,10 +12,12 @@ import ("unicode""github.com/pkg/errors"+ openai "github.com/sashabaranov/go-openai""go.uber.org/zap""google.golang.org/grpc/codes""google.golang.org/grpc/status"+ "google.golang.org/protobuf/encoding/protojson""google.golang.org/protobuf/types/known/durationpb""google.golang.org/protobuf/types/known/emptypb""google.golang.org/protobuf/types/known/timestamppb"@@ -24,6 +26,9 @@ import ("github.com/bytebase/bytebase/backend/common/log"enterpriseAPI "github.com/bytebase/bytebase/backend/enterprise/api"api "github.com/bytebase/bytebase/backend/legacyapi"+ "github.com/bytebase/bytebase/backend/plugin/db"+ parser "github.com/bytebase/bytebase/backend/plugin/parser/sql"+ "github.com/bytebase/bytebase/backend/plugin/parser/sql/ast""github.com/bytebase/bytebase/backend/runner/backuprun""github.com/bytebase/bytebase/backend/store"storepb "github.com/bytebase/bytebase/proto/generated-go/store"@@ -1390,3 +1395,159 @@ func isSecretValid(secret *storepb.SecretItem) error {func isUpperCaseLetter(c rune) bool {return 'A' <= c && c <= 'Z'}++// AdviseIndex advises the index of a table.+func (s *DatabaseService) AdviseIndex(ctx context.Context, request *v1pb.AdviseIndexRequest) (*v1pb.AdviseIndexResponse, error) {+ environmentID, instanceID, databaseName, err := getEnvironmentInstanceDatabaseID(request.Parent)+ if err != nil {+ return nil, status.Errorf(codes.InvalidArgument, err.Error())+ }++ findDatabase := &store.FindDatabaseMessage{+ EnvironmentID: &environmentID,+ InstanceID: &instanceID,+ DatabaseName: &databaseName,+ }+ database, err := s.store.GetDatabaseV2(ctx, findDatabase)+ if err != nil {+ return nil, status.Errorf(codes.Internal, "Failed to get database: %v", err)+ }++ findInstance := &store.FindInstanceMessage{+ EnvironmentID: &environmentID,+ ResourceID: &instanceID,+ }+ instance, err := s.store.GetInstanceV2(ctx, findInstance)+ if err != nil {+ return nil, status.Errorf(codes.Internal, "Failed to get instance: %v", err)+ }++ switch instance.Engine {+ case db.Postgres:+ return s.pgAdviseIndex(ctx, request, database)+ default:+ return nil, status.Errorf(codes.Unimplemented, "AdviseIndex is not implemented for engine: %v", instance.Engine)+ }+}++func (s *DatabaseService) pgAdviseIndex(ctx context.Context, request *v1pb.AdviseIndexRequest, database *store.DatabaseMessage) (*v1pb.AdviseIndexResponse, error) {+ openaiKeyName := api.SettingPluginOpenAIKey+ key, err := s.store.GetSettingV2(ctx, &store.FindSettingMessage{Name: &openaiKeyName})+ if err != nil {+ return nil, status.Errorf(codes.Internal, "Failed to get setting: %v", err)+ }+ if key.Value == "" {+ return nil, status.Errorf(codes.FailedPrecondition, "OpenAI key is not set")+ }++ schema, err := s.store.GetDBSchema(ctx, database.UID)+ if err != nil {+ return nil, status.Errorf(codes.Internal, "Failed to get database schema: %v", err)+ }+ compactSchema, err := schema.CompactText()+ if err != nil {+ return nil, status.Errorf(codes.Internal, "Failed to compact database schema: %v", err)+ }++ messages := []openai.ChatCompletionMessage{+ {+ Role: openai.ChatMessageRoleSystem,+ Content: `You are a PostgreSQL index advisor. You answer the question about the index of tables and SQLs. DO NOT EXPLAIN THE ANSWER.`,+ },+ {+ Role: openai.ChatMessageRoleUser,+ Content: `You are an assistant who works as a Magic: The strict PostgreSQL index advisor. Analyze the SQL with schema and existing indexes, then give the advice in the JSON format.+ If the SQL will use the existing index, the current_index field is the index name with schema name and table name. Otherwise, the current_index field is "N/A".+ If it is possible to create a new index to speed up the query, the create_index_statement field is the SQL statement to create the index. Otherwise, the create_index_statement field is empty string.+ YOUR ADVICE MUST FOLLOW JSON FORMAT. DO NOT EXPLAIN THE ADVICE.+ Here two examples:+ {"current_index": "index_schema_table_age ON public.schema_table", "create_index_statement":""}+ {"current_index": "N/A", "create_index_statement":"CREATE INDEX ON schema_table(collected_at, schema_index_id)"}+ ` + fmt.Sprintf(`### Postgres schema:\n### %s\n###The SQL is:\n### %s###`, compactSchema, request.Statement),+ },+ }++ generateFunc := func(resp *v1pb.AdviseIndexResponse) error {+ // Generate current index.+ if resp.CurrentIndex != "N/A" {+ // Use regex to extract the index name, schema name and table name from "index_schema_table_age ON public.schema_table".+ reg := regexp.MustCompile(`(?i)(.*) ON (.*)\.(.*)`)+ matches := reg.FindStringSubmatch(resp.CurrentIndex)+ if len(matches) != 4 {+ return errors.Errorf("failed to extract index name, schema name and table name from %s", resp.CurrentIndex)+ }+ indexMetadata := schema.FindIndex(matches[2], matches[3], matches[1])+ if indexMetadata == nil {+ return errors.Errorf("index %s doesn't exist", resp.CurrentIndex)+ }+ resp.CurrentIndex = fmt.Sprintf("USING %s (%s)", indexMetadata.Type, strings.Join(indexMetadata.Expressions, ", "))+ } else {+ resp.CurrentIndex = "No usable index"+ }++ // Generate suggestion and create index statement.+ if resp.CreateIndexStatement != "" {+ nodes, err := parser.Parse(parser.Postgres, parser.ParseContext{}, resp.CreateIndexStatement)+ if err != nil {+ return errors.Errorf("failed to parse create index statement: %v", err)+ }+ if len(nodes) != 1 {+ return errors.Errorf("expect 1 statement, but got %d", len(nodes))+ }+ switch node := nodes[0].(type) {+ case *ast.CreateIndexStmt:+ resp.Suggestion = fmt.Sprintf("USING %s (%s)", node.Index.Method, strings.Join(node.Index.GetKeyNameList(), ", "))+ default:+ return errors.Errorf("expect CreateIndexStmt, but got %T", node)+ }+ } else {+ resp.Suggestion = "N/A"+ }++ return nil+ }++ result, err := getOpenAIResponse(ctx, messages, key.Value, generateFunc)+ if err != nil {+ return nil, err+ }++ return result, nil+}++func getOpenAIResponse(ctx context.Context, messages []openai.ChatCompletionMessage, key string, generateResponse func(*v1pb.AdviseIndexResponse) error) (*v1pb.AdviseIndexResponse, error) {+ var result v1pb.AdviseIndexResponse+ successful := false+ // Retry 5 times if failed.+ for i := 0; i < 5; i++ {+ client := openai.NewClient(key)+ resp, err := client.CreateChatCompletion(+ ctx,+ openai.ChatCompletionRequest{+ Model: openai.GPT3Dot5Turbo,+ Messages: messages,+ Temperature: 0,+ Stop: []string{"#", ";"},+ TopP: 1.0,+ FrequencyPenalty: 0.0,+ PresencePenalty: 0.0,+ },+ )+ if err != nil {+ continue+ }+ if err := protojson.Unmarshal([]byte(resp.Choices[0].Message.Content), &result); err != nil {+ continue+ }+ if err = generateResponse(&result); err != nil {+ continue+ }+ successful = true+ break+ }++ if !successful {+ return nil, status.Errorf(codes.Internal, "Failed to get index advice")+ }+ return &result, nil+}diff --git a/backend/plugin/parser/sql/ast/index_def.go b/backend/plugin/parser/sql/ast/index_def.goindex e5e8d82808..271154b950 100644--- a/backend/plugin/parser/sql/ast/index_def.go+++ b/backend/plugin/parser/sql/ast/index_def.go@@ -18,6 +18,26 @@ const (IndexMethodTypeBrin)+// String implements fmt.Stringer interface.+func (tp IndexMethodType) String() string {+ switch tp {+ case IndexMethodTypeBTree:+ return "btree"+ case IndexMethodTypeHash:+ return "hash"+ case IndexMethodTypeGiST:+ return "gist"+ case IndexMethodTypeSpGiST:+ return "spgist"+ case IndexMethodTypeGin:+ return "gin"+ case IndexMethodTypeBrin:+ return "brin"+ default:+ return ""+ }+}+// IndexDef is the struct for index definition.type IndexDef struct {nodediff --git a/backend/store/db_schema.go b/backend/store/db_schema.goindex b04a41c84b..e72110d770 100644--- a/backend/store/db_schema.go+++ b/backend/store/db_schema.go@@ -1,6 +1,7 @@package storeimport (+ "bytes""context""database/sql""fmt"@@ -17,6 +18,66 @@ type DBSchema struct {Schema []byte}+// CompactText returns the compact text representation of the database schema.+func (s *DBSchema) CompactText() (string, error) {+ if s.Metadata == nil {+ return "", nil+ }++ var buf bytes.Buffer+ for _, schema := range s.Metadata.Schemas {+ for _, table := range schema.Tables {+ // Table with columns.+ if _, err := buf.WriteString(fmt.Sprintf("# Table %s.%s(", schema.Name, table.Name)); err != nil {+ return "", err+ }+ for i, column := range table.Columns {+ if i == 0 {+ if _, err := buf.WriteString(column.Name); err != nil {+ return "", err+ }+ } else {+ if _, err := buf.WriteString(fmt.Sprintf(", %s", column.Name)); err != nil {+ return "", err+ }+ }+ }+ if _, err := buf.WriteString(") #\n"); err != nil {+ return "", err+ }++ // Indexes.+ for _, index := range table.Indexes {+ if _, err := buf.WriteString(fmt.Sprintf("# Index %s(%s) ON table %s.%s #\n", index.Name, strings.Join(index.Expressions, ", "), schema.Name, table.Name)); err != nil {+ return "", err+ }+ }+ }+ }++ return buf.String(), nil+}++// FindIndex finds the index by name.+func (s *DBSchema) FindIndex(schemaName string, tableName string, indexName string) *storepb.IndexMetadata {+ for _, schema := range s.Metadata.Schemas {+ if schema.Name != schemaName {+ continue+ }+ for _, table := range schema.Tables {+ if table.Name != tableName {+ continue+ }+ for _, index := range table.Indexes {+ if index.Name == indexName {+ return index+ }+ }+ }+ }+ return nil+}+// GetDBSchema gets the schema for a database.func (s *Store) GetDBSchema(ctx context.Context, databaseID int) (*DBSchema, error) {if dbSchema, ok := s.dbSchemaCache.Load(databaseID); ok {diff --git a/go.mod b/go.modindex 263f2f673e..7a4d5030ba 100644--- a/go.mod+++ b/go.mod@@ -42,6 +42,7 @@ require (github.com/pkg/errors v0.9.1github.com/qiangmzsx/string-adapter/v2 v2.2.0github.com/redis/go-redis/v9 v9.0.3+ github.com/sashabaranov/go-openai v1.9.0github.com/segmentio/analytics-go v3.1.0+incompatiblegithub.com/shopspring/decimal v1.3.1github.com/sijms/go-ora/v2 v2.7.1diff --git a/go.sum b/go.sumindex 84c8b44efb..77e441177a 100644--- a/go.sum+++ b/go.sum@@ -790,6 +790,8 @@ github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDgithub.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=github.com/samuel/go-zookeeper v0.0.0-20190923202752-2cc03de413da/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E=+github.com/sashabaranov/go-openai v1.9.0 h1:NoiO++IISxxJ1pRc0n7uZvMGMake0G+FJ1XPwXtprsA=+github.com/sashabaranov/go-openai v1.9.0/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg=github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww=github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=