Skip to content

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

feat: support PG index-naming rule (#2093)

rebelicefdb115814dc4
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.go
index c2a20a66a5..0b6abbb844 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"
+ // PostgreSQLNamingIndexConvention is an advisor type for PostgreSQL index naming convention.
+ PostgreSQLNamingIndexConvention Type = "bb.plugin.advisor.postgresql.naming.index"
+
// PostgreSQLNamingUKConvention is an advisor type for PostgreSQL unique key naming convention.
PostgreSQLNamingUKConvention Type = "bb.plugin.advisor.postgresql.naming.uk"
diff --git a/plugin/advisor/pg/advisor_naming_index_convention.go b/plugin/advisor/pg/advisor_naming_index_convention.go
new file mode 100644
index 0000000000..c20ec197e4
--- /dev/null
+++ b/plugin/advisor/pg/advisor_naming_index_convention.go
@@ -0,0 +1,151 @@
+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 = (*NamingIndexConventionAdvisor)(nil)
+ _ ast.Visitor = (*namingIndexConventionChecker)(nil)
+)
+
+func init() {
+ advisor.Register(advisor.Postgres, advisor.PostgreSQLNamingIndexConvention, &NamingColumnConventionAdvisor{})
+}
+
+// NamingIndexConventionAdvisor is the advisor checking for index naming convention.
+type NamingIndexConventionAdvisor struct {
+}
+
+// Check checks for index naming convention.
+func (*NamingIndexConventionAdvisor) 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 := &namingIndexConventionChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ format: format,
+ maxLength: maxLength,
+ templateList: templateList,
+ database: ctx.Database,
+ }
+ for _, stmt := range stmts {
+ 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 namingIndexConventionChecker 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 *namingIndexConventionChecker) Visit(node ast.Node) ast.Visitor {
+ indexDataList := checker.getMetaDataList(node)
+
+ 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 index naming convention rule",
+ Content: fmt.Sprintf("%q meet internal error %q", node.Text(), err.Error()),
+ })
+ continue
+ }
+ if !regex.MatchString(indexData.indexName) {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.NamingIndexConventionMismatch,
+ Title: checker.title,
+ Content: fmt.Sprintf("Index in table %q mismatches the naming convention, expect %q but found %q", 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.NamingIndexConventionMismatch,
+ Title: checker.title,
+ Content: fmt.Sprintf("Index %q in table %q mismatches the naming convention, its length should be within %d characters", indexData.indexName, indexData.tableName, checker.maxLength),
+ })
+ }
+ }
+ return checker
+}
+
+func (checker *namingIndexConventionChecker) getMetaDataList(in ast.Node) []*indexMetaData {
+ var res []*indexMetaData
+
+ switch node := in.(type) {
+ 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.RenameIndexStmt:
+ tableName, index := checker.database.FindIndex(&catalog.IndexFind{
+ SchemaName: normalizeSchemaName(node.Table.Schema),
+ TableName: "",
+ IndexName: node.IndexName,
+ })
+ if index != nil && !index.Unique {
+ 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
+}
diff --git a/plugin/advisor/pg/advisor_naming_index_convention_test.go b/plugin/advisor/pg/advisor_naming_index_convention_test.go
new file mode 100644
index 0000000000..a6748f3017
--- /dev/null
+++ b/plugin/advisor/pg/advisor_naming_index_convention_test.go
@@ -0,0 +1,97 @@
+package pg
+
+import (
+ "encoding/json"
+ "fmt"
+ "strings"
+ "testing"
+
+ "github.com/bytebase/bytebase/plugin/advisor"
+ "github.com/stretchr/testify/require"
+)
+
+func TestNamingIndexConvention(t *testing.T) {
+ invalidIndexName := advisor.RandomString(33)
+
+ tests := []advisor.TestCase{
+ {
+ Statement: "CREATE INDEX idx_tech_book_id_name ON tech_book(id, name)",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ Statement: "CREATE INDEX tech_book_id_name ON tech_book(id, name)",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: advisor.NamingIndexConventionMismatch,
+ Title: "naming.index.idx",
+ Content: "Index in table \"tech_book\" mismatches the naming convention, expect \"^idx_tech_book_id_name$\" but found \"tech_book_id_name\"",
+ },
+ },
+ },
+ {
+ Statement: fmt.Sprintf("CREATE INDEX %s ON tech_book(id, name)", invalidIndexName),
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: advisor.NamingIndexConventionMismatch,
+ Title: "naming.index.idx",
+ Content: fmt.Sprintf("Index in table \"tech_book\" mismatches the naming convention, expect \"^idx_tech_book_id_name$\" but found \"%s\"", invalidIndexName),
+ },
+ {
+ Status: advisor.Error,
+ Code: advisor.NamingIndexConventionMismatch,
+ Title: "naming.index.idx",
+ Content: fmt.Sprintf("Index \"%s\" in table \"tech_book\" mismatches the naming convention, its length should be within 32 characters", invalidIndexName),
+ },
+ },
+ },
+ {
+ Statement: fmt.Sprintf(
+ "ALTER INDEX %s RENAME TO idx_tech_book_%s",
+ advisor.MockOldIndexName,
+ strings.Join(advisor.MockIndexColumnList, "_"),
+ ),
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ Statement: fmt.Sprintf(
+ "ALTER INDEX %s RENAME TO idx_tech_book",
+ advisor.MockOldIndexName,
+ ),
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: advisor.NamingIndexConventionMismatch,
+ Title: "naming.index.idx",
+ Content: "Index in table \"tech_book\" mismatches the naming convention, expect \"^idx_tech_book_id_name$\" but found \"idx_tech_book\"",
+ },
+ },
+ },
+ }
+
+ payload, err := json.Marshal(advisor.NamingRulePayload{
+ Format: "^idx_{{table}}_{{column_list}}$",
+ MaxLength: 32,
+ })
+ require.NoError(t, err)
+ advisor.RunSchemaReviewRuleTests(t, tests, &NamingIndexConventionAdvisor{}, &advisor.SQLReviewRule{
+ Type: advisor.SchemaRuleIDXNaming,
+ Level: advisor.SchemaRuleLevelError,
+ Payload: string(payload),
+ }, advisor.MockPostgreSQLDatabase)
+}