forked from Vanssh-k/go-ds-dynamodb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkey.go
65 lines (50 loc) · 1.74 KB
/
key.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
package ddbds
import (
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/dynamodb"
ds "github.com/ipfs/go-datastore"
)
func namespaces(k ds.Key) []string {
namespaces := k.Namespaces()
// for the root key "/", we want an empty/nil slice, not [""]
if len(namespaces) == 1 && namespaces[0] == "" {
namespaces = nil
}
return namespaces
}
func (d *DDBDatastore) queryKey(queryPrefix ds.Key) (map[string]*dynamodb.AttributeValue, bool) {
queryPrefixNamespaces := namespaces(queryPrefix)
if len(queryPrefixNamespaces) == 0 {
return nil, false
}
return map[string]*dynamodb.AttributeValue{
d.partitionKey: {S: &queryPrefixNamespaces[0]},
}, true
}
func (d *DDBDatastore) putKey(key ds.Key) (map[string]*dynamodb.AttributeValue, bool) {
attrs, ok := d.getKey(key)
attrs[attrNameKey] = &dynamodb.AttributeValue{S: aws.String(key.String())}
return attrs, ok
}
func (d *DDBDatastore) getKey(key ds.Key) (map[string]*dynamodb.AttributeValue, bool) {
keyNamespaces := namespaces(key)
attrs := map[string]*dynamodb.AttributeValue{}
if d.sortKey == "" {
partitionKey := key.String()
attrs[d.partitionKey] = &dynamodb.AttributeValue{S: &partitionKey}
} else {
// if there's a sort key, then the first element of the trimmed key is the partition key
// and the rest of the trimmed key is the sort key
// there need to be >= 2 elements in the trimmed key so we can derive a sort key
// otherwise we can't write to this table
if len(keyNamespaces) < 2 {
return nil, false
}
partitionKey := keyNamespaces[0]
attrs[d.partitionKey] = &dynamodb.AttributeValue{S: &partitionKey}
sortKey := strings.Join(keyNamespaces[1:], "/")
attrs[d.sortKey] = &dynamodb.AttributeValue{S: &sortKey}
}
return attrs, true
}