function_call_response.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package pgproto3
  2. import (
  3. "encoding/binary"
  4. "encoding/hex"
  5. "encoding/json"
  6. "github.com/jackc/pgx/v5/internal/pgio"
  7. )
  8. type FunctionCallResponse struct {
  9. Result []byte
  10. }
  11. // Backend identifies this message as sendable by the PostgreSQL backend.
  12. func (*FunctionCallResponse) Backend() {}
  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 *FunctionCallResponse) Decode(src []byte) error {
  16. if len(src) < 4 {
  17. return &invalidMessageFormatErr{messageType: "FunctionCallResponse"}
  18. }
  19. rp := 0
  20. resultSize := int(binary.BigEndian.Uint32(src[rp:]))
  21. rp += 4
  22. if resultSize == -1 {
  23. dst.Result = nil
  24. return nil
  25. }
  26. if len(src[rp:]) != resultSize {
  27. return &invalidMessageFormatErr{messageType: "FunctionCallResponse"}
  28. }
  29. dst.Result = src[rp:]
  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 *FunctionCallResponse) Encode(dst []byte) ([]byte, error) {
  34. dst, sp := beginMessage(dst, 'V')
  35. if src.Result == nil {
  36. dst = pgio.AppendInt32(dst, -1)
  37. } else {
  38. dst = pgio.AppendInt32(dst, int32(len(src.Result)))
  39. dst = append(dst, src.Result...)
  40. }
  41. return finishMessage(dst, sp)
  42. }
  43. // MarshalJSON implements encoding/json.Marshaler.
  44. func (src FunctionCallResponse) MarshalJSON() ([]byte, error) {
  45. var formattedValue map[string]string
  46. var hasNonPrintable bool
  47. for _, b := range src.Result {
  48. if b < 32 {
  49. hasNonPrintable = true
  50. break
  51. }
  52. }
  53. if hasNonPrintable {
  54. formattedValue = map[string]string{"binary": hex.EncodeToString(src.Result)}
  55. } else {
  56. formattedValue = map[string]string{"text": string(src.Result)}
  57. }
  58. return json.Marshal(struct {
  59. Type string
  60. Result map[string]string
  61. }{
  62. Type: "FunctionCallResponse",
  63. Result: formattedValue,
  64. })
  65. }
  66. // UnmarshalJSON implements encoding/json.Unmarshaler.
  67. func (dst *FunctionCallResponse) UnmarshalJSON(data []byte) error {
  68. // Ignore null, like in the main JSON package.
  69. if string(data) == "null" {
  70. return nil
  71. }
  72. var msg struct {
  73. Result map[string]string
  74. }
  75. err := json.Unmarshal(data, &msg)
  76. if err != nil {
  77. return err
  78. }
  79. dst.Result, err = getValueFromJSON(msg.Result)
  80. return err
  81. }