Debian Codegraph @

docstore/memdocstore/query.go

raw
1 // Copyright 2019 The Go Cloud Development Kit Authors
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 // https://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 memdocstore
16
17 import (
18 "context"
19 "io"
20 "reflect"
21 "sort"
22 "strings"
23 "time"
24
25 "gocloud.dev/docstore/driver"
26 )
27
28 func (c *collection) RunGetQuery(_ context.Context, q *driver.Query) (driver.DocumentIterator, error) {
29 if q.BeforeQuery != nil {
30 if err := q.BeforeQuery(func(any) bool { return false }); err != nil {
31 return nil, err
32 }
33 }
34
35 c.mu.Lock()
36 defer c.mu.Unlock()
37
38 var resultDocs []storedDoc
39 for _, doc := range c.docs {
40 if filtersMatch(q.Filters, doc, c.opts.AllowNestedSliceQueries) {
41 resultDocs = append(resultDocs, doc)
42 }
43 }
44 if q.OrderByField != "" {
45 sortDocs(resultDocs, q.OrderByField, q.OrderAscending)
46 }
47
48 // Apply offset
49 if q.Offset > 0 {
50 if q.Offset >= len(resultDocs) {
51 resultDocs = []storedDoc{} // If offset is larger than or equal to the length, result should be an empty slice
52 } else {
53 resultDocs = resultDocs[q.Offset:]
54 }
55 }
56
57 // Apply limit
58 if q.Limit > 0 && len(resultDocs) > q.Limit {
59 resultDocs = resultDocs[:q.Limit]
60 }
61
62 // Include the key field in the field paths if there is one.
63 var fps [][]string
64 if len(q.FieldPaths) > 0 && c.keyField != "" {
65 fps = append([][]string{{c.keyField}}, q.FieldPaths...)
66 } else {
67 fps = q.FieldPaths
68 }
69
70 return &docIterator{
71 docs: resultDocs,
72 fieldPaths: fps,
73 revField: c.opts.RevisionField,
74 }, nil
75 }
76
77 func filtersMatch(fs []driver.Filter, doc storedDoc, nested bool) bool {
78 for _, f := range fs {
79 if !filterMatches(f, doc, nested) {
80 return false
81 }
82 }
83 return true
84 }
85
86 func filterMatches(f driver.Filter, doc storedDoc, nested bool) bool {
87 docval, err := getAtFieldPath(doc, f.FieldPath, nested)
88 // missing or bad field path => no match
89 if err != nil {
90 return false
91 }
92 c, ok := compare(docval, f.Value, f.Op)
93 if !ok {
94 return false
95 }
96 return applyComparison(f.Op, c)
97 }
98
99 // op is one of the permitted docstore operators ("=", "<", etc.)
100 // c is the result of strings.Compare or the like.
101 // TODO(jba): dedup from gcpfirestore/query?
102 func applyComparison(op string, c int) bool {
103 switch op {
104 case driver.EqualOp:
105 return c == 0
106 case ">":
107 return c > 0
108 case "<":
109 return c < 0
110 case ">=":
111 return c >= 0
112 case "<=":
113 return c <= 0
114 case "in":
115 return c == 0
116 case "not-in":
117 return c != 0
118 default:
119 panic("bad op")
120 }
121 }
122
123 func compare(x1, x2 any, op string) (int, bool) {
124 v1 := reflect.ValueOf(x1)
125 v2 := reflect.ValueOf(x2)
126 // For in/not-in queries. Otherwise this should only be reached with AllowNestedSliceQueries set.
127 // Return 0 if x1 is in slice x2, -1 if not.
128 if v2.Kind() == reflect.Slice {
129 for i := range v2.Len() {
130 if c, ok := compare(x1, v2.Index(i).Interface(), op); ok {
131 if c == 0 {
132 return 0, true
133 }
134 if op != "in" && op != "not-in" {
135 return c, true
136 }
137 }
138 }
139 return -1, true
140 }
141 // See Options.AllowNestedSliceQueries
142 // When querying for x2 in the document and x1 is a list of values we only need one value to match
143 // the comparison value depends on the operator.
144 if v1.Kind() == reflect.Slice {
145 v2Greater := false
146 v2Less := false
147 for i := range v1.Len() {
148 if c, ok := compare(x2, v1.Index(i).Interface(), op); ok {
149 if c == 0 {
150 return 0, true
151 }
152 v2Greater = v2Greater || c > 0
153 v2Less = v2Less || c < 0
154 }
155 }
156 if op[0] == '>' && v2Less {
157 return 1, true
158 } else if op[0] == '<' && v2Greater {
159 return -1, true
160 }
161 return 0, false
162 }
163 if v1.Kind() == reflect.String && v2.Kind() == reflect.String {
164 return strings.Compare(v1.String(), v2.String()), true
165 }
166 if cmp, err := driver.CompareNumbers(v1, v2); err == nil {
167 return cmp, true
168 }
169 if t1, ok := x1.(time.Time); ok {
170 if t2, ok := x2.(time.Time); ok {
171 return driver.CompareTimes(t1, t2), true
172 }
173 }
174 if v1.Kind() == reflect.Bool && v2.Kind() == reflect.Bool {
175 if v1.Bool() == v2.Bool() {
176 return 0, true
177 }
178 return -1, true
179 }
180 return 0, false
181 }
182
183 func sortDocs(docs []storedDoc, field string, asc bool) {
184 sort.Slice(docs, func(i, j int) bool {
185 c, ok := compare(docs[i][field], docs[j][field], ">")
186 if !ok {
187 return false
188 }
189 if asc {
190 return c < 0
191 }
192 return c > 0
193 })
194 }
195
196 type docIterator struct {
197 docs []storedDoc
198 fieldPaths [][]string
199 revField string
200 err error
201 }
202
203 func (it *docIterator) Next(ctx context.Context, doc driver.Document) error {
204 if it.err != nil {
205 return it.err
206 }
207 if len(it.docs) == 0 {
208 it.err = io.EOF
209 return it.err
210 }
211 if err := decodeDoc(it.docs[0], doc, it.fieldPaths); err != nil {
212 it.err = err
213 return it.err
214 }
215 it.docs = it.docs[1:]
216 return nil
217 }
218
219 func (it *docIterator) Stop() { it.err = io.EOF }
220
221 func (it *docIterator) As(i any) bool { return false }
222
223 func (c *collection) QueryPlan(q *driver.Query) (string, error) {
224 return "", nil
225 }