Skip to content

Commit

Permalink
Add parsing date as string to nullable.Of[time.time]
Browse files Browse the repository at this point in the history
  • Loading branch information
pivaldi committed Nov 27, 2023
1 parent 8c6b8e8 commit d8761da
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
27 changes: 23 additions & 4 deletions nullable.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"database/sql/driver"
"encoding/json"
"fmt"
"time"
)

// JSON permits to handle Postgresl Json[b] type
Expand Down Expand Up @@ -178,10 +179,28 @@ func (n *Of[T]) scanBool(v any) error {
}

func (n *Of[T]) scanTime(v any) error {
null := sql.NullTime{}
err := null.Scan(v)
if err != nil {
return fmt.Errorf("nullable database scanning Time : %w", err)
if v == nil {
n.SetNull()

return nil
}

null := new(sql.NullTime)

switch t := v.(type) {
case string:
var err error
null.Time, err = time.Parse(t, t)
if err != nil {
return fmt.Errorf("%w", err)
}
case time.Time:
err := null.Scan(v)
if err != nil {
return fmt.Errorf("nullable database scanning Time : %w", err)
}
default:
return fmt.Errorf("canot parse type \"%T\" with value \"%v\" to time", t, t)
}

if null.Valid {
Expand Down
1 change: 1 addition & 0 deletions of.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
)

type Of[T bool | int | int16 | int32 | int64 | string | float64 | JSON] struct {
//nolint: tagliatelle // Internal use
Val *T `json:"nullable_value" db:"_"`
}

Expand Down

0 comments on commit d8761da

Please sign in to comment.