describe.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package pgproto3
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. )
  7. type Describe struct {
  8. ObjectType byte // 'S' = prepared statement, 'P' = portal
  9. Name string
  10. }
  11. // Frontend identifies this message as sendable by a PostgreSQL frontend.
  12. func (*Describe) Frontend() {}
  13. // Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message
  14. // type identifier and 4 byte message length.
  15. func (dst *Describe) Decode(src []byte) error {
  16. if len(src) < 2 {
  17. return &invalidMessageFormatErr{messageType: "Describe"}
  18. }
  19. dst.ObjectType = src[0]
  20. rp := 1
  21. idx := bytes.IndexByte(src[rp:], 0)
  22. if idx != len(src[rp:])-1 {
  23. return &invalidMessageFormatErr{messageType: "Describe"}
  24. }
  25. dst.Name = string(src[rp : len(src)-1])
  26. return nil
  27. }
  28. // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length.
  29. func (src *Describe) Encode(dst []byte) ([]byte, error) {
  30. dst, sp := beginMessage(dst, 'D')
  31. dst = append(dst, src.ObjectType)
  32. dst = append(dst, src.Name...)
  33. dst = append(dst, 0)
  34. return finishMessage(dst, sp)
  35. }
  36. // MarshalJSON implements encoding/json.Marshaler.
  37. func (src Describe) MarshalJSON() ([]byte, error) {
  38. return json.Marshal(struct {
  39. Type string
  40. ObjectType string
  41. Name string
  42. }{
  43. Type: "Describe",
  44. ObjectType: string(src.ObjectType),
  45. Name: src.Name,
  46. })
  47. }
  48. // UnmarshalJSON implements encoding/json.Unmarshaler.
  49. func (dst *Describe) UnmarshalJSON(data []byte) error {
  50. // Ignore null, like in the main JSON package.
  51. if string(data) == "null" {
  52. return nil
  53. }
  54. var msg struct {
  55. ObjectType string
  56. Name string
  57. }
  58. if err := json.Unmarshal(data, &msg); err != nil {
  59. return err
  60. }
  61. if len(msg.ObjectType) != 1 {
  62. return errors.New("invalid length for Describe.ObjectType")
  63. }
  64. dst.ObjectType = byte(msg.ObjectType[0])
  65. dst.Name = msg.Name
  66. return nil
  67. }