Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore(sql-review-rules): require charset/collation for tables in mysql (#14140)
boojack1a8520d2450a
diff --git a/backend/plugin/advisor/code.go b/backend/plugin/advisor/code.goindex 5070de557b..9443c16c7b 100644--- a/backend/plugin/advisor/code.go+++ b/backend/plugin/advisor/code.go@@ -127,6 +127,8 @@ const (TableDisallowDDL Code = 613TableDisallowDML Code = 614TableExceedLimitSize Code = 615+ NoCharset Code = 616+ NoCollation Code = 617// 701 ~ 799 database advisor error code.DatabaseNotEmpty Code = 701@@ -351,6 +353,12 @@ const (// MySQLTableFieldsMaximumCount is an advisor type for limiting MySQL table size.MySQLTableLimitSize Type = "bb.plugin.advisor.mysql.table.limit-size"+ // MySQLTableRequireCharset is an advisor type for MySQL table require charset.+ MySQLTableRequireCharset Type = "bb.plugin.advisor.mysql.table.require-charset"++ // MySQLTableRequireCollation is an advisor type for MySQL table require collation.+ MySQLTableRequireCollation Type = "bb.plugin.advisor.mysql.table.require-collation"+// MySQLDatabaseAllowDropIfEmpty is an advisor type for MySQL only allow drop empty database.MySQLDatabaseAllowDropIfEmpty Type = "bb.plugin.advisor.mysql.database.drop-empty-database"diff --git a/backend/plugin/advisor/mysql/advisor_table_require_charset.go b/backend/plugin/advisor/mysql/advisor_table_require_charset.gonew file mode 100644index 0000000000..228a25854d--- /dev/null+++ b/backend/plugin/advisor/mysql/advisor_table_require_charset.go@@ -0,0 +1,89 @@+package mysql++import (+ "fmt"++ "github.com/antlr4-go/antlr/v4"+ "github.com/pkg/errors"++ mysql "github.com/bytebase/mysql-parser"++ "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"+)++var (+ _ advisor.Advisor = (*TableRequireCharsetAdvisor)(nil)+)++func init() {+ advisor.Register(storepb.Engine_MYSQL, advisor.MySQLTableRequireCharset, &TableRequireCharsetAdvisor{})+}++// TableRequireCharsetAdvisor is the advisor checking for require charset.+type TableRequireCharsetAdvisor struct {+}++func (*TableRequireCharsetAdvisor) Check(ctx advisor.Context, _ string) ([]*storepb.Advice, error) {+ stmtList, ok := ctx.AST.([]*mysqlparser.ParseResult)+ if !ok {+ return nil, errors.Errorf("failed to convert to mysql parse result")+ }++ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)+ if err != nil {+ return nil, err+ }+ checker := &tableRequireCharsetChecker{+ level: level,+ title: string(ctx.Rule.Type),+ }++ for _, stmt := range stmtList {+ checker.baseLine = stmt.BaseLine+ antlr.ParseTreeWalkerDefault.Walk(checker, stmt.Tree)+ }++ return checker.adviceList, nil+}++type tableRequireCharsetChecker struct {+ *mysql.BaseMySQLParserListener++ adviceList []*storepb.Advice+ level storepb.Advice_Status+ title string+ baseLine int+}++func (checker *tableRequireCharsetChecker) EnterCreateTable(ctx *mysql.CreateTableContext) {+ if ctx.TableName() == nil {+ return+ }+ _, tableName := mysqlparser.NormalizeMySQLTableName(ctx.TableName())+ if tableName == "" {+ return+ }++ hasCharset := false+ if ctx.CreateTableOptions() != nil {+ for _, tableOption := range ctx.CreateTableOptions().AllCreateTableOption() {+ if tableOption.DefaultCharset() != nil {+ hasCharset = true+ break+ }+ }+ }+ if !hasCharset {+ checker.adviceList = append(checker.adviceList, &storepb.Advice{+ Status: checker.level,+ Code: advisor.NoCharset.Int32(),+ Title: checker.title,+ Content: fmt.Sprintf("Table %s does not have a character set specified", tableName),+ StartPosition: &storepb.Position{+ Line: int32(checker.baseLine + ctx.GetStart().GetLine()),+ },+ })+ }+}diff --git a/backend/plugin/advisor/mysql/advisor_table_require_collation.go b/backend/plugin/advisor/mysql/advisor_table_require_collation.gonew file mode 100644index 0000000000..cb66185d89--- /dev/null+++ b/backend/plugin/advisor/mysql/advisor_table_require_collation.go@@ -0,0 +1,89 @@+package mysql++import (+ "fmt"++ "github.com/antlr4-go/antlr/v4"+ "github.com/pkg/errors"++ mysql "github.com/bytebase/mysql-parser"++ "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"+)++var (+ _ advisor.Advisor = (*TableRequireCollationAdvisor)(nil)+)++func init() {+ advisor.Register(storepb.Engine_MYSQL, advisor.MySQLTableRequireCollation, &TableRequireCollationAdvisor{})+}++// TableRequireCollationAdvisor is the advisor checking for require collation.+type TableRequireCollationAdvisor struct {+}++func (*TableRequireCollationAdvisor) Check(ctx advisor.Context, _ string) ([]*storepb.Advice, error) {+ stmtList, ok := ctx.AST.([]*mysqlparser.ParseResult)+ if !ok {+ return nil, errors.Errorf("failed to convert to mysql parse result")+ }++ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)+ if err != nil {+ return nil, err+ }+ checker := &tableRequireCollationChecker{+ level: level,+ title: string(ctx.Rule.Type),+ }++ for _, stmt := range stmtList {+ checker.baseLine = stmt.BaseLine+ antlr.ParseTreeWalkerDefault.Walk(checker, stmt.Tree)+ }++ return checker.adviceList, nil+}++type tableRequireCollationChecker struct {+ *mysql.BaseMySQLParserListener++ adviceList []*storepb.Advice+ level storepb.Advice_Status+ title string+ baseLine int+}++func (checker *tableRequireCollationChecker) EnterCreateTable(ctx *mysql.CreateTableContext) {+ if ctx.TableName() == nil {+ return+ }+ _, tableName := mysqlparser.NormalizeMySQLTableName(ctx.TableName())+ if tableName == "" {+ return+ }++ hasCollation := false+ if ctx.CreateTableOptions() != nil {+ for _, tableOption := range ctx.CreateTableOptions().AllCreateTableOption() {+ if tableOption.DefaultCollation() != nil {+ hasCollation = true+ break+ }+ }+ }+ if !hasCollation {+ checker.adviceList = append(checker.adviceList, &storepb.Advice{+ Status: checker.level,+ Code: advisor.NoCollation.Int32(),+ Title: checker.title,+ Content: fmt.Sprintf("Table %s does not have a collation specified", tableName),+ StartPosition: &storepb.Position{+ Line: int32(checker.baseLine + ctx.GetStart().GetLine()),+ },+ })+ }+}diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.goindex a5e83c9f7b..45dde67bae 100644--- a/backend/plugin/advisor/sql_review.go+++ b/backend/plugin/advisor/sql_review.go@@ -163,6 +163,10 @@ const (SchemaRuleTableDisallowDML SQLReviewRuleType = "table.disallow-dml"// SchemaRuleTableLimitSize restrict access to tables based on size.SchemaRuleTableLimitSize SQLReviewRuleType = "table.limit-size"+ // SchemaRuleTableRequireCharset enforce the table charset.+ SchemaRuleTableRequireCharset SQLReviewRuleType = "table.require-charset"+ // SchemaRuleTableRequireCollation enforce the table collation.+ SchemaRuleTableRequireCollation SQLReviewRuleType = "table.require-collation"// SchemaRuleRequiredColumn enforce the required columns in each table.SchemaRuleRequiredColumn SQLReviewRuleType = "column.required"// SchemaRuleColumnNotNull enforce the columns cannot have NULL value.@@ -1257,6 +1261,14 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine storepb.Engine) (Tyif engine == storepb.Engine_MYSQL {return MySQLTableLimitSize, nil}+ case SchemaRuleTableRequireCharset:+ if engine == storepb.Engine_MYSQL {+ return MySQLTableRequireCharset, nil+ }+ case SchemaRuleTableRequireCollation:+ if engine == storepb.Engine_MYSQL {+ return MySQLTableRequireCollation, nil+ }case SchemaRuleMySQLEngine:switch engine {case storepb.Engine_MYSQL, storepb.Engine_MARIADB:diff --git a/frontend/src/locales/sql-review/en-US.json b/frontend/src/locales/sql-review/en-US.jsonindex 16fb93ec0f..5a94524251 100644--- a/frontend/src/locales/sql-review/en-US.json+++ b/frontend/src/locales/sql-review/en-US.json@@ -124,6 +124,14 @@}}},+ "table-require-charset": {+ "title": "Require charset",+ "description": "The charset of the table must be specified. Suggestion error level: Warning"+ },+ "table-require-collation": {+ "title": "Require collation",+ "description": "The collation of the table must be specified. Suggestion error level: Warning"+ },"naming-fully-qualified": {"title": "Fully qualified object name","description": "Enforce the use of fully qualified object names. For example, “schema.table”, suggested error level: Warning"diff --git a/frontend/src/locales/sql-review/es-ES.json b/frontend/src/locales/sql-review/es-ES.jsonindex 42b7306a57..03d6ca19ca 100644--- a/frontend/src/locales/sql-review/es-ES.json+++ b/frontend/src/locales/sql-review/es-ES.json@@ -124,6 +124,14 @@}}},+ "table-require-charset": {+ "title": "Requerir juego de caracteres",+ "description": "Se debe especificar el conjunto de caracteres de la tabla. Nivel de error sugerido: Advertencia"+ },+ "table-require-collation": {+ "title": "Requerir intercalación",+ "description": "Se debe especificar la intercalación de la tabla. Nivel de error sugerido: Advertencia"+ },"naming-fully-qualified": {"title": "Nombre de objeto completo","description": "Forzar el uso de nombres de objetos completamente calificados. Por ejemplo, “schema.table”, nivel de error sugerido: Advertencia"diff --git a/frontend/src/locales/sql-review/ja-JP.json b/frontend/src/locales/sql-review/ja-JP.jsonindex eadc99f821..ad63ce4cef 100644--- a/frontend/src/locales/sql-review/ja-JP.json+++ b/frontend/src/locales/sql-review/ja-JP.json@@ -124,6 +124,14 @@}}},+ "table-require-charset": {+ "title": "文字セットを要求する",+ "description": "テーブルの文字セットを指定する必要があります。提案エラーレベル: 警告"+ },+ "table-require-collation": {+ "title": "照合を要求する",+ "description": "テーブルの照合順序を指定する必要があります。提案エラー レベル: 警告"+ },"naming-fully-qualified": {"title": "完全修飾オブジェクト名","description": "完全修飾オブジェクト名の使用を強制します。 例えば、「schema.table」、推奨エラーレベル:警告"diff --git a/frontend/src/locales/sql-review/zh-CN.json b/frontend/src/locales/sql-review/zh-CN.jsonindex 9987919d83..b477fb636b 100644--- a/frontend/src/locales/sql-review/zh-CN.json+++ b/frontend/src/locales/sql-review/zh-CN.json@@ -124,6 +124,14 @@}}},+ "table-require-charset": {+ "title": "需要指定字符集",+ "description": "必须指定表格的字符集。建议错误级别:警告"+ },+ "table-require-collation": {+ "title": "需要指定排序规则",+ "description": "必须指定表的排序规则。建议错误级别:警告"+ },"naming-fully-qualified": {"title": "完全限定对象名称","description": "强制使用完全限定的对象名称。例如 “schema.table”,建议错误级别:警告"@@ -703,4 +711,4 @@"warning": "警告","disabled": "禁用"}-}\ No newline at end of file+}diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 9c50eb460f..4ff9f0ee50 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -3806,4 +3806,4 @@"setup": {"self": "设置"}-}+}\ No newline at end of filediff --git a/frontend/src/types/sql-review-schema.yaml b/frontend/src/types/sql-review-schema.yamlindex 5aa62d018f..3cec8348af 100644--- a/frontend/src/types/sql-review-schema.yaml+++ b/frontend/src/types/sql-review-schema.yaml@@ -266,6 +266,12 @@type: NUMBERdefault: 10000000engine: MYSQL+- type: table.require-charset+ category: TABLE+ engine: MYSQL+- type: table.require-collation+ category: TABLE+ engine: MYSQL- type: statement.select.no-select-allcategory: STATEMENTengine: MYSQLdiff --git a/frontend/src/types/sql-review.prod.yaml b/frontend/src/types/sql-review.prod.yamlindex 282a07cad0..06aaea6b99 100644--- a/frontend/src/types/sql-review.prod.yaml+++ b/frontend/src/types/sql-review.prod.yaml@@ -177,6 +177,12 @@ ruleList:payload:number: 10000000engine: MYSQL+ - type: table.require-charset+ level: WARNING+ engine: MYSQL+ - type: table.require-collation+ level: WARNING+ engine: MYSQL- type: statement.select.no-select-alllevel: ERRORengine: MYSQL