Debian Codegraph @

string.go

raw symbols SCIP
1 // Package null contains SQL types that consider zero input and null input as separate values,
2 // with convenient support for JSON and text marshaling.
3 // Types in this package will always encode to their null value if null.
4 // Use the zero subpackage if you want zero values and null to be treated the same.
5 package null
6
7 import (
8 "database/sql"
9 "encoding/json"
10 "fmt"
11 "reflect"
12 )
13
14 // String is a nullable string. It supports SQL and JSON serialization.
15 // It will marshal to null if null. Blank string input will be considered null.
16 type String struct {
17 sql.NullString
18 }
19
20 // StringFrom creates a new String that will never be blank.
21 func StringFrom(s string) String {
22 return NewString(s, true)
23 }
24
25 // StringFromPtr creates a new String that be null if s is nil.
26 func StringFromPtr(s *string) String {
27 if s == nil {
28 return NewString("", false)
29 }
30 return NewString(*s, true)
31 }
32
33 // NewString creates a new String
34 func NewString(s string, valid bool) String {
35 return String{
36 NullString: sql.NullString{
37 String: s,
38 Valid: valid,
39 },
40 }
41 }
42
43 // UnmarshalJSON implements json.Unmarshaler.
44 // It supports string and null input. Blank string input produces a null String.
45 // It also supports unmarshalling a sql.NullString.
46 func (s *String) UnmarshalJSON(data []byte) error {
47 var err error
48 var v interface{}
49 if err = json.Unmarshal(data, &v); err != nil {
50 return err
51 }
52 switch x := v.(type) {
53 case string:
54 s.String = x
55 case map[string]interface{}:
56 err = json.Unmarshal(data, &s.NullString)
57 case nil:
58 s.Valid = false
59 return nil
60 default:
61 err = fmt.Errorf("json: cannot unmarshal %v into Go value of type null.String", reflect.TypeOf(v).Name())
62 }
63 s.Valid = (err == nil) && (s.String != "")
64 return err
65 }
66
67 // MarshalJSON implements json.Marshaler.
68 // It will encode null if this String is null.
69 func (s String) MarshalJSON() ([]byte, error) {
70 if !s.Valid {
71 return []byte("null"), nil
72 }
73 return json.Marshal(s.String)
74 }
75
76 // UnmarshalText implements encoding.TextUnmarshaler.
77 // It will unmarshal to a null String if the input is a blank string.
78 func (s *String) UnmarshalText(text []byte) error {
79 s.String = string(text)
80 s.Valid = s.String != ""
81 return nil
82 }
83
84 // SetValid changes this String's value and also sets it to be non-null.
85 func (s *String) SetValid(v string) {
86 s.String = v
87 s.Valid = true
88 }
89
90 // Ptr returns a pointer to this String's value, or a nil pointer if this String is null.
91 func (s String) Ptr() *string {
92 if !s.Valid {
93 return nil
94 }
95 return &s.String
96 }
97
98 // IsZero returns true for null or empty strings, for future omitempty support. (Go 1.4?)
99 // Will return false s if blank but non-null.
100 func (s String) IsZero() bool {
101 return !s.Valid
102 }