github.com/dolthub/go-mysql-server@v0.18.0/sql/expression/function/json/json_replace.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  	"fmt"
    19  	"strings"
    20  
    21  	"github.com/dolthub/go-mysql-server/sql"
    22  	"github.com/dolthub/go-mysql-server/sql/types"
    23  )
    24  
    25  // JSON_REPLACE(json_doc, path, val[, path, val] ...)
    26  //
    27  // JSONReplace Replaces existing values in a JSON document and returns the result. Returns NULL if any argument is NULL.
    28  // An error occurs if the json_doc argument is not a valid JSON document or any path argument is not a valid path
    29  // expression or contains a * or ** wildcard. The path-value pairs are evaluated left to right. The document produced by
    30  // evaluating one pair becomes the new value against which the next pair is evaluated. A path-value pair for an existing
    31  // path in the document overwrites the existing document value with the new value. A path-value pair for a non-existing
    32  // path in the document is ignored and has no effect.
    33  //
    34  // https://dev.mysql.com/doc/refman/8.0/en/json-modification-functions.html#function_json-replace
    35  type JSONReplace struct {
    36  	doc      sql.Expression
    37  	pathVals []sql.Expression
    38  }
    39  
    40  var _ sql.FunctionExpression = JSONReplace{}
    41  
    42  func (j JSONReplace) Resolved() bool {
    43  	for _, child := range j.Children() {
    44  		if child != nil && !child.Resolved() {
    45  			return false
    46  		}
    47  	}
    48  	return true
    49  }
    50  
    51  func (j JSONReplace) String() string {
    52  	children := j.Children()
    53  	var parts = make([]string, len(children))
    54  
    55  	for i, c := range children {
    56  		parts[i] = c.String()
    57  	}
    58  
    59  	return fmt.Sprintf("%s(%s)", j.FunctionName(), strings.Join(parts, ","))
    60  }
    61  
    62  func (j JSONReplace) Type() sql.Type {
    63  	return types.JSON
    64  }
    65  
    66  func (j JSONReplace) IsNullable() bool {
    67  	for _, arg := range j.pathVals {
    68  		if arg.IsNullable() {
    69  			return true
    70  		}
    71  	}
    72  	return j.doc.IsNullable()
    73  }
    74  
    75  func (j JSONReplace) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) {
    76  	doc, err := getMutableJSONVal(ctx, row, j.doc)
    77  	if err != nil || doc == nil {
    78  		return nil, err
    79  	}
    80  
    81  	pairs := make([]pathValPair, 0, len(j.pathVals)/2)
    82  	for i := 0; i < len(j.pathVals); i += 2 {
    83  		argPair, err := buildPathValue(ctx, j.pathVals[i], j.pathVals[i+1], row)
    84  		if argPair == nil || err != nil {
    85  			return nil, err
    86  		}
    87  		pairs = append(pairs, *argPair)
    88  	}
    89  
    90  	// Apply the path-value pairs to the document.
    91  	for _, pair := range pairs {
    92  		doc, _, err = doc.Replace(pair.path, pair.val)
    93  		if err != nil {
    94  			return nil, err
    95  		}
    96  	}
    97  
    98  	return doc, nil
    99  }
   100  
   101  func (j JSONReplace) Children() []sql.Expression {
   102  	return append([]sql.Expression{j.doc}, j.pathVals...)
   103  }
   104  
   105  func (j JSONReplace) WithChildren(children ...sql.Expression) (sql.Expression, error) {
   106  	if len(j.Children()) != len(children) {
   107  		return nil, fmt.Errorf("json_replace did not receive the correct amount of args")
   108  	}
   109  	return NewJSONReplace(children...)
   110  }
   111  
   112  // NewJSONReplace creates a new JSONReplace function.
   113  func NewJSONReplace(args ...sql.Expression) (sql.Expression, error) {
   114  	if len(args) <= 1 {
   115  		return nil, sql.ErrInvalidArgumentNumber.New("JSON_REPLACE", "more than 1", len(args))
   116  	} else if (len(args)-1)%2 == 1 {
   117  		return nil, sql.ErrInvalidArgumentNumber.New("JSON_REPLACE", "even number of path/val", len(args)-1)
   118  	}
   119  
   120  	return JSONReplace{args[0], args[1:]}, nil
   121  }
   122  
   123  // FunctionName implements sql.FunctionExpression
   124  func (j JSONReplace) FunctionName() string {
   125  	return "json_replace"
   126  }
   127  
   128  // Description implements sql.FunctionExpression
   129  func (j JSONReplace) Description() string {
   130  	return "replaces values in JSON document."
   131  }
   132  
   133  // IsUnsupported implements sql.UnsupportedFunctionStub
   134  func (j JSONReplace) IsUnsupported() bool {
   135  	return false
   136  }