github.com/acoshift/pgsql@v0.15.3/null.go (about) 1 package pgsql 2 3 import ( 4 "database/sql" 5 "database/sql/driver" 6 _ "unsafe" 7 ) 8 9 func Null[T comparable](v *T) interface { 10 driver.Valuer 11 sql.Scanner 12 } { 13 return &null[T]{v} 14 } 15 16 type null[T comparable] struct { 17 value *T 18 } 19 20 func (s *null[T]) Scan(src any) error { 21 *s.value = *(new(T)) 22 if src == nil { 23 return nil 24 } 25 26 return convertAssign(s.value, src) 27 } 28 29 func (s null[T]) Value() (driver.Value, error) { 30 if s.value == nil || isZero(*s.value) || *s.value == *(new(T)) { 31 return nil, nil 32 } 33 if v, ok := any(s.value).(driver.Valuer); ok { 34 return v.Value() 35 } 36 return *s.value, nil 37 } 38 39 type zeroer interface { 40 IsZero() bool 41 } 42 43 func isZero(v any) bool { 44 if z, ok := v.(zeroer); ok { 45 return z.IsZero() 46 } 47 return false 48 } 49 50 //go:linkname convertAssign database/sql.convertAssign 51 func convertAssign(dst, src any) error