Skip to content

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

feat: support PG pk-naming rule (#2094)

rebelicea3d2729c4a30
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.go
index 0b6abbb844..6967c644c5 100644
--- a/plugin/advisor/advisor.go
+++ b/plugin/advisor/advisor.go
@@ -108,6 +108,9 @@ const (
// PostgreSQLNamingColumnConvention is an advisor type for PostgreSQL column naming convention.
PostgreSQLNamingColumnConvention Type = "bb.plugin.advisor.postgresql.naming.column"
+ // PostgreSQLNamingPKConvention is an advisor type for PostgreSQL primary key naming convention.
+ PostgreSQLNamingPKConvention Type = "bb.plugin.advisor.postgresql.naming.pk"
+
// PostgreSQLNamingIndexConvention is an advisor type for PostgreSQL index naming convention.
PostgreSQLNamingIndexConvention Type = "bb.plugin.advisor.postgresql.naming.index"
diff --git a/plugin/advisor/code.go b/plugin/advisor/code.go
index d1c38b92f0..ea7bed2407 100644
--- a/plugin/advisor/code.go
+++ b/plugin/advisor/code.go
@@ -39,6 +39,8 @@ const (
NamingUKConventionMismatch Code = 304
// 305 foreign key naming advisor error code.
NamingFKConventionMismatch Code = 305
+ // 306 primary key naming advisor error code.
+ NamingPKConventionMismatch Code = 306
// 401 ~ 499 column error code.
NoRequiredColumn Code = 401
diff --git a/plugin/advisor/pg/advisor_naming_primary_key_convention.go b/plugin/advisor/pg/advisor_naming_primary_key_convention.go
new file mode 100644
index 0000000000..72125582f2
--- /dev/null
+++ b/plugin/advisor/pg/advisor_naming_primary_key_convention.go
@@ -0,0 +1,211 @@
+package pg
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/bytebase/bytebase/plugin/advisor"
+ "github.com/bytebase/bytebase/plugin/advisor/catalog"
+ "github.com/bytebase/bytebase/plugin/parser/ast"
+)
+
+var (
+ _ advisor.Advisor = (*NamingPKConventionAdvisor)(nil)
+ _ ast.Visitor = (*namingPKConventionChecker)(nil)
+)
+
+func init() {
+ advisor.Register(advisor.Postgres, advisor.PostgreSQLNamingPKConvention, &NamingPKConventionAdvisor{})
+}
+
+// NamingPKConventionAdvisor is the advisor checking for primary key naming convention.
+type NamingPKConventionAdvisor struct {
+}
+
+// Check checks for index naming convention.
+func (*NamingPKConventionAdvisor) Check(ctx advisor.Context, statement string) ([]advisor.Advice, error) {
+ stmts, errAdvice := parseStatement(statement)
+ if errAdvice != nil {
+ return errAdvice, nil
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+
+ format, templateList, maxLength, err := advisor.UnmarshalNamingRulePayloadAsTemplate(ctx.Rule.Type, ctx.Rule.Payload)
+ if err != nil {
+ return nil, err
+ }
+
+ checker := &namingPKConventionChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ format: format,
+ maxLength: maxLength,
+ templateList: templateList,
+ database: ctx.Database,
+ }
+
+ for _, stmtNode := range stmts {
+ ast.Walk(checker, stmtNode)
+ }
+
+ 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 namingPKConventionChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ format string
+ maxLength int
+ templateList []string
+ database *catalog.Database
+}
+
+// Visit implements ast.Visitor interface.
+func (checker *namingPKConventionChecker) Visit(in ast.Node) ast.Visitor {
+ indexDataList := checker.getMetaDataList(in)
+
+ for _, indexData := range indexDataList {
+ regex, err := getTemplateRegexp(checker.format, checker.templateList, indexData.metaData)
+ if err != nil {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.Internal,
+ Title: "Internal error for primary key naming convention rule",
+ Content: fmt.Sprintf("%q meet internal error %q", in.Text(), err.Error()),
+ })
+ continue
+ }
+ if !regex.MatchString(indexData.indexName) {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.NamingPKConventionMismatch,
+ Title: checker.title,
+ Content: fmt.Sprintf(`Primary key in table "%s" mismatches the naming convention, expect %q but found "%s"`, indexData.tableName, regex, indexData.indexName),
+ })
+ }
+ if checker.maxLength > 0 && len(indexData.indexName) > checker.maxLength {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.NamingPKConventionMismatch,
+ Title: checker.title,
+ Content: fmt.Sprintf(`Primary key "%s" in table "%s" mismatches the naming convention, its length should be within %d characters`, indexData.indexName, indexData.tableName, checker.maxLength),
+ })
+ }
+ }
+
+ return checker
+}
+
+// getMetaDataList returns the list of primary key with metadata.
+func (checker *namingPKConventionChecker) getMetaDataList(in ast.Node) []*indexMetaData {
+ var res []*indexMetaData
+ switch node := in.(type) {
+ case *ast.CreateTableStmt:
+ for _, constraint := range node.ConstraintList {
+ if metadata := checker.getPrimaryKeyMetadata(node.Name.Schema, node.Name.Name, constraint); metadata != nil {
+ res = append(res, metadata)
+ }
+ }
+ for _, column := range node.ColumnList {
+ for _, constraint := range column.ConstraintList {
+ if metadata := checker.getPrimaryKeyMetadata(node.Name.Schema, node.Name.Name, constraint); metadata != nil {
+ res = append(res, metadata)
+ }
+ }
+ }
+ case *ast.AddConstraintStmt:
+ constraint := node.Constraint
+ if metadata := checker.getPrimaryKeyMetadata(node.Table.Schema, node.Table.Name, constraint); metadata != nil {
+ res = append(res, metadata)
+ }
+ case *ast.AddColumnListStmt:
+ for _, column := range node.ColumnList {
+ for _, constraint := range column.ConstraintList {
+ if metadata := checker.getPrimaryKeyMetadata(node.Table.Schema, node.Table.Name, constraint); metadata != nil {
+ res = append(res, metadata)
+ }
+ }
+ }
+ case *ast.RenameConstraintStmt:
+ tableName, index := checker.findIndex(node.Table.Schema, node.Table.Name, node.ConstraintName)
+ if index != nil && index.Primary {
+ metaData := map[string]string{
+ advisor.ColumnListTemplateToken: strings.Join(index.ExpressionList, "_"),
+ advisor.TableNameTemplateToken: tableName,
+ }
+ res = append(res, &indexMetaData{
+ indexName: node.NewName,
+ tableName: node.Table.Name,
+ metaData: metaData,
+ })
+ }
+ case *ast.RenameIndexStmt:
+ // "ALTER INDEX name RENAME TO new_name" doesn't take a table name
+ tableName, index := checker.findIndex(node.Table.Schema, "", node.IndexName)
+ if index != nil && index.Primary {
+ metaData := map[string]string{
+ advisor.ColumnListTemplateToken: strings.Join(index.ExpressionList, "_"),
+ advisor.TableNameTemplateToken: tableName,
+ }
+ res = append(res, &indexMetaData{
+ indexName: node.NewName,
+ tableName: tableName,
+ metaData: metaData,
+ })
+ }
+ }
+ return res
+}
+
+// getPrimaryKeyMetadata returns index metadata of a primary key constraint, nil if other constraints.
+func (checker *namingPKConventionChecker) getPrimaryKeyMetadata(schemaName string, tableName string, constraint *ast.ConstraintDef) *indexMetaData {
+ switch constraint.Type {
+ case ast.ConstraintTypePrimary:
+ metaData := map[string]string{
+ advisor.ColumnListTemplateToken: strings.Join(constraint.KeyList, "_"),
+ advisor.TableNameTemplateToken: tableName,
+ }
+ return &indexMetaData{
+ indexName: constraint.Name,
+ tableName: tableName,
+ metaData: metaData,
+ }
+ case ast.ConstraintTypePrimaryUsingIndex:
+ tableName, index := checker.findIndex(schemaName, tableName, constraint.IndexName)
+ if index != nil {
+ metaData := map[string]string{
+ advisor.ColumnListTemplateToken: strings.Join(index.ExpressionList, "_"),
+ advisor.TableNameTemplateToken: tableName,
+ }
+ return &indexMetaData{
+ indexName: constraint.Name,
+ tableName: tableName,
+ metaData: metaData,
+ }
+ }
+ }
+ return nil
+}
+
+// findIndex returns index found in catalogs, nil if not found.
+func (checker *namingPKConventionChecker) findIndex(schemaName string, tableName string, indexName string) (string, *catalog.Index) {
+ return checker.database.FindIndex(&catalog.IndexFind{
+ SchemaName: normalizeSchemaName(schemaName),
+ TableName: tableName,
+ IndexName: indexName,
+ })
+}
diff --git a/plugin/advisor/pg/advisor_naming_primary_key_convention_test.go b/plugin/advisor/pg/advisor_naming_primary_key_convention_test.go
new file mode 100644
index 0000000000..bac81b9798
--- /dev/null
+++ b/plugin/advisor/pg/advisor_naming_primary_key_convention_test.go
@@ -0,0 +1,193 @@
+package pg
+
+import (
+ "encoding/json"
+ "fmt"
+ "strings"
+ "testing"
+
+ "github.com/bytebase/bytebase/plugin/advisor"
+ "github.com/stretchr/testify/require"
+)
+
+func TestNamingPKConvention(t *testing.T) {
+ maxLength := 32
+
+ tests := []advisor.TestCase{
+ {
+ Statement: "ALTER TABLE tech_book ADD CONSTRAINT pk_tech_book_id_name PRIMARY KEY (id, name)",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ Statement: "ALTER TABLE tech_book ADD CONSTRAINT tech_book_id_name PRIMARY KEY (id, name)",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: advisor.NamingPKConventionMismatch,
+ Title: "naming.index.pk",
+ Content: "Primary key in table \"tech_book\" mismatches the naming convention, expect \"^pk_tech_book_id_name$\" but found \"tech_book_id_name\"",
+ },
+ },
+ },
+ {
+ Statement: "CREATE TABLE tech_book(id INT, name VARCHAR(20), CONSTRAINT pk_tech_book_name PRIMARY KEY (name))",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ Statement: "CREATE TABLE tech_book(id INT, name VARCHAR(20), CONSTRAINT tech_book_name PRIMARY KEY (name))",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: advisor.NamingPKConventionMismatch,
+ Title: "naming.index.pk",
+ Content: "Primary key in table \"tech_book\" mismatches the naming convention, expect \"^pk_tech_book_name$\" but found \"tech_book_name\"",
+ },
+ },
+ },
+ {
+ Statement: "CREATE TABLE tech_book(id INT, name VARCHAR(20), PRIMARY KEY (name))",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: advisor.NamingPKConventionMismatch,
+ Title: "naming.index.pk",
+ Content: "Primary key in table \"tech_book\" mismatches the naming convention, expect \"^pk_tech_book_name$\" but found \"\"",
+ },
+ },
+ },
+ {
+ Statement: "CREATE TABLE tech_book(id INT, name VARCHAR(20) PRIMARY KEY)",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: advisor.NamingPKConventionMismatch,
+ Title: "naming.index.pk",
+ Content: "Primary key in table \"tech_book\" mismatches the naming convention, expect \"^pk_tech_book_name$\" but found \"\"",
+ },
+ },
+ },
+ {
+ Statement: "CREATE TABLE tech_book(id INT, name VARCHAR(20), PRIMARY KEY (name))",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: advisor.NamingPKConventionMismatch,
+ Title: "naming.index.pk",
+ Content: "Primary key in table \"tech_book\" mismatches the naming convention, expect \"^pk_tech_book_name$\" but found \"\"",
+ },
+ },
+ },
+ {
+ Statement: fmt.Sprintf(
+ "ALTER TABLE tech_book ADD CONSTRAINT pk_tech_book_%s PRIMARY KEY USING INDEX %s",
+ strings.Join(advisor.MockIndexColumnList, "_"),
+ advisor.MockOldIndexName,
+ ),
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ Statement: fmt.Sprintf(
+ "ALTER TABLE tech_book ADD CONSTRAINT pk_tech_book PRIMARY KEY USING INDEX %s",
+ advisor.MockOldIndexName,
+ ),
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: advisor.NamingPKConventionMismatch,
+ Title: "naming.index.pk",
+ Content: "Primary key in table \"tech_book\" mismatches the naming convention, expect \"^pk_tech_book_id_name$\" but found \"pk_tech_book\"",
+ },
+ },
+ },
+ {
+ Statement: fmt.Sprintf(
+ "ALTER TABLE tech_book RENAME CONSTRAINT %s TO pk_tech_book_%s",
+ advisor.MockOldPostgreSQLPKName,
+ strings.Join(advisor.MockIndexColumnList, "_"),
+ ),
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ Statement: fmt.Sprintf(
+ "ALTER TABLE tech_book RENAME CONSTRAINT %s TO pk_tech_book",
+ advisor.MockOldPostgreSQLPKName,
+ ),
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: advisor.NamingPKConventionMismatch,
+ Title: "naming.index.pk",
+ Content: "Primary key in table \"tech_book\" mismatches the naming convention, expect \"^pk_tech_book_id_name$\" but found \"pk_tech_book\"",
+ },
+ },
+ },
+ {
+ Statement: fmt.Sprintf(
+ "ALTER INDEX %s RENAME TO pk_tech_book_%s",
+ advisor.MockOldPostgreSQLPKName,
+ strings.Join(advisor.MockIndexColumnList, "_"),
+ ),
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ Statement: fmt.Sprintf(
+ "ALTER INDEX %s RENAME TO pk_tech_book",
+ advisor.MockOldPostgreSQLPKName,
+ ),
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: advisor.NamingPKConventionMismatch,
+ Title: "naming.index.pk",
+ Content: "Primary key in table \"tech_book\" mismatches the naming convention, expect \"^pk_tech_book_id_name$\" but found \"pk_tech_book\"",
+ },
+ },
+ },
+ }
+
+ payload, err := json.Marshal(advisor.NamingRulePayload{
+ Format: "^pk_{{table}}_{{column_list}}$",
+ MaxLength: maxLength,
+ })
+ require.NoError(t, err)
+ advisor.RunSchemaReviewRuleTests(t, tests, &NamingPKConventionAdvisor{}, &advisor.SQLReviewRule{
+ Type: advisor.SchemaRulePKNaming,
+ Level: advisor.SchemaRuleLevelError,
+ Payload: string(payload),
+ }, advisor.MockPostgreSQLDatabase)
+}
diff --git a/plugin/advisor/sql_review.go b/plugin/advisor/sql_review.go
index 8e775cdeb2..f9a78a8c3a 100644
--- a/plugin/advisor/sql_review.go
+++ b/plugin/advisor/sql_review.go
@@ -37,6 +37,8 @@ const (
SchemaRuleTableNaming SQLReviewRuleType = "naming.table"
// SchemaRuleColumnNaming enforce the column name format.
SchemaRuleColumnNaming SQLReviewRuleType = "naming.column"
+ // SchemaRulePKNaming enforce the primary key name format.
+ SchemaRulePKNaming SQLReviewRuleType = "naming.index.pk"
// SchemaRuleUKNaming enforce the unique key name format.
SchemaRuleUKNaming SQLReviewRuleType = "naming.index.uk"
// SchemaRuleFKNaming enforce the foreign key name format.
@@ -93,6 +95,10 @@ var (
TableNameTemplateToken: true,
ColumnListTemplateToken: true,
},
+ SchemaRulePKNaming: {
+ TableNameTemplateToken: true,
+ ColumnListTemplateToken: true,
+ },
SchemaRuleUKNaming: {
TableNameTemplateToken: true,
ColumnListTemplateToken: true,