parameter_description.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 ParameterDescription struct {
  11. ParameterOIDs []uint32
  12. }
  13. // Backend identifies this message as sendable by the PostgreSQL backend.
  14. func (*ParameterDescription) Backend() {}
  15. // Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message
  16. // type identifier and 4 byte message length.
  17. func (dst *ParameterDescription) Decode(src []byte) error {
  18. buf := bytes.NewBuffer(src)
  19. if buf.Len() < 2 {
  20. return &invalidMessageFormatErr{messageType: "ParameterDescription"}
  21. }
  22. // Reported parameter count will be incorrect when number of args is greater than uint16
  23. buf.Next(2)
  24. // Instead infer parameter count by remaining size of message
  25. parameterCount := buf.Len() / 4
  26. *dst = ParameterDescription{ParameterOIDs: make([]uint32, parameterCount)}
  27. for i := range parameterCount {
  28. dst.ParameterOIDs[i] = binary.BigEndian.Uint32(buf.Next(4))
  29. }
  30. return nil
  31. }
  32. // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length.
  33. func (src *ParameterDescription) Encode(dst []byte) ([]byte, error) {
  34. dst, sp := beginMessage(dst, 't')
  35. if len(src.ParameterOIDs) > math.MaxUint16 {
  36. return nil, errors.New("too many parameter oids")
  37. }
  38. dst = pgio.AppendUint16(dst, uint16(len(src.ParameterOIDs)))
  39. for _, oid := range src.ParameterOIDs {
  40. dst = pgio.AppendUint32(dst, oid)
  41. }
  42. return finishMessage(dst, sp)
  43. }
  44. // MarshalJSON implements encoding/json.Marshaler.
  45. func (src ParameterDescription) MarshalJSON() ([]byte, error) {
  46. return json.Marshal(struct {
  47. Type string
  48. ParameterOIDs []uint32
  49. }{
  50. Type: "ParameterDescription",
  51. ParameterOIDs: src.ParameterOIDs,
  52. })
  53. }