gtsocial-umbx

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

command_complete.go (1644B)


      1 package pgproto3
      2 
      3 import (
      4 	"bytes"
      5 	"encoding/json"
      6 
      7 	"github.com/jackc/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 != len(src)-1 {
     22 		return &invalidMessageFormatErr{messageType: "CommandComplete"}
     23 	}
     24 
     25 	dst.CommandTag = src[:idx]
     26 
     27 	return nil
     28 }
     29 
     30 // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length.
     31 func (src *CommandComplete) Encode(dst []byte) []byte {
     32 	dst = append(dst, 'C')
     33 	sp := len(dst)
     34 	dst = pgio.AppendInt32(dst, -1)
     35 
     36 	dst = append(dst, src.CommandTag...)
     37 	dst = append(dst, 0)
     38 
     39 	pgio.SetInt32(dst[sp:], int32(len(dst[sp:])))
     40 
     41 	return dst
     42 }
     43 
     44 // MarshalJSON implements encoding/json.Marshaler.
     45 func (src CommandComplete) MarshalJSON() ([]byte, error) {
     46 	return json.Marshal(struct {
     47 		Type       string
     48 		CommandTag string
     49 	}{
     50 		Type:       "CommandComplete",
     51 		CommandTag: string(src.CommandTag),
     52 	})
     53 }
     54 
     55 // UnmarshalJSON implements encoding/json.Unmarshaler.
     56 func (dst *CommandComplete) UnmarshalJSON(data []byte) error {
     57 	// Ignore null, like in the main JSON package.
     58 	if string(data) == "null" {
     59 		return nil
     60 	}
     61 
     62 	var msg struct {
     63 		CommandTag string
     64 	}
     65 	if err := json.Unmarshal(data, &msg); err != nil {
     66 		return err
     67 	}
     68 
     69 	dst.CommandTag = []byte(msg.CommandTag)
     70 	return nil
     71 }