parse.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package pgproto3
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "encoding/json"
  6. "errors"
  7. "math"
  8. "github.com/jackc/pgx/v5/internal/pgio"
  9. )
  10. type Parse struct {
  11. Name string
  12. Query string
  13. ParameterOIDs []uint32
  14. }
  15. // Frontend identifies this message as sendable by a PostgreSQL frontend.
  16. func (*Parse) Frontend() {}
  17. // Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message
  18. // type identifier and 4 byte message length.
  19. func (dst *Parse) Decode(src []byte) error {
  20. *dst = Parse{}
  21. buf := bytes.NewBuffer(src)
  22. b, err := buf.ReadBytes(0)
  23. if err != nil {
  24. return err
  25. }
  26. dst.Name = string(b[:len(b)-1])
  27. b, err = buf.ReadBytes(0)
  28. if err != nil {
  29. return err
  30. }
  31. dst.Query = string(b[:len(b)-1])
  32. if buf.Len() < 2 {
  33. return &invalidMessageFormatErr{messageType: "Parse"}
  34. }
  35. parameterOIDCount := int(binary.BigEndian.Uint16(buf.Next(2)))
  36. for range parameterOIDCount {
  37. if buf.Len() < 4 {
  38. return &invalidMessageFormatErr{messageType: "Parse"}
  39. }
  40. dst.ParameterOIDs = append(dst.ParameterOIDs, binary.BigEndian.Uint32(buf.Next(4)))
  41. }
  42. return nil
  43. }
  44. // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length.
  45. func (src *Parse) Encode(dst []byte) ([]byte, error) {
  46. dst, sp := beginMessage(dst, 'P')
  47. dst = append(dst, src.Name...)
  48. dst = append(dst, 0)
  49. dst = append(dst, src.Query...)
  50. dst = append(dst, 0)
  51. if len(src.ParameterOIDs) > math.MaxUint16 {
  52. return nil, errors.New("too many parameter oids")
  53. }
  54. dst = pgio.AppendUint16(dst, uint16(len(src.ParameterOIDs)))
  55. for _, oid := range src.ParameterOIDs {
  56. dst = pgio.AppendUint32(dst, oid)
  57. }
  58. return finishMessage(dst, sp)
  59. }
  60. // MarshalJSON implements encoding/json.Marshaler.
  61. func (src Parse) MarshalJSON() ([]byte, error) {
  62. return json.Marshal(struct {
  63. Type string
  64. Name string
  65. Query string
  66. ParameterOIDs []uint32
  67. }{
  68. Type: "Parse",
  69. Name: src.Name,
  70. Query: src.Query,
  71. ParameterOIDs: src.ParameterOIDs,
  72. })
  73. }