Browse Source

fix(func): array_sort works for arr (#2187)

Signed-off-by: Jiyong Huang <huangjy@emqx.io>
ngjaying 1 year ago
parent
commit
05aebde8b8

+ 5 - 4
internal/binder/function/funcs_array.go

@@ -626,16 +626,17 @@ func registerArrayFunc() {
 	builtins["array_sort"] = builtinFunc{
 		fType: ast.FuncTypeScalar,
 		exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
-			t := reflect.TypeOf(args)
+			array := args[0]
+			t := reflect.TypeOf(array)
 			k := t.Kind()
 			if k != reflect.Slice && k != reflect.Array {
 				return errorArrayNotArrayElementError, false
 			}
-			inValue := reflect.ValueOf(args)
+			inValue := reflect.ValueOf(array)
 			inLen := inValue.Len()
 
 			if inLen <= 1 {
-				return args, true
+				return array, true
 			}
 
 			sliceType := reflect.SliceOf(inValue.Index(0).Type())
@@ -655,7 +656,7 @@ func registerArrayFunc() {
 			return outValue.Interface(), true
 		},
 		val: func(ctx api.FunctionContext, args []ast.Expr) error {
-			return ValidateAtLeast(1, len(args))
+			return ValidateLen(1, len(args))
 		},
 		check: returnNilIfHasAnyNil,
 	}

+ 38 - 4
internal/binder/function/funcs_array_test.go

@@ -27,6 +27,7 @@ import (
 	kctx "github.com/lf-edge/ekuiper/internal/topo/context"
 	"github.com/lf-edge/ekuiper/internal/topo/state"
 	"github.com/lf-edge/ekuiper/pkg/api"
+	"github.com/lf-edge/ekuiper/pkg/ast"
 )
 
 func TestArrayCommonFunctions(t *testing.T) {
@@ -785,20 +786,25 @@ func TestArraySort(t *testing.T) {
 	}{
 		{
 			name: "array_sort",
-			args: []interface{}{3, 2, 1},
+			args: []any{
+				[]any{3, 2, 1},
+			},
 
 			result: []interface{}{1, 2, 3},
 		},
 		{
 			name: "array_sort",
-			args: []interface{}{3, 1.6, -0.83},
+			args: []any{
+				[]any{3, 1.6, -0.83},
+			},
 
 			result: []interface{}{-0.83, 1.6, 3},
 		},
 		{
 			name: "array_sort",
-			args: []interface{}{"abc", 3, "def", 1.6, -0.83},
-
+			args: []any{
+				[]any{"abc", 3, "def", 1.6, -0.83},
+			},
 			result: []interface{}{-0.83, 1.6, 3, "abc", "def"},
 		},
 	}
@@ -863,3 +869,31 @@ func TestArrayFuncNil(t *testing.T) {
 		}
 	}
 }
+
+func TestArrayFuncVal(t *testing.T) {
+	tests := []struct {
+		name     string
+		funcName string
+		args     []ast.Expr
+		err      error
+	}{
+		{
+			name:     "array sort failure",
+			funcName: "array_sort",
+			args: []ast.Expr{
+				&ast.BooleanLiteral{Val: true},
+				&ast.BooleanLiteral{Val: true},
+			},
+			err: fmt.Errorf("Expect 1 arguments but found 2."),
+		},
+	}
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			f, ok := builtins[tt.funcName]
+			assert.True(t, ok)
+			err := f.val(nil, tt.args)
+			assert.Equal(t, tt.err, err)
+		})
+	}
+}