summaryrefslogtreecommitdiffstats
path: root/pkg/types/string.go
blob: f8ead450c15d7377a4cf264779fa579cdfe68d3b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package types

import (
	"bytes"
	"database/sql"
	"database/sql/driver"
	"encoding"
	"encoding/json"
	"github.com/icinga/icingadb/internal"
	"strings"
)

// String adds JSON support to sql.NullString.
type String struct {
	sql.NullString
}

// MarshalJSON implements the json.Marshaler interface.
// Supports JSON null.
func (s String) MarshalJSON() ([]byte, error) {
	var v interface{}
	if s.Valid {
		v = s.String
	}

	return internal.MarshalJSON(v)
}

// UnmarshalText implements the encoding.TextUnmarshaler interface.
func (s *String) UnmarshalText(text []byte) error {
	*s = String{sql.NullString{
		String: string(text),
		Valid:  true,
	}}

	return nil
}

// UnmarshalJSON implements the json.Unmarshaler interface.
// Supports JSON null.
func (s *String) UnmarshalJSON(data []byte) error {
	// Ignore null, like in the main JSON package.
	if bytes.HasPrefix(data, []byte{'n'}) {
		return nil
	}

	if err := internal.UnmarshalJSON(data, &s.String); err != nil {
		return err
	}

	s.Valid = true

	return nil
}

// Value implements the driver.Valuer interface.
// Supports SQL NULL.
func (s String) Value() (driver.Value, error) {
	if !s.Valid {
		return nil, nil
	}

	// PostgreSQL does not allow null bytes in varchar, char and text fields.
	return strings.ReplaceAll(s.String, "\x00", ""), nil
}

// Assert interface compliance.
var (
	_ json.Marshaler           = String{}
	_ encoding.TextUnmarshaler = (*String)(nil)
	_ json.Unmarshaler         = (*String)(nil)
	_ driver.Valuer            = String{}
	_ sql.Scanner              = (*String)(nil)
)