github.com/dolthub/go-mysql-server@v0.18.0/sql/expression/function/json/json_value_test.go (about) 1 // Copyright 2023 Dolthub, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package json 16 17 import ( 18 "strings" 19 "testing" 20 21 "github.com/stretchr/testify/require" 22 "gopkg.in/src-d/go-errors.v1" 23 24 "github.com/dolthub/go-mysql-server/sql" 25 "github.com/dolthub/go-mysql-server/sql/expression" 26 "github.com/dolthub/go-mysql-server/sql/types" 27 ) 28 29 func TestJsonValue(t *testing.T) { 30 _, err := NewJSONValid() 31 require.True(t, errors.Is(err, sql.ErrInvalidArgumentNumber)) 32 33 tests := []struct { 34 row sql.Row 35 typ sql.Type 36 path string 37 exp interface{} 38 }{ 39 {row: sql.Row{`null`}, exp: nil}, 40 {row: sql.Row{`1`}, exp: "1"}, 41 {row: sql.Row{`[1]`}, exp: `[1]`}, 42 {row: sql.Row{`{"a": "fjsadflkd"}`}, exp: `{"a": "fjsadflkd"}`}, 43 {row: sql.Row{`[1, false]`}, exp: `[1, false]`}, 44 {row: sql.Row{`[1, false]`}, path: "$[0]", typ: types.Int64, exp: int64(1)}, 45 {row: sql.Row{`[1, false]`}, path: "$[0]", typ: types.Uint64, exp: uint64(1)}, 46 {row: sql.Row{`[1, false]`}, path: "$[0]", exp: "1"}, 47 {row: sql.Row{`[1, {"a": 1}]`}, path: "$[1].a", typ: types.Int64, exp: int64(1)}, 48 {row: sql.Row{`[1, {"a": 1}]`}, path: "$[1]", typ: types.JSON, exp: types.MustJSON(`{"a": 1}`)}, 49 } 50 51 for _, tt := range tests { 52 args := make([]string, len(tt.row)) 53 for i, a := range tt.row { 54 args[i] = a.(string) 55 } 56 if tt.path == "" { 57 tt.path = "$" 58 } 59 args = append(args, tt.path) 60 if tt.typ != nil { 61 args = append(args, tt.typ.String()) 62 } 63 t.Run(strings.Join(args, ", "), func(t *testing.T) { 64 args := []sql.Expression{expression.NewGetField(0, types.JSON, "", true)} 65 if tt.path != "" { 66 args = append(args, expression.NewLiteral(tt.path, types.Text)) 67 } 68 if tt.typ != nil { 69 args = append(args, expression.NewLiteral(tt.typ.Zero(), tt.typ)) 70 } 71 f, _ := NewJsonValue(args...) 72 require := require.New(t) 73 // any error case will result in output of 'false' value 74 result, _ := f.Eval(sql.NewEmptyContext(), tt.row) 75 require.Equal(tt.exp, result) 76 }) 77 } 78 }