sql.go 1.2 KB

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