blob: 68c15edd1b84290c0573490f5b699bfcf1a5dafe [file] [log] [blame]
Don Newton379ae252019-04-01 12:17:06 -04001// Copyright (C) MongoDB, Inc. 2017-present.
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may
4// not use this file except in compliance with the License. You may obtain
5// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
6
7package command
8
9import (
10 "github.com/mongodb/mongo-go-driver/bson"
11 "github.com/mongodb/mongo-go-driver/x/network/wiremessage"
12)
13
14// decodeCommandOpReply handles decoding the OP_REPLY response to an OP_QUERY
15// command.
16func decodeCommandOpReply(reply wiremessage.Reply) (bson.Raw, error) {
17 if reply.NumberReturned == 0 {
18 return nil, ErrNoDocCommandResponse
19 }
20 if reply.NumberReturned > 1 {
21 return nil, ErrMultiDocCommandResponse
22 }
23 if len(reply.Documents) != 1 {
24 return nil, NewCommandResponseError("malformed OP_REPLY: NumberReturned does not match number of documents returned", nil)
25 }
26 rdr := reply.Documents[0]
27 err := rdr.Validate()
28 if err != nil {
29 return nil, NewCommandResponseError("malformed OP_REPLY: invalid document", err)
30 }
31 if reply.ResponseFlags&wiremessage.QueryFailure == wiremessage.QueryFailure {
32 return nil, QueryFailureError{
33 Message: "command failure",
34 Response: reply.Documents[0],
35 }
36 }
37
38 err = extractError(rdr)
39 if err != nil {
40 return nil, err
41 }
42 return rdr, nil
43}