Skip to content

Commit

Permalink
Add typeof function
Browse files Browse the repository at this point in the history
  • Loading branch information
asdine committed Jul 26, 2021
1 parent 01c87d1 commit bba4c0a
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 0 deletions.
41 changes: 41 additions & 0 deletions internal/expr/functions/builtins.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,13 @@ import (
)

var builtinFunctions = Definitions{
"typeof": &definition{
name: "typeof",
arity: 1,
constructorFn: func(args ...expr.Expr) (expr.Function, error) {
return &TypeOf{Expr: args[0]}, nil
},
},
"pk": &definition{
name: "pk",
arity: 0,
Expand Down Expand Up @@ -60,6 +67,40 @@ func BuiltinDefinitions() Definitions {
return builtinFunctions
}

type TypeOf struct {
Expr expr.Expr
}

func (t *TypeOf) Eval(env *environment.Environment) (types.Value, error) {
v, err := t.Expr.Eval(env)
if err != nil {
return nil, err
}

return types.NewTextValue(v.Type().String()), nil
}

// IsEqual compares this expression with the other expression and returns
// true if they are equal.
func (t *TypeOf) IsEqual(other expr.Expr) bool {
if other == nil {
return false
}

o, ok := other.(*TypeOf)
if !ok {
return false
}

return expr.Equal(t.Expr, o.Expr)
}

func (t *TypeOf) Params() []expr.Expr { return []expr.Expr{t.Expr} }

func (t *TypeOf) String() string {
return stringutil.Sprintf("typeof(%v)", t.Expr)
}

// PK represents the pk() function.
// It returns the primary key of the current document.
type PK struct{}
Expand Down
5 changes: 5 additions & 0 deletions internal/expr/functions/builtins_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package functions_test

import (
"bytes"
"path/filepath"
"testing"

"github.com/genjidb/genji/document"
Expand Down Expand Up @@ -56,3 +57,7 @@ func TestPk(t *testing.T) {
})
}
}

func TestBuiltinFunctions(t *testing.T) {
testutil.ExprRunner(t, filepath.Join("testdata", "builtin_functions.sql"))
}
36 changes: 36 additions & 0 deletions internal/expr/functions/testdata/builtin_functions.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
-- test: typeof
! typeof()

! typeof(a)
'field not found'

> typeof(1)
'integer'

> typeof(1 + 1)
'integer'

> typeof(2.0)
'double'

> typeof(2.0)
'double'

> typeof(true)
'bool'

> typeof('hello')
'text'

> typeof('\xAA')
'blob'

> typeof([])
'array'

> typeof({})
'document'

> typeof(NULL)
'null'

0 comments on commit bba4c0a

Please sign in to comment.