Skip to content

Commit

Permalink
Merge pull request #7579 from GuptaManan100/unary-ops
Browse files Browse the repository at this point in the history
Avoiding addition of redundant unary operators
  • Loading branch information
systay authored Mar 3, 2021
2 parents 9ca4525 + 67dca5c commit 25c1088
Show file tree
Hide file tree
Showing 4 changed files with 259 additions and 263 deletions.
16 changes: 16 additions & 0 deletions go/vt/sqlparser/ast_funcs.go
Original file line number Diff line number Diff line change
Expand Up @@ -1338,3 +1338,19 @@ const (
// DoubleAt represnts @@
DoubleAt
)

// handleUnaryMinus handles the case when a unary minus operator is seen in the parser. It takes 1 argument which is the expr to which the unary minus has been added to.
func handleUnaryMinus(expr Expr) Expr {
if num, ok := expr.(*Literal); ok && num.Type == IntVal {
// Handle double negative
if num.Val[0] == '-' {
num.Val = num.Val[1:]
return num
}
return NewIntLiteral(append([]byte("-"), num.Val...))
}
if unaryExpr, ok := expr.(*UnaryExpr); ok && unaryExpr.Operator == UMinusOp {
return unaryExpr.Expr
}
return &UnaryExpr{Operator: UMinusOp, Expr: expr}
}
12 changes: 10 additions & 2 deletions go/vt/sqlparser/parse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -447,7 +447,8 @@ var (
input: "select /* % no space */ 1 from t where a = b%c",
output: "select /* % no space */ 1 from t where a = b % c",
}, {
input: "select /* u+ */ 1 from t where a = +b",
input: "select /* u+ */ 1 from t where a = +b",
output: "select /* u+ */ 1 from t where a = b",
}, {
input: "select /* u- */ 1 from t where a = -b",
}, {
Expand Down Expand Up @@ -607,7 +608,8 @@ var (
input: "select /* binary unary */ a- -b from t",
output: "select /* binary unary */ a - -b from t",
}, {
input: "select /* - - */ - -b from t",
input: "select /* - - */ - -b from t",
output: "select /* - - */ b from t",
}, {
input: "select /* binary binary */ binary binary b from t",
}, {
Expand Down Expand Up @@ -904,6 +906,12 @@ var (
input: "set @variable = 42",
}, {
input: "set @period.variable = 42",
}, {
input: "set S= +++-++-+(4+1)",
output: "set S = 4 + 1",
}, {
input: "set S= +- - - - -(4+1)",
output: "set S = -(4 + 1)",
}, {
input: "alter table a add foo int first v",
output: "alter table a add column foo int first v",
Expand Down
Loading

0 comments on commit 25c1088

Please sign in to comment.