github.com/datastax/go-cassandra-native-protocol@v0.0.0-20220706104457-5e8aad05cf90/message/query.go (about) 1 // Copyright 2020 DataStax 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package message 16 17 import ( 18 "errors" 19 "fmt" 20 "io" 21 22 "github.com/datastax/go-cassandra-native-protocol/primitive" 23 ) 24 25 // Query is a request that executes a CQL query. 26 // +k8s:deepcopy-gen=true 27 // +k8s:deepcopy-gen:interfaces=github.com/datastax/go-cassandra-native-protocol/message.Message 28 type Query struct { 29 Query string 30 Options *QueryOptions 31 } 32 33 func (q *Query) String() string { 34 return fmt.Sprintf("QUERY %s", q.Query) 35 } 36 37 func (q *Query) IsResponse() bool { 38 return false 39 } 40 41 func (q *Query) GetOpCode() primitive.OpCode { 42 return primitive.OpCodeQuery 43 } 44 45 type queryCodec struct{} 46 47 func (c *queryCodec) Encode(msg Message, dest io.Writer, version primitive.ProtocolVersion) error { 48 query, ok := msg.(*Query) 49 if !ok { 50 return errors.New(fmt.Sprintf("expected *message.Query, got %T", msg)) 51 } 52 if err := primitive.WriteLongString(query.Query, dest); err != nil { 53 return fmt.Errorf("cannot write QUERY query string: %w", err) 54 } 55 if err := EncodeQueryOptions(query.Options, dest, version); err != nil { 56 return fmt.Errorf("cannot write QUERY options: %w", err) 57 } 58 return nil 59 } 60 61 func (c *queryCodec) EncodedLength(msg Message, version primitive.ProtocolVersion) (int, error) { 62 query, ok := msg.(*Query) 63 if !ok { 64 return -1, errors.New(fmt.Sprintf("expected *message.Query, got %T", msg)) 65 } 66 lengthOfQuery := primitive.LengthOfLongString(query.Query) 67 lengthOfQueryOptions, err := LengthOfQueryOptions(query.Options, version) 68 if err != nil { 69 return -1, fmt.Errorf("cannot compute size of QUERY message: %w", err) 70 } 71 return lengthOfQuery + lengthOfQueryOptions, nil 72 } 73 74 func (c *queryCodec) Decode(source io.Reader, version primitive.ProtocolVersion) (Message, error) { 75 if query, err := primitive.ReadLongString(source); err != nil { 76 return nil, err 77 } else if options, err := DecodeQueryOptions(source, version); err != nil { 78 return nil, err 79 } else { 80 return &Query{Query: query, Options: options}, nil 81 } 82 } 83 84 func (c *queryCodec) GetOpCode() primitive.OpCode { 85 return primitive.OpCodeQuery 86 }