Documentation
¶
Overview ¶
Package nullable provides nullable wrapper types for database/sql and encoding/json, and the interfaces that describe nullable values across this module.
Every type has one null state that is written as SQL NULL and JSON null and read back from them, without pointer fields:
- Type wraps any type with a valid flag, so its zero value Type[T]{} is null while TypeFrom(0) is a valid zero.
- NonEmptyString is null when empty, TrimmedString when empty after trimming.
- Time is null for the zero time.Time.
- JSON holds raw JSON text and is null when nil or empty.
- StringArray, IntArray, FloatArray, BoolArray and the element-nullable NullIntArray, NullFloatArray and NullBoolArray are PostgreSQL arrays where only a nil slice is NULL, so NULL and the empty array '{}' stay distinct. Package github.com/domonda/go-types/notnull writes a nil slice as '{}' instead.
The interface Nullable is implemented by these types except StringArray and BoolArray, and by the NullableX types of the domain packages. NullSetable is implemented by pointers to Type, Time and the NullableX types of the domain packages, NullableValidator by the domain types whose non-null values can be invalid, and Zeroable matches types with an IsZero method like time.Time. ReflectIsNull and IsNull report null values of any type, including nil pointers.
See the README for tables of all functions and the exact serialization rules.
Index ¶
- func IsNull(v any) bool
- func ReflectIsNull(v reflect.Value) bool
- func SQLArrayLiteral(s []string) string
- func SplitArray(array string) ([]string, error)
- func SplitArrayValues(array string) ([]string, error)
- type BoolArray
- type FloatArray
- func (a FloatArray) Contains(value float64) bool
- func (a FloatArray) IsNull() bool
- func (a FloatArray) Len() int
- func (a FloatArray) Less(i, j int) bool
- func (a *FloatArray) Scan(src any) error
- func (a FloatArray) String() string
- func (a FloatArray) StringOr(nilStr string) string
- func (a FloatArray) Swap(i, j int)
- func (a FloatArray) Value() (driver.Value, error)
- type IntArray
- type JSON
- func (j JSON) Clone() JSON
- func (j JSON) GoString() string
- func (j JSON) IsEmpty() bool
- func (j JSON) IsNull() bool
- func (j *JSON) MarshalFrom(source any) error
- func (j JSON) MarshalJSON() ([]byte, error)
- func (j JSON) PrettyPrint(w io.Writer) (int, error)
- func (j *JSON) Scan(src any) error
- func (j JSON) String() string
- func (j *JSON) UnmarshalJSON(sourceJSON []byte) error
- func (j JSON) UnmarshalTo(dest any) error
- func (j JSON) Valid() bool
- func (j JSON) Value() (driver.Value, error)
- type NonEmptyString
- func JoinNonEmptyStrings(separator string, strs ...NonEmptyString) NonEmptyString
- func NonEmptyStringFromError(err error) NonEmptyString
- func NonEmptyStringFromPtr(ptr *string) NonEmptyString
- func NonEmptyStringTrimSpace(str string) NonEmptyString
- func NonEmptyStringf(format string, a ...any) NonEmptyString
- func (n NonEmptyString) Get() string
- func (n NonEmptyString) IsNotNull() bool
- func (n NonEmptyString) IsNull() bool
- func (n NonEmptyString) MarshalJSON() ([]byte, error)
- func (n NonEmptyString) Ptr() *string
- func (n *NonEmptyString) Scan(value any) error
- func (n *NonEmptyString) Set(s string)
- func (n *NonEmptyString) SetNull()
- func (n NonEmptyString) StringOr(nullString string) string
- func (n NonEmptyString) TrimSpace() NonEmptyString
- func (n *NonEmptyString) UnmarshalJSON(j []byte) error
- func (n *NonEmptyString) UnmarshalText(text []byte) error
- func (n NonEmptyString) Value() (driver.Value, error)
- type NullBoolArray
- type NullFloatArray
- type NullIntArray
- type NullSetable
- type Nullable
- type NullableValidator
- type StringArray
- type Time
- func (n Time) Add(duration time.Duration) Time
- func (n Time) AddDate(years int, months int, days int) Time
- func (n Time) AppendFormat(b []byte, layout string) []byte
- func (n Time) Equal(o Time) bool
- func (n Time) Format(layout string) string
- func (n Time) Get() time.Time
- func (n Time) GetOr(defaultTime time.Time) time.Time
- func (n Time) IsNotNull() bool
- func (n Time) IsNull() bool
- func (Time) JSONSchema() *jsonschema.Schema
- func (n Time) MarshalJSON() ([]byte, error)
- func (n Time) MarshalText() ([]byte, error)
- func (n *Time) MarshalXMLAttr(name xml.Name) (xml.Attr, error)
- func (n Time) PrettyPrint(w io.Writer) (int, error)
- func (n Time) Ptr() *time.Time
- func (n *Time) Scan(value any) error
- func (n *Time) Set(t time.Time)
- func (n *Time) SetNull()
- func (n Time) String() string
- func (n Time) StringOr(nullStr string) string
- func (n Time) UTC() Time
- func (n *Time) UnmarshalJSON(sourceJSON []byte) error
- func (n *Time) UnmarshalText(text []byte) error
- func (n Time) Value() (driver.Value, error)
- type TrimmedString
- func (s TrimmedString) Contains(substr string) bool
- func (s TrimmedString) ContainsAny(chars string) bool
- func (s TrimmedString) ContainsRune(r rune) bool
- func (s TrimmedString) Get() string
- func (s TrimmedString) HasPrefix(prefix string) bool
- func (s TrimmedString) HasSuffix(suffix string) bool
- func (s TrimmedString) IsNotNull() bool
- func (s TrimmedString) IsNull() bool
- func (TrimmedString) JSONSchema() *jsonschema.Schema
- func (s TrimmedString) MarshalJSON() ([]byte, error)
- func (s TrimmedString) MarshalText() ([]byte, error)
- func (s TrimmedString) MarshalXML(e *xml.Encoder, start xml.StartElement) error
- func (s *TrimmedString) MarshalXMLAttr(name xml.Name) (xml.Attr, error)
- func (s TrimmedString) Ptr() *string
- func (s TrimmedString) ReplaceAll(old, new string) TrimmedString
- func (s *TrimmedString) Scan(value any) error
- func (s *TrimmedString) Set(str string)
- func (s *TrimmedString) SetNull()
- func (s TrimmedString) Split(sep string) []TrimmedString
- func (s TrimmedString) String() string
- func (s TrimmedString) StringOr(nullString string) string
- func (s TrimmedString) ToLower() TrimmedString
- func (s TrimmedString) ToUpper() TrimmedString
- func (s TrimmedString) ToValidUTF8(replacement string) TrimmedString
- func (s TrimmedString) TrimPrefix(prefix string) TrimmedString
- func (s TrimmedString) TrimSuffix(suffix string) TrimmedString
- func (s *TrimmedString) UnmarshalJSON(j []byte) error
- func (s *TrimmedString) UnmarshalText(text []byte) error
- func (s *TrimmedString) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error
- func (s TrimmedString) Value() (driver.Value, error)
- type Type
- func (t Type[T]) Get() T
- func (t Type[T]) GetOr(defaultValue T) T
- func (t Type[T]) IsNotNull() bool
- func (t Type[T]) IsNull() bool
- func (t Type[T]) JSONSchema() *jsonschema.Schema
- func (t Type[T]) MarshalJSON() ([]byte, error)
- func (t Type[T]) Ptr() *T
- func (t *Type[T]) Scan(value any) error
- func (t *Type[T]) Set(value T)
- func (t *Type[T]) SetNull()
- func (t *Type[T]) UnmarshalJSON(sourceJSON []byte) error
- func (t Type[T]) Value() (driver.Value, error)
- type Zeroable
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func IsNull ¶
IsNull is the any-typed convenience wrapper around ReflectIsNull. See ReflectIsNull for the full unwrapping and dispatch rules.
IsNull never panics.
func ReflectIsNull ¶
ReflectIsNull returns true if v represents a "null" value, defined as:
- the zero reflect.Value (Kind Invalid),
- a nil pointer, interface, map, slice, channel, function, or unsafe.Pointer anywhere along the chain of pointer/interface unwrapping,
- a value whose type (or addressable pointer-to-type) implements Nullable and whose IsNull method returns true,
- a value whose type (or addressable pointer-to-type) implements Zeroable and whose IsZero method returns true (only when Nullable is not implemented).
Pointers and interfaces are unwrapped iteratively, so a non-nil **T pointing at a nil *T, or a non-nil interface holding a typed-nil pointer, are both reported as null without invoking IsNull on the nil receiver.
ReflectIsNull never panics. Values that cannot be passed to reflect.Value.Interface (for example, unexported struct fields) are reported as not-null instead.
func SQLArrayLiteral ¶
SQLArrayLiteral joins the passed strings as an SQL array literal. A nil slice will produce NULL, pass an empty non nil slice to get the empty SQL array literal {} (use notnull.SQLArrayLiteral if a nil slice should also produce {}).
The result uses the PostgreSQL array text format ({"a","b"}), see https://www.postgresql.org/docs/current/arrays.html. That format is understood by PostgreSQL and array-compatible databases such as CockroachDB and YugabyteDB; databases without a native array type (MySQL, MariaDB, SQLite, SQL Server, Oracle) are not supported.
func SplitArray ¶
SplitArray splits an SQL or JSON array into its top level elements. Array elements that are quoted strings will not be unquoted, use SplitArrayValues to get the values of quoted string elements. Returns nil in case of an empty array ("{}" or "[]"). Passing "null" or "NULL" as array will return nil without an error.
An unquoted NULL element of an SQL array (null in a JSON array) is returned as the unquoted string "NULL" ("null").
A trailing comma announces an element that is not there and yields an empty string as last element. PostgreSQL rejects such a literal, this parser reports the announced element instead of dropping it silently.
func SplitArrayValues ¶
SplitArrayValues splits an SQL or JSON array into its top level elements like SplitArray and returns the value of every element that is a double quoted string with the quotes removed and the escape sequences of the parsed array syntax undone. Returns nil in case of an empty array ("{}" or "[]"). Passing "null" or "NULL" as array will return nil without an error.
A backslash escapes the following character in a PostgreSQL array element whether it is quoted or not, so every element of an SQL array is unescaped. In a JSON array only double quoted strings are, every other element, like the objects of a JSON array of objects, is returned unchanged.
An unquoted NULL element of an SQL array (null in a JSON array) is returned as the string "NULL" ("null") and is indistinguishable from a quoted "NULL" ("null") string element. Use SplitArray to tell them apart, its elements correspond by index and a quoted element still has its quotes there.
Returns an error for a quoted element of a JSON array that is not a valid JSON string, like one with an invalid escape sequence.
Types ¶
type BoolArray ¶
BoolArray implements the sql.Scanner and driver.Valuer interfaces for a slice of bool. A nil slice is mapped to the SQL NULL value, and a non nil zero length slice to an empty SQL array '{}'.
Value and Scan use the PostgreSQL array text format ({t,f,t}), see https://www.postgresql.org/docs/current/arrays.html. That format is understood by PostgreSQL and array-compatible databases such as CockroachDB and YugabyteDB; databases without a native array type (MySQL, MariaDB, SQLite, SQL Server, Oracle) are not supported.
type FloatArray ¶
type FloatArray []float64
FloatArray implements the sql.Scanner and driver.Valuer interfaces for a slice of float64. A nil slice is mapped to the SQL NULL value, and a non nil zero length slice to an empty SQL array '{}'.
Value and Scan use the PostgreSQL array text format ({1.5,2,3}), see https://www.postgresql.org/docs/current/arrays.html. That format is understood by PostgreSQL and array-compatible databases such as CockroachDB and YugabyteDB; databases without a native array type (MySQL, MariaDB, SQLite, SQL Server, Oracle) are not supported.
func (FloatArray) Contains ¶
func (a FloatArray) Contains(value float64) bool
Contains reports if the passed value is present in a.
func (FloatArray) IsNull ¶
func (a FloatArray) IsNull() bool
IsNull returns true if a is nil. IsNull implements the Nullable interface.
func (FloatArray) Len ¶
func (a FloatArray) Len() int
Len is the number of elements in the collection. One of the methods to implement sort.Interface.
func (FloatArray) Less ¶
func (a FloatArray) Less(i, j int) bool
Less reports whether the element with index i should sort before the element with index j. One of the methods to implement sort.Interface.
func (*FloatArray) Scan ¶
func (a *FloatArray) Scan(src any) error
Scan implements the sql.Scanner interface. A nil source scans to a nil slice (SQL NULL). Any other source scans to a non-nil slice: {} to an empty slice, otherwise the parsed PostgreSQL float array literal like {1.5,2,3}.
func (FloatArray) String ¶
func (a FloatArray) String() string
String implements the fmt.Stringer interface
func (FloatArray) StringOr ¶
func (a FloatArray) StringOr(nilStr string) string
StringOr returns the string representation of a or nilStr if a is null.
func (FloatArray) Swap ¶
func (a FloatArray) Swap(i, j int)
Swap swaps the elements with indexes i and j. One of the methods to implement sort.Interface.
type IntArray ¶
type IntArray []int64
IntArray implements the sql.Scanner and driver.Valuer interfaces for a slice of int64. A nil slice is mapped to the SQL NULL value, and a non nil zero length slice to an empty SQL array '{}'.
Value and Scan use the PostgreSQL array text format ({1,2,3}), see https://www.postgresql.org/docs/current/arrays.html. That format is understood by PostgreSQL and array-compatible databases such as CockroachDB and YugabyteDB; databases without a native array type (MySQL, MariaDB, SQLite, SQL Server, Oracle) are not supported.
func (IntArray) Len ¶
Len is the number of elements in the collection. One of the methods to implement sort.Interface.
func (IntArray) Less ¶
Less reports whether the element with index i should sort before the element with index j. One of the methods to implement sort.Interface.
func (*IntArray) Scan ¶
Scan implements the sql.Scanner interface. A nil source scans to a nil slice (SQL NULL). Any other source scans to a non-nil slice: {} to an empty slice, otherwise the parsed PostgreSQL integer array literal like {1,2,3}.
type JSON ¶
type JSON []byte
JSON is a []byte slice containing JSON text or nil as the representation of the JSON "null" value. It implements the interfaces json.Marshaler, json.Unmarshaler, driver.Valuer and sql.Scanner. The nil value of the type JSON is marshalled as the JSON "null" and SQL NULL values. The JSON "null" and SQL NULL values are unmarshalled as nil value of the type JSON.
func MarshalJSON ¶
MarshalJSON marshals source as JSON and returns it as a nullable JSON value. If source marshals to the JSON "null" value, the result is JSON("null") and not nil; use the method JSON.MarshalFrom to get nil in that case.
func (JSON) GoString ¶
GoString returns a Go syntax representation of j as a nullable.JSON literal. GoString implements the fmt.GoStringer interface.
func (JSON) IsEmpty ¶
IsEmpty returns true if j is nil, or an empty JSON value like "", "{}", or "[]"
func (JSON) IsNull ¶
IsNull returns true if j is nil or empty. An empty JSON is marshalled as null and written as SQL NULL like nil. IsNull implements the Nullable interface.
func (*JSON) MarshalFrom ¶
MarshalFrom marshals source as JSON and sets it at j when there was no error. If source marshals to the JSON "null" value, j is set to nil.
func (JSON) MarshalJSON ¶
MarshalJSON returns j as the JSON encoding of j. A nil or empty j holds no JSON text and returns null. MarshalJSON implements encoding/json.Marshaler See the package function MarshalJSON to marshal a struct into JSON
func (JSON) PrettyPrint ¶
PrettyPrint implements the pretty.PrintableWithResult interface returning the JSON as a Go literal.
func (*JSON) Scan ¶
Scan stores the src in *j. No validation is done. SQL NULL, the text null, and an empty string or []byte, which hold no JSON text, store nil.
func (JSON) String ¶
String returns the JSON as string. String implements the fmt.Stringer interface.
func (*JSON) UnmarshalJSON ¶
UnmarshalJSON sets *j to a copy of sourceJSON. UnmarshalJSON implements encoding/json.Unmarshaler See method UnmarshalTo for unmarshalling into a struct.
func (JSON) UnmarshalTo ¶
UnmarshalTo unmarshals the JSON of j to dest. A nil j returns an error because it holds no JSON text.
type NonEmptyString ¶
type NonEmptyString string
NonEmptyString is a string type where the empty string value is interpreted as SQL NULL and JSON null by implementing the sql.Scanner and driver.Valuer interfaces and also json.Marshaler and json.Unmarshaler. Note that this type can't hold an empty string that is not interpreted as SQL NULL or JSON null. The string is not trimmed, so a string of spaces is not null.
const NonEmptyStringNull NonEmptyString = ""
NonEmptyStringNull is the SQL NULL and JSON null value for NonEmptyString.
func JoinNonEmptyStrings ¶
func JoinNonEmptyStrings(separator string, strs ...NonEmptyString) NonEmptyString
JoinNonEmptyStrings joins only those strings that are not empty/null with the passed separator between them.
func NonEmptyStringFromError ¶
func NonEmptyStringFromError(err error) NonEmptyString
NonEmptyStringFromError converts an error to a NonEmptyString interpreting a nil error as null value "" or else using err.Error() as value.
func NonEmptyStringFromPtr ¶
func NonEmptyStringFromPtr(ptr *string) NonEmptyString
NonEmptyStringFromPtr converts a string pointer to a NonEmptyString interpreting nil as null value "".
func NonEmptyStringTrimSpace ¶
func NonEmptyStringTrimSpace(str string) NonEmptyString
NonEmptyStringTrimSpace returns a NonEmptyString by trimming space from the passed string. If the passed string with trimmed space is an empty string then the NonEmptyString will represent null.
func NonEmptyStringf ¶
func NonEmptyStringf(format string, a ...any) NonEmptyString
NonEmptyStringf formats a string using fmt.Sprintf and returns it as NonEmptyString. An empty string will be interpreted as null value.
func (NonEmptyString) Get ¶
func (n NonEmptyString) Get() string
Get returns the non nullable string value or panics if the NonEmptyString is null. Note: check with IsNull before using Get!
func (NonEmptyString) IsNotNull ¶
func (n NonEmptyString) IsNotNull() bool
IsNotNull returns true if the string n is not empty.
func (NonEmptyString) IsNull ¶
func (n NonEmptyString) IsNull() bool
IsNull returns true if the string n is empty. IsNull implements the Nullable interface.
func (NonEmptyString) MarshalJSON ¶
func (n NonEmptyString) MarshalJSON() ([]byte, error)
MarshalJSON implements encoding/json.Marshaler by returning the JSON null value for an empty (null) string.
func (NonEmptyString) Ptr ¶
func (n NonEmptyString) Ptr() *string
Ptr returns the address of the string value or nil if n.IsNull()
func (*NonEmptyString) Scan ¶
func (n *NonEmptyString) Scan(value any) error
Scan implements the database/sql.Scanner interface.
func (*NonEmptyString) Set ¶
func (n *NonEmptyString) Set(s string)
Set the passed string as NonEmptyString. Passing an empty string will be interpreted as setting NULL.
func (*NonEmptyString) SetNull ¶
func (n *NonEmptyString) SetNull()
SetNull sets the string to its null value
func (NonEmptyString) StringOr ¶
func (n NonEmptyString) StringOr(nullString string) string
StringOr returns the string value of n or the passed nullString if n.IsNull()
func (NonEmptyString) TrimSpace ¶
func (n NonEmptyString) TrimSpace() NonEmptyString
TrimSpace returns the string with all white-space characters trimmed from beginning and end. A potentially resulting empty string will be interpreted as null.
func (*NonEmptyString) UnmarshalJSON ¶
func (n *NonEmptyString) UnmarshalJSON(j []byte) error
UnmarshalJSON implements encoding/json.Unmarshaler by interpreting the JSON null value as an empty (null) string.
func (*NonEmptyString) UnmarshalText ¶
func (n *NonEmptyString) UnmarshalText(text []byte) error
UnmarshalText implements the encoding.TextUnmarshaler interface
type NullBoolArray ¶
NullBoolArray is a slice of nullable bool values, each element stored as a Type[bool]. It implements the sql.Scanner and driver.Valuer interfaces for a SQL array. JSON marshalling needs no methods on the slice itself: encoding/json handles the slice and each Type[bool] element marshals a value as true/false and a null element as JSON null, e.g. [true,null,false].
A nil slice maps to SQL NULL and JSON null, a non-nil zero length slice to the empty SQL array '{}' and JSON [].
Value and Scan use the PostgreSQL array text format ({t,NULL,f}), see https://www.postgresql.org/docs/current/arrays.html. That format is understood by PostgreSQL and array-compatible databases such as CockroachDB and YugabyteDB; databases without a native array type (MySQL, MariaDB, SQLite, SQL Server, Oracle) are not supported.
func (NullBoolArray) Bools ¶
func (a NullBoolArray) Bools() []bool
Bools returns all NullBoolArray elements as []bool with null elements set to false.
func (NullBoolArray) IsNull ¶
func (a NullBoolArray) IsNull() bool
IsNull returns true if a is nil. IsNull implements the Nullable interface.
func (*NullBoolArray) Scan ¶
func (a *NullBoolArray) Scan(src any) error
Scan implements the sql.Scanner interface. A nil source scans to a nil slice (SQL NULL), the empty array {} to a non-nil empty slice. Otherwise it parses a PostgreSQL boolean array literal like {t,NULL,f} from a string or []byte. The elements t, f, true and false scan as values and NULL as a null Type[bool], all case-insensitive. Any other element returns an error and leaves a unchanged.
func (NullBoolArray) String ¶
func (a NullBoolArray) String() string
String implements the fmt.Stringer interface.
type NullFloatArray ¶
NullFloatArray is a slice of nullable float64 values, each element stored as a Type[float64]. It implements the sql.Scanner and driver.Valuer interfaces for a SQL array. JSON marshalling needs no methods on the slice itself: encoding/json handles the slice and each Type[float64] element marshals a value as a number and a null element as JSON null, e.g. [1.5,null,3].
A nil slice maps to SQL NULL and JSON null, a non-nil zero length slice to the empty SQL array '{}' and JSON [].
Value and Scan use the PostgreSQL array text format ({1.5,NULL,3}), see https://www.postgresql.org/docs/current/arrays.html. That format is understood by PostgreSQL and array-compatible databases such as CockroachDB and YugabyteDB; databases without a native array type (MySQL, MariaDB, SQLite, SQL Server, Oracle) are not supported.
func (NullFloatArray) Floats ¶
func (a NullFloatArray) Floats() []float64
Floats returns all NullFloatArray elements as []float64 with null elements set to 0.
func (NullFloatArray) IsNull ¶
func (a NullFloatArray) IsNull() bool
IsNull returns true if a is nil. IsNull implements the Nullable interface.
func (*NullFloatArray) Scan ¶
func (a *NullFloatArray) Scan(src any) error
Scan implements the sql.Scanner interface. A nil source scans to a nil slice (SQL NULL), the empty array {} to a non-nil empty slice. Otherwise it parses a PostgreSQL float array literal like {1.5,NULL,3} from a string or []byte, NULL elements scanning as a null Type[float64].
func (NullFloatArray) String ¶
func (a NullFloatArray) String() string
String implements the fmt.Stringer interface.
type NullIntArray ¶
NullIntArray is a slice of nullable int64 values, each element stored as a Type[int64]. It implements the sql.Scanner and driver.Valuer interfaces for a SQL array. JSON marshalling needs no methods on the slice itself: encoding/json handles the slice and each Type[int64] element marshals a value as a number and a null element as JSON null, e.g. [1,null,3].
A nil slice maps to SQL NULL and JSON null, a non-nil zero length slice to the empty SQL array '{}' and JSON [].
Value and Scan use the PostgreSQL array text format ({1,NULL,3}), see https://www.postgresql.org/docs/current/arrays.html. That format is understood by PostgreSQL and array-compatible databases such as CockroachDB and YugabyteDB; databases without a native array type (MySQL, MariaDB, SQLite, SQL Server, Oracle) are not supported.
func (NullIntArray) Ints ¶
func (a NullIntArray) Ints() []int64
Ints returns all NullIntArray elements as []int64 with null elements set to 0.
func (NullIntArray) IsNull ¶
func (a NullIntArray) IsNull() bool
IsNull returns true if a is nil. IsNull implements the Nullable interface.
func (*NullIntArray) Scan ¶
func (a *NullIntArray) Scan(src any) error
Scan implements the sql.Scanner interface. A nil source scans to a nil slice (SQL NULL), the empty array {} to a non-nil empty slice. Otherwise it parses a PostgreSQL integer array literal like {1,NULL,3} from a string or []byte, NULL elements scanning as a null Type[int64].
func (NullIntArray) String ¶
func (a NullIntArray) String() string
String implements the fmt.Stringer interface.
type NullSetable ¶
type NullSetable[T any] interface { Nullable // SetNull sets the value to null/empty state. SetNull() // Set assigns a non-null value of type T. Set(T) // Get returns the non-null value or panics if the value is null. // Use IsNull() to check before calling Get() to avoid panics. Get() T // GetOr returns the non-null value or the provided default value if null. // This is a safe alternative to Get() that never panics. GetOr(T) T }
NullSetable is a generic interface that extends Nullable for types that can be set to null and have their values retrieved with fallback options. This interface is typically implemented by nullable wrapper types that provide safe handling of optional values with null state management.
type Nullable ¶
type Nullable interface {
// IsNull returns true if the implementing value is considered null.
IsNull() bool
}
Nullable is an interface with an IsNull method for types that can represent null values.
type NullableValidator ¶
NullableValidator is an interface that combines Nullable and types.Validator for nullable types whose non-null values can be invalid. Its ValidAndNotNull method returns true if the value is valid and not null.
type StringArray ¶
type StringArray = pq.StringArray
StringArray implements the sql.Scanner and driver.Valuer interfaces for a slice of strings. A nil slice is mapped to the SQL NULL value, and a non nil zero length slice to an empty SQL array '{}'.
Value and Scan use the PostgreSQL array text format ({"a","b"}), see https://www.postgresql.org/docs/current/arrays.html. That format is understood by PostgreSQL and array-compatible databases such as CockroachDB and YugabyteDB; databases without a native array type (MySQL, MariaDB, SQLite, SQL Server, Oracle) are not supported.
type Time ¶
Time represents a time.Time where the zero time instant (which is the empty default value of the type) is interpreted as SQL NULL and JSON null. It implements the sql.Scanner and driver.Valuer interfaces and also json.Marshaler and json.Unmarshaler. It assumes that zero time instant is never used in any real life application so it's free to be used as magical value for representing NULL. IsNull uses time.Time.IsZero internally.
var TimeNull Time
TimeNull is a null Time value.
Note: use Time.IsNull or IsNotNull to check for null instead of comparing a Time with TimeNull because Time.IsNull uses time.Time.IsZero internally which can return true for times that are not the empty time.Time{} default value.
func TimeFromPtr ¶
TimeFromPtr returns a nullable.Time from a time.Time pointer with nil interpreted as null.
func TimeParse ¶
TimeParse parses a time value with the provided layout using time.Parse(layout, value) except for when value is one of "", "null", "NULL", then a null/zero time and no error are returned.
func TimeParseInLocation ¶
TimeParseInLocation parses a time value with the provided layout and location using time.ParseInLocation(layout, value, loc) except for when value is one of "", "null", "NULL", then a null/zero time and no error are returned.
func (Time) AddDate ¶
AddDate returns the nullable time corresponding to adding the given number of years, months, and days to t. For example, AddDate(-1, 2, 3) applied to January 1, 2011 returns March 4, 2010.
AddDate normalizes its result in the same way that Date does, so, for example, adding one month to October 31 yields December 1, the normalized form for November 31.
Returns null if n is null.
func (Time) AppendFormat ¶
AppendFormat the time to b using time.Time.AppendFormat or b if n is null.
func (Time) Equal ¶
Equal reports whether n and o represent the same time instant or both are null. Two times can be equal even if they are in different locations. For example, 6:00 +0200 and 4:00 UTC are Equal. See the documentation on the Time type for the pitfalls of using == with Time values; most code should use Equal instead.
func (Time) Get ¶
Get returns the non nullable time.Time value or panics if the Time is null. Note: check with IsNull before using Get!
func (Time) GetOr ¶
GetOr returns the non nullable time.Time value or the passed defaultTime if the Time is null.
func (Time) IsNotNull ¶
IsNotNull returns true if the Time is not null. Uses time.Time.IsZero internally.
func (Time) IsNull ¶
IsNull returns true if the Time is null. Uses time.Time.IsZero internally. IsNull implements the Nullable interface.
func (Time) JSONSchema ¶
func (Time) JSONSchema() *jsonschema.Schema
JSONSchema returns a JSON schema for Time as a nullable date-time string, allowing either an RFC 3339 date-time string or null. JSONSchema implements the github.com/invopop/jsonschema.Schema interface.
func (Time) MarshalJSON ¶
MarshalJSON implements encoding/json.Marshaler
func (Time) MarshalText ¶
MarshalText implements the encoding.TextMarshaler interface. The time is formatted in RFC 3339 format, with sub-second precision added if present. "NULL" is returned as text if the time is null.
func (*Time) MarshalXMLAttr ¶
MarshalXMLAttr implements encoding/xml.MarshalerAttr by writing the text of MarshalText, and no attribute for a nil pointer, because encoding/xml calls MarshalText through a nil pointer attribute field and panics.
func (Time) PrettyPrint ¶
PrettyPrint implements the pretty.PrintableWithResult interface
func (*Time) UnmarshalJSON ¶
UnmarshalJSON implements encoding/json.Unmarshaler. Interprets []byte(nil), []byte(""), []byte("null") as null. The JSON string "" is not null but an error.
func (*Time) UnmarshalText ¶
UnmarshalText implements the encoding.TextUnmarshaler interface. The time is expected to be in RFC 3339 format. Empty text or "null" in any letter case will set the time to null.
type TrimmedString ¶
type TrimmedString string
TrimmedString is a string type where the empty trimmed string value is interpreted as SQL NULL and JSON null by implementing the sql.Scanner and driver.Valuer interfaces and also json.Marshaler and json.Unmarshaler.
Note that this type can't hold a not null empty string, because it will interpret it as null SQL or JSON value.
const TrimmedStringNull TrimmedString = ""
TrimmedStringNull is the NULL value "" for TrimmedString
func TrimmedStringFrom ¶
func TrimmedStringFrom(str string) TrimmedString
TrimmedStringFrom trims the passed str and returns it as TrimmedString An empty trimmed string will be interpreted as null value.
func TrimmedStringFromError ¶
func TrimmedStringFromError(err error) TrimmedString
TrimmedStringFromError converts an error to a TrimmedString interpreting a nil error as null value "" or else using err.Error() as value.
func TrimmedStringFromPtr ¶
func TrimmedStringFromPtr(ptr *string) TrimmedString
TrimmedStringFromPtr converts a string pointer to a TrimmedString interpreting nil as null value "". An empty trimmed string will be interpreted as null value.
func TrimmedStringJoin ¶
func TrimmedStringJoin[S ~string](separator string, strs ...S) TrimmedString
TrimmedStringJoin joins only those strings that are not empty after trimming with the passed separator between them.
func TrimmedStringf ¶
func TrimmedStringf(format string, a ...any) TrimmedString
TrimmedStringf formats a string using fmt.Sprintf and returns it as TrimmedString. An empty trimmed string will be interpreted as null value.
func (TrimmedString) Contains ¶
func (s TrimmedString) Contains(substr string) bool
Contains reports whether substr is within s.
func (TrimmedString) ContainsAny ¶
func (s TrimmedString) ContainsAny(chars string) bool
ContainsAny reports whether any Unicode code points in chars are within s.
func (TrimmedString) ContainsRune ¶
func (s TrimmedString) ContainsRune(r rune) bool
ContainsRune reports whether the Unicode code point r is within s.
func (TrimmedString) Get ¶
func (s TrimmedString) Get() string
Get returns the non nullable string value or panics if the TrimmedString is null. Note: check with IsNull before using Get!
func (TrimmedString) HasPrefix ¶
func (s TrimmedString) HasPrefix(prefix string) bool
HasPrefix tests whether the TrimmedString begins with prefix.
func (TrimmedString) HasSuffix ¶
func (s TrimmedString) HasSuffix(suffix string) bool
HasSuffix tests whether the TrimmedString ends with suffix.
func (TrimmedString) IsNotNull ¶
func (s TrimmedString) IsNotNull() bool
IsNotNull returns true if the string is not empty.
func (TrimmedString) IsNull ¶
func (s TrimmedString) IsNull() bool
IsNull returns true if the trimmed string is empty, which is also the case when the underlying string consists only of runes removed by strutil.TrimSpace. Value, MarshalJSON and MarshalText write such a string as null.
IsNull implements the Nullable interface.
func (TrimmedString) JSONSchema ¶
func (TrimmedString) JSONSchema() *jsonschema.Schema
JSONSchema returns a JSON schema for TrimmedString as a nullable string, allowing either a plain string or null. JSONSchema implements the github.com/invopop/jsonschema.Schema interface.
func (TrimmedString) MarshalJSON ¶
func (s TrimmedString) MarshalJSON() ([]byte, error)
MarshalJSON implements encoding/json.Marshaler by returning the JSON null value for an empty (null) string.
func (TrimmedString) MarshalText ¶
func (s TrimmedString) MarshalText() ([]byte, error)
MarshalText implements the encoding.TextMarshaler interface
func (TrimmedString) MarshalXML ¶
func (s TrimmedString) MarshalXML(e *xml.Encoder, start xml.StartElement) error
MarshalXML implements encoding/xml.Marshaler by encoding the trimmed string as the character data of an XML element. A null (empty) string encodes as an empty element.
func (*TrimmedString) MarshalXMLAttr ¶
MarshalXMLAttr implements encoding/xml.MarshalerAttr by writing the text of MarshalText, and no attribute for a nil pointer, because encoding/xml calls MarshalText through a nil pointer attribute field and panics.
func (TrimmedString) Ptr ¶
func (s TrimmedString) Ptr() *string
Ptr returns the address of the string value or nil if n.IsNull()
func (TrimmedString) ReplaceAll ¶
func (s TrimmedString) ReplaceAll(old, new string) TrimmedString
ReplaceAll returns a copy of the TrimmedString with all non-overlapping instances of old replaced by new. If old is empty, it matches at the beginning of the string and after each UTF-8 sequence, yielding up to k+1 replacements for a k-rune string.
func (*TrimmedString) Scan ¶
func (s *TrimmedString) Scan(value any) error
Scan implements the database/sql.Scanner interface.
func (*TrimmedString) Set ¶
func (s *TrimmedString) Set(str string)
Set the passed string as TrimmedString. Passing an empty trimmed string will be interpreted as setting NULL.
func (*TrimmedString) SetNull ¶
func (s *TrimmedString) SetNull()
SetNull sets the string to its null value
func (TrimmedString) Split ¶
func (s TrimmedString) Split(sep string) []TrimmedString
Split slices s into all substrings separated by sep and returns a slice of the substrings between those separators.
If s does not contain sep and sep is not empty, Split returns a slice of length 1 whose only element is s.
If sep is empty, Split splits after each UTF-8 sequence. If both s and sep are empty, Split returns an empty slice.
It is equivalent to SplitN with a count of -1.
To split around the first instance of a separator, see Cut.
func (TrimmedString) String ¶
func (s TrimmedString) String() string
String implements the fmt.Stringer interface by returning a trimmed string that might be empty in case of the NULL value or an underlying string consisting only of whitespace.
func (TrimmedString) StringOr ¶
func (s TrimmedString) StringOr(nullString string) string
StringOr returns the trimmed string value of n or the passed nullString if n.IsNull()
func (TrimmedString) ToLower ¶
func (s TrimmedString) ToLower() TrimmedString
ToLower returns s with all Unicode letters mapped to their lower case.
func (TrimmedString) ToUpper ¶
func (s TrimmedString) ToUpper() TrimmedString
ToUpper returns s with all Unicode letters mapped to their upper case.
func (TrimmedString) ToValidUTF8 ¶
func (s TrimmedString) ToValidUTF8(replacement string) TrimmedString
ToValidUTF8 returns a copy of the TrimmedString with each run of invalid UTF-8 byte sequences replaced by the replacement string, which may be empty.
func (TrimmedString) TrimPrefix ¶
func (s TrimmedString) TrimPrefix(prefix string) TrimmedString
TrimPrefix returns s without the provided leading prefix string. If the TrimmedString doesn't start with prefix, s is returned unchanged.
func (TrimmedString) TrimSuffix ¶
func (s TrimmedString) TrimSuffix(suffix string) TrimmedString
TrimSuffix returns s without the provided trailing suffix string. If the TrimmedString doesn't end with suffix, s is returned unchanged.
func (*TrimmedString) UnmarshalJSON ¶
func (s *TrimmedString) UnmarshalJSON(j []byte) error
UnmarshalJSON implements encoding/json.Unmarshaler.
func (*TrimmedString) UnmarshalText ¶
func (s *TrimmedString) UnmarshalText(text []byte) error
UnmarshalText implements the encoding.TextUnmarshaler interface
func (*TrimmedString) UnmarshalXML ¶
func (s *TrimmedString) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error
UnmarshalXML implements encoding/xml.Unmarshaler by decoding the character data of the XML element, trimming whitespace, and storing the result. An empty element sets s to the null value.
type Type ¶
type Type[T any] struct { // contains filtered or unexported fields }
Type wraps a type T to support null values without resorting to pointers.
The zero value represents null.
Type implements the following interfaces:
- database/sql/driver.Valuer
- database/sql.Scanner
- encoding/json.Marshaler
- encoding/json.Unmarshaler
It also provides a JSONSchema method to generate a JSON Schema for the type using the github.com/invopop/jsonschema package.
Use TypeFromPtr to create a valid nullable type from a pointer. Use Type.Ptr to get a pointer to the value. Use Type.Get to get a non-null value. Use Type.GetOr to get a non-null value or a default value if the value is null. Use Type.Set to set the value. Use Type.SetNull to set the value to null.
func TypeFromPtr ¶
TypeFromPtr returns a nullable type from a pointer. If the pointer is nil, the returned type is null. If the pointer is non-nil, the returned type is valid and contains a copy of the dereferenced pointer value.
See Type[T].Ptr for the inverse.
func (Type[T]) Get ¶
func (t Type[T]) Get() T
Get returns the non-null value or panics if the value is null.
Use IsNotNull first to check if the value is not null.
func (Type[T]) GetOr ¶
func (t Type[T]) GetOr(defaultValue T) T
GetOr returns the non-null value or a default value if the value is null.
func (Type[T]) JSONSchema ¶
func (t Type[T]) JSONSchema() *jsonschema.Schema
JSONSchema returns a JSON Schema for the type using the github.com/invopop/jsonschema package.
func (Type[T]) MarshalJSON ¶
MarshalJSON implements encoding/json.Marshaler
func (Type[T]) Ptr ¶
func (t Type[T]) Ptr() *T
Ptr returns a pointer to the value or nil if the value is null.
See TypeFromPtr[T] for the inverse.
func (*Type[T]) UnmarshalJSON ¶
UnmarshalJSON implements encoding/json.Unmarshaler. Interprets []byte(nil), []byte(""), []byte("null") as null.