scan.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright 2019 The Xorm Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package core
  5. import (
  6. "database/sql/driver"
  7. "fmt"
  8. "time"
  9. )
  10. type NullTime time.Time
  11. var (
  12. _ driver.Valuer = NullTime{}
  13. )
  14. func (ns *NullTime) Scan(value interface{}) error {
  15. if value == nil {
  16. return nil
  17. }
  18. return convertTime(ns, value)
  19. }
  20. // Value implements the driver Valuer interface.
  21. func (ns NullTime) Value() (driver.Value, error) {
  22. if (time.Time)(ns).IsZero() {
  23. return nil, nil
  24. }
  25. return (time.Time)(ns).Format("2006-01-02 15:04:05"), nil
  26. }
  27. func convertTime(dest *NullTime, src interface{}) error {
  28. // Common cases, without reflect.
  29. switch s := src.(type) {
  30. case string:
  31. t, err := time.Parse("2006-01-02 15:04:05", s)
  32. if err != nil {
  33. return err
  34. }
  35. *dest = NullTime(t)
  36. return nil
  37. case []uint8:
  38. t, err := time.Parse("2006-01-02 15:04:05", string(s))
  39. if err != nil {
  40. return err
  41. }
  42. *dest = NullTime(t)
  43. return nil
  44. case time.Time:
  45. *dest = NullTime(s)
  46. return nil
  47. case nil:
  48. default:
  49. return fmt.Errorf("unsupported driver -> Scan pair: %T -> %T", src, dest)
  50. }
  51. return nil
  52. }
  53. type EmptyScanner struct {
  54. }
  55. func (EmptyScanner) Scan(src interface{}) error {
  56. return nil
  57. }