Skip to content

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

feat(advisor): implement PG insert-disallow-order-by-rand rule (#4189)

rebelicecde6102b8b04
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.go
index b8f3a358c7..f61b1ca0db 100644
--- a/plugin/advisor/advisor.go
+++ b/plugin/advisor/advisor.go
@@ -257,6 +257,9 @@ const (
// PostgreSQLInsertMustSpecifyColumn is an advisor type for PostgreSQL to enforce column specified.
PostgreSQLInsertMustSpecifyColumn Type = "bb.plugin.advisor.postgresql.insert.must-specify-column"
+ // PostgreSQLInsertDisallowOrderByRand is an advisor type for PostgreSQL to disallow order by rand in INSERT statements.
+ PostgreSQLInsertDisallowOrderByRand Type = "bb.plugin.advisor.postgresql.insert.disallow-order-by-rand"
+
// PostgreSQLIndexKeyNumberLimit is an advisor type for postgresql index key number limit.
PostgreSQLIndexKeyNumberLimit Type = "bb.plugin.advisor.postgresql.index.key-number-limit"
diff --git a/plugin/advisor/pg/advisor_insert_disallow_order_by_rand.go b/plugin/advisor/pg/advisor_insert_disallow_order_by_rand.go
new file mode 100644
index 0000000000..d7958a3795
--- /dev/null
+++ b/plugin/advisor/pg/advisor_insert_disallow_order_by_rand.go
@@ -0,0 +1,90 @@
+package pg
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/bytebase/bytebase/plugin/advisor"
+ "github.com/bytebase/bytebase/plugin/advisor/db"
+ "github.com/bytebase/bytebase/plugin/parser/ast"
+)
+
+var (
+ _ advisor.Advisor = (*InsertDisallowOrderByRandAdvisor)(nil)
+ _ ast.Visitor = (*insertDisallowOrderByRandChecker)(nil)
+)
+
+func init() {
+ advisor.Register(db.Postgres, advisor.PostgreSQLInsertDisallowOrderByRand, &InsertDisallowOrderByRandAdvisor{})
+}
+
+// InsertDisallowOrderByRandAdvisor is the advisor checking for to disallow order by rand in INSERT statements.
+type InsertDisallowOrderByRandAdvisor struct {
+}
+
+// Check checks for to disallow order by rand in INSERT statements.
+func (*InsertDisallowOrderByRandAdvisor) 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 := &insertDisallowOrderByRandChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = advisor.NormalizeStatement(stmt.Text())
+ 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 insertDisallowOrderByRandChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+}
+
+// Visit implements ast.Visitor interface.
+func (checker *insertDisallowOrderByRandChecker) Visit(in ast.Node) ast.Visitor {
+ code := advisor.Ok
+ if insert, ok := in.(*ast.InsertStmt); ok && insert.Select != nil {
+ for _, item := range insert.Select.OrderByClause {
+ if strings.Contains(item.Expression.Text(), "random()") ||
+ strings.Contains(item.Expression.Text(), "random_between()") {
+ code = advisor.InsertUseOrderByRand
+ break
+ }
+ }
+ }
+
+ if code != advisor.Ok {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: code,
+ Title: checker.title,
+ Content: fmt.Sprintf("The INSERT statement uses ORDER BY random() or random_between(), related statement \"%s\"", checker.text),
+ Line: in.LastLine(),
+ })
+ }
+
+ return checker
+}
diff --git a/plugin/advisor/pg/pg_rules_test.go b/plugin/advisor/pg/pg_rules_test.go
index 80a276471d..6fa536bb29 100644
--- a/plugin/advisor/pg/pg_rules_test.go
+++ b/plugin/advisor/pg/pg_rules_test.go
@@ -36,6 +36,7 @@ func TestPostgreSQLRules(t *testing.T) {
advisor.SchemaRuleStatementDisallowCommit,
advisor.SchemaRuleStatementDMLDryRun,
advisor.SchemaRuleStatementInsertMustSpecifyColumn,
+ advisor.SchemaRuleStatementInsertDisallowOrderByRand,
}
for _, rule := range pgRules {
diff --git a/plugin/advisor/pg/test/statement_insert_disallow_order_by_rand.yaml b/plugin/advisor/pg/test/statement_insert_disallow_order_by_rand.yaml
new file mode 100644
index 0000000000..f25b64d047
--- /dev/null
+++ b/plugin/advisor/pg/test/statement_insert_disallow_order_by_rand.yaml
@@ -0,0 +1,14 @@
+- statement: INSERT INTO tech_book VALUES(1, "a")
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+- statement: INSERT INTO tech_book SELECT * FROM tech_book ORDER BY random()
+ want:
+ - status: WARN
+ code: 1108
+ title: statement.insert.disallow-order-by-rand
+ content: The INSERT statement uses ORDER BY random() or random_between(), related statement "INSERT INTO tech_book SELECT * FROM tech_book ORDER BY random()"
+ line: 1
diff --git a/plugin/advisor/sql_review.go b/plugin/advisor/sql_review.go
index 89a0e7c595..58a76b3531 100644
--- a/plugin/advisor/sql_review.go
+++ b/plugin/advisor/sql_review.go
@@ -891,6 +891,8 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine db.Type) (Type, err
switch engine {
case db.MySQL, db.TiDB:
return MySQLInsertDisallowOrderByRand, nil
+ case db.Postgres:
+ return PostgreSQLInsertDisallowOrderByRand, nil
}
case SchemaRuleStatementDisallowLimit:
switch engine {
diff --git a/plugin/parser/ast/select_stmt.go b/plugin/parser/ast/select_stmt.go
index c21c1a19f8..17cb518100 100644
--- a/plugin/parser/ast/select_stmt.go
+++ b/plugin/parser/ast/select_stmt.go
@@ -32,8 +32,9 @@ type SelectStmt struct {
RQuery *SelectStmt
// SELECT fields
- FieldList []ExpressionNode
- WhereClause ExpressionNode
+ FieldList []ExpressionNode
+ WhereClause ExpressionNode
+ OrderByClause []*ByItemDef
// TODO(rebelice): support all expression and remove them.
// We define them because we cannot convert all expression now.
@@ -44,3 +45,10 @@ type SelectStmt struct {
// SubqueryList is the list of the subquery nodes.
SubqueryList []*SubqueryDef
}
+
+// ByItemDef is the struct for item in order by or group by.
+type ByItemDef struct {
+ node
+
+ Expression ExpressionNode
+}
diff --git a/plugin/parser/engine/pg/convert.go b/plugin/parser/engine/pg/convert.go
index 93e290f29c..b2040ab859 100644
--- a/plugin/parser/engine/pg/convert.go
+++ b/plugin/parser/engine/pg/convert.go
@@ -1,6 +1,7 @@
package pg
import (
+ "fmt"
"strconv"
"strings"
@@ -1204,6 +1205,26 @@ func convertSelectStmt(in *pgquery.SelectStmt) (*ast.SelectStmt, error) {
}
selectStmt.SubqueryList = append(selectStmt.SubqueryList, subqueryList...)
}
+
+ // Convert ORDER BY clause.
+ for _, itemNode := range in.SortClause {
+ item, ok := itemNode.Node.(*pgquery.Node_SortBy)
+ if !ok {
+ return nil, parser.NewConvertErrorf("expected SortBy but found %t", itemNode.Node)
+ }
+ expression, _, _, err := convertExpressionNode(item.SortBy.Node)
+ if err != nil {
+ return nil, err
+ }
+
+ text, err := pgquery.DeparseNode(pgquery.DeparseTypeExpr, item.SortBy.Node)
+ if err != nil {
+ fmt.Printf("itemNode %t %v", itemNode.Node, item)
+ return nil, err
+ }
+ expression.SetText(text)
+ selectStmt.OrderByClause = append(selectStmt.OrderByClause, &ast.ByItemDef{Expression: expression})
+ }
return selectStmt, nil
}
diff --git a/plugin/parser/engine/pg/convert_test.go b/plugin/parser/engine/pg/convert_test.go
index a204f3eaea..88efcd5186 100644
--- a/plugin/parser/engine/pg/convert_test.go
+++ b/plugin/parser/engine/pg/convert_test.go
@@ -54,6 +54,11 @@ func newUnconvertedDataType(name []string, text string) *ast.UnconvertedDataType
return tp
}
+func newExpression(expression ast.ExpressionNode, text string) ast.ExpressionNode {
+ expression.SetText(text)
+ return expression
+}
+
func TestPGConvertCreateTableStmt(t *testing.T) {
tests := []testData{
{
@@ -1571,7 +1576,7 @@ func TestPGNotNullStmt(t *testing.T) {
func TestPGSelectStmt(t *testing.T) {
tests := []testData{
{
- stmt: "SELECT public.t.a, t.*, t1.* FROM (SELECT * FROM t) t, t1",
+ stmt: "SELECT public.t.a, t.*, t1.* FROM (SELECT * FROM t) t, t1 ORDER BY t.a, random()",
want: []ast.Node{
&ast.SelectStmt{
SetOperation: ast.SetOperationTypeNone,
@@ -1592,6 +1597,17 @@ func TestPGSelectStmt(t *testing.T) {
ColumnName: "*",
},
},
+ OrderByClause: []*ast.ByItemDef{
+ {
+ Expression: newExpression(&ast.ColumnNameDef{
+ Table: &ast.TableDef{Name: "t"},
+ ColumnName: "a",
+ }, "t.a"),
+ },
+ {
+ Expression: newExpression(&ast.UnconvertedExpressionDef{}, "random()"),
+ },
+ },
SubqueryList: []*ast.SubqueryDef{
{
Select: &ast.SelectStmt{
@@ -1609,7 +1625,7 @@ func TestPGSelectStmt(t *testing.T) {
},
statementList: []parser.SingleSQL{
{
- Text: "SELECT public.t.a, t.*, t1.* FROM (SELECT * FROM t) t, t1",
+ Text: "SELECT public.t.a, t.*, t1.* FROM (SELECT * FROM t) t, t1 ORDER BY t.a, random()",
LastLine: 1,
},
},