Skip to content

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

feat(schema system): support PG uk name convention rules (#1983)

tison112a8f1b71ad
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.go
index 2634cd6c41..c168955060 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"
+ // PostgreSQLNamingUKConvention is an advisor type for PostgreSQL unique key naming convention.
+ PostgreSQLNamingUKConvention Type = "bb.plugin.advisor.postgresql.naming.uk"
+
// PostgreSQLNamingFKConvention is an advisor type for PostgreSQL foreign key naming convention.
PostgreSQLNamingFKConvention Type = "bb.plugin.advisor.postgresql.naming.fk"
diff --git a/plugin/advisor/pg/advisor_naming_unique_key_convention.go b/plugin/advisor/pg/advisor_naming_unique_key_convention.go
new file mode 100644
index 0000000000..6a824fe5a5
--- /dev/null
+++ b/plugin/advisor/pg/advisor_naming_unique_key_convention.go
@@ -0,0 +1,234 @@
+package pg
+
+import (
+ "context"
+ "fmt"
+ "log"
+ "strings"
+
+ "github.com/bytebase/bytebase/plugin/advisor"
+ "github.com/bytebase/bytebase/plugin/advisor/catalog"
+ "github.com/bytebase/bytebase/plugin/parser/ast"
+)
+
+var (
+ _ advisor.Advisor = (*NamingUKConventionAdvisor)(nil)
+)
+
+func init() {
+ advisor.Register(advisor.Postgres, advisor.PostgreSQLNamingUKConvention, &NamingUKConventionAdvisor{})
+}
+
+// NamingUKConventionAdvisor is the advisor checking for unique key naming convention.
+type NamingUKConventionAdvisor struct {
+}
+
+// Check checks for unique key naming convention.
+func (check *NamingUKConventionAdvisor) Check(ctx advisor.Context, statement string) ([]advisor.Advice, error) {
+ root, 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 := &namingUKConventionChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ format: format,
+ maxLength: maxLength,
+ templateList: templateList,
+ catalog: ctx.Catalog,
+ }
+
+ for _, stmtNode := range root {
+ 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 namingUKConventionChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ format string
+ maxLength int
+ templateList []string
+ catalog catalog.Catalog
+}
+
+// Visit implements ast.Visitor interface
+func (checker *namingUKConventionChecker) 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 unique 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.NamingUKConventionMismatch,
+ Title: checker.title,
+ Content: fmt.Sprintf(`Unique 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.NamingUKConventionMismatch,
+ Title: checker.title,
+ Content: fmt.Sprintf(`Unique 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 unique key with metadata.
+func (checker *namingUKConventionChecker) getMetaDataList(in ast.Node) []*indexMetaData {
+ var res []*indexMetaData
+ switch node := in.(type) {
+ case *ast.CreateTableStmt:
+ for _, constraint := range node.ConstraintList {
+ if metadata := checker.getUniqueKeyMetadata(constraint, node.Name.Name); metadata != nil {
+ res = append(res, metadata)
+ }
+ }
+ for _, column := range node.ColumnList {
+ for _, constraint := range column.ConstraintList {
+ if metadata := checker.getUniqueKeyMetadata(constraint, node.Name.Name); metadata != nil {
+ res = append(res, metadata)
+ }
+ }
+ }
+ case *ast.AddConstraintStmt:
+ constraint := node.Constraint
+ if metadata := checker.getUniqueKeyMetadata(constraint, node.Table.Name); metadata != nil {
+ res = append(res, metadata)
+ }
+ case *ast.AddColumnListStmt:
+ for _, column := range node.ColumnList {
+ for _, constraint := range column.ConstraintList {
+ if metadata := checker.getUniqueKeyMetadata(constraint, node.Table.Name); metadata != nil {
+ res = append(res, metadata)
+ }
+ }
+ }
+ case *ast.CreateIndexStmt:
+ if node.Index.Unique {
+ var columnList []string
+ for _, key := range node.Index.KeyList {
+ columnList = append(columnList, key.Key)
+ }
+ metaData := map[string]string{
+ advisor.ColumnListTemplateToken: strings.Join(columnList, "_"),
+ advisor.TableNameTemplateToken: node.Index.Table.Name,
+ }
+ res = append(res, &indexMetaData{
+ indexName: node.Index.Name,
+ tableName: node.Index.Table.Name,
+ metaData: metaData,
+ })
+ }
+ case *ast.RenameConstraintStmt:
+ if index := checker.findIndex(context.Background(), node.Table.Name, node.ConstraintName); index != nil && index.Unique && !index.Primary {
+ metaData := map[string]string{
+ advisor.ColumnListTemplateToken: strings.Join(index.ColumnExpressions, "_"),
+ advisor.TableNameTemplateToken: node.Table.Name,
+ }
+ res = append(res, &indexMetaData{
+ indexName: node.NewName,
+ tableName: node.Table.Name,
+ metaData: metaData,
+ })
+ }
+ case *ast.RenameIndexStmt:
+ // TODO(rebelice): "ALTER INDEX name RENAME TO new_name" doesn't take a table name
+ if index := checker.findIndex(context.Background(), "", node.IndexName); index != nil && index.Unique && !index.Primary {
+ metaData := map[string]string{
+ advisor.ColumnListTemplateToken: strings.Join(index.ColumnExpressions, "_"),
+ advisor.TableNameTemplateToken: index.TableName,
+ }
+ res = append(res, &indexMetaData{
+ indexName: node.NewName,
+ tableName: index.TableName,
+ metaData: metaData,
+ })
+ }
+ }
+ return res
+}
+
+// getUniqueKeyMetadata returns index metadata of a unique key constraint, nil if other constraints.
+func (checker *namingUKConventionChecker) getUniqueKeyMetadata(constraint *ast.ConstraintDef, tableName string) *indexMetaData {
+ switch constraint.Type {
+ case ast.ConstraintTypeUnique:
+ metaData := map[string]string{
+ advisor.ColumnListTemplateToken: strings.Join(constraint.KeyList, "_"),
+ advisor.TableNameTemplateToken: tableName,
+ }
+ return &indexMetaData{
+ indexName: constraint.Name,
+ tableName: tableName,
+ metaData: metaData,
+ }
+ case ast.ConstraintTypeUniqueUsingIndex:
+ if index := checker.findIndex(context.Background(), tableName, constraint.IndexName); index != nil {
+ metaData := map[string]string{
+ advisor.ColumnListTemplateToken: strings.Join(index.ColumnExpressions, "_"),
+ 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 *namingUKConventionChecker) findIndex(ctx context.Context, tableName string, indexName string) *catalog.Index {
+ index, err := checker.catalog.FindIndex(ctx, &catalog.IndexFind{
+ TableName: tableName,
+ IndexName: indexName,
+ })
+ if err != nil {
+ log.Printf(
+ "Cannot find index %s in table %s with error %v\n",
+ indexName,
+ tableName,
+ err,
+ )
+ return nil
+ }
+ return index
+}
diff --git a/plugin/advisor/pg/advisor_naming_unique_key_convention_test.go b/plugin/advisor/pg/advisor_naming_unique_key_convention_test.go
new file mode 100644
index 0000000000..93b89960bb
--- /dev/null
+++ b/plugin/advisor/pg/advisor_naming_unique_key_convention_test.go
@@ -0,0 +1,233 @@
+package pg
+
+import (
+ "encoding/json"
+ "fmt"
+ "strings"
+ "testing"
+
+ "github.com/bytebase/bytebase/plugin/advisor"
+ "github.com/stretchr/testify/require"
+)
+
+func TestNamingUKConvention(t *testing.T) {
+ invalidUKName := advisor.RandomString(42)
+ maxLength := 32
+
+ tests := []advisor.TestCase{
+ {
+ Statement: "CREATE UNIQUE INDEX uk_tech_book_id_name ON tech_book(id, name)",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ Statement: "CREATE UNIQUE INDEX tech_book_id_name ON tech_book(id, name)",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: advisor.NamingUKConventionMismatch,
+ Title: "naming.index.uk",
+ Content: "Unique key in table \"tech_book\" mismatches the naming convention, expect \"^uk_tech_book_id_name$\" but found \"tech_book_id_name\"",
+ },
+ },
+ },
+ {
+ Statement: fmt.Sprintf("CREATE UNIQUE INDEX %s ON tech_book(id, name)", invalidUKName),
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: advisor.NamingUKConventionMismatch,
+ Title: "naming.index.uk",
+ Content: fmt.Sprintf("Unique key in table \"tech_book\" mismatches the naming convention, expect \"^uk_tech_book_id_name$\" but found \"%s\"", invalidUKName),
+ },
+ {
+ Status: advisor.Error,
+ Code: advisor.NamingUKConventionMismatch,
+ Title: "naming.index.uk",
+ Content: fmt.Sprintf("Unique key \"%s\" in table \"tech_book\" mismatches the naming convention, its length should be within %d characters", invalidUKName, maxLength),
+ },
+ },
+ },
+ {
+ Statement: "ALTER TABLE tech_book ADD CONSTRAINT uk_tech_book_id_name UNIQUE (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 UNIQUE (id, name)",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: advisor.NamingUKConventionMismatch,
+ Title: "naming.index.uk",
+ Content: "Unique key in table \"tech_book\" mismatches the naming convention, expect \"^uk_tech_book_id_name$\" but found \"tech_book_id_name\"",
+ },
+ },
+ },
+ {
+ Statement: "CREATE TABLE tech_book(id INT PRIMARY KEY, name VARCHAR(20), CONSTRAINT uk_tech_book_name UNIQUE (name))",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ Statement: "CREATE TABLE tech_book(id INT PRIMARY KEY, name VARCHAR(20), CONSTRAINT tech_book_name UNIQUE (name))",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: advisor.NamingUKConventionMismatch,
+ Title: "naming.index.uk",
+ Content: "Unique key in table \"tech_book\" mismatches the naming convention, expect \"^uk_tech_book_name$\" but found \"tech_book_name\"",
+ },
+ },
+ },
+ {
+ Statement: "CREATE TABLE tech_book(id INT PRIMARY KEY, name VARCHAR(20), UNIQUE (name))",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: advisor.NamingUKConventionMismatch,
+ Title: "naming.index.uk",
+ Content: "Unique key in table \"tech_book\" mismatches the naming convention, expect \"^uk_tech_book_name$\" but found \"\"",
+ },
+ },
+ },
+ {
+ Statement: "CREATE TABLE tech_book(id INT PRIMARY KEY, name VARCHAR(20) UNIQUE)",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: advisor.NamingUKConventionMismatch,
+ Title: "naming.index.uk",
+ Content: "Unique key in table \"tech_book\" mismatches the naming convention, expect \"^uk_tech_book_name$\" but found \"\"",
+ },
+ },
+ },
+ {
+ Statement: "CREATE TABLE tech_book(id INT PRIMARY KEY, name VARCHAR(20), UNIQUE (name))",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: advisor.NamingUKConventionMismatch,
+ Title: "naming.index.uk",
+ Content: "Unique key in table \"tech_book\" mismatches the naming convention, expect \"^uk_tech_book_name$\" but found \"\"",
+ },
+ },
+ },
+ {
+ Statement: fmt.Sprintf(
+ "ALTER TABLE tech_book ADD CONSTRAINT uk_tech_book_%s UNIQUE 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 uk_tech_book UNIQUE USING INDEX %s",
+ advisor.MockOldIndexName,
+ ),
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: advisor.NamingUKConventionMismatch,
+ Title: "naming.index.uk",
+ Content: "Unique key in table \"tech_book\" mismatches the naming convention, expect \"^uk_tech_book_id_name$\" but found \"uk_tech_book\"",
+ },
+ },
+ },
+ {
+ Statement: fmt.Sprintf(
+ "ALTER TABLE tech_book RENAME CONSTRAINT %s TO uk_tech_book_%s",
+ advisor.MockOldUKName,
+ 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 uk_tech_book",
+ advisor.MockOldUKName,
+ ),
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: advisor.NamingUKConventionMismatch,
+ Title: "naming.index.uk",
+ Content: "Unique key in table \"tech_book\" mismatches the naming convention, expect \"^uk_tech_book_id_name$\" but found \"uk_tech_book\"",
+ },
+ },
+ },
+ {
+ Statement: fmt.Sprintf(
+ "ALTER INDEX %s RENAME TO uk_tech_book_%s",
+ advisor.MockOldUKName,
+ strings.Join(advisor.MockIndexColumnList, "_"),
+ ),
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ Statement: fmt.Sprintf(
+ "ALTER INDEX %s RENAME TO uk_tech_book",
+ advisor.MockOldUKName,
+ ),
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: advisor.NamingUKConventionMismatch,
+ Title: "naming.index.uk",
+ Content: "Unique key in table \"tech_book\" mismatches the naming convention, expect \"^uk_tech_book_id_name$\" but found \"uk_tech_book\"",
+ },
+ },
+ },
+ }
+
+ payload, err := json.Marshal(advisor.NamingRulePayload{
+ Format: "^uk_{{table}}_{{column_list}}$",
+ MaxLength: maxLength,
+ })
+ require.NoError(t, err)
+ advisor.RunSchemaReviewRuleTests(t, tests, &NamingUKConventionAdvisor{}, &advisor.SQLReviewRule{
+ Type: advisor.SchemaRuleUKNaming,
+ Level: advisor.SchemaRuleLevelError,
+ Payload: string(payload),
+ }, &advisor.MockCatalogService{})
+}
diff --git a/plugin/advisor/utils_for_tests.go b/plugin/advisor/utils_for_tests.go
index fa8a1070b9..8290010e28 100644
--- a/plugin/advisor/utils_for_tests.go
+++ b/plugin/advisor/utils_for_tests.go
@@ -22,6 +22,8 @@ const (
MockOldUKName = "old_uk"
// MockOldPKName is the mock old foreign key for test.
MockOldPKName = "PRIMARY"
+ // MockTableName is the mock table for test.
+ MockTableName = "tech_book"
)
var (
@@ -37,18 +39,21 @@ func (*MockCatalogService) FindIndex(_ context.Context, find *catalog.IndexFind)
case MockOldIndexName:
return &catalog.Index{
Name: MockOldIndexName,
+ TableName: MockTableName,
ColumnExpressions: MockIndexColumnList,
}, nil
case MockOldUKName:
return &catalog.Index{
Unique: true,
Name: MockOldIndexName,
+ TableName: MockTableName,
ColumnExpressions: MockIndexColumnList,
}, nil
case MockOldPKName:
return &catalog.Index{
Unique: true,
Name: MockOldPKName,
+ TableName: MockTableName,
ColumnExpressions: MockIndexColumnList,
}, nil
}