github.com/dolthub/go-mysql-server@v0.18.0/sql/expression/function/json/json_length.go (about)

     1  // Copyright 2020-2021 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  	"fmt"
    19  
    20  	"github.com/dolthub/jsonpath"
    21  	"gopkg.in/src-d/go-errors.v1"
    22  
    23  	"github.com/dolthub/go-mysql-server/sql"
    24  	"github.com/dolthub/go-mysql-server/sql/expression"
    25  	"github.com/dolthub/go-mysql-server/sql/types"
    26  )
    27  
    28  // JSON_LENGTH(json_doc [, path])
    29  //
    30  // JsonLength returns the length of a JSON document, or the length of the value extracted from the specified path.
    31  // https://dev.mysql.com/doc/refman/8.0/en/json-attribute-functions.html#function_json-length
    32  type JsonLength struct {
    33  	JSON sql.Expression
    34  	Path sql.Expression
    35  }
    36  
    37  var _ sql.FunctionExpression = (*JsonLength)(nil)
    38  var _ sql.CollationCoercible = (*JsonLength)(nil)
    39  
    40  // NewJsonLength creates a new JsonLength UDF.
    41  func NewJsonLength(args ...sql.Expression) (sql.Expression, error) {
    42  	if len(args) == 0 || len(args) > 2 {
    43  		return nil, sql.ErrInvalidArgumentNumber.New("JSON_LENGTH", 2, len(args))
    44  	} else if len(args) == 1 {
    45  		return &JsonLength{args[0], expression.NewLiteral("$", types.Text)}, nil
    46  	} else {
    47  		return &JsonLength{args[0], args[1]}, nil
    48  	}
    49  }
    50  
    51  // FunctionName implements sql.FunctionExpression
    52  func (j *JsonLength) FunctionName() string {
    53  	return "json_length"
    54  }
    55  
    56  // Description implements sql.FunctionExpression
    57  func (j *JsonLength) Description() string {
    58  	return "returns length of JSON object"
    59  }
    60  
    61  // Resolved implements the sql.Expression interface.
    62  func (j *JsonLength) Resolved() bool {
    63  	return j.JSON.Resolved()
    64  }
    65  
    66  // Type implements the sql.Expression interface.
    67  func (j *JsonLength) Type() sql.Type { return types.Int64 }
    68  
    69  // CollationCoercibility implements the interface sql.CollationCoercible.
    70  func (*JsonLength) CollationCoercibility(ctx *sql.Context) (collation sql.CollationID, coercibility byte) {
    71  	return ctx.GetCharacterSet().BinaryCollation(), 7
    72  }
    73  
    74  // Eval implements the sql.Expression interface.
    75  func (j *JsonLength) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) {
    76  	span, ctx := ctx.Span("function.JsonLength")
    77  	defer span.End()
    78  
    79  	doc, err := getJSONDocumentFromRow(ctx, row, j.JSON)
    80  	if err != nil {
    81  		return nil, err
    82  	}
    83  	if doc == nil {
    84  		return nil, nil
    85  	}
    86  
    87  	pathVal, err := j.Path.Eval(ctx, row)
    88  	if err != nil {
    89  		return nil, err
    90  	}
    91  	if pathVal == nil {
    92  		return nil, nil
    93  	}
    94  	var path string
    95  	if p, _, strErr := types.LongText.Convert(pathVal); strErr == nil {
    96  		path = p.(string)
    97  	} else {
    98  		return nil, strErr
    99  	}
   100  
   101  	res, err := jsonpath.JsonPathLookup(doc.Val, path)
   102  	if err != nil {
   103  		if errors.Is(err, jsonpath.ErrKeyError) {
   104  			return nil, nil
   105  		}
   106  		return nil, err
   107  	}
   108  
   109  	switch v := res.(type) {
   110  	case nil:
   111  		return nil, nil
   112  	case []interface{}:
   113  		if len(v) == 0 {
   114  			return nil, nil
   115  		}
   116  		return len(v), nil
   117  	case map[any]any:
   118  		return len(v), nil
   119  	default:
   120  		return 1, nil
   121  	}
   122  }
   123  
   124  // IsNullable implements the sql.Expression interface.
   125  func (j *JsonLength) IsNullable() bool {
   126  	return j.JSON.IsNullable()
   127  }
   128  
   129  // Children implements the sql.Expression interface.
   130  func (j *JsonLength) Children() []sql.Expression {
   131  	return []sql.Expression{j.JSON, j.Path}
   132  }
   133  
   134  // WithChildren implements the Expression interface.
   135  func (j *JsonLength) WithChildren(children ...sql.Expression) (sql.Expression, error) {
   136  	return NewJsonLength(children...)
   137  }
   138  
   139  func (j *JsonLength) String() string {
   140  	return fmt.Sprintf("json_length(%s)", j.JSON.String())
   141  }