forked from aws/aws-sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 3
/
expression.go
635 lines (583 loc) · 22.8 KB
/
expression.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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
package expression
import (
"fmt"
"sort"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/dynamodb"
)
// expressionType specifies the type of Expression. Declaring this type is used
// to eliminate magic strings
type expressionType string
const (
projection expressionType = "projection"
keyCondition = "keyCondition"
condition = "condition"
filter = "filter"
update = "update"
)
// Implement the Sort interface
type typeList []expressionType
func (l typeList) Len() int {
return len(l)
}
func (l typeList) Less(i, j int) bool {
return string(l[i]) < string(l[j])
}
func (l typeList) Swap(i, j int) {
l[i], l[j] = l[j], l[i]
}
// Builder represents the struct that builds the Expression struct. Methods such
// as WithProjection() and WithCondition() can add different kinds of DynamoDB
// Expressions to the Builder. The method Build() creates an Expression struct
// with the specified types of DynamoDB Expressions.
//
// Example:
//
// keyCond := expression.Key("someKey").Equal(expression.Value("someValue"))
// proj := expression.NamesList(expression.Name("aName"), expression.Name("anotherName"), expression.Name("oneOtherName"))
//
// builder := expression.NewBuilder().WithKeyCondition(keyCond).WithProjection(proj)
// expression := builder.Build()
//
// queryInput := dynamodb.QueryInput{
// KeyConditionExpression: expression.KeyCondition(),
// ProjectionExpression: expression.Projection(),
// ExpressionAttributeNames: expression.Names(),
// ExpressionAttributeValues: expression.Values(),
// TableName: aws.String("SomeTable"),
// }
type Builder struct {
expressionMap map[expressionType]treeBuilder
}
// NewBuilder returns an empty Builder struct. Methods such as WithProjection()
// and WithCondition() can add different kinds of DynamoDB Expressions to the
// Builder. The method Build() creates an Expression struct with the specified
// types of DynamoDB Expressions.
//
// Example:
//
// keyCond := expression.Key("someKey").Equal(expression.Value("someValue"))
// proj := expression.NamesList(expression.Name("aName"), expression.Name("anotherName"), expression.Name("oneOtherName"))
// builder := expression.NewBuilder().WithKeyCondition(keyCond).WithProjection(proj)
func NewBuilder() Builder {
return Builder{}
}
// Build builds an Expression struct representing multiple types of DynamoDB
// Expressions. Getter methods on the resulting Expression struct returns the
// DynamoDB Expression strings as well as the maps that correspond to
// ExpressionAttributeNames and ExpressionAttributeValues. Calling Build() on an
// empty Builder returns the typed error EmptyParameterError.
//
// Example:
//
// // keyCond represents the Key Condition Expression
// keyCond := expression.Key("someKey").Equal(expression.Value("someValue"))
// // proj represents the Projection Expression
// proj := expression.NamesList(expression.Name("aName"), expression.Name("anotherName"), expression.Name("oneOtherName"))
//
// // Add keyCond and proj to builder as a Key Condition and Projection
// // respectively
// builder := expression.NewBuilder().WithKeyCondition(keyCond).WithProjection(proj)
// expression := builder.Build()
//
// queryInput := dynamodb.QueryInput{
// KeyConditionExpression: expression.KeyCondition(),
// ProjectionExpression: expression.Projection(),
// ExpressionAttributeNames: expression.Names(),
// ExpressionAttributeValues: expression.Values(),
// TableName: aws.String("SomeTable"),
// }
func (b Builder) Build() (Expression, error) {
if b.expressionMap == nil {
return Expression{}, newUnsetParameterError("Build", "Builder")
}
aliasList, expressionMap, err := b.buildChildTrees()
if err != nil {
return Expression{}, err
}
expression := Expression{
expressionMap: expressionMap,
}
if len(aliasList.namesList) != 0 {
namesMap := map[string]*string{}
for ind, val := range aliasList.namesList {
namesMap[fmt.Sprintf("#%v", ind)] = aws.String(val)
}
expression.namesMap = namesMap
}
if len(aliasList.valuesList) != 0 {
valuesMap := map[string]*dynamodb.AttributeValue{}
for i := 0; i < len(aliasList.valuesList); i++ {
valuesMap[fmt.Sprintf(":%v", i)] = &aliasList.valuesList[i]
}
expression.valuesMap = valuesMap
}
return expression, nil
}
// buildChildTrees compiles the list of treeBuilders that are the children of
// the argument Builder. The returned aliasList represents all the alias tokens
// used in the expression strings. The returned map[string]string maps the type
// of expression (i.e. "condition", "update") to the appropriate expression
// string.
func (b Builder) buildChildTrees() (aliasList, map[expressionType]string, error) {
aList := aliasList{}
formattedExpressions := map[expressionType]string{}
keys := typeList{}
for expressionType := range b.expressionMap {
keys = append(keys, expressionType)
}
sort.Sort(keys)
for _, key := range keys {
node, err := b.expressionMap[key].buildTree()
if err != nil {
return aliasList{}, nil, err
}
formattedExpression, err := node.buildExpressionString(&aList)
if err != nil {
return aliasList{}, nil, err
}
formattedExpressions[key] = formattedExpression
}
return aList, formattedExpressions, nil
}
// WithCondition method adds the argument ConditionBuilder as a Condition
// Expression to the argument Builder. If the argument Builder already has a
// ConditionBuilder representing a Condition Expression, WithCondition()
// overwrites the existing ConditionBuilder.
//
// Example:
//
// // let builder be an existing Builder{} and cond be an existing
// // ConditionBuilder{}
// builder = builder.WithCondition(cond)
//
// // add other DynamoDB Expressions to the builder. let proj be an already
// // existing ProjectionBuilder
// builder = builder.WithProjection(proj)
// // create an Expression struct
// expression := builder.Build()
func (b Builder) WithCondition(conditionBuilder ConditionBuilder) Builder {
if b.expressionMap == nil {
b.expressionMap = map[expressionType]treeBuilder{}
}
b.expressionMap[condition] = conditionBuilder
return b
}
// WithProjection method adds the argument ProjectionBuilder as a Projection
// Expression to the argument Builder. If the argument Builder already has a
// ProjectionBuilder representing a Projection Expression, WithProjection()
// overwrites the existing ProjectionBuilder.
//
// Example:
//
// // let builder be an existing Builder{} and proj be an existing
// // ProjectionBuilder{}
// builder = builder.WithProjection(proj)
//
// // add other DynamoDB Expressions to the builder. let cond be an already
// // existing ConditionBuilder
// builder = builder.WithCondition(cond)
// // create an Expression struct
// expression := builder.Build()
func (b Builder) WithProjection(projectionBuilder ProjectionBuilder) Builder {
if b.expressionMap == nil {
b.expressionMap = map[expressionType]treeBuilder{}
}
b.expressionMap[projection] = projectionBuilder
return b
}
// WithKeyCondition method adds the argument KeyConditionBuilder as a Key
// Condition Expression to the argument Builder. If the argument Builder already
// has a KeyConditionBuilder representing a Key Condition Expression,
// WithKeyCondition() overwrites the existing KeyConditionBuilder.
//
// Example:
//
// // let builder be an existing Builder{} and keyCond be an existing
// // KeyConditionBuilder{}
// builder = builder.WithKeyCondition(keyCond)
//
// // add other DynamoDB Expressions to the builder. let cond be an already
// // existing ConditionBuilder
// builder = builder.WithCondition(cond)
// // create an Expression struct
// expression := builder.Build()
func (b Builder) WithKeyCondition(keyConditionBuilder KeyConditionBuilder) Builder {
if b.expressionMap == nil {
b.expressionMap = map[expressionType]treeBuilder{}
}
b.expressionMap[keyCondition] = keyConditionBuilder
return b
}
// WithFilter method adds the argument ConditionBuilder as a Filter Expression
// to the argument Builder. If the argument Builder already has a
// ConditionBuilder representing a Filter Expression, WithFilter()
// overwrites the existing ConditionBuilder.
//
// Example:
//
// // let builder be an existing Builder{} and filt be an existing
// // ConditionBuilder{}
// builder = builder.WithFilter(filt)
//
// // add other DynamoDB Expressions to the builder. let cond be an already
// // existing ConditionBuilder
// builder = builder.WithCondition(cond)
// // create an Expression struct
// expression := builder.Build()
func (b Builder) WithFilter(filterBuilder ConditionBuilder) Builder {
if b.expressionMap == nil {
b.expressionMap = map[expressionType]treeBuilder{}
}
b.expressionMap[filter] = filterBuilder
return b
}
// WithUpdate method adds the argument UpdateBuilder as an Update Expression
// to the argument Builder. If the argument Builder already has a UpdateBuilder
// representing a Update Expression, WithUpdate() overwrites the existing
// UpdateBuilder.
//
// Example:
//
// // let builder be an existing Builder{} and update be an existing
// // UpdateBuilder{}
// builder = builder.WithUpdate(update)
//
// // add other DynamoDB Expressions to the builder. let cond be an already
// // existing ConditionBuilder
// builder = builder.WithCondition(cond)
// // create an Expression struct
// expression := builder.Build()
func (b Builder) WithUpdate(updateBuilder UpdateBuilder) Builder {
if b.expressionMap == nil {
b.expressionMap = map[expressionType]treeBuilder{}
}
b.expressionMap[update] = updateBuilder
return b
}
// Expression represents a collection of DynamoDB Expressions. The getter
// methods of the Expression struct retrieves the formatted DynamoDB
// Expressions, ExpressionAttributeNames, and ExpressionAttributeValues.
//
// Example:
//
// // keyCond represents the Key Condition Expression
// keyCond := expression.Key("someKey").Equal(expression.Value("someValue"))
// // proj represents the Projection Expression
// proj := expression.NamesList(expression.Name("aName"), expression.Name("anotherName"), expression.Name("oneOtherName"))
//
// // Add keyCond and proj to builder as a Key Condition and Projection
// // respectively
// builder := expression.NewBuilder().WithKeyCondition(keyCond).WithProjection(proj)
// expression := builder.Build()
//
// queryInput := dynamodb.QueryInput{
// KeyConditionExpression: expression.KeyCondition(),
// ProjectionExpression: expression.Projection(),
// ExpressionAttributeNames: expression.Names(),
// ExpressionAttributeValues: expression.Values(),
// TableName: aws.String("SomeTable"),
// }
type Expression struct {
expressionMap map[expressionType]string
namesMap map[string]*string
valuesMap map[string]*dynamodb.AttributeValue
}
// treeBuilder interface is fulfilled by builder structs that represent
// different types of Expressions.
type treeBuilder interface {
// buildTree creates the tree structure of exprNodes. The tree structure
// of exprNodes are traversed in order to build the string representing
// different types of Expressions as well as the maps that represent
// ExpressionAttributeNames and ExpressionAttributeValues.
buildTree() (exprNode, error)
}
// Condition returns the *string corresponding to the Condition Expression
// of the argument Expression. This method is used to satisfy the members of
// DynamoDB input structs. If the Expression does not have a condition
// expression this method returns nil.
//
// Example:
//
// // let expression be an instance of Expression{}
//
// deleteInput := dynamodb.DeleteItemInput{
// ConditionExpression: expression.Condition(),
// ExpressionAttributeNames: expression.Names(),
// ExpressionAttributeValues: expression.Values(),
// Key: map[string]*dynamodb.AttributeValue{
// "PartitionKey": &dynamodb.AttributeValue{
// S: aws.String("SomeKey"),
// },
// },
// TableName: aws.String("SomeTable"),
// }
func (e Expression) Condition() *string {
return e.returnExpression(condition)
}
// Filter returns the *string corresponding to the Filter Expression of the
// argument Expression. This method is used to satisfy the members of DynamoDB
// input structs. If the Expression does not have a filter expression this
// method returns nil.
//
// Example:
//
// // let expression be an instance of Expression{}
//
// queryInput := dynamodb.QueryInput{
// KeyConditionExpression: expression.KeyCondition(),
// FilterExpression: expression.Filter(),
// ExpressionAttributeNames: expression.Names(),
// ExpressionAttributeValues: expression.Values(),
// TableName: aws.String("SomeTable"),
// }
func (e Expression) Filter() *string {
return e.returnExpression(filter)
}
// Projection returns the *string corresponding to the Projection Expression
// of the argument Expression. This method is used to satisfy the members of
// DynamoDB input structs. If the Expression does not have a projection
// expression this method returns nil.
//
// Example:
//
// // let expression be an instance of Expression{}
//
// queryInput := dynamodb.QueryInput{
// KeyConditionExpression: expression.KeyCondition(),
// ProjectionExpression: expression.Projection(),
// ExpressionAttributeNames: expression.Names(),
// ExpressionAttributeValues: expression.Values(),
// TableName: aws.String("SomeTable"),
// }
func (e Expression) Projection() *string {
return e.returnExpression(projection)
}
// KeyCondition returns the *string corresponding to the Key Condition
// Expression of the argument Expression. This method is used to satisfy the
// members of DynamoDB input structs. If the argument Expression does not have a
// KeyConditionExpression, KeyCondition() returns nil.
//
// Example:
//
// // let expression be an instance of Expression{}
//
// queryInput := dynamodb.QueryInput{
// KeyConditionExpression: expression.KeyCondition(),
// ProjectionExpression: expression.Projection(),
// ExpressionAttributeNames: expression.Names(),
// ExpressionAttributeValues: expression.Values(),
// TableName: aws.String("SomeTable"),
// }
func (e Expression) KeyCondition() *string {
return e.returnExpression(keyCondition)
}
// Update returns the *string corresponding to the Update Expression of the
// argument Expression. This method is used to satisfy the members of DynamoDB
// input structs. If the argument Expression does not have a UpdateExpression,
// Update() returns nil.
//
// Example:
//
// // let expression be an instance of Expression{}
//
// updateInput := dynamodb.UpdateInput{
// Key: map[string]*dynamodb.AttributeValue{
// "PartitionKey": {
// S: aws.String("someKey"),
// },
// },
// UpdateExpression: expression.Update(),
// ExpressionAttributeNames: expression.Names(),
// ExpressionAttributeValues: expression.Values(),
// TableName: aws.String("SomeTable"),
// }
func (e Expression) Update() *string {
return e.returnExpression(update)
}
// Names returns the map[string]*string corresponding to the
// ExpressionAttributeNames of the argument Expression. This method is used to
// satisfy the members of DynamoDB input structs. If Expression does not use
// ExpressionAttributeNames, this method returns nil. The
// ExpressionAttributeNames and ExpressionAttributeValues member of the input
// struct must always be assigned when using the Expression struct since all
// item attribute names and values are aliased. That means that if the
// ExpressionAttributeNames and ExpressionAttributeValues member is not assigned
// with the corresponding Names() and Values() methods, the DynamoDB operation
// will run into a logic error.
//
// Example:
//
// // let expression be an instance of Expression{}
//
// queryInput := dynamodb.QueryInput{
// KeyConditionExpression: expression.KeyCondition(),
// ProjectionExpression: expression.Projection(),
// ExpressionAttributeNames: expression.Names(),
// ExpressionAttributeValues: expression.Values(),
// TableName: aws.String("SomeTable"),
// }
func (e Expression) Names() map[string]*string {
return e.namesMap
}
// Values returns the map[string]*dynamodb.AttributeValue corresponding to
// the ExpressionAttributeValues of the argument Expression. This method is used
// to satisfy the members of DynamoDB input structs. If Expression does not use
// ExpressionAttributeValues, this method returns nil. The
// ExpressionAttributeNames and ExpressionAttributeValues member of the input
// struct must always be assigned when using the Expression struct since all
// item attribute names and values are aliased. That means that if the
// ExpressionAttributeNames and ExpressionAttributeValues member is not assigned
// with the corresponding Names() and Values() methods, the DynamoDB operation
// will run into a logic error.
//
// Example:
//
// // let expression be an instance of Expression{}
//
// queryInput := dynamodb.QueryInput{
// KeyConditionExpression: expression.KeyCondition(),
// ProjectionExpression: expression.Projection(),
// ExpressionAttributeNames: expression.Names(),
// ExpressionAttributeValues: expression.Values(),
// TableName: aws.String("SomeTable"),
// }
func (e Expression) Values() map[string]*dynamodb.AttributeValue {
return e.valuesMap
}
// returnExpression returns *string corresponding to the type of Expression
// string specified by the expressionType. If there is no corresponding
// expression available in Expression, the method returns nil
func (e Expression) returnExpression(expressionType expressionType) *string {
if e.expressionMap == nil {
return nil
}
return aws.String(e.expressionMap[expressionType])
}
// exprNode are the generic nodes that represents both Operands and
// Conditions. The purpose of exprNode is to be able to call an generic
// recursive function on the top level exprNode to be able to determine a root
// node in order to deduplicate name aliases.
// fmtExpr is a string that has escaped characters to refer to
// names/values/children which needs to be aliased at runtime in order to avoid
// duplicate values. The rules are as follows:
// $n: Indicates that an alias of a name needs to be inserted. The
// corresponding name to be alias is in the []names slice.
// $v: Indicates that an alias of a value needs to be inserted. The
// corresponding value to be alias is in the []values slice.
// $c: Indicates that the fmtExpr of a child exprNode needs to be inserted.
// The corresponding child node is in the []children slice.
type exprNode struct {
names []string
values []dynamodb.AttributeValue
children []exprNode
fmtExpr string
}
// aliasList keeps track of all the names we need to alias in the nested
// struct of conditions and operands. This allows each alias to be unique.
// aliasList is passed in as a pointer when buildChildTrees is called in
// order to deduplicate all names within the tree strcuture of the exprNodes.
type aliasList struct {
namesList []string
valuesList []dynamodb.AttributeValue
}
// buildExpressionString returns a string with aliasing for names/values
// specified by aliasList. The string corresponds to the expression that the
// exprNode tree represents.
func (en exprNode) buildExpressionString(aliasList *aliasList) (string, error) {
// Since each exprNode contains a slice of names, values, and children that
// correspond to the escaped characters, we an index to traverse the slices
index := struct {
name, value, children int
}{}
formattedExpression := en.fmtExpr
for i := 0; i < len(formattedExpression); {
if formattedExpression[i] != '$' {
i++
continue
}
if i == len(formattedExpression)-1 {
return "", fmt.Errorf("buildexprNode error: invalid escape character")
}
var alias string
var err error
// if an escaped character is found, substitute it with the proper alias
// TODO consider AST instead of string in the future
switch formattedExpression[i+1] {
case 'n':
alias, err = substitutePath(index.name, en, aliasList)
if err != nil {
return "", err
}
index.name++
case 'v':
alias, err = substituteValue(index.value, en, aliasList)
if err != nil {
return "", err
}
index.value++
case 'c':
alias, err = substituteChild(index.children, en, aliasList)
if err != nil {
return "", err
}
index.children++
default:
return "", fmt.Errorf("buildexprNode error: invalid escape rune %#v", formattedExpression[i+1])
}
formattedExpression = formattedExpression[:i] + alias + formattedExpression[i+2:]
i += len(alias)
}
return formattedExpression, nil
}
// substitutePath substitutes the escaped character $n with the appropriate
// alias.
func substitutePath(index int, node exprNode, aliasList *aliasList) (string, error) {
if index >= len(node.names) {
return "", fmt.Errorf("substitutePath error: exprNode []names out of range")
}
str, err := aliasList.aliasPath(node.names[index])
if err != nil {
return "", err
}
return str, nil
}
// substituteValue substitutes the escaped character $v with the appropriate
// alias.
func substituteValue(index int, node exprNode, aliasList *aliasList) (string, error) {
if index >= len(node.values) {
return "", fmt.Errorf("substituteValue error: exprNode []values out of range")
}
str, err := aliasList.aliasValue(node.values[index])
if err != nil {
return "", err
}
return str, nil
}
// substituteChild substitutes the escaped character $c with the appropriate
// alias.
func substituteChild(index int, node exprNode, aliasList *aliasList) (string, error) {
if index >= len(node.children) {
return "", fmt.Errorf("substituteChild error: exprNode []children out of range")
}
return node.children[index].buildExpressionString(aliasList)
}
// aliasValue returns the corresponding alias to the dav value argument. Since
// values are not deduplicated as of now, all values are just appended to the
// aliasList and given the index as the alias.
func (al *aliasList) aliasValue(dav dynamodb.AttributeValue) (string, error) {
al.valuesList = append(al.valuesList, dav)
return fmt.Sprintf(":%d", len(al.valuesList)-1), nil
}
// aliasPath returns the corresponding alias to the argument string. The
// argument is checked against all existing aliasList names in order to avoid
// duplicate strings getting two different aliases.
func (al *aliasList) aliasPath(nm string) (string, error) {
for ind, name := range al.namesList {
if nm == name {
return fmt.Sprintf("#%d", ind), nil
}
}
al.namesList = append(al.namesList, nm)
return fmt.Sprintf("#%d", len(al.namesList)-1), nil
}