Skip to content

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

chore: update rules to support force classification in the comment (#13881)

ecmadao83644882be8b
diff --git a/backend/api/v1/plan_service.go b/backend/api/v1/plan_service.go
index c45ecc3d64..8d84d32ced 100644
--- a/backend/api/v1/plan_service.go
+++ b/backend/api/v1/plan_service.go
@@ -25,7 +25,6 @@ import (
"github.com/bytebase/bytebase/backend/component/state"
enterprise "github.com/bytebase/bytebase/backend/enterprise/api"
api "github.com/bytebase/bytebase/backend/legacyapi"
- "github.com/bytebase/bytebase/backend/runner/plancheck"
"github.com/bytebase/bytebase/backend/store"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
v1pb "github.com/bytebase/bytebase/proto/generated-go/v1"
@@ -34,27 +33,25 @@ import (
// PlanService represents a service for managing plan.
type PlanService struct {
v1pb.UnimplementedPlanServiceServer
- store *store.Store
- sheetManager *sheet.Manager
- licenseService enterprise.LicenseService
- dbFactory *dbfactory.DBFactory
- planCheckScheduler *plancheck.Scheduler
- stateCfg *state.State
- profile *config.Profile
- iamManager *iam.Manager
+ store *store.Store
+ sheetManager *sheet.Manager
+ licenseService enterprise.LicenseService
+ dbFactory *dbfactory.DBFactory
+ stateCfg *state.State
+ profile *config.Profile
+ iamManager *iam.Manager
}
// NewPlanService returns a plan service instance.
-func NewPlanService(store *store.Store, sheetManager *sheet.Manager, licenseService enterprise.LicenseService, dbFactory *dbfactory.DBFactory, planCheckScheduler *plancheck.Scheduler, stateCfg *state.State, profile *config.Profile, iamManager *iam.Manager) *PlanService {
+func NewPlanService(store *store.Store, sheetManager *sheet.Manager, licenseService enterprise.LicenseService, dbFactory *dbfactory.DBFactory, stateCfg *state.State, profile *config.Profile, iamManager *iam.Manager) *PlanService {
return &PlanService{
- store: store,
- sheetManager: sheetManager,
- licenseService: licenseService,
- dbFactory: dbFactory,
- planCheckScheduler: planCheckScheduler,
- stateCfg: stateCfg,
- profile: profile,
- iamManager: iamManager,
+ store: store,
+ sheetManager: sheetManager,
+ licenseService: licenseService,
+ dbFactory: dbFactory,
+ stateCfg: stateCfg,
+ profile: profile,
+ iamManager: iamManager,
}
}
diff --git a/backend/api/v1/sql_service.go b/backend/api/v1/sql_service.go
index 7d1ba5fea0..90761ee309 100644
--- a/backend/api/v1/sql_service.go
+++ b/backend/api/v1/sql_service.go
@@ -1230,6 +1230,28 @@ func (s *SQLService) Check(ctx context.Context, request *v1pb.CheckRequest) (*v1
}, nil
}
+func GetClassificationByProject(ctx context.Context, stores *store.Store, projectID string) *storepb.DataClassificationSetting_DataClassificationConfig {
+ project, err := stores.GetProjectV2(ctx, &store.FindProjectMessage{
+ ResourceID: &projectID,
+ })
+ if err != nil {
+ slog.Warn("failed to find project", slog.String("project", projectID), log.BBError(err))
+ return nil
+ }
+ if project == nil {
+ return nil
+ }
+ if project.DataClassificationConfigID == "" {
+ return nil
+ }
+ classificationConfig, err := stores.GetDataClassificationConfigByID(ctx, project.DataClassificationConfigID)
+ if err != nil {
+ slog.Warn("failed to find classification", slog.String("project", projectID), slog.String("classification", project.DataClassificationConfigID), log.BBError(err))
+ return nil
+ }
+ return classificationConfig
+}
+
// SQLReviewCheck checks the SQL statement against the SQL review policy bind to given environment,
// against the database schema bind to the given database, if the overrideMetadata is provided,
// it will be used instead of fetching the database schema from the store.
@@ -1278,16 +1300,18 @@ func (s *SQLService) SQLReviewCheck(
defer driver.Close(ctx)
connection := driver.GetDB()
+ classificationConfig := GetClassificationByProject(ctx, s.store, database.ProjectID)
context := advisor.SQLReviewCheckContext{
- Charset: dbMetadata.CharacterSet,
- Collation: dbMetadata.Collation,
- ChangeType: convertChangeType(changeType),
- DBSchema: dbMetadata,
- DbType: instance.Engine,
- Catalog: catalog,
- Driver: connection,
- Context: ctx,
- CurrentDatabase: database.DatabaseName,
+ Charset: dbMetadata.CharacterSet,
+ Collation: dbMetadata.Collation,
+ ChangeType: convertChangeType(changeType),
+ DBSchema: dbMetadata,
+ DbType: instance.Engine,
+ Catalog: catalog,
+ Driver: connection,
+ Context: ctx,
+ CurrentDatabase: database.DatabaseName,
+ ClassificationConfig: classificationConfig,
}
reviewConfig, err := s.store.GetReviewConfigForDatabase(ctx, database)
diff --git a/backend/plugin/advisor/advisor.go b/backend/plugin/advisor/advisor.go
index 3b84e7e8b8..d11ee5c571 100644
--- a/backend/plugin/advisor/advisor.go
+++ b/backend/plugin/advisor/advisor.go
@@ -50,6 +50,7 @@ type Context struct {
SyntaxMode SyntaxMode
ChangeType storepb.PlanCheckRunConfig_ChangeDatabaseType
PreUpdateBackupDetail *storepb.PreUpdateBackupDetail
+ ClassificationConfig *storepb.DataClassificationSetting_DataClassificationConfig
// SQL review rule special fields.
AST any
diff --git a/backend/plugin/advisor/code.go b/backend/plugin/advisor/code.go
index c95b60b86a..a2dae9e7ea 100644
--- a/backend/plugin/advisor/code.go
+++ b/backend/plugin/advisor/code.go
@@ -90,8 +90,6 @@ const (
ColumnNotExists Code = 405
UseChangeColumnStatement Code = 406
ChangeColumnOrder Code = 407
- NoColumnComment Code = 408
- ColumnCommentTooLong Code = 409
AutoIncrementColumnNotInteger Code = 410
DisabledColumnType Code = 411
ColumnExists Code = 412
@@ -117,8 +115,6 @@ const (
TableHasFK Code = 602
TableDropNamingConventionMismatch Code = 603
TableNotExists Code = 604
- NoTableComment Code = 605
- TableCommentTooLong Code = 606
TableExists Code = 607
CreateTablePartition Code = 608
TableIsReferencedByView Code = 609
@@ -171,7 +167,9 @@ const (
DisabledCollation Code = 1201
// 1301 ~ 1399 comment error code.
- CommentTooLong Code = 1301
+ CommentTooLong Code = 1301
+ CommentEmpty Code = 1032
+ CommentMissingClassification Code = 1303
// 1401 ~ 1499 procedure error code.
DisallowCreateProcedure Code = 1401
diff --git a/backend/plugin/advisor/mysql/advisor_column_comment_convention.go b/backend/plugin/advisor/mysql/advisor_column_comment_convention.go
index c7397df4f6..eda5f27cdb 100644
--- a/backend/plugin/advisor/mysql/advisor_column_comment_convention.go
+++ b/backend/plugin/advisor/mysql/advisor_column_comment_convention.go
@@ -10,6 +10,7 @@ import (
mysql "github.com/bytebase/mysql-parser"
+ "github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/plugin/advisor"
mysqlparser "github.com/bytebase/bytebase/backend/plugin/parser/mysql"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
@@ -45,10 +46,10 @@ func (*ColumnCommentConventionAdvisor) Check(ctx advisor.Context, _ string) ([]*
return nil, err
}
checker := &columnCommentConventionChecker{
- level: level,
- title: string(ctx.Rule.Type),
- required: payload.Required,
- maxLength: payload.MaxLength,
+ level: level,
+ title: string(ctx.Rule.Type),
+ payload: payload,
+ classificationConfig: ctx.ClassificationConfig,
}
for _, stmt := range stmtList {
@@ -62,12 +63,12 @@ func (*ColumnCommentConventionAdvisor) Check(ctx advisor.Context, _ string) ([]*
type columnCommentConventionChecker struct {
*mysql.BaseMySQLParserListener
- baseLine int
- adviceList []*storepb.Advice
- level storepb.Advice_Status
- title string
- required bool
- maxLength int
+ baseLine int
+ adviceList []*storepb.Advice
+ level storepb.Advice_Status
+ title string
+ payload *advisor.CommentConventionRulePayload
+ classificationConfig *storepb.DataClassificationSetting_DataClassificationConfig
}
func (checker *columnCommentConventionChecker) EnterCreateTable(ctx *mysql.CreateTableContext) {
@@ -161,29 +162,44 @@ func (checker *columnCommentConventionChecker) checkFieldDefinition(tableName, c
continue
}
comment = mysqlparser.NormalizeMySQLTextLiteral(attribute.TextLiteral())
- if checker.maxLength >= 0 && len(comment) > checker.maxLength {
+ if checker.payload.MaxLength >= 0 && len(comment) > checker.payload.MaxLength {
checker.adviceList = append(checker.adviceList, &storepb.Advice{
Status: checker.level,
- Code: advisor.ColumnCommentTooLong.Int32(),
+ Code: advisor.CommentTooLong.Int32(),
Title: checker.title,
- Content: fmt.Sprintf("The length of column `%s`.`%s` comment should be within %d characters", tableName, columnName, checker.maxLength),
+ Content: fmt.Sprintf("The length of column `%s`.`%s` comment should be within %d characters", tableName, columnName, checker.payload.MaxLength),
StartPosition: &storepb.Position{
Line: int32(checker.baseLine + ctx.GetStart().GetLine()),
},
})
}
- }
- if len(comment) == 0 {
- if checker.required {
- checker.adviceList = append(checker.adviceList, &storepb.Advice{
- Status: checker.level,
- Code: advisor.NoColumnComment.Int32(),
- Title: checker.title,
- Content: fmt.Sprintf("Column `%s`.`%s` requires comments", tableName, columnName),
- StartPosition: &storepb.Position{
- Line: int32(checker.baseLine + ctx.GetStart().GetLine()),
- },
- })
+
+ if checker.payload.RequiredClassification {
+ if classification, _ := common.GetClassificationAndUserComment(comment, checker.classificationConfig); classification == "" {
+ checker.adviceList = append(checker.adviceList, &storepb.Advice{
+ Status: checker.level,
+ Code: advisor.CommentMissingClassification.Int32(),
+ Title: checker.title,
+ Content: fmt.Sprintf("Column `%s`.`%s` comment requires classification", tableName, columnName),
+ StartPosition: &storepb.Position{
+ Line: int32(checker.baseLine + ctx.GetStart().GetLine()),
+ },
+ })
+ }
}
+
+ break
+ }
+
+ if len(comment) == 0 && checker.payload.Required {
+ checker.adviceList = append(checker.adviceList, &storepb.Advice{
+ Status: checker.level,
+ Code: advisor.CommentEmpty.Int32(),
+ Title: checker.title,
+ Content: fmt.Sprintf("Column `%s`.`%s` requires comments", tableName, columnName),
+ StartPosition: &storepb.Position{
+ Line: int32(checker.baseLine + ctx.GetStart().GetLine()),
+ },
+ })
}
}
diff --git a/backend/plugin/advisor/mysql/advisor_table_comment_convention.go b/backend/plugin/advisor/mysql/advisor_table_comment_convention.go
index 2e40507483..4c5adcc84b 100644
--- a/backend/plugin/advisor/mysql/advisor_table_comment_convention.go
+++ b/backend/plugin/advisor/mysql/advisor_table_comment_convention.go
@@ -7,6 +7,7 @@ import (
mysql "github.com/bytebase/mysql-parser"
"github.com/pkg/errors"
+ "github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/plugin/advisor"
mysqlparser "github.com/bytebase/bytebase/backend/plugin/parser/mysql"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
@@ -43,10 +44,10 @@ func (*TableCommentConventionAdvisor) Check(ctx advisor.Context, _ string) ([]*s
}
checker := &tableCommentConventionChecker{
- level: level,
- title: string(ctx.Rule.Type),
- required: payload.Required,
- maxLength: payload.MaxLength,
+ level: level,
+ title: string(ctx.Rule.Type),
+ payload: payload,
+ classificationConfig: ctx.ClassificationConfig,
}
for _, stmt := range list {
@@ -60,12 +61,12 @@ func (*TableCommentConventionAdvisor) Check(ctx advisor.Context, _ string) ([]*s
type tableCommentConventionChecker struct {
*mysql.BaseMySQLParserListener
- baseLine int
- adviceList []*storepb.Advice
- level storepb.Advice_Status
- title string
- required bool
- maxLength int
+ baseLine int
+ adviceList []*storepb.Advice
+ level storepb.Advice_Status
+ title string
+ payload *advisor.CommentConventionRulePayload
+ classificationConfig *storepb.DataClassificationSetting_DataClassificationConfig
}
// EnterCreateTable is called when production createTable is entered.
@@ -81,10 +82,10 @@ func (checker *tableCommentConventionChecker) EnterCreateTable(ctx *mysql.Create
comment, exists := checker.handleCreateTableOptions(ctx.CreateTableOptions())
- if checker.required && !exists {
+ if checker.payload.Required && !exists {
checker.adviceList = append(checker.adviceList, &storepb.Advice{
Status: checker.level,
- Code: advisor.NoTableComment.Int32(),
+ Code: advisor.CommentEmpty.Int32(),
Title: checker.title,
Content: fmt.Sprintf("Table `%s` requires comments", tableName),
StartPosition: &storepb.Position{
@@ -92,17 +93,30 @@ func (checker *tableCommentConventionChecker) EnterCreateTable(ctx *mysql.Create
},
})
}
- if checker.maxLength >= 0 && len(comment) > checker.maxLength {
+ if checker.payload.MaxLength >= 0 && len(comment) > checker.payload.MaxLength {
checker.adviceList = append(checker.adviceList, &storepb.Advice{
Status: checker.level,
- Code: advisor.TableCommentTooLong.Int32(),
+ Code: advisor.CommentTooLong.Int32(),
Title: checker.title,
- Content: fmt.Sprintf("The length of table `%s` comment should be within %d characters", tableName, checker.maxLength),
+ Content: fmt.Sprintf("The length of table `%s` comment should be within %d characters", tableName, checker.payload.MaxLength),
StartPosition: &storepb.Position{
Line: int32(checker.baseLine + ctx.GetStart().GetLine()),
},
})
}
+ if checker.payload.RequiredClassification {
+ if classification, _ := common.GetClassificationAndUserComment(comment, checker.classificationConfig); classification == "" {
+ checker.adviceList = append(checker.adviceList, &storepb.Advice{
+ Status: checker.level,
+ Code: advisor.CommentMissingClassification.Int32(),
+ Title: checker.title,
+ Content: fmt.Sprintf("Tolumn `%s` comment requires classification", tableName),
+ StartPosition: &storepb.Position{
+ Line: int32(checker.baseLine + ctx.GetStart().GetLine()),
+ },
+ })
+ }
+ }
}
func (*tableCommentConventionChecker) handleCreateTableOptions(ctx mysql.ICreateTableOptionsContext) (string, bool) {
diff --git a/backend/plugin/advisor/mysql/test/column_comment.yaml b/backend/plugin/advisor/mysql/test/column_comment.yaml
index 8c98341177..acc7ea83a5 100644
--- a/backend/plugin/advisor/mysql/test/column_comment.yaml
+++ b/backend/plugin/advisor/mysql/test/column_comment.yaml
@@ -14,7 +14,7 @@
changeType: 0
want:
- status: 2
- code: 408
+ code: 1032
title: column.comment
content: Column `userTable`.`id` requires comments
detail: ""
@@ -23,7 +23,7 @@
column: 0
endposition: null
- status: 2
- code: 408
+ code: 1032
title: column.comment
content: Column `userTable`.`name` requires comments
detail: ""
@@ -32,7 +32,7 @@
column: 0
endposition: null
- status: 2
- code: 408
+ code: 1032
title: column.comment
content: Column `userTable`.`roomId` requires comments
detail: ""
@@ -64,7 +64,7 @@
changeType: 0
want:
- status: 2
- code: 409
+ code: 1301
title: column.comment
content: The length of column `t`.`a` comment should be within 10 characters
detail: ""
@@ -73,7 +73,7 @@
column: 0
endposition: null
- status: 2
- code: 408
+ code: 1032
title: column.comment
content: Column `t`.`b` requires comments
detail: ""
@@ -82,7 +82,7 @@
column: 0
endposition: null
- status: 2
- code: 408
+ code: 1032
title: column.comment
content: Column `t`.`c` requires comments
detail: ""
@@ -96,7 +96,7 @@
changeType: 0
want:
- status: 2
- code: 408
+ code: 1032
title: column.comment
content: Column `t`.`b` requires comments
detail: ""
@@ -110,7 +110,7 @@
changeType: 0
want:
- status: 2
- code: 408
+ code: 1032
title: column.comment
content: Column `t`.`b` requires comments
detail: ""
@@ -119,7 +119,7 @@
column: 0
endposition: null
- status: 2
- code: 408
+ code: 1032
title: column.comment
content: Column `t`.`c` requires comments
detail: ""
@@ -133,7 +133,7 @@
changeType: 0
want:
- status: 2
- code: 409
+ code: 1301
title: column.comment
content: The length of column `t`.`a` comment should be within 10 characters
detail: ""
@@ -142,7 +142,7 @@
column: 0
endposition: null
- status: 2
- code: 408
+ code: 1032
title: column.comment
content: Column `t`.`b` requires comments
detail: ""
@@ -156,7 +156,7 @@
changeType: 0
want:
- status: 2
- code: 409
+ code: 1301
title: column.comment
content: The length of column `t`.`b` comment should be within 10 characters
detail: ""
@@ -165,7 +165,7 @@
column: 0
endposition: null
- status: 2
- code: 408
+ code: 1032
title: column.comment
content: Column `t`.`b` requires comments
detail: ""
@@ -179,7 +179,7 @@
changeType: 0
want:
- status: 2
- code: 409
+ code: 1301
title: column.comment
content: The length of column `t`.`b` comment should be within 10 characters
detail: ""
@@ -188,7 +188,7 @@
column: 0
endposition: null
- status: 2
- code: 409
+ code: 1301
title: column.comment
content: The length of column `t`.`b` comment should be within 10 characters
detail: ""
diff --git a/backend/plugin/advisor/mysql/test/table_comment.yaml b/backend/plugin/advisor/mysql/test/table_comment.yaml
index e7b5e603f1..cad625a9d4 100644
--- a/backend/plugin/advisor/mysql/test/table_comment.yaml
+++ b/backend/plugin/advisor/mysql/test/table_comment.yaml
@@ -4,7 +4,7 @@
changeType: 0
want:
- status: 2
- code: 606
+ code: 1301
title: table.comment
content: The length of table `t` comment should be within 10 characters
detail: ""
@@ -18,7 +18,7 @@
changeType: 0
want:
- status: 2
- code: 605
+ code: 1032
title: table.comment
content: Table `t` requires comments
detail: ""
@@ -32,7 +32,7 @@
changeType: 0
want:
- status: 2
- code: 606
+ code: 1301
title: table.comment
content: The length of table `t` comment should be within 10 characters
detail: ""
diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.go
index 2f982ba2a5..80d226c3a2 100644
--- a/backend/plugin/advisor/sql_review.go
+++ b/backend/plugin/advisor/sql_review.go
@@ -303,8 +303,9 @@ type RequiredColumnRulePayload struct {
// CommentConventionRulePayload is the payload for comment convention rule.
type CommentConventionRulePayload struct {
- Required bool `json:"required"`
- MaxLength int `json:"maxLength"`
+ Required bool `json:"required"`
+ RequiredClassification bool `json:"requiredClassification"`
+ MaxLength int `json:"maxLength"`
}
// NumberTypeRulePayload is the number type payload.
@@ -485,6 +486,7 @@ type SQLReviewCheckContext struct {
Driver *sql.DB
Context context.Context
PreUpdateBackupDetail *storepb.PreUpdateBackupDetail
+ ClassificationConfig *storepb.DataClassificationSetting_DataClassificationConfig
// Snowflake specific fields
CurrentDatabase string
@@ -556,6 +558,7 @@ func SQLReviewCheck(
Driver: checkContext.Driver,
Context: checkContext.Context,
CurrentDatabase: checkContext.CurrentDatabase,
+ ClassificationConfig: checkContext.ClassificationConfig,
},
statements,
)
diff --git a/backend/plugin/advisor/tidb/advisor_column_comment_convention.go b/backend/plugin/advisor/tidb/advisor_column_comment_convention.go
index 53e462f6dd..6413b14e14 100644
--- a/backend/plugin/advisor/tidb/advisor_column_comment_convention.go
+++ b/backend/plugin/advisor/tidb/advisor_column_comment_convention.go
@@ -9,6 +9,7 @@ import (
"github.com/pingcap/tidb/pkg/parser/format"
"github.com/pkg/errors"
+ "github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/plugin/advisor"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
)
@@ -42,10 +43,10 @@ func (*ColumnCommentConventionAdvisor) Check(ctx advisor.Context, _ string) ([]*
return nil, err
}
checker := &columnCommentConventionChecker{
- level: level,
- title: string(ctx.Rule.Type),
- required: payload.Required,
- maxLength: payload.MaxLength,
+ level: level,
+ title: string(ctx.Rule.Type),
+ payload: payload,
+ classificationConfig: ctx.ClassificationConfig,
}
for _, stmt := range stmtList {
@@ -58,13 +59,13 @@ func (*ColumnCommentConventionAdvisor) Check(ctx advisor.Context, _ string) ([]*
}
type columnCommentConventionChecker struct {
- adviceList []*storepb.Advice
- level storepb.Advice_Status
- title string
- text string
- line int
- required bool
- maxLength int
+ adviceList []*storepb.Advice
+ level storepb.Advice_Status
+ title string
+ text string
+ line int
+ payload *advisor.CommentConventionRulePayload
+ classificationConfig *storepb.DataClassificationSetting_DataClassificationConfig
}
type columnCommentData struct {
@@ -119,10 +120,10 @@ func (checker *columnCommentConventionChecker) Enter(in ast.Node) (ast.Node, boo
}
for _, column := range columnList {
- if checker.required && !column.exist {
+ if checker.payload.Required && !column.exist {
checker.adviceList = append(checker.adviceList, &storepb.Advice{
Status: checker.level,
- Code: advisor.NoColumnComment.Int32(),
+ Code: advisor.CommentEmpty.Int32(),
Title: checker.title,
Content: fmt.Sprintf("Column `%s`.`%s` requires comments", column.table, column.column),
StartPosition: &storepb.Position{
@@ -130,17 +131,30 @@ func (checker *columnCommentConventionChecker) Enter(in ast.Node) (ast.Node, boo
},
})
}
- if checker.maxLength >= 0 && len(column.comment) > checker.maxLength {
+ if checker.payload.MaxLength >= 0 && len(column.comment) > checker.payload.MaxLength {
checker.adviceList = append(checker.adviceList, &storepb.Advice{
Status: checker.level,
- Code: advisor.ColumnCommentTooLong.Int32(),
+ Code: advisor.CommentTooLong.Int32(),
Title: checker.title,
- Content: fmt.Sprintf("The length of column `%s`.`%s` comment should be within %d characters", column.table, column.column, checker.maxLength),
+ Content: fmt.Sprintf("The length of column `%s`.`%s` comment should be within %d characters", column.table, column.column, checker.payload.MaxLength),
StartPosition: &storepb.Position{
Line: int32(column.line),
},
})
}
+ if checker.payload.RequiredClassification {
+ if classification, _ := common.GetClassificationAndUserComment(column.comment, checker.classificationConfig); classification == "" {
+ checker.adviceList = append(checker.adviceList, &storepb.Advice{
+ Status: checker.level,
+ Code: advisor.CommentMissingClassification.Int32(),
+ Title: checker.title,
+ Content: fmt.Sprintf("Column `%s`.`%s` comment requires classification", column.table, column.column),
+ StartPosition: &storepb.Position{
+ Line: int32(column.line),
+ },
+ })
+ }
+ }
}
return in, false
diff --git a/backend/plugin/advisor/tidb/advisor_table_comment_convention.go b/backend/plugin/advisor/tidb/advisor_table_comment_convention.go
index c725c3be15..c3c09f1b9b 100644
--- a/backend/plugin/advisor/tidb/advisor_table_comment_convention.go
+++ b/backend/plugin/advisor/tidb/advisor_table_comment_convention.go
@@ -8,6 +8,7 @@ import (
"github.com/pingcap/tidb/pkg/parser/ast"
"github.com/pkg/errors"
+ "github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/plugin/advisor"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
)
@@ -41,10 +42,10 @@ func (*TableCommentConventionAdvisor) Check(ctx advisor.Context, _ string) ([]*s
return nil, err
}
checker := &tableCommentConventionChecker{
- level: level,
- title: string(ctx.Rule.Type),
- required: payload.Required,
- maxLength: payload.MaxLength,
+ level: level,
+ title: string(ctx.Rule.Type),
+ payload: payload,
+ classificationConfig: ctx.ClassificationConfig,
}
for _, stmt := range stmtList {
@@ -57,23 +58,23 @@ func (*TableCommentConventionAdvisor) Check(ctx advisor.Context, _ string) ([]*s
}
type tableCommentConventionChecker struct {
- adviceList []*storepb.Advice
- level storepb.Advice_Status
- title string
- text string
- line int
- required bool
- maxLength int
+ adviceList []*storepb.Advice
+ level storepb.Advice_Status
+ title string
+ text string
+ line int
+ payload *advisor.CommentConventionRulePayload
+ classificationConfig *storepb.DataClassificationSetting_DataClassificationConfig
}
// Enter implements the ast.Visitor interface.
func (checker *tableCommentConventionChecker) Enter(in ast.Node) (ast.Node, bool) {
if node, ok := in.(*ast.CreateTableStmt); ok {
exist, comment := tableComment(node.Options)
- if checker.required && !exist {
+ if checker.payload.Required && !exist {
checker.adviceList = append(checker.adviceList, &storepb.Advice{
Status: checker.level,
- Code: advisor.NoTableComment.Int32(),
+ Code: advisor.CommentEmpty.Int32(),
Title: checker.title,
Content: fmt.Sprintf("Table `%s` requires comments", node.Table.Name.O),
StartPosition: &storepb.Position{
@@ -81,17 +82,30 @@ func (checker *tableCommentConventionChecker) Enter(in ast.Node) (ast.Node, bool
},
})
}
- if checker.maxLength >= 0 && len(comment) > checker.maxLength {
+ if checker.payload.MaxLength >= 0 && len(comment) > checker.payload.MaxLength {
checker.adviceList = append(checker.adviceList, &storepb.Advice{
Status: checker.level,
- Code: advisor.TableCommentTooLong.Int32(),
+ Code: advisor.CommentTooLong.Int32(),
Title: checker.title,
- Content: fmt.Sprintf("The length of table `%s` comment should be within %d characters", node.Table.Name.O, checker.maxLength),
+ Content: fmt.Sprintf("The length of table `%s` comment should be within %d characters", node.Table.Name.O, checker.payload.MaxLength),
StartPosition: &storepb.Position{
Line: int32(checker.line),
},
})
}
+ if checker.payload.RequiredClassification {
+ if classification, _ := common.GetClassificationAndUserComment(comment, checker.classificationConfig); classification == "" {
+ checker.adviceList = append(checker.adviceList, &storepb.Advice{
+ Status: checker.level,
+ Code: advisor.CommentMissingClassification.Int32(),
+ Title: checker.title,
+ Content: fmt.Sprintf("Tolumn `%s` comment requires classification", node.Table.Name.O),
+ StartPosition: &storepb.Position{
+ Line: int32(checker.line),
+ },
+ })
+ }
+ }
}
return in, false
diff --git a/backend/plugin/advisor/tidb/test/column_comment.yaml b/backend/plugin/advisor/tidb/test/column_comment.yaml
index ceb12ac0fe..2eb618deff 100644
--- a/backend/plugin/advisor/tidb/test/column_comment.yaml
+++ b/backend/plugin/advisor/tidb/test/column_comment.yaml
@@ -8,7 +8,7 @@
changeType: 0
want:
- status: 2
- code: 409
+ code: 1301
title: column.comment
content: The length of column `t`.`a` comment should be within 10 characters
detail: ""
@@ -17,7 +17,7 @@
column: 0
endposition: null
- status: 2
- code: 408
+ code: 1032
title: column.comment
content: Column `t`.`b` requires comments
detail: ""
@@ -26,7 +26,7 @@
column: 0
endposition: null
- status: 2
- code: 408
+ code: 1032
title: column.comment
content: Column `t`.`c` requires comments
detail: ""
@@ -40,7 +40,7 @@
changeType: 0
want:
- status: 2
- code: 408
+ code: 1032
title: column.comment
content: Column `t`.`b` requires comments
detail: ""
@@ -54,7 +54,7 @@
changeType: 0
want:
- status: 2
- code: 409
+ code: 1301
title: column.comment
content: The length of column `t`.`a` comment should be within 10 characters
detail: ""
@@ -63,7 +63,7 @@
column: 0
endposition: null
- status: 2
- code: 408
+ code: 1032
title: column.comment
content: Column `t`.`b` requires comments
detail: ""
@@ -77,7 +77,7 @@
changeType: 0
want:
- status: 2
- code: 409
+ code: 1301
title: column.comment
content: The length of column `t`.`b` comment should be within 10 characters
detail: ""
@@ -86,7 +86,7 @@
column: 0
endposition: null
- status: 2
- code: 408
+ code: 1032
title: column.comment
content: Column `t`.`b` requires comments
detail: ""
@@ -100,7 +100,7 @@
changeType: 0
want:
- status: 2
- code: 409
+ code: 1301
title: column.comment
content: The length of column `t`.`b` comment should be within 10 characters
detail: ""
@@ -109,7 +109,7 @@
column: 0
endposition: null
- status: 2
- code: 409
+ code: 1301
title: column.comment
content: The length of column `t`.`b` comment should be within 10 characters
detail: ""
diff --git a/backend/plugin/advisor/tidb/test/table_comment.yaml b/backend/plugin/advisor/tidb/test/table_comment.yaml
index 2af50e685a..431ae460a9 100644
--- a/backend/plugin/advisor/tidb/test/table_comment.yaml
+++ b/backend/plugin/advisor/tidb/test/table_comment.yaml
@@ -2,7 +2,7 @@
changeType: 0
want:
- status: 2
- code: 606
+ code: 1301
title: table.comment
content: The length of table `t` comment should be within 10 characters
detail: ""
@@ -14,7 +14,7 @@
changeType: 0
want:
- status: 2
- code: 605
+ code: 1032
title: table.comment
content: Table `t` requires comments
detail: ""
@@ -26,7 +26,7 @@
changeType: 0
want:
- status: 2
- code: 606
+ code: 1301
title: table.comment
content: The length of table `t` comment should be within 10 characters
detail: ""
diff --git a/backend/runner/plancheck/statement_advise_executor.go b/backend/runner/plancheck/statement_advise_executor.go
index 49eeeeb7a6..b128b1a865 100644
--- a/backend/runner/plancheck/statement_advise_executor.go
+++ b/backend/runner/plancheck/statement_advise_executor.go
@@ -9,6 +9,8 @@ import (
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/component/dbfactory"
"github.com/bytebase/bytebase/backend/component/sheet"
+
+ v1api "github.com/bytebase/bytebase/backend/api/v1"
enterprise "github.com/bytebase/bytebase/backend/enterprise/api"
api "github.com/bytebase/bytebase/backend/legacyapi"
"github.com/bytebase/bytebase/backend/plugin/advisor"
@@ -181,6 +183,8 @@ func (e *StatementAdviseExecutor) runReview(
materials := utils.GetSecretMapFromDatabaseMessage(database)
// To avoid leaking the rendered statement, the error message should use the original statement and not the rendered statement.
renderedStatement := utils.RenderStatement(statement, materials)
+ classificationConfig := v1api.GetClassificationByProject(ctx, e.store, database.ProjectID)
+
adviceList, err := advisor.SQLReviewCheck(e.sheetManager, renderedStatement, reviewConfig.SqlReviewRules, advisor.SQLReviewCheckContext{
Charset: dbSchema.GetMetadata().CharacterSet,
Collation: dbSchema.GetMetadata().Collation,
@@ -191,6 +195,7 @@ func (e *StatementAdviseExecutor) runReview(
Driver: connection,
Context: ctx,
PreUpdateBackupDetail: preUpdateBackupDetail,
+ ClassificationConfig: classificationConfig,
})
if err != nil {
return nil, err
diff --git a/backend/server/grpc_routes.go b/backend/server/grpc_routes.go
index 590bdf9e67..0015b355d7 100644
--- a/backend/server/grpc_routes.go
+++ b/backend/server/grpc_routes.go
@@ -18,7 +18,6 @@ import (
"github.com/bytebase/bytebase/backend/component/webhook"
enterprise "github.com/bytebase/bytebase/backend/enterprise/api"
"github.com/bytebase/bytebase/backend/runner/metricreport"
- "github.com/bytebase/bytebase/backend/runner/plancheck"
"github.com/bytebase/bytebase/backend/runner/relay"
"github.com/bytebase/bytebase/backend/runner/schemasync"
"github.com/bytebase/bytebase/backend/store"
@@ -40,7 +39,6 @@ func configureGrpcRouters(
webhookManager *webhook.Manager,
iamManager *iam.Manager,
relayRunner *relay.Runner,
- planCheckScheduler *plancheck.Scheduler,
postCreateUser apiv1.CreateUserFunc,
secret string) (*apiv1.PlanService, *apiv1.RolloutService, *apiv1.IssueService, *apiv1.SQLService, error) {
// Register services.
@@ -80,7 +78,7 @@ func configureGrpcRouters(
v1pb.RegisterRiskServiceServer(grpcServer, apiv1.NewRiskService(stores, licenseService))
releaseService := apiv1.NewReleaseService(stores)
v1pb.RegisterReleaseServiceServer(grpcServer, releaseService)
- planService := apiv1.NewPlanService(stores, sheetManager, licenseService, dbFactory, planCheckScheduler, stateCfg, profile, iamManager)
+ planService := apiv1.NewPlanService(stores, sheetManager, licenseService, dbFactory, stateCfg, profile, iamManager)
v1pb.RegisterPlanServiceServer(grpcServer, planService)
issueService := apiv1.NewIssueService(stores, webhookManager, relayRunner, stateCfg, licenseService, profile, iamManager, metricReporter)
v1pb.RegisterIssueServiceServer(grpcServer, issueService)
diff --git a/backend/server/server.go b/backend/server/server.go
index d064637b69..b0361851c5 100644
--- a/backend/server/server.go
+++ b/backend/server/server.go
@@ -346,7 +346,7 @@ func NewServer(ctx context.Context, profile *config.Profile) (*Server, error) {
}
return nil
}
- planService, rolloutService, issueService, sqlService, err := configureGrpcRouters(ctx, mux, s.grpcServer, s.store, s.sheetManager, s.dbFactory, s.licenseService, s.profile, s.metricReporter, s.stateCfg, s.schemaSyncer, s.webhookManager, s.iamManager, s.relayRunner, s.planCheckScheduler, postCreateUser, s.secret)
+ planService, rolloutService, issueService, sqlService, err := configureGrpcRouters(ctx, mux, s.grpcServer, s.store, s.sheetManager, s.dbFactory, s.licenseService, s.profile, s.metricReporter, s.stateCfg, s.schemaSyncer, s.webhookManager, s.iamManager, s.relayRunner, postCreateUser, s.secret)
if err != nil {
return nil, err
}
diff --git a/backend/tests/test-data/sql_review_mysql.yaml b/backend/tests/test-data/sql_review_mysql.yaml
index 430bc92297..18a719cd61 100644
--- a/backend/tests/test-data/sql_review_mysql.yaml
+++ b/backend/tests/test-data/sql_review_mysql.yaml
@@ -150,7 +150,7 @@
"content": "Table `userTable` requires comments",
"sqlReviewReport": {
"line": 1,
- "code": 605,
+ "code": 1032,
"startPosition": {
"line": 1
}
@@ -215,7 +215,7 @@
"content": "Column `userTable`.`id` requires comments",
"sqlReviewReport": {
"line": 1,
- "code": 408,
+ "code": 1032,
"startPosition": {
"line": 1
}
@@ -228,7 +228,7 @@
"content": "Column `userTable`.`name` requires comments",
"sqlReviewReport": {
"line": 1,
- "code": 408,
+ "code": 1032,
"startPosition": {
"line": 1
}
@@ -241,7 +241,7 @@
"content": "Column `userTable`.`roomId` requires comments",
"sqlReviewReport": {
"line": 1,
- "code": 408,
+ "code": 1032,
"startPosition": {
"line": 1
}
diff --git a/frontend/src/components/SQLReview/components/RuleConfigComponents/BooleanComponent.vue b/frontend/src/components/SQLReview/components/RuleConfigComponents/BooleanComponent.vue
index 904d57ab25..0037651ec1 100644
--- a/frontend/src/components/SQLReview/components/RuleConfigComponents/BooleanComponent.vue
+++ b/frontend/src/components/SQLReview/components/RuleConfigComponents/BooleanComponent.vue
@@ -1,18 +1,31 @@
<template>
<NCheckbox
- :label="title"
:checked="value"
:disabled="disabled"
@update:checked="$emit('update:value', $event)"
- />
+ >
+ <div class="flex items-center space-x-1">
+ <p class="font-medium">
+ {{ title }}
+ </p>
+ <NTooltip v-if="tooltip">
+ <template #trigger>
+ <CircleHelpIcon class="w-4" />
+ </template>
+ <span>{{ tooltip }}</span>
+ </NTooltip>
+ </div>
+ </NCheckbox>
</template>
<script lang="ts" setup>
-import { NCheckbox } from "naive-ui";
+import { CircleHelpIcon } from "lucide-vue-next";
+import { NCheckbox, NTooltip } from "naive-ui";
import type { RuleConfigComponent } from "@/types";
defineProps<{
title: string;
+ tooltip?: string;
config: RuleConfigComponent;
value: boolean;
disabled: boolean;
diff --git a/frontend/src/components/SQLReview/components/RuleConfigComponents/RuleConfig.vue b/frontend/src/components/SQLReview/components/RuleConfigComponents/RuleConfig.vue
index 60d1a08911..11b75dd83e 100644
--- a/frontend/src/components/SQLReview/components/RuleConfigComponents/RuleConfig.vue
+++ b/frontend/src/components/SQLReview/components/RuleConfigComponents/RuleConfig.vue
@@ -5,14 +5,25 @@
:key="index"
class="space-y-1"
>
- <p
- :class="[
- 'font-medium',
- size !== 'small' && 'text-lg text-control mb-2',
- ]"
+ <div
+ v-if="config.payload.type !== 'BOOLEAN'"
+ class="flex items-center space-x-1"
>
- {{ configTitle(config) }}
- </p>
+ <p
+ :class="[
+ 'font-medium',
+ size !== 'small' && 'text-lg text-control mb-2',
+ ]"
+ >
+ {{ configTitle(config) }}
+ </p>
+ <NTooltip v-if="configTooltip(config)">
+ <template #trigger>
+ <CircleHelpIcon class="w-4" />
+ </template>
+ <span>{{ configTooltip(config) }}</span>
+ </NTooltip>
+ </div>
<StringComponent
v-if="config.payload.type === 'STRING'"
:value="payload[index] as string"
@@ -28,8 +39,9 @@
@update:value="payload[index] = $event"
/>
<BooleanComponent
- v-else-if="config.payload.type == 'BOOLEAN'"
+ v-else-if="config.payload.type === 'BOOLEAN'"
:title="configTitle(config)"
+ :tooltip="configTooltip(config)"
:value="payload[index] as boolean"
:config="config"
:disabled="disabled"
@@ -37,7 +49,8 @@
/>
<StringArrayComponent
v-else-if="
- config.payload.type == 'STRING_ARRAY' && Array.isArray(payload[index])
+ config.payload.type === 'STRING_ARRAY' &&
+ Array.isArray(payload[index])
"
:value="payload[index] as string[]"
:config="config"
@@ -45,7 +58,7 @@
@update:value="payload[index] = $event"
/>
<TemplateComponent
- v-else-if="config.payload.type == 'TEMPLATE'"
+ v-else-if="config.payload.type === 'TEMPLATE'"
:rule-type="rule.type"
:value="payload[index] as string"
:config="config"
@@ -57,6 +70,8 @@
</template>
<script setup lang="ts">
+import { CircleHelpIcon } from "lucide-vue-next";
+import { NTooltip } from "naive-ui";
import { ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import type { RuleConfigComponent, RuleTemplateV2 } from "@/types/sqlReview";
@@ -75,7 +90,7 @@ const props = defineProps<{
size: "small" | "medium";
}>();
-const { t } = useI18n();
+const { t, te } = useI18n();
const payload = ref<PayloadValueType[]>([]);
const configTitle = (config: RuleConfigComponent): string => {
@@ -85,6 +100,13 @@ const configTitle = (config: RuleConfigComponent): string => {
return t(key);
};
+const configTooltip = (config: RuleConfigComponent): string => {
+ const key = `sql-review.rule.${getRuleLocalizationKey(
+ props.rule.type
+ )}.component.${config.key}.tooltip`;
+ return te(key) ? t(key) : "";
+};
+
watch(
() => props.rule.componentList,
() => (payload.value = getRulePayload(props.rule)),
diff --git a/frontend/src/locales/sql-review/en-US.json b/frontend/src/locales/sql-review/en-US.json
index 037f270ea6..1abfaea0cb 100644
--- a/frontend/src/locales/sql-review/en-US.json
+++ b/frontend/src/locales/sql-review/en-US.json
@@ -82,12 +82,16 @@
"description": "It is recommended to set the charset at the database level. Setting the charset at finer granularity can bring unnecessary complexities. Suggested error level: Error."
},
"table-comment": {
- "title": "Comment convention",
+ "title": "Table comment convention",
"description": "Configure whether the table requires comments and the maximum comment length.",
"component": {
"required": {
"title": "Require comment"
},
+ "requiredClassification": {
+ "title": "Require classification",
+ "tooltip": "The comment should follow {'{'}classification id{'}'}-{'{'}comment{'}'} format."
+ },
"maxLength": {
"title": "Max length"
}
@@ -302,12 +306,16 @@
"description": "Unsigned types do not store negative numbers, and the range of values that can be stored by the same type is doubled, which can avoid auto-increment columns overflow. Suggested error level: Warning"
},
"column-comment": {
- "title": "Enforce adding comments to columns",
- "description": "Adding comments to columns is a good development practice, but excessively long comments can decrease the readability of the schema.Suggested error level: Warning",
+ "title": "Table comment convention",
+ "description": "Adding comments to columns is a good development practice, but excessively long comments can decrease the readability of the schema. Suggested error level: Warning",
"component": {
"required": {
"title": "Require comment"
},
+ "requiredClassification": {
+ "title": "Require classification",
+ "tooltip": "The comment should follow {'{'}classification id{'}'}-{'{'}comment{'}'} format."
+ },
"maxLength": {
"title": "Max length"
}
diff --git a/frontend/src/locales/sql-review/es-ES.json b/frontend/src/locales/sql-review/es-ES.json
index 613308e705..784817bc42 100644
--- a/frontend/src/locales/sql-review/es-ES.json
+++ b/frontend/src/locales/sql-review/es-ES.json
@@ -88,6 +88,10 @@
"required": {
"title": "Requerir comentario"
},
+ "requiredClassification": {
+ "title": "Requerir clasificación",
+ "tooltip": "El comentario debe seguir el formato {'{'}identificación de clasificación{'}'}-{'{'}comentario{'}'}."
+ },
"maxLength": {
"title": "Longitud máxima"
}
@@ -302,12 +306,16 @@
"description": "Los tipos no signados no almacenan números negativos, y el rango de valores que pueden almacenar se duplica, lo que puede evitar que las columnas de autoincremento desborden. Nivel de error sugerido: Advertencia"
},
"column-comment": {
- "title": "Hacer obligatorio agregar comentarios a las columnas",
+ "title": "Convención de comentarios de tabla",
"description": "Agregar comentarios a las columnas es una buena práctica de desarrollo, pero comentarios demasiado largos pueden disminuir la legibilidad del esquema. Nivel de error sugerido: Advertencia",
"component": {
"required": {
"title": "Comentario obligatorio"
},
+ "requiredClassification": {
+ "title": "Requerir clasificación",
+ "tooltip": "El comentario debe seguir el formato {'{'}identificación de clasificación{'}'}-{'{'}comentario{'}'}."
+ },
"maxLength": {
"title": "Longitud máxima"
}
diff --git a/frontend/src/locales/sql-review/ja-JP.json b/frontend/src/locales/sql-review/ja-JP.json
index 6a438d660e..835738e64c 100644
--- a/frontend/src/locales/sql-review/ja-JP.json
+++ b/frontend/src/locales/sql-review/ja-JP.json
@@ -88,6 +88,10 @@
"required": {
"title": "コメントの必須化"
},
+ "requiredClassification": {
+ "title": "分類が必要",
+ "tooltip": "コメントは、{'{'}分類 ID{'}'}-{'{'}コメント{'}'} の形式に従う必要があります。"
+ },
"maxLength": {
"title": "最大長"
}
@@ -302,12 +306,16 @@
"description": "符号なしの型は負の数を格納せず、同じ型で格納できる値の範囲が倍増するため、自動増分列のオーバーフローを回避することができます。推奨エラーレベル:警告"
},
"column-comment": {
- "title": "カラムにコメントの追加を強制する",
+ "title": "コメントの規約",
"description": "カラムにコメントを追加することは良い開発の慣行ですが、極端に長いコメントはスキーマの可読性を低下させる可能性があります。推奨エラーレベル:警告",
"component": {
"required": {
"title": "コメントの必須化"
},
+ "requiredClassification": {
+ "title": "分類が必要",
+ "tooltip": "コメントは、{'{'}分類 ID{'}'}-{'{'}コメント{'}'} の形式に従う必要があります。"
+ },
"maxLength": {
"title": "最大長"
}
diff --git a/frontend/src/locales/sql-review/zh-CN.json b/frontend/src/locales/sql-review/zh-CN.json
index ffc335b559..c87fca9406 100644
--- a/frontend/src/locales/sql-review/zh-CN.json
+++ b/frontend/src/locales/sql-review/zh-CN.json
@@ -82,12 +82,16 @@
"description": "建议在数据库层面设置字符集。在更细粒度设置字符集会带来不必要的复杂性。建议错误等级:错误。"
},
"table-comment": {
- "title": "注释检查",
+ "title": "表注释检查",
"description": "配置表是否需要注释和最大注释长度。",
"component": {
"required": {
"title": "必须注释"
},
+ "requiredClassification": {
+ "title": "需要分类",
+ "tooltip": "评论应遵循{'{'}分类 ID{'}'}-{'{'}评论{'}'}格式。"
+ },
"maxLength": {
"title": "长度限制"
}
@@ -302,12 +306,16 @@
"description": "无符号类型不存储负数,同样的类型存放的数值范围增加一倍,可以避免自增列超出上限。建议错误等级:警告"
},
"column-comment": {
- "title": "强制列增加注释并限制长度",
+ "title": "列注释检查",
"description": "对列添加注释是良好的开发习惯,但过长的注释将导致 Schema 易读性降低。建议错误等级:警告",
"component": {
"required": {
"title": "必须注释"
},
+ "requiredClassification": {
+ "title": "需要分类",
+ "tooltip": "评论应遵循{'{'}分类 ID{'}'}-{'{'}评论{'}'}格式。"
+ },
"maxLength": {
"title": "长度限制"
}
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index 53f2610554..dab51caa48 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -12,7 +12,6 @@ export * from "./notification";
export * from "./oauth";
export * from "./plan";
export * from "./member";
-export * from "./sqlAdvice";
export * from "./store";
export * from "./vcs";
export * from "./sqlEditor";
diff --git a/frontend/src/types/sql-review-schema.yaml b/frontend/src/types/sql-review-schema.yaml
index 38627da566..8dc64690ec 100644
--- a/frontend/src/types/sql-review-schema.yaml
+++ b/frontend/src/types/sql-review-schema.yaml
@@ -121,6 +121,10 @@
payload:
type: BOOLEAN
default: false
+ - key: requiredClassification
+ payload:
+ type: BOOLEAN
+ default: false
- key: maxLength
payload:
type: NUMBER
@@ -133,6 +137,10 @@
payload:
type: BOOLEAN
default: false
+ - key: requiredClassification
+ payload:
+ type: BOOLEAN
+ default: false
- key: maxLength
payload:
type: NUMBER
@@ -145,6 +153,10 @@
payload:
type: BOOLEAN
default: false
+ - key: requiredClassification
+ payload:
+ type: BOOLEAN
+ default: false
- key: maxLength
payload:
type: NUMBER
@@ -157,6 +169,10 @@
payload:
type: BOOLEAN
default: false
+ - key: requiredClassification
+ payload:
+ type: BOOLEAN
+ default: false
- key: maxLength
payload:
type: NUMBER
@@ -1384,6 +1400,10 @@
payload:
type: BOOLEAN
default: false
+ - key: requiredClassification
+ payload:
+ type: BOOLEAN
+ default: false
- key: maxLength
payload:
type: NUMBER
@@ -1396,6 +1416,10 @@
payload:
type: BOOLEAN
default: false
+ - key: requiredClassification
+ payload:
+ type: BOOLEAN
+ default: false
- key: maxLength
payload:
type: NUMBER
@@ -1408,6 +1432,10 @@
payload:
type: BOOLEAN
default: false
+ - key: requiredClassification
+ payload:
+ type: BOOLEAN
+ default: false
- key: maxLength
payload:
type: NUMBER
@@ -1420,6 +1448,10 @@
payload:
type: BOOLEAN
default: false
+ - key: requiredClassification
+ payload:
+ type: BOOLEAN
+ default: false
- key: maxLength
payload:
type: NUMBER
diff --git a/frontend/src/types/sqlAdvice.ts b/frontend/src/types/sqlAdvice.ts
deleted file mode 100644
index c82a2e516a..0000000000
--- a/frontend/src/types/sqlAdvice.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from "./sqlAdviceCode";
diff --git a/frontend/src/types/sqlAdviceCode.ts b/frontend/src/types/sqlAdviceCode.ts
deleted file mode 100644
index 3a8903ccef..0000000000
--- a/frontend/src/types/sqlAdviceCode.ts
+++ /dev/null
@@ -1,172 +0,0 @@
-/**
- * Backend reference: /plugin/advisor/code.go
- */
-
-export enum SQLAdviceCodeGeneral {
- Ok = 0,
- Internal = 1,
- NotFound = 2,
- Unsupported = 3,
-}
-
-// 101 ~ 199 compatibility error code.
-export enum SQLAdviceCodeCompatibility {
- DropDatabase = 101,
- RenameTable = 102,
- DropTable = 103,
- RenameColumn = 104,
- DropColumn = 105,
- AddPrimaryKey = 106,
- AddUniqueKey = 107,
- AddForeignKey = 108,
- AddCheck = 109,
- AlterCheck = 110,
- AlterColumn = 111,
-}
-
-// 201 ~ 299 statement error code.
-export enum SQLAdviceCodeStatement {
- SyntaxError = 201,
- NoWhere = 202,
- SelectAll = 203,
- LeadingWildcardLike = 204,
- CreateTableAs = 205,
- DisallowCommit = 206,
- RedundantAlterTable = 207,
- DMLDryRunFailed = 208,
- AffectedRowExceedsLimit = 209,
- StatementAddColumnWithDefault = 210,
- StatementAddCheckWithValidation = 211,
- StatementAddNotNull = 212,
-}
-
-// 301 ~ 399 naming error code
-export enum SQLAdviceCodeNaming {
- // 301 table naming advisor error code.
- TableConventionMismatch = 301,
- // 302 column naming advisor error code.
- ColumnConventionMismatch = 302,
- // 303 index naming advisor error code.
- IndexConventionMismatch = 303,
- // 304 unique key naming advisor error code.
- UKConventionMismatch = 304,
- // 305 foreign key naming advisor error code.
- FKConventionMismatch = 305,
- // 306 primary key naming advisor error code.
- PKConventionMismatch = 306,
- // 307 auto_increment column naming advisor error code.
- AutoIncrementColumnConventionMismatch = 307,
-}
-
-// 401 ~ 499 column error code.
-export enum SQLAdviceCodeColumn {
- NoRequiredColumn = 401,
- ColumnCannotNull = 402,
- ChangeColumnType = 403,
- NotNullColumnWithNoDefault = 404,
- ColumnNotExists = 405,
- UseChangeColumnStatement = 406,
- ChangeColumnOrder = 407,
- NoColumnComment = 408,
- ColumnCommentTooLong = 409,
- AutoIncrementColumnNotInteger = 410,
- DisabledColumnType = 411,
- ColumnExists = 412,
- DropAllColumns = 413,
- SetColumnCharset = 414,
- CharLengthExceedsLimit = 415,
- AutoIncrementColumnInitialValueNotMatch = 416,
- AutoIncrementColumnSigned = 417,
- DefaultCurrentTimeColumnCountExceedsLimit = 418,
- OnUpdateCurrentTimeColumnCountExceedsLimit = 419,
- NoDefault = 420,
-}
-
-// 501 engine error code.
-export enum SQLAdviceCodeEngine {
- NotInnoDBEngine = 501,
-}
-
-// 601 ~ 699 table rule advisor error code.
-export enum SQLAdviceCodeTable {
- TableNoPK = 601,
- TableHasFK = 602,
- TableDropNamingConventionMismatch = 603,
- TableNotExists = 604,
- NoTableComment = 605,
- TableCommentTooLong = 606,
- TableExists = 607,
- CreateTablePartition = 608,
- CreateTableTrigger = 610,
-}
-
-// 701 ~ 799 database advisor error code.
-export enum SQLAdviceCodeDatabase {
- DatabaseNotEmpty = 701,
- NotCurrentDatabase = 702,
- DatabaseIsDeleted = 703,
-}
-
-// 801 ~ 899 index error code.
-export enum SQLAdviceCodeIndex {
- NotUseIndex = 801,
- IndexKeyNumberExceedsLimit = 802,
- IndexPKType = 803,
- IndexTypeNoBlob = 804,
- IndexExists = 805,
- PrimaryKeyExists = 806,
- IndexEmptyKeys = 807,
- PrimaryKeyNotExists = 808,
- IndexNotExists = 809,
- IncorrectIndexName = 810,
- SpatialIndexKeyNullable = 811,
- DuplicateColumnInIndex = 812,
- IndexCountExceedsLimit = 813,
- CreateIndexUnconcurrently = 814,
-}
-
-// 1001 ~ 1099 charset error code.
-export enum SQLAdviceCodeCharset {
- DisabledCharset = 1001,
-}
-
-// 1101 ~ 1199 insert/update/delete error code.
-export enum SQLAdviceCodeDML {
- InsertTooManyRows = 1101,
- UpdateUseLimit = 1102,
- InsertUseLimit = 1103,
- UpdateUseOrderBy = 1104,
- DeleteUseOrderBy = 1105,
- DeleteUseLimit = 1106,
- InsertNotSpecifyColumn = 1107,
- InsertUseOrderByRand = 1108,
-}
-
-// 1201 ~ 1299 collation error code.
-export enum SQLAdviceCodeCollation {
- DisabledCollation = 1201,
-}
-
-// 1301 ~ 1399 comment error code.
-export enum SQLAdviceCodeComment {
- CommentTooLong = 1301,
-}
-
-export enum SQLAdviceCodeProcedure {
- CreateProcedure = 1401,
-}
-
-export type SQLAdviceCode =
- | SQLAdviceCodeGeneral
- | SQLAdviceCodeCompatibility
- | SQLAdviceCodeStatement
- | SQLAdviceCodeNaming
- | SQLAdviceCodeColumn
- | SQLAdviceCodeEngine
- | SQLAdviceCodeTable
- | SQLAdviceCodeDatabase
- | SQLAdviceCodeIndex
- | SQLAdviceCodeCharset
- | SQLAdviceCodeDML
- | SQLAdviceCodeCollation
- | SQLAdviceCodeComment;
diff --git a/frontend/src/types/sqlReview.ts b/frontend/src/types/sqlReview.ts
index 9ae8011269..a1f117a4b3 100644
--- a/frontend/src/types/sqlReview.ts
+++ b/frontend/src/types/sqlReview.ts
@@ -81,6 +81,7 @@ interface StringArrayLimitPayload {
// Used by the backend.
interface CommentFormatPayload {
required: boolean;
+ requiredClassification: boolean;
maxLength: number;
}
@@ -460,8 +461,17 @@ export const convertPolicyRuleToRuleTemplate = (
}
// Following rules require BOOLEAN and NUMBER component.
case "column.comment":
- case "table.comment":
- if (!booleanComponent || !numberComponent) {
+ case "table.comment": {
+ const requireComponent = componentList.find((c) => c.key === "required");
+ const requiredClassificationComponent = componentList.find(
+ (c) => c.key === "requiredClassification"
+ );
+
+ if (
+ !requireComponent ||
+ !requiredClassificationComponent ||
+ !numberComponent
+ ) {
throw new Error(`Invalid rule ${ruleTemplate.type}`);
}
@@ -469,12 +479,19 @@ export const convertPolicyRuleToRuleTemplate = (
...res,
componentList: [
{
- ...booleanComponent,
+ ...requireComponent,
payload: {
- ...booleanComponent.payload,
+ ...requireComponent.payload,
value: (payload as CommentFormatPayload).required,
} as BooleanPayload,
},
+ {
+ ...requiredClassificationComponent,
+ payload: {
+ ...requiredClassificationComponent.payload,
+ value: (payload as CommentFormatPayload).requiredClassification,
+ } as BooleanPayload,
+ },
{
...numberComponent,
payload: {
@@ -484,6 +501,7 @@ export const convertPolicyRuleToRuleTemplate = (
},
],
};
+ }
// Following rules require NUMBER component.
case "statement.insert.row-limit":
case "statement.affected-row-limit":
@@ -636,17 +654,28 @@ const mergeIndividualConfigAsRule = (
}
// Following rules require BOOLEAN and NUMBER component.
case "column.comment":
- case "table.comment":
- if (!booleanPayload || !numberPayload) {
+ case "table.comment": {
+ const requirePayload = componentList.find((c) => c.key === "required")
+ ?.payload as BooleanPayload | undefined;
+ const requiredClassificationPayload = componentList.find(
+ (c) => c.key === "requiredClassification"
+ )?.payload as BooleanPayload | undefined;
+
+ if (!requirePayload || !numberPayload) {
throw new Error(`Invalid rule ${template.type}`);
}
return {
...base,
payload: {
- required: booleanPayload.value ?? booleanPayload.default,
+ required: requirePayload.value ?? requirePayload.default,
maxLength: numberPayload.value ?? numberPayload.default,
+ requiredClassification:
+ requiredClassificationPayload?.value ??
+ requiredClassificationPayload?.default ??
+ false,
},
};
+ }
// Following rules require NUMBER component.
case "statement.insert.row-limit":
case "statement.affected-row-limit":