Skip to content

Commit

Permalink
feat: add AND rewriter to drop some unnecessary predicates
Browse files Browse the repository at this point in the history
Signed-off-by: Manan Gupta <[email protected]>
  • Loading branch information
GuptaManan100 committed Oct 20, 2023
1 parent b1432c4 commit fd79f83
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
4 changes: 2 additions & 2 deletions go/vt/vtgate/planbuilder/testdata/postprocess_cases.json
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@
"Sharded": true
},
"FieldQuery": "select `user`.col1 as a, `user`.col2 from `user` where 1 != 1",
"Query": "select `user`.col1 as a, `user`.col2 from `user` where `user`.col1 = 1 and `user`.col1 = `user`.col2 and 1 = 1",
"Query": "select `user`.col1 as a, `user`.col2 from `user` where `user`.col1 = 1 and `user`.col1 = `user`.col2",
"Table": "`user`"
},
{
Expand All @@ -99,7 +99,7 @@
"Sharded": true
},
"FieldQuery": "select user_extra.col3 from user_extra where 1 != 1",
"Query": "select user_extra.col3 from user_extra where user_extra.col3 = 1 and 1 = 1",
"Query": "select user_extra.col3 from user_extra where user_extra.col3 = 1",
"Table": "user_extra"
}
]
Expand Down
41 changes: 41 additions & 0 deletions go/vt/vtgate/semantics/early_rewriter.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ func (r *earlyRewriter) down(cursor *sqlparser.Cursor) error {
handleOrderBy(r, cursor, node)
case *sqlparser.OrExpr:
rewriteOrExpr(cursor, node)
case *sqlparser.AndExpr:
rewriteAndExpr(cursor, node)
case *sqlparser.NotExpr:
rewriteNotExpr(cursor, node)
case sqlparser.GroupBy:
Expand Down Expand Up @@ -138,6 +140,45 @@ func rewriteOrExpr(cursor *sqlparser.Cursor, node *sqlparser.OrExpr) {
}
}

// rewriteAndExpr rewrites AND expressions when either side is TRUE.
func rewriteAndExpr(cursor *sqlparser.Cursor, node *sqlparser.AndExpr) {
newNode := rewriteAndTrue(*node)
if newNode != nil {
cursor.ReplaceAndRevisit(newNode)
}
}

func rewriteAndTrue(andExpr sqlparser.AndExpr) sqlparser.Expr {
// we are looking for the pattern `WHERE c = 1 AND 1 = 1`
isTrue := func(subExpr sqlparser.Expr) bool {
evalEnginePred, err := evalengine.Translate(subExpr, nil)
if err != nil {
return false
}

env := evalengine.EmptyExpressionEnv()
res, err := env.Evaluate(evalEnginePred)
if err != nil {
return false
}

boolValue, err := res.Value(collations.Default()).ToBool()
if err != nil {
return false
}

return boolValue
}

if isTrue(andExpr.Left) {
return andExpr.Right
} else if isTrue(andExpr.Right) {
return andExpr.Left
}

return nil
}

// handleLiteral processes literals within the context of ORDER BY expressions.
func handleLiteral(r *earlyRewriter, cursor *sqlparser.Cursor, node *sqlparser.Literal) error {
newNode, err := r.rewriteOrderByExpr(node)
Expand Down

0 comments on commit fd79f83

Please sign in to comment.