Debian Codegraph @

docstore/awsdynamodb/v2/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 awsdynamodb
16
17 import (
18 "bytes"
19 "context"
20 "errors"
21 "fmt"
22 "io"
23 "reflect"
24 "sort"
25 "strings"
26 "time"
27
28 "github.com/aws/aws-sdk-go-v2/aws"
29 "github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression"
30 dyn "github.com/aws/aws-sdk-go-v2/service/dynamodb"
31 dyn2Types "github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
32 "gocloud.dev/docstore/driver"
33 "gocloud.dev/gcerrors"
34 "gocloud.dev/internal/gcerr"
35 )
36
37 // TODO: support parallel scans (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Scan.html#Scan.ParallelScan)
38
39 // TODO(jba): support an empty item slice returned from an RPC: "A Query operation can
40 // return an empty result set and a LastEvaluatedKey if all the items read for the
41 // page of results are filtered out."
42
43 type avmap = map[string]dyn2Types.AttributeValue
44
45 func (c *collection) RunGetQuery(ctx context.Context, q *driver.Query) (driver.DocumentIterator, error) {
46 qr, err := c.planQuery(q)
47 if err != nil {
48 if gcerrors.Code(err) == gcerrors.Unimplemented && c.opts.RunQueryFallback != nil {
49 return c.opts.RunQueryFallback(ctx, q, c.RunGetQuery)
50 }
51 return nil, err
52 }
53 if err := c.checkPlan(qr); err != nil {
54 return nil, err
55 }
56 it := &documentIterator{
57 qr: qr,
58 offset: q.Offset,
59 limit: q.Limit,
60 count: 0, // manually count limit since dynamodb uses "limit" as scan limit before filtering
61 }
62 it.items, it.last, it.asFunc, err = it.qr.run(ctx, nil)
63 if err != nil {
64 return nil, err
65 }
66 return it, nil
67 }
68
69 func (c *collection) checkPlan(qr *queryRunner) error {
70 if qr.scanIn != nil && qr.scanIn.FilterExpression != nil && !c.opts.AllowScans {
71 return gcerr.Newf(gcerr.InvalidArgument, nil, "query requires a table scan; set Options.AllowScans to true to enable")
72 }
73 return nil
74 }
75
76 func (c *collection) planQuery(q *driver.Query) (*queryRunner, error) {
77 var cb expression.Builder
78 cbUsed := false // It's an error to build an empty Builder.
79 // Set up the projection expression.
80 if len(q.FieldPaths) > 0 {
81 var pb expression.ProjectionBuilder
82 hasFields := map[string]bool{}
83 for _, fp := range q.FieldPaths {
84 if len(fp) == 1 {
85 hasFields[fp[0]] = true
86 }
87 pb = pb.AddNames(expression.Name(strings.Join(fp, ".")))
88 }
89 // Always include the keys.
90 for _, f := range []string{c.partitionKey, c.sortKey} {
91 if f != "" && !hasFields[f] {
92 pb = pb.AddNames(expression.Name(f))
93 q.FieldPaths = append(q.FieldPaths, []string{f})
94 }
95 }
96 cb = cb.WithProjection(pb)
97 cbUsed = true
98 }
99
100 // Find the best thing to query (table or index).
101 indexName, pkey, skey := c.bestQueryable(q)
102 if indexName == nil && pkey == "" {
103 // No query can be done: fall back to scanning.
104 if q.OrderByField != "" {
105 // Scans are unordered, so we can't run this query.
106 // TODO(jba): If the user specifies all the partition keys, and there is a global
107 // secondary index whose sort key is the order-by field, then we can query that index
108 // for every value of the partition key and merge the results.
109 // TODO(jba): If the query has a reasonable limit N, then we can run a scan and keep
110 // the top N documents in memory.
111 return nil, gcerr.Newf(gcerr.Unimplemented, nil, "query requires a table scan, but has an ordering requirement; add an index or provide Options.RunQueryFallback")
112 }
113 if len(q.Filters) > 0 {
114 cb = cb.WithFilter(filtersToConditionBuilder(q.Filters))
115 cbUsed = true
116 }
117 in := &dyn.ScanInput{
118 TableName: &c.table,
119 ConsistentRead: aws.Bool(c.opts.ConsistentRead),
120 }
121 if cbUsed {
122 ce, err := cb.Build()
123 if err != nil {
124 return nil, err
125 }
126 in.ExpressionAttributeNames = ce.Names()
127 in.ExpressionAttributeValues = ce.Values()
128 in.FilterExpression = ce.Filter()
129 in.ProjectionExpression = ce.Projection()
130 }
131 return &queryRunner{c: c, scanIn: in, beforeRun: q.BeforeQuery}, nil
132 }
133
134 // Do a query.
135 cb = processFilters(cb, q.Filters, pkey, skey)
136 ce, err := cb.Build()
137 if err != nil {
138 return nil, err
139 }
140 qIn := &dyn.QueryInput{
141 TableName: &c.table,
142 IndexName: indexName,
143 ExpressionAttributeNames: ce.Names(),
144 ExpressionAttributeValues: ce.Values(),
145 KeyConditionExpression: ce.KeyCondition(),
146 FilterExpression: ce.Filter(),
147 ProjectionExpression: ce.Projection(),
148 ConsistentRead: aws.Bool(c.opts.ConsistentRead),
149 }
150 if q.OrderByField != "" && !q.OrderAscending {
151 qIn.ScanIndexForward = &q.OrderAscending
152 }
153 return &queryRunner{
154 c: c,
155 queryIn: qIn,
156 beforeRun: q.BeforeQuery,
157 }, nil
158 }
159
160 // Return the best choice of queryable (table or index) for this query.
161 // How to interpret the return values:
162 // - If indexName is nil but pkey is not empty, then use the table.
163 // - If all return values are zero, no query will work: do a scan.
164 func (c *collection) bestQueryable(q *driver.Query) (indexName *string, pkey, skey string) {
165 // If the query has an "=" filter on the table's partition key, look at the table
166 // and local indexes.
167 if hasEqualityFilter(q, c.partitionKey) {
168 // If the table has a sort key that's in the query, and the ordering
169 // constraint works with the sort key, use the table.
170 // (Query results are always ordered by sort key.)
171 if hasFilter(q, c.sortKey) && orderingConsistent(q, c.sortKey) {
172 return nil, c.partitionKey, c.sortKey
173 }
174 // Look at local indexes. They all have the same partition key as the base table.
175 // If one has a sort key in the query, use it.
176 for _, li := range c.description.LocalSecondaryIndexes {
177 pkey, skey := keyAttributes(li.KeySchema)
178 if hasFilter(q, skey) && localFieldsIncluded(q, li) && orderingConsistent(q, skey) {
179 return li.IndexName, pkey, skey
180 }
181 }
182 }
183 // Consider the global indexes: if one has a matching partition and sort key, and
184 // the projected fields of the index include those of the query, use it.
185 for _, gi := range c.description.GlobalSecondaryIndexes {
186 pkey, skey := keyAttributes(gi.KeySchema)
187 if skey == "" {
188 continue // We'll visit global indexes without a sort key later.
189 }
190 if hasEqualityFilter(q, pkey) && hasFilter(q, skey) && c.globalFieldsIncluded(q, gi) && orderingConsistent(q, skey) {
191 return gi.IndexName, pkey, skey
192 }
193 }
194 // There are no matches for both partition and sort key. Now consider matches on partition key only.
195 // That will still be better than a scan.
196 // First, check the table itself.
197 if hasEqualityFilter(q, c.partitionKey) && orderingConsistent(q, c.sortKey) {
198 return nil, c.partitionKey, c.sortKey
199 }
200 // No point checking local indexes: they have the same partition key as the table.
201 // Check the global indexes.
202 for _, gi := range c.description.GlobalSecondaryIndexes {
203 pkey, skey := keyAttributes(gi.KeySchema)
204 if hasEqualityFilter(q, pkey) && c.globalFieldsIncluded(q, gi) && orderingConsistent(q, skey) {
205 return gi.IndexName, pkey, skey
206 }
207 }
208 // We cannot do a query.
209 // TODO: return the reason why we couldn't. At a minimum, distinguish failure due to keys
210 // from failure due to projection (i.e. a global index had the right partition and sort key,
211 // but didn't project the necessary fields).
212 return nil, "", ""
213 }
214
215 // localFieldsIncluded reports whether a local index supports all the selected fields
216 // of a query. Since DynamoDB will read explicitly provided fields from the table if
217 // they are not projected into the index, the only case where a local index cannot
218 // be used is when the query wants all the fields, and the index projection is not ALL.
219 // See https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LSI.html#LSI.Projections.
220 func localFieldsIncluded(q *driver.Query, li dyn2Types.LocalSecondaryIndexDescription) bool {
221 return len(q.FieldPaths) > 0 || li.Projection.ProjectionType == dyn2Types.ProjectionTypeAll
222 }
223
224 // orderingConsistent reports whether the ordering constraint is consistent with the sort key field.
225 // That is, either there is no OrderBy clause, or the clause specifies the sort field.
226 func orderingConsistent(q *driver.Query, sortField string) bool {
227 return q.OrderByField == "" || q.OrderByField == sortField
228 }
229
230 // globalFieldsIncluded reports whether the fields selected by the query are
231 // projected into (that is, contained directly in) the global index. We need this
232 // check before using the index, because if a global index doesn't have all the
233 // desired fields, then a separate RPC for each returned item would be necessary to
234 // retrieve those fields, and we'd rather scan than do that.
235 func (c *collection) globalFieldsIncluded(q *driver.Query, gi dyn2Types.GlobalSecondaryIndexDescription) bool {
236 proj := gi.Projection
237 if proj.ProjectionType == dyn2Types.ProjectionTypeAll {
238 // The index has all the fields of the table: we're good.
239 return true
240 }
241 if len(q.FieldPaths) == 0 {
242 // The query wants all the fields of the table, but we can't be sure that the
243 // index has them.
244 return false
245 }
246 // The table's keys and the index's keys are always in the index.
247 pkey, skey := keyAttributes(gi.KeySchema)
248 indexFields := map[string]bool{c.partitionKey: true, pkey: true}
249 if c.sortKey != "" {
250 indexFields[c.sortKey] = true
251 }
252 if skey != "" {
253 indexFields[skey] = true
254 }
255 for _, nka := range proj.NonKeyAttributes {
256 indexFields[nka] = true
257 }
258 // Every field path in the query must be in the index.
259 for _, fp := range q.FieldPaths {
260 if !indexFields[strings.Join(fp, ".")] {
261 return false
262 }
263 }
264 return true
265 }
266
267 // Extract the names of the partition and sort key attributes from the schema of a
268 // table or index.
269 func keyAttributes(ks []dyn2Types.KeySchemaElement) (pkey, skey string) {
270 for _, k := range ks {
271 switch k.KeyType {
272 case dyn2Types.KeyTypeHash:
273 pkey = *k.AttributeName
274 case dyn2Types.KeyTypeRange:
275 skey = *k.AttributeName
276 default:
277 panic("bad key type: " + k.KeyType)
278 }
279 }
280 return pkey, skey
281 }
282
283 // Reports whether q has a filter that mentions the top-level field.
284 func hasFilter(q *driver.Query, field string) bool {
285 if field == "" {
286 return false
287 }
288 for _, f := range q.Filters {
289 if driver.FieldPathEqualsField(f.FieldPath, field) {
290 return true
291 }
292 }
293 return false
294 }
295
296 // Reports whether q has a filter that checks if the top-level field is equal to something.
297 func hasEqualityFilter(q *driver.Query, field string) bool {
298 for _, f := range q.Filters {
299 if f.Op == driver.EqualOp && driver.FieldPathEqualsField(f.FieldPath, field) {
300 return true
301 }
302 }
303 return false
304 }
305
306 type queryRunner struct {
307 c *collection
308 scanIn *dyn.ScanInput
309 queryIn *dyn.QueryInput
310 beforeRun func(asFunc func(i any) bool) error
311 }
312
313 func (qr *queryRunner) run(ctx context.Context, startAfter avmap) (items []avmap, last avmap, asFunc func(i any) bool, err error) {
314 if qr.scanIn != nil {
315 qr.scanIn.ExclusiveStartKey = startAfter
316 if qr.beforeRun != nil {
317 asFunc := func(i any) bool {
318 p, ok := i.(**dyn.ScanInput)
319 if !ok {
320 return false
321 }
322 *p = qr.scanIn
323 return true
324 }
325 if err := qr.beforeRun(asFunc); err != nil {
326 return nil, nil, nil, err
327 }
328 }
329 out, err := qr.c.db.Scan(ctx, qr.scanIn)
330 if err != nil {
331 return nil, nil, nil, err
332 }
333 return out.Items, out.LastEvaluatedKey,
334 func(i any) bool {
335 p, ok := i.(**dyn.ScanOutput)
336 if !ok {
337 return false
338 }
339 *p = out
340 return true
341 }, nil
342 }
343 qr.queryIn.ExclusiveStartKey = startAfter
344 if qr.beforeRun != nil {
345 asFunc := func(i any) bool {
346 p, ok := i.(**dyn.QueryInput)
347 if !ok {
348 return false
349 }
350 *p = qr.queryIn
351 return true
352 }
353 if err := qr.beforeRun(asFunc); err != nil {
354 return nil, nil, nil, err
355 }
356 }
357 out, err := qr.c.db.Query(ctx, qr.queryIn)
358 if err != nil {
359 return nil, nil, nil, err
360 }
361 return out.Items, out.LastEvaluatedKey,
362 func(i any) bool {
363 p, ok := i.(**dyn.QueryOutput)
364 if !ok {
365 return false
366 }
367 *p = out
368 return true
369 }, nil
370 }
371
372 func processFilters(cb expression.Builder, fs []driver.Filter, pkey, skey string) expression.Builder {
373 var kbs []expression.KeyConditionBuilder
374 var cfs []driver.Filter
375 for _, f := range fs {
376 if kb, ok := toKeyCondition(f, pkey, skey); ok {
377 kbs = append(kbs, kb)
378 continue
379 }
380 cfs = append(cfs, f)
381 }
382 keyBuilder := kbs[0]
383 for i := 1; i < len(kbs); i++ {
384 keyBuilder = keyBuilder.And(kbs[i])
385 }
386 cb = cb.WithKeyCondition(keyBuilder)
387 if len(cfs) > 0 {
388 cb = cb.WithFilter(filtersToConditionBuilder(cfs))
389 }
390 return cb
391 }
392
393 func filtersToConditionBuilder(fs []driver.Filter) expression.ConditionBuilder {
394 if len(fs) == 0 {
395 panic("no filters")
396 }
397 var cb expression.ConditionBuilder
398 cb = toFilter(fs[0])
399 for _, f := range fs[1:] {
400 cb = cb.And(toFilter(f))
401 }
402 return cb
403 }
404
405 func toKeyCondition(f driver.Filter, pkey, skey string) (expression.KeyConditionBuilder, bool) {
406 kp := strings.Join(f.FieldPath, ".")
407 if kp == pkey || kp == skey {
408 key := expression.Key(kp)
409 val := expression.Value(f.Value)
410 switch f.Op {
411 case "<":
412 return expression.KeyLessThan(key, val), true
413 case "<=":
414 return expression.KeyLessThanEqual(key, val), true
415 case driver.EqualOp:
416 return expression.KeyEqual(key, val), true
417 case ">=":
418 return expression.KeyGreaterThanEqual(key, val), true
419 case ">":
420 return expression.KeyGreaterThan(key, val), true
421 default:
422 panic(fmt.Sprint("invalid filter operation:", f.Op))
423 }
424 }
425 return expression.KeyConditionBuilder{}, false
426 }
427
428 func toFilter(f driver.Filter) expression.ConditionBuilder {
429 name := expression.Name(strings.Join(f.FieldPath, "."))
430 val := expression.Value(f.Value)
431 switch f.Op {
432 case "<":
433 return expression.LessThan(name, val)
434 case "<=":
435 return expression.LessThanEqual(name, val)
436 case driver.EqualOp:
437 return expression.Equal(name, val)
438 case ">=":
439 return expression.GreaterThanEqual(name, val)
440 case ">":
441 return expression.GreaterThan(name, val)
442 case "in":
443 return toInCondition(f)
444 case "not-in":
445 return expression.Not(toInCondition(f))
446 default:
447 panic(fmt.Sprint("invalid filter operation:", f.Op))
448 }
449 }
450
451 func toInCondition(f driver.Filter) expression.ConditionBuilder {
452 name := expression.Name(strings.Join(f.FieldPath, "."))
453 vslice := reflect.ValueOf(f.Value)
454 right := expression.Value(vslice.Index(0).Interface())
455 other := make([]expression.OperandBuilder, vslice.Len()-1)
456 for i := 1; i < vslice.Len(); i++ {
457 other[i-1] = expression.Value(vslice.Index(i).Interface())
458 }
459 return expression.In(name, right, other...)
460 }
461
462 type documentIterator struct {
463 qr *queryRunner // the query runner
464 items []map[string]dyn2Types.AttributeValue // items from the last query
465 curr int // index of the current item in items
466 offset int // number of items to skip
467 limit int // number of items to return
468 count int // number of items returned
469 last map[string]dyn2Types.AttributeValue // lastEvaluatedKey from the last query
470 asFunc func(i any) bool // for As
471 }
472
473 func (it *documentIterator) Next(ctx context.Context, doc driver.Document) error {
474 // Skip the first 'n' documents where 'n' is the offset.
475 for it.count < it.offset {
476 if err := it.next(ctx, doc, false); err != nil {
477 return err
478 }
479 }
480 return it.next(ctx, doc, true)
481 }
482
483 func (it *documentIterator) next(ctx context.Context, doc driver.Document, decode bool) error {
484 // Only start counting towards the limit after the offset has been reached.
485 if it.limit > 0 && it.count >= it.offset+it.limit {
486 return io.EOF
487 }
488 // it.items can be empty after a call to it.qr.run, but unless it.last is nil there may be more items.
489 for it.curr >= len(it.items) {
490 // Make a new query request at the end of this page.
491 if it.last == nil {
492 return io.EOF
493 }
494 var err error
495 it.items, it.last, it.asFunc, err = it.qr.run(ctx, it.last)
496 if err != nil {
497 return err
498 }
499 it.curr = 0
500 }
501 if decode {
502 if err := decodeDoc(&dyn2Types.AttributeValueMemberM{Value: it.items[it.curr]}, doc); err != nil {
503 return err
504 }
505 }
506 it.curr++
507 it.count++
508 return nil
509 }
510
511 func (it *documentIterator) Stop() {
512 it.items = nil
513 it.last = nil
514 }
515
516 func (it *documentIterator) As(i any) bool {
517 return it.asFunc(i)
518 }
519
520 func (c *collection) QueryPlan(q *driver.Query) (string, error) {
521 qr, err := c.planQuery(q)
522 if err != nil {
523 return "", err
524 }
525 return qr.queryPlan(), nil
526 }
527
528 func (qr *queryRunner) queryPlan() string {
529 if qr.scanIn != nil {
530 return "Scan"
531 }
532 if qr.queryIn.IndexName != nil {
533 return fmt.Sprintf("Index: %q", *qr.queryIn.IndexName)
534 }
535 return "Table"
536 }
537
538 // InMemorySortFallback returns a query fallback function for Options.RunQueryFallback.
539 // The function accepts a query with an OrderBy clause. It runs the query without that clause,
540 // reading all documents into memory, then sorts the documents according to the OrderBy clause.
541 //
542 // Only string, numeric, time and binary ([]byte) fields can be sorted.
543 //
544 // createDocument should create an empty document to be passed to DocumentIterator.Next.
545 // The DocumentIterator returned by the FallbackFunc will also expect the same type of document.
546 // If nil, then a map[string]interface{} will be used.
547 func InMemorySortFallback(createDocument func() any) FallbackFunc {
548 if createDocument == nil {
549 createDocument = func() any { return map[string]any{} }
550 }
551 return func(ctx context.Context, q *driver.Query, run RunQueryFunc) (driver.DocumentIterator, error) {
552 if q.OrderByField == "" {
553 return nil, errors.New("InMemorySortFallback expects an OrderBy query")
554 }
555 // Run the query without the OrderBy.
556 orderByField := q.OrderByField
557 q.OrderByField = ""
558 iter, err := run(ctx, q)
559 if err != nil {
560 return nil, err
561 }
562 defer iter.Stop()
563 // Collect the results into a slice.
564 var docs []driver.Document
565 for {
566 doc, err := driver.NewDocument(createDocument())
567 if err != nil {
568 return nil, err
569 }
570 err = iter.Next(ctx, doc)
571 if err == io.EOF {
572 break
573 }
574 if err != nil {
575 return nil, err
576 }
577 docs = append(docs, doc)
578 }
579 // Sort the documents.
580 // OrderByField is a single field, not a field path.
581 // First, put the field values in another slice, so we can
582 // return on error.
583 sortValues := make([]any, len(docs))
584 for i, doc := range docs {
585 v, err := doc.GetField(orderByField)
586 if err != nil {
587 return nil, err
588 }
589 sortValues[i] = v
590 }
591 sort.Sort(docsForSorting{docs, sortValues, q.OrderAscending})
592 return &sliceIterator{docs: docs}, nil
593 }
594 }
595
596 type docsForSorting struct {
597 docs []driver.Document
598 vals []any
599 ascending bool
600 }
601
602 func (d docsForSorting) Len() int { return len(d.docs) }
603
604 func (d docsForSorting) Swap(i, j int) {
605 d.docs[i], d.docs[j] = d.docs[j], d.docs[i]
606 d.vals[i], d.vals[j] = d.vals[j], d.vals[i]
607 }
608
609 func (d docsForSorting) Less(i, j int) bool {
610 c := compare(d.vals[i], d.vals[j])
611 if d.ascending {
612 return c < 0
613 }
614 return c > 0
615 }
616
617 // compare returns -1 if v1 < v2, 0 if v1 == v2 and 1 if v1 > v2.
618 //
619 // Arbitrarily decide that strings < times < []byte < numbers.
620 // TODO(jba): find and use the actual sort order that DynamoDB uses.
621 func compare(v1, v2 any) int {
622 switch v1 := v1.(type) {
623 case string:
624 if v2, ok := v2.(string); ok {
625 return strings.Compare(v1, v2)
626 }
627 return -1
628
629 case time.Time:
630 if v2, ok := v2.(time.Time); ok {
631 return driver.CompareTimes(v1, v2)
632 }
633 if _, ok := v2.(string); ok {
634 return 1
635 }
636 return -1
637
638 case []byte:
639 if v2, ok := v2.([]byte); ok {
640 return bytes.Compare(v1, v2)
641 }
642 if _, ok := v2.(string); ok {
643 return 1
644 }
645 if _, ok := v2.(time.Time); ok {
646 return 1
647 }
648 return -1
649
650 default:
651 cmp, err := driver.CompareNumbers(v1, v2)
652 if err != nil {
653 return -1
654 }
655 return cmp
656 }
657 }
658
659 type sliceIterator struct {
660 docs []driver.Document
661 next int
662 }
663
664 func (it *sliceIterator) Next(ctx context.Context, doc driver.Document) error {
665 if it.next >= len(it.docs) {
666 return io.EOF
667 }
668 it.next++
669 return copyTopLevel(doc, it.docs[it.next-1])
670 }
671
672 // Copy the top-level fields of src into dest.
673 func copyTopLevel(dest, src driver.Document) error {
674 for _, f := range src.FieldNames() {
675 v, err := src.GetField(f)
676 if err != nil {
677 return err
678 }
679 if err := dest.SetField(f, v); err != nil {
680 return err
681 }
682 }
683 return nil
684 }
685
686 func (*sliceIterator) Stop() {}
687 func (*sliceIterator) As(any) bool { return false }