86 lines
1.8 KiB
Go
86 lines
1.8 KiB
Go
package main
|
|
|
|
import (
|
|
"database/sql"
|
|
"database/sql/driver"
|
|
"encoding/json"
|
|
"time"
|
|
)
|
|
|
|
// Źródło poniższych:
|
|
// https://stackoverflow.com/questions/33072172/how-can-i-work-with-sql-null-values-and-json-in-golang-in-a-good-way
|
|
type NullTime struct {
|
|
Time time.Time
|
|
Valid bool // Valid is true if Time is not NULL
|
|
}
|
|
|
|
// Scan implements the Scanner interface.
|
|
func (nt *NullTime) Scan(value interface{}) error {
|
|
nt.Time, nt.Valid = value.(time.Time)
|
|
return nil
|
|
}
|
|
|
|
// Value implements the driver Valuer interface.
|
|
func (nt NullTime) Value() (driver.Value, error) {
|
|
if !nt.Valid {
|
|
return nil, nil
|
|
}
|
|
return nt.Time, nil
|
|
}
|
|
func (nt NullTime) MarshalJSON() ([]byte, error) {
|
|
if nt.Valid {
|
|
return json.Marshal(nt.Time)
|
|
}
|
|
return json.Marshal(nil)
|
|
}
|
|
|
|
type nullTimeInHours struct {
|
|
NullTime
|
|
}
|
|
|
|
// Scan implements the Scanner interface.
|
|
func (nt *nullTimeInHours) Scan(value interface{}) error {
|
|
nt.Time = value.(time.Time)
|
|
return nil
|
|
}
|
|
|
|
// Value implements the driver Valuer interface.
|
|
func (nt nullTimeInHours) Value() (driver.Value, error) {
|
|
if !nt.Valid {
|
|
return nil, nil
|
|
}
|
|
return nt.Time, nil
|
|
}
|
|
func (nt nullTimeInHours) MarshalJSON() ([]byte, error) {
|
|
if nt.Valid {
|
|
t, _ := time.Parse("15:04:05", time.Time.String(nt.Time))
|
|
return json.Marshal(t)
|
|
}
|
|
return json.Marshal(nil)
|
|
|
|
}
|
|
|
|
type nullString struct {
|
|
sql.NullString
|
|
}
|
|
|
|
// Scan implements the Scanner interface.
|
|
func (nt *nullString) Scan(value interface{}) error {
|
|
nt.String, nt.Valid = value.(string)
|
|
return nil
|
|
}
|
|
|
|
// Value implements the driver Valuer interface.
|
|
func (nt nullString) Value() (driver.Value, error) {
|
|
if !nt.Valid {
|
|
return nil, nil
|
|
}
|
|
return nt.String, nil
|
|
}
|
|
func (nt nullString) MarshalJSON() ([]byte, error) {
|
|
if nt.Valid {
|
|
return json.Marshal(nt.String)
|
|
}
|
|
return json.Marshal("null")
|
|
}
|