sql.go 1.4 KB

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