Skip to content

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

feat(sql-review): mysql column in primary key must INT/BIGINT (#2486)

h3n4l1143af1bfaad
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.go
index 5d0a256089..2c4ecb73a0 100644
--- a/plugin/advisor/advisor.go
+++ b/plugin/advisor/advisor.go
@@ -136,6 +136,9 @@ const (
// MySQLIndexNoDuplicateColumn is an advisor type for MySQL no duplicate columns in index.
MySQLIndexNoDuplicateColumn Type = "bb.plugin.advisor.mysql.index.no-duplicate-column"
+ // MySQLIndexPKType is an advisor type for MySQL correct type of PK.
+ MySQLIndexPKType Type = "bb.plugin.advisor.mysql.index.pk-type"
+
// MySQLIndexKeyNumberLimit is an advisor type for MySQL index key number limit.
MySQLIndexKeyNumberLimit Type = "bb.plugin.advisor.mysql.index.key-number-limit"
diff --git a/plugin/advisor/code.go b/plugin/advisor/code.go
index ae711ac6a0..eb5df17f3e 100644
--- a/plugin/advisor/code.go
+++ b/plugin/advisor/code.go
@@ -74,6 +74,7 @@ const (
// 801 miss index error code.
NotUseIndex Code = 801
IndexKeyNumberExceedsLimit Code = 802
+ IndexPKType Code = 803
// 901 ~ 999 index error code.
DuplicateColumnInIndex Code = 901
diff --git a/plugin/advisor/mysql/advisor_index_pk_type.go b/plugin/advisor/mysql/advisor_index_pk_type.go
new file mode 100644
index 0000000000..10cbdedc29
--- /dev/null
+++ b/plugin/advisor/mysql/advisor_index_pk_type.go
@@ -0,0 +1,250 @@
+package mysql
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pingcap/tidb/parser/mysql"
+ "github.com/pingcap/tidb/parser/types"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/plugin/advisor"
+ "github.com/bytebase/bytebase/plugin/advisor/catalog"
+ "github.com/bytebase/bytebase/plugin/advisor/db"
+)
+
+var (
+ _ advisor.Advisor = (*IndexPkTypeAdvisor)(nil)
+ _ ast.Visitor = (*indexPkTypeChecker)(nil)
+)
+
+func init() {
+ advisor.Register(db.MySQL, advisor.MySQLIndexPKType, &IndexPkTypeAdvisor{})
+ advisor.Register(db.TiDB, advisor.MySQLIndexPKType, &IndexPkTypeAdvisor{})
+}
+
+// IndexPkTypeAdvisor is the advisor checking for correct type of PK.
+type IndexPkTypeAdvisor struct {
+}
+
+// Check checks for correct type of PK.
+func (*IndexPkTypeAdvisor) Check(ctx advisor.Context, statement string) ([]advisor.Advice, error) {
+ stmtList, errAdvice := parseStatement(statement, ctx.Charset, ctx.Collation)
+ if errAdvice != nil {
+ return errAdvice, nil
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ checker := &indexPkTypeChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ line: make(map[string]int),
+ database: ctx.Database,
+ tablesNewColumns: make(map[string]columnNameToColumnDef),
+ }
+
+ for _, stmt := range stmtList {
+ (stmt).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type columnNameToColumnDef map[string]*ast.ColumnDef
+type tableNewColumn map[string]columnNameToColumnDef
+
+func (t tableNewColumn) set(tableName string, columnName string, colDef *ast.ColumnDef) {
+ if _, ok := t[tableName]; !ok {
+ t[tableName] = make(map[string]*ast.ColumnDef)
+ }
+ t[tableName][columnName] = colDef
+}
+
+func (t tableNewColumn) get(tableName string, columnName string) (colDef *ast.ColumnDef, ok bool) {
+ if _, ok := t[tableName]; !ok {
+ return nil, false
+ }
+ col, ok := t[tableName][columnName]
+ return col, ok
+}
+
+func (t tableNewColumn) delete(tableName string, columnName string) {
+ if _, ok := t[tableName]; !ok {
+ return
+ }
+ delete(t[tableName], columnName)
+}
+
+type indexPkTypeChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ line map[string]int
+ database *catalog.Database
+ tablesNewColumns tableNewColumn
+}
+
+type pkData struct {
+ table string
+ column string
+ columnType string
+ line int
+}
+
+// Enter implements the ast.Visitor interface.
+func (v *indexPkTypeChecker) Enter(in ast.Node) (ast.Node, bool) {
+ var pkDataList []pkData
+ switch node := in.(type) {
+ case *ast.CreateTableStmt:
+ tableName := node.Table.Name.String()
+ for _, column := range node.Cols {
+ pds := v.addNewColumn(tableName, column.OriginTextPosition(), column)
+ pkDataList = append(pkDataList, pds...)
+ }
+ for _, constraint := range node.Constraints {
+ pds := v.addConstraint(tableName, constraint.OriginTextPosition(), constraint)
+ pkDataList = append(pkDataList, pds...)
+ }
+ case *ast.AlterTableStmt:
+ tableName := node.Table.Name.String()
+ for _, spec := range node.Specs {
+ switch spec.Tp {
+ case ast.AlterTableAddColumns:
+ for _, column := range spec.NewColumns {
+ pds := v.addNewColumn(tableName, node.OriginTextPosition(), column)
+ pkDataList = append(pkDataList, pds...)
+ }
+ case ast.AlterTableAddConstraint:
+ pds := v.addConstraint(tableName, node.OriginTextPosition(), spec.Constraint)
+ pkDataList = append(pkDataList, pds...)
+ case ast.AlterTableChangeColumn, ast.AlterTableModifyColumn:
+ newColumnDef := spec.NewColumns[0]
+ oldColumnName := newColumnDef.Name.Name.String()
+ if spec.OldColumnName != nil {
+ oldColumnName = spec.OldColumnName.Name.String()
+ }
+ pds := v.changeColumn(tableName, oldColumnName, node.OriginTextPosition(), newColumnDef)
+ pkDataList = append(pkDataList, pds...)
+ }
+ }
+ }
+ for _, pd := range pkDataList {
+ v.adviceList = append(v.adviceList, advisor.Advice{
+ Status: v.level,
+ Code: advisor.IndexPKType,
+ Title: v.title,
+ Content: fmt.Sprintf("Columns in primary key must be INT/BIGINT but `%s`.`%s` is %s", pd.table, pd.column, pd.columnType),
+ Line: pd.line,
+ })
+ }
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*indexPkTypeChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
+
+func (v *indexPkTypeChecker) addNewColumn(tableName string, line int, colDef *ast.ColumnDef) []pkData {
+ var pkDataList []pkData
+ for _, option := range colDef.Options {
+ if option.Tp == ast.ColumnOptionPrimaryKey {
+ tp := v.getIntOrBigIntStr(colDef.Tp)
+ if tp != "INT" && tp != "BIGINT" {
+ pkDataList = append(pkDataList, pkData{
+ table: tableName,
+ column: colDef.Name.String(),
+ columnType: tp,
+ line: line,
+ })
+ }
+ }
+ }
+ v.tablesNewColumns.set(tableName, colDef.Name.String(), colDef)
+ return pkDataList
+}
+
+func (v *indexPkTypeChecker) changeColumn(tableName, oldColumnName string, line int, newColumnDef *ast.ColumnDef) []pkData {
+ var pkDataList []pkData
+ v.tablesNewColumns.delete(tableName, oldColumnName)
+ for _, option := range newColumnDef.Options {
+ if option.Tp == ast.ColumnOptionPrimaryKey {
+ tp := v.getIntOrBigIntStr(newColumnDef.Tp)
+ if tp != "INT" && tp != "BIGINT" {
+ pkDataList = append(pkDataList, pkData{
+ table: tableName,
+ column: newColumnDef.Name.String(),
+ columnType: tp,
+ line: line,
+ })
+ }
+ }
+ }
+ v.tablesNewColumns.set(tableName, newColumnDef.Name.String(), newColumnDef)
+ return pkDataList
+}
+
+func (v *indexPkTypeChecker) addConstraint(tableName string, line int, constraint *ast.Constraint) []pkData {
+ var pkDataList []pkData
+ if constraint.Tp == ast.ConstraintPrimaryKey {
+ for _, key := range constraint.Keys {
+ columnName := key.Column.Name.String()
+ columnType, err := v.getPKColumnType(tableName, columnName)
+ if err != nil {
+ continue
+ }
+ if columnType != "INT" && columnType != "BIGINT" {
+ pkDataList = append(pkDataList, pkData{
+ table: tableName,
+ column: columnName,
+ columnType: columnType,
+ line: line,
+ })
+ }
+ }
+ }
+ return pkDataList
+}
+
+// getPKColumnType gets the column type string from v.tablesNewColumns or catalog, returns empty string and non-nil error if cannot find the column in given table.
+func (v *indexPkTypeChecker) getPKColumnType(tableName string, columnName string) (string, error) {
+ if colDef, ok := v.tablesNewColumns.get(tableName, columnName); ok {
+ return v.getIntOrBigIntStr(colDef.Tp), nil
+ }
+ column := v.database.FindColumn(&catalog.ColumnFind{
+ TableName: tableName,
+ ColumnName: columnName,
+ })
+ if column != nil {
+ return column.Type, nil
+ }
+ return "", errors.Errorf("cannot find the type of `%s`.`%s`", tableName, columnName)
+}
+
+// getIntOrBigIntStr returns the type string of tp.
+func (*indexPkTypeChecker) getIntOrBigIntStr(tp *types.FieldType) string {
+ switch tp.Tp {
+ // https://pkg.go.dev/github.com/pingcap/tidb/parser/mysql#TypeLong
+ case mysql.TypeLong:
+ // tp.String() return int(11)
+ return "INT"
+ // https://pkg.go.dev/github.com/pingcap/tidb/parser/mysql#TypeLonglong
+ case mysql.TypeLonglong:
+ // tp.String() return bigint(20)
+ return "BIGINT"
+ }
+ return tp.String()
+}
diff --git a/plugin/advisor/mysql/advisor_index_pk_type_test.go b/plugin/advisor/mysql/advisor_index_pk_type_test.go
new file mode 100644
index 0000000000..34ee644605
--- /dev/null
+++ b/plugin/advisor/mysql/advisor_index_pk_type_test.go
@@ -0,0 +1,286 @@
+package mysql
+
+// Framework code is generated by the generator.
+
+import (
+ "testing"
+
+ "github.com/bytebase/bytebase/plugin/advisor"
+)
+
+func TestIndexPkType(t *testing.T) {
+ tests := []advisor.TestCase{
+ // CREATE TABLE COLUMN OPTION PRIMARY KEY
+ {
+ Statement: `CREATE TABLE t(id VARCHAR(5) PRIMARY KEY)`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.IndexPKType,
+ Title: "index.pk-type",
+ Content: "Columns in primary key must be INT/BIGINT but `t`.`id` is varchar(5)",
+ Line: 1,
+ },
+ },
+ },
+ {
+ Statement: `CREATE TABLE t(id INT PRIMARY KEY)`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ // CREATE TABLE TABLE OPTION PRIAMRY KEY
+ {
+ Statement: `CREATE TABLE t(id VARCHAR(5), PRIMARY KEY(id))`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.IndexPKType,
+ Title: "index.pk-type",
+ Content: "Columns in primary key must be INT/BIGINT but `t`.`id` is varchar(5)",
+ Line: 1,
+ },
+ },
+ },
+ {
+ Statement: `CREATE TABLE t(id INT, id2 VARCHAR(5), id3 VARCHAR(5), PRIMARY KEY(id, id2, id3))`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.IndexPKType,
+ Title: "index.pk-type",
+ Content: "Columns in primary key must be INT/BIGINT but `t`.`id2` is varchar(5)",
+ Line: 1,
+ },
+ {
+ Status: advisor.Warn,
+ Code: advisor.IndexPKType,
+ Title: "index.pk-type",
+ Content: "Columns in primary key must be INT/BIGINT but `t`.`id3` is varchar(5)",
+ Line: 1,
+ },
+ },
+ },
+ {
+ Statement: `CREATE TABLE t(id INT, id2 BIGINT, PRIMARY KEY(id, id2))`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ Statement: `CREATE TABLE t(id INT, PRIMARY KEY(id))`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ // ALTER TABLE ADD COLUMN OPTION PRIMARY KEY
+ {
+ Statement: `ALTER TABLE t ADD COLUMN id VARCHAR(5) PRIMARY KEY`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.IndexPKType,
+ Title: "index.pk-type",
+ Content: "Columns in primary key must be INT/BIGINT but `t`.`id` is varchar(5)",
+ Line: 1,
+ },
+ },
+ },
+ {
+ Statement: `ALTER TABLE t ADD COLUMN id INT PRIMARY KEY`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ // ALTER TABLE ADD COLUMN ADD PRIAMRY KEY CONSTRAINT
+ {
+ Statement: `ALTER TABLE t ADD COLUMN id VARCHAR(5), ADD PRIMARY KEY (id)`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.IndexPKType,
+ Title: "index.pk-type",
+ Content: "Columns in primary key must be INT/BIGINT but `t`.`id` is varchar(5)",
+ Line: 1,
+ },
+ },
+ },
+ {
+ Statement: `ALTER TABLE t ADD COLUMN id INT, ADD COLUMN id2 VARCHAR(5), ADD COLUMN id3 VARCHAR(5), ADD PRIMARY KEY (id, id2, id3)`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.IndexPKType,
+ Title: "index.pk-type",
+ Content: "Columns in primary key must be INT/BIGINT but `t`.`id2` is varchar(5)",
+ Line: 1,
+ },
+ {
+ Status: advisor.Warn,
+ Code: advisor.IndexPKType,
+ Title: "index.pk-type",
+ Content: "Columns in primary key must be INT/BIGINT but `t`.`id3` is varchar(5)",
+ Line: 1,
+ },
+ },
+ },
+ {
+ Statement: `ALTER TABLE t ADD COLUMN id INT, ADD COLUMN id2 BIGINT, ADD PRIMARY KEY (id, id2)`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ Statement: `ALTER TABLE t ADD COLUMN id BIGINT, ADD PRIMARY KEY (id)`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ // CRAETE TABLE; ALTER TABLE ADD PRIMARY KEY CONSTRAINT
+ {
+ Statement: `CREATE TABLE t(id VARCHAR(5));
+ ALTER TABLE t ADD PRIMARY KEY(id);
+ `,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.IndexPKType,
+ Title: "index.pk-type",
+ Content: "Columns in primary key must be INT/BIGINT but `t`.`id` is varchar(5)",
+ Line: 2,
+ },
+ },
+ },
+ {
+ Statement: `CREATE TABLE t(id INT, id2 VARCHAR(5), id3 VARCHAR(5));
+ ALTER TABLE t ADD PRIMARY KEY(id, id2, id3);
+ `,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.IndexPKType,
+ Title: "index.pk-type",
+ Content: "Columns in primary key must be INT/BIGINT but `t`.`id2` is varchar(5)",
+ Line: 2,
+ },
+ {
+ Status: advisor.Warn,
+ Code: advisor.IndexPKType,
+ Title: "index.pk-type",
+ Content: "Columns in primary key must be INT/BIGINT but `t`.`id3` is varchar(5)",
+ Line: 2,
+ },
+ },
+ },
+ {
+ Statement: `CREATE TABLE t(id INT, id2 BIGINT);
+ ALTER TABLE t ADD PRIMARY KEY(id, id2);
+ `,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ Statement: `CREATE TABLE t(id BIGINT);
+ ALTER TABLE t ADD PRIMARY KEY(id);
+ `,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ // ALTER TABLE MODIFY COLUMN
+ {
+ Statement: `ALTER TABLE t MODIFY COLUMN id VARCHAR(5) PRIMARY KEY;`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.IndexPKType,
+ Title: "index.pk-type",
+ Content: "Columns in primary key must be INT/BIGINT but `t`.`id` is varchar(5)",
+ Line: 1,
+ },
+ },
+ },
+ {
+ Statement: `ALTER TABLE t MODIFY COLUMN id INT(5) PRIMARY KEY;`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ // ALTER TABLE CHANGE COLUMN
+ {
+ Statement: `ALTER TABLE t CHANGE COLUMN id id2 VARCHAR(5) PRIMARY KEY`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.IndexPKType,
+ Title: "index.pk-type",
+ Content: "Columns in primary key must be INT/BIGINT but `t`.`id2` is varchar(5)",
+ Line: 1,
+ },
+ },
+ },
+ {
+ Statement: `ALTER TABLE t CHANGE COLUMN id id2 INT(5) PRIMARY KEY`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ }
+
+ advisor.RunSQLReviewRuleTests(t, tests, &IndexPkTypeAdvisor{}, &advisor.SQLReviewRule{
+ Type: advisor.SchemaRuleIndexPKType,
+ Level: advisor.SchemaRuleLevelWarning,
+ Payload: "",
+ }, advisor.MockMySQLDatabase)
+}
diff --git a/plugin/advisor/sql_review.go b/plugin/advisor/sql_review.go
index 912d4a7671..0ebba4eb3c 100644
--- a/plugin/advisor/sql_review.go
+++ b/plugin/advisor/sql_review.go
@@ -99,6 +99,8 @@ const (
SchemaRuleIndexNoDuplicateColumn SQLReviewRuleType = "index.no-duplicate-column"
// SchemaRuleIndexKeyNumberLimit enforce the index key number limit.
SchemaRuleIndexKeyNumberLimit SQLReviewRuleType = "index.key-number-limit"
+ // SchemaRuleIndexPKType enforce the type restriction of columns in primary key.
+ SchemaRuleIndexPKType SQLReviewRuleType = "index.pk-type"
// TableNameTemplateToken is the token for table name.
TableNameTemplateToken = "{{table}}"
@@ -574,6 +576,11 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine db.Type) (Type, err
case db.MySQL, db.TiDB:
return MySQLTableDisallowCreateTableAs, nil
}
+ case SchemaRuleIndexPKType:
+ switch engine {
+ case db.MySQL, db.TiDB:
+ return MySQLIndexPKType, nil
+ }
}
return Fake, errors.Errorf("unknown SQL review rule type %v for %v", ruleType, engine)
}