Skip to content

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

feat(advisor): use EXPLAIN to support more INSERT statements for PG insert-row-limit rule (#4155)

rebelicee3722b004938
diff --git a/plugin/advisor/pg/advisor_insert_row_limit.go b/plugin/advisor/pg/advisor_insert_row_limit.go
index e37bdda72c..7c7576e309 100644
--- a/plugin/advisor/pg/advisor_insert_row_limit.go
+++ b/plugin/advisor/pg/advisor_insert_row_limit.go
@@ -1,7 +1,13 @@
package pg
import (
+ "context"
+ "database/sql"
"fmt"
+ "regexp"
+ "strconv"
+
+ "github.com/pkg/errors"
"github.com/bytebase/bytebase/plugin/advisor"
"github.com/bytebase/bytebase/plugin/advisor/db"
@@ -40,6 +46,8 @@ func (*InsertRowLimitAdvisor) Check(ctx advisor.Context, statement string) ([]ad
level: level,
title: string(ctx.Rule.Type),
maxRow: payload.Number,
+ driver: ctx.Driver,
+ ctx: ctx.Context,
}
if payload.Number > 0 {
@@ -68,18 +76,49 @@ type insertRowLimitChecker struct {
text string
line int
maxRow int
+ driver *sql.DB
+ ctx context.Context
}
// Visit implements the ast.Visitor interface.
func (checker *insertRowLimitChecker) Visit(node ast.Node) ast.Visitor {
code := advisor.Ok
- rows := 0
+ rows := int64(0)
n, ok := node.(*ast.InsertStmt)
if ok {
- if len(n.ValueList) > checker.maxRow {
- code = advisor.InsertTooManyRows
- rows = len(n.ValueList)
+ if len(n.ValueList) > 0 {
+ // For INSERT INTO ... VALUES ... statements, use parser only.
+ if len(n.ValueList) > checker.maxRow {
+ code = advisor.InsertTooManyRows
+ rows = int64(len(n.ValueList))
+ }
+ } else if checker.driver != nil {
+ // For INSERT INTO ... SELECT statements, use EXPLAIN.
+ res, err := advisor.Query(checker.ctx, checker.driver, fmt.Sprintf("EXPLAIN %s", node.Text()))
+ if err != nil {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.InsertTooManyRows,
+ Title: checker.title,
+ Content: fmt.Sprintf("\"%s\" dry runs failed: %s", checker.text, err.Error()),
+ Line: checker.line,
+ })
+ } else {
+ rowCount, err := getInsertRows(res)
+ if err != nil {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.Internal,
+ Title: checker.title,
+ Content: fmt.Sprintf("failed to get row count for \"%s\": %s", checker.text, err.Error()),
+ Line: checker.line,
+ })
+ } else if rowCount > int64(checker.maxRow) {
+ code = advisor.InsertTooManyRows
+ rows = rowCount
+ }
+ }
}
}
@@ -88,9 +127,54 @@ func (checker *insertRowLimitChecker) Visit(node ast.Node) ast.Visitor {
Status: checker.level,
Code: code,
Title: checker.title,
- Content: fmt.Sprintf("The value rows in \"%s\" should be no more than %d, but found %d", checker.text, checker.maxRow, rows),
+ Content: fmt.Sprintf("The statement \"%s\" inserts %d rows. The count exceeds %d.", checker.text, rows, checker.maxRow),
Line: checker.line,
})
}
return checker
}
+
+func getInsertRows(res []interface{}) (int64, error) {
+ // the res struct is []interface{}{columnName, columnTable, rowDataList}
+ if len(res) != 3 {
+ return 0, errors.Errorf("expected 3 but got %d", len(res))
+ }
+ rowList, ok := res[2].([]interface{})
+ if !ok {
+ return 0, errors.Errorf("expected []interface{} but got %t", res[2])
+ }
+ // test-bb=# EXPLAIN INSERT INTO t SELECT * FROM t;
+ // QUERY PLAN
+ // -------------------------------------------------------------
+ // Insert on t (cost=0.00..1.03 rows=0 width=0)
+ // -> Seq Scan on t t_1 (cost=0.00..1.03 rows=3 width=520)
+ // (2 rows)
+ if len(rowList) < 2 {
+ return 0, errors.Errorf("not found any data")
+ }
+ // We need the row 2.
+ rowTwo, ok := rowList[1].([]interface{})
+ if !ok {
+ return 0, errors.Errorf("expected []interface{} but got %t", rowList[0])
+ }
+ // PostgreSQL EXPLAIN statement result has one column.
+ if len(rowTwo) != 1 {
+ return 0, errors.Errorf("expected one but got %d", len(rowTwo))
+ }
+ // Get the string value.
+ text, ok := rowTwo[0].(string)
+ if !ok {
+ return 0, errors.Errorf("expected string but got %t", rowTwo[0])
+ }
+
+ rowsRegexp := regexp.MustCompile("rows=([0-9]+)")
+ matches := rowsRegexp.FindStringSubmatch(text)
+ if len(matches) != 2 {
+ return 0, errors.Errorf("failed to find rows in %q", text)
+ }
+ value, err := strconv.ParseInt(matches[1], 10, 64)
+ if err != nil {
+ return 0, errors.Errorf("failed to get integer from %q", matches[1])
+ }
+ return value, nil
+}
diff --git a/plugin/advisor/pg/test/statement_insert_row_limit.yaml b/plugin/advisor/pg/test/statement_insert_row_limit.yaml
index a2f5f7242a..1ea838146b 100644
--- a/plugin/advisor/pg/test/statement_insert_row_limit.yaml
+++ b/plugin/advisor/pg/test/statement_insert_row_limit.yaml
@@ -10,5 +10,12 @@
- status: WARN
code: 1101
title: statement.insert.row-limit
- content: The value rows in "INSERT INTO tech_book values(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e'), (6, 'f')" should be no more than 5, but found 6
+ content: The statement "INSERT INTO tech_book values(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e'), (6, 'f')" inserts 6 rows. The count exceeds 5.
line: 1
+- statement: INSERT INTO tech_book SELECT * FROM tech_book;
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0