You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

uniqueidentifier.go 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package mssql
  2. import (
  3. "database/sql/driver"
  4. "encoding/hex"
  5. "errors"
  6. "fmt"
  7. )
  8. type UniqueIdentifier [16]byte
  9. func (u *UniqueIdentifier) Scan(v interface{}) error {
  10. reverse := func(b []byte) {
  11. for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
  12. b[i], b[j] = b[j], b[i]
  13. }
  14. }
  15. switch vt := v.(type) {
  16. case []byte:
  17. if len(vt) != 16 {
  18. return errors.New("mssql: invalid UniqueIdentifier length")
  19. }
  20. var raw UniqueIdentifier
  21. copy(raw[:], vt)
  22. reverse(raw[0:4])
  23. reverse(raw[4:6])
  24. reverse(raw[6:8])
  25. *u = raw
  26. return nil
  27. case string:
  28. if len(vt) != 36 {
  29. return errors.New("mssql: invalid UniqueIdentifier string length")
  30. }
  31. b := []byte(vt)
  32. for i, c := range b {
  33. switch c {
  34. case '-':
  35. b = append(b[:i], b[i+1:]...)
  36. }
  37. }
  38. _, err := hex.Decode(u[:], []byte(b))
  39. return err
  40. default:
  41. return fmt.Errorf("mssql: cannot convert %T to UniqueIdentifier", v)
  42. }
  43. }
  44. func (u UniqueIdentifier) Value() (driver.Value, error) {
  45. reverse := func(b []byte) {
  46. for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
  47. b[i], b[j] = b[j], b[i]
  48. }
  49. }
  50. raw := make([]byte, len(u))
  51. copy(raw, u[:])
  52. reverse(raw[0:4])
  53. reverse(raw[4:6])
  54. reverse(raw[6:8])
  55. return raw, nil
  56. }
  57. func (u UniqueIdentifier) String() string {
  58. return fmt.Sprintf("%X-%X-%X-%X-%X", u[0:4], u[4:6], u[6:8], u[8:10], u[10:])
  59. }
  60. // MarshalText converts Uniqueidentifier to bytes corresponding to the stringified hexadecimal representation of the Uniqueidentifier
  61. // e.g., "AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA" -> [65 65 65 65 65 65 65 65 45 65 65 65 65 45 65 65 65 65 45 65 65 65 65 65 65 65 65 65 65 65 65]
  62. func (u UniqueIdentifier) MarshalText() []byte {
  63. return []byte(u.String())
  64. }