/
backends.go
189 lines (160 loc) · 5.61 KB
/
backends.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
package backends
import (
"fmt"
"strings"
"time"
"github.com/alexcesaro/statsd"
"github.com/ghetzel/go-stockutil/log"
"github.com/ghetzel/go-stockutil/sliceutil"
"github.com/ghetzel/go-stockutil/stringutil"
"github.com/ghetzel/go-stockutil/typeutil"
"github.com/ghetzel/pivot/dal"
"github.com/ghetzel/pivot/filter"
)
var querylog = log.Logger()
var stats, _ = statsd.New()
var DefaultAutoregister = false
type Backend interface {
Initialize() error
SetIndexer(dal.ConnectionString) error
RegisterCollection(*dal.Collection)
GetConnectionString() *dal.ConnectionString
Exists(collection string, id interface{}) bool
Retrieve(collection string, id interface{}, fields ...string) (*dal.Record, error)
Insert(collection string, records *dal.RecordSet) error
Update(collection string, records *dal.RecordSet, target ...string) error
Delete(collection string, ids ...interface{}) error
CreateCollection(definition *dal.Collection) error
DeleteCollection(collection string) error
ListCollections() ([]string, error)
GetCollection(collection string) (*dal.Collection, error)
WithSearch(collection *dal.Collection, filters ...*filter.Filter) Indexer
WithAggregator(collection *dal.Collection) Aggregator
Flush() error
Ping(time.Duration) error
String() string
}
var NotImplementedError = fmt.Errorf("Not Implemented")
type BackendFunc func(dal.ConnectionString) Backend
var backendMap = map[string]BackendFunc{
`dynamodb`: NewDynamoBackend,
`file`: NewFilesystemBackend,
`fs`: NewFilesystemBackend,
`mongodb`: NewMongoBackend,
`mongo`: NewMongoBackend,
`mysql`: NewSqlBackend,
`postgres`: NewSqlBackend,
`postgresql`: NewSqlBackend,
`psql`: NewSqlBackend,
`sqlite`: NewSqlBackend,
`redis`: NewRedisBackend,
}
func RegisterBackend(name string, fn BackendFunc) {
backendMap[name] = fn
}
func MakeBackend(connection dal.ConnectionString) (Backend, error) {
backendName := connection.Backend()
log.Infof("Creating backend: %v", connection.String())
if fn, ok := backendMap[backendName]; ok {
if backend := fn(connection); backend != nil {
return backend, nil
} else {
return nil, fmt.Errorf("Error occurred instantiating backend %q", backendName)
}
} else {
return nil, fmt.Errorf("Unknown backend type %q", backendName)
}
}
func InflateEmbeddedRecords(backend Backend, parent *dal.Collection, record *dal.Record, prepId func(interface{}) interface{}) error { // for each relationship
for _, relationship := range parent.EmbeddedCollections {
keys := sliceutil.CompactString(sliceutil.Stringify(sliceutil.Sliceify(relationship.Keys)))
var related *dal.Collection
if relationship.Collection != nil {
related = relationship.Collection
} else if c, err := backend.GetCollection(relationship.CollectionName); c != nil {
related = c
} else {
return fmt.Errorf("error in relationship %v: %v", keys, err)
}
if related.Name == parent.Name {
log.Debugf("not descending into %v to avoid loop", related.Name)
continue
}
var nestedFields []string
// determine fields in final output handling
// a. no exported fields -> use relationship fields
// b. exported fields, no relationship fields -> use exported fields
// c. both relationship and exported fields -> relfields ∩ exported
//
relfields := relationship.Fields
exported := related.ExportedFields
if len(exported) == 0 {
nestedFields = relfields
} else if len(relfields) == 0 {
nestedFields = exported
} else {
nestedFields = sliceutil.IntersectStrings(relfields, exported)
}
for _, key := range keys {
keyBefore, _ := stringutil.SplitPair(key, `.*`)
if nestedId := record.Get(key); nestedId != nil {
if typeutil.IsArray(nestedId) {
results := make([]map[string]interface{}, 0)
for _, id := range sliceutil.Sliceify(nestedId) {
if prepId != nil {
id = prepId(id)
}
if data, err := retrieveEmbeddedRecord(backend, parent, related, id, nestedFields...); err == nil {
results = append(results, data)
} else {
return err
}
}
for i, result := range results {
if len(result) > 0 {
nestKey := strings.Replace(key, `*`, fmt.Sprintf("%d", i), 1)
record.SetNested(nestKey, result)
}
}
} else {
if prepId != nil {
nestedId = prepId(nestedId)
}
if data, err := retrieveEmbeddedRecord(backend, parent, related, nestedId, nestedFields...); err == nil {
if len(data) > 0 {
record.SetNested(keyBefore, data)
}
} else {
return err
}
}
}
}
}
return nil
}
func retrieveEmbeddedRecord(backend Backend, parent *dal.Collection, related *dal.Collection, id interface{}, fields ...string) (map[string]interface{}, error) {
if id == nil {
return nil, nil
}
// retrieve the record by ID
if record, err := backend.Retrieve(related.Name, id, fields...); err == nil {
if data, err := related.MapFromRecord(record, fields...); err == nil {
return data, nil
} else if parent.AllowMissingEmbeddedRecords {
// log.Warningf("nested(%s[%s]): %v", parent.Name, related.Name, err)
return nil, nil
} else {
return nil, fmt.Errorf("nested(%s[%s]): serialization error: %v", parent.Name, related.Name, err)
}
} else if parent.AllowMissingEmbeddedRecords {
// if dal.IsNotExistError(err) {
// log.Warningf("nested(%s[%s]): record %v is missing", parent.Name, related.Name, id)
// } else {
// log.Warningf("nested(%s[%s]): retrieval error on %v: %v", parent.Name, related.Name, id, err)
// }
return nil, nil
} else {
return nil, fmt.Errorf("nested(%s[%s]): %v", parent.Name, related.Name, err)
}
}