github.com/dolthub/go-mysql-server@v0.18.0/sql/expression/function/space.go (about) 1 // Copyright 2024 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 function 16 17 import ( 18 "github.com/dolthub/go-mysql-server/sql" 19 "github.com/dolthub/go-mysql-server/sql/types" 20 ) 21 22 // Space implements the sql function "space" which returns a string with the number of spaces specified by the argument 23 type Space struct { 24 *UnaryFunc 25 } 26 27 var _ sql.FunctionExpression = (*Space)(nil) 28 var _ sql.CollationCoercible = (*Space)(nil) 29 30 func NewSpace(arg sql.Expression) sql.Expression { 31 return &Space{NewUnaryFunc(arg, "SPACE", types.LongText)} 32 } 33 34 // Description implements sql.FunctionExpression 35 func (s *Space) Description() string { 36 return "return a string of the specified number of spaces." 37 } 38 39 // CollationCoercibility implements the interface sql.CollationCoercible. 40 func (s *Space) CollationCoercibility(ctx *sql.Context) (collation sql.CollationID, coercibility byte) { 41 return sql.Collation_binary, 5 42 } 43 44 // Eval implements the sql.Expression interface 45 func (s *Space) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) { 46 val, err := s.EvalChild(ctx, row) 47 if err != nil { 48 return nil, err 49 } 50 51 if val == nil { 52 return nil, nil 53 } 54 55 // TODO: better truncate integer handling 56 v, _, err := types.Int64.Convert(val) 57 if err != nil { 58 ctx.Warn(1292, "Truncated incorrect INTEGER value: '%v'", val) 59 v = int64(0) 60 } 61 62 num := int(v.(int64)) 63 if num < 0 { 64 num = 0 65 } 66 67 res := "" 68 for i := 0; i < num; i++ { 69 res += " " 70 } 71 return res, nil 72 } 73 74 // WithChildren implements the sql.Expression interface 75 func (s *Space) WithChildren(children ...sql.Expression) (sql.Expression, error) { 76 if len(children) != 1 { 77 return nil, sql.ErrInvalidChildrenNumber.New(s, len(children), 1) 78 } 79 return NewSpace(children[0]), nil 80 }