1package pgproto3
2
3import (
4	"encoding/json"
5	"errors"
6)
7
8type ReadyForQuery struct {
9	TxStatus byte
10}
11
12// Backend identifies this message as sendable by the PostgreSQL backend.
13func (*ReadyForQuery) Backend() {}
14
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.
17func (dst *ReadyForQuery) Decode(src []byte) error {
18	if len(src) != 1 {
19		return &invalidMessageLenErr{messageType: "ReadyForQuery", expectedLen: 1, actualLen: len(src)}
20	}
21
22	dst.TxStatus = src[0]
23
24	return nil
25}
26
27// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length.
28func (src *ReadyForQuery) Encode(dst []byte) []byte {
29	return append(dst, 'Z', 0, 0, 0, 5, src.TxStatus)
30}
31
32// MarshalJSON implements encoding/json.Marshaler.
33func (src ReadyForQuery) MarshalJSON() ([]byte, error) {
34	return json.Marshal(struct {
35		Type     string
36		TxStatus string
37	}{
38		Type:     "ReadyForQuery",
39		TxStatus: string(src.TxStatus),
40	})
41}
42
43// UnmarshalJSON implements encoding/json.Unmarshaler.
44func (dst *ReadyForQuery) UnmarshalJSON(data []byte) error {
45	// Ignore null, like in the main JSON package.
46	if string(data) == "null" {
47		return nil
48	}
49
50	var msg struct {
51		TxStatus string
52	}
53	if err := json.Unmarshal(data, &msg); err != nil {
54		return err
55	}
56	if len(msg.TxStatus) != 1 {
57		return errors.New("invalid length for ReadyForQuery.TxStatus")
58	}
59	dst.TxStatus = msg.TxStatus[0]
60	return nil
61}
62