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(schema system): schema review supports SQL Editor (#1546)
rebelice313ee4894ce3
diff --git a/api/activity.go b/api/activity.goindex 4b735ccae2..588af6dfaf 100644--- a/api/activity.go+++ b/api/activity.go@@ -3,6 +3,7 @@ package apiimport ("encoding/json"+ "github.com/bytebase/bytebase/plugin/advisor""github.com/bytebase/bytebase/plugin/vcs")@@ -241,11 +242,12 @@ type ActivityProjectDatabaseTransferPayload struct {// ActivitySQLEditorQueryPayload is the API message payloads for the executed query info.type ActivitySQLEditorQueryPayload struct {// Used by activity table to display info without paying the join cost- Statement string `json:"statement"`- DurationNs int64 `json:"durationNs"`- InstanceName string `json:"instanceName"`- DatabaseName string `json:"databaseName"`- Error string `json:"error"`+ Statement string `json:"statement"`+ DurationNs int64 `json:"durationNs"`+ InstanceName string `json:"instanceName"`+ DatabaseName string `json:"databaseName"`+ Error string `json:"error"`+ AdviceList []advisor.Advice `json:"adviceList"`}// Activity is the API message for an activity.diff --git a/api/sql.go b/api/sql.goindex 1f6f370ab8..8c7a64522b 100644--- a/api/sql.go+++ b/api/sql.go@@ -3,6 +3,7 @@ package apiimport ("context"+ "github.com/bytebase/bytebase/plugin/advisor""github.com/bytebase/bytebase/plugin/db")@@ -42,6 +43,8 @@ type SQLResultSet struct {Data string `jsonapi:"attr,data"`// SQL operation may fail for connection issue and there is no proper http status code for it, so we return error in the response body.Error string `jsonapi:"attr,error"`+ // A list of SQL check advice.+ AdviceList []advisor.Advice `jsonapi:"attr,adviceList"`}// SQLService is the service for SQL.diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.goindex 75560acc54..104d23b893 100644--- a/plugin/advisor/advisor.go+++ b/plugin/advisor/advisor.go@@ -9,6 +9,7 @@ import ("github.com/bytebase/bytebase/common""github.com/bytebase/bytebase/plugin/catalog""github.com/bytebase/bytebase/plugin/db"+ "go.uber.org/zap/zapcore")// Status is the advisor result status.@@ -107,6 +108,28 @@ type Advice struct {Content string}+// MarshalLogObject constructs a field that carries Advice.+func (a Advice) MarshalLogObject(enc zapcore.ObjectEncoder) error {+ enc.AddString("status", a.Status.String())+ enc.AddInt("code", int(a.Code))+ enc.AddString("title", a.Title)+ enc.AddString("content", a.Content)+ return nil+}++// ZapAdviceArray is a helper to format zap.Array.+type ZapAdviceArray []Advice++// MarshalLogArray implements the zapcore.ArrayMarshaler interface.+func (array ZapAdviceArray) MarshalLogArray(enc zapcore.ArrayEncoder) error {+ for i := range array {+ if err := enc.AppendObject(array[i]); err != nil {+ return err+ }+ }+ return nil+}+// Context is the context for advisor.type Context struct {Charset stringdiff --git a/server/sql.go b/server/sql.goindex 2dddbef1f6..36b6c6d896 100644--- a/server/sql.go+++ b/server/sql.go@@ -17,8 +17,10 @@ import ("github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common""github.com/bytebase/bytebase/common/log"+ "github.com/bytebase/bytebase/plugin/advisor""github.com/bytebase/bytebase/plugin/db""github.com/bytebase/bytebase/plugin/db/util"+ "github.com/bytebase/bytebase/store")func (s *Server) registerSQLRoutes(g *echo.Group) {@@ -131,9 +133,45 @@ func (s *Server) registerSQLRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", exec.InstanceID))}+ adviceLevel := advisor.Success+ var adviceList []advisor.Advice++ if s.feature(api.FeatureSchemaReviewPolicy) &&+ // For now we only support MySQL dialect schema review check.+ (instance.Engine == db.MySQL || instance.Engine == db.TiDB) {++ adviceLevel, adviceList, err = s.sqlCheck(ctx, instance, exec)+ if err != nil {+ return err+ }++ if adviceLevel == advisor.Error {+ if err := s.createSQLEditorQueryActivity(ctx, c, api.ActivityError, exec.InstanceID, api.ActivitySQLEditorQueryPayload{+ Statement: exec.Statement,+ DurationNs: 0,+ InstanceName: instance.Name,+ DatabaseName: exec.DatabaseName,+ Error: "",+ AdviceList: adviceList,+ }); err != nil {+ return err+ }++ resultSet := api.SQLResultSet{+ AdviceList: adviceList,+ }++ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)+ if err := jsonapi.MarshalPayload(c.Response().Writer, resultSet); err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal sql result set response").SetInternal(err)+ }+ return nil+ }+ }+start := time.Now().UnixNano()- bytes, err := func() ([]byte, error) {+ bytes, queryErr := func() ([]byte, error) {driver, err := tryGetReadOnlyDatabaseDriver(ctx, instance, exec.DatabaseName)if err != nil {return nil, err@@ -148,71 +186,47 @@ func (s *Server) registerSQLRoutes(g *echo.Group) {return json.Marshal(rowSet)}()- {- errMessage := ""- activityLevel := api.ActivityInfo- if err != nil {- errMessage = err.Error()- activityLevel = api.ActivityError- }-- activityBytes, err := json.Marshal(api.ActivitySQLEditorQueryPayload{- Statement: exec.Statement,- DurationNs: time.Now().UnixNano() - start,- InstanceName: instance.Name,- DatabaseName: exec.DatabaseName,- Error: errMessage,- })-- if err != nil {- log.Warn("Failed to marshal activity after executing sql statement",- zap.String("database_name", exec.DatabaseName),- zap.String("instance_name", instance.Name),- zap.String("statement", exec.Statement),- zap.Error(err))- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to construct activity payload").SetInternal(err)- }-- activityCreate := &api.ActivityCreate{- CreatorID: c.Get(getPrincipalIDContextKey()).(int),- Type: api.ActivitySQLEditorQuery,- ContainerID: exec.InstanceID,- Level: activityLevel,- Comment: fmt.Sprintf("Executed `%q` in database %q of instance %q.",- exec.Statement, exec.DatabaseName, instance.Name),- Payload: string(activityBytes),- }-- _, err = s.ActivityManager.CreateActivity(ctx, activityCreate, &ActivityMeta{})-- if err != nil {- log.Warn("Failed to create activity after executing sql statement",- zap.String("database_name", exec.DatabaseName),- zap.String("instance_name", instance.Name),- zap.String("statement", exec.Statement),- zap.Error(err))- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create activity").SetInternal(err)- }+ level := api.ActivityInfo+ errMessage := ""+ if adviceLevel == advisor.Warn {+ level = api.ActivityWarn+ }+ if queryErr != nil {+ level = api.ActivityError+ errMessage = err.Error()+ }+ if err := s.createSQLEditorQueryActivity(ctx, c, level, exec.InstanceID, api.ActivitySQLEditorQueryPayload{+ Statement: exec.Statement,+ DurationNs: time.Now().UnixNano() - start,+ InstanceName: instance.Name,+ DatabaseName: exec.DatabaseName,+ Error: errMessage,+ AdviceList: adviceList,+ }); err != nil {+ return err}- resultSet := &api.SQLResultSet{}- if err == nil {+ resultSet := &api.SQLResultSet{AdviceList: adviceList}+ if queryErr == nil {resultSet.Data = string(bytes)log.Debug("Query result",zap.String("statement", exec.Statement),zap.String("data", resultSet.Data),+ zap.Array("advice", advisor.ZapAdviceArray(resultSet.AdviceList)),)} else {- resultSet.Error = err.Error()+ resultSet.Error = queryErr.Error()if s.profile.Mode == common.ReleaseModeDev {log.Error("Failed to execute query",zap.Error(err),zap.String("statement", exec.Statement),+ zap.Array("advice", advisor.ZapAdviceArray(resultSet.AdviceList)),)} else {log.Debug("Failed to execute query",zap.Error(err),zap.String("statement", exec.Statement),+ zap.Array("advice", advisor.ZapAdviceArray(resultSet.AdviceList)),)}}@@ -695,3 +709,105 @@ func validateSQLSelectStatement(sqlStatement string) bool {}return false}++func (s *Server) createSQLEditorQueryActivity(ctx context.Context, c echo.Context, level api.ActivityLevel, containerID int, payload api.ActivitySQLEditorQueryPayload) error {+ activityBytes, err := json.Marshal(payload)+ if err != nil {+ log.Warn("Failed to marshal activity after executing sql statement",+ zap.String("database_name", payload.DatabaseName),+ zap.String("instance_name", payload.InstanceName),+ zap.String("statement", payload.Statement),+ zap.Error(err))+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to construct activity payload").SetInternal(err)+ }++ activityCreate := &api.ActivityCreate{+ CreatorID: c.Get(getPrincipalIDContextKey()).(int),+ Type: api.ActivitySQLEditorQuery,+ ContainerID: containerID,+ Level: level,+ Comment: fmt.Sprintf("Executed `%q` in database %q of instance %q.",+ payload.Statement, payload.DatabaseName, payload.InstanceName),+ Payload: string(activityBytes),+ }++ if _, err = s.ActivityManager.CreateActivity(ctx, activityCreate, &ActivityMeta{}); err != nil {+ log.Warn("Failed to create activity after executing sql statement",+ zap.String("database_name", payload.DatabaseName),+ zap.String("instance_name", payload.InstanceName),+ zap.String("statement", payload.Statement),+ zap.Error(err))+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create activity").SetInternal(err)+ }+ return nil+}++func (s *Server) sqlCheck(ctx context.Context, instance *api.Instance, exec *api.SQLExecute) (advisor.Status, []advisor.Advice, error) {+ adviceLevel := advisor.Success+ var adviceList []advisor.Advice+ policy, err := s.store.GetNormalSchemaReviewPolicy(ctx, &api.PolicyFind{EnvironmentID: &instance.EnvironmentID})+ if err != nil {+ if e, ok := err.(*common.Error); ok && e.Code == common.NotFound {+ adviceLevel = advisor.Warn+ adviceList = append(adviceList, advisor.Advice{+ Status: advisor.Warn,+ Code: common.TaskCheckEmptySchemaReviewPolicy,+ Title: "Empty schema review policy or disabled",+ Content: "",+ })+ } else {+ return advisor.Error, nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch schema review policy by environment ID: %d", instance.EnvironmentID)).SetInternal(err)+ }+ }+ if adviceLevel == advisor.Success {+ databaseFind := &api.DatabaseFind{+ InstanceID: &instance.ID,+ Name: &exec.DatabaseName,+ }+ db, err := s.store.FindDatabase(ctx, databaseFind)+ if err != nil {+ return advisor.Error, nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch database `%s` for instance ID: %d", exec.DatabaseName, instance.ID)).SetInternal(err)+ }+ if len(db) == 0 {+ return advisor.Error, nil, echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Database `%s` for instance ID: %d not found", exec.DatabaseName, instance.ID))+ }+ if len(db) > 1 {+ return advisor.Error, nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("There are multiple database `%s` for instance ID: %d", exec.DatabaseName, instance.ID))+ }++ res, err := advisor.SchemaReviewCheck(ctx, exec.Statement, policy, advisor.SchemaReviewCheckContext{+ Charset: db[0].CharacterSet,+ Collation: db[0].Collation,+ DbType: instance.Engine,+ Catalog: store.NewCatalog(&db[0].ID, s.store),+ })+ if err != nil {+ return advisor.Error, nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to run schema review check").SetInternal(err)+ }++ for _, advice := range res {+ switch advice.Status {+ case advisor.Warn:+ if adviceLevel != advisor.Error {+ adviceLevel = advisor.Warn+ }+ case advisor.Error:+ adviceLevel = advisor.Error+ case advisor.Success:+ continue+ }++ adviceList = append(adviceList, advice)+ }++ if len(adviceList) == 0 {+ adviceList = append(adviceList, advisor.Advice{+ Status: advisor.Success,+ Code: common.Ok,+ Title: "OK",+ Content: "",+ })+ }+ }+ return adviceLevel, adviceList, nil+}diff --git a/server/task_check_executor_statement_advisor_composite.go b/server/task_check_executor_statement_advisor_composite.goindex aefb15f170..253e6a0fc7 100644--- a/server/task_check_executor_statement_advisor_composite.go+++ b/server/task_check_executor_statement_advisor_composite.go@@ -40,7 +40,7 @@ func (exec *TaskCheckStatementAdvisorCompositeExecutor) Run(ctx context.Context,return nil, common.Errorf(common.Invalid, fmt.Errorf("invalid check statement advise payload: %w", err))}- policy, err := server.store.GetSchemaReviewPolicyNormalByID(ctx, payload.PolicyID)+ policy, err := server.store.GetNormalSchemaReviewPolicy(ctx, &api.PolicyFind{ID: &payload.PolicyID})if err != nil {if e, ok := err.(*common.Error); ok && e.Code == common.NotFound {return []api.TaskCheckResult{diff --git a/store/policy.go b/store/policy.goindex 09abcd01b7..84ebbdd053 100644--- a/store/policy.go+++ b/store/policy.go@@ -177,6 +177,27 @@ func (s *Store) GetPipelineApprovalPolicy(ctx context.Context, environmentID intreturn api.UnmarshalPipelineApprovalPolicy(policy.Payload)}+// GetNormalSchemaReviewPolicy will get the normal schema review policy for an environment.+func (s *Store) GetNormalSchemaReviewPolicy(ctx context.Context, find *api.PolicyFind) (*advisor.SchemaReviewPolicy, error) {+ if find.ID != nil && *find.ID == api.DefaultPolicyID {+ return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("schema review policy not found with ID %d", *find.ID)}+ }++ pType := api.PolicyTypeSchemaReview+ find.Type = &pType+ policy, err := s.getPolicyRaw(ctx, find)+ if err != nil {+ return nil, err+ }+ if policy.RowStatus == api.Archived {+ return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("schema review policy ID: %d for environment %d is archived", policy.ID, policy.EnvironmentID)}+ }+ if policy.ID == api.DefaultPolicyID {+ return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("schema review policy ID: %d for environment %d not found", policy.ID, policy.EnvironmentID)}+ }+ return api.UnmarshalSchemaReviewPolicy(policy.Payload)+}+// GetSchemaReviewPolicyIDByEnvID will get the schema review policy ID for an environment.func (s *Store) GetSchemaReviewPolicyIDByEnvID(ctx context.Context, environmentID int) (int, error) {pType := api.PolicyTypeSchemaReview@@ -190,28 +211,6 @@ func (s *Store) GetSchemaReviewPolicyIDByEnvID(ctx context.Context, environmentIreturn policy.ID, nil}-// GetSchemaReviewPolicyNormalByID will get the schema review policy for an environment.-// If policy.ID is DefaultPolicyID or policy is archived, return the default empty policy.-func (s *Store) GetSchemaReviewPolicyNormalByID(ctx context.Context, id int) (*advisor.SchemaReviewPolicy, error) {- pType := api.PolicyTypeSchemaReview-- if id == api.DefaultPolicyID {- return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("schema review policy not found with ID %d", id)}- }-- policy, err := s.getPolicyRaw(ctx, &api.PolicyFind{- ID: &id,- Type: &pType,- })- if err != nil {- return nil, err- }- if policy.RowStatus == api.Archived {- return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("schema review policy with ID %d is archived", id)}- }- return api.UnmarshalSchemaReviewPolicy(policy.Payload)-}-//// private functions//@@ -263,10 +262,12 @@ func (s *Store) getPolicyRaw(ctx context.Context, find *api.PolicyFind) (*policyif len(policyRawList) == 0 {ret = &policyRaw{- CreatorID: api.SystemBotID,- UpdaterID: api.SystemBotID,- EnvironmentID: *find.EnvironmentID,- Type: *find.Type,+ CreatorID: api.SystemBotID,+ UpdaterID: api.SystemBotID,+ Type: *find.Type,+ }+ if find.EnvironmentID != nil {+ ret.EnvironmentID = *find.EnvironmentID}} else if len(policyRawList) > 1 {return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d policy with filter %+v, expect 1. ", len(policyRawList), find)}