sql.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. *uuid = UUID(b)
  36. } else {
  37. u := Parse(string(b))
  38. if u == nil {
  39. return errors.New("Scan: invalid UUID format")
  40. }
  41. *uuid = u
  42. }
  43. default:
  44. return fmt.Errorf("Scan: unable to scan type %T into UUID", src)
  45. }
  46. return nil
  47. }
  48. // Value implements sql.Valuer so that UUIDs can be written to databases
  49. // transparently. Currently, UUIDs map to strings. Please consult
  50. // database-specific driver documentation for matching types.
  51. func (uuid UUID) Value() (driver.Value, error) {
  52. return uuid.String(), nil
  53. }