From aa211713b2e56c02b4621afcd2b10f91efdddfb9 Mon Sep 17 00:00:00 2001 From: William Flores Date: Sun, 19 Apr 2020 16:58:03 -0700 Subject: [PATCH] feat: change default value for time Fields to CURRENT_TIMESTAMP for better cross database support. Support Scanning String Dates for HeartBeatReqTime --- models/heartbeat.go | 13 ++++++++++--- models/summary.go | 4 ++-- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/models/heartbeat.go b/models/heartbeat.go index 80e7d9d..61fad35 100644 --- a/models/heartbeat.go +++ b/models/heartbeat.go @@ -3,6 +3,7 @@ package models import ( "database/sql/driver" "errors" + "fmt" "regexp" "strconv" "strings" @@ -24,7 +25,7 @@ type Heartbeat struct { IsWrite bool `json:"is_write"` Editor string `json:"editor"` OperatingSystem string `json:"operating_system"` - Time HeartbeatReqTime `json:"time" gorm:"type:timestamp; default:now(); index:idx_time,idx_time_user"` + Time HeartbeatReqTime `json:"time" gorm:"type:timestamp; default:CURRENT_TIMESTAMP; index:idx_time,idx_time_user"` languageRegex *regexp.Regexp } @@ -62,14 +63,20 @@ func (j *HeartbeatReqTime) UnmarshalJSON(b []byte) error { func (j *HeartbeatReqTime) Scan(value interface{}) error { switch value.(type) { + case string: + t, err := time.Parse("2006-01-02 15:04:05-07:00", value.(string)) + if err != nil { + return errors.New(fmt.Sprintf("unsupported date time format: %s", value)) + } + *j = HeartbeatReqTime(t) case int64: - *j = HeartbeatReqTime(time.Unix(123456, 0)) + *j = HeartbeatReqTime(time.Unix(value.(int64), 0)) break case time.Time: *j = HeartbeatReqTime(value.(time.Time)) break default: - return errors.New("unsupported type") + return errors.New(fmt.Sprintf("unsupported type: %T", value)) } return nil } diff --git a/models/summary.go b/models/summary.go index 6e8032c..3c50196 100644 --- a/models/summary.go +++ b/models/summary.go @@ -15,8 +15,8 @@ const ( type Summary struct { ID uint `json:"-" gorm:"primary_key"` UserID string `json:"user_id" gorm:"not null; index:idx_time_summary_user"` - FromTime time.Time `json:"from" gorm:"not null; type:timestamp; default:now(); index:idx_time_summary_user"` - ToTime time.Time `json:"to" gorm:"not null; type:timestamp; default:now(); index:idx_time_summary_user"` + FromTime time.Time `json:"from" gorm:"not null; type:timestamp; default:CURRENT_TIMESTAMP; index:idx_time_summary_user"` + ToTime time.Time `json:"to" gorm:"not null; type:timestamp; default:CURRENT_TIMESTAMP; index:idx_time_summary_user"` Projects []*SummaryItem `json:"projects"` Languages []*SummaryItem `json:"languages"` Editors []*SummaryItem `json:"editors"`