Skip to content

Commit

Permalink
Add dbutil helpers for converting time.Time into *int64
Browse files Browse the repository at this point in the history
  • Loading branch information
tulir committed Feb 17, 2024
1 parent 8753c3e commit b5e57f8
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions dbutil/queryhelper.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"context"
"database/sql"
"errors"
"time"

"golang.org/x/exp/constraints"
)
Expand Down Expand Up @@ -60,6 +61,34 @@ func NumPtr[T constraints.Integer | constraints.Float](val T) *T {
return &val
}

// UnixPtr returns a pointer to the given time as unix seconds, or nil if the time is zero.
func UnixPtr(val time.Time) *int64 {
return ConvertedPtr(val, time.Time.Unix)
}

// UnixMilliPtr returns a pointer to the given time as unix milliseconds, or nil if the time is zero.
func UnixMilliPtr(val time.Time) *int64 {
return ConvertedPtr(val, time.Time.UnixMilli)
}

type Zeroable interface {
IsZero() bool
}

// ConvertedPtr returns a pointer to the converted version of the given value, or nil if the input is zero.
//
// This is primarily meant for time.Time, but it can be used with any type that has implements `IsZero() bool`.
//
// yourTime := time.Now()
// unixMSPtr := dbutil.TimePtr(yourTime, time.Time.UnixMilli)
func ConvertedPtr[Input Zeroable, Output any](val Input, converter func(Input) Output) *Output {
if val.IsZero() {
return nil
}
converted := converter(val)
return &converted
}

func (qh *QueryHelper[T]) GetDB() *Database {
return qh.db
}
Expand Down

0 comments on commit b5e57f8

Please sign in to comment.