copy_both_response.go (2470B)
1 package pgproto3 2 3 import ( 4 "bytes" 5 "encoding/binary" 6 "encoding/json" 7 "errors" 8 9 "github.com/jackc/pgio" 10 ) 11 12 type CopyBothResponse struct { 13 OverallFormat byte 14 ColumnFormatCodes []uint16 15 } 16 17 // Backend identifies this message as sendable by the PostgreSQL backend. 18 func (*CopyBothResponse) Backend() {} 19 20 // Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message 21 // type identifier and 4 byte message length. 22 func (dst *CopyBothResponse) Decode(src []byte) error { 23 buf := bytes.NewBuffer(src) 24 25 if buf.Len() < 3 { 26 return &invalidMessageFormatErr{messageType: "CopyBothResponse"} 27 } 28 29 overallFormat := buf.Next(1)[0] 30 31 columnCount := int(binary.BigEndian.Uint16(buf.Next(2))) 32 if buf.Len() != columnCount*2 { 33 return &invalidMessageFormatErr{messageType: "CopyBothResponse"} 34 } 35 36 columnFormatCodes := make([]uint16, columnCount) 37 for i := 0; i < columnCount; i++ { 38 columnFormatCodes[i] = binary.BigEndian.Uint16(buf.Next(2)) 39 } 40 41 *dst = CopyBothResponse{OverallFormat: overallFormat, ColumnFormatCodes: columnFormatCodes} 42 43 return nil 44 } 45 46 // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. 47 func (src *CopyBothResponse) Encode(dst []byte) []byte { 48 dst = append(dst, 'W') 49 sp := len(dst) 50 dst = pgio.AppendInt32(dst, -1) 51 dst = append(dst, src.OverallFormat) 52 dst = pgio.AppendUint16(dst, uint16(len(src.ColumnFormatCodes))) 53 for _, fc := range src.ColumnFormatCodes { 54 dst = pgio.AppendUint16(dst, fc) 55 } 56 57 pgio.SetInt32(dst[sp:], int32(len(dst[sp:]))) 58 59 return dst 60 } 61 62 // MarshalJSON implements encoding/json.Marshaler. 63 func (src CopyBothResponse) MarshalJSON() ([]byte, error) { 64 return json.Marshal(struct { 65 Type string 66 ColumnFormatCodes []uint16 67 }{ 68 Type: "CopyBothResponse", 69 ColumnFormatCodes: src.ColumnFormatCodes, 70 }) 71 } 72 73 // UnmarshalJSON implements encoding/json.Unmarshaler. 74 func (dst *CopyBothResponse) UnmarshalJSON(data []byte) error { 75 // Ignore null, like in the main JSON package. 76 if string(data) == "null" { 77 return nil 78 } 79 80 var msg struct { 81 OverallFormat string 82 ColumnFormatCodes []uint16 83 } 84 if err := json.Unmarshal(data, &msg); err != nil { 85 return err 86 } 87 88 if len(msg.OverallFormat) != 1 { 89 return errors.New("invalid length for CopyBothResponse.OverallFormat") 90 } 91 92 dst.OverallFormat = msg.OverallFormat[0] 93 dst.ColumnFormatCodes = msg.ColumnFormatCodes 94 return nil 95 }