2
0

Date text encoding pads year with 0 for at least 4 digits

e.g. 0007-01-02 instead of 7-01-02

https://github.com/jackc/pgx/commit/89f69aaea9748ae0ea121af4f1886d24966cef56#commitcomment-89173737
This commit is contained in:
Jack Christensen
2022-11-12 06:14:04 -06:00
parent a86acf61e0
commit daf570c752
2 changed files with 29 additions and 1 deletions
+5 -1
View File
@@ -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')
+24
View File
@@ -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