gtsocial-umbx

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README | LICENSE

command_complete.go (1817B)


      1 package pgproto3
      2 
      3 import (
      4 	"bytes"
      5 	"encoding/json"
      6 
      7 	"github.com/jackc/pgx/v5/internal/pgio"
      8 )
      9 
     10 type CommandComplete struct {
     11 	CommandTag []byte
     12 }
     13 
     14 // Backend identifies this message as sendable by the PostgreSQL backend.
     15 func (*CommandComplete) Backend() {}
     16 
     17 // Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message
     18 // type identifier and 4 byte message length.
     19 func (dst *CommandComplete) Decode(src []byte) error {
     20 	idx := bytes.IndexByte(src, 0)
     21 	if idx == -1 {
     22 		return &invalidMessageFormatErr{messageType: "CommandComplete", details: "unterminated string"}
     23 	}
     24 	if idx != len(src)-1 {
     25 		return &invalidMessageFormatErr{messageType: "CommandComplete", details: "string terminated too early"}
     26 	}
     27 
     28 	dst.CommandTag = src[:idx]
     29 
     30 	return nil
     31 }
     32 
     33 // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length.
     34 func (src *CommandComplete) Encode(dst []byte) []byte {
     35 	dst = append(dst, 'C')
     36 	sp := len(dst)
     37 	dst = pgio.AppendInt32(dst, -1)
     38 
     39 	dst = append(dst, src.CommandTag...)
     40 	dst = append(dst, 0)
     41 
     42 	pgio.SetInt32(dst[sp:], int32(len(dst[sp:])))
     43 
     44 	return dst
     45 }
     46 
     47 // MarshalJSON implements encoding/json.Marshaler.
     48 func (src CommandComplete) MarshalJSON() ([]byte, error) {
     49 	return json.Marshal(struct {
     50 		Type       string
     51 		CommandTag string
     52 	}{
     53 		Type:       "CommandComplete",
     54 		CommandTag: string(src.CommandTag),
     55 	})
     56 }
     57 
     58 // UnmarshalJSON implements encoding/json.Unmarshaler.
     59 func (dst *CommandComplete) UnmarshalJSON(data []byte) error {
     60 	// Ignore null, like in the main JSON package.
     61 	if string(data) == "null" {
     62 		return nil
     63 	}
     64 
     65 	var msg struct {
     66 		CommandTag string
     67 	}
     68 	if err := json.Unmarshal(data, &msg); err != nil {
     69 		return err
     70 	}
     71 
     72 	dst.CommandTag = []byte(msg.CommandTag)
     73 	return nil
     74 }