Skip to content

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

feat(schema system): support PostgreSQL naming table convention (#1581)

rebeliceeb3a09893d55
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.go
index 6b9167f29f..027671c20f 100644
--- a/plugin/advisor/advisor.go
+++ b/plugin/advisor/advisor.go
@@ -105,6 +105,9 @@ const (
// PostgreSQLSyntax is an advisor type for PostgreSQL syntax.
PostgreSQLSyntax Type = "bb.plugin.advisor.postgresql.syntax"
+
+ // PostgreSQLNamingTableConvention is an advisor type for PostgreSQL table naming convention.
+ PostgreSQLNamingTableConvention Type = "bb.plugin.advisor.postgresql.naming.table"
)
// Advice is the result of an advisor.
@@ -206,7 +209,7 @@ func IsSyntaxCheckSupported(engine db.Type) bool {
// IsSchemaReviewSupported checks the engine type if schema review supports it.
func IsSchemaReviewSupported(engine db.Type) bool {
- if engine == db.MySQL || engine == db.TiDB {
+ if engine == db.MySQL || engine == db.TiDB || engine == db.Postgres {
return true
}
return false
diff --git a/plugin/advisor/pg/advisor_naming_table.go b/plugin/advisor/pg/advisor_naming_table.go
new file mode 100644
index 0000000000..2f13781e5b
--- /dev/null
+++ b/plugin/advisor/pg/advisor_naming_table.go
@@ -0,0 +1,114 @@
+package pg
+
+import (
+ "fmt"
+ "regexp"
+
+ "github.com/auxten/postgresql-parser/pkg/sql/parser"
+ "github.com/auxten/postgresql-parser/pkg/sql/sem/tree"
+ "github.com/auxten/postgresql-parser/pkg/walk"
+ "github.com/bytebase/bytebase/common"
+ "github.com/bytebase/bytebase/plugin/advisor"
+ "github.com/bytebase/bytebase/plugin/db"
+)
+
+var (
+ _ advisor.Advisor = (*NamingTableConventionAdvisor)(nil)
+)
+
+func init() {
+ advisor.Register(db.Postgres, advisor.PostgreSQLNamingTableConvention, &NamingTableConventionAdvisor{})
+}
+
+// NamingTableConventionAdvisor is the advisor checking for table naming convention.
+type NamingTableConventionAdvisor struct {
+}
+
+// Check checks for table naming convention.
+func (adv *NamingTableConventionAdvisor) Check(ctx advisor.Context, statement string) ([]advisor.Advice, error) {
+ stmts, errAdvice := parseStatement(statement)
+ if errAdvice != nil {
+ return errAdvice, nil
+ }
+
+ level, err := advisor.NewStatusBySchemaReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ format, err := advisor.UnamrshalNamingRulePayloadAsRegexp(ctx.Rule.Payload)
+ if err != nil {
+ return nil, err
+ }
+ checker := &namingTableConventionChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ format: format,
+ }
+
+ walker := &walk.AstWalker{
+ Fn: check,
+ }
+
+ for _, stmt := range stmts {
+ if _, err := walker.Walk(parser.Statements{stmt}, checker); err != nil {
+ return nil, err
+ }
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: common.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type namingTableConventionChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ format *regexp.Regexp
+}
+
+func check(ctx interface{}, node interface{}) (stop bool) {
+ checker, ok := ctx.(*namingTableConventionChecker)
+ if !ok {
+ return true
+ }
+
+ var tableNames []string
+
+ switch n := node.(type) {
+ // CREATE TABLE
+ case *tree.CreateTable:
+ tableNames = append(tableNames, n.Table.Table())
+ // ALTER TABLE
+ case *tree.AlterTable:
+ for _, cmd := range n.Cmds {
+ if c, ok := cmd.(*tree.AlterTableRenameTable); ok {
+ tableNames = append(tableNames, c.NewName.Table())
+ }
+ }
+ // RENAME TABLE
+ case *tree.RenameTable:
+ if !n.IsSequence && !n.IsView {
+ tableNames = append(tableNames, string(n.NewName.ToTableName().TableName))
+ }
+ }
+
+ for _, tableName := range tableNames {
+ if !checker.format.MatchString(tableName) {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: common.NamingTableConventionMismatch,
+ Title: checker.title,
+ Content: fmt.Sprintf(`"%s" mismatches table naming convention, naming format should be %q`, tableName, checker.format),
+ })
+ }
+ }
+
+ return false
+}
diff --git a/plugin/advisor/pg/advisor_naming_table_test.go b/plugin/advisor/pg/advisor_naming_table_test.go
new file mode 100644
index 0000000000..ff1f7ededc
--- /dev/null
+++ b/plugin/advisor/pg/advisor_naming_table_test.go
@@ -0,0 +1,92 @@
+package pg
+
+import (
+ "encoding/json"
+ "testing"
+
+ "github.com/bytebase/bytebase/common"
+ "github.com/bytebase/bytebase/plugin/advisor"
+ "github.com/stretchr/testify/require"
+)
+
+func TestPostgreSQLNamingTableConvention(t *testing.T) {
+ tests := []advisor.TestCase{
+ {
+ Statement: "CREATE TABLE \"techBook\"(id int, name varchar(255))",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: common.NamingTableConventionMismatch,
+ Title: "naming.table",
+ Content: "\"techBook\" mismatches table naming convention, naming format should be \"^[a-z]+(_[a-z]+)*$\"",
+ },
+ },
+ },
+ {
+ Statement: "CREATE TABLE _techBook(id int, name varchar(255))",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: common.NamingTableConventionMismatch,
+ Title: "naming.table",
+ Content: "\"_techbook\" mismatches table naming convention, naming format should be \"^[a-z]+(_[a-z]+)*$\"",
+ },
+ },
+ },
+ {
+ // PostgreSQL uses lowercase by default unless using double quotes.
+ Statement: "CREATE TABLE techBook(id int, name varchar(255))",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: common.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ Statement: "CREATE TABLE tech_book(id int, name varchar(255))",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: common.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ Statement: "ALTER TABLE tech_book RENAME TO \"TechBook\"",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: common.NamingTableConventionMismatch,
+ Title: "naming.table",
+ Content: "\"TechBook\" mismatches table naming convention, naming format should be \"^[a-z]+(_[a-z]+)*$\"",
+ },
+ },
+ },
+ {
+ Statement: "ALTER TABLE techBook RENAME TO tech_book",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: common.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ }
+ payload, err := json.Marshal(advisor.NamingRulePayload{
+ Format: "^[a-z]+(_[a-z]+)*$",
+ })
+ require.NoError(t, err)
+ advisor.RunSchemaReviewRuleTests(t, tests, &NamingTableConventionAdvisor{}, &advisor.SchemaReviewRule{
+ Type: advisor.SchemaRuleTableNaming,
+ Level: advisor.SchemaRuleLevelError,
+ Payload: string(payload),
+ }, &advisor.MockCatalogService{})
+
+}
diff --git a/plugin/advisor/schema_review.go b/plugin/advisor/schema_review.go
index a8ea2e8cfb..1b845635c8 100644
--- a/plugin/advisor/schema_review.go
+++ b/plugin/advisor/schema_review.go
@@ -283,6 +283,8 @@ func getAdvisorTypeByRule(ruleType SchemaReviewRuleType, engine db.Type) (Type,
switch engine {
case db.MySQL, db.TiDB:
return MySQLNamingTableConvention, nil
+ case db.Postgres:
+ return PostgreSQLNamingTableConvention, nil
}
case SchemaRuleIDXNaming:
switch engine {
diff --git a/server/sql.go b/server/sql.go
index 300ab2fd4b..bd210aab02 100644
--- a/server/sql.go
+++ b/server/sql.go
@@ -141,10 +141,7 @@ func (s *Server) registerSQLRoutes(g *echo.Group) {
adviceLevel := advisor.Success
adviceList := []advisor.Advice{}
- if s.feature(api.FeatureSchemaReviewPolicy) &&
- // For now we only support MySQL dialect schema review check.
- (instance.Engine == db.MySQL || instance.Engine == db.TiDB) {
-
+ if s.feature(api.FeatureSchemaReviewPolicy) && advisor.IsSchemaReviewSupported(instance.Engine) {
adviceLevel, adviceList, err = s.sqlCheck(ctx, instance, exec)
if err != nil {
return err