copy_out_response.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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 CopyOutResponse struct {
  11. OverallFormat byte
  12. ColumnFormatCodes []uint16
  13. }
  14. func (*CopyOutResponse) 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 *CopyOutResponse) Decode(src []byte) error {
  18. buf := bytes.NewBuffer(src)
  19. if buf.Len() < 3 {
  20. return &invalidMessageFormatErr{messageType: "CopyOutResponse"}
  21. }
  22. overallFormat := buf.Next(1)[0]
  23. columnCount := int(binary.BigEndian.Uint16(buf.Next(2)))
  24. if buf.Len() != columnCount*2 {
  25. return &invalidMessageFormatErr{messageType: "CopyOutResponse"}
  26. }
  27. columnFormatCodes := make([]uint16, columnCount)
  28. for i := range columnCount {
  29. columnFormatCodes[i] = binary.BigEndian.Uint16(buf.Next(2))
  30. }
  31. *dst = CopyOutResponse{OverallFormat: overallFormat, ColumnFormatCodes: columnFormatCodes}
  32. return nil
  33. }
  34. // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length.
  35. func (src *CopyOutResponse) Encode(dst []byte) ([]byte, error) {
  36. dst, sp := beginMessage(dst, 'H')
  37. dst = append(dst, src.OverallFormat)
  38. if len(src.ColumnFormatCodes) > math.MaxUint16 {
  39. return nil, errors.New("too many column format codes")
  40. }
  41. dst = pgio.AppendUint16(dst, uint16(len(src.ColumnFormatCodes)))
  42. for _, fc := range src.ColumnFormatCodes {
  43. dst = pgio.AppendUint16(dst, fc)
  44. }
  45. return finishMessage(dst, sp)
  46. }
  47. // MarshalJSON implements encoding/json.Marshaler.
  48. func (src CopyOutResponse) MarshalJSON() ([]byte, error) {
  49. return json.Marshal(struct {
  50. Type string
  51. ColumnFormatCodes []uint16
  52. }{
  53. Type: "CopyOutResponse",
  54. ColumnFormatCodes: src.ColumnFormatCodes,
  55. })
  56. }
  57. // UnmarshalJSON implements encoding/json.Unmarshaler.
  58. func (dst *CopyOutResponse) UnmarshalJSON(data []byte) error {
  59. // Ignore null, like in the main JSON package.
  60. if string(data) == "null" {
  61. return nil
  62. }
  63. var msg struct {
  64. OverallFormat string
  65. ColumnFormatCodes []uint16
  66. }
  67. if err := json.Unmarshal(data, &msg); err != nil {
  68. return err
  69. }
  70. if len(msg.OverallFormat) != 1 {
  71. return errors.New("invalid length for CopyOutResponse.OverallFormat")
  72. }
  73. dst.OverallFormat = msg.OverallFormat[0]
  74. dst.ColumnFormatCodes = msg.ColumnFormatCodes
  75. return nil
  76. }