| 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 docstore |
| 16 |
|
| 17 |
import ( |
| 18 |
"context" |
| 19 |
"io" |
| 20 |
"reflect" |
| 21 |
"time" |
| 22 |
|
| 23 |
"go.opentelemetry.io/otel/trace" |
| 24 |
"gocloud.dev/docstore/driver" |
| 25 |
"gocloud.dev/internal/gcerr" |
| 26 |
) |
| 27 |
|
| 28 |
// Query represents a query over a collection. |
| 29 |
type Query struct { |
| 30 |
coll *Collection |
| 31 |
dq *driver.Query |
| 32 |
err error |
| 33 |
} |
| 34 |
|
| 35 |
// Query creates a new Query over the collection. |
| 36 |
func (c *Collection) Query() *Query { |
| 37 |
return &Query{coll: c, dq: &driver.Query{}} |
| 38 |
} |
| 39 |
|
| 40 |
// Where expresses a condition on the query. |
| 41 |
// Valid ops are: "=", ">", "<", ">=", "<=, "in", "not-in". |
| 42 |
// Valid values are strings, integers, floating-point numbers, time.Time and boolean (only for "=", "in" and "not-in") values. |
| 43 |
func (q *Query) Where(fp FieldPath, op string, value any) *Query { |
| 44 |
if q.err != nil { |
| 45 |
return q |
| 46 |
} |
| 47 |
pfp, err := parseFieldPath(fp) |
| 48 |
if err != nil { |
| 49 |
q.err = err |
| 50 |
return q |
| 51 |
} |
| 52 |
validator, ok := validOp[op] |
| 53 |
if !ok { |
| 54 |
return q.invalidf("invalid filter operator: %q. Use one of: =, >, <, >=, <=, in, not-in", op) |
| 55 |
} |
| 56 |
if !validator(value) { |
| 57 |
return q.invalidf("invalid filter value: %v", value) |
| 58 |
} |
| 59 |
q.dq.Filters = append(q.dq.Filters, driver.Filter{ |
| 60 |
FieldPath: pfp, |
| 61 |
Op: op, |
| 62 |
Value: value, |
| 63 |
}) |
| 64 |
return q |
| 65 |
} |
| 66 |
|
| 67 |
type valueValidator func(any) bool |
| 68 |
|
| 69 |
var validOp = map[string]valueValidator{ |
| 70 |
"=": validEqualValue, |
| 71 |
">": validFilterValue, |
| 72 |
"<": validFilterValue, |
| 73 |
">=": validFilterValue, |
| 74 |
"<=": validFilterValue, |
| 75 |
"in": validFilterSlice, |
| 76 |
"not-in": validFilterSlice, |
| 77 |
} |
| 78 |
|
| 79 |
func validEqualValue(v any) bool { |
| 80 |
if v == nil { |
| 81 |
return false |
| 82 |
} |
| 83 |
if reflect.TypeOf(v).Kind() == reflect.Bool { |
| 84 |
return true |
| 85 |
} |
| 86 |
return validFilterValue(v) |
| 87 |
} |
| 88 |
|
| 89 |
func validFilterValue(v any) bool { |
| 90 |
if v == nil { |
| 91 |
return false |
| 92 |
} |
| 93 |
if _, ok := v.(time.Time); ok { |
| 94 |
return true |
| 95 |
} |
| 96 |
switch reflect.TypeOf(v).Kind() { |
| 97 |
case reflect.String: |
| 98 |
return true |
| 99 |
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: |
| 100 |
return true |
| 101 |
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: |
| 102 |
return true |
| 103 |
case reflect.Float32, reflect.Float64: |
| 104 |
return true |
| 105 |
default: |
| 106 |
return false |
| 107 |
} |
| 108 |
} |
| 109 |
|
| 110 |
func validFilterSlice(v any) bool { |
| 111 |
if v == nil || reflect.TypeOf(v).Kind() != reflect.Slice { |
| 112 |
return false |
| 113 |
} |
| 114 |
vv := reflect.ValueOf(v) |
| 115 |
for i := 0; i < vv.Len(); i++ { |
| 116 |
if !validEqualValue(vv.Index(i).Interface()) { |
| 117 |
return false |
| 118 |
} |
| 119 |
} |
| 120 |
return true |
| 121 |
} |
| 122 |
|
| 123 |
// Offset (also commonly referred to as `Skip`) specifies the number of |
| 124 |
// documents to skip before returning results. |
| 125 |
// n must be non-negative. |
| 126 |
// It is an error to specify Offset more than once in a Get query, or |
| 127 |
// at all in a Delete or Update query. |
| 128 |
func (q *Query) Offset(n int) *Query { |
| 129 |
if q.err != nil { |
| 130 |
return q |
| 131 |
} |
| 132 |
if n < 0 { |
| 133 |
return q.invalidf("offset value of %d must be non-negative", n) |
| 134 |
} |
| 135 |
if q.dq.Offset > 0 { |
| 136 |
return q.invalidf("query can have at most one offset clause") |
| 137 |
} |
| 138 |
q.dq.Offset = n |
| 139 |
return q |
| 140 |
} |
| 141 |
|
| 142 |
// Limit will limit the results to at most n documents. |
| 143 |
// n must be positive. |
| 144 |
// It is an error to specify Limit more than once in a Get query, or |
| 145 |
// at all in a Delete or Update query. |
| 146 |
func (q *Query) Limit(n int) *Query { |
| 147 |
if q.err != nil { |
| 148 |
return q |
| 149 |
} |
| 150 |
if n <= 0 { |
| 151 |
return q.invalidf("limit value of %d must be greater than zero", n) |
| 152 |
} |
| 153 |
if q.dq.Limit > 0 { |
| 154 |
return q.invalidf("query can have at most one limit clause") |
| 155 |
} |
| 156 |
q.dq.Limit = n |
| 157 |
return q |
| 158 |
} |
| 159 |
|
| 160 |
// Ascending and Descending are constants for use in the OrderBy method. |
| 161 |
const ( |
| 162 |
Ascending = "asc" |
| 163 |
Descending = "desc" |
| 164 |
) |
| 165 |
|
| 166 |
// OrderBy specifies that the returned documents appear sorted by the given field in |
| 167 |
// the given direction. |
| 168 |
// A query can have at most one OrderBy clause. If it has none, the order of returned |
| 169 |
// documents is unspecified. |
| 170 |
// If a query has a Where clause and an OrderBy clause, the OrderBy clause's field |
| 171 |
// must appear in a Where clause. |
| 172 |
// It is an error to specify OrderBy in a Delete or Update query. |
| 173 |
func (q *Query) OrderBy(field, direction string) *Query { |
| 174 |
if q.err != nil { |
| 175 |
return q |
| 176 |
} |
| 177 |
if field == "" { |
| 178 |
return q.invalidf("OrderBy: empty field") |
| 179 |
} |
| 180 |
if direction != Ascending && direction != Descending { |
| 181 |
return q.invalidf("OrderBy: direction must be one of %q or %q", Ascending, Descending) |
| 182 |
} |
| 183 |
if q.dq.OrderByField != "" { |
| 184 |
return q.invalidf("a query can have at most one OrderBy") |
| 185 |
} |
| 186 |
q.dq.OrderByField = field |
| 187 |
q.dq.OrderAscending = (direction == Ascending) |
| 188 |
return q |
| 189 |
} |
| 190 |
|
| 191 |
// BeforeQuery takes a callback function that will be called before the Query is |
| 192 |
// executed to the underlying service's query functionality. The callback takes |
| 193 |
// a parameter, asFunc, that converts its argument to driver-specific types. |
| 194 |
// See https://gocloud.dev/concepts/as/ for background information. |
| 195 |
func (q *Query) BeforeQuery(f func(asFunc func(any) bool) error) *Query { |
| 196 |
q.dq.BeforeQuery = f |
| 197 |
return q |
| 198 |
} |
| 199 |
|
| 200 |
// Get returns an iterator for retrieving the documents specified by the query. If |
| 201 |
// field paths are provided, only those paths are set in the resulting documents. |
| 202 |
// |
| 203 |
// Call Stop on the iterator when finished. |
| 204 |
func (q *Query) Get(ctx context.Context, fps ...FieldPath) *DocumentIterator { |
| 205 |
return q.get(ctx, true, fps...) |
| 206 |
} |
| 207 |
|
| 208 |
// get implements Get, with optional OpenTelemetry tracing so it can be used internally. |
| 209 |
func (q *Query) get(ctx context.Context, withTracing bool, fps ...FieldPath) *DocumentIterator { |
| 210 |
dcoll := q.coll.driver |
| 211 |
if err := q.initGet(fps); err != nil { |
| 212 |
return &DocumentIterator{err: wrapError(dcoll, err)} |
| 213 |
} |
| 214 |
|
| 215 |
var err error |
| 216 |
|
| 217 |
if withTracing { |
| 218 |
var span trace.Span |
| 219 |
ctx, span = q.coll.tracer.Start(ctx, "Query.Get") |
| 220 |
defer func() { |
| 221 |
q.coll.tracer.End(ctx, span, err) |
| 222 |
}() |
| 223 |
} |
| 224 |
it, err := dcoll.RunGetQuery(ctx, q.dq) |
| 225 |
return &DocumentIterator{iter: it, coll: q.coll, err: wrapError(dcoll, err)} |
| 226 |
} |
| 227 |
|
| 228 |
func (q *Query) initGet(fps []FieldPath) error { |
| 229 |
if q.err != nil { |
| 230 |
return q.err |
| 231 |
} |
| 232 |
if err := q.coll.checkClosed(); err != nil { |
| 233 |
return errClosed |
| 234 |
} |
| 235 |
pfps, err := parseFieldPaths(fps) |
| 236 |
if err != nil { |
| 237 |
return err |
| 238 |
} |
| 239 |
q.dq.FieldPaths = pfps |
| 240 |
if q.dq.OrderByField != "" && len(q.dq.Filters) > 0 { |
| 241 |
found := false |
| 242 |
for _, f := range q.dq.Filters { |
| 243 |
if len(f.FieldPath) == 1 && f.FieldPath[0] == q.dq.OrderByField { |
| 244 |
found = true |
| 245 |
break |
| 246 |
} |
| 247 |
} |
| 248 |
if !found { |
| 249 |
return gcerr.Newf(gcerr.InvalidArgument, nil, "OrderBy field %s must appear in a Where clause", |
| 250 |
q.dq.OrderByField) |
| 251 |
} |
| 252 |
} |
| 253 |
return nil |
| 254 |
} |
| 255 |
|
| 256 |
func (q *Query) invalidf(format string, args ...any) *Query { |
| 257 |
q.err = gcerr.Newf(gcerr.InvalidArgument, nil, format, args...) |
| 258 |
return q |
| 259 |
} |
| 260 |
|
| 261 |
// DocumentIterator iterates over documents. |
| 262 |
// |
| 263 |
// Always call Stop on the iterator. |
| 264 |
type DocumentIterator struct { |
| 265 |
iter driver.DocumentIterator |
| 266 |
coll *Collection |
| 267 |
err error // already wrapped |
| 268 |
} |
| 269 |
|
| 270 |
// Next stores the next document in dst. It returns io.EOF if there are no more |
| 271 |
// documents. |
| 272 |
// Once Next returns an error, it will always return the same error. |
| 273 |
func (it *DocumentIterator) Next(ctx context.Context, dst Document) error { |
| 274 |
if it.err != nil { |
| 275 |
return it.err |
| 276 |
} |
| 277 |
if err := it.coll.checkClosed(); err != nil { |
| 278 |
it.err = err |
| 279 |
return it.err |
| 280 |
} |
| 281 |
ddoc, err := driver.NewDocument(dst) |
| 282 |
if err != nil { |
| 283 |
it.err = wrapError(it.coll.driver, err) |
| 284 |
return it.err |
| 285 |
} |
| 286 |
it.err = wrapError(it.coll.driver, it.iter.Next(ctx, ddoc)) |
| 287 |
return it.err |
| 288 |
} |
| 289 |
|
| 290 |
// Stop stops the iterator. Calling Next on a stopped iterator will return io.EOF, or |
| 291 |
// the error that Next previously returned. |
| 292 |
func (it *DocumentIterator) Stop() { |
| 293 |
if it.err != nil { |
| 294 |
return |
| 295 |
} |
| 296 |
it.err = io.EOF |
| 297 |
it.iter.Stop() |
| 298 |
} |
| 299 |
|
| 300 |
// As converts i to driver-specific types. |
| 301 |
// See https://gocloud.dev/concepts/as/ for background information, the "As" |
| 302 |
// examples in this package for examples, and the driver package |
| 303 |
// documentation for the specific types supported for that driver. |
| 304 |
func (it *DocumentIterator) As(i any) bool { |
| 305 |
if i == nil || it.iter == nil { |
| 306 |
return false |
| 307 |
} |
| 308 |
return it.iter.As(i) |
| 309 |
} |
| 310 |
|
| 311 |
// Plan describes how the query would be executed if its Get method were called with |
| 312 |
// the given field paths. Plan uses only information available to the client, so it |
| 313 |
// cannot know whether a service uses indexes or scans internally. |
| 314 |
func (q *Query) Plan(fps ...FieldPath) (string, error) { |
| 315 |
if err := q.initGet(fps); err != nil { |
| 316 |
return "", err |
| 317 |
} |
| 318 |
return q.coll.driver.QueryPlan(q.dq) |
| 319 |
} |