github.com/solongordon/pop@v4.10.0+incompatible/slices/string.go (about)

     1  package slices
     2  
     3  import (
     4  	"bytes"
     5  	"database/sql/driver"
     6  	"encoding/csv"
     7  	"encoding/json"
     8  	"io"
     9  	"strings"
    10  
    11  	"github.com/lib/pq"
    12  )
    13  
    14  // For reading in arrays from postgres
    15  
    16  // String is a slice of strings.
    17  type String pq.StringArray
    18  
    19  // Interface implements the nulls.nullable interface.
    20  func (s String) Interface() interface{} {
    21  	return []string(s)
    22  }
    23  
    24  // Scan implements the sql.Scanner interface.
    25  // It allows to read the string slice from the database value.
    26  func (s *String) Scan(src interface{}) error {
    27  	ss := pq.StringArray(*s)
    28  	err := ss.Scan(src)
    29  	*s = String(ss)
    30  	return err
    31  }
    32  
    33  // Value implements the driver.Valuer interface.
    34  // It allows to convert the string slice to a driver.value.
    35  func (s String) Value() (driver.Value, error) {
    36  	ss := pq.StringArray(s)
    37  	return ss.Value()
    38  }
    39  
    40  // UnmarshalJSON will unmarshall JSON value into
    41  // the string slice representation of this value.
    42  func (s *String) UnmarshalJSON(data []byte) error {
    43  	var ss pq.StringArray
    44  	if err := json.Unmarshal(data, &ss); err != nil {
    45  		return err
    46  	}
    47  	*s = String(ss)
    48  	return nil
    49  }
    50  
    51  // UnmarshalText will unmarshall text value into
    52  // the string slice representation of this value.
    53  func (s *String) UnmarshalText(text []byte) error {
    54  	r := csv.NewReader(bytes.NewReader(text))
    55  
    56  	var words []string
    57  	for {
    58  		record, err := r.Read()
    59  		if err == io.EOF {
    60  			break
    61  		}
    62  		if err != nil {
    63  			return err
    64  		}
    65  
    66  		words = append(words, record...)
    67  	}
    68  
    69  	*s = String(words)
    70  	return nil
    71  }
    72  
    73  // TagValue implements the tagValuer interface, to work with https://github.com/gobuffalo/tags.
    74  func (s String) TagValue() string {
    75  	return s.Format(",")
    76  }
    77  
    78  // Format presents the slice as a string, using a given separator.
    79  func (s String) Format(sep string) string {
    80  	return strings.Join([]string(s), sep)
    81  }