Skip to content

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

feat(advisor): implement PostgreSQL index-total-number-limit rule (#4298)

rebelicead13e922247f
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.go
index fa9d8b46f0..05ff6145cd 100644
--- a/plugin/advisor/advisor.go
+++ b/plugin/advisor/advisor.go
@@ -266,6 +266,9 @@ const (
// PostgreSQLPrimaryKeyTypeAllowlist is an advisor type for postgresql primary key type allowlist.
PostgreSQLPrimaryKeyTypeAllowlist Type = "bb.plugin.advisor.postgresql.index.primary-key-type-allowlist"
+ // PostgreSQLIndexTotalNumberLimit is an advisor type for PostgreSQL index total number limit.
+ PostgreSQLIndexTotalNumberLimit Type = "bb.plugin.advisor.postgresql.index.total-number-limit"
+
// PostgreSQLEncodingAllowlist is an advisor type for PostgreSQL encoding allowlist.
PostgreSQLEncodingAllowlist Type = "bb.plugin.advisor.postgresql.charset.allowlist"
diff --git a/plugin/advisor/catalog/state.go b/plugin/advisor/catalog/state.go
index 7af7e0f6ad..b427863302 100644
--- a/plugin/advisor/catalog/state.go
+++ b/plugin/advisor/catalog/state.go
@@ -131,6 +131,11 @@ type DatabaseState struct {
usable bool
}
+// Usable returns the usable of the database state.
+func (d *DatabaseState) Usable() bool {
+ return d.usable
+}
+
// HasNoTable returns true if the current database has no table.
func (d *DatabaseState) HasNoTable() bool {
for _, schema := range d.schemaSet {
diff --git a/plugin/advisor/pg/advisor_index_total_number_limit.go b/plugin/advisor/pg/advisor_index_total_number_limit.go
new file mode 100644
index 0000000000..b1ed38bdc0
--- /dev/null
+++ b/plugin/advisor/pg/advisor_index_total_number_limit.go
@@ -0,0 +1,169 @@
+package pg
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+ "sort"
+
+ "github.com/bytebase/bytebase/plugin/advisor"
+ "github.com/bytebase/bytebase/plugin/advisor/catalog"
+ "github.com/bytebase/bytebase/plugin/advisor/db"
+ "github.com/bytebase/bytebase/plugin/parser/ast"
+)
+
+var (
+ _ advisor.Advisor = (*IndexTotalNumberLimitAdvisor)(nil)
+ _ ast.Visitor = (*indexTotalNumberLimitChecker)(nil)
+)
+
+func init() {
+ advisor.Register(db.Postgres, advisor.PostgreSQLIndexTotalNumberLimit, &IndexTotalNumberLimitAdvisor{})
+}
+
+// IndexTotalNumberLimitAdvisor is the advisor checking for index total number limit.
+type IndexTotalNumberLimitAdvisor struct {
+}
+
+// Check checks for index total number limit.
+func (*IndexTotalNumberLimitAdvisor) 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
+ }
+ payload, err := advisor.UnmarshalNumberTypeRulePayload(ctx.Rule.Payload)
+ if err != nil {
+ return nil, err
+ }
+ checker := &indexTotalNumberLimitChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ max: payload.Number,
+ catalog: ctx.Catalog,
+ tableLine: make(tableLineMap),
+ }
+
+ if checker.catalog.Final.Usable() {
+ for _, stmt := range stmtList {
+ ast.Walk(checker, stmt)
+ }
+ }
+
+ return checker.generateAdvice(), nil
+}
+
+type tableLine struct {
+ schema string
+ table string
+ line int
+}
+
+type tableLineMap map[string]tableLine
+
+func (m tableLineMap) set(schema string, table string, line int) {
+ if schema == "" {
+ schema = "public"
+ }
+ m[fmt.Sprintf("%q.%q", schema, table)] = tableLine{
+ schema: schema,
+ table: table,
+ line: line,
+ }
+}
+
+type indexTotalNumberLimitChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ max int
+ catalog *catalog.Finder
+ tableLine tableLineMap
+}
+
+func (checker *indexTotalNumberLimitChecker) generateAdvice() []advisor.Advice {
+ var tableList []tableLine
+ for _, table := range checker.tableLine {
+ tableList = append(tableList, table)
+ }
+ sort.Slice(tableList, func(i, j int) bool {
+ return tableList[i].line < tableList[j].line
+ })
+
+ for _, table := range tableList {
+ tableInfo := checker.catalog.Final.FindTable(&catalog.TableFind{
+ SchemaName: table.schema,
+ TableName: table.table,
+ })
+ if tableInfo != nil && tableInfo.CountIndex() > checker.max {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.IndexCountExceedsLimit,
+ Title: checker.title,
+ Content: fmt.Sprintf("The count of index in table %q.%q should be no more than %d, but found %d", table.schema, table.table, checker.max, tableInfo.CountIndex()),
+ Line: table.line,
+ })
+ }
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList
+}
+
+// Visit implements ast.Visitor interface.
+func (checker *indexTotalNumberLimitChecker) Visit(in ast.Node) ast.Visitor {
+ switch node := in.(type) {
+ case *ast.CreateTableStmt:
+ checker.tableLine.set(node.Name.Schema, node.Name.Name, node.LastLine())
+ case *ast.AlterTableStmt:
+ for _, item := range node.AlterItemList {
+ switch itemNode := item.(type) {
+ case *ast.AddColumnListStmt:
+ for _, column := range itemNode.ColumnList {
+ if createIndex(column) {
+ checker.tableLine.set(node.Table.Schema, node.Table.Name, node.LastLine())
+ break
+ }
+ }
+ case *ast.AddConstraintStmt:
+ if createIndex(itemNode.Constraint) {
+ checker.tableLine.set(node.Table.Schema, node.Table.Name, node.LastLine())
+ break
+ }
+ }
+ }
+ case *ast.CreateIndexStmt:
+ checker.tableLine.set(node.Index.Table.Schema, node.Index.Table.Name, node.LastLine())
+ }
+
+ return checker
+}
+
+func createIndex(in ast.Node) bool {
+ switch node := in.(type) {
+ case *ast.ColumnDef:
+ for _, constraint := range node.ConstraintList {
+ switch constraint.Type {
+ case ast.ConstraintTypePrimary, ast.ConstraintTypeUnique:
+ return true
+ }
+ }
+ case *ast.ConstraintDef:
+ switch node.Type {
+ case ast.ConstraintTypePrimary, ast.ConstraintTypeUnique:
+ return true
+ }
+ }
+ return false
+}
diff --git a/plugin/advisor/pg/pg_rules_test.go b/plugin/advisor/pg/pg_rules_test.go
index f80866b0de..5bc190eab3 100644
--- a/plugin/advisor/pg/pg_rules_test.go
+++ b/plugin/advisor/pg/pg_rules_test.go
@@ -39,6 +39,7 @@ func TestPostgreSQLRules(t *testing.T) {
advisor.SchemaRuleStatementInsertDisallowOrderByRand,
advisor.SchemaRuleTableDropNamingConvention,
advisor.SchemaRuleCollationAllowlist,
+ advisor.SchemaRuleIndexTotalNumberLimit,
}
for _, rule := range pgRules {
diff --git a/plugin/advisor/pg/test/index_total_number_limit.yaml b/plugin/advisor/pg/test/index_total_number_limit.yaml
new file mode 100644
index 0000000000..21c866a394
--- /dev/null
+++ b/plugin/advisor/pg/test/index_total_number_limit.yaml
@@ -0,0 +1,55 @@
+- statement: CREATE TABLE t(a int, b int, c int, unique (a, b, c))
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+- statement: CREATE INDEX idx_id_name on tech_book(id, name)
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+- statement: |-
+ CREATE INDEX idx_id_name_1 on tech_book(id, name);
+ CREATE INDEX idx_id_name_2 on tech_book(id, name);
+ CREATE INDEX idx_id_name_3 on tech_book(id, name);
+ CREATE INDEX idx_id_name_4 on tech_book(id, name);
+ CREATE INDEX idx_id_name_5 on tech_book(id, name);
+ want:
+ - status: WARN
+ code: 813
+ title: index.total-number-limit
+ content: The count of index in table "public"."tech_book" should be no more than 5, but found 8
+ line: 5
+- statement: |-
+ CREATE TABLE t(a int PRIMARY KEY, b int, c int);
+ CREATE INDEX idx_a_b_1 on t(a, b);
+ CREATE INDEX idx_a_b_2 on t(a, b);
+ CREATE INDEX idx_a_b_3 on t(a, b);
+ CREATE INDEX idx_a_b_4 on t(a, b);
+ CREATE INDEX idx_a_b_5 on t(a, b);
+ want:
+ - status: WARN
+ code: 813
+ title: index.total-number-limit
+ content: The count of index in table "public"."t" should be no more than 5, but found 6
+ line: 6
+- statement: |-
+ CREATE TABLE t(
+ a int PRIMARY KEY,
+ b int,
+ c int,
+ CONSTRAINT idx_a_b_1 UNIQUE (a, b),
+ CONSTRAINT idx_a_b_2 UNIQUE (a, b),
+ CONSTRAINT idx_a_b_3 UNIQUE (a, b),
+ CONSTRAINT idx_a_b_4 UNIQUE (a, b),
+ CONSTRAINT idx_a_b_5 UNIQUE (a, b));
+ want:
+ - status: WARN
+ code: 813
+ title: index.total-number-limit
+ content: The count of index in table "public"."t" should be no more than 5, but found 6
+ line: 9
diff --git a/plugin/advisor/sql_review.go b/plugin/advisor/sql_review.go
index c94dc7f601..f2b76fd04c 100644
--- a/plugin/advisor/sql_review.go
+++ b/plugin/advisor/sql_review.go
@@ -858,6 +858,8 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine db.Type) (Type, err
switch engine {
case db.MySQL, db.TiDB:
return MySQLIndexTotalNumberLimit, nil
+ case db.Postgres:
+ return PostgreSQLIndexTotalNumberLimit, nil
}
case SchemaRuleStatementDisallowCommit:
switch engine {