Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoiding addition of redundant unary operators #7579

Merged
merged 4 commits into from
Mar 3, 2021
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions go/vt/sqlparser/ast_funcs.go
Original file line number Diff line number Diff line change
Expand Up @@ -1642,3 +1642,19 @@ func (node *Default) Clone() Expr {
}
return &Default{ColName: node.ColName}
}

// 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 @@ -901,6 +903,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