You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

95 lines
2.4 KiB

  1. package dynamodb
  2. import simplejson "github.com/bitly/go-simplejson"
  3. /*
  4. Construct an update item query.
  5. The query can be composed via chaining and then executed via Execute()
  6. Usage:
  7. update := table.UpdateItem(key)
  8. .ReturnValues(dynamodb.UPDATED_NEW)
  9. .UpdateExpression("SET Counter = Counter + :incr")
  10. .UpdateCondition("Counter < :checkVal")
  11. .ExpressionAttributes(NewNumberAttribute(":incr", "1"), NewNumberAttribute(":checkVal", 42))
  12. result, err := update.Execute()
  13. if err == nil {
  14. log.Printf("Counter is now %v", result.Attributes["Counter"].Value)
  15. }
  16. */
  17. func (t *Table) UpdateItem(key *Key) *UpdateItem {
  18. q := NewQuery(t)
  19. q.AddKey(t, key)
  20. return &UpdateItem{table: t, query: q}
  21. }
  22. type UpdateItem struct {
  23. table *Table
  24. query *Query
  25. hasReturnValues bool
  26. }
  27. // Specify how return values are to be provided.
  28. func (u *UpdateItem) ReturnValues(returnValues ReturnValues) *UpdateItem {
  29. u.hasReturnValues = (returnValues != NONE)
  30. u.query.AddReturnValues(returnValues)
  31. return u
  32. }
  33. /*
  34. Specify an update expression and optional attribute settings at the same time.
  35. update.UpdateExpression("SET Foo = Foo + :incr", dynamodb.NewNumberAttribute(":incr", "7"))
  36. is equivalent to
  37. update.UpdateExpression("SET Foo = Foo + :incr")
  38. .ExpressionAttributes(NewNumberAttribute(":incr", "7"))
  39. */
  40. func (u *UpdateItem) UpdateExpression(expression string, attributes ...Attribute) *UpdateItem {
  41. u.query.AddUpdateExpression(expression)
  42. u.ExpressionAttributes(attributes...)
  43. return u
  44. }
  45. // Specify attribute substitutions to be used in expressions.
  46. func (u *UpdateItem) ExpressionAttributes(attributes ...Attribute) *UpdateItem {
  47. u.query.AddExpressionAttributes(attributes)
  48. return u
  49. }
  50. // Specify a check condition for conditional updates.
  51. func (u *UpdateItem) ConditionExpression(expression string) *UpdateItem {
  52. u.query.AddConditionExpression(expression)
  53. return u
  54. }
  55. // Execute this query.
  56. func (u *UpdateItem) Execute() (*UpdateResult, error) {
  57. jsonResponse, err := u.table.Server.queryServer(target("UpdateItem"), u.query)
  58. if err != nil {
  59. return nil, err
  60. }
  61. if u.hasReturnValues {
  62. resp, err := simplejson.NewJson(jsonResponse)
  63. if err != nil {
  64. return nil, err
  65. }
  66. attrib, err := resp.Get("Attributes").Map()
  67. if err != nil {
  68. return nil, err
  69. }
  70. return &UpdateResult{parseAttributes(attrib)}, nil
  71. }
  72. return nil, nil
  73. }
  74. type UpdateResult struct {
  75. Attributes map[string]*Attribute
  76. }