/
query.go
490 lines (460 loc) · 14.1 KB
/
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
// Copyright 2019 The Go Cloud Development Kit Authors
//
// 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
//
// https://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 dynamodocstore
import (
"context"
"fmt"
"io"
"strings"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/expression"
"github.com/eliben/gocdkx/internal/docstore"
"github.com/eliben/gocdkx/internal/docstore/driver"
)
// TODO: support parallel scans (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Scan.html#Scan.ParallelScan)
// TODO: support an empty item slice returned from an RPC: "A Query operation can
// return an empty result set and a LastEvaluatedKey if all the items read for the
// page of results are filtered out."
type avmap = map[string]*dynamodb.AttributeValue
func (c *collection) RunGetQuery(ctx context.Context, q *driver.Query) (driver.DocumentIterator, error) {
qr, err := c.planQuery(q)
if err != nil {
return nil, err
}
it := &documentIterator{
qr: qr,
limit: q.Limit,
count: 0, // manually count limit since dynamodb uses "limit" as scan limit before filtering
}
it.items, it.last, it.asFunc, err = it.qr.run(ctx, nil)
if err != nil {
return nil, err
}
return it, nil
}
func (c *collection) planQuery(q *driver.Query) (*queryRunner, error) {
var cb expression.Builder
cbUsed := false // It's an error to build an empty Builder.
// Set up the projection expression.
if len(q.FieldPaths) > 0 {
var pb expression.ProjectionBuilder
hasRevisionField := false
for _, fp := range q.FieldPaths {
if fpEqual(fp, docstore.RevisionField) {
hasRevisionField = true
}
pb = pb.AddNames(expression.Name(strings.Join(fp, ".")))
}
if !hasRevisionField {
pb = pb.AddNames(expression.Name(docstore.RevisionField))
q.FieldPaths = append(q.FieldPaths, []string{docstore.RevisionField})
}
cb = cb.WithProjection(pb)
cbUsed = true
}
// Find the best thing to query (table or index).
indexName, pkey, skey := c.bestQueryable(q)
if indexName == nil && pkey == "" {
// No query can be done: fall back to scanning.
if len(q.Filters) > 0 {
cb = cb.WithFilter(filtersToConditionBuilder(q.Filters))
cbUsed = true
}
in := &dynamodb.ScanInput{TableName: &c.table}
if cbUsed {
ce, err := cb.Build()
if err != nil {
return nil, err
}
in.ExpressionAttributeNames = ce.Names()
in.ExpressionAttributeValues = ce.Values()
in.FilterExpression = ce.Filter()
in.ProjectionExpression = ce.Projection()
}
return &queryRunner{c: c, scanIn: in, beforeRun: q.BeforeQuery}, nil
}
// Do a query.
cb = processFilters(cb, q.Filters, pkey, skey)
ce, err := cb.Build()
if err != nil {
return nil, err
}
return &queryRunner{
c: c,
queryIn: &dynamodb.QueryInput{
TableName: &c.table,
IndexName: indexName,
ExpressionAttributeNames: ce.Names(),
ExpressionAttributeValues: ce.Values(),
KeyConditionExpression: ce.KeyCondition(),
FilterExpression: ce.Filter(),
ProjectionExpression: ce.Projection(),
},
beforeRun: q.BeforeQuery,
}, nil
}
// Return the best choice of queryable (table or index) for this query.
// How to interpret the return values:
// - If indexName is nil but pkey is not empty, then use the table.
// - If all return values are zero, no query will work: do a scan.
func (c *collection) bestQueryable(q *driver.Query) (indexName *string, pkey, skey string) {
// If the query has an "=" filter on the table's partition key, look at the table
// and local indexes.
if hasEqualityFilter(q, c.partitionKey) {
// If the table has a sort key that's in the query, use the table.
if hasFilter(q, c.sortKey) {
return nil, c.partitionKey, c.sortKey
}
// Look at local indexes. They all have the same partition key as the base table.
// If one has a sort key in the query, use it.
for _, li := range c.description.LocalSecondaryIndexes {
pkey, skey := keyAttributes(li.KeySchema)
if hasFilter(q, skey) && localFieldsIncluded(q, li) {
return li.IndexName, pkey, skey
}
}
}
// Consider the global indexes: if one has a matching partition and sort key, and
// the projected fields of the index include those of the query, use it.
for _, gi := range c.description.GlobalSecondaryIndexes {
pkey, skey := keyAttributes(gi.KeySchema)
if skey == "" {
continue // We'll visit global indexes without a sort key later.
}
if hasEqualityFilter(q, pkey) && hasFilter(q, skey) && c.globalFieldsIncluded(q, gi) {
return gi.IndexName, pkey, skey
}
}
// There are no matches for both partition and sort key. Now consider matches on partition key only.
// That will still be better than a scan.
// First, check the table itself.
if hasEqualityFilter(q, c.partitionKey) {
return nil, c.partitionKey, c.sortKey
}
// No point checking local indexes: they have the same partition key as the table.
// Check the global indexes.
for _, gi := range c.description.GlobalSecondaryIndexes {
pkey, skey := keyAttributes(gi.KeySchema)
if hasEqualityFilter(q, pkey) && c.globalFieldsIncluded(q, gi) {
return gi.IndexName, pkey, skey
}
}
// We cannot do a query.
// TODO: return the reason why we couldn't. At a minimum, distinguish failure due to keys
// from failure due to projection (i.e. a global index had the right partition and sort key,
// but didn't project the necessary fields).
return nil, "", ""
}
// localFieldsIncluded reports whether a local index supports all the selected fields
// of a query. Since DynamoDB will read explicitly provided fields from the table if
// they are not projected into the index, the only case where a local index cannot
// be used is when the query wants all the fields, and the index projection is not ALL.
// See https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LSI.html#LSI.Projections.
func localFieldsIncluded(q *driver.Query, li *dynamodb.LocalSecondaryIndexDescription) bool {
return len(q.FieldPaths) > 0 || *li.Projection.ProjectionType == "ALL"
}
// globalFieldsIncluded reports whether the fields selected by the query are
// projected into (that is, contained directly in) the global index. We need this
// check before using the index, because if a global index doesn't have all the
// desired fields, then a separate RPC for each returned item would be necessary to
// retrieve those fields, and we'd rather scan than do that.
func (c *collection) globalFieldsIncluded(q *driver.Query, gi *dynamodb.GlobalSecondaryIndexDescription) bool {
proj := gi.Projection
if *proj.ProjectionType == "ALL" {
// The index has all the fields of the table: we're good.
return true
}
if len(q.FieldPaths) == 0 {
// The query wants all the fields of the table, but we can't be sure that the
// index has them.
return false
}
// The table's keys and the index's keys are always in the index.
pkey, skey := keyAttributes(gi.KeySchema)
indexFields := map[string]bool{c.partitionKey: true, pkey: true}
if c.sortKey != "" {
indexFields[c.sortKey] = true
}
if skey != "" {
indexFields[skey] = true
}
for _, nka := range proj.NonKeyAttributes {
indexFields[*nka] = true
}
// Every field path in the query must be in the index.
for _, fp := range q.FieldPaths {
if !indexFields[strings.Join(fp, ".")] {
return false
}
}
return true
}
// Extract the names of the partition and sort key attributes from the schema of a
// table or index.
func keyAttributes(ks []*dynamodb.KeySchemaElement) (pkey, skey string) {
for _, k := range ks {
switch *k.KeyType {
case "HASH":
pkey = *k.AttributeName
case "RANGE":
skey = *k.AttributeName
default:
panic("bad key type: " + *k.KeyType)
}
}
return pkey, skey
}
// Reports whether q has a filter that mentions the top-level field.
func hasFilter(q *driver.Query, field string) bool {
if field == "" {
return false
}
for _, f := range q.Filters {
if fpEqual(f.FieldPath, field) {
return true
}
}
return false
}
// Reports whether q has a filter that checks if the top-level field is equal to something.
func hasEqualityFilter(q *driver.Query, field string) bool {
for _, f := range q.Filters {
if f.Op == driver.EqualOp && fpEqual(f.FieldPath, field) {
return true
}
}
return false
}
func fpEqual(fp []string, s string) bool {
return len(fp) == 1 && fp[0] == s
}
type queryRunner struct {
c *collection
scanIn *dynamodb.ScanInput
queryIn *dynamodb.QueryInput
beforeRun func(asFunc func(i interface{}) bool) error
}
func (qr *queryRunner) run(ctx context.Context, startAfter avmap) (items []avmap, last avmap, asFunc func(i interface{}) bool, err error) {
if qr.scanIn != nil {
qr.scanIn.ExclusiveStartKey = startAfter
if qr.beforeRun != nil {
asFunc := func(i interface{}) bool {
p, ok := i.(**dynamodb.ScanInput)
if !ok {
return false
}
*p = qr.scanIn
return true
}
if err := qr.beforeRun(asFunc); err != nil {
return nil, nil, nil, err
}
}
out, err := qr.c.db.ScanWithContext(ctx, qr.scanIn)
if err != nil {
return nil, nil, nil, err
}
return out.Items, out.LastEvaluatedKey,
func(i interface{}) bool {
p, ok := i.(**dynamodb.ScanOutput)
if !ok {
return false
}
*p = out
return true
}, nil
}
qr.queryIn.ExclusiveStartKey = startAfter
if qr.beforeRun != nil {
asFunc := func(i interface{}) bool {
p, ok := i.(**dynamodb.QueryInput)
if !ok {
return false
}
*p = qr.queryIn
return true
}
if err := qr.beforeRun(asFunc); err != nil {
return nil, nil, nil, err
}
}
out, err := qr.c.db.QueryWithContext(ctx, qr.queryIn)
if err != nil {
return nil, nil, nil, err
}
return out.Items, out.LastEvaluatedKey,
func(i interface{}) bool {
p, ok := i.(**dynamodb.QueryOutput)
if !ok {
return false
}
*p = out
return true
}, nil
}
func processFilters(cb expression.Builder, fs []driver.Filter, pkey, skey string) expression.Builder {
var kbs []expression.KeyConditionBuilder
var cfs []driver.Filter
for _, f := range fs {
if kb, ok := toKeyCondition(f, pkey, skey); ok {
kbs = append(kbs, kb)
continue
}
cfs = append(cfs, f)
}
keyBuilder := kbs[0]
for i := 1; i < len(kbs); i++ {
keyBuilder = keyBuilder.And(kbs[i])
}
cb = cb.WithKeyCondition(keyBuilder)
if len(cfs) > 0 {
cb = cb.WithFilter(filtersToConditionBuilder(cfs))
}
return cb
}
func filtersToConditionBuilder(fs []driver.Filter) expression.ConditionBuilder {
if len(fs) == 0 {
panic("no filters")
}
var cb expression.ConditionBuilder
cb = toFilter(fs[0])
for _, f := range fs[1:] {
cb = cb.And(toFilter(f))
}
return cb
}
func toKeyCondition(f driver.Filter, pkey, skey string) (expression.KeyConditionBuilder, bool) {
kp := strings.Join(f.FieldPath, ".")
if kp == pkey || kp == skey {
key := expression.Key(kp)
val := expression.Value(f.Value)
switch f.Op {
case "<":
return expression.KeyLessThan(key, val), true
case "<=":
return expression.KeyLessThanEqual(key, val), true
case driver.EqualOp:
return expression.KeyEqual(key, val), true
case ">=":
return expression.KeyGreaterThanEqual(key, val), true
case ">":
return expression.KeyGreaterThan(key, val), true
default:
panic(fmt.Sprint("invalid filter operation:", f.Op))
}
}
return expression.KeyConditionBuilder{}, false
}
func toFilter(f driver.Filter) expression.ConditionBuilder {
name := expression.Name(strings.Join(f.FieldPath, "."))
val := expression.Value(f.Value)
switch f.Op {
case "<":
return expression.LessThan(name, val)
case "<=":
return expression.LessThanEqual(name, val)
case driver.EqualOp:
return expression.Equal(name, val)
case ">=":
return expression.GreaterThanEqual(name, val)
case ">":
return expression.GreaterThan(name, val)
default:
panic(fmt.Sprint("invalid filter operation:", f.Op))
}
}
type documentIterator struct {
qr *queryRunner
items []map[string]*dynamodb.AttributeValue
curr int
limit int
count int // number of items returned
last map[string]*dynamodb.AttributeValue
asFunc func(i interface{}) bool
}
func (it *documentIterator) Next(ctx context.Context, doc driver.Document) error {
if it.limit > 0 && it.count >= it.limit || it.curr >= len(it.items) && it.last == nil {
return io.EOF
}
if it.curr >= len(it.items) {
// Make a new query request at the end of this page.
var err error
it.items, it.last, it.asFunc, err = it.qr.run(ctx, it.last)
if err != nil {
return err
}
it.curr = 0
}
if err := decodeDoc(&dynamodb.AttributeValue{M: it.items[it.curr]}, doc); err != nil {
return err
}
it.curr++
it.count++
return nil
}
func (it *documentIterator) Stop() {
it.items = nil
it.last = nil
}
func (it *documentIterator) As(i interface{}) bool {
return it.asFunc(i)
}
func (c *collection) QueryPlan(q *driver.Query) (string, error) {
qr, err := c.planQuery(q)
if err != nil {
return "", err
}
return qr.queryPlan(), nil
}
func (qr *queryRunner) queryPlan() string {
if qr.scanIn != nil {
return "Scan"
}
if qr.queryIn.IndexName != nil {
return fmt.Sprintf("Index: %q", *qr.queryIn.IndexName)
}
return "Table"
}
// TODO(shantuo): use BatchWrite.
func (c *collection) RunDeleteQuery(ctx context.Context, q *driver.Query) error {
q.FieldPaths = [][]string{{c.partitionKey}}
if c.sortKey != "" {
q.FieldPaths = append(q.FieldPaths, []string{c.sortKey})
}
iter, err := c.RunGetQuery(ctx, q)
if err != nil {
return err
}
defer iter.Stop()
var actions []*driver.Action
for {
doc, err := driver.NewDocument(map[string]interface{}{})
if err != nil {
return err
}
err = iter.Next(ctx, doc)
if err == io.EOF {
break
}
if err != nil {
return err
}
actions = append(actions, &driver.Action{Kind: driver.Delete, Doc: doc})
}
alerr := c.RunActions(ctx, actions, &driver.RunActionsOptions{})
if len(alerr) == 0 {
return nil
}
return docstore.ActionListError(alerr)
}