Skip to content

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

feat(schema system): support table require pk rule (#1312)

rebelice41831f2b7a08
diff --git a/common/error.go b/common/error.go
index 8014668303..8d19905875 100644
--- a/common/error.go
+++ b/common/error.go
@@ -69,6 +69,9 @@ const (
ColumnCanNull Code = 10302
NotInnoDBEngine Code = 10401
+
+ // 10501 table rule advisor error code
+ TableNoPK Code = 10501
)
// Error represents an application-specific error. Application errors can be
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.go
index 12d9dcfb0d..17991e8090 100644
--- a/plugin/advisor/advisor.go
+++ b/plugin/advisor/advisor.go
@@ -96,6 +96,9 @@ const (
// MySQLNoSelectAll is an advisor type for MySQL no select all.
MySQLNoSelectAll Type = "bb.plugin.advisor.mysql.select.no-select-all"
+
+ // MySQLTableRequirePK is an advisor type for MySQL table require primary key.
+ MySQLTableRequirePK Type = "bb.plugin.advisor.mysql.table.require-pk"
)
// Advice is the result of an advisor.
diff --git a/plugin/advisor/mysql/advisor_table_require_pk.go b/plugin/advisor/mysql/advisor_table_require_pk.go
new file mode 100644
index 0000000000..8b83c94a49
--- /dev/null
+++ b/plugin/advisor/mysql/advisor_table_require_pk.go
@@ -0,0 +1,208 @@
+package mysql
+
+import (
+ "context"
+ "fmt"
+ "strings"
+
+ "github.com/bytebase/bytebase/common"
+ "github.com/bytebase/bytebase/plugin/advisor"
+ "github.com/bytebase/bytebase/plugin/catalog"
+ "github.com/bytebase/bytebase/plugin/db"
+ "github.com/pingcap/tidb/parser/ast"
+ "go.uber.org/zap"
+)
+
+const (
+ primaryKeyName = "PRIMARY"
+)
+
+var (
+ _ advisor.Advisor = (*TableRequirePKAdvisor)(nil)
+)
+
+func init() {
+ advisor.Register(db.MySQL, advisor.MySQLTableRequirePK, &TableRequirePKAdvisor{})
+ advisor.Register(db.TiDB, advisor.MySQLTableRequirePK, &TableRequirePKAdvisor{})
+}
+
+// TableRequirePKAdvisor is the advisor checking table requires PK.
+type TableRequirePKAdvisor struct {
+}
+
+// Check checks table requires PK.
+func (adv *TableRequirePKAdvisor) Check(ctx advisor.Context, statement string) ([]advisor.Advice, error) {
+ root, errAdvice := parseStatement(statement, ctx.Charset, ctx.Collation)
+ if errAdvice != nil {
+ return errAdvice, nil
+ }
+
+ level, err := advisor.NewStatusBySchemaReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ checker := &tableRequirePKChecker{
+ level: level,
+ tables: make(tablePK),
+ catalog: ctx.Catalog,
+ logger: ctx.Logger,
+ }
+
+ for _, stmtNode := range root {
+ (stmtNode).Accept(checker)
+ }
+
+ return checker.generateAdviceList(), nil
+}
+
+type tableRequirePKChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ tables tablePK
+ catalog catalog.Service
+ logger *zap.Logger
+}
+
+// Enter implements the ast.Visitor interface
+func (v *tableRequirePKChecker) Enter(in ast.Node) (ast.Node, bool) {
+ switch node := in.(type) {
+ // CREATE TABLE
+ case *ast.CreateTableStmt:
+ v.createTable(node)
+ // DROP TABLE
+ case *ast.DropTableStmt:
+ for _, table := range node.Tables {
+ delete(v.tables, table.Name.String())
+ }
+ // ALTER TABLE
+ case *ast.AlterTableStmt:
+ tableName := node.Table.Name.O
+ for _, spec := range node.Specs {
+ switch spec.Tp {
+ // ADD CONSTRAINT
+ case ast.AlterTableAddConstraint:
+ if spec.Constraint.Tp == ast.ConstraintPrimaryKey {
+ v.tables[tableName] = newColumnSet(convertConstraintToKeySlice(spec.Constraint))
+ }
+ // DROP PRIMARY KEY
+ case ast.AlterTableDropPrimaryKey:
+ v.initEmptyTable(tableName)
+ // DROP INDEX
+ case ast.AlterTableDropIndex:
+ if strings.ToUpper(spec.Name) == primaryKeyName {
+ v.initEmptyTable(tableName)
+ }
+ // ADD COLUMNS
+ case ast.AlterTableAddColumns:
+ v.addPKIfExistByCols(tableName, spec.NewColumns)
+ // CHANGE COLUMN
+ case ast.AlterTableChangeColumn:
+ v.changeColumn(tableName, spec.OldColumnName.Name.String(), spec.NewColumns[0].Name.Name.String())
+ v.addPKIfExistByCols(tableName, spec.NewColumns[:1])
+ // MODIFY COLUMN
+ case ast.AlterTableModifyColumn:
+ v.addPKIfExistByCols(tableName, spec.NewColumns[:1])
+ // DROP COLUMN
+ case ast.AlterTableDropColumn:
+ v.dropColumn(tableName, spec.OldColumnName.Name.String())
+ }
+ }
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface
+func (v *tableRequirePKChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
+
+func (v *tableRequirePKChecker) generateAdviceList() []advisor.Advice {
+ tableList := v.tables.tableList()
+ for _, tableName := range tableList {
+ if len(v.tables[tableName]) == 0 {
+ v.adviceList = append(v.adviceList, advisor.Advice{
+ Status: v.level,
+ Code: common.TableNoPK,
+ Title: "Require PRIMARY KEY",
+ Content: fmt.Sprintf("Table `%s` requires PRIMARY KEY", tableName),
+ })
+ }
+ }
+
+ if len(v.adviceList) == 0 {
+ v.adviceList = append(v.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: common.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return v.adviceList
+}
+
+func (v *tableRequirePKChecker) initEmptyTable(name string) columnSet {
+ v.tables[name] = make(columnSet)
+ return v.tables[name]
+}
+
+func (v *tableRequirePKChecker) createTable(node *ast.CreateTableStmt) {
+ table := node.Table.Name.String()
+ v.initEmptyTable(table)
+ v.addPKIfExistByCols(table, node.Cols)
+
+ for _, constraint := range node.Constraints {
+ if constraint.Tp == ast.ConstraintPrimaryKey {
+ v.tables[table] = newColumnSet(convertConstraintToKeySlice(constraint))
+ }
+ }
+}
+
+func (v *tableRequirePKChecker) dropColumn(table string, column string) {
+ if _, ok := v.tables[table]; !ok {
+ ctx := context.Background()
+ pk, err := v.catalog.FindIndex(ctx, &catalog.IndexFind{
+ TableName: table,
+ IndexName: primaryKeyName,
+ })
+ if err != nil {
+ v.logger.Error(
+ "Cannot find primary key in table",
+ zap.String("table_name", table),
+ zap.Error(err),
+ )
+ return
+ }
+ if pk == nil {
+ return
+ }
+ v.tables[table] = newColumnSet(pk.ColumnExpressions)
+ }
+
+ delete(v.tables[table], column)
+}
+
+func (v *tableRequirePKChecker) changeColumn(table string, oldColumn string, newColumn string) {
+ v.dropColumn(table, oldColumn)
+ pk := v.tables[table]
+ pk[newColumn] = true
+}
+
+func (v *tableRequirePKChecker) addPKIfExistByCols(table string, columns []*ast.ColumnDef) {
+ for _, column := range columns {
+ for _, option := range column.Options {
+ if option.Tp == ast.ColumnOptionPrimaryKey {
+ v.tables[table] = newColumnSet([]string{column.Name.Name.String()})
+ return
+ }
+ }
+ }
+}
+
+func convertConstraintToKeySlice(constraint *ast.Constraint) []string {
+ var columns []string
+ for _, key := range constraint.Keys {
+ columns = append(columns, key.Column.Name.String())
+ }
+ return columns
+}
diff --git a/plugin/advisor/mysql/advisor_table_require_pk_test.go b/plugin/advisor/mysql/advisor_table_require_pk_test.go
new file mode 100644
index 0000000000..7961f2525f
--- /dev/null
+++ b/plugin/advisor/mysql/advisor_table_require_pk_test.go
@@ -0,0 +1,222 @@
+package mysql
+
+import (
+ "testing"
+
+ "github.com/bytebase/bytebase/api"
+ "github.com/bytebase/bytebase/common"
+ "github.com/bytebase/bytebase/plugin/advisor"
+)
+
+func TestRequirePK(t *testing.T) {
+ tests := []test{
+ {
+ statement: "CREATE TABLE t(id INT PRIMARY KEY)",
+ want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: common.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ statement: "CREATE TABLE t(id INT, PRIMARY KEY (id))",
+ want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: common.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ statement: "CREATE TABLE t(id INT)",
+ want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: common.TableNoPK,
+ Title: "Require PRIMARY KEY",
+ Content: "Table `t` requires PRIMARY KEY",
+ },
+ },
+ },
+ {
+ statement: `CREATE TABLE t(id INT);
+ DROP TABLE t`,
+ want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: common.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ statement: `CREATE TABLE t(id INT);
+ ALTER TABLE t ADD CONSTRAINT PRIMARY KEY (id)`,
+ want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: common.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ statement: `CREATE TABLE t(id INT PRIMARY KEY);
+ ALTER TABLE t DROP PRIMARY KEY`,
+ want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: common.TableNoPK,
+ Title: "Require PRIMARY KEY",
+ Content: "Table `t` requires PRIMARY KEY",
+ },
+ },
+ },
+ {
+ statement: "CREATE TABLE t(id INT PRIMARY KEY);" +
+ "ALTER TABLE t DROP INDEX `PRIMARY`",
+ want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: common.TableNoPK,
+ Title: "Require PRIMARY KEY",
+ Content: "Table `t` requires PRIMARY KEY",
+ },
+ },
+ },
+ {
+ statement: `CREATE TABLE t(id INT);
+ ALTER TABLE t ADD COLUMN name varchar(30) PRIMARY KEY`,
+ want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: common.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ statement: `CREATE TABLE t(id INT);
+ ALTER TABLE t CHANGE COLUMN id id INT PRIMARY KEY`,
+ want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: common.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ // Use MockCatalogService
+ statement: `ALTER TABLE t CHANGE COLUMN id uid INT`,
+ want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: common.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ statement: `CREATE TABLE t(id INT);
+ ALTER TABLE t MODIFY COLUMN id INT PRIMARY KEY`,
+ want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: common.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ // Use MockCatalogService
+ statement: `ALTER TABLE t MODIFY COLUMN id INT PRIMARY KEY`,
+ want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: common.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ statement: `CREATE TABLE t(id INT, name varchar(30), PRIMARY KEY(id, name));
+ ALTER TABLE t DROP COLUMN id`,
+ want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: common.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ statement: `CREATE TABLE t(id INT, name varchar(30), comment varchar(255), PRIMARY KEY(id, name));
+ ALTER TABLE t DROP COLUMN id, DROP COLUMN name`,
+ want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: common.TableNoPK,
+ Title: "Require PRIMARY KEY",
+ Content: "Table `t` requires PRIMARY KEY",
+ },
+ },
+ },
+ {
+ // Use MockCatalogService
+ statement: `ALTER TABLE t DROP COLUMN id, DROP COLUMN name`,
+ want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: common.TableNoPK,
+ Title: "Require PRIMARY KEY",
+ Content: "Table `t` requires PRIMARY KEY",
+ },
+ },
+ },
+ {
+ // Use MockCatalogService
+ statement: `ALTER TABLE t DROP COLUMN uid, DROP COLUMN name`,
+ want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: common.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ // Use MockCatalogService
+ statement: `ALTER TABLE t CHANGE COLUMN id uid int;
+ ALTER TABLE t DROP COLUMN uid, DROP COLUMN name`,
+ want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: common.TableNoPK,
+ Title: "Require PRIMARY KEY",
+ Content: "Table `t` requires PRIMARY KEY",
+ },
+ },
+ },
+ }
+
+ runSchemaReviewRuleTests(t, tests, &TableRequirePKAdvisor{}, &api.SchemaReviewRule{
+ Type: api.SchemaRuleTableRequirePK,
+ Level: api.SchemaRuleLevelError,
+ Payload: "",
+ }, &MockCatalogService{})
+}
diff --git a/plugin/advisor/mysql/utils.go b/plugin/advisor/mysql/utils.go
index f58a7fa0ee..29939c04fd 100644
--- a/plugin/advisor/mysql/utils.go
+++ b/plugin/advisor/mysql/utils.go
@@ -9,6 +9,15 @@ import (
)
type columnSet map[string]bool
+
+func newColumnSet(columns []string) columnSet {
+ res := make(columnSet)
+ for _, col := range columns {
+ res[col] = true
+ }
+ return res
+}
+
type tableState map[string]columnSet
// tableList returns table list in lexicographical order.
@@ -21,6 +30,18 @@ func (t tableState) tableList() []string {
return tableList
}
+type tablePK map[string]columnSet
+
+// tableList returns table list in lexicographical order.
+func (t tablePK) tableList() []string {
+ var tableList []string
+ for tableName := range t {
+ tableList = append(tableList, tableName)
+ }
+ sort.Strings(tableList)
+ return tableList
+}
+
func restoreNode(node ast.Node, flag format.RestoreFlags) (string, error) {
var buffer strings.Builder
ctx := format.NewRestoreCtx(flag, &buffer)
diff --git a/plugin/advisor/mysql/utils_for_test.go b/plugin/advisor/mysql/utils_for_test.go
index e62b722e23..edf141e86e 100644
--- a/plugin/advisor/mysql/utils_for_test.go
+++ b/plugin/advisor/mysql/utils_for_test.go
@@ -18,6 +18,7 @@ type MockCatalogService struct{}
const (
MockOldIndexName = "old_index"
MockOldUKName = "old_uk"
+ MockOldPKName = "PRIMARY"
)
var (
@@ -37,6 +38,12 @@ func (c *MockCatalogService) FindIndex(ctx context.Context, find *catalog.IndexF
Name: MockOldIndexName,
ColumnExpressions: MockIndexColumnList,
}, nil
+ case MockOldPKName:
+ return &catalog.Index{
+ Unique: true,
+ Name: MockOldPKName,
+ ColumnExpressions: MockIndexColumnList,
+ }, nil
}
return nil, fmt.Errorf("cannot find index for %v", find)
}
diff --git a/server/task_check_executor_statement_advisor_composite.go b/server/task_check_executor_statement_advisor_composite.go
index ef1f20c1c9..af78c52d53 100644
--- a/server/task_check_executor_statement_advisor_composite.go
+++ b/server/task_check_executor_statement_advisor_composite.go
@@ -179,6 +179,11 @@ func getAdvisorTypeByRule(ruleType api.SchemaReviewRuleType, engine db.Type) (ad
case db.MySQL, db.TiDB:
return advisor.MySQLColumnNoNull, nil
}
+ case api.SchemaRuleTableRequirePK:
+ switch engine {
+ case db.MySQL, db.TiDB:
+ return advisor.MySQLTableRequirePK, nil
+ }
case api.SchemaRuleMySQLEngine:
switch engine {
case db.MySQL: