Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(advisor): implement PostgreSQL create-index-concurrently rule (#4346)
rebelice33744648127f
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.goindex f363c4983e..08decf9e5a 100644--- a/plugin/advisor/advisor.go+++ b/plugin/advisor/advisor.go@@ -275,6 +275,9 @@ const (// PostgreSQLIndexNoDuplicateColumn is an advisor type for Postgresql no duplicate columns in index.PostgreSQLIndexNoDuplicateColumn Type = "bb.plugin.advisor.postgresql.index.no-duplicate-column"+ // PostgreSQLCreateIndexConcurrently is an advisor type for PostgreSQL to create index concurrently.+ PostgreSQLCreateIndexConcurrently Type = "bb.plugin.advisor.postgresql.index.create-concurrently"+// PostgreSQLColumnTypeDisallowList is an advisor type for Postgresql column type disallow list.PostgreSQLColumnTypeDisallowList Type = "bb.plugin.advisor.postgresql.column.type-disallow-list"diff --git a/plugin/advisor/code.go b/plugin/advisor/code.goindex 47a11488a0..76cb5dd2a7 100644--- a/plugin/advisor/code.go+++ b/plugin/advisor/code.go@@ -105,6 +105,7 @@ const (SpatialIndexKeyNullable Code = 811DuplicateColumnInIndex Code = 812IndexCountExceedsLimit Code = 813+ CreateIndexUnconcurrently Code = 814// 1001 ~ 1099 charset error code.DisabledCharset Code = 1001diff --git a/plugin/advisor/pg/advisor_index_create_concurrently.go b/plugin/advisor/pg/advisor_index_create_concurrently.gonew file mode 100644index 0000000000..3af37cb8d5--- /dev/null+++ b/plugin/advisor/pg/advisor_index_create_concurrently.go@@ -0,0 +1,76 @@+package pg++// Framework code is generated by the generator.++import (+ "github.com/bytebase/bytebase/plugin/advisor"+ "github.com/bytebase/bytebase/plugin/advisor/db"+ "github.com/bytebase/bytebase/plugin/parser/ast"+)++var (+ _ advisor.Advisor = (*IndexCreateConcurrentlyAdvisor)(nil)+ _ ast.Visitor = (*indexCreateConcurrentlyChecker)(nil)+)++func init() {+ advisor.Register(db.Postgres, advisor.PostgreSQLCreateIndexConcurrently, &IndexCreateConcurrentlyAdvisor{})+}++// IndexCreateConcurrentlyAdvisor is the advisor checking for to create index concurrently.+type IndexCreateConcurrentlyAdvisor struct {+}++// Check checks for to create index concurrently.+func (*IndexCreateConcurrentlyAdvisor) 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 := &indexCreateConcurrentlyChecker{+ level: level,+ title: string(ctx.Rule.Type),+ }++ for _, stmt := range stmtList {+ 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 indexCreateConcurrentlyChecker struct {+ adviceList []advisor.Advice+ level advisor.Status+ title string+}++// Visit implements ast.Visitor interface.+func (checker *indexCreateConcurrentlyChecker) Visit(in ast.Node) ast.Visitor {+ if node, ok := in.(*ast.CreateIndexStmt); ok {+ if !node.Concurrently {+ checker.adviceList = append(checker.adviceList, advisor.Advice{+ Status: checker.level,+ Code: advisor.CreateIndexUnconcurrently,+ Title: checker.title,+ Content: "Creating indexes will block writes on the table, unless use CONCURRENTLY",+ Line: in.LastLine(),+ })+ }+ }++ return checker+}diff --git a/plugin/advisor/pg/pg_rules_test.go b/plugin/advisor/pg/pg_rules_test.goindex 071711ab15..b87677d432 100644--- a/plugin/advisor/pg/pg_rules_test.go+++ b/plugin/advisor/pg/pg_rules_test.go@@ -44,6 +44,7 @@ func TestPostgreSQLRules(t *testing.T) {advisor.SchemaRuleStatementMergeAlterTable,advisor.SchemaRuleColumnRequireDefault,advisor.SchemaRuleStatementDisallowAddColumnWithDefault,+ advisor.SchemaRuleCreateIndexConcurrently,}for _, rule := range pgRules {diff --git a/plugin/advisor/pg/test/index_create_concurrently.yaml b/plugin/advisor/pg/test/index_create_concurrently.yamlnew file mode 100644index 0000000000..2b209ee2d5--- /dev/null+++ b/plugin/advisor/pg/test/index_create_concurrently.yaml@@ -0,0 +1,14 @@+- statement: create index on tech_book(id);+ want:+ - status: WARN+ code: 814+ title: index.create-concurrently+ content: Creating indexes will block writes on the table, unless use CONCURRENTLY+ line: 1+- statement: create index concurrently on tech_book(id);+ want:+ - status: SUCCESS+ code: 0+ title: OK+ content: ""+ line: 0diff --git a/plugin/advisor/sql_review.go b/plugin/advisor/sql_review.goindex ec8e62ad16..f707649769 100644--- a/plugin/advisor/sql_review.go+++ b/plugin/advisor/sql_review.go@@ -138,6 +138,8 @@ const (SchemaRuleIndexTotalNumberLimit SQLReviewRuleType = "index.total-number-limit"// SchemaRuleIndexPrimaryKeyTypeAllowlist enforce the primary key type allowlist.SchemaRuleIndexPrimaryKeyTypeAllowlist SQLReviewRuleType = "index.primary-key-type-allowlist"+ // SchemaRuleCreateIndexConcurrently require creating indexes concurrently.+ SchemaRuleCreateIndexConcurrently SQLReviewRuleType = "index.create-concurrently"// SchemaRuleCharsetAllowlist enforce the charset allowlist.SchemaRuleCharsetAllowlist SQLReviewRuleType = "system.charset.allowlist"@@ -900,6 +902,10 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine db.Type) (Type, errif engine == db.Postgres {return PostgreSQLPrimaryKeyTypeAllowlist, nil}+ case SchemaRuleCreateIndexConcurrently:+ if engine == db.Postgres {+ return PostgreSQLCreateIndexConcurrently, nil+ }case SchemaRuleStatementInsertRowLimit:switch engine {case db.MySQL:diff --git a/plugin/advisor/utils_for_tests.go b/plugin/advisor/utils_for_tests.goindex b9c0812f14..54f1f0476f 100644--- a/plugin/advisor/utils_for_tests.go+++ b/plugin/advisor/utils_for_tests.go@@ -381,6 +381,7 @@ func SetDefaultSQLReviewRulePayload(ruleTp SQLReviewRuleType) (string, error) {SchemaRuleIndexNoDuplicateColumn,SchemaRuleIndexPKTypeLimit,SchemaRuleStatementDisallowAddColumnWithDefault,+ SchemaRuleCreateIndexConcurrently,SchemaRuleIndexTypeNoBlob:case SchemaRuleTableDropNamingConvention:payload, err = json.Marshal(NamingRulePayload{diff --git a/plugin/parser/ast/create_index_stmt.go b/plugin/parser/ast/create_index_stmt.goindex 1c67079e82..e8d14f9f98 100644--- a/plugin/parser/ast/create_index_stmt.go+++ b/plugin/parser/ast/create_index_stmt.go@@ -4,12 +4,13 @@ package ast// TODO(rebelice): fully support CREATE INDEX statements.// Currently, only support:// ```-// CREATE [ UNIQUE ] INDEX [ [ IF NOT EXISTS ] name ] ON table_name [ USING method ]+// CREATE [ UNIQUE ] INDEX [ CONCURRENTLY ] [ [ IF NOT EXISTS ] name ] ON table_name [ USING method ]// ( { column_name | ( expression ) } [ ASC | DESC ] [ NULLS { FIRST | LAST } ] [, ...] )// ```.type CreateIndexStmt struct {ddl- Index *IndexDef- IfNotExists bool+ Index *IndexDef+ IfNotExists bool+ Concurrently bool}diff --git a/plugin/parser/engine/pg/convert.go b/plugin/parser/engine/pg/convert.goindex 65cbbfcbab..b69d6c2a26 100644--- a/plugin/parser/engine/pg/convert.go+++ b/plugin/parser/engine/pg/convert.go@@ -272,7 +272,7 @@ func convert(node *pgquery.Node, statement parser.SingleSQL) (res ast.Node, errindexDef.KeyList = append(indexDef.KeyList, indexKey)}- return &ast.CreateIndexStmt{Index: indexDef, IfNotExists: in.IndexStmt.IfNotExists}, nil+ return &ast.CreateIndexStmt{Index: indexDef, IfNotExists: in.IndexStmt.IfNotExists, Concurrently: in.IndexStmt.Concurrent}, nilcase *pgquery.Node_DropStmt:switch in.DropStmt.RemoveType {case pgquery.ObjectType_OBJECT_INDEX:diff --git a/plugin/parser/engine/pg/convert_test.go b/plugin/parser/engine/pg/convert_test.goindex 5695a1ec15..ecce185be4 100644--- a/plugin/parser/engine/pg/convert_test.go+++ b/plugin/parser/engine/pg/convert_test.go@@ -783,10 +783,11 @@ func TestPGRenameConstraintStmt(t *testing.T) {func TestPGCreateIndexStmt(t *testing.T) {tests := []testData{{- stmt: "CREATE INDEX IF NOT EXISTS idx_id ON tech_book ((id+1) DESC, name)",+ stmt: "CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_id ON tech_book ((id+1) DESC, name)",want: []ast.Node{&ast.CreateIndexStmt{- IfNotExists: true,+ IfNotExists: true,+ Concurrently: true,Index: &ast.IndexDef{Name: "idx_id",Table: &ast.TableDef{Name: "tech_book"},@@ -810,7 +811,7 @@ func TestPGCreateIndexStmt(t *testing.T) {},statementList: []parser.SingleSQL{{- Text: "CREATE INDEX IF NOT EXISTS idx_id ON tech_book ((id+1) DESC, name)",+ Text: "CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_id ON tech_book ((id+1) DESC, name)",LastLine: 1,},},diff --git a/plugin/parser/engine/pg/deparse.go b/plugin/parser/engine/pg/deparse.goindex 56cb80415e..ad281536b3 100644--- a/plugin/parser/engine/pg/deparse.go+++ b/plugin/parser/engine/pg/deparse.go@@ -168,6 +168,12 @@ func deparseCreateIndex(context parser.DeparseContext, in *ast.CreateIndexStmt,return err}+ if in.Concurrently {+ if _, err := buf.WriteString("CONCURRENTLY "); err != nil {+ return err+ }+ }+if in.IfNotExists {if _, err := buf.WriteString("IF NOT EXISTS "); err != nil {return errdiff --git a/plugin/parser/engine/pg/test-data/test_create_index_data.yaml b/plugin/parser/engine/pg/test-data/test_create_index_data.yamlindex d64b0a3621..52239bad6c 100644--- a/plugin/parser/engine/pg/test-data/test_create_index_data.yaml+++ b/plugin/parser/engine/pg/test-data/test_create_index_data.yaml@@ -1,5 +1,5 @@-- stmt: create index idx_1 on public.t using btree (a, b, c)- want: CREATE INDEX "idx_1" ON "public"."t" USING btree (a, b, c);+- stmt: create index concurrently idx_1 on public.t using btree (a, b, c)+ want: CREATE INDEX CONCURRENTLY "idx_1" ON "public"."t" USING btree (a, b, c);- stmt: create unique index if not exists idx_1 on public.t(a nulls first, b desc nulls last, c asc)want: CREATE UNIQUE INDEX IF NOT EXISTS "idx_1" ON "public"."t" USING btree (a NULLS FIRST, b DESC NULLS LAST, c);- stmt: create index if not exists idx_1 on public.t using hash (a, b, c)