copy_in_response.go (2449B)
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 CopyInResponse struct { 13 OverallFormat byte 14 ColumnFormatCodes []uint16 15 } 16 17 // Backend identifies this message as sendable by the PostgreSQL backend. 18 func (*CopyInResponse) 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 *CopyInResponse) Decode(src []byte) error { 23 buf := bytes.NewBuffer(src) 24 25 if buf.Len() < 3 { 26 return &invalidMessageFormatErr{messageType: "CopyInResponse"} 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: "CopyInResponse"} 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 = CopyInResponse{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 *CopyInResponse) Encode(dst []byte) []byte { 48 dst = append(dst, 'G') 49 sp := len(dst) 50 dst = pgio.AppendInt32(dst, -1) 51 52 dst = append(dst, src.OverallFormat) 53 dst = pgio.AppendUint16(dst, uint16(len(src.ColumnFormatCodes))) 54 for _, fc := range src.ColumnFormatCodes { 55 dst = pgio.AppendUint16(dst, fc) 56 } 57 58 pgio.SetInt32(dst[sp:], int32(len(dst[sp:]))) 59 60 return dst 61 } 62 63 // MarshalJSON implements encoding/json.Marshaler. 64 func (src CopyInResponse) MarshalJSON() ([]byte, error) { 65 return json.Marshal(struct { 66 Type string 67 ColumnFormatCodes []uint16 68 }{ 69 Type: "CopyInResponse", 70 ColumnFormatCodes: src.ColumnFormatCodes, 71 }) 72 } 73 74 // UnmarshalJSON implements encoding/json.Unmarshaler. 75 func (dst *CopyInResponse) UnmarshalJSON(data []byte) error { 76 // Ignore null, like in the main JSON package. 77 if string(data) == "null" { 78 return nil 79 } 80 81 var msg struct { 82 OverallFormat string 83 ColumnFormatCodes []uint16 84 } 85 if err := json.Unmarshal(data, &msg); err != nil { 86 return err 87 } 88 89 if len(msg.OverallFormat) != 1 { 90 return errors.New("invalid length for CopyInResponse.OverallFormat") 91 } 92 93 dst.OverallFormat = msg.OverallFormat[0] 94 dst.ColumnFormatCodes = msg.ColumnFormatCodes 95 return nil 96 }