Skip to content

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

feat(schema system): support PG fk name convention rules (#1890)

tison79622e79f877
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.go
index 7b2dd2225f..02a3269f02 100644
--- a/plugin/advisor/advisor.go
+++ b/plugin/advisor/advisor.go
@@ -101,6 +101,9 @@ const (
// PostgreSQLNamingColumnConvention is an advisor type for PostgreSQL column naming convention.
PostgreSQLNamingColumnConvention Type = "bb.plugin.advisor.postgresql.naming.column"
+ // PostgreSQLNamingFKConvention is an advisor type for PostgreSQL foreign key naming convention.
+ PostgreSQLNamingFKConvention Type = "bb.plugin.advisor.postgresql.naming.fk"
+
// PostgreSQLTableRequirePK is an advisor type for PostgreSQL table require primary key.
PostgreSQLTableRequirePK Type = "bb.plugin.advisor.postgresql.table.require-pk"
)
diff --git a/plugin/advisor/pg/advisor_naming_foreign_key_convention.go b/plugin/advisor/pg/advisor_naming_foreign_key_convention.go
new file mode 100644
index 0000000000..d7d27c74c5
--- /dev/null
+++ b/plugin/advisor/pg/advisor_naming_foreign_key_convention.go
@@ -0,0 +1,188 @@
+package pg
+
+import (
+ "fmt"
+ "regexp"
+ "strings"
+
+ "github.com/bytebase/bytebase/plugin/advisor"
+ "github.com/bytebase/bytebase/plugin/parser/ast"
+)
+
+var (
+ _ advisor.Advisor = (*NamingFKConventionAdvisor)(nil)
+)
+
+func init() {
+ advisor.Register(advisor.Postgres, advisor.PostgreSQLNamingFKConvention, &NamingFKConventionAdvisor{})
+}
+
+// NamingFKConventionAdvisor is the advisor checking for foreign key naming convention.
+type NamingFKConventionAdvisor struct {
+}
+
+// Check checks for foreign key naming convention.
+func (check *NamingFKConventionAdvisor) 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 := &namingFKConventionChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ format: format,
+ maxLength: maxLength,
+ templateList: templateList,
+ }
+
+ 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 namingFKConventionChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ format string
+ maxLength int
+ templateList []string
+}
+
+type indexMetaData struct {
+ indexName string
+ tableName string
+ metaData map[string]string
+}
+
+// Visit implements ast.Visitor interface
+func (checker *namingFKConventionChecker) 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 foreign 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.NamingFKConventionMismatch,
+ Title: checker.title,
+ Content: fmt.Sprintf(`Foreign 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.NamingFKConventionMismatch,
+ Title: checker.title,
+ Content: fmt.Sprintf(`Foreign key "%s" in table "%s" mismatches the naming convention, its length should within %d characters`, indexData.indexName, indexData.tableName, checker.maxLength),
+ })
+ }
+ }
+
+ return checker
+}
+
+// getMetaDataList returns the list of foreign key with metadata.
+func (checker *namingFKConventionChecker) getMetaDataList(in ast.Node) []*indexMetaData {
+ var res []*indexMetaData
+ switch node := in.(type) {
+ case *ast.CreateTableStmt:
+ for _, constraint := range node.ConstraintList {
+ if metadata := getForeignKeyMetadata(constraint, node.Name.Name); metadata != nil {
+ res = append(res, metadata)
+ }
+ }
+ for _, column := range node.ColumnList {
+ for _, constraint := range column.ConstraintList {
+ if metadata := getForeignKeyMetadata(constraint, node.Name.Name); metadata != nil {
+ res = append(res, metadata)
+ }
+ }
+ }
+ case *ast.AddConstraintStmt:
+ constraint := node.Constraint
+ if metadata := getForeignKeyMetadata(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 := getForeignKeyMetadata(constraint, node.Table.Name); metadata != nil {
+ res = append(res, metadata)
+ }
+ }
+ }
+ }
+ return res
+}
+
+// getForeignKeyMetadata returns index metadata of a foreign key constraint, nil if other constraints.
+func getForeignKeyMetadata(constraint *ast.ConstraintDef, tableName string) *indexMetaData {
+ if constraint.Type == ast.ConstraintTypeForeign {
+ var referencingColumnList []string
+ for _, key := range constraint.KeyList {
+ referencingColumnList = append(referencingColumnList, key)
+ }
+
+ var referencedColumnList []string
+ for _, key := range constraint.Foreign.ColumnList {
+ referencedColumnList = append(referencedColumnList, key)
+ }
+
+ metaData := map[string]string{
+ advisor.ReferencingTableNameTemplateToken: tableName,
+ advisor.ReferencingColumnNameTemplateToken: strings.Join(referencingColumnList, "_"),
+ advisor.ReferencedTableNameTemplateToken: constraint.Foreign.Table.Name,
+ advisor.ReferencedColumnNameTemplateToken: strings.Join(referencedColumnList, "_"),
+ }
+
+ return &indexMetaData{
+ indexName: constraint.Name,
+ tableName: tableName,
+ metaData: metaData,
+ }
+ }
+ return nil
+}
+
+// getTemplateRegexp formats the template as regex.
+func getTemplateRegexp(template string, templateList []string, tokens map[string]string) (*regexp.Regexp, error) {
+ for _, key := range templateList {
+ if token, ok := tokens[key]; ok {
+ template = strings.ReplaceAll(template, key, token)
+ }
+ }
+
+ return regexp.Compile(template)
+}
diff --git a/plugin/advisor/pg/advisor_naming_foreign_key_convention_test.go b/plugin/advisor/pg/advisor_naming_foreign_key_convention_test.go
new file mode 100644
index 0000000000..7aac517902
--- /dev/null
+++ b/plugin/advisor/pg/advisor_naming_foreign_key_convention_test.go
@@ -0,0 +1,134 @@
+package pg
+
+import (
+ "encoding/json"
+ "fmt"
+ "testing"
+
+ "github.com/bytebase/bytebase/plugin/advisor"
+ "github.com/stretchr/testify/require"
+)
+
+func TestNamingFKConvention(t *testing.T) {
+ invalidFKName := advisor.RandomString(42)
+ maxLength := 32
+
+ tests := []advisor.TestCase{
+ {
+ Statement: "ALTER TABLE tech_book ADD CONSTRAINT fk_tech_book_author_id_author_id FOREIGN KEY (author_id) REFERENCES author (id)",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ Statement: "ALTER TABLE tech_book ADD CONSTRAINT fk_author_id FOREIGN KEY (author_id) REFERENCES author (id)",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: advisor.NamingFKConventionMismatch,
+ Title: "naming.index.fk",
+ Content: "Foreign key in table \"tech_book\" mismatches the naming convention, expect \"^fk_tech_book_author_id_author_id$\" but found \"fk_author_id\"",
+ },
+ },
+ },
+ {
+ Statement: fmt.Sprintf("ALTER TABLE tech_book ADD CONSTRAINT %s FOREIGN KEY (author_id) REFERENCES author (id)", invalidFKName),
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: advisor.NamingFKConventionMismatch,
+ Title: "naming.index.fk",
+ Content: fmt.Sprintf("Foreign key in table \"tech_book\" mismatches the naming convention, expect \"^fk_tech_book_author_id_author_id$\" but found \"%s\"", invalidFKName),
+ },
+ {
+ Status: advisor.Error,
+ Code: advisor.NamingFKConventionMismatch,
+ Title: "naming.index.fk",
+ Content: fmt.Sprintf("Foreign key \"%s\" in table \"tech_book\" mismatches the naming convention, its length should within %d characters", invalidFKName, maxLength),
+ },
+ },
+ },
+ {
+ Statement: "ALTER TABLE tech_book ADD COLUMN author_id INT CONSTRAINT fk_tech_book_author_id_author_id REFERENCES author (id)",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ Statement: "ALTER TABLE tech_book ADD COLUMN author_id INT CONSTRAINT fk_author_id REFERENCES author (id)",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: advisor.NamingFKConventionMismatch,
+ Title: "naming.index.fk",
+ Content: "Foreign key in table \"tech_book\" mismatches the naming convention, expect \"^fk_tech_book_author_id_author_id$\" but found \"fk_author_id\"",
+ },
+ },
+ },
+ {
+ Statement: "CREATE TABLE book(id INT, author_id INT, CONSTRAINT fk_book_author_id_author_id FOREIGN KEY (author_id) REFERENCES author (id))",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ Statement: "CREATE TABLE book(id INT, author_id INT, CONSTRAINT fk_book_author_id FOREIGN KEY (author_id) REFERENCES author (id))",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: advisor.NamingFKConventionMismatch,
+ Title: "naming.index.fk",
+ Content: "Foreign key in table \"book\" mismatches the naming convention, expect \"^fk_book_author_id_author_id$\" but found \"fk_book_author_id\"",
+ },
+ },
+ },
+ {
+ Statement: "CREATE TABLE book(id INT, author_id INT CONSTRAINT fk_book_author_id_author_id REFERENCES author (id))",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ Statement: "CREATE TABLE book(id INT, author_id INT CONSTRAINT fk_book_author_id REFERENCES author (id))",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: advisor.NamingFKConventionMismatch,
+ Title: "naming.index.fk",
+ Content: "Foreign key in table \"book\" mismatches the naming convention, expect \"^fk_book_author_id_author_id$\" but found \"fk_book_author_id\"",
+ },
+ },
+ },
+ }
+
+ payload, err := json.Marshal(advisor.NamingRulePayload{
+ Format: "^fk_{{referencing_table}}_{{referencing_column}}_{{referenced_table}}_{{referenced_column}}$",
+ MaxLength: maxLength,
+ })
+ require.NoError(t, err)
+ advisor.RunSchemaReviewRuleTests(t, tests, &NamingFKConventionAdvisor{}, &advisor.SQLReviewRule{
+ Type: advisor.SchemaRuleFKNaming,
+ Level: advisor.SchemaRuleLevelError,
+ Payload: string(payload),
+ }, &advisor.MockCatalogService{})
+}
diff --git a/plugin/parser/ast/constraint_def.go b/plugin/parser/ast/constraint_def.go
index 9ad29a110e..278d604a50 100644
--- a/plugin/parser/ast/constraint_def.go
+++ b/plugin/parser/ast/constraint_def.go
@@ -44,7 +44,7 @@ type ConstraintDef struct {
KeyList []string
// Foreign is a FOREIGN type specific field.
Foreign *ForeignDef
- // IndexName is a ConstraintTypePrimaryUsingIndex/ConstraintTypeUniqueUsingIndex type specific field.
+ // IndexName is a ConstraintTypePrimaryUsingIndex or ConstraintTypeUniqueUsingIndex type specific field.
// See https://www.postgresql.org/docs/current/sql-altertable.html.
IndexName string
}