github.com/matrixorigin/matrixone@v0.7.0/pkg/sql/plan/function/builtin/multi/trim.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 multi 16 17 import ( 18 "github.com/matrixorigin/matrixone/pkg/common/moerr" 19 "github.com/matrixorigin/matrixone/pkg/container/types" 20 "github.com/matrixorigin/matrixone/pkg/container/vector" 21 "github.com/matrixorigin/matrixone/pkg/vm/process" 22 "strings" 23 ) 24 25 func trimBoth(src, cuts string) string { 26 if len(cuts) == 0 { 27 return src 28 } 29 return trimLeading(trimTrailing(src, cuts), cuts) 30 } 31 32 func trimLeading(src, cuts string) string { 33 if len(cuts) == 0 { 34 return src 35 } 36 for strings.HasPrefix(src, cuts) { 37 src = src[len(cuts):] 38 } 39 return src 40 } 41 42 func trimTrailing(src, cuts string) string { 43 if len(cuts) == 0 { 44 return src 45 } 46 for strings.HasSuffix(src, cuts) { 47 src = src[:len(src)-len(cuts)] 48 } 49 return src 50 } 51 52 func Trim(parameters []*vector.Vector, result vector.FunctionResultWrapper, proc *process.Process, length int) error { 53 tp := strings.ToLower(vector.MustStrCols(parameters[0])[0]) 54 switch tp { 55 case "both": 56 return trim(parameters[1:], result, length, trimBoth) 57 case "leading": 58 return trim(parameters[1:], result, length, trimLeading) 59 case "trailing": 60 return trim(parameters[1:], result, length, trimTrailing) 61 default: 62 return moerr.NewNotSupported(proc.Ctx, "trim type %s", tp) 63 } 64 } 65 66 func trim(parameters []*vector.Vector, result vector.FunctionResultWrapper, length int, trimFn func(string, string) string) error { 67 cutsets := vector.GenerateFunctionStrParameter(parameters[0]) 68 origin := vector.GenerateFunctionStrParameter(parameters[1]) 69 rs := vector.MustFunctionResult[types.Varlena](result) 70 for i := uint64(0); i < uint64(length); i++ { 71 cutset, cIsNull := cutsets.GetStrValue(i) 72 orig, oIsNull := origin.GetStrValue(i) 73 if cIsNull || oIsNull { 74 if err := rs.AppendStr(nil, true); err != nil { 75 return err 76 } 77 continue 78 } 79 if err := rs.AppendStr([]byte(trimFn(string(orig), string(cutset))), false); err != nil { 80 return err 81 } 82 } 83 return nil 84 }