Skip to content

Commit

Permalink
Implement unary minus operator
Browse files Browse the repository at this point in the history
  • Loading branch information
totem3 committed Apr 10, 2024
1 parent b6dd6a5 commit 28a61ef
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 1 deletion.
18 changes: 18 additions & 0 deletions internal/function_bind.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package internal
import (
"errors"
"fmt"
"math"
"sync"

"github.com/goccy/go-json"
Expand Down Expand Up @@ -184,6 +185,23 @@ func bindOpDiv(args ...Value) (Value, error) {
return OP_DIV(args[0], args[1])
}

func bindUnaryMinus(args ...Value) (Value, error) {
if existsNull(args) {
return nil, nil
}
v, ok := args[0].(IntValue)
if ok {
i, err := v.ToInt64()
if err != nil {
return nil, err
}
if i <= math.MinInt64 {

Check failure on line 198 in internal/function_bind.go

View workflow job for this annotation

GitHub Actions / lint

SA4003: no value of type int64 is less than math.MinInt64 (staticcheck)
return nil, fmt.Errorf("int64 overflow: -%d", i)
}
}
return SAFE_NEGATE(args[0])
}

func bindEqual(args ...Value) (Value, error) {
if existsNull(args) {
return nil, nil
Expand Down
1 change: 1 addition & 0 deletions internal/function_register.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ var normalFuncs = []*FuncInfo{
{Name: "subtract", BindFunc: bindSub},
{Name: "multiply", BindFunc: bindMul},
{Name: "divide", BindFunc: bindOpDiv},
{Name: "unary_minus", BindFunc: bindUnaryMinus},
{Name: "equal", BindFunc: bindEqual},
{Name: "not_equal", BindFunc: bindNotEqual},
{Name: "greater", BindFunc: bindGreater},
Expand Down
21 changes: 20 additions & 1 deletion query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,29 @@ UNION ALL
expectedRows: [][]interface{}{{int64(1)}},
},
{
name: "unary minus operator",
name: "unary minus operator with literal",
query: "SELECT -2",
expectedRows: [][]interface{}{{int64(-2)}},
},
{
name: "unary minus operator with column",
query: `WITH x AS (
SELECT 2 AS i, 2.0 AS f
UNION ALL
SELECT -9223372036854775807, -9223372036854775807
UNION ALL
SELECT NULL, -9223372036854775808
) SELECT -i, -f FROM x`,
expectedRows: [][]interface{}{
{int64(-2), float64(-2.0)},
{int64(9223372036854775807), float64(9223372036854775807)},
{nil, float64(9223372036854775808)}},
},
{
name: "unary minus operator overflow",
query: "WITH x AS (SELECT -9223372036854775808 as v) SELECT -v FROM x",
expectedErr: "int64 overflow: --9223372036854775808",
},
{
name: "bit not operator",
query: "SELECT ~1",
Expand Down

0 comments on commit 28a61ef

Please sign in to comment.