Skip to content

Commit

Permalink
Merge pull request #173 from patdowney/zero_time_fix
Browse files Browse the repository at this point in the history
Drop millisecond precision if given value is too old
  • Loading branch information
dancannon committed Apr 14, 2015
2 parents c40e0ca + b4693ce commit 9ce3fd1
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 1 deletion.
3 changes: 3 additions & 0 deletions cursor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,10 +145,12 @@ func (s *RethinkSuite) TestCursorStruct(c *test.C) {
}

func (s *RethinkSuite) TestCursorStructPseudoTypes(c *test.C) {
var zeroTime time.Time
t := time.Now()

res, err := Expr(map[string]interface{}{
"T": time.Unix(t.Unix(), 0).In(time.UTC),
"Z": zeroTime,
"B": []byte("hello"),
}).Run(sess)
c.Assert(err, test.IsNil)
Expand All @@ -159,6 +161,7 @@ func (s *RethinkSuite) TestCursorStructPseudoTypes(c *test.C) {
c.Assert(res.Type(), test.Equals, "Cursor")

c.Assert(response.T.Equal(time.Unix(t.Unix(), 0)), test.Equals, true)
c.Assert(response.Z.Equal(zeroTime), test.Equals, true)
c.Assert(response.B, jsonEquals, []byte("hello"))
}

Expand Down
11 changes: 10 additions & 1 deletion encoding/encoder_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package encoding

import (
"encoding/base64"
"math"
"reflect"
"time"
)
Expand Down Expand Up @@ -262,9 +263,17 @@ func newCondAddrEncoder(canAddrEnc, elseEnc encoderFunc) encoderFunc {
func timePseudoTypeEncoder(v reflect.Value) interface{} {
t := v.Interface().(time.Time)

timeVal := float64(t.UnixNano()) / float64(time.Second)

// use seconds-since-epoch precision if time.Time `t`
// is before the oldest nanosecond time
if t.Before(time.Unix(0, math.MinInt64)) {
timeVal = float64(t.Unix())
}

return map[string]interface{}{
"$reql_type$": "TIME",
"epoch_time": float64(t.UnixNano()) / 1000 / 1000 / 1000, //milliseconds
"epoch_time": timeVal,
"timezone": "+00:00",
}
}
Expand Down
1 change: 1 addition & 0 deletions gorethink_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,7 @@ type Y struct {

type PseudoTypes struct {
T time.Time
Z time.Time
B []byte
}

Expand Down

0 comments on commit 9ce3fd1

Please sign in to comment.