sql.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright 2016 Google Inc. 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 uuid
  5. import (
  6. "database/sql/driver"
  7. "errors"
  8. "fmt"
  9. )
  10. // Scan implements sql.Scanner so UUIDs can be read from databases transparently
  11. // Currently, database types that map to string and []byte are supported. Please
  12. // consult database-specific driver documentation for matching types.
  13. func (uuid *UUID) Scan(src interface{}) error {
  14. switch src := src.(type) {
  15. case nil:
  16. return nil
  17. case string:
  18. // if an empty UUID comes from a table, we return a null UUID
  19. if src == "" {
  20. return nil
  21. }
  22. // see Parse for required string format
  23. u, err := Parse(src)
  24. if err != nil {
  25. return errors.New("Scan: " + err.Error())
  26. }
  27. *uuid = u
  28. case []byte:
  29. // if an empty UUID comes from a table, we return a null UUID
  30. if len(src) == 0 {
  31. return nil
  32. }
  33. // assumes a simple slice of bytes if 16 bytes
  34. // otherwise attempts to parse
  35. if len(src) != 16 {
  36. return uuid.Scan(string(src))
  37. }
  38. copy((*uuid)[:], src)
  39. default:
  40. // here we use %T for type
  41. return fmt.Errorf("Scan: unable to scan type %T into UUID", src)
  42. }
  43. return nil
  44. }
  45. // Value implements sql.Valuer so that UUIDs can be written to databases
  46. // transparently. Currently, UUIDs map to strings. Please consult
  47. // database-specific driver documentation for matching types.
  48. func (uuid UUID) Value() (driver.Value, error) {
  49. return uuid.String(), nil
  50. }