scan.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 time.Time:
  42. *dest = NullTime(s)
  43. return nil
  44. case nil:
  45. default:
  46. return fmt.Errorf("unsupported driver -> Scan pair: %T -> %T", src, dest)
  47. }
  48. return nil
  49. }