scan.go 973 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package core
  2. import (
  3. "database/sql/driver"
  4. "fmt"
  5. "time"
  6. )
  7. type NullTime time.Time
  8. var (
  9. _ driver.Valuer = NullTime{}
  10. )
  11. func (ns *NullTime) Scan(value interface{}) error {
  12. if value == nil {
  13. return nil
  14. }
  15. return convertTime(ns, value)
  16. }
  17. // Value implements the driver Valuer interface.
  18. func (ns NullTime) Value() (driver.Value, error) {
  19. if (time.Time)(ns).IsZero() {
  20. return nil, nil
  21. }
  22. return (time.Time)(ns).Format("2006-01-02 15:04:05"), nil
  23. }
  24. func convertTime(dest *NullTime, src interface{}) error {
  25. // Common cases, without reflect.
  26. switch s := src.(type) {
  27. case string:
  28. t, err := time.Parse("2006-01-02 15:04:05", s)
  29. if err != nil {
  30. return err
  31. }
  32. *dest = NullTime(t)
  33. return nil
  34. case []uint8:
  35. t, err := time.Parse("2006-01-02 15:04:05", string(s))
  36. if err != nil {
  37. return err
  38. }
  39. *dest = NullTime(t)
  40. return nil
  41. case nil:
  42. default:
  43. return fmt.Errorf("unsupported driver -> Scan pair: %T -> %T", src, dest)
  44. }
  45. return nil
  46. }