1package pgproto3
2
3import (
4	"bytes"
5	"encoding/binary"
6	"encoding/json"
7
8	"github.com/jackc/pgio"
9)
10
11type Execute struct {
12	Portal  string
13	MaxRows uint32
14}
15
16// Frontend identifies this message as sendable by a PostgreSQL frontend.
17func (*Execute) Frontend() {}
18
19// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message
20// type identifier and 4 byte message length.
21func (dst *Execute) Decode(src []byte) error {
22	buf := bytes.NewBuffer(src)
23
24	b, err := buf.ReadBytes(0)
25	if err != nil {
26		return err
27	}
28	dst.Portal = string(b[:len(b)-1])
29
30	if buf.Len() < 4 {
31		return &invalidMessageFormatErr{messageType: "Execute"}
32	}
33	dst.MaxRows = binary.BigEndian.Uint32(buf.Next(4))
34
35	return nil
36}
37
38// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length.
39func (src *Execute) Encode(dst []byte) []byte {
40	dst = append(dst, 'E')
41	sp := len(dst)
42	dst = pgio.AppendInt32(dst, -1)
43
44	dst = append(dst, src.Portal...)
45	dst = append(dst, 0)
46
47	dst = pgio.AppendUint32(dst, src.MaxRows)
48
49	pgio.SetInt32(dst[sp:], int32(len(dst[sp:])))
50
51	return dst
52}
53
54// MarshalJSON implements encoding/json.Marshaler.
55func (src Execute) MarshalJSON() ([]byte, error) {
56	return json.Marshal(struct {
57		Type    string
58		Portal  string
59		MaxRows uint32
60	}{
61		Type:    "Execute",
62		Portal:  src.Portal,
63		MaxRows: src.MaxRows,
64	})
65}
66