Skip to content

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

feat(advisor): implement PG primary-key-type-allowlist rule (#4137)

rebelicea614c592fb63
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.go
index 159286a75a..2d87930013 100644
--- a/plugin/advisor/advisor.go
+++ b/plugin/advisor/advisor.go
@@ -257,6 +257,9 @@ const (
// PostgreSQLIndexKeyNumberLimit is an advisor type for postgresql index key number limit.
PostgreSQLIndexKeyNumberLimit Type = "bb.plugin.advisor.postgresql.index.key-number-limit"
+ // PostgreSQLPrimaryKeyTypeAllowlist is an advisor type for postgresql primary key type allowlist.
+ PostgreSQLPrimaryKeyTypeAllowlist Type = "bb.plugin.advisor.postgresql.index.primary-key-type-allowlist"
+
// PostgreSQLEncodingAllowlist is an advisor type for PostgreSQL encoding allowlist.
PostgreSQLEncodingAllowlist Type = "bb.plugin.advisor.postgresql.charset.allowlist"
diff --git a/plugin/advisor/pg/advisor_index_primary_key_type_allowlist.go b/plugin/advisor/pg/advisor_index_primary_key_type_allowlist.go
new file mode 100644
index 0000000000..1722dc10d7
--- /dev/null
+++ b/plugin/advisor/pg/advisor_index_primary_key_type_allowlist.go
@@ -0,0 +1,134 @@
+package pg
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+
+ "go.uber.org/zap"
+
+ "github.com/bytebase/bytebase/common/log"
+ "github.com/bytebase/bytebase/plugin/advisor"
+ "github.com/bytebase/bytebase/plugin/advisor/db"
+ "github.com/bytebase/bytebase/plugin/parser"
+ "github.com/bytebase/bytebase/plugin/parser/ast"
+)
+
+var (
+ _ advisor.Advisor = (*IndexPrimaryKeyTypeAllowlistAdvisor)(nil)
+ _ ast.Visitor = (*indexPrimaryKeyTypeAllowlistChecker)(nil)
+)
+
+func init() {
+ advisor.Register(db.Postgres, advisor.PostgreSQLPrimaryKeyTypeAllowlist, &IndexPrimaryKeyTypeAllowlistAdvisor{})
+}
+
+// IndexPrimaryKeyTypeAllowlistAdvisor is the advisor checking for primary key type allowlist.
+type IndexPrimaryKeyTypeAllowlistAdvisor struct {
+}
+
+// Check checks for primary key type allowlist.
+func (*IndexPrimaryKeyTypeAllowlistAdvisor) Check(ctx advisor.Context, statement string) ([]advisor.Advice, error) {
+ stmtList, errAdvice := parseStatement(statement)
+ if errAdvice != nil {
+ return errAdvice, nil
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ payload, err := advisor.UnmarshalStringArrayTypeRulePayload(ctx.Rule.Payload)
+ if err != nil {
+ return nil, err
+ }
+ checker := &indexPrimaryKeyTypeAllowlistChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ allowlist: payload.List,
+ }
+
+ for _, stmt := range stmtList {
+ ast.Walk(checker, stmt)
+ }
+
+ 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 indexPrimaryKeyTypeAllowlistChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ allowlist []string
+}
+
+// Visit implements ast.Visitor interface.
+func (checker *indexPrimaryKeyTypeAllowlistChecker) Visit(in ast.Node) ast.Visitor {
+ var columnList []*ast.ColumnDef
+ columnMap := make(map[string]*ast.ColumnDef)
+ if node, ok := in.(*ast.CreateTableStmt); ok {
+ for _, column := range node.ColumnList {
+ columnMap[column.ColumnName] = column
+ if isPKColumn(column) {
+ columnList = append(columnList, column)
+ }
+ }
+ for _, constraint := range node.ConstraintList {
+ if constraint.Type == ast.ConstraintTypePrimary {
+ for _, key := range constraint.KeyList {
+ if column, exists := columnMap[key]; exists {
+ columnList = append(columnList, column)
+ }
+ }
+ }
+ }
+ }
+
+ for _, column := range columnList {
+ if !allowType(checker.allowlist, column.Type) {
+ typeText, err := parser.Deparse(parser.Postgres, parser.DeparseContext{}, column.Type)
+ if err != nil {
+ log.Warn("Failed to deparse the PostgreSQL data type",
+ zap.String("columnName", column.ColumnName),
+ zap.String("originalSQL", in.Text()))
+ typeText = ""
+ }
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.IndexPKType,
+ Title: checker.title,
+ Content: fmt.Sprintf(`The column "%s" is one of the primary key, but its type "%s" is not in allowlist`, column.ColumnName, typeText),
+ Line: column.LastLine(),
+ })
+ }
+ }
+
+ return checker
+}
+
+func allowType(allowlist []string, columnType ast.DataType) bool {
+ for _, tp := range allowlist {
+ if columnType.EquivalentType(tp) {
+ return true
+ }
+ }
+ return false
+}
+
+func isPKColumn(column *ast.ColumnDef) bool {
+ for _, constraint := range column.ConstraintList {
+ if constraint.Type == ast.ConstraintTypePrimary {
+ return true
+ }
+ }
+
+ return false
+}
diff --git a/plugin/advisor/pg/pg_rules_test.go b/plugin/advisor/pg/pg_rules_test.go
index 3ce5862a1b..a656fa9b60 100644
--- a/plugin/advisor/pg/pg_rules_test.go
+++ b/plugin/advisor/pg/pg_rules_test.go
@@ -31,6 +31,7 @@ func TestPostgreSQLRules(t *testing.T) {
advisor.SchemaRuleTableRequirePK,
advisor.SchemaRuleColumnDisallowChangeType,
advisor.SchemaRuleTableDisallowPartition,
+ advisor.SchemaRuleIndexPrimaryKeyTypeAllowlist,
}
for _, rule := range pgRules {
diff --git a/plugin/advisor/pg/test/index_primary_key_type_allowlist.yaml b/plugin/advisor/pg/test/index_primary_key_type_allowlist.yaml
new file mode 100644
index 0000000000..dfaad583fc
--- /dev/null
+++ b/plugin/advisor/pg/test/index_primary_key_type_allowlist.yaml
@@ -0,0 +1,35 @@
+- statement: CREATE TABLE t(a SERIAL PRIMARY KEY);
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+- statement: CREATE TABLE t(a BIGSERIAL, PRIMARY KEY(a));
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+- statement: |-
+ CREATE TABLE t(
+ a varchar(20) PRIMARY KEY
+ );
+ want:
+ - status: WARN
+ code: 803
+ title: index.primary-key-type-allowlist
+ content: The column "a" is one of the primary key, but its type "character varying(20)" is not in allowlist
+ line: 2
+- statement: |-
+ CREATE TABLE t(
+ a varchar(20),
+ PRIMARY KEY(a)
+ );
+ want:
+ - status: WARN
+ code: 803
+ title: index.primary-key-type-allowlist
+ content: The column "a" is one of the primary key, but its type "character varying(20)" is not in allowlist
+ line: 2
diff --git a/plugin/advisor/sql_review.go b/plugin/advisor/sql_review.go
index ac8e82adf8..358dc6bd49 100644
--- a/plugin/advisor/sql_review.go
+++ b/plugin/advisor/sql_review.go
@@ -134,6 +134,8 @@ const (
SchemaRuleIndexTypeNoBlob SQLReviewRuleType = "index.type-no-blob"
// SchemaRuleIndexTotalNumberLimit enforce the index total number limit.
SchemaRuleIndexTotalNumberLimit SQLReviewRuleType = "index.total-number-limit"
+ // SchemaRuleIndexPrimaryKeyTypeAllowlist enforce the primary key type allowlist.
+ SchemaRuleIndexPrimaryKeyTypeAllowlist SQLReviewRuleType = "index.primary-key-type-allowlist"
// SchemaRuleCharsetAllowlist enforce the charset allowlist.
SchemaRuleCharsetAllowlist SQLReviewRuleType = "system.charset.allowlist"
@@ -241,7 +243,7 @@ func (rule *SQLReviewRule) Validate() error {
if _, err := UnmarshalNumberTypeRulePayload(rule.Payload); err != nil {
return err
}
- case SchemaRuleColumnTypeDisallowList, SchemaRuleCharsetAllowlist, SchemaRuleCollationAllowlist:
+ case SchemaRuleColumnTypeDisallowList, SchemaRuleCharsetAllowlist, SchemaRuleCollationAllowlist, SchemaRuleIndexPrimaryKeyTypeAllowlist:
if _, err := UnmarshalStringArrayTypeRulePayload(rule.Payload); err != nil {
return err
}
@@ -863,6 +865,10 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine db.Type) (Type, err
case db.MySQL, db.TiDB:
return MySQLIndexTypeNoBlob, nil
}
+ case SchemaRuleIndexPrimaryKeyTypeAllowlist:
+ if engine == db.Postgres {
+ return PostgreSQLPrimaryKeyTypeAllowlist, nil
+ }
case SchemaRuleStatementInsertRowLimit:
switch engine {
case db.MySQL:
diff --git a/plugin/advisor/utils_for_tests.go b/plugin/advisor/utils_for_tests.go
index f40cc15d8a..1eef7b328c 100644
--- a/plugin/advisor/utils_for_tests.go
+++ b/plugin/advisor/utils_for_tests.go
@@ -466,6 +466,10 @@ func SetDefaultSQLReviewRulePayload(ruleTp SQLReviewRuleType) (string, error) {
Required: true,
MaxLength: 20,
})
+ case SchemaRuleIndexPrimaryKeyTypeAllowlist:
+ payload, err = json.Marshal(StringArrayTypeRulePayload{
+ List: []string{"serial", "bigserial"},
+ })
default:
return "", errors.Errorf("unknown SQL review type for default payload: %s", ruleTp)
}