带有conditionexpression的dynamodb updateitem返回项是否已更新

时间:2016-03-25 21:13:45

标签: amazon-web-services go amazon-dynamodb

我想在某些条件下更新项目,然后我想知道在UpdateItem返回时该项是否已更新。

文档似乎与我相矛盾。

在此页面上:http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UpdateItem.html在“条件更新”示例中,它说“在更新后出现的所有项目属性都会在响应中返回。”

在此页面上:https://godoc.org/github.com/aws/aws-sdk-go/service/dynamodb#UpdateItemOutput它表示属性是“在UpdateItem操作之前出现的属性值的映射”

我真的不想要其中任何一个。我想要的是一个bool,说明是否有更新。

这是我的大脑现在的位置:

out, err := db.DynamoDB.UpdateItem(&dynamodb.UpdateItemInput{
    TableName: tableName,
    Key: map[string]*dynamodb.AttributeValue{
        "KeyName": {S: aws.String(keyname)},
    },
    ExpressionAttributeNames: map[string]*string{
        "#lock": aws.String("Lock"),
    },
    ExpressionAttributeValues: map[string]*string{
        ":now":     aws.String(compfmt(time.Now())),
        ":promise": aws.String(compfmt(time.Now().Add(30 * time.Second))),
    },
    ConditionExpression: aws.String("attribute_not_exist(#lock) OR :now > #lock"),
    UpdateExpression:    aws.String("SET #lock = :promise"),
})

3 个答案:

答案 0 :(得分:1)

One way to do this is to check the Code on the awserr

import "github.com/aws/aws-sdk-go/aws/awserr"
func Lock()(bool, error) {
    //Create value v
    _, err := db.DynamoDB.UpdateItem(v)
    if err != nil {
         if ae, ok := err.(awserr.RequestFailure); ok && ae.Code() == "ConditionalCheckFailedException" {
             return false, nil
         }
        return false, err
    }
    return true, nil
}

答案 1 :(得分:0)

原来我想要做的是检查错误,看它是否包含字符串ConditionalCheckFailedException

func Lock() (bool, error) {
  ...
  _, err := db.DynamoDB.UpdateItem(v)
  if err != nil {
    if strings.Contains(err.Error(), "ConditionalCheckFailedException") {
      return false, nil
    }
    return false, err
  }
  return true, nil
}

答案 2 :(得分:0)

现在有常量可以比较错误,而不是像其他答案中那样使用硬编码的字符串:

result, err := svc.UpdateItem(input)
if err != nil {
    if aerr, ok := err.(awserr.Error); ok {
        switch aerr.Code() {
        case dynamodb.ErrCodeConditionalCheckFailedException:
            fmt.Println(dynamodb.ErrCodeConditionalCheckFailedException, aerr.Error())
        default:
            fmt.Println(aerr.Error())
        }
    }
}