Skip to content

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

feat(sql-review): implement postgresql no duplicate columns in the index (#3037)

Vũ Hải Lâm1bf292b43d31
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.go
index acbbae0a0b..36bed5d599 100644
--- a/plugin/advisor/advisor.go
+++ b/plugin/advisor/advisor.go
@@ -245,6 +245,9 @@ const (
// PostgreSQLEncodingAllowlist is an advisor type for PostgreSQL encoding allowlist.
PostgreSQLEncodingAllowlist Type = "bb.plugin.advisor.postgresql.charset.allowlist"
+
+ // PostgreSQLIndexNoDuplicateColumn is an advisor type for Postgresql no duplicate columns in index.
+ PostgreSQLIndexNoDuplicateColumn Type = "bb.plugin.advisor.postgresql.index.no-duplicate-column"
)
// Advice is the result of an advisor.
diff --git a/plugin/advisor/pg/advisor_index_no_duplicate_column.go b/plugin/advisor/pg/advisor_index_no_duplicate_column.go
new file mode 100644
index 0000000000..3f7079b05e
--- /dev/null
+++ b/plugin/advisor/pg/advisor_index_no_duplicate_column.go
@@ -0,0 +1,161 @@
+package pg
+
+import (
+ "fmt"
+
+ "github.com/bytebase/bytebase/plugin/advisor"
+ "github.com/bytebase/bytebase/plugin/advisor/db"
+ "github.com/bytebase/bytebase/plugin/parser/ast"
+)
+
+func init() {
+ advisor.Register(db.Postgres, advisor.PostgreSQLIndexNoDuplicateColumn, &IndexNoDuplicateColumnAdvisor{})
+}
+
+// IndexNoDuplicateColumnAdvisor is the advisor checking for no duplicate columns in index.
+type IndexNoDuplicateColumnAdvisor struct {
+}
+
+// Check checks for no duplicate columns in index.
+func (*IndexNoDuplicateColumnAdvisor) Check(ctx advisor.Context, statement string) ([]advisor.Advice, error) {
+ stmtList, errAdvice := parseStatement(statement)
+ if errAdvice != nil {
+ return errAdvice, nil
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ checker := &indexNoDuplicateColumnChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.LastLine()
+ 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 indexNoDuplicateColumnChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+}
+
+type duplicateColumn struct {
+ table string
+ index string
+ column string
+ constraintType string
+ line int
+}
+
+func (checker *indexNoDuplicateColumnChecker) Visit(node ast.Node) ast.Visitor {
+ var columnList []duplicateColumn
+ switch node := node.(type) {
+ case *ast.CreateTableStmt:
+ for _, constraint := range node.ConstraintList {
+ switch constraint.Type {
+ case ast.ConstraintTypePrimary,
+ ast.ConstraintTypeForeign,
+ ast.ConstraintTypePrimaryUsingIndex,
+ ast.ConstraintTypeUnique,
+ ast.ConstraintTypeUniqueUsingIndex:
+ if column, duplicate := hasDuplicateColumn(constraint.KeyList); duplicate {
+ columnList = append(columnList, duplicateColumn{
+ table: node.Name.Name,
+ index: constraint.Name,
+ column: column,
+ constraintType: contraintsTypeToString(constraint.Type),
+ line: checker.line,
+ })
+ }
+ }
+ }
+ case *ast.CreateIndexStmt:
+ if column, duplicate := hasDuplicateColumn(node.Index.GetKeyNameList()); duplicate {
+ columnList = append(columnList, duplicateColumn{
+ table: node.Index.Table.Name,
+ index: node.Index.Name,
+ column: column,
+ constraintType: "INDEX",
+ line: checker.line,
+ })
+ }
+ case *ast.AlterTableStmt:
+ for _, item := range node.AlterItemList {
+ switch cmd := item.(type) {
+ case *ast.AddConstraintStmt:
+ switch cmd.Constraint.Type {
+ case ast.ConstraintTypePrimary,
+ ast.ConstraintTypeForeign,
+ ast.ConstraintTypePrimaryUsingIndex,
+ ast.ConstraintTypeUnique,
+ ast.ConstraintTypeUniqueUsingIndex:
+ if column, duplicate := hasDuplicateColumn(cmd.Constraint.KeyList); duplicate {
+ columnList = append(columnList, duplicateColumn{
+ table: cmd.Table.Name,
+ index: cmd.Constraint.Name,
+ column: column,
+ constraintType: contraintsTypeToString(cmd.Constraint.Type),
+ line: checker.line,
+ })
+ }
+ }
+ default:
+ continue
+ }
+ }
+ }
+
+ for _, column := range columnList {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.DuplicateColumnInIndex,
+ Title: checker.title,
+ Content: fmt.Sprintf("%s \"%s\" has duplicate column \"%s\".\"%s\"", column.constraintType, column.index, column.table, column.column),
+ Line: column.line,
+ })
+ }
+
+ return checker
+}
+
+func hasDuplicateColumn(keyList []string) (string, bool) {
+ existMap := make(map[string]bool)
+ for _, key := range keyList {
+ if _, isExist := existMap[key]; isExist {
+ return key, true
+ }
+ existMap[key] = true
+ }
+ return "", false
+}
+
+func contraintsTypeToString(constrainType ast.ConstraintType) string {
+ switch constrainType {
+ case ast.ConstraintTypePrimary, ast.ConstraintTypePrimaryUsingIndex:
+ return "PRIMARY KEY"
+ case ast.ConstraintTypeUnique, ast.ConstraintTypeUniqueUsingIndex:
+ return "UNIQUE KEY"
+ case ast.ConstraintTypeForeign:
+ return "FOREIGN KEY"
+ }
+ return "INDEX"
+}
diff --git a/plugin/advisor/pg/advisor_index_no_duplicate_column_test.go b/plugin/advisor/pg/advisor_index_no_duplicate_column_test.go
new file mode 100644
index 0000000000..c54c7f2ad0
--- /dev/null
+++ b/plugin/advisor/pg/advisor_index_no_duplicate_column_test.go
@@ -0,0 +1,99 @@
+package pg
+
+import (
+ "testing"
+
+ "github.com/bytebase/bytebase/plugin/advisor"
+)
+
+func TestIndexNoDuplicateColumn(t *testing.T) {
+ tests := []advisor.TestCase{
+ {
+ Statement: `CREATE TABLE t (a INT, PRIMARY KEY (a));`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ Statement: `CREATE TABLE t (
+ a int,
+ PRIMARY KEY (a, a));`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.DuplicateColumnInIndex,
+ Title: "index.no-duplicate-column",
+ Content: "PRIMARY KEY \"\" has duplicate column \"t\".\"a\"",
+ Line: 3,
+ },
+ },
+ },
+ {
+ Statement: `
+ CREATE TABLE t(a int);
+ CREATE INDEX idx_a on t(a, a);`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.DuplicateColumnInIndex,
+ Title: "index.no-duplicate-column",
+ Content: "INDEX \"idx_a\" has duplicate column \"t\".\"a\"",
+ Line: 3,
+ },
+ },
+ },
+ {
+ Statement: `
+ CREATE TABLE t(a int);
+ ALTER TABLE t ADD CONSTRAINT uk_a UNIQUE (a, a);`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.DuplicateColumnInIndex,
+ Title: "index.no-duplicate-column",
+ Content: "UNIQUE KEY \"uk_a\" has duplicate column \"t\".\"a\"",
+ Line: 3,
+ },
+ },
+ },
+ {
+ Statement: `
+ CREATE TABLE t(a int);
+ ALTER TABLE t ADD CONSTRAINT pk_a PRIMARY KEY (a, a);`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.DuplicateColumnInIndex,
+ Title: "index.no-duplicate-column",
+ Content: "PRIMARY KEY \"pk_a\" has duplicate column \"t\".\"a\"",
+ Line: 3,
+ },
+ },
+ },
+ {
+ Statement: `
+ CREATE TABLE t(a int);
+ ALTER TABLE t ADD CONSTRAINT fk_a FOREIGN KEY (a, a) REFERENCES t1(a, b);`,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.DuplicateColumnInIndex,
+ Title: "index.no-duplicate-column",
+ Content: "FOREIGN KEY \"fk_a\" has duplicate column \"t\".\"a\"",
+ Line: 3,
+ },
+ },
+ },
+ }
+
+ advisor.RunSQLReviewRuleTests(t, tests, &IndexNoDuplicateColumnAdvisor{}, &advisor.SQLReviewRule{
+ Type: advisor.SchemaRuleIndexNoDuplicateColumn,
+ Level: advisor.SchemaRuleLevelWarning,
+ Payload: "",
+ }, advisor.MockPostgreSQLDatabase)
+}
diff --git a/plugin/parser/ast/index_def.go b/plugin/parser/ast/index_def.go
index fa4d5f7053..2d6a7b6fa3 100644
--- a/plugin/parser/ast/index_def.go
+++ b/plugin/parser/ast/index_def.go
@@ -9,3 +9,12 @@ type IndexDef struct {
Unique bool
KeyList []*IndexKeyDef
}
+
+// GetKeyNameList to get the name from KeyList.
+func (id IndexDef) GetKeyNameList() []string {
+ nameList := []string{}
+ for _, key := range id.KeyList {
+ nameList = append(nameList, key.Key)
+ }
+ return nameList
+}