...
1 package pgproto3
2
3 import (
4 "bytes"
5 "encoding/binary"
6 "encoding/json"
7 "errors"
8 "math"
9
10 "github.com/jackc/pgio"
11 )
12
13 type CopyOutResponse struct {
14 OverallFormat byte
15 ColumnFormatCodes []uint16
16 }
17
18 func (*CopyOutResponse) Backend() {}
19
20
21
22 func (dst *CopyOutResponse) Decode(src []byte) error {
23 buf := bytes.NewBuffer(src)
24
25 if buf.Len() < 3 {
26 return &invalidMessageFormatErr{messageType: "CopyOutResponse"}
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: "CopyOutResponse"}
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 = CopyOutResponse{OverallFormat: overallFormat, ColumnFormatCodes: columnFormatCodes}
42
43 return nil
44 }
45
46
47 func (src *CopyOutResponse) Encode(dst []byte) ([]byte, error) {
48 dst, sp := beginMessage(dst, 'H')
49
50 dst = append(dst, src.OverallFormat)
51
52 if len(src.ColumnFormatCodes) > math.MaxUint16 {
53 return nil, errors.New("too many column format codes")
54 }
55 dst = pgio.AppendUint16(dst, uint16(len(src.ColumnFormatCodes)))
56 for _, fc := range src.ColumnFormatCodes {
57 dst = pgio.AppendUint16(dst, fc)
58 }
59
60 return finishMessage(dst, sp)
61 }
62
63
64 func (src CopyOutResponse) MarshalJSON() ([]byte, error) {
65 return json.Marshal(struct {
66 Type string
67 ColumnFormatCodes []uint16
68 }{
69 Type: "CopyOutResponse",
70 ColumnFormatCodes: src.ColumnFormatCodes,
71 })
72 }
73
74
75 func (dst *CopyOutResponse) UnmarshalJSON(data []byte) error {
76
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 CopyOutResponse.OverallFormat")
91 }
92
93 dst.OverallFormat = msg.OverallFormat[0]
94 dst.ColumnFormatCodes = msg.ColumnFormatCodes
95 return nil
96 }
97
View as plain text