github.com/matrixorigin/matrixone@v0.7.0/pkg/sql/plan/function/builtin/unary/json_unquote.go (about)

     1  // Copyright 2022 Matrix Origin
     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 unary
    16  
    17  import (
    18  	"github.com/matrixorigin/matrixone/pkg/container/nulls"
    19  	"github.com/matrixorigin/matrixone/pkg/container/types"
    20  	"github.com/matrixorigin/matrixone/pkg/container/vector"
    21  	"github.com/matrixorigin/matrixone/pkg/vectorize/json_unquote"
    22  	"github.com/matrixorigin/matrixone/pkg/vm/process"
    23  )
    24  
    25  func JsonUnquote(vecs []*vector.Vector, proc *process.Process) (ret *vector.Vector, err error) {
    26  	defer func() {
    27  		if err != nil && ret != nil {
    28  			ret.Free(proc.Mp())
    29  		}
    30  	}()
    31  	vec := vecs[0]
    32  	var (
    33  		fSingle func([]byte) (string, error)
    34  		fBacth  func([][]byte, []string, *nulls.Nulls) ([]string, error)
    35  	)
    36  	switch {
    37  	case types.IsString(vec.Typ.Oid):
    38  		fSingle = json_unquote.StringSingle
    39  		fBacth = json_unquote.StringBatch
    40  	default:
    41  		fSingle = json_unquote.JsonSingle
    42  		fBacth = json_unquote.JsonBatch
    43  	}
    44  	resultType := types.T_varchar.ToType()
    45  	if vec.IsScalarNull() {
    46  		ret = proc.AllocScalarNullVector(resultType)
    47  		return
    48  	}
    49  	if vec.IsScalar() {
    50  		ret = proc.AllocScalarVector(resultType)
    51  		v := vector.MustBytesCols(vec)[0]
    52  		var r string
    53  		r, err = fSingle(v)
    54  		if err != nil {
    55  			return nil, err
    56  		}
    57  		err = vector.SetStringAt(ret, 0, r, proc.Mp())
    58  		return
    59  	}
    60  	ret, err = proc.AllocVectorOfRows(resultType, int64(vec.Length()), vec.Nsp)
    61  	if err != nil {
    62  		return nil, err
    63  	}
    64  	rs := vector.MustStrCols(vec)
    65  	xs := vector.MustBytesCols(vec)
    66  	rs, err = fBacth(xs, rs, ret.Nsp)
    67  	if err != nil {
    68  		return nil, err
    69  	}
    70  	for i, r := range rs {
    71  		if ret.Nsp.Contains(uint64(i)) {
    72  			continue
    73  		}
    74  		err = vector.SetStringAt(ret, i, r, proc.Mp())
    75  		if err != nil {
    76  			return nil, err
    77  		}
    78  	}
    79  	return
    80  }