forked from aws-samples/aws-dynamodb-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathputItemConditional.go
89 lines (74 loc) · 1.92 KB
/
putItemConditional.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
package main
import (
"fmt"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
)
// Create structs to hold info about new item
type Address struct {
City string`json:"city"`
Country string`json:"country"`
Pcode string`json:"pcode"`
Road string`json:"road"`
State string`json:"state"`
}
type Item struct {
Pk string`json:"pk"`
Sk string`json:"sk"`
Name string`json:"name"`
FirstName string`json:"firstName"`
LastName string`json:"lastName"`
Username string`json:"username"`
Address Address`json:"address"`
Age int`json:"age"`
}
func main() {
// Create Session
sess, err := session.NewSession(&aws.Config{
Region: aws.String("eu-west-1")},
)
// Create DynamoDB client
svc := dynamodb.New(sess)
// Address info
address := Address{
City: "Greenbank",
Country: "USA",
Pcode: "98253",
Road: "89105 Bakken Rd",
State: "WA",
}
// Item info
item := Item{
Pk: "[email protected]",
Sk: "metadata",
FirstName: "Jose",
LastName: "Schneller",
Name: "Jose Schneller",
Username: "joses",
Age: 27,
Address: address,
}
// Marshall
av, err := dynamodbattribute.MarshalMap(item)
if err != nil {
fmt.Println("Got error marshalling map:")
fmt.Println(err.Error())
os.Exit(1)
}
// Create item in table only if it doesn't already exist
input := &dynamodb.PutItemInput{
Item: av,
TableName: aws.String("RetailDatabase"),
ConditionExpression: aws.String("attribute_not_exists (pk) AND attribute_not_exists (sk)"),
}
_, err = svc.PutItem(input)
if err != nil {
fmt.Println("Got error calling PutItem:")
fmt.Println(err.Error())
os.Exit(1)
}
fmt.Println("Successfully added item to table")
}