command_complete.go 1.7 KB

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