Skip to content

feat(scan): scan time.Time sets the default decoding #2413

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Feb 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions commands_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1900,6 +1900,25 @@ var _ = Describe("Commands", func() {
Key2: 123,
Time: TimeValue{Time: time.Time{}},
}))

type data2 struct {
Key1 string `redis:"key1"`
Key2 int `redis:"key2"`
Time time.Time `redis:"time"`
}
err = client.HSet(ctx, "hash", &data2{
Key1: "hello2",
Key2: 200,
Time: now,
}).Err()
Expect(err).NotTo(HaveOccurred())

var d2 data2
err = client.HMGet(ctx, "hash", "key1", "key2", "time").Scan(&d2)
Expect(err).NotTo(HaveOccurred())
Expect(d2.Key1).To(Equal("hello2"))
Expect(d2.Key2).To(Equal(200))
Expect(d2.Time.Unix()).To(Equal(now.Unix()))
})

It("should HIncrBy", func() {
Expand Down
12 changes: 12 additions & 0 deletions internal/hscan/hscan_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -200,4 +200,16 @@ var _ = Describe("Scan", func() {
Expect(td.Time.UnixNano()).To(Equal(now.UnixNano()))
Expect(td.Time.Format(time.RFC3339Nano)).To(Equal(now.Format(time.RFC3339Nano)))
})

It("should time.Time RFC3339Nano", func() {
type TimeTime struct {
Time time.Time `redis:"time"`
}

now := time.Now()

var tt TimeTime
Expect(Scan(&tt, i{"time"}, i{now.Format(time.RFC3339Nano)})).NotTo(HaveOccurred())
Expect(now.Unix()).To(Equal(tt.Time.Unix()))
})
})
8 changes: 7 additions & 1 deletion internal/hscan/structmap.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package hscan

import (
"encoding"
"fmt"
"reflect"
"strings"
"sync"

"github.com/redis/go-redis/v9/internal/util"
)

// structMap contains the map of struct fields for target structs
Expand Down Expand Up @@ -97,8 +100,11 @@ func (s StructValue) Scan(key string, value string) error {
}

if isPtr && v.Type().NumMethod() > 0 && v.CanInterface() {
if scan, ok := v.Interface().(Scanner); ok {
switch scan := v.Interface().(type) {
case Scanner:
return scan.ScanRedis(value)
case encoding.TextUnmarshaler:
return scan.UnmarshalText(util.StringToBytes(value))
}
}

Expand Down