pgproto3.go (2088B)
1 package pgproto3 2 3 import ( 4 "encoding/hex" 5 "errors" 6 "fmt" 7 ) 8 9 // Message is the interface implemented by an object that can decode and encode 10 // a particular PostgreSQL message. 11 type Message interface { 12 // Decode is allowed and expected to retain a reference to data after 13 // returning (unlike encoding.BinaryUnmarshaler). 14 Decode(data []byte) error 15 16 // Encode appends itself to dst and returns the new buffer. 17 Encode(dst []byte) []byte 18 } 19 20 // FrontendMessage is a message sent by the frontend (i.e. the client). 21 type FrontendMessage interface { 22 Message 23 Frontend() // no-op method to distinguish frontend from backend methods 24 } 25 26 // BackendMessage is a message sent by the backend (i.e. the server). 27 type BackendMessage interface { 28 Message 29 Backend() // no-op method to distinguish frontend from backend methods 30 } 31 32 type AuthenticationResponseMessage interface { 33 BackendMessage 34 AuthenticationResponse() // no-op method to distinguish authentication responses 35 } 36 37 type invalidMessageLenErr struct { 38 messageType string 39 expectedLen int 40 actualLen int 41 } 42 43 func (e *invalidMessageLenErr) Error() string { 44 return fmt.Sprintf("%s body must have length of %d, but it is %d", e.messageType, e.expectedLen, e.actualLen) 45 } 46 47 type invalidMessageFormatErr struct { 48 messageType string 49 details string 50 } 51 52 func (e *invalidMessageFormatErr) Error() string { 53 return fmt.Sprintf("%s body is invalid %s", e.messageType, e.details) 54 } 55 56 type writeError struct { 57 err error 58 safeToRetry bool 59 } 60 61 func (e *writeError) Error() string { 62 return fmt.Sprintf("write failed: %s", e.err.Error()) 63 } 64 65 func (e *writeError) SafeToRetry() bool { 66 return e.safeToRetry 67 } 68 69 func (e *writeError) Unwrap() error { 70 return e.err 71 } 72 73 // getValueFromJSON gets the value from a protocol message representation in JSON. 74 func getValueFromJSON(v map[string]string) ([]byte, error) { 75 if v == nil { 76 return nil, nil 77 } 78 if text, ok := v["text"]; ok { 79 return []byte(text), nil 80 } 81 if binary, ok := v["binary"]; ok { 82 return hex.DecodeString(binary) 83 } 84 return nil, errors.New("unknown protocol representation") 85 }