sql.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. "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.(type) {
  15. case string:
  16. // if an empty UUID comes from a table, we return a null UUID
  17. if src.(string) == "" {
  18. return nil
  19. }
  20. // see uuid.Parse for required string format
  21. parsed := Parse(src.(string))
  22. if parsed == nil {
  23. return errors.New("Scan: invalid UUID format")
  24. }
  25. *uuid = parsed
  26. case []byte:
  27. b := src.([]byte)
  28. // if an empty UUID comes from a table, we return a null UUID
  29. if len(b) == 0 {
  30. return nil
  31. }
  32. // assumes a simple slice of bytes if 16 bytes
  33. // otherwise attempts to parse
  34. if len(b) == 16 {
  35. parsed := make([]byte, 16)
  36. copy(parsed, b)
  37. *uuid = UUID(parsed)
  38. } else {
  39. u := Parse(string(b))
  40. if u == nil {
  41. return errors.New("Scan: invalid UUID format")
  42. }
  43. *uuid = u
  44. }
  45. default:
  46. return fmt.Errorf("Scan: unable to scan type %T into UUID", src)
  47. }
  48. return nil
  49. }
  50. // Value implements sql.Valuer so that UUIDs can be written to databases
  51. // transparently. Currently, UUIDs map to strings. Please consult
  52. // database-specific driver documentation for matching types.
  53. func (uuid UUID) Value() (driver.Value, error) {
  54. return uuid.String(), nil
  55. }