Skip to content

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

chore(sql-review-rules): require charset/collation for columns in mysql (#14141)

boojackd32b9d289db2
diff --git a/backend/plugin/advisor/code.go b/backend/plugin/advisor/code.go
index 9443c16c7b..ed71e7f987 100644
--- a/backend/plugin/advisor/code.go
+++ b/backend/plugin/advisor/code.go
@@ -308,6 +308,12 @@ const (
// MySQLColumnMaximumVarcharLength is an advisor type for MySQL maximum varchar length.
MySQLColumnMaximumVarcharLength Type = "bb.plugin.advisor.mysql.column.maximum-varchar-length"
+ // MySQLColumnRequireCharset is an advisor type for MySQL column require charset.
+ MySQLColumnRequireCharset Type = "bb.plugin.advisor.mysql.column.require-charset"
+
+ // MySQLColumnRequireCollation is an advisor type for MySQL column require collation.
+ MySQLColumnRequireCollation Type = "bb.plugin.advisor.mysql.column.require-collation"
+
// MySQLAutoIncrementColumnInitialValue is an advisor type for MySQL auto-increment column initial value.
MySQLAutoIncrementColumnInitialValue Type = "bb.plugin.advisor.mysql.column.auto-increment-initial-value"
diff --git a/backend/plugin/advisor/mysql/advisor_column_require_charset.go b/backend/plugin/advisor/mysql/advisor_column_require_charset.go
new file mode 100644
index 0000000000..9e14a00b19
--- /dev/null
+++ b/backend/plugin/advisor/mysql/advisor_column_require_charset.go
@@ -0,0 +1,132 @@
+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 = (*ColumnRequireCharsetAdvisor)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_MYSQL, advisor.MySQLColumnRequireCharset, &ColumnRequireCharsetAdvisor{})
+}
+
+// ColumnRequireCharsetAdvisor is the advisor checking for require charset.
+type ColumnRequireCharsetAdvisor struct {
+}
+
+func (*ColumnRequireCharsetAdvisor) 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 := &columnRequireCharsetChecker{
+ 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 columnRequireCharsetChecker struct {
+ *mysql.BaseMySQLParserListener
+
+ adviceList []*storepb.Advice
+ level storepb.Advice_Status
+ title string
+ baseLine int
+}
+
+func (checker *columnRequireCharsetChecker) EnterCreateTable(ctx *mysql.CreateTableContext) {
+ if ctx.TableName() == nil || ctx.TableElementList() == nil {
+ return
+ }
+ _, tableName := mysqlparser.NormalizeMySQLTableName(ctx.TableName())
+ if tableName == "" {
+ return
+ }
+
+ for _, tableElement := range ctx.TableElementList().AllTableElement() {
+ if tableElement.ColumnDefinition() == nil {
+ continue
+ }
+ columnDefinition := tableElement.ColumnDefinition()
+ if columnDefinition.FieldDefinition() == nil || columnDefinition.FieldDefinition().DataType() == nil {
+ continue
+ }
+
+ _, _, columnName := mysqlparser.NormalizeMySQLColumnName(tableElement.ColumnDefinition().ColumnName())
+ dataType := columnDefinition.FieldDefinition().DataType()
+ if isCharsetDataType(dataType) {
+ if dataType.CharsetWithOptBinary() == nil {
+ checker.adviceList = append(checker.adviceList, &storepb.Advice{
+ Status: checker.level,
+ Code: advisor.NoCharset.Int32(),
+ Title: checker.title,
+ Content: fmt.Sprintf("Column %s does not have a character set specified", columnName),
+ StartPosition: &storepb.Position{
+ Line: int32(checker.baseLine + columnDefinition.GetStart().GetLine()),
+ },
+ })
+ }
+ }
+ }
+}
+
+func (checker *columnRequireCharsetChecker) EnterAlterTable(ctx *mysql.AlterTableContext) {
+ if ctx.AlterTableActions() == nil || ctx.AlterTableActions().AlterCommandList() == nil || ctx.AlterTableActions().AlterCommandList().AlterList() == nil {
+ return
+ }
+ for _, alterListItem := range ctx.AlterTableActions().AlterCommandList().AlterList().AllAlterListItem() {
+ // Only check ADD COLUMN for now.
+ if alterListItem.ADD_SYMBOL() == nil || alterListItem.COLUMN_SYMBOL() == nil || alterListItem.FieldDefinition() == nil {
+ continue
+ }
+
+ columnName := mysqlparser.NormalizeMySQLIdentifier(alterListItem.Identifier())
+ dataType := alterListItem.FieldDefinition().DataType()
+ if isCharsetDataType(dataType) {
+ if dataType.CharsetWithOptBinary() == nil {
+ checker.adviceList = append(checker.adviceList, &storepb.Advice{
+ Status: checker.level,
+ Code: advisor.NoCharset.Int32(),
+ Title: checker.title,
+ Content: fmt.Sprintf("Column %s does not have a character set specified", columnName),
+ StartPosition: &storepb.Position{
+ Line: int32(checker.baseLine + alterListItem.GetStart().GetLine()),
+ },
+ })
+ }
+ }
+ }
+}
+
+func isCharsetDataType(dataType mysql.IDataTypeContext) bool {
+ return dataType != nil && (dataType.CHAR_SYMBOL() != nil ||
+ dataType.VARCHAR_SYMBOL() != nil ||
+ dataType.VARYING_SYMBOL() != nil ||
+ dataType.TINYTEXT_SYMBOL() != nil ||
+ dataType.TEXT_SYMBOL() != nil ||
+ dataType.MEDIUMTEXT_SYMBOL() != nil ||
+ dataType.LONGTEXT_SYMBOL() != nil)
+}
diff --git a/backend/plugin/advisor/mysql/advisor_column_require_collation.go b/backend/plugin/advisor/mysql/advisor_column_require_collation.go
new file mode 100644
index 0000000000..e8c3583f48
--- /dev/null
+++ b/backend/plugin/advisor/mysql/advisor_column_require_collation.go
@@ -0,0 +1,122 @@
+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 = (*ColumnRequireCollationAdvisor)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_MYSQL, advisor.MySQLColumnRequireCollation, &ColumnRequireCollationAdvisor{})
+}
+
+// ColumnRequireCollationAdvisor is the advisor checking for require collation.
+type ColumnRequireCollationAdvisor struct {
+}
+
+func (*ColumnRequireCollationAdvisor) 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 := &columnRequireCollationChecker{
+ 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 columnRequireCollationChecker struct {
+ *mysql.BaseMySQLParserListener
+
+ adviceList []*storepb.Advice
+ level storepb.Advice_Status
+ title string
+ baseLine int
+}
+
+func (checker *columnRequireCollationChecker) EnterCreateTable(ctx *mysql.CreateTableContext) {
+ if ctx.TableName() == nil || ctx.TableElementList() == nil {
+ return
+ }
+ _, tableName := mysqlparser.NormalizeMySQLTableName(ctx.TableName())
+ if tableName == "" {
+ return
+ }
+
+ for _, tableElement := range ctx.TableElementList().AllTableElement() {
+ if tableElement.ColumnDefinition() == nil {
+ continue
+ }
+ columnDefinition := tableElement.ColumnDefinition()
+ if columnDefinition.FieldDefinition() == nil || columnDefinition.FieldDefinition().DataType() == nil {
+ continue
+ }
+
+ _, _, columnName := mysqlparser.NormalizeMySQLColumnName(tableElement.ColumnDefinition().ColumnName())
+ dataType := columnDefinition.FieldDefinition().DataType()
+ if isCharsetDataType(dataType) {
+ if columnDefinition.FieldDefinition().Collate() == nil {
+ checker.adviceList = append(checker.adviceList, &storepb.Advice{
+ Status: checker.level,
+ Code: advisor.NoCollation.Int32(),
+ Title: checker.title,
+ Content: fmt.Sprintf("Column %s does not have a collation specified", columnName),
+ StartPosition: &storepb.Position{
+ Line: int32(checker.baseLine + columnDefinition.GetStart().GetLine()),
+ },
+ })
+ }
+ }
+ }
+}
+
+func (checker *columnRequireCollationChecker) EnterAlterTable(ctx *mysql.AlterTableContext) {
+ if ctx.AlterTableActions() == nil || ctx.AlterTableActions().AlterCommandList() == nil || ctx.AlterTableActions().AlterCommandList().AlterList() == nil {
+ return
+ }
+ for _, alterListItem := range ctx.AlterTableActions().AlterCommandList().AlterList().AllAlterListItem() {
+ // Only check ADD COLUMN for now.
+ if alterListItem.ADD_SYMBOL() == nil || alterListItem.COLUMN_SYMBOL() == nil || alterListItem.FieldDefinition() == nil {
+ continue
+ }
+
+ columnName := mysqlparser.NormalizeMySQLIdentifier(alterListItem.Identifier())
+ dataType := alterListItem.FieldDefinition().DataType()
+ if isCharsetDataType(dataType) {
+ if alterListItem.FieldDefinition().Collate() == nil {
+ checker.adviceList = append(checker.adviceList, &storepb.Advice{
+ Status: checker.level,
+ Code: advisor.NoCollation.Int32(),
+ Title: checker.title,
+ Content: fmt.Sprintf("Column %s does not have a collation specified", columnName),
+ StartPosition: &storepb.Position{
+ Line: int32(checker.baseLine + alterListItem.GetStart().GetLine()),
+ },
+ })
+ }
+ }
+ }
+}
diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.go
index 45dde67bae..7248c1e90e 100644
--- a/backend/plugin/advisor/sql_review.go
+++ b/backend/plugin/advisor/sql_review.go
@@ -207,6 +207,10 @@ const (
SchemaRuleColumnDefaultDisallowVolatile SQLReviewRuleType = "column.default-disallow-volatile"
// SchemaRuleAddNotNullColumnRequireDefault enforce the adding not null column requires default.
SchemaRuleAddNotNullColumnRequireDefault SQLReviewRuleType = "column.add-not-null-require-default"
+ // SchemaRuleColumnRequireCharset enforce the column require charset.
+ SchemaRuleColumnRequireCharset SQLReviewRuleType = "column.require-charset"
+ // SchemaRuleColumnRequireCollation enforce the column require collation.
+ SchemaRuleColumnRequireCollation SQLReviewRuleType = "column.require-collation"
// SchemaRuleSchemaBackwardCompatibility enforce the MySQL and TiDB support check whether the schema change is backward compatible.
SchemaRuleSchemaBackwardCompatibility SQLReviewRuleType = "schema.backward-compatibility"
@@ -1180,6 +1184,14 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine storepb.Engine) (Ty
if engine == storepb.Engine_ORACLE {
return OracleAddNotNullColumnRequireDefault, nil
}
+ case SchemaRuleColumnRequireCharset:
+ if engine == storepb.Engine_MYSQL {
+ return MySQLColumnRequireCharset, nil
+ }
+ case SchemaRuleColumnRequireCollation:
+ if engine == storepb.Engine_MYSQL {
+ return MySQLColumnRequireCollation, nil
+ }
case SchemaRuleTableRequirePK:
switch engine {
case storepb.Engine_MYSQL, storepb.Engine_TIDB, storepb.Engine_MARIADB, storepb.Engine_OCEANBASE:
diff --git a/frontend/src/locales/sql-review/en-US.json b/frontend/src/locales/sql-review/en-US.json
index 5a94524251..eba012ce32 100644
--- a/frontend/src/locales/sql-review/en-US.json
+++ b/frontend/src/locales/sql-review/en-US.json
@@ -368,6 +368,14 @@
"title": "Disallow setting volatile default value on columns",
"description": "Volatile functions (e.g., clock_timestamp()) update each row with the value at the time of ALTER TABLE execution, potentially causing lengthy updates."
},
+ "column-require-charset": {
+ "title": "Require charset for text columns",
+ "description": "The charset of columns with text data types must be specified. Suggestion error level: Warning"
+ },
+ "column-require-collation": {
+ "title": "Require collation for text columns",
+ "description": "The collation of columns with text data types must be specified. Suggestion error level: Warning"
+ },
"statement-select-no-select-all": {
"title": "Prohibit using \"SELECT *\"",
"description": "SELECT * to fetch entire row data may cause unnecessary resource overhead and may also cause unexpected results in applications once the table adds or removes columns. Suggestion error level: Error"
diff --git a/frontend/src/locales/sql-review/es-ES.json b/frontend/src/locales/sql-review/es-ES.json
index 03d6ca19ca..9907dc3730 100644
--- a/frontend/src/locales/sql-review/es-ES.json
+++ b/frontend/src/locales/sql-review/es-ES.json
@@ -368,6 +368,14 @@
"title": "No permitir establecer valores predeterminados volátiles en las columnas",
"description": "Las funciones volátiles (por ejemplo, clock_timestamp()) actualizan cada fila con el valor en el momento de la ejecución de ALTER TABLE, lo que puede causar actualizaciones prolongadas."
},
+ "column-require-charset": {
+ "title": "Requerir juego de caracteres para columnas de texto",
+ "description": "Se debe especificar el conjunto de caracteres de las columnas con tipos de datos de texto. Nivel de error sugerido: Advertencia"
+ },
+ "column-require-collation": {
+ "title": "Requerir intercalación para columnas de texto",
+ "description": "Se debe especificar la intercalación de columnas con tipos de datos de texto. Nivel de error sugerido: Advertencia"
+ },
"statement-select-no-select-all": {
"title": "Prohibir el uso de \"SELECT *\"",
"description": "El uso de SELECT * para obtener todos los datos de una fila puede causar una sobrecarga de recursos innecesaria y también puede causar resultados inesperados en las aplicaciones una vez que la tabla agrega o elimina columnas. Nivel de sugerencia de error: Error"
diff --git a/frontend/src/locales/sql-review/ja-JP.json b/frontend/src/locales/sql-review/ja-JP.json
index ad63ce4cef..48f6910b67 100644
--- a/frontend/src/locales/sql-review/ja-JP.json
+++ b/frontend/src/locales/sql-review/ja-JP.json
@@ -368,6 +368,14 @@
"title": "列に対して揮発性のあるデフォルト値の設定を禁止します",
"description": "ボラタイル関数(例: clock_timestamp())は、ALTER TABLE 実行時の値で各行を更新し、更新が長引く可能性があります。"
},
+ "column-require-charset": {
+ "title": "テキスト列に文字セットを要求する",
+ "description": "テキスト データ型の列の文字セットを指定する必要があります。提案エラー レベル: 警告"
+ },
+ "column-require-collation": {
+ "title": "テキスト列の照合を要求する",
+ "description": "テキスト データ型の列の照合を指定する必要があります。提案エラー レベル: 警告"
+ },
"statement-select-no-select-all": {
"title": "「SELECT *」の使用を禁止する",
"description": "「SELECT *」を使用して全行データを取得すると、不必要なリソースのオーバーヘッドが発生し、テーブルに列を追加または削除した場合にアプリケーションで予期しない結果が発生する可能性があります。提案エラーレベル:エラー"
diff --git a/frontend/src/locales/sql-review/zh-CN.json b/frontend/src/locales/sql-review/zh-CN.json
index b477fb636b..1d6b4b491c 100644
--- a/frontend/src/locales/sql-review/zh-CN.json
+++ b/frontend/src/locales/sql-review/zh-CN.json
@@ -368,6 +368,14 @@
"title": "禁止在列上设置易变的默认值",
"description": "易变函数(例如,clock_timestamp())会在执行 ALTER TABLE 时更新每一行的值,可能导致更新操作时间过长。"
},
+ "column-require-charset": {
+ "title": "要求列设置字符集",
+ "description": "必须指定字符数据类型的列的字符集。建议错误级别:警告"
+ },
+ "column-require-collation": {
+ "title": "要求对列设置排序规则",
+ "description": "必须指定字符数据类型的列的排序规则。建议错误级别:警告"
+ },
"statement-select-no-select-all": {
"title": "禁止使用 \"SELECT *\"",
"description": "SELECT * 拉取整行数据可能造成不必要的资源开销,同时一旦表增减列,也可能造成应用出现不符合预期的结果。建议错误等级:错误"
diff --git a/frontend/src/types/sql-review-schema.yaml b/frontend/src/types/sql-review-schema.yaml
index 3cec8348af..42d7b19369 100644
--- a/frontend/src/types/sql-review-schema.yaml
+++ b/frontend/src/types/sql-review-schema.yaml
@@ -1840,6 +1840,12 @@
- type: column.default-disallow-volatile
category: COLUMN
engine: POSTGRES
+- type: column.require-charset
+ category: COLUMN
+ engine: MYSQL
+- type: column.require-collation
+ category: COLUMN
+ engine: MYSQL
- type: schema.backward-compatibility
category: SCHEMA
engine: MYSQL
diff --git a/frontend/src/types/sql-review.prod.yaml b/frontend/src/types/sql-review.prod.yaml
index 06aaea6b99..0718da0353 100644
--- a/frontend/src/types/sql-review.prod.yaml
+++ b/frontend/src/types/sql-review.prod.yaml
@@ -1293,6 +1293,12 @@ ruleList:
- type: column.default-disallow-volatile
level: WARNING
engine: POSTGRES
+ - type: column.require-charset
+ level: WARNING
+ engine: MYSQL
+ - type: column.require-collation
+ level: WARNING
+ engine: MYSQL
- type: schema.backward-compatibility
level: WARNING
engine: MYSQL