diff --git a/.gitignore b/.gitignore index abda3049c494f025ffb25e370661c4017f2b2582..138f5ca57889f0ccc20291b08fe4e641151b8ab0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ .idea/ .tmp/ +go.sum coverage.txt *.out diff --git a/datatypes/pg_timestamptz.go b/datatypes/pg_timestamptz.go new file mode 100644 index 0000000000000000000000000000000000000000..cf5ee5ee9ee3118e94603de19f58a82f4909f3fc --- /dev/null +++ b/datatypes/pg_timestamptz.go @@ -0,0 +1,70 @@ +package datatypes + +import ( + "database/sql/driver" + "fmt" + "time" +) + +var ( + TimestampTzZero = PgTimestampTz(time.Time{}) + TimestampTzUnixZero = PgTimestampTz(time.Unix(0, 0)) +) + +type PgTimestampTz time.Time + +func (p *PgTimestampTz) UnmarshalText(text []byte) (err error) { + str := string(text) + if len(str) == 0 || str == "0" { + return nil + } + *p, err = ParseTimestampTzFromString(str) + return +} + +func (p *PgTimestampTz) MarshalText() (text []byte, err error) { + return []byte(p.String()), nil +} + +func (p *PgTimestampTz) String() string { + if p.IsZero() { + return "" + } + return time.Time(*p).In(CST).Format(time.RFC3339) +} + +func (p *PgTimestampTz) Unix() int64 { + return time.Time(*p).Unix() +} + +func (p *PgTimestampTz) IsZero() bool { + unix := p.Unix() + return unix == 0 || unix == TimestampZero.Unix() +} + +func (p *PgTimestampTz) Value() (driver.Value, error) { + return p.String(), nil +} + +func (p *PgTimestampTz) Scan(value any) error { + switch v := value.(type) { + case time.Time: + *p = PgTimestampTz(v) + case nil: + *p = TimestampTzZero + default: + return fmt.Errorf("cannot sql.Scan() strfmt.Timestamp from: %#v", v) + } + return nil +} + +func (p *PgTimestampTz) DataType(driverName string) string { + return "timestamptz" +} + +func ParseTimestampTzFromString(s string) (dt PgTimestampTz, err error) { + var t time.Time + t, err = time.Parse(time.RFC3339, s) + dt = PgTimestampTz(t) + return +}