nulltime.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Go MySQL Driver - A MySQL-Driver for Go's database/sql package
  2. //
  3. // Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved.
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public
  6. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  7. // You can obtain one at http://mozilla.org/MPL/2.0/.
  8. package mysql
  9. import (
  10. "database/sql"
  11. "database/sql/driver"
  12. "fmt"
  13. "time"
  14. )
  15. // NullTime represents a time.Time that may be NULL.
  16. // NullTime implements the Scanner interface so
  17. // it can be used as a scan destination:
  18. //
  19. // var nt NullTime
  20. // err := db.QueryRow("SELECT time FROM foo WHERE id=?", id).Scan(&nt)
  21. // ...
  22. // if nt.Valid {
  23. // // use nt.Time
  24. // } else {
  25. // // NULL value
  26. // }
  27. //
  28. // # This NullTime implementation is not driver-specific
  29. //
  30. // Deprecated: NullTime doesn't honor the loc DSN parameter.
  31. // NullTime.Scan interprets a time as UTC, not the loc DSN parameter.
  32. // Use sql.NullTime instead.
  33. type NullTime sql.NullTime
  34. // Scan implements the Scanner interface.
  35. // The value type must be time.Time or string / []byte (formatted time-string),
  36. // otherwise Scan fails.
  37. func (nt *NullTime) Scan(value any) (err error) {
  38. if value == nil {
  39. nt.Time, nt.Valid = time.Time{}, false
  40. return
  41. }
  42. switch v := value.(type) {
  43. case time.Time:
  44. nt.Time, nt.Valid = v, true
  45. return
  46. case []byte:
  47. nt.Time, err = parseDateTime(v, time.UTC)
  48. nt.Valid = (err == nil)
  49. return
  50. case string:
  51. nt.Time, err = parseDateTime([]byte(v), time.UTC)
  52. nt.Valid = (err == nil)
  53. return
  54. }
  55. nt.Valid = false
  56. return fmt.Errorf("can't convert %T to time.Time", value)
  57. }
  58. // Value implements the driver Valuer interface.
  59. func (nt NullTime) Value() (driver.Value, error) {
  60. if !nt.Valid {
  61. return nil, nil
  62. }
  63. return nt.Time, nil
  64. }