github.com/Accefy/pop@v0.0.0-20230428174248-e9f677eab5b9/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 []string
    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  	// Still relying on pq driver to help with string arrays.
    28  	ss := pq.StringArray(*s)
    29  	err := ss.Scan(src)
    30  	*s = String(ss)
    31  	return err
    32  }
    33  
    34  // Value implements the driver.Valuer interface.
    35  // It allows to convert the string slice to a driver.value.
    36  func (s String) Value() (driver.Value, error) {
    37  	ss := pq.StringArray(s)
    38  	return ss.Value()
    39  }
    40  
    41  // UnmarshalJSON will unmarshall JSON value into
    42  // the string slice representation of this value.
    43  func (s *String) UnmarshalJSON(data []byte) error {
    44  	var ss pq.StringArray
    45  	if err := json.Unmarshal(data, &ss); err != nil {
    46  		return err
    47  	}
    48  	*s = String(ss)
    49  	return nil
    50  }
    51  
    52  // UnmarshalText will unmarshall text value into
    53  // the string slice representation of this value.
    54  func (s *String) UnmarshalText(text []byte) error {
    55  	r := csv.NewReader(bytes.NewReader(text))
    56  
    57  	var words []string
    58  	for {
    59  		record, err := r.Read()
    60  		if err == io.EOF {
    61  			break
    62  		}
    63  		if err != nil {
    64  			return err
    65  		}
    66  
    67  		words = append(words, record...)
    68  	}
    69  
    70  	*s = String(words)
    71  	return nil
    72  }
    73  
    74  // TagValue implements the tagValuer interface, to work with https://github.com/gobuffalo/tags.
    75  func (s String) TagValue() string {
    76  	return s.Format(",")
    77  }
    78  
    79  // Format presents the slice as a string, using a given separator.
    80  func (s String) Format(sep string) string {
    81  	return strings.Join([]string(s), sep)
    82  }