diff --git a/pgtype/date.go b/pgtype/date.go index 24ed20cc..bb65996a 100644 --- a/pgtype/date.go +++ b/pgtype/date.go @@ -193,7 +193,11 @@ func (encodePlanDateCodecText) Encode(value any, buf []byte) (newBuf []byte, err bc = true } - buf = strconv.AppendInt(buf, int64(year), 10) + yearBytes := strconv.AppendInt(make([]byte, 0, 6), int64(year), 10) + for i := len(yearBytes); i < 4; i++ { + buf = append(buf, '0') + } + buf = append(buf, yearBytes...) buf = append(buf, '-') if date.Time.Month() < 10 { buf = append(buf, '0') diff --git a/pgtype/date_test.go b/pgtype/date_test.go index de61fd72..806ffbfe 100644 --- a/pgtype/date_test.go +++ b/pgtype/date_test.go @@ -7,6 +7,7 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxtest" + "github.com/stretchr/testify/assert" ) func isExpectedEqTime(a any) func(any) bool { @@ -37,6 +38,29 @@ func TestDateCodec(t *testing.T) { }) } +func TestDateCodecTextEncode(t *testing.T) { + m := pgtype.NewMap() + + successfulTests := []struct { + source pgtype.Date + result string + }{ + {source: pgtype.Date{Time: time.Date(2012, 3, 29, 0, 0, 0, 0, time.UTC), Valid: true}, result: "2012-03-29"}, + {source: pgtype.Date{Time: time.Date(2012, 3, 29, 10, 5, 45, 0, time.FixedZone("", -6*60*60)), Valid: true}, result: "2012-03-29"}, + {source: pgtype.Date{Time: time.Date(2012, 3, 29, 10, 5, 45, 555*1000*1000, time.FixedZone("", -6*60*60)), Valid: true}, result: "2012-03-29"}, + {source: pgtype.Date{Time: time.Date(789, 1, 2, 0, 0, 0, 0, time.UTC), Valid: true}, result: "0789-01-02"}, + {source: pgtype.Date{Time: time.Date(89, 1, 2, 0, 0, 0, 0, time.UTC), Valid: true}, result: "0089-01-02"}, + {source: pgtype.Date{Time: time.Date(9, 1, 2, 0, 0, 0, 0, time.UTC), Valid: true}, result: "0009-01-02"}, + {source: pgtype.Date{InfinityModifier: pgtype.Infinity, Valid: true}, result: "infinity"}, + {source: pgtype.Date{InfinityModifier: pgtype.NegativeInfinity, Valid: true}, result: "-infinity"}, + } + for i, tt := range successfulTests { + buf, err := m.Encode(pgtype.DateOID, pgtype.TextFormatCode, tt.source, nil) + assert.NoErrorf(t, err, "%d", i) + assert.Equalf(t, tt.result, string(buf), "%d", i) + } +} + func TestDateMarshalJSON(t *testing.T) { successfulTests := []struct { source pgtype.Date