forked from viant/dsunit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataset.go
308 lines (280 loc) · 7.8 KB
/
dataset.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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
package dsunit
import (
"bytes"
"encoding/json"
"github.com/pkg/errors"
"github.com/viant/assertly"
"github.com/viant/dsunit/sv"
"github.com/viant/toolbox"
"github.com/viant/toolbox/storage"
"github.com/viant/toolbox/url"
"io"
"io/ioutil"
"sort"
"strings"
)
const (
AutoincrementDirective = "@autoincrement@"
FromQueryDirective = "@fromQuery@"
FromQueryAliasDirective = "@fromQueryAlias@"
)
//Records represent data records
type Dataset struct {
Table string `required:"true"`
Records Records `required:"true"`
}
//NewDataset creates a new dataset for supplied table and records.
func NewDataset(table string, records ...map[string]interface{}) *Dataset {
return &Dataset{
Table: table,
Records: records,
}
}
//Records represents table records
type Records []map[string]interface{}
//Records returns non empty records //directive a filtered out
func (r *Records) Expand(context toolbox.Context, includeDirectives bool) (result []interface{}, err error) {
result = make([]interface{}, 0)
var evaluator = assertly.NewDefaultMacroEvaluator()
for _, candidate := range *r {
record := Record(candidate)
recordValues := make(map[string]interface{})
var keys = record.Columns()
if includeDirectives {
keys = toolbox.MapKeysToStringSlice(record)
}
for _, k := range keys {
v := record[k]
recordValues[k] = v
if text, ok := v.(string); ok {
if recordValues[k], err = evaluator.Expand(context, text); err != nil {
return nil, err
}
}
}
if len(recordValues) > 0 {
result = append(result, recordValues)
}
}
return result, nil
}
//ShouldDeleteAll checks if dataset contains empty record (indicator to delete all)
func (r *Records) ShouldDeleteAll() bool {
var result = len(*r) == 0
directiveScan(*r, func(record Record) {
if record == nil || len(record) == 0 {
result = true
}
})
return result
}
//UniqueKeys returns value for unique key directive, it test keys in the following order: @Autoincrement@, @IndexBy@
func (r *Records) UniqueKeys() []string {
var result []string
directiveScan(*r, func(record Record) {
for k, v := range record {
if k == AutoincrementDirective || k == assertly.IndexByDirective {
if keys, ok := v.([]string); ok {
result = keys
} else {
result = strings.Split(toolbox.AsString(v), ",")
}
}
}
})
return result
}
//FromQuery returns value for @FromQuery@ directive
func (r *Records) FromQuery() (string, string) {
var fromQuery string
var alias string
directiveScan(*r, func(record Record) {
for k, v := range record {
if k == FromQueryDirective {
fromQuery = toolbox.AsString(v)
}
if k == FromQueryAliasDirective {
alias = toolbox.AsString(v)
}
}
})
return fromQuery, alias
}
//PrimaryKey returns primary key directive if matched in the following order: @Autoincrement@, @IndexBy@
func (r *Records) Autoincrement() bool {
var result = false
directiveScan(*r, func(record Record) {
for k := range record {
if k == AutoincrementDirective {
result = true
}
}
})
return result
}
//Columns returns unique column names for this dataset
func (r *Records) Columns() []string {
var result = make([]string, 0)
var unique = make(map[string]bool)
for _, record := range *r {
var actualRecord = Record(record)
for _, column := range actualRecord.Columns() {
if _, has := unique[column]; has {
continue
}
unique[column] = true
result = append(result, column)
}
}
sort.Strings(result)
return result
}
//DatastoreDatasets represents a collection of datastore datasets
type DatastoreDatasets struct {
Datastore string `required:"true" description:"register datastore"`
Datasets []*Dataset `description:"collection of dataset per table"`
Data map[string][]map[string]interface{} `description:"map, where each pair represent table name and records (backwad compatiblity)"`
}
//DatasetResource represents a dataset resource
type DatasetResource struct {
*url.Resource ` description:"data file location, csv, json, ndjson formats are supported"`
*DatastoreDatasets `required:"true" description:"datastore datasets"`
Prefix string ` description:"location data file prefix"` //apply prefix
Postfix string ` description:"location data file postgix"` //apply suffix
loaded bool //flag to indicate load is called
}
func (r *DatasetResource) loadDataset() (err error) {
if r.Resource.URL == "" {
return errors.New("resource was empty")
}
r.Resource.Init()
var storageService storage.Service
storageService, err = storage.NewServiceForURL(r.URL, r.Credentials)
if err != nil {
return err
}
var candidates []storage.Object
candidates, err = storageService.List(r.Resource.URL)
if err != nil {
return err
}
for _, candidate := range candidates {
if candidate.FileInfo().IsDir() {
continue
}
err = r.load(storageService, candidate)
if err != nil {
return err
}
}
return err
}
//Loads dataset from specified resource or data map
func (r *DatasetResource) Load() (err error) {
if r == nil {
return errors.New("dataset resource was empty")
}
if r.loaded {
return nil
}
r.loaded = true
if len(r.Datasets) == 0 {
r.Datasets = make([]*Dataset, 0)
}
if r.Resource != nil && r.Resource.URL != "" {
if err = r.loadDataset(); err != nil {
return err
}
}
if len(r.Data) > 0 {
for k, v := range r.Data {
r.Datasets = append(r.Datasets, NewDataset(k, v...))
}
}
return nil
}
func (r *DatasetResource) Init() error {
return nil
}
func (r *DatasetResource) load(service storage.Service, object storage.Object) (err error) {
if len(r.Datasets) == 0 {
r.Datasets = make([]*Dataset, 0)
}
datafile := NewDatafileInfo(object.FileInfo().Name(), r.Prefix, r.Postfix)
if datafile == nil {
return nil
}
var loader func(datafile *DatafileInfo, data []byte) error
switch datafile.Ext {
case "json":
loader = r.loadJSON
case "csv":
loader = r.loadCSV
case "tsv":
loader = r.loadTSV
}
if loader != nil {
var reader io.ReadCloser
if reader, err = service.Download(object); err == nil {
defer reader.Close()
var content []byte
if content, err = ioutil.ReadAll(reader); err == nil {
err = loader(datafile, content)
}
}
}
return nil
}
func (r *DatasetResource) loadJSON(datafile *DatafileInfo, data []byte) error {
var dataSet = &Dataset{
Table: datafile.Name,
Records: make([]map[string]interface{}, 0),
}
if toolbox.IsNewLineDelimitedJSON(string(data)) {
if records, err := toolbox.NewLineDelimitedJSON(string(data)); err == nil {
for _, record := range records {
if recordMap, ok := record.(map[string]interface{}); ok {
dataSet.Records = append(dataSet.Records, recordMap)
}
}
r.Datasets = append(r.Datasets, dataSet)
return nil
}
}
err := json.NewDecoder(bytes.NewReader(data)).Decode(&dataSet.Records)
if err != nil {
return err
}
r.Datasets = append(r.Datasets, dataSet)
return nil
}
func (r *DatasetResource) loadCSV(datafile *DatafileInfo, data []byte) error {
return r.loadSeparatedData(",", datafile, data)
}
func (r *DatasetResource) loadTSV(datafile *DatafileInfo, data []byte) error {
return r.loadSeparatedData("\t", datafile, data)
}
func (r *DatasetResource) loadSeparatedData(delimiter string, datafile *DatafileInfo, data []byte) error {
records, err := sv.NewSeparatedValueParser(delimiter).Parse(data)
if err != nil {
return err
}
var dataSet = &Dataset{
Table: datafile.Name,
Records: records,
}
r.Datasets = append(r.Datasets, dataSet)
return nil
}
func NewDatasetResource(datastore string, URL, prefix, postfix string, datasets ...*Dataset) *DatasetResource {
var result = &DatasetResource{
Resource: url.NewResource(URL),
DatastoreDatasets: &DatastoreDatasets{
Datastore: datastore,
Datasets: datasets,
},
Prefix: prefix,
Postfix: postfix,
}
return result
}