github.com/hasnat/dolt/go@v0.0.0-20210628190320-9eb5d843fbb7/libraries/doltcore/row/fmt.go (about)

     1  // Copyright 2019 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 row
    16  
    17  import (
    18  	"bytes"
    19  	"context"
    20  
    21  	"github.com/dolthub/dolt/go/libraries/doltcore/schema"
    22  	"github.com/dolthub/dolt/go/store/types"
    23  )
    24  
    25  type TupleFormatFunc func(ctx context.Context, t types.Tuple) string
    26  type RowFormatFunc func(ctx context.Context, r Row, sch schema.Schema) string
    27  
    28  var TupleFmt = FieldSeparatedTupleFmt(',')
    29  var Fmt = FieldSeparatedFmt(':')
    30  var fieldDelim = []byte(" | ")
    31  
    32  func FieldSeparatedFmt(delim rune) RowFormatFunc {
    33  	return func(ctx context.Context, r Row, sch schema.Schema) string {
    34  		if r == nil {
    35  			return "null"
    36  		}
    37  
    38  		allCols := sch.GetAllCols()
    39  
    40  		var backingBuffer [512]byte
    41  		buf := bytes.NewBuffer(backingBuffer[:0])
    42  
    43  		var ok bool
    44  		allCols.IterInSortedOrder(func(tag uint64, col schema.Column) (stop bool) {
    45  			if ok {
    46  				buf.Write(fieldDelim)
    47  			}
    48  
    49  			var val types.Value
    50  			val, ok = r.GetColVal(tag)
    51  
    52  			if ok {
    53  				buf.Write([]byte(col.Name))
    54  				buf.WriteRune(delim)
    55  				types.WriteEncodedValue(ctx, buf, val)
    56  			}
    57  
    58  			return false
    59  		})
    60  
    61  		return buf.String()
    62  	}
    63  }
    64  
    65  func FieldSeparatedTupleFmt(delim rune) TupleFormatFunc {
    66  	return func(ctx context.Context, t types.Tuple) string {
    67  		var backingBuffer [512]byte
    68  		buf := bytes.NewBuffer(backingBuffer[:0])
    69  
    70  		_ = t.IterFields(func(index uint64, val types.Value) (stop bool, err error) {
    71  			if index%2 == 1 {
    72  				if index != 1 {
    73  					buf.WriteRune(delim)
    74  				}
    75  				types.WriteEncodedValue(ctx, buf, val)
    76  			}
    77  
    78  			return false, nil
    79  		})
    80  
    81  		return buf.String()
    82  	}
    83  }