/
timestamp.go
70 lines (60 loc) · 1.66 KB
/
timestamp.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package dbtest
import (
"database/sql/driver"
"errors"
"math"
"time"
"google.golang.org/protobuf/types/known/timestamppb"
)
// New constructs a new Timestamp from the provided time.Time.
func New(t time.Time) *Timestamp {
return &Timestamp{
Timestamp: timestamppb.New(t),
}
}
// Now constructs a new Timestamp from the current time.
func Now() *Timestamp {
return &Timestamp{
Timestamp: timestamppb.Now(),
}
}
// AsTime converts x to a time.Time.
func (ts *Timestamp) AsTime() time.Time {
return ts.Timestamp.AsTime()
}
var (
// NegativeInfinityTS defines a value for postgres -infinity
NegativeInfinityTS = time.Date(math.MinInt32, time.January, 1, 0, 0, 0, 0, time.UTC)
// PositiveInfinityTS defines a value for postgres infinity
PositiveInfinityTS = time.Date(math.MaxInt32, time.December, 31, 23, 59, 59, 1e9-1, time.UTC)
)
// Scan implements sql.Scanner for protobuf Timestamp.
func (ts *Timestamp) Scan(value interface{}) error {
switch t := value.(type) {
case time.Time:
ts.Timestamp = timestamppb.New(t) // google proto version
case string:
switch value {
case "-infinity":
ts.Timestamp = timestamppb.New(NegativeInfinityTS)
case "infinity":
ts.Timestamp = timestamppb.New(PositiveInfinityTS)
}
default:
return errors.New("Not a protobuf Timestamp")
}
return nil
}
// Scan implements driver.Valuer for protobuf Timestamp.
func (ts *Timestamp) Value() (driver.Value, error) {
if ts == nil {
return nil, nil
}
return ts.Timestamp.AsTime(), nil
}
// GormDataType gorm common data type (required)
func (ts *Timestamp) GormDataType() string {
return "timestamp"
}