From 99fb8cf2f33d61b19dc417af17d02fc82eac306e Mon Sep 17 00:00:00 2001 From: Jack Christensen Date: Tue, 18 Jan 2022 21:49:38 -0600 Subject: [PATCH] Convert timestamp and timestamptz to Codec --- pgtype/builtin_wrappers.go | 44 +++ pgtype/pgtype.go | 8 +- pgtype/timestamp.go | 410 ++++++++++++++----------- pgtype/timestamp_array.go | 505 ------------------------------- pgtype/timestamp_array_test.go | 307 ------------------- pgtype/timestamp_test.go | 186 ++---------- pgtype/timestamptz.go | 443 +++++++++++++++------------ pgtype/timestamptz_array.go | 505 ------------------------------- pgtype/timestamptz_array_test.go | 343 --------------------- pgtype/timestamptz_test.go | 181 ++--------- pgtype/zeronull/timestamp.go | 82 ++--- pgtype/zeronull/timestamptz.go | 106 +++---- 12 files changed, 630 insertions(+), 2490 deletions(-) delete mode 100644 pgtype/timestamp_array.go delete mode 100644 pgtype/timestamp_array_test.go delete mode 100644 pgtype/timestamptz_array.go delete mode 100644 pgtype/timestamptz_array_test.go diff --git a/pgtype/builtin_wrappers.go b/pgtype/builtin_wrappers.go index 5689b321..3c8d23fb 100644 --- a/pgtype/builtin_wrappers.go +++ b/pgtype/builtin_wrappers.go @@ -342,6 +342,50 @@ func (w timeWrapper) DateValue() (Date, error) { return Date{Time: time.Time(w), Valid: true}, nil } +func (w *timeWrapper) ScanTimestamp(v Timestamp) error { + if !v.Valid { + return fmt.Errorf("cannot scan NULL into *time.Time") + } + + switch v.InfinityModifier { + case None: + *w = timeWrapper(v.Time) + return nil + case Infinity: + return fmt.Errorf("cannot scan Infinity into *time.Time") + case NegativeInfinity: + return fmt.Errorf("cannot scan -Infinity into *time.Time") + default: + return fmt.Errorf("invalid InfinityModifier: %v", v.InfinityModifier) + } +} + +func (w timeWrapper) TimestampValue() (Timestamp, error) { + return Timestamp{Time: time.Time(w), Valid: true}, nil +} + +func (w *timeWrapper) ScanTimestamptz(v Timestamptz) error { + if !v.Valid { + return fmt.Errorf("cannot scan NULL into *time.Time") + } + + switch v.InfinityModifier { + case None: + *w = timeWrapper(v.Time) + return nil + case Infinity: + return fmt.Errorf("cannot scan Infinity into *time.Time") + case NegativeInfinity: + return fmt.Errorf("cannot scan -Infinity into *time.Time") + default: + return fmt.Errorf("invalid InfinityModifier: %v", v.InfinityModifier) + } +} + +func (w timeWrapper) TimestamptzValue() (Timestamptz, error) { + return Timestamptz{Time: time.Time(w), Valid: true}, nil +} + type durationWrapper time.Duration func (w *durationWrapper) ScanInterval(v Interval) error { diff --git a/pgtype/pgtype.go b/pgtype/pgtype.go index 744671ab..5072d061 100644 --- a/pgtype/pgtype.go +++ b/pgtype/pgtype.go @@ -287,8 +287,8 @@ func NewConnInfo() *ConnInfo { ci.RegisterDataType(DataType{Name: "_name", OID: NameArrayOID, Codec: &ArrayCodec{ElementCodec: TextCodec{}, ElementOID: NameOID}}) ci.RegisterDataType(DataType{Value: &NumericArray{}, Name: "_numeric", OID: NumericArrayOID}) ci.RegisterDataType(DataType{Name: "_text", OID: TextArrayOID, Codec: &ArrayCodec{ElementCodec: TextCodec{}, ElementOID: TextOID}}) - ci.RegisterDataType(DataType{Value: &TimestampArray{}, Name: "_timestamp", OID: TimestampArrayOID}) - ci.RegisterDataType(DataType{Value: &TimestamptzArray{}, Name: "_timestamptz", OID: TimestamptzArrayOID}) + ci.RegisterDataType(DataType{Name: "_timestamp", OID: TimestampArrayOID, Codec: &ArrayCodec{ElementCodec: TimestampCodec{}, ElementOID: TimestampOID}}) + ci.RegisterDataType(DataType{Name: "_timestamptz", OID: TimestamptzArrayOID, Codec: &ArrayCodec{ElementCodec: TimestamptzCodec{}, ElementOID: TimestamptzOID}}) ci.RegisterDataType(DataType{Value: &UUIDArray{}, Name: "_uuid", OID: UUIDArrayOID}) ci.RegisterDataType(DataType{Name: "_jsonb", OID: JSONBArrayOID, Codec: &ArrayCodec{ElementCodec: JSONBCodec{}, ElementOID: JSONBOID}}) ci.RegisterDataType(DataType{Name: "_json", OID: JSONArrayOID, Codec: &ArrayCodec{ElementCodec: JSONCodec{}, ElementOID: JSONOID}}) @@ -335,8 +335,8 @@ func NewConnInfo() *ConnInfo { ci.RegisterDataType(DataType{Name: "text", OID: TextOID, Codec: TextCodec{}}) ci.RegisterDataType(DataType{Value: &TID{}, Name: "tid", OID: TIDOID}) ci.RegisterDataType(DataType{Value: &Time{}, Name: "time", OID: TimeOID}) - ci.RegisterDataType(DataType{Value: &Timestamp{}, Name: "timestamp", OID: TimestampOID}) - ci.RegisterDataType(DataType{Value: &Timestamptz{}, Name: "timestamptz", OID: TimestamptzOID}) + ci.RegisterDataType(DataType{Name: "timestamp", OID: TimestampOID, Codec: TimestampCodec{}}) + ci.RegisterDataType(DataType{Name: "timestamptz", OID: TimestamptzOID, Codec: TimestamptzCodec{}}) // ci.RegisterDataType(DataType{Value: &Tsrange{}, Name: "tsrange", OID: TsrangeOID}) // ci.RegisterDataType(DataType{Value: &TsrangeArray{}, Name: "_tsrange", OID: TsrangeArrayOID}) // ci.RegisterDataType(DataType{Value: &Tstzrange{}, Name: "tstzrange", OID: TstzrangeOID}) diff --git a/pgtype/timestamp.go b/pgtype/timestamp.go index 882cd41a..374aafe4 100644 --- a/pgtype/timestamp.go +++ b/pgtype/timestamp.go @@ -11,203 +11,42 @@ import ( const pgTimestampFormat = "2006-01-02 15:04:05.999999999" -// Timestamp represents the PostgreSQL timestamp type. The PostgreSQL -// timestamp does not have a time zone. This presents a problem when -// translating to and from time.Time which requires a time zone. It is highly -// recommended to use timestamptz whenever possible. Timestamp methods either -// convert to UTC or return an error on non-UTC times. +type TimestampScanner interface { + ScanTimestamp(v Timestamp) error +} + +type TimestampValuer interface { + TimestampValue() (Timestamp, error) +} + +// Timestamp represents the PostgreSQL timestamp type. type Timestamp struct { - Time time.Time // Time must always be in UTC. - Valid bool + Time time.Time // Time zone will be ignored when encoding to PostgreSQL. InfinityModifier InfinityModifier + Valid bool } -// Set converts src into a Timestamp and stores in dst. If src is a -// time.Time in a non-UTC time zone, the time zone is discarded. -func (dst *Timestamp) Set(src interface{}) error { - if src == nil { - *dst = Timestamp{} - return nil - } - - if value, ok := src.(interface{ Get() interface{} }); ok { - value2 := value.Get() - if value2 != value { - return dst.Set(value2) - } - } - - switch value := src.(type) { - case time.Time: - *dst = Timestamp{Time: time.Date(value.Year(), value.Month(), value.Day(), value.Hour(), value.Minute(), value.Second(), value.Nanosecond(), time.UTC), Valid: true} - case *time.Time: - if value == nil { - *dst = Timestamp{} - } else { - return dst.Set(*value) - } - case InfinityModifier: - *dst = Timestamp{InfinityModifier: value, Valid: true} - default: - if originalSrc, ok := underlyingTimeType(src); ok { - return dst.Set(originalSrc) - } - return fmt.Errorf("cannot convert %v to Timestamp", value) - } - +func (ts *Timestamp) ScanTimestamp(v Timestamp) error { + *ts = v return nil } -func (dst Timestamp) Get() interface{} { - if !dst.Valid { - return nil - } - if dst.InfinityModifier != None { - return dst.InfinityModifier - } - return dst.Time -} - -func (src *Timestamp) AssignTo(dst interface{}) error { - if !src.Valid { - return NullAssignTo(dst) - } - - switch v := dst.(type) { - case *time.Time: - if src.InfinityModifier != None { - return fmt.Errorf("cannot assign %v to %T", src, dst) - } - *v = src.Time - return nil - default: - if nextDst, retry := GetAssignToDstType(dst); retry { - return src.AssignTo(nextDst) - } - return fmt.Errorf("unable to assign to %T", dst) - } -} - -// DecodeText decodes from src into dst. The decoded time is considered to -// be in UTC. -func (dst *Timestamp) DecodeText(ci *ConnInfo, src []byte) error { - if src == nil { - *dst = Timestamp{} - return nil - } - - sbuf := string(src) - switch sbuf { - case "infinity": - *dst = Timestamp{Valid: true, InfinityModifier: Infinity} - case "-infinity": - *dst = Timestamp{Valid: true, InfinityModifier: -Infinity} - default: - tim, err := time.Parse(pgTimestampFormat, sbuf) - if err != nil { - return err - } - - *dst = Timestamp{Time: tim, Valid: true} - } - - return nil -} - -// DecodeBinary decodes from src into dst. The decoded time is considered to -// be in UTC. -func (dst *Timestamp) DecodeBinary(ci *ConnInfo, src []byte) error { - if src == nil { - *dst = Timestamp{} - return nil - } - - if len(src) != 8 { - return fmt.Errorf("invalid length for timestamp: %v", len(src)) - } - - microsecSinceY2K := int64(binary.BigEndian.Uint64(src)) - - switch microsecSinceY2K { - case infinityMicrosecondOffset: - *dst = Timestamp{Valid: true, InfinityModifier: Infinity} - case negativeInfinityMicrosecondOffset: - *dst = Timestamp{Valid: true, InfinityModifier: -Infinity} - default: - tim := time.Unix( - microsecFromUnixEpochToY2K/1000000+microsecSinceY2K/1000000, - (microsecFromUnixEpochToY2K%1000000*1000)+(microsecSinceY2K%1000000*1000), - ).UTC() - *dst = Timestamp{Time: tim, Valid: true} - } - - return nil -} - -// EncodeText writes the text encoding of src into w. If src.Time is not in -// the UTC time zone it returns an error. -func (src Timestamp) EncodeText(ci *ConnInfo, buf []byte) ([]byte, error) { - if !src.Valid { - return nil, nil - } - if src.Time.Location() != time.UTC { - return nil, fmt.Errorf("cannot encode non-UTC time into timestamp") - } - - var s string - - switch src.InfinityModifier { - case None: - s = src.Time.Truncate(time.Microsecond).Format(pgTimestampFormat) - case Infinity: - s = "infinity" - case NegativeInfinity: - s = "-infinity" - } - - return append(buf, s...), nil -} - -// EncodeBinary writes the binary encoding of src into w. If src.Time is not in -// the UTC time zone it returns an error. -func (src Timestamp) EncodeBinary(ci *ConnInfo, buf []byte) ([]byte, error) { - if !src.Valid { - return nil, nil - } - if src.Time.Location() != time.UTC { - return nil, fmt.Errorf("cannot encode non-UTC time into timestamp") - } - - var microsecSinceY2K int64 - switch src.InfinityModifier { - case None: - microsecSinceUnixEpoch := src.Time.Unix()*1000000 + int64(src.Time.Nanosecond())/1000 - microsecSinceY2K = microsecSinceUnixEpoch - microsecFromUnixEpochToY2K - case Infinity: - microsecSinceY2K = infinityMicrosecondOffset - case NegativeInfinity: - microsecSinceY2K = negativeInfinityMicrosecondOffset - } - - return pgio.AppendInt64(buf, microsecSinceY2K), nil +func (ts Timestamp) TimestampValue() (Timestamp, error) { + return ts, nil } // Scan implements the database/sql Scanner interface. -func (dst *Timestamp) Scan(src interface{}) error { +func (ts *Timestamp) Scan(src interface{}) error { if src == nil { - *dst = Timestamp{} + *ts = Timestamp{} return nil } switch src := src.(type) { case string: - return dst.DecodeText(nil, []byte(src)) - case []byte: - srcCopy := make([]byte, len(src)) - copy(srcCopy, src) - return dst.DecodeText(nil, srcCopy) + return scanPlanTextTimestampToTimestampScanner{}.Scan(nil, 0, TextFormatCode, []byte(src), ts) case time.Time: - *dst = Timestamp{Time: src, Valid: true} + *ts = Timestamp{Time: src, Valid: true} return nil } @@ -215,13 +54,214 @@ func (dst *Timestamp) Scan(src interface{}) error { } // Value implements the database/sql/driver Valuer interface. -func (src Timestamp) Value() (driver.Value, error) { - if !src.Valid { +func (ts Timestamp) Value() (driver.Value, error) { + if !ts.Valid { return nil, nil } - if src.InfinityModifier != None { - return src.InfinityModifier.String(), nil + if ts.InfinityModifier != None { + return ts.InfinityModifier.String(), nil } - return src.Time, nil + return ts.Time, nil +} + +type TimestampCodec struct{} + +func (TimestampCodec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (TimestampCodec) PreferredFormat() int16 { + return BinaryFormatCode +} + +func (TimestampCodec) PlanEncode(ci *ConnInfo, oid uint32, format int16, value interface{}) EncodePlan { + if _, ok := value.(TimestampValuer); !ok { + return nil + } + + switch format { + case BinaryFormatCode: + return encodePlanTimestampCodecBinary{} + case TextFormatCode: + return encodePlanTimestampCodecText{} + } + + return nil +} + +type encodePlanTimestampCodecBinary struct{} + +func (encodePlanTimestampCodecBinary) Encode(value interface{}, buf []byte) (newBuf []byte, err error) { + ts, err := value.(TimestampValuer).TimestampValue() + if err != nil { + return nil, err + } + + if !ts.Valid { + return nil, nil + } + + var microsecSinceY2K int64 + switch ts.InfinityModifier { + case None: + t := discardTimeZone(ts.Time) + microsecSinceUnixEpoch := t.Unix()*1000000 + int64(t.Nanosecond())/1000 + microsecSinceY2K = microsecSinceUnixEpoch - microsecFromUnixEpochToY2K + case Infinity: + microsecSinceY2K = infinityMicrosecondOffset + case NegativeInfinity: + microsecSinceY2K = negativeInfinityMicrosecondOffset + } + + buf = pgio.AppendInt64(buf, microsecSinceY2K) + + return buf, nil +} + +type encodePlanTimestampCodecText struct{} + +func (encodePlanTimestampCodecText) Encode(value interface{}, buf []byte) (newBuf []byte, err error) { + ts, err := value.(TimestampValuer).TimestampValue() + if err != nil { + return nil, err + } + + var s string + + switch ts.InfinityModifier { + case None: + t := discardTimeZone(ts.Time) + s = t.Truncate(time.Microsecond).Format(pgTimestampFormat) + case Infinity: + s = "infinity" + case NegativeInfinity: + s = "-infinity" + } + + buf = append(buf, s...) + + return buf, nil +} + +func discardTimeZone(t time.Time) time.Time { + if t.Location() != time.UTC { + return time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), time.UTC) + } + + return t +} + +func (TimestampCodec) PlanScan(ci *ConnInfo, oid uint32, format int16, target interface{}, actualTarget bool) ScanPlan { + + switch format { + case BinaryFormatCode: + switch target.(type) { + case TimestampScanner: + return scanPlanBinaryTimestampToTimestampScanner{} + } + case TextFormatCode: + switch target.(type) { + case TimestampScanner: + return scanPlanTextTimestampToTimestampScanner{} + } + } + + return nil +} + +type scanPlanBinaryTimestampToTimestampScanner struct{} + +func (scanPlanBinaryTimestampToTimestampScanner) Scan(ci *ConnInfo, oid uint32, formatCode int16, src []byte, dst interface{}) error { + scanner := (dst).(TimestampScanner) + + if src == nil { + return scanner.ScanTimestamp(Timestamp{}) + } + + if len(src) != 8 { + return fmt.Errorf("invalid length for timestamp: %v", len(src)) + } + + var ts Timestamp + microsecSinceY2K := int64(binary.BigEndian.Uint64(src)) + + switch microsecSinceY2K { + case infinityMicrosecondOffset: + ts = Timestamp{Valid: true, InfinityModifier: Infinity} + case negativeInfinityMicrosecondOffset: + ts = Timestamp{Valid: true, InfinityModifier: -Infinity} + default: + tim := time.Unix( + microsecFromUnixEpochToY2K/1000000+microsecSinceY2K/1000000, + (microsecFromUnixEpochToY2K%1000000*1000)+(microsecSinceY2K%1000000*1000), + ).UTC() + ts = Timestamp{Time: tim, Valid: true} + } + + return scanner.ScanTimestamp(ts) +} + +type scanPlanTextTimestampToTimestampScanner struct{} + +func (scanPlanTextTimestampToTimestampScanner) Scan(ci *ConnInfo, oid uint32, formatCode int16, src []byte, dst interface{}) error { + scanner := (dst).(TimestampScanner) + + if src == nil { + return scanner.ScanTimestamp(Timestamp{}) + } + + var ts Timestamp + sbuf := string(src) + switch sbuf { + case "infinity": + ts = Timestamp{Valid: true, InfinityModifier: Infinity} + case "-infinity": + ts = Timestamp{Valid: true, InfinityModifier: -Infinity} + default: + tim, err := time.Parse(pgTimestampFormat, sbuf) + if err != nil { + return err + } + + ts = Timestamp{Time: tim, Valid: true} + } + + return scanner.ScanTimestamp(ts) +} + +func (c TimestampCodec) DecodeDatabaseSQLValue(ci *ConnInfo, oid uint32, format int16, src []byte) (driver.Value, error) { + if src == nil { + return nil, nil + } + + var ts Timestamp + err := codecScan(c, ci, oid, format, src, &ts) + if err != nil { + return nil, err + } + + if ts.InfinityModifier != None { + return ts.InfinityModifier.String(), nil + } + + return ts.Time, nil +} + +func (c TimestampCodec) DecodeValue(ci *ConnInfo, oid uint32, format int16, src []byte) (interface{}, error) { + if src == nil { + return nil, nil + } + + var ts Timestamp + err := codecScan(c, ci, oid, format, src, &ts) + if err != nil { + return nil, err + } + + if ts.InfinityModifier != None { + return ts.InfinityModifier, nil + } + + return ts.Time, nil } diff --git a/pgtype/timestamp_array.go b/pgtype/timestamp_array.go deleted file mode 100644 index fbf7c48a..00000000 --- a/pgtype/timestamp_array.go +++ /dev/null @@ -1,505 +0,0 @@ -// Code generated by erb. DO NOT EDIT. - -package pgtype - -import ( - "database/sql/driver" - "encoding/binary" - "fmt" - "reflect" - "time" - - "github.com/jackc/pgio" -) - -type TimestampArray struct { - Elements []Timestamp - Dimensions []ArrayDimension - Valid bool -} - -func (dst *TimestampArray) Set(src interface{}) error { - // untyped nil and typed nil interfaces are different - if src == nil { - *dst = TimestampArray{} - return nil - } - - if value, ok := src.(interface{ Get() interface{} }); ok { - value2 := value.Get() - if value2 != value { - return dst.Set(value2) - } - } - - // Attempt to match to select common types: - switch value := src.(type) { - - case []time.Time: - if value == nil { - *dst = TimestampArray{} - } else if len(value) == 0 { - *dst = TimestampArray{Valid: true} - } else { - elements := make([]Timestamp, len(value)) - for i := range value { - if err := elements[i].Set(value[i]); err != nil { - return err - } - } - *dst = TimestampArray{ - Elements: elements, - Dimensions: []ArrayDimension{{Length: int32(len(elements)), LowerBound: 1}}, - Valid: true, - } - } - - case []*time.Time: - if value == nil { - *dst = TimestampArray{} - } else if len(value) == 0 { - *dst = TimestampArray{Valid: true} - } else { - elements := make([]Timestamp, len(value)) - for i := range value { - if err := elements[i].Set(value[i]); err != nil { - return err - } - } - *dst = TimestampArray{ - Elements: elements, - Dimensions: []ArrayDimension{{Length: int32(len(elements)), LowerBound: 1}}, - Valid: true, - } - } - - case []Timestamp: - if value == nil { - *dst = TimestampArray{} - } else if len(value) == 0 { - *dst = TimestampArray{Valid: true} - } else { - *dst = TimestampArray{ - Elements: value, - Dimensions: []ArrayDimension{{Length: int32(len(value)), LowerBound: 1}}, - Valid: true, - } - } - default: - // Fallback to reflection if an optimised match was not found. - // The reflection is necessary for arrays and multidimensional slices, - // but it comes with a 20-50% performance penalty for large arrays/slices - reflectedValue := reflect.ValueOf(src) - if !reflectedValue.IsValid() || reflectedValue.IsZero() { - *dst = TimestampArray{} - return nil - } - - dimensions, elementsLength, ok := findDimensionsFromValue(reflectedValue, nil, 0) - if !ok { - return fmt.Errorf("cannot find dimensions of %v for TimestampArray", src) - } - if elementsLength == 0 { - *dst = TimestampArray{Valid: true} - return nil - } - if len(dimensions) == 0 { - if originalSrc, ok := underlyingSliceType(src); ok { - return dst.Set(originalSrc) - } - return fmt.Errorf("cannot convert %v to TimestampArray", src) - } - - *dst = TimestampArray{ - Elements: make([]Timestamp, elementsLength), - Dimensions: dimensions, - Valid: true, - } - elementCount, err := dst.setRecursive(reflectedValue, 0, 0) - if err != nil { - // Maybe the target was one dimension too far, try again: - if len(dst.Dimensions) > 1 { - dst.Dimensions = dst.Dimensions[:len(dst.Dimensions)-1] - elementsLength = 0 - for _, dim := range dst.Dimensions { - if elementsLength == 0 { - elementsLength = int(dim.Length) - } else { - elementsLength *= int(dim.Length) - } - } - dst.Elements = make([]Timestamp, elementsLength) - elementCount, err = dst.setRecursive(reflectedValue, 0, 0) - if err != nil { - return err - } - } else { - return err - } - } - if elementCount != len(dst.Elements) { - return fmt.Errorf("cannot convert %v to TimestampArray, expected %d dst.Elements, but got %d instead", src, len(dst.Elements), elementCount) - } - } - - return nil -} - -func (dst *TimestampArray) setRecursive(value reflect.Value, index, dimension int) (int, error) { - switch value.Kind() { - case reflect.Array: - fallthrough - case reflect.Slice: - if len(dst.Dimensions) == dimension { - break - } - - valueLen := value.Len() - if int32(valueLen) != dst.Dimensions[dimension].Length { - return 0, fmt.Errorf("multidimensional arrays must have array expressions with matching dimensions") - } - for i := 0; i < valueLen; i++ { - var err error - index, err = dst.setRecursive(value.Index(i), index, dimension+1) - if err != nil { - return 0, err - } - } - - return index, nil - } - if !value.CanInterface() { - return 0, fmt.Errorf("cannot convert all values to TimestampArray") - } - if err := dst.Elements[index].Set(value.Interface()); err != nil { - return 0, fmt.Errorf("%v in TimestampArray", err) - } - index++ - - return index, nil -} - -func (dst TimestampArray) Get() interface{} { - if !dst.Valid { - return nil - } - return dst -} - -func (src *TimestampArray) AssignTo(dst interface{}) error { - if !src.Valid { - return NullAssignTo(dst) - } - - if len(src.Dimensions) <= 1 { - // Attempt to match to select common types: - switch v := dst.(type) { - - case *[]time.Time: - *v = make([]time.Time, len(src.Elements)) - for i := range src.Elements { - if err := src.Elements[i].AssignTo(&((*v)[i])); err != nil { - return err - } - } - return nil - - case *[]*time.Time: - *v = make([]*time.Time, len(src.Elements)) - for i := range src.Elements { - if err := src.Elements[i].AssignTo(&((*v)[i])); err != nil { - return err - } - } - return nil - - } - } - - // Try to convert to something AssignTo can use directly. - if nextDst, retry := GetAssignToDstType(dst); retry { - return src.AssignTo(nextDst) - } - - // Fallback to reflection if an optimised match was not found. - // The reflection is necessary for arrays and multidimensional slices, - // but it comes with a 20-50% performance penalty for large arrays/slices - value := reflect.ValueOf(dst) - if value.Kind() == reflect.Ptr { - value = value.Elem() - } - - switch value.Kind() { - case reflect.Array, reflect.Slice: - default: - return fmt.Errorf("cannot assign %T to %T", src, dst) - } - - if len(src.Elements) == 0 { - if value.Kind() == reflect.Slice { - value.Set(reflect.MakeSlice(value.Type(), 0, 0)) - return nil - } - } - - elementCount, err := src.assignToRecursive(value, 0, 0) - if err != nil { - return err - } - if elementCount != len(src.Elements) { - return fmt.Errorf("cannot assign %v, needed to assign %d elements, but only assigned %d", dst, len(src.Elements), elementCount) - } - - return nil -} - -func (src *TimestampArray) assignToRecursive(value reflect.Value, index, dimension int) (int, error) { - switch kind := value.Kind(); kind { - case reflect.Array: - fallthrough - case reflect.Slice: - if len(src.Dimensions) == dimension { - break - } - - length := int(src.Dimensions[dimension].Length) - if reflect.Array == kind { - typ := value.Type() - if typ.Len() != length { - return 0, fmt.Errorf("expected size %d array, but %s has size %d array", length, typ, typ.Len()) - } - value.Set(reflect.New(typ).Elem()) - } else { - value.Set(reflect.MakeSlice(value.Type(), length, length)) - } - - var err error - for i := 0; i < length; i++ { - index, err = src.assignToRecursive(value.Index(i), index, dimension+1) - if err != nil { - return 0, err - } - } - - return index, nil - } - if len(src.Dimensions) != dimension { - return 0, fmt.Errorf("incorrect dimensions, expected %d, found %d", len(src.Dimensions), dimension) - } - if !value.CanAddr() { - return 0, fmt.Errorf("cannot assign all values from TimestampArray") - } - addr := value.Addr() - if !addr.CanInterface() { - return 0, fmt.Errorf("cannot assign all values from TimestampArray") - } - if err := src.Elements[index].AssignTo(addr.Interface()); err != nil { - return 0, err - } - index++ - return index, nil -} - -func (dst *TimestampArray) DecodeText(ci *ConnInfo, src []byte) error { - if src == nil { - *dst = TimestampArray{} - return nil - } - - uta, err := ParseUntypedTextArray(string(src)) - if err != nil { - return err - } - - var elements []Timestamp - - if len(uta.Elements) > 0 { - elements = make([]Timestamp, len(uta.Elements)) - - for i, s := range uta.Elements { - var elem Timestamp - var elemSrc []byte - if s != "NULL" || uta.Quoted[i] { - elemSrc = []byte(s) - } - err = elem.DecodeText(ci, elemSrc) - if err != nil { - return err - } - - elements[i] = elem - } - } - - *dst = TimestampArray{Elements: elements, Dimensions: uta.Dimensions, Valid: true} - - return nil -} - -func (dst *TimestampArray) DecodeBinary(ci *ConnInfo, src []byte) error { - if src == nil { - *dst = TimestampArray{} - return nil - } - - var arrayHeader ArrayHeader - rp, err := arrayHeader.DecodeBinary(ci, src) - if err != nil { - return err - } - - if len(arrayHeader.Dimensions) == 0 { - *dst = TimestampArray{Dimensions: arrayHeader.Dimensions, Valid: true} - return nil - } - - elementCount := arrayHeader.Dimensions[0].Length - for _, d := range arrayHeader.Dimensions[1:] { - elementCount *= d.Length - } - - elements := make([]Timestamp, elementCount) - - for i := range elements { - elemLen := int(int32(binary.BigEndian.Uint32(src[rp:]))) - rp += 4 - var elemSrc []byte - if elemLen >= 0 { - elemSrc = src[rp : rp+elemLen] - rp += elemLen - } - err = elements[i].DecodeBinary(ci, elemSrc) - if err != nil { - return err - } - } - - *dst = TimestampArray{Elements: elements, Dimensions: arrayHeader.Dimensions, Valid: true} - return nil -} - -func (src TimestampArray) EncodeText(ci *ConnInfo, buf []byte) ([]byte, error) { - if !src.Valid { - return nil, nil - } - - if len(src.Dimensions) == 0 { - return append(buf, '{', '}'), nil - } - - buf = EncodeTextArrayDimensions(buf, src.Dimensions) - - // dimElemCounts is the multiples of elements that each array lies on. For - // example, a single dimension array of length 4 would have a dimElemCounts of - // [4]. A multi-dimensional array of lengths [3,5,2] would have a - // dimElemCounts of [30,10,2]. This is used to simplify when to render a '{' - // or '}'. - dimElemCounts := make([]int, len(src.Dimensions)) - dimElemCounts[len(src.Dimensions)-1] = int(src.Dimensions[len(src.Dimensions)-1].Length) - for i := len(src.Dimensions) - 2; i > -1; i-- { - dimElemCounts[i] = int(src.Dimensions[i].Length) * dimElemCounts[i+1] - } - - inElemBuf := make([]byte, 0, 32) - for i, elem := range src.Elements { - if i > 0 { - buf = append(buf, ',') - } - - for _, dec := range dimElemCounts { - if i%dec == 0 { - buf = append(buf, '{') - } - } - - elemBuf, err := elem.EncodeText(ci, inElemBuf) - if err != nil { - return nil, err - } - if elemBuf == nil { - buf = append(buf, `NULL`...) - } else { - buf = append(buf, QuoteArrayElementIfNeeded(string(elemBuf))...) - } - - for _, dec := range dimElemCounts { - if (i+1)%dec == 0 { - buf = append(buf, '}') - } - } - } - - return buf, nil -} - -func (src TimestampArray) EncodeBinary(ci *ConnInfo, buf []byte) ([]byte, error) { - if !src.Valid { - return nil, nil - } - - arrayHeader := ArrayHeader{ - Dimensions: src.Dimensions, - } - - if dt, ok := ci.DataTypeForName("timestamp"); ok { - arrayHeader.ElementOID = int32(dt.OID) - } else { - return nil, fmt.Errorf("unable to find oid for type name %v", "timestamp") - } - - for i := range src.Elements { - if !src.Elements[i].Valid { - arrayHeader.ContainsNull = true - break - } - } - - buf = arrayHeader.EncodeBinary(ci, buf) - - for i := range src.Elements { - sp := len(buf) - buf = pgio.AppendInt32(buf, -1) - - elemBuf, err := src.Elements[i].EncodeBinary(ci, buf) - if err != nil { - return nil, err - } - if elemBuf != nil { - buf = elemBuf - pgio.SetInt32(buf[sp:], int32(len(buf[sp:])-4)) - } - } - - return buf, nil -} - -// Scan implements the database/sql Scanner interface. -func (dst *TimestampArray) Scan(src interface{}) error { - if src == nil { - return dst.DecodeText(nil, nil) - } - - switch src := src.(type) { - case string: - return dst.DecodeText(nil, []byte(src)) - case []byte: - srcCopy := make([]byte, len(src)) - copy(srcCopy, src) - return dst.DecodeText(nil, srcCopy) - } - - return fmt.Errorf("cannot scan %T", src) -} - -// Value implements the database/sql/driver Valuer interface. -func (src TimestampArray) Value() (driver.Value, error) { - buf, err := src.EncodeText(nil, nil) - if err != nil { - return nil, err - } - if buf == nil { - return nil, nil - } - - return string(buf), nil -} diff --git a/pgtype/timestamp_array_test.go b/pgtype/timestamp_array_test.go deleted file mode 100644 index f78bf14e..00000000 --- a/pgtype/timestamp_array_test.go +++ /dev/null @@ -1,307 +0,0 @@ -package pgtype_test - -import ( - "reflect" - "testing" - "time" - - "github.com/jackc/pgx/v5/pgtype" - "github.com/jackc/pgx/v5/pgtype/testutil" -) - -func TestTimestampArrayTranscode(t *testing.T) { - testutil.TestSuccessfulTranscodeEqFunc(t, "timestamp[]", []interface{}{ - &pgtype.TimestampArray{ - Elements: nil, - Dimensions: nil, - Valid: true, - }, - &pgtype.TimestampArray{ - Elements: []pgtype.Timestamp{ - {Time: time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - {}, - }, - Dimensions: []pgtype.ArrayDimension{{Length: 2, LowerBound: 1}}, - Valid: true, - }, - &pgtype.TimestampArray{}, - &pgtype.TimestampArray{ - Elements: []pgtype.Timestamp{ - {Time: time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2016, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2017, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - {}, - {Time: time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - }, - Dimensions: []pgtype.ArrayDimension{{Length: 3, LowerBound: 1}, {Length: 2, LowerBound: 1}}, - Valid: true, - }, - &pgtype.TimestampArray{ - Elements: []pgtype.Timestamp{ - {Time: time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2015, 2, 2, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2015, 2, 3, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2015, 2, 4, 0, 0, 0, 0, time.UTC), Valid: true}, - }, - Dimensions: []pgtype.ArrayDimension{ - {Length: 2, LowerBound: 4}, - {Length: 2, LowerBound: 2}, - }, - Valid: true, - }, - }, func(a, b interface{}) bool { - ata := a.(pgtype.TimestampArray) - bta := b.(pgtype.TimestampArray) - - if len(ata.Elements) != len(bta.Elements) || ata.Valid != bta.Valid { - return false - } - - for i := range ata.Elements { - ae, be := ata.Elements[i], bta.Elements[i] - if !(ae.Time.Equal(be.Time) && ae.Valid == be.Valid && ae.InfinityModifier == be.InfinityModifier) { - return false - } - } - - return true - }) -} - -func TestTimestampArraySet(t *testing.T) { - successfulTests := []struct { - source interface{} - result pgtype.TimestampArray - }{ - { - source: []time.Time{time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC)}, - result: pgtype.TimestampArray{ - Elements: []pgtype.Timestamp{{Time: time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}}, - Dimensions: []pgtype.ArrayDimension{{LowerBound: 1, Length: 1}}, - Valid: true}, - }, - { - source: (([]time.Time)(nil)), - result: pgtype.TimestampArray{}, - }, - { - source: [][]time.Time{ - {time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC)}, - {time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC)}}, - result: pgtype.TimestampArray{ - Elements: []pgtype.Timestamp{ - {Time: time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC), Valid: true}}, - Dimensions: []pgtype.ArrayDimension{{LowerBound: 1, Length: 2}, {LowerBound: 1, Length: 1}}, - Valid: true}, - }, - { - source: [][][][]time.Time{ - {{{ - time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), - time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC), - time.Date(2017, 5, 6, 0, 0, 0, 0, time.UTC)}}}, - {{{ - time.Date(2018, 7, 8, 0, 0, 0, 0, time.UTC), - time.Date(2019, 9, 10, 0, 0, 0, 0, time.UTC), - time.Date(2020, 11, 12, 0, 0, 0, 0, time.UTC)}}}}, - result: pgtype.TimestampArray{ - Elements: []pgtype.Timestamp{ - {Time: time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2017, 5, 6, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2018, 7, 8, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2019, 9, 10, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2020, 11, 12, 0, 0, 0, 0, time.UTC), Valid: true}}, - Dimensions: []pgtype.ArrayDimension{ - {LowerBound: 1, Length: 2}, - {LowerBound: 1, Length: 1}, - {LowerBound: 1, Length: 1}, - {LowerBound: 1, Length: 3}}, - Valid: true}, - }, - } - - for i, tt := range successfulTests { - var r pgtype.TimestampArray - err := r.Set(tt.source) - if err != nil { - t.Errorf("%d: %v", i, err) - } - - if !reflect.DeepEqual(r, tt.result) { - t.Errorf("%d: expected %v to convert to %v, but it was %v", i, tt.source, tt.result, r) - } - } -} - -func TestTimestampArrayAssignTo(t *testing.T) { - var timeSlice []time.Time - var timeSliceDim2 [][]time.Time - var timeSliceDim4 [][][][]time.Time - var timeArrayDim2 [2][1]time.Time - var timeArrayDim4 [2][1][1][3]time.Time - - simpleTests := []struct { - src pgtype.TimestampArray - dst interface{} - expected interface{} - }{ - { - src: pgtype.TimestampArray{ - Elements: []pgtype.Timestamp{{Time: time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}}, - Dimensions: []pgtype.ArrayDimension{{LowerBound: 1, Length: 1}}, - Valid: true, - }, - dst: &timeSlice, - expected: []time.Time{time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC)}, - }, - { - src: pgtype.TimestampArray{}, - dst: &timeSlice, - expected: (([]time.Time)(nil)), - }, - { - src: pgtype.TimestampArray{Valid: true}, - dst: &timeSlice, - expected: []time.Time{}, - }, - { - src: pgtype.TimestampArray{ - Elements: []pgtype.Timestamp{ - {Time: time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC), Valid: true}}, - Dimensions: []pgtype.ArrayDimension{{LowerBound: 1, Length: 2}, {LowerBound: 1, Length: 1}}, - Valid: true}, - dst: &timeSliceDim2, - expected: [][]time.Time{ - {time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC)}, - {time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC)}}, - }, - { - src: pgtype.TimestampArray{ - Elements: []pgtype.Timestamp{ - {Time: time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2017, 5, 6, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2018, 7, 8, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2019, 9, 10, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2020, 11, 12, 0, 0, 0, 0, time.UTC), Valid: true}}, - Dimensions: []pgtype.ArrayDimension{ - {LowerBound: 1, Length: 2}, - {LowerBound: 1, Length: 1}, - {LowerBound: 1, Length: 1}, - {LowerBound: 1, Length: 3}}, - Valid: true}, - dst: &timeSliceDim4, - expected: [][][][]time.Time{ - {{{ - time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), - time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC), - time.Date(2017, 5, 6, 0, 0, 0, 0, time.UTC)}}}, - {{{ - time.Date(2018, 7, 8, 0, 0, 0, 0, time.UTC), - time.Date(2019, 9, 10, 0, 0, 0, 0, time.UTC), - time.Date(2020, 11, 12, 0, 0, 0, 0, time.UTC)}}}}, - }, - { - src: pgtype.TimestampArray{ - Elements: []pgtype.Timestamp{ - {Time: time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC), Valid: true}}, - Dimensions: []pgtype.ArrayDimension{{LowerBound: 1, Length: 2}, {LowerBound: 1, Length: 1}}, - Valid: true}, - dst: &timeArrayDim2, - expected: [2][1]time.Time{ - {time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC)}, - {time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC)}}, - }, - { - src: pgtype.TimestampArray{ - Elements: []pgtype.Timestamp{ - {Time: time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2017, 5, 6, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2018, 7, 8, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2019, 9, 10, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2020, 11, 12, 0, 0, 0, 0, time.UTC), Valid: true}}, - Dimensions: []pgtype.ArrayDimension{ - {LowerBound: 1, Length: 2}, - {LowerBound: 1, Length: 1}, - {LowerBound: 1, Length: 1}, - {LowerBound: 1, Length: 3}}, - Valid: true}, - dst: &timeArrayDim4, - expected: [2][1][1][3]time.Time{ - {{{ - time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), - time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC), - time.Date(2017, 5, 6, 0, 0, 0, 0, time.UTC)}}}, - {{{ - time.Date(2018, 7, 8, 0, 0, 0, 0, time.UTC), - time.Date(2019, 9, 10, 0, 0, 0, 0, time.UTC), - time.Date(2020, 11, 12, 0, 0, 0, 0, time.UTC)}}}}, - }, - } - - for i, tt := range simpleTests { - err := tt.src.AssignTo(tt.dst) - if err != nil { - t.Errorf("%d: %v", i, err) - } - - if dst := reflect.ValueOf(tt.dst).Elem().Interface(); !reflect.DeepEqual(dst, tt.expected) { - t.Errorf("%d: expected %v to assign %v, but result was %v", i, tt.src, tt.expected, dst) - } - } - - errorTests := []struct { - src pgtype.TimestampArray - dst interface{} - }{ - { - src: pgtype.TimestampArray{ - Elements: []pgtype.Timestamp{{}}, - Dimensions: []pgtype.ArrayDimension{{LowerBound: 1, Length: 1}}, - Valid: true, - }, - dst: &timeSlice, - }, - { - src: pgtype.TimestampArray{ - Elements: []pgtype.Timestamp{ - {Time: time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC), Valid: true}}, - Dimensions: []pgtype.ArrayDimension{{LowerBound: 1, Length: 1}, {LowerBound: 1, Length: 2}}, - Valid: true}, - dst: &timeArrayDim2, - }, - { - src: pgtype.TimestampArray{ - Elements: []pgtype.Timestamp{ - {Time: time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC), Valid: true}}, - Dimensions: []pgtype.ArrayDimension{{LowerBound: 1, Length: 1}, {LowerBound: 1, Length: 2}}, - Valid: true}, - dst: &timeSlice, - }, - { - src: pgtype.TimestampArray{ - Elements: []pgtype.Timestamp{ - {Time: time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC), Valid: true}}, - Dimensions: []pgtype.ArrayDimension{{LowerBound: 1, Length: 2}, {LowerBound: 1, Length: 1}}, - Valid: true}, - dst: &timeArrayDim4, - }, - } - - for i, tt := range errorTests { - err := tt.src.AssignTo(tt.dst) - if err == nil { - t.Errorf("%d: expected error but none was returned (%v -> %v)", i, tt.src, tt.dst) - } - } - -} diff --git a/pgtype/timestamp_test.go b/pgtype/timestamp_test.go index 85de5c94..1caca58b 100644 --- a/pgtype/timestamp_test.go +++ b/pgtype/timestamp_test.go @@ -2,7 +2,6 @@ package pgtype_test import ( "context" - "reflect" "testing" "time" @@ -11,41 +10,35 @@ import ( "github.com/stretchr/testify/require" ) -func TestTimestampTranscode(t *testing.T) { - testutil.TestSuccessfulTranscodeEqFunc(t, "timestamp", []interface{}{ - &pgtype.Timestamp{Time: time.Date(1800, 1, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - &pgtype.Timestamp{Time: time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - &pgtype.Timestamp{Time: time.Date(1905, 1, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - &pgtype.Timestamp{Time: time.Date(1940, 1, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - &pgtype.Timestamp{Time: time.Date(1960, 1, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - &pgtype.Timestamp{Time: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - &pgtype.Timestamp{Time: time.Date(1999, 12, 31, 0, 0, 0, 0, time.UTC), Valid: true}, - &pgtype.Timestamp{Time: time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - &pgtype.Timestamp{Time: time.Date(2000, 1, 2, 0, 0, 0, 0, time.UTC), Valid: true}, - &pgtype.Timestamp{Time: time.Date(2200, 1, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - &pgtype.Timestamp{}, - &pgtype.Timestamp{Valid: true, InfinityModifier: pgtype.Infinity}, - &pgtype.Timestamp{Valid: true, InfinityModifier: -pgtype.Infinity}, - }, func(a, b interface{}) bool { - at := a.(pgtype.Timestamp) - bt := b.(pgtype.Timestamp) +func TestTimestampCodec(t *testing.T) { + testPgxCodec(t, "timestamp", []PgxTranscodeTestCase{ + {time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC), new(time.Time), isExpectedEqTime(time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC))}, + {time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC), new(time.Time), isExpectedEqTime(time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC))}, + {time.Date(1999, 12, 31, 0, 0, 0, 0, time.UTC), new(time.Time), isExpectedEqTime(time.Date(1999, 12, 31, 0, 0, 0, 0, time.UTC))}, + {time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC), new(time.Time), isExpectedEqTime(time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC))}, + {time.Date(2000, 1, 2, 0, 0, 0, 0, time.UTC), new(time.Time), isExpectedEqTime(time.Date(2000, 1, 2, 0, 0, 0, 0, time.UTC))}, + {time.Date(2200, 1, 1, 0, 0, 0, 0, time.UTC), new(time.Time), isExpectedEqTime(time.Date(2200, 1, 1, 0, 0, 0, 0, time.UTC))}, - return at.Time.Equal(bt.Time) && at.Valid == bt.Valid && at.InfinityModifier == bt.InfinityModifier + // Nanosecond truncation + {time.Date(2020, 1, 1, 0, 0, 0, 999999999, time.UTC), new(time.Time), isExpectedEqTime(time.Date(2020, 1, 1, 0, 0, 0, 999999000, time.UTC))}, + {time.Date(2020, 1, 1, 0, 0, 0, 999999001, time.UTC), new(time.Time), isExpectedEqTime(time.Date(2020, 1, 1, 0, 0, 0, 999999000, time.UTC))}, + + {pgtype.Timestamp{InfinityModifier: pgtype.Infinity, Valid: true}, new(pgtype.Timestamp), isExpectedEq(pgtype.Timestamp{InfinityModifier: pgtype.Infinity, Valid: true})}, + {pgtype.Timestamp{InfinityModifier: pgtype.NegativeInfinity, Valid: true}, new(pgtype.Timestamp), isExpectedEq(pgtype.Timestamp{InfinityModifier: pgtype.NegativeInfinity, Valid: true})}, + {pgtype.Timestamp{}, new(pgtype.Timestamp), isExpectedEq(pgtype.Timestamp{})}, + {nil, new(*time.Time), isExpectedEq((*time.Time)(nil))}, }) } // https://github.com/jackc/pgx/v4/pgtype/pull/128 func TestTimestampTranscodeBigTimeBinary(t *testing.T) { conn := testutil.MustConnectPgx(t) - if _, ok := conn.ConnInfo().DataTypeForName("line"); !ok { - t.Skip("Skipping due to no line type") - } defer testutil.MustCloseContext(t, conn) in := &pgtype.Timestamp{Time: time.Date(294276, 12, 31, 23, 59, 59, 999999000, time.UTC), Valid: true} var out pgtype.Timestamp - err := conn.QueryRow(context.Background(), "select $1::timestamptz", in).Scan(&out) + err := conn.QueryRow(context.Background(), "select $1::timestamp", in).Scan(&out) if err != nil { t.Fatal(err) } @@ -54,146 +47,11 @@ func TestTimestampTranscodeBigTimeBinary(t *testing.T) { require.Truef(t, in.Time.Equal(out.Time), "expected %v got %v", in.Time, out.Time) } -func TestTimestampNanosecondsTruncated(t *testing.T) { - tests := []struct { - input time.Time - expected time.Time - }{ - {time.Date(2020, 1, 1, 0, 0, 0, 999999999, time.UTC), time.Date(2020, 1, 1, 0, 0, 0, 999999000, time.UTC)}, - {time.Date(2020, 1, 1, 0, 0, 0, 999999001, time.UTC), time.Date(2020, 1, 1, 0, 0, 0, 999999000, time.UTC)}, - } - for i, tt := range tests { - { - ts := pgtype.Timestamp{Time: tt.input, Valid: true} - buf, err := ts.EncodeText(nil, nil) - if err != nil { - t.Errorf("%d. EncodeText failed - %v", i, err) - } - - ts.DecodeText(nil, buf) - if err != nil { - t.Errorf("%d. DecodeText failed - %v", i, err) - } - - if !(ts.Valid && ts.Time.Equal(tt.expected)) { - t.Errorf("%d. EncodeText did not truncate nanoseconds", i) - } - } - - { - ts := pgtype.Timestamp{Time: tt.input, Valid: true} - buf, err := ts.EncodeBinary(nil, nil) - if err != nil { - t.Errorf("%d. EncodeBinary failed - %v", i, err) - } - - ts.DecodeBinary(nil, buf) - if err != nil { - t.Errorf("%d. DecodeBinary failed - %v", i, err) - } - - if !(ts.Valid && ts.Time.Equal(tt.expected)) { - t.Errorf("%d. EncodeBinary did not truncate nanoseconds", i) - } - } - } -} - // https://github.com/jackc/pgtype/issues/74 -func TestTimestampDecodeTextInvalid(t *testing.T) { - tstz := &pgtype.Timestamp{} - err := tstz.DecodeText(nil, []byte(`eeeee`)) +func TestTimestampCodecDecodeTextInvalid(t *testing.T) { + c := &pgtype.TimestampCodec{} + var ts pgtype.Timestamp + plan := c.PlanScan(nil, pgtype.TimestampOID, pgtype.TextFormatCode, &ts, false) + err := plan.Scan(nil, pgtype.TimestampOID, pgtype.TextFormatCode, []byte(`eeeee`), &ts) require.Error(t, err) } - -func TestTimestampSet(t *testing.T) { - type _time time.Time - - successfulTests := []struct { - source interface{} - result pgtype.Timestamp - }{ - {source: time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC), result: pgtype.Timestamp{Time: time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC), Valid: true}}, - {source: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC), result: pgtype.Timestamp{Time: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC), Valid: true}}, - {source: time.Date(1999, 12, 31, 12, 59, 59, 0, time.UTC), result: pgtype.Timestamp{Time: time.Date(1999, 12, 31, 12, 59, 59, 0, time.UTC), Valid: true}}, - {source: time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC), result: pgtype.Timestamp{Time: time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC), Valid: true}}, - {source: time.Date(2000, 1, 1, 0, 0, 1, 0, time.UTC), result: pgtype.Timestamp{Time: time.Date(2000, 1, 1, 0, 0, 1, 0, time.UTC), Valid: true}}, - {source: time.Date(2200, 1, 1, 0, 0, 0, 0, time.UTC), result: pgtype.Timestamp{Time: time.Date(2200, 1, 1, 0, 0, 0, 0, time.UTC), Valid: true}}, - {source: time.Date(2015, 1, 1, 0, 0, 0, 0, time.Local), result: pgtype.Timestamp{Time: time.Date(2015, 1, 1, 0, 0, 0, 0, time.UTC), Valid: true}}, - {source: _time(time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC)), result: pgtype.Timestamp{Time: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC), Valid: true}}, - {source: pgtype.Infinity, result: pgtype.Timestamp{InfinityModifier: pgtype.Infinity, Valid: true}}, - {source: pgtype.NegativeInfinity, result: pgtype.Timestamp{InfinityModifier: pgtype.NegativeInfinity, Valid: true}}, - } - - for i, tt := range successfulTests { - var r pgtype.Timestamp - err := r.Set(tt.source) - if err != nil { - t.Errorf("%d: %v", i, err) - } - - if r != tt.result { - t.Errorf("%d: expected %v to convert to %v, but it was %v", i, tt.source, tt.result, r) - } - } -} - -func TestTimestampAssignTo(t *testing.T) { - var tim time.Time - var ptim *time.Time - - simpleTests := []struct { - src pgtype.Timestamp - dst interface{} - expected interface{} - }{ - {src: pgtype.Timestamp{Time: time.Date(2015, 1, 1, 0, 0, 0, 0, time.UTC), Valid: true}, dst: &tim, expected: time.Date(2015, 1, 1, 0, 0, 0, 0, time.UTC)}, - {src: pgtype.Timestamp{Time: time.Time{}}, dst: &ptim, expected: ((*time.Time)(nil))}, - } - - for i, tt := range simpleTests { - err := tt.src.AssignTo(tt.dst) - if err != nil { - t.Errorf("%d: %v", i, err) - } - - if dst := reflect.ValueOf(tt.dst).Elem().Interface(); dst != tt.expected { - t.Errorf("%d: expected %v to assign %v, but result was %v", i, tt.src, tt.expected, dst) - } - } - - pointerAllocTests := []struct { - src pgtype.Timestamp - dst interface{} - expected interface{} - }{ - {src: pgtype.Timestamp{Time: time.Date(2015, 1, 1, 0, 0, 0, 0, time.Local), Valid: true}, dst: &ptim, expected: time.Date(2015, 1, 1, 0, 0, 0, 0, time.Local)}, - } - - for i, tt := range pointerAllocTests { - err := tt.src.AssignTo(tt.dst) - if err != nil { - t.Errorf("%d: %v", i, err) - } - - if dst := reflect.ValueOf(tt.dst).Elem().Elem().Interface(); dst != tt.expected { - t.Errorf("%d: expected %v to assign %v, but result was %v", i, tt.src, tt.expected, dst) - } - } - - errorTests := []struct { - src pgtype.Timestamp - dst interface{} - }{ - {src: pgtype.Timestamp{Time: time.Date(2015, 1, 1, 0, 0, 0, 0, time.Local), InfinityModifier: pgtype.Infinity, Valid: true}, dst: &tim}, - {src: pgtype.Timestamp{Time: time.Date(2015, 1, 1, 0, 0, 0, 0, time.Local), InfinityModifier: pgtype.NegativeInfinity, Valid: true}, dst: &tim}, - {src: pgtype.Timestamp{Time: time.Date(2015, 1, 1, 0, 0, 0, 0, time.Local)}, dst: &tim}, - } - - for i, tt := range errorTests { - err := tt.src.AssignTo(tt.dst) - if err == nil { - t.Errorf("%d: expected error but none was returned (%v -> %v)", i, tt.src, tt.dst) - } - } -} diff --git a/pgtype/timestamptz.go b/pgtype/timestamptz.go index 2a711ffa..eec1dca5 100644 --- a/pgtype/timestamptz.go +++ b/pgtype/timestamptz.go @@ -20,88 +20,252 @@ const ( infinityMicrosecondOffset = 9223372036854775807 ) -type Timestamptz struct { - Time time.Time - Valid bool - InfinityModifier InfinityModifier +type TimestamptzScanner interface { + ScanTimestamptz(v Timestamptz) error } -func (dst *Timestamptz) Set(src interface{}) error { +type TimestamptzValuer interface { + TimestamptzValue() (Timestamptz, error) +} + +// Timestamptz represents the PostgreSQL timestamptz type. +type Timestamptz struct { + Time time.Time + InfinityModifier InfinityModifier + Valid bool +} + +func (tstz *Timestamptz) ScanTimestamptz(v Timestamptz) error { + *tstz = v + return nil +} + +func (tstz Timestamptz) TimestamptzValue() (Timestamptz, error) { + return tstz, nil +} + +// Scan implements the database/sql Scanner interface. +func (tstz *Timestamptz) Scan(src interface{}) error { if src == nil { - *dst = Timestamptz{} + *tstz = Timestamptz{} return nil } - if value, ok := src.(interface{ Get() interface{} }); ok { - value2 := value.Get() - if value2 != value { - return dst.Set(value2) - } + switch src := src.(type) { + case string: + return scanPlanTextTimestamptzToTimestamptzScanner{}.Scan(nil, 0, TextFormatCode, []byte(src), tstz) + case time.Time: + *tstz = Timestamptz{Time: src, Valid: true} + return nil } - switch value := src.(type) { - case time.Time: - *dst = Timestamptz{Time: value, Valid: true} - case *time.Time: - if value == nil { - *dst = Timestamptz{} - } else { - return dst.Set(*value) - } - case InfinityModifier: - *dst = Timestamptz{InfinityModifier: value, Valid: true} + return fmt.Errorf("cannot scan %T", src) +} + +// Value implements the database/sql/driver Valuer interface. +func (tstz Timestamptz) Value() (driver.Value, error) { + if !tstz.Valid { + return nil, nil + } + + if tstz.InfinityModifier != None { + return tstz.InfinityModifier.String(), nil + } + return tstz.Time, nil +} + +func (tstz Timestamptz) MarshalJSON() ([]byte, error) { + if !tstz.Valid { + return []byte("null"), nil + } + + var s string + + switch tstz.InfinityModifier { + case None: + s = tstz.Time.Format(time.RFC3339Nano) + case Infinity: + s = "infinity" + case NegativeInfinity: + s = "-infinity" + } + + return json.Marshal(s) +} + +func (tstz *Timestamptz) UnmarshalJSON(b []byte) error { + var s *string + err := json.Unmarshal(b, &s) + if err != nil { + return err + } + + if s == nil { + *tstz = Timestamptz{} + return nil + } + + switch *s { + case "infinity": + *tstz = Timestamptz{Valid: true, InfinityModifier: Infinity} + case "-infinity": + *tstz = Timestamptz{Valid: true, InfinityModifier: -Infinity} default: - if originalSrc, ok := underlyingTimeType(src); ok { - return dst.Set(originalSrc) + // PostgreSQL uses ISO 8601 for to_json function and casting from a string to timestamptz + tim, err := time.Parse(time.RFC3339Nano, *s) + if err != nil { + return err } - return fmt.Errorf("cannot convert %v to Timestamptz", value) + + *tstz = Timestamptz{Time: tim, Valid: true} } return nil } -func (dst Timestamptz) Get() interface{} { - if !dst.Valid { - return nil - } - if dst.InfinityModifier != None { - return dst.InfinityModifier - } - return dst.Time +type TimestamptzCodec struct{} + +func (TimestamptzCodec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode } -func (src *Timestamptz) AssignTo(dst interface{}) error { - if !src.Valid { - return NullAssignTo(dst) - } - - switch v := dst.(type) { - case *time.Time: - if src.InfinityModifier != None { - return fmt.Errorf("cannot assign %v to %T", src, dst) - } - *v = src.Time - return nil - default: - if nextDst, retry := GetAssignToDstType(dst); retry { - return src.AssignTo(nextDst) - } - return fmt.Errorf("unable to assign to %T", dst) - } +func (TimestamptzCodec) PreferredFormat() int16 { + return BinaryFormatCode } -func (dst *Timestamptz) DecodeText(ci *ConnInfo, src []byte) error { +func (TimestamptzCodec) PlanEncode(ci *ConnInfo, oid uint32, format int16, value interface{}) EncodePlan { + if _, ok := value.(TimestamptzValuer); !ok { + return nil + } + + switch format { + case BinaryFormatCode: + return encodePlanTimestamptzCodecBinary{} + case TextFormatCode: + return encodePlanTimestamptzCodecText{} + } + + return nil +} + +type encodePlanTimestamptzCodecBinary struct{} + +func (encodePlanTimestamptzCodecBinary) Encode(value interface{}, buf []byte) (newBuf []byte, err error) { + ts, err := value.(TimestamptzValuer).TimestamptzValue() + if err != nil { + return nil, err + } + + if !ts.Valid { + return nil, nil + } + + var microsecSinceY2K int64 + switch ts.InfinityModifier { + case None: + microsecSinceUnixEpoch := ts.Time.Unix()*1000000 + int64(ts.Time.Nanosecond())/1000 + microsecSinceY2K = microsecSinceUnixEpoch - microsecFromUnixEpochToY2K + case Infinity: + microsecSinceY2K = infinityMicrosecondOffset + case NegativeInfinity: + microsecSinceY2K = negativeInfinityMicrosecondOffset + } + + buf = pgio.AppendInt64(buf, microsecSinceY2K) + + return buf, nil +} + +type encodePlanTimestamptzCodecText struct{} + +func (encodePlanTimestamptzCodecText) Encode(value interface{}, buf []byte) (newBuf []byte, err error) { + ts, err := value.(TimestamptzValuer).TimestamptzValue() + if err != nil { + return nil, err + } + + var s string + + switch ts.InfinityModifier { + case None: + s = ts.Time.UTC().Truncate(time.Microsecond).Format(pgTimestamptzSecondFormat) + case Infinity: + s = "infinity" + case NegativeInfinity: + s = "-infinity" + } + + buf = append(buf, s...) + + return buf, nil +} + +func (TimestamptzCodec) PlanScan(ci *ConnInfo, oid uint32, format int16, target interface{}, actualTarget bool) ScanPlan { + + switch format { + case BinaryFormatCode: + switch target.(type) { + case TimestamptzScanner: + return scanPlanBinaryTimestamptzToTimestamptzScanner{} + } + case TextFormatCode: + switch target.(type) { + case TimestamptzScanner: + return scanPlanTextTimestamptzToTimestamptzScanner{} + } + } + + return nil +} + +type scanPlanBinaryTimestamptzToTimestamptzScanner struct{} + +func (scanPlanBinaryTimestamptzToTimestamptzScanner) Scan(ci *ConnInfo, oid uint32, formatCode int16, src []byte, dst interface{}) error { + scanner := (dst).(TimestamptzScanner) + if src == nil { - *dst = Timestamptz{} - return nil + return scanner.ScanTimestamptz(Timestamptz{}) } + if len(src) != 8 { + return fmt.Errorf("invalid length for timestamptz: %v", len(src)) + } + + var tstz Timestamptz + microsecSinceY2K := int64(binary.BigEndian.Uint64(src)) + + switch microsecSinceY2K { + case infinityMicrosecondOffset: + tstz = Timestamptz{Valid: true, InfinityModifier: Infinity} + case negativeInfinityMicrosecondOffset: + tstz = Timestamptz{Valid: true, InfinityModifier: -Infinity} + default: + tim := time.Unix( + microsecFromUnixEpochToY2K/1000000+microsecSinceY2K/1000000, + (microsecFromUnixEpochToY2K%1000000*1000)+(microsecSinceY2K%1000000*1000), + ) + tstz = Timestamptz{Time: tim, Valid: true} + } + + return scanner.ScanTimestamptz(tstz) +} + +type scanPlanTextTimestamptzToTimestamptzScanner struct{} + +func (scanPlanTextTimestamptzToTimestamptzScanner) Scan(ci *ConnInfo, oid uint32, formatCode int16, src []byte, dst interface{}) error { + scanner := (dst).(TimestamptzScanner) + + if src == nil { + return scanner.ScanTimestamptz(Timestamptz{}) + } + + var tstz Timestamptz sbuf := string(src) switch sbuf { case "infinity": - *dst = Timestamptz{Valid: true, InfinityModifier: Infinity} + tstz = Timestamptz{Valid: true, InfinityModifier: Infinity} case "-infinity": - *dst = Timestamptz{Valid: true, InfinityModifier: -Infinity} + tstz = Timestamptz{Valid: true, InfinityModifier: -Infinity} default: var format string if len(sbuf) >= 9 && (sbuf[len(sbuf)-9] == '-' || sbuf[len(sbuf)-9] == '+') { @@ -117,157 +281,44 @@ func (dst *Timestamptz) DecodeText(ci *ConnInfo, src []byte) error { return err } - *dst = Timestamptz{Time: tim, Valid: true} + tstz = Timestamptz{Time: tim, Valid: true} } - return nil + return scanner.ScanTimestamptz(tstz) } -func (dst *Timestamptz) DecodeBinary(ci *ConnInfo, src []byte) error { +func (c TimestamptzCodec) DecodeDatabaseSQLValue(ci *ConnInfo, oid uint32, format int16, src []byte) (driver.Value, error) { if src == nil { - *dst = Timestamptz{} - return nil - } - - if len(src) != 8 { - return fmt.Errorf("invalid length for timestamptz: %v", len(src)) - } - - microsecSinceY2K := int64(binary.BigEndian.Uint64(src)) - - switch microsecSinceY2K { - case infinityMicrosecondOffset: - *dst = Timestamptz{Valid: true, InfinityModifier: Infinity} - case negativeInfinityMicrosecondOffset: - *dst = Timestamptz{Valid: true, InfinityModifier: -Infinity} - default: - tim := time.Unix( - microsecFromUnixEpochToY2K/1000000+microsecSinceY2K/1000000, - (microsecFromUnixEpochToY2K%1000000*1000)+(microsecSinceY2K%1000000*1000), - ) - *dst = Timestamptz{Time: tim, Valid: true} - } - - return nil -} - -func (src Timestamptz) EncodeText(ci *ConnInfo, buf []byte) ([]byte, error) { - if !src.Valid { return nil, nil } - var s string - - switch src.InfinityModifier { - case None: - s = src.Time.UTC().Truncate(time.Microsecond).Format(pgTimestamptzSecondFormat) - case Infinity: - s = "infinity" - case NegativeInfinity: - s = "-infinity" - } - - return append(buf, s...), nil -} - -func (src Timestamptz) EncodeBinary(ci *ConnInfo, buf []byte) ([]byte, error) { - if !src.Valid { - return nil, nil - } - - var microsecSinceY2K int64 - switch src.InfinityModifier { - case None: - microsecSinceUnixEpoch := src.Time.Unix()*1000000 + int64(src.Time.Nanosecond())/1000 - microsecSinceY2K = microsecSinceUnixEpoch - microsecFromUnixEpochToY2K - case Infinity: - microsecSinceY2K = infinityMicrosecondOffset - case NegativeInfinity: - microsecSinceY2K = negativeInfinityMicrosecondOffset - } - - return pgio.AppendInt64(buf, microsecSinceY2K), nil -} - -// Scan implements the database/sql Scanner interface. -func (dst *Timestamptz) Scan(src interface{}) error { - if src == nil { - *dst = Timestamptz{} - return nil - } - - switch src := src.(type) { - case string: - return dst.DecodeText(nil, []byte(src)) - case []byte: - srcCopy := make([]byte, len(src)) - copy(srcCopy, src) - return dst.DecodeText(nil, srcCopy) - case time.Time: - *dst = Timestamptz{Time: src, Valid: true} - return nil - } - - return fmt.Errorf("cannot scan %T", src) -} - -// Value implements the database/sql/driver Valuer interface. -func (src Timestamptz) Value() (driver.Value, error) { - if !src.Valid { - return nil, nil - } - - if src.InfinityModifier != None { - return src.InfinityModifier.String(), nil - } - return src.Time, nil -} - -func (src Timestamptz) MarshalJSON() ([]byte, error) { - if !src.Valid { - return []byte("null"), nil - } - - var s string - - switch src.InfinityModifier { - case None: - s = src.Time.Format(time.RFC3339Nano) - case Infinity: - s = "infinity" - case NegativeInfinity: - s = "-infinity" - } - - return json.Marshal(s) -} - -func (dst *Timestamptz) UnmarshalJSON(b []byte) error { - var s *string - err := json.Unmarshal(b, &s) + var tstz Timestamptz + err := codecScan(c, ci, oid, format, src, &tstz) if err != nil { - return err + return nil, err } - if s == nil { - *dst = Timestamptz{} - return nil + if tstz.InfinityModifier != None { + return tstz.InfinityModifier.String(), nil } - switch *s { - case "infinity": - *dst = Timestamptz{Valid: true, InfinityModifier: Infinity} - case "-infinity": - *dst = Timestamptz{Valid: true, InfinityModifier: -Infinity} - default: - // PostgreSQL uses ISO 8601 for to_json function and casting from a string to timestamptz - tim, err := time.Parse(time.RFC3339Nano, *s) - if err != nil { - return err - } - - *dst = Timestamptz{Time: tim, Valid: true} - } - - return nil + return tstz.Time, nil +} + +func (c TimestamptzCodec) DecodeValue(ci *ConnInfo, oid uint32, format int16, src []byte) (interface{}, error) { + if src == nil { + return nil, nil + } + + var tstz Timestamptz + err := codecScan(c, ci, oid, format, src, &tstz) + if err != nil { + return nil, err + } + + if tstz.InfinityModifier != None { + return tstz.InfinityModifier, nil + } + + return tstz.Time, nil } diff --git a/pgtype/timestamptz_array.go b/pgtype/timestamptz_array.go deleted file mode 100644 index 4523b251..00000000 --- a/pgtype/timestamptz_array.go +++ /dev/null @@ -1,505 +0,0 @@ -// Code generated by erb. DO NOT EDIT. - -package pgtype - -import ( - "database/sql/driver" - "encoding/binary" - "fmt" - "reflect" - "time" - - "github.com/jackc/pgio" -) - -type TimestamptzArray struct { - Elements []Timestamptz - Dimensions []ArrayDimension - Valid bool -} - -func (dst *TimestamptzArray) Set(src interface{}) error { - // untyped nil and typed nil interfaces are different - if src == nil { - *dst = TimestamptzArray{} - return nil - } - - if value, ok := src.(interface{ Get() interface{} }); ok { - value2 := value.Get() - if value2 != value { - return dst.Set(value2) - } - } - - // Attempt to match to select common types: - switch value := src.(type) { - - case []time.Time: - if value == nil { - *dst = TimestamptzArray{} - } else if len(value) == 0 { - *dst = TimestamptzArray{Valid: true} - } else { - elements := make([]Timestamptz, len(value)) - for i := range value { - if err := elements[i].Set(value[i]); err != nil { - return err - } - } - *dst = TimestamptzArray{ - Elements: elements, - Dimensions: []ArrayDimension{{Length: int32(len(elements)), LowerBound: 1}}, - Valid: true, - } - } - - case []*time.Time: - if value == nil { - *dst = TimestamptzArray{} - } else if len(value) == 0 { - *dst = TimestamptzArray{Valid: true} - } else { - elements := make([]Timestamptz, len(value)) - for i := range value { - if err := elements[i].Set(value[i]); err != nil { - return err - } - } - *dst = TimestamptzArray{ - Elements: elements, - Dimensions: []ArrayDimension{{Length: int32(len(elements)), LowerBound: 1}}, - Valid: true, - } - } - - case []Timestamptz: - if value == nil { - *dst = TimestamptzArray{} - } else if len(value) == 0 { - *dst = TimestamptzArray{Valid: true} - } else { - *dst = TimestamptzArray{ - Elements: value, - Dimensions: []ArrayDimension{{Length: int32(len(value)), LowerBound: 1}}, - Valid: true, - } - } - default: - // Fallback to reflection if an optimised match was not found. - // The reflection is necessary for arrays and multidimensional slices, - // but it comes with a 20-50% performance penalty for large arrays/slices - reflectedValue := reflect.ValueOf(src) - if !reflectedValue.IsValid() || reflectedValue.IsZero() { - *dst = TimestamptzArray{} - return nil - } - - dimensions, elementsLength, ok := findDimensionsFromValue(reflectedValue, nil, 0) - if !ok { - return fmt.Errorf("cannot find dimensions of %v for TimestamptzArray", src) - } - if elementsLength == 0 { - *dst = TimestamptzArray{Valid: true} - return nil - } - if len(dimensions) == 0 { - if originalSrc, ok := underlyingSliceType(src); ok { - return dst.Set(originalSrc) - } - return fmt.Errorf("cannot convert %v to TimestamptzArray", src) - } - - *dst = TimestamptzArray{ - Elements: make([]Timestamptz, elementsLength), - Dimensions: dimensions, - Valid: true, - } - elementCount, err := dst.setRecursive(reflectedValue, 0, 0) - if err != nil { - // Maybe the target was one dimension too far, try again: - if len(dst.Dimensions) > 1 { - dst.Dimensions = dst.Dimensions[:len(dst.Dimensions)-1] - elementsLength = 0 - for _, dim := range dst.Dimensions { - if elementsLength == 0 { - elementsLength = int(dim.Length) - } else { - elementsLength *= int(dim.Length) - } - } - dst.Elements = make([]Timestamptz, elementsLength) - elementCount, err = dst.setRecursive(reflectedValue, 0, 0) - if err != nil { - return err - } - } else { - return err - } - } - if elementCount != len(dst.Elements) { - return fmt.Errorf("cannot convert %v to TimestamptzArray, expected %d dst.Elements, but got %d instead", src, len(dst.Elements), elementCount) - } - } - - return nil -} - -func (dst *TimestamptzArray) setRecursive(value reflect.Value, index, dimension int) (int, error) { - switch value.Kind() { - case reflect.Array: - fallthrough - case reflect.Slice: - if len(dst.Dimensions) == dimension { - break - } - - valueLen := value.Len() - if int32(valueLen) != dst.Dimensions[dimension].Length { - return 0, fmt.Errorf("multidimensional arrays must have array expressions with matching dimensions") - } - for i := 0; i < valueLen; i++ { - var err error - index, err = dst.setRecursive(value.Index(i), index, dimension+1) - if err != nil { - return 0, err - } - } - - return index, nil - } - if !value.CanInterface() { - return 0, fmt.Errorf("cannot convert all values to TimestamptzArray") - } - if err := dst.Elements[index].Set(value.Interface()); err != nil { - return 0, fmt.Errorf("%v in TimestamptzArray", err) - } - index++ - - return index, nil -} - -func (dst TimestamptzArray) Get() interface{} { - if !dst.Valid { - return nil - } - return dst -} - -func (src *TimestamptzArray) AssignTo(dst interface{}) error { - if !src.Valid { - return NullAssignTo(dst) - } - - if len(src.Dimensions) <= 1 { - // Attempt to match to select common types: - switch v := dst.(type) { - - case *[]time.Time: - *v = make([]time.Time, len(src.Elements)) - for i := range src.Elements { - if err := src.Elements[i].AssignTo(&((*v)[i])); err != nil { - return err - } - } - return nil - - case *[]*time.Time: - *v = make([]*time.Time, len(src.Elements)) - for i := range src.Elements { - if err := src.Elements[i].AssignTo(&((*v)[i])); err != nil { - return err - } - } - return nil - - } - } - - // Try to convert to something AssignTo can use directly. - if nextDst, retry := GetAssignToDstType(dst); retry { - return src.AssignTo(nextDst) - } - - // Fallback to reflection if an optimised match was not found. - // The reflection is necessary for arrays and multidimensional slices, - // but it comes with a 20-50% performance penalty for large arrays/slices - value := reflect.ValueOf(dst) - if value.Kind() == reflect.Ptr { - value = value.Elem() - } - - switch value.Kind() { - case reflect.Array, reflect.Slice: - default: - return fmt.Errorf("cannot assign %T to %T", src, dst) - } - - if len(src.Elements) == 0 { - if value.Kind() == reflect.Slice { - value.Set(reflect.MakeSlice(value.Type(), 0, 0)) - return nil - } - } - - elementCount, err := src.assignToRecursive(value, 0, 0) - if err != nil { - return err - } - if elementCount != len(src.Elements) { - return fmt.Errorf("cannot assign %v, needed to assign %d elements, but only assigned %d", dst, len(src.Elements), elementCount) - } - - return nil -} - -func (src *TimestamptzArray) assignToRecursive(value reflect.Value, index, dimension int) (int, error) { - switch kind := value.Kind(); kind { - case reflect.Array: - fallthrough - case reflect.Slice: - if len(src.Dimensions) == dimension { - break - } - - length := int(src.Dimensions[dimension].Length) - if reflect.Array == kind { - typ := value.Type() - if typ.Len() != length { - return 0, fmt.Errorf("expected size %d array, but %s has size %d array", length, typ, typ.Len()) - } - value.Set(reflect.New(typ).Elem()) - } else { - value.Set(reflect.MakeSlice(value.Type(), length, length)) - } - - var err error - for i := 0; i < length; i++ { - index, err = src.assignToRecursive(value.Index(i), index, dimension+1) - if err != nil { - return 0, err - } - } - - return index, nil - } - if len(src.Dimensions) != dimension { - return 0, fmt.Errorf("incorrect dimensions, expected %d, found %d", len(src.Dimensions), dimension) - } - if !value.CanAddr() { - return 0, fmt.Errorf("cannot assign all values from TimestamptzArray") - } - addr := value.Addr() - if !addr.CanInterface() { - return 0, fmt.Errorf("cannot assign all values from TimestamptzArray") - } - if err := src.Elements[index].AssignTo(addr.Interface()); err != nil { - return 0, err - } - index++ - return index, nil -} - -func (dst *TimestamptzArray) DecodeText(ci *ConnInfo, src []byte) error { - if src == nil { - *dst = TimestamptzArray{} - return nil - } - - uta, err := ParseUntypedTextArray(string(src)) - if err != nil { - return err - } - - var elements []Timestamptz - - if len(uta.Elements) > 0 { - elements = make([]Timestamptz, len(uta.Elements)) - - for i, s := range uta.Elements { - var elem Timestamptz - var elemSrc []byte - if s != "NULL" || uta.Quoted[i] { - elemSrc = []byte(s) - } - err = elem.DecodeText(ci, elemSrc) - if err != nil { - return err - } - - elements[i] = elem - } - } - - *dst = TimestamptzArray{Elements: elements, Dimensions: uta.Dimensions, Valid: true} - - return nil -} - -func (dst *TimestamptzArray) DecodeBinary(ci *ConnInfo, src []byte) error { - if src == nil { - *dst = TimestamptzArray{} - return nil - } - - var arrayHeader ArrayHeader - rp, err := arrayHeader.DecodeBinary(ci, src) - if err != nil { - return err - } - - if len(arrayHeader.Dimensions) == 0 { - *dst = TimestamptzArray{Dimensions: arrayHeader.Dimensions, Valid: true} - return nil - } - - elementCount := arrayHeader.Dimensions[0].Length - for _, d := range arrayHeader.Dimensions[1:] { - elementCount *= d.Length - } - - elements := make([]Timestamptz, elementCount) - - for i := range elements { - elemLen := int(int32(binary.BigEndian.Uint32(src[rp:]))) - rp += 4 - var elemSrc []byte - if elemLen >= 0 { - elemSrc = src[rp : rp+elemLen] - rp += elemLen - } - err = elements[i].DecodeBinary(ci, elemSrc) - if err != nil { - return err - } - } - - *dst = TimestamptzArray{Elements: elements, Dimensions: arrayHeader.Dimensions, Valid: true} - return nil -} - -func (src TimestamptzArray) EncodeText(ci *ConnInfo, buf []byte) ([]byte, error) { - if !src.Valid { - return nil, nil - } - - if len(src.Dimensions) == 0 { - return append(buf, '{', '}'), nil - } - - buf = EncodeTextArrayDimensions(buf, src.Dimensions) - - // dimElemCounts is the multiples of elements that each array lies on. For - // example, a single dimension array of length 4 would have a dimElemCounts of - // [4]. A multi-dimensional array of lengths [3,5,2] would have a - // dimElemCounts of [30,10,2]. This is used to simplify when to render a '{' - // or '}'. - dimElemCounts := make([]int, len(src.Dimensions)) - dimElemCounts[len(src.Dimensions)-1] = int(src.Dimensions[len(src.Dimensions)-1].Length) - for i := len(src.Dimensions) - 2; i > -1; i-- { - dimElemCounts[i] = int(src.Dimensions[i].Length) * dimElemCounts[i+1] - } - - inElemBuf := make([]byte, 0, 32) - for i, elem := range src.Elements { - if i > 0 { - buf = append(buf, ',') - } - - for _, dec := range dimElemCounts { - if i%dec == 0 { - buf = append(buf, '{') - } - } - - elemBuf, err := elem.EncodeText(ci, inElemBuf) - if err != nil { - return nil, err - } - if elemBuf == nil { - buf = append(buf, `NULL`...) - } else { - buf = append(buf, QuoteArrayElementIfNeeded(string(elemBuf))...) - } - - for _, dec := range dimElemCounts { - if (i+1)%dec == 0 { - buf = append(buf, '}') - } - } - } - - return buf, nil -} - -func (src TimestamptzArray) EncodeBinary(ci *ConnInfo, buf []byte) ([]byte, error) { - if !src.Valid { - return nil, nil - } - - arrayHeader := ArrayHeader{ - Dimensions: src.Dimensions, - } - - if dt, ok := ci.DataTypeForName("timestamptz"); ok { - arrayHeader.ElementOID = int32(dt.OID) - } else { - return nil, fmt.Errorf("unable to find oid for type name %v", "timestamptz") - } - - for i := range src.Elements { - if !src.Elements[i].Valid { - arrayHeader.ContainsNull = true - break - } - } - - buf = arrayHeader.EncodeBinary(ci, buf) - - for i := range src.Elements { - sp := len(buf) - buf = pgio.AppendInt32(buf, -1) - - elemBuf, err := src.Elements[i].EncodeBinary(ci, buf) - if err != nil { - return nil, err - } - if elemBuf != nil { - buf = elemBuf - pgio.SetInt32(buf[sp:], int32(len(buf[sp:])-4)) - } - } - - return buf, nil -} - -// Scan implements the database/sql Scanner interface. -func (dst *TimestamptzArray) Scan(src interface{}) error { - if src == nil { - return dst.DecodeText(nil, nil) - } - - switch src := src.(type) { - case string: - return dst.DecodeText(nil, []byte(src)) - case []byte: - srcCopy := make([]byte, len(src)) - copy(srcCopy, src) - return dst.DecodeText(nil, srcCopy) - } - - return fmt.Errorf("cannot scan %T", src) -} - -// Value implements the database/sql/driver Valuer interface. -func (src TimestamptzArray) Value() (driver.Value, error) { - buf, err := src.EncodeText(nil, nil) - if err != nil { - return nil, err - } - if buf == nil { - return nil, nil - } - - return string(buf), nil -} diff --git a/pgtype/timestamptz_array_test.go b/pgtype/timestamptz_array_test.go deleted file mode 100644 index e00b7d7f..00000000 --- a/pgtype/timestamptz_array_test.go +++ /dev/null @@ -1,343 +0,0 @@ -package pgtype_test - -import ( - "reflect" - "testing" - "time" - - "github.com/jackc/pgx/v5/pgtype" - "github.com/jackc/pgx/v5/pgtype/testutil" -) - -func TestTimestamptzArrayTranscode(t *testing.T) { - testutil.TestSuccessfulTranscodeEqFunc(t, "timestamptz[]", []interface{}{ - &pgtype.TimestamptzArray{ - Elements: nil, - Dimensions: nil, - Valid: true, - }, - &pgtype.TimestamptzArray{ - Elements: []pgtype.Timestamptz{ - {Time: time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - {}, - }, - Dimensions: []pgtype.ArrayDimension{{Length: 2, LowerBound: 1}}, - Valid: true, - }, - &pgtype.TimestamptzArray{}, - &pgtype.TimestamptzArray{ - Elements: []pgtype.Timestamptz{ - {Time: time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2016, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2017, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - {}, - {Time: time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - }, - Dimensions: []pgtype.ArrayDimension{{Length: 3, LowerBound: 1}, {Length: 2, LowerBound: 1}}, - Valid: true, - }, - &pgtype.TimestamptzArray{ - Elements: []pgtype.Timestamptz{ - {Time: time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2015, 2, 2, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2015, 2, 3, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2015, 2, 4, 0, 0, 0, 0, time.UTC), Valid: true}, - }, - Dimensions: []pgtype.ArrayDimension{ - {Length: 2, LowerBound: 4}, - {Length: 2, LowerBound: 2}, - }, - Valid: true, - }, - }, func(a, b interface{}) bool { - ata := a.(pgtype.TimestamptzArray) - bta := b.(pgtype.TimestamptzArray) - - if len(ata.Elements) != len(bta.Elements) || ata.Valid != bta.Valid { - return false - } - - for i := range ata.Elements { - ae, be := ata.Elements[i], bta.Elements[i] - if !(ae.Time.Equal(be.Time) && ae.Valid == be.Valid && ae.InfinityModifier == be.InfinityModifier) { - return false - } - } - - return true - }) -} - -func TestTimestamptzArraySet(t *testing.T) { - successfulTests := []struct { - source interface{} - result pgtype.TimestamptzArray - }{ - { - source: []time.Time{time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC)}, - result: pgtype.TimestamptzArray{ - Elements: []pgtype.Timestamptz{{Time: time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}}, - Dimensions: []pgtype.ArrayDimension{{LowerBound: 1, Length: 1}}, - Valid: true}, - }, - { - source: (([]time.Time)(nil)), - result: pgtype.TimestamptzArray{}, - }, - { - source: [][]time.Time{ - {time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC)}, - {time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC)}}, - result: pgtype.TimestamptzArray{ - Elements: []pgtype.Timestamptz{ - {Time: time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC), Valid: true}}, - Dimensions: []pgtype.ArrayDimension{{LowerBound: 1, Length: 2}, {LowerBound: 1, Length: 1}}, - Valid: true}, - }, - { - source: [][][][]time.Time{ - {{{ - time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), - time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC), - time.Date(2017, 5, 6, 0, 0, 0, 0, time.UTC)}}}, - {{{ - time.Date(2018, 7, 8, 0, 0, 0, 0, time.UTC), - time.Date(2019, 9, 10, 0, 0, 0, 0, time.UTC), - time.Date(2020, 11, 12, 0, 0, 0, 0, time.UTC)}}}}, - result: pgtype.TimestamptzArray{ - Elements: []pgtype.Timestamptz{ - {Time: time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2017, 5, 6, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2018, 7, 8, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2019, 9, 10, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2020, 11, 12, 0, 0, 0, 0, time.UTC), Valid: true}}, - Dimensions: []pgtype.ArrayDimension{ - {LowerBound: 1, Length: 2}, - {LowerBound: 1, Length: 1}, - {LowerBound: 1, Length: 1}, - {LowerBound: 1, Length: 3}}, - Valid: true}, - }, - { - source: [2][1]time.Time{ - {time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC)}, - {time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC)}}, - result: pgtype.TimestamptzArray{ - Elements: []pgtype.Timestamptz{ - {Time: time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC), Valid: true}}, - Dimensions: []pgtype.ArrayDimension{{LowerBound: 1, Length: 2}, {LowerBound: 1, Length: 1}}, - Valid: true}, - }, - { - source: [2][1][1][3]time.Time{ - {{{ - time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), - time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC), - time.Date(2017, 5, 6, 0, 0, 0, 0, time.UTC)}}}, - {{{ - time.Date(2018, 7, 8, 0, 0, 0, 0, time.UTC), - time.Date(2019, 9, 10, 0, 0, 0, 0, time.UTC), - time.Date(2020, 11, 12, 0, 0, 0, 0, time.UTC)}}}}, - result: pgtype.TimestamptzArray{ - Elements: []pgtype.Timestamptz{ - {Time: time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2017, 5, 6, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2018, 7, 8, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2019, 9, 10, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2020, 11, 12, 0, 0, 0, 0, time.UTC), Valid: true}}, - Dimensions: []pgtype.ArrayDimension{ - {LowerBound: 1, Length: 2}, - {LowerBound: 1, Length: 1}, - {LowerBound: 1, Length: 1}, - {LowerBound: 1, Length: 3}}, - Valid: true}, - }, - } - - for i, tt := range successfulTests { - var r pgtype.TimestamptzArray - err := r.Set(tt.source) - if err != nil { - t.Errorf("%d: %v", i, err) - } - - if !reflect.DeepEqual(r, tt.result) { - t.Errorf("%d: expected %v to convert to %v, but it was %v", i, tt.source, tt.result, r) - } - } -} - -func TestTimestamptzArrayAssignTo(t *testing.T) { - var timeSlice []time.Time - var timeSliceDim2 [][]time.Time - var timeSliceDim4 [][][][]time.Time - var timeArrayDim2 [2][1]time.Time - var timeArrayDim4 [2][1][1][3]time.Time - - simpleTests := []struct { - src pgtype.TimestamptzArray - dst interface{} - expected interface{} - }{ - { - src: pgtype.TimestamptzArray{ - Elements: []pgtype.Timestamptz{{Time: time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}}, - Dimensions: []pgtype.ArrayDimension{{LowerBound: 1, Length: 1}}, - Valid: true, - }, - dst: &timeSlice, - expected: []time.Time{time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC)}, - }, - { - src: pgtype.TimestamptzArray{}, - dst: &timeSlice, - expected: (([]time.Time)(nil)), - }, - { - src: pgtype.TimestamptzArray{Valid: true}, - dst: &timeSlice, - expected: []time.Time{}, - }, - { - src: pgtype.TimestamptzArray{ - Elements: []pgtype.Timestamptz{ - {Time: time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC), Valid: true}}, - Dimensions: []pgtype.ArrayDimension{{LowerBound: 1, Length: 2}, {LowerBound: 1, Length: 1}}, - Valid: true}, - dst: &timeSliceDim2, - expected: [][]time.Time{ - {time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC)}, - {time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC)}}, - }, - { - src: pgtype.TimestamptzArray{ - Elements: []pgtype.Timestamptz{ - {Time: time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2017, 5, 6, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2018, 7, 8, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2019, 9, 10, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2020, 11, 12, 0, 0, 0, 0, time.UTC), Valid: true}}, - Dimensions: []pgtype.ArrayDimension{ - {LowerBound: 1, Length: 2}, - {LowerBound: 1, Length: 1}, - {LowerBound: 1, Length: 1}, - {LowerBound: 1, Length: 3}}, - Valid: true}, - dst: &timeSliceDim4, - expected: [][][][]time.Time{ - {{{ - time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), - time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC), - time.Date(2017, 5, 6, 0, 0, 0, 0, time.UTC)}}}, - {{{ - time.Date(2018, 7, 8, 0, 0, 0, 0, time.UTC), - time.Date(2019, 9, 10, 0, 0, 0, 0, time.UTC), - time.Date(2020, 11, 12, 0, 0, 0, 0, time.UTC)}}}}, - }, - { - src: pgtype.TimestamptzArray{ - Elements: []pgtype.Timestamptz{ - {Time: time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC), Valid: true}}, - Dimensions: []pgtype.ArrayDimension{{LowerBound: 1, Length: 2}, {LowerBound: 1, Length: 1}}, - Valid: true}, - dst: &timeArrayDim2, - expected: [2][1]time.Time{ - {time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC)}, - {time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC)}}, - }, - { - src: pgtype.TimestamptzArray{ - Elements: []pgtype.Timestamptz{ - {Time: time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2017, 5, 6, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2018, 7, 8, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2019, 9, 10, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2020, 11, 12, 0, 0, 0, 0, time.UTC), Valid: true}}, - Dimensions: []pgtype.ArrayDimension{ - {LowerBound: 1, Length: 2}, - {LowerBound: 1, Length: 1}, - {LowerBound: 1, Length: 1}, - {LowerBound: 1, Length: 3}}, - Valid: true}, - dst: &timeArrayDim4, - expected: [2][1][1][3]time.Time{ - {{{ - time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), - time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC), - time.Date(2017, 5, 6, 0, 0, 0, 0, time.UTC)}}}, - {{{ - time.Date(2018, 7, 8, 0, 0, 0, 0, time.UTC), - time.Date(2019, 9, 10, 0, 0, 0, 0, time.UTC), - time.Date(2020, 11, 12, 0, 0, 0, 0, time.UTC)}}}}, - }, - } - - for i, tt := range simpleTests { - err := tt.src.AssignTo(tt.dst) - if err != nil { - t.Errorf("%d: %v", i, err) - } - - if dst := reflect.ValueOf(tt.dst).Elem().Interface(); !reflect.DeepEqual(dst, tt.expected) { - t.Errorf("%d: expected %v to assign %v, but result was %v", i, tt.src, tt.expected, dst) - } - } - - errorTests := []struct { - src pgtype.TimestamptzArray - dst interface{} - }{ - { - src: pgtype.TimestamptzArray{ - Elements: []pgtype.Timestamptz{{}}, - Dimensions: []pgtype.ArrayDimension{{LowerBound: 1, Length: 1}}, - Valid: true, - }, - dst: &timeSlice, - }, - { - src: pgtype.TimestamptzArray{ - Elements: []pgtype.Timestamptz{ - {Time: time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC), Valid: true}}, - Dimensions: []pgtype.ArrayDimension{{LowerBound: 1, Length: 1}, {LowerBound: 1, Length: 2}}, - Valid: true}, - dst: &timeArrayDim2, - }, - { - src: pgtype.TimestamptzArray{ - Elements: []pgtype.Timestamptz{ - {Time: time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC), Valid: true}}, - Dimensions: []pgtype.ArrayDimension{{LowerBound: 1, Length: 1}, {LowerBound: 1, Length: 2}}, - Valid: true}, - dst: &timeSlice, - }, - { - src: pgtype.TimestamptzArray{ - Elements: []pgtype.Timestamptz{ - {Time: time.Date(2015, 2, 1, 0, 0, 0, 0, time.UTC), Valid: true}, - {Time: time.Date(2016, 3, 4, 0, 0, 0, 0, time.UTC), Valid: true}}, - Dimensions: []pgtype.ArrayDimension{{LowerBound: 1, Length: 2}, {LowerBound: 1, Length: 1}}, - Valid: true}, - dst: &timeArrayDim4, - }, - } - - for i, tt := range errorTests { - err := tt.src.AssignTo(tt.dst) - if err == nil { - t.Errorf("%d: expected error but none was returned (%v -> %v)", i, tt.src, tt.dst) - } - } - -} diff --git a/pgtype/timestamptz_test.go b/pgtype/timestamptz_test.go index 332fc8a7..2a45d2cb 100644 --- a/pgtype/timestamptz_test.go +++ b/pgtype/timestamptz_test.go @@ -2,7 +2,6 @@ package pgtype_test import ( "context" - "reflect" "testing" "time" @@ -11,35 +10,29 @@ import ( "github.com/stretchr/testify/require" ) -func TestTimestamptzTranscode(t *testing.T) { - testutil.TestSuccessfulTranscodeEqFunc(t, "timestamptz", []interface{}{ - &pgtype.Timestamptz{Time: time.Date(1800, 1, 1, 0, 0, 0, 0, time.Local), Valid: true}, - &pgtype.Timestamptz{Time: time.Date(1900, 1, 1, 0, 0, 0, 0, time.Local), Valid: true}, - &pgtype.Timestamptz{Time: time.Date(1905, 1, 1, 0, 0, 0, 0, time.Local), Valid: true}, - &pgtype.Timestamptz{Time: time.Date(1940, 1, 1, 0, 0, 0, 0, time.Local), Valid: true}, - &pgtype.Timestamptz{Time: time.Date(1960, 1, 1, 0, 0, 0, 0, time.Local), Valid: true}, - &pgtype.Timestamptz{Time: time.Date(1970, 1, 1, 0, 0, 0, 0, time.Local), Valid: true}, - &pgtype.Timestamptz{Time: time.Date(1999, 12, 31, 0, 0, 0, 0, time.Local), Valid: true}, - &pgtype.Timestamptz{Time: time.Date(2000, 1, 1, 0, 0, 0, 0, time.Local), Valid: true}, - &pgtype.Timestamptz{Time: time.Date(2000, 1, 2, 0, 0, 0, 0, time.Local), Valid: true}, - &pgtype.Timestamptz{Time: time.Date(2200, 1, 1, 0, 0, 0, 0, time.Local), Valid: true}, - &pgtype.Timestamptz{}, - &pgtype.Timestamptz{Valid: true, InfinityModifier: pgtype.Infinity}, - &pgtype.Timestamptz{Valid: true, InfinityModifier: -pgtype.Infinity}, - }, func(a, b interface{}) bool { - at := a.(pgtype.Timestamptz) - bt := b.(pgtype.Timestamptz) +func TestTimestamptzCodec(t *testing.T) { + testPgxCodec(t, "timestamptz", []PgxTranscodeTestCase{ + {time.Date(1900, 1, 1, 0, 0, 0, 0, time.Local), new(time.Time), isExpectedEqTime(time.Date(1900, 1, 1, 0, 0, 0, 0, time.Local))}, + {time.Date(1970, 1, 1, 0, 0, 0, 0, time.Local), new(time.Time), isExpectedEqTime(time.Date(1970, 1, 1, 0, 0, 0, 0, time.Local))}, + {time.Date(1999, 12, 31, 0, 0, 0, 0, time.Local), new(time.Time), isExpectedEqTime(time.Date(1999, 12, 31, 0, 0, 0, 0, time.Local))}, + {time.Date(2000, 1, 1, 0, 0, 0, 0, time.Local), new(time.Time), isExpectedEqTime(time.Date(2000, 1, 1, 0, 0, 0, 0, time.Local))}, + {time.Date(2000, 1, 2, 0, 0, 0, 0, time.Local), new(time.Time), isExpectedEqTime(time.Date(2000, 1, 2, 0, 0, 0, 0, time.Local))}, + {time.Date(2200, 1, 1, 0, 0, 0, 0, time.Local), new(time.Time), isExpectedEqTime(time.Date(2200, 1, 1, 0, 0, 0, 0, time.Local))}, - return at.Time.Equal(bt.Time) && at.Valid == bt.Valid && at.InfinityModifier == bt.InfinityModifier + // Nanosecond truncation + {time.Date(2020, 1, 1, 0, 0, 0, 999999999, time.Local), new(time.Time), isExpectedEqTime(time.Date(2020, 1, 1, 0, 0, 0, 999999000, time.Local))}, + {time.Date(2020, 1, 1, 0, 0, 0, 999999001, time.Local), new(time.Time), isExpectedEqTime(time.Date(2020, 1, 1, 0, 0, 0, 999999000, time.Local))}, + + {pgtype.Timestamptz{InfinityModifier: pgtype.Infinity, Valid: true}, new(pgtype.Timestamptz), isExpectedEq(pgtype.Timestamptz{InfinityModifier: pgtype.Infinity, Valid: true})}, + {pgtype.Timestamptz{InfinityModifier: pgtype.NegativeInfinity, Valid: true}, new(pgtype.Timestamptz), isExpectedEq(pgtype.Timestamptz{InfinityModifier: pgtype.NegativeInfinity, Valid: true})}, + {pgtype.Timestamptz{}, new(pgtype.Timestamptz), isExpectedEq(pgtype.Timestamptz{})}, + {nil, new(*time.Time), isExpectedEq((*time.Time)(nil))}, }) } // https://github.com/jackc/pgx/v4/pgtype/pull/128 func TestTimestamptzTranscodeBigTimeBinary(t *testing.T) { conn := testutil.MustConnectPgx(t) - if _, ok := conn.ConnInfo().DataTypeForName("line"); !ok { - t.Skip("Skipping due to no line type") - } defer testutil.MustCloseContext(t, conn) in := &pgtype.Timestamptz{Time: time.Date(294276, 12, 31, 23, 59, 59, 999999000, time.UTC), Valid: true} @@ -54,149 +47,15 @@ func TestTimestamptzTranscodeBigTimeBinary(t *testing.T) { require.Truef(t, in.Time.Equal(out.Time), "expected %v got %v", in.Time, out.Time) } -func TestTimestamptzNanosecondsTruncated(t *testing.T) { - tests := []struct { - input time.Time - expected time.Time - }{ - {time.Date(2020, 1, 1, 0, 0, 0, 999999999, time.Local), time.Date(2020, 1, 1, 0, 0, 0, 999999000, time.Local)}, - {time.Date(2020, 1, 1, 0, 0, 0, 999999001, time.Local), time.Date(2020, 1, 1, 0, 0, 0, 999999000, time.Local)}, - } - for i, tt := range tests { - { - tstz := pgtype.Timestamptz{Time: tt.input, Valid: true} - buf, err := tstz.EncodeText(nil, nil) - if err != nil { - t.Errorf("%d. EncodeText failed - %v", i, err) - } - - tstz.DecodeText(nil, buf) - if err != nil { - t.Errorf("%d. DecodeText failed - %v", i, err) - } - - if !(tstz.Valid && tstz.Time.Equal(tt.expected)) { - t.Errorf("%d. EncodeText did not truncate nanoseconds", i) - } - } - - { - tstz := pgtype.Timestamptz{Time: tt.input, Valid: true} - buf, err := tstz.EncodeBinary(nil, nil) - if err != nil { - t.Errorf("%d. EncodeBinary failed - %v", i, err) - } - - tstz.DecodeBinary(nil, buf) - if err != nil { - t.Errorf("%d. DecodeBinary failed - %v", i, err) - } - - if !(tstz.Valid && tstz.Time.Equal(tt.expected)) { - t.Errorf("%d. EncodeBinary did not truncate nanoseconds", i) - } - } - } -} - // https://github.com/jackc/pgtype/issues/74 func TestTimestamptzDecodeTextInvalid(t *testing.T) { - tstz := &pgtype.Timestamptz{} - err := tstz.DecodeText(nil, []byte(`eeeee`)) + c := &pgtype.TimestamptzCodec{} + var tstz pgtype.Timestamptz + plan := c.PlanScan(nil, pgtype.TimestamptzOID, pgtype.TextFormatCode, &tstz, false) + err := plan.Scan(nil, pgtype.TimestamptzOID, pgtype.TextFormatCode, []byte(`eeeee`), &tstz) require.Error(t, err) } -func TestTimestamptzSet(t *testing.T) { - type _time time.Time - - successfulTests := []struct { - source interface{} - result pgtype.Timestamptz - }{ - {source: time.Date(1900, 1, 1, 0, 0, 0, 0, time.Local), result: pgtype.Timestamptz{Time: time.Date(1900, 1, 1, 0, 0, 0, 0, time.Local), Valid: true}}, - {source: time.Date(1970, 1, 1, 0, 0, 0, 0, time.Local), result: pgtype.Timestamptz{Time: time.Date(1970, 1, 1, 0, 0, 0, 0, time.Local), Valid: true}}, - {source: time.Date(1999, 12, 31, 12, 59, 59, 0, time.Local), result: pgtype.Timestamptz{Time: time.Date(1999, 12, 31, 12, 59, 59, 0, time.Local), Valid: true}}, - {source: time.Date(2000, 1, 1, 0, 0, 0, 0, time.Local), result: pgtype.Timestamptz{Time: time.Date(2000, 1, 1, 0, 0, 0, 0, time.Local), Valid: true}}, - {source: time.Date(2000, 1, 1, 0, 0, 1, 0, time.Local), result: pgtype.Timestamptz{Time: time.Date(2000, 1, 1, 0, 0, 1, 0, time.Local), Valid: true}}, - {source: time.Date(2200, 1, 1, 0, 0, 0, 0, time.Local), result: pgtype.Timestamptz{Time: time.Date(2200, 1, 1, 0, 0, 0, 0, time.Local), Valid: true}}, - {source: _time(time.Date(1970, 1, 1, 0, 0, 0, 0, time.Local)), result: pgtype.Timestamptz{Time: time.Date(1970, 1, 1, 0, 0, 0, 0, time.Local), Valid: true}}, - {source: pgtype.Infinity, result: pgtype.Timestamptz{InfinityModifier: pgtype.Infinity, Valid: true}}, - {source: pgtype.NegativeInfinity, result: pgtype.Timestamptz{InfinityModifier: pgtype.NegativeInfinity, Valid: true}}, - } - - for i, tt := range successfulTests { - var r pgtype.Timestamptz - err := r.Set(tt.source) - if err != nil { - t.Errorf("%d: %v", i, err) - } - - if r != tt.result { - t.Errorf("%d: expected %v to convert to %v, but it was %v", i, tt.source, tt.result, r) - } - } -} - -func TestTimestamptzAssignTo(t *testing.T) { - var tim time.Time - var ptim *time.Time - - simpleTests := []struct { - src pgtype.Timestamptz - dst interface{} - expected interface{} - }{ - {src: pgtype.Timestamptz{Time: time.Date(2015, 1, 1, 0, 0, 0, 0, time.Local), Valid: true}, dst: &tim, expected: time.Date(2015, 1, 1, 0, 0, 0, 0, time.Local)}, - {src: pgtype.Timestamptz{Time: time.Time{}}, dst: &ptim, expected: ((*time.Time)(nil))}, - } - - for i, tt := range simpleTests { - err := tt.src.AssignTo(tt.dst) - if err != nil { - t.Errorf("%d: %v", i, err) - } - - if dst := reflect.ValueOf(tt.dst).Elem().Interface(); dst != tt.expected { - t.Errorf("%d: expected %v to assign %v, but result was %v", i, tt.src, tt.expected, dst) - } - } - - pointerAllocTests := []struct { - src pgtype.Timestamptz - dst interface{} - expected interface{} - }{ - {src: pgtype.Timestamptz{Time: time.Date(2015, 1, 1, 0, 0, 0, 0, time.Local), Valid: true}, dst: &ptim, expected: time.Date(2015, 1, 1, 0, 0, 0, 0, time.Local)}, - } - - for i, tt := range pointerAllocTests { - err := tt.src.AssignTo(tt.dst) - if err != nil { - t.Errorf("%d: %v", i, err) - } - - if dst := reflect.ValueOf(tt.dst).Elem().Elem().Interface(); dst != tt.expected { - t.Errorf("%d: expected %v to assign %v, but result was %v", i, tt.src, tt.expected, dst) - } - } - - errorTests := []struct { - src pgtype.Timestamptz - dst interface{} - }{ - {src: pgtype.Timestamptz{Time: time.Date(2015, 1, 1, 0, 0, 0, 0, time.Local), InfinityModifier: pgtype.Infinity, Valid: true}, dst: &tim}, - {src: pgtype.Timestamptz{Time: time.Date(2015, 1, 1, 0, 0, 0, 0, time.Local), InfinityModifier: pgtype.NegativeInfinity, Valid: true}, dst: &tim}, - {src: pgtype.Timestamptz{Time: time.Date(2015, 1, 1, 0, 0, 0, 0, time.Local)}, dst: &tim}, - } - - for i, tt := range errorTests { - err := tt.src.AssignTo(tt.dst) - if err == nil { - t.Errorf("%d: expected error but none was returned (%v -> %v)", i, tt.src, tt.dst) - } - } -} - func TestTimestamptzMarshalJSON(t *testing.T) { successfulTests := []struct { source pgtype.Timestamptz diff --git a/pgtype/zeronull/timestamp.go b/pgtype/zeronull/timestamp.go index d96dbf08..1c2a1a63 100644 --- a/pgtype/zeronull/timestamp.go +++ b/pgtype/zeronull/timestamp.go @@ -2,6 +2,7 @@ package zeronull import ( "database/sql/driver" + "fmt" "time" "github.com/jackc/pgx/v5/pgtype" @@ -9,68 +10,37 @@ import ( type Timestamp time.Time -func (dst *Timestamp) DecodeText(ci *pgtype.ConnInfo, src []byte) error { - var nullable pgtype.Timestamp - err := nullable.DecodeText(ci, src) - if err != nil { - return err +func (ts *Timestamp) ScanTimestamp(v pgtype.Timestamp) error { + if !v.Valid { + *ts = Timestamp{} + return nil } - if nullable.Valid { - *dst = Timestamp(nullable.Time) - } else { - *dst = Timestamp{} + switch v.InfinityModifier { + case pgtype.None: + *ts = Timestamp(v.Time) + return nil + case pgtype.Infinity: + return fmt.Errorf("cannot scan Infinity into *time.Time") + case pgtype.NegativeInfinity: + return fmt.Errorf("cannot scan -Infinity into *time.Time") + default: + return fmt.Errorf("invalid InfinityModifier: %v", v.InfinityModifier) } - - return nil } -func (dst *Timestamp) DecodeBinary(ci *pgtype.ConnInfo, src []byte) error { - var nullable pgtype.Timestamp - err := nullable.DecodeBinary(ci, src) - if err != nil { - return err +func (ts Timestamp) TimestampValue() (pgtype.Timestamp, error) { + if time.Time(ts).IsZero() { + return pgtype.Timestamp{}, nil } - if nullable.Valid { - *dst = Timestamp(nullable.Time) - } else { - *dst = Timestamp{} - } - - return nil -} - -func (src Timestamp) EncodeText(ci *pgtype.ConnInfo, buf []byte) ([]byte, error) { - if (src == Timestamp{}) { - return nil, nil - } - - nullable := pgtype.Timestamp{ - Time: time.Time(src), - Valid: true, - } - - return nullable.EncodeText(ci, buf) -} - -func (src Timestamp) EncodeBinary(ci *pgtype.ConnInfo, buf []byte) ([]byte, error) { - if (src == Timestamp{}) { - return nil, nil - } - - nullable := pgtype.Timestamp{ - Time: time.Time(src), - Valid: true, - } - - return nullable.EncodeBinary(ci, buf) + return pgtype.Timestamp{Time: time.Time(ts), Valid: true}, nil } // Scan implements the database/sql Scanner interface. -func (dst *Timestamp) Scan(src interface{}) error { +func (ts *Timestamp) Scan(src interface{}) error { if src == nil { - *dst = Timestamp{} + *ts = Timestamp{} return nil } @@ -80,12 +50,16 @@ func (dst *Timestamp) Scan(src interface{}) error { return err } - *dst = Timestamp(nullable.Time) + *ts = Timestamp(nullable.Time) return nil } // Value implements the database/sql/driver Valuer interface. -func (src Timestamp) Value() (driver.Value, error) { - return pgtype.EncodeValueText(src) +func (ts Timestamp) Value() (driver.Value, error) { + if time.Time(ts).IsZero() { + return nil, nil + } + + return time.Time(ts), nil } diff --git a/pgtype/zeronull/timestamptz.go b/pgtype/zeronull/timestamptz.go index 46448607..c5378059 100644 --- a/pgtype/zeronull/timestamptz.go +++ b/pgtype/zeronull/timestamptz.go @@ -2,6 +2,7 @@ package zeronull import ( "database/sql/driver" + "fmt" "time" "github.com/jackc/pgx/v5/pgtype" @@ -9,83 +10,56 @@ import ( type Timestamptz time.Time -func (dst *Timestamptz) DecodeText(ci *pgtype.ConnInfo, src []byte) error { - var nullable pgtype.Timestamptz - err := nullable.DecodeText(ci, src) - if err != nil { - return err - } - - if nullable.Valid { - *dst = Timestamptz(nullable.Time) - } else { - *dst = Timestamptz{} - } - - return nil -} - -func (dst *Timestamptz) DecodeBinary(ci *pgtype.ConnInfo, src []byte) error { - var nullable pgtype.Timestamptz - err := nullable.DecodeBinary(ci, src) - if err != nil { - return err - } - - if nullable.Valid { - *dst = Timestamptz(nullable.Time) - } else { - *dst = Timestamptz{} - } - - return nil -} - -func (src Timestamptz) EncodeText(ci *pgtype.ConnInfo, buf []byte) ([]byte, error) { - if (src == Timestamptz{}) { - return nil, nil - } - - nullable := pgtype.Timestamptz{ - Time: time.Time(src), - Valid: true, - } - - return nullable.EncodeText(ci, buf) -} - -func (src Timestamptz) EncodeBinary(ci *pgtype.ConnInfo, buf []byte) ([]byte, error) { - if (src == Timestamptz{}) { - return nil, nil - } - - nullable := pgtype.Timestamptz{ - Time: time.Time(src), - Valid: true, - } - - return nullable.EncodeBinary(ci, buf) -} - -// Scan implements the database/sql Scanner interface. -func (dst *Timestamptz) Scan(src interface{}) error { - if src == nil { - *dst = Timestamptz{} +func (ts *Timestamptz) ScanTimestamptz(v pgtype.Timestamptz) error { + if !v.Valid { + *ts = Timestamptz{} return nil } - var nullable pgtype.Timestamptz + switch v.InfinityModifier { + case pgtype.None: + *ts = Timestamptz(v.Time) + return nil + case pgtype.Infinity: + return fmt.Errorf("cannot scan Infinity into *time.Time") + case pgtype.NegativeInfinity: + return fmt.Errorf("cannot scan -Infinity into *time.Time") + default: + return fmt.Errorf("invalid InfinityModifier: %v", v.InfinityModifier) + } +} + +func (ts Timestamptz) TimestamptzValue() (pgtype.Timestamptz, error) { + if time.Time(ts).IsZero() { + return pgtype.Timestamptz{}, nil + } + + return pgtype.Timestamptz{Time: time.Time(ts), Valid: true}, nil +} + +// Scan implements the database/sql Scanner interface. +func (ts *Timestamptz) Scan(src interface{}) error { + if src == nil { + *ts = Timestamptz{} + return nil + } + + var nullable pgtype.Timestamp err := nullable.Scan(src) if err != nil { return err } - *dst = Timestamptz(nullable.Time) + *ts = Timestamptz(nullable.Time) return nil } // Value implements the database/sql/driver Valuer interface. -func (src Timestamptz) Value() (driver.Value, error) { - return pgtype.EncodeValueText(src) +func (ts Timestamptz) Value() (driver.Value, error) { + if time.Time(ts).IsZero() { + return nil, nil + } + + return time.Time(ts), nil }