/
query_query.go
94 lines (89 loc) · 2.29 KB
/
query_query.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// Copyright (C) 2019 Satoshi Konno. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package message
import (
"github.com/cybergarage/go-mongo/mongo/protocol"
"go.mongodb.org/mongo-driver/bson/bsontype"
)
// NewQueryWithQuery returns a new query with the specified OP_QUERY.
func NewQueryWithQuery(msg *protocol.Query) (*Query, error) {
q := NewQuery()
return q, q.ParseQuery(msg)
}
// ParseQuery parses the specified OP_MSG.
func (q *Query) ParseQuery(msg *protocol.Query) error {
query := msg.GetQuery()
if query == nil {
return nil
}
elements, err := query.Elements()
if err != nil {
return err
}
for _, element := range elements {
key := element.Key()
val := element.Value()
switch key {
case Insert, Delete, Update, Find:
q.Type = key
col, ok := val.StringValueOK()
if ok {
q.Collection = col
}
case Documents:
switch val.Type {
case bsontype.Array:
docs, ok := val.ArrayOK()
if ok {
docsElems, err := docs.Values()
if err == nil {
for _, docElem := range docsElems {
doc, ok := docElem.DocumentOK()
if ok {
q.Documents = append(q.Documents, doc)
}
}
}
}
case bsontype.EmbeddedDocument:
doc, ok := val.DocumentOK()
if ok {
q.Documents = append(q.Documents, doc)
}
}
case Filter:
switch val.Type {
case bsontype.Array:
conds, ok := val.ArrayOK()
if ok {
condsElems, err := conds.Values()
if err == nil {
for _, condElem := range condsElems {
cond, ok := condElem.DocumentOK()
if ok {
q.Conditions = append(q.Conditions, cond)
}
}
}
}
case bsontype.EmbeddedDocument:
cond, ok := val.DocumentOK()
if ok {
q.Conditions = append(q.Conditions, cond)
}
}
}
}
return nil
}