diff --git a/advisor/heuristic.go b/advisor/heuristic.go index 258e6149a632d5c14dba6a293e4036eed0464bac..f06bc30f7fb3efc6c860dd4aa72a1638fe0a8183 100644 --- a/advisor/heuristic.go +++ b/advisor/heuristic.go @@ -1253,20 +1253,66 @@ func (q *Query4Audit) RuleImpossibleWhere() Rule { // RuleMeaninglessWhere RES.007 func (q *Query4Audit) RuleMeaninglessWhere() Rule { var rule = q.RuleOK() - // SELECT * FROM tb WHERE 1 + + var where *sqlparser.Where switch n := q.Stmt.(type) { case *sqlparser.Select: - if n.Where != nil { - switch n.Where.Expr.(type) { - case *sqlparser.SQLVal: + where = n.Where + case *sqlparser.Update: + where = n.Where + case *sqlparser.Delete: + where = n.Where + } + if where != nil { + switch v := where.Expr.(type) { + // WHERE 1 + case *sqlparser.SQLVal: + switch string(v.Val) { + case "0", "false": + default: + rule = HeuristicRules["RES.007"] + return rule + } + // WHERE true + case sqlparser.BoolVal: + if v { rule = HeuristicRules["RES.007"] return rule } } } - // 1=1, 0=0 + err := sqlparser.Walk(func(node sqlparser.SQLNode) (kontinue bool, err error) { switch n := node.(type) { + // WHERE id = 1 or 2 + case *sqlparser.OrExpr: + // right always true + switch v := n.Right.(type) { + case *sqlparser.SQLVal: + switch string(v.Val) { + case "0", "false": + default: + rule = HeuristicRules["RES.007"] + } + case sqlparser.BoolVal: + if v { + rule = HeuristicRules["RES.007"] + } + } + // left always true + switch v := n.Left.(type) { + case *sqlparser.SQLVal: + switch string(v.Val) { + case "0", "false": + default: + rule = HeuristicRules["RES.007"] + } + case sqlparser.BoolVal: + if v { + rule = HeuristicRules["RES.007"] + } + } + // 1=1, 0=0 case *sqlparser.ComparisonExpr: factor := false switch n.Operator { @@ -1300,6 +1346,12 @@ func (q *Query4Audit) RuleMeaninglessWhere() Rule { if (bytes.Equal(left, right) && !factor) || (!bytes.Equal(left, right) && factor) { rule = HeuristicRules["RES.007"] } + + // TODO: + // 2 > 1 + // true = 1 + // false != 1 + return false, nil } return true, nil diff --git a/advisor/heuristic_test.go b/advisor/heuristic_test.go index a5a0a8ef95fc633042c89e9a2525c1afb5930e0d..8b57ace8a166a5f5584278d364da911598b18903 100644 --- a/advisor/heuristic_test.go +++ b/advisor/heuristic_test.go @@ -931,8 +931,15 @@ func TestRuleMeaninglessWhere(t *testing.T) { "select * from tbl where 'a' limit 1;", "select * from tbl where 1;", "select * from tbl where 1 limit 1;", + "select * from tbl where id = 1 or 2;", + "select * from tbl where true;", + "select * from tbl where 'true';", }, { + "select * from tbl where false;", + "select * from tbl where 'false';", + "select * from tbl where 0;", + "select * from tbl where '0';", "select * from tbl where 2 = 1;", "select * from tbl where 'b' = 'a';", },