This repository has been archived by the owner on Feb 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
dataset.go
468 lines (407 loc) · 10.5 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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
package iop
import (
"context"
"fmt"
"io"
"math"
"sort"
"strings"
"time"
"github.com/dustin/go-humanize"
"github.com/flarco/g"
"github.com/flarco/g/csv"
"github.com/jedib0t/go-pretty/table"
"github.com/jmoiron/sqlx"
"github.com/samber/lo"
"github.com/spf13/cast"
)
// Dataset is a query returned dataset
type Dataset struct {
Result *sqlx.Rows
Columns Columns
Rows [][]interface{}
SQL string
Duration float64
Sp *StreamProcessor
Inferred bool
SafeInference bool
NoDebug bool
}
// NewDataset return a new dataset
func NewDataset(columns Columns) (data Dataset) {
data = Dataset{
Result: nil,
Columns: NewColumns(columns...),
Rows: [][]interface{}{},
Sp: NewStreamProcessor(),
}
return
}
// NewDatasetFromMap return a new dataset
func NewDatasetFromMap(m map[string]interface{}) (data Dataset) {
data = Dataset{
Result: nil,
Columns: Columns{},
Rows: [][]interface{}{},
Sp: NewStreamProcessor(),
}
if fieldsI, ok := m["headers"]; ok {
fields := []string{}
for _, f := range fieldsI.([]interface{}) {
fields = append(fields, cast.ToString(f))
}
data.Columns = NewColumnsFromFields(fields...)
}
if rowsI, ok := m["rows"]; ok {
for _, rowI := range rowsI.([]interface{}) {
data.Rows = append(data.Rows, rowI.([]interface{}))
}
}
return
}
// SetColumns sets the columns
func (data *Dataset) AddColumns(newCols Columns, overwrite bool) (added Columns) {
data.Columns, added = data.Columns.Add(newCols, overwrite)
return added
}
// Sort sorts by cols
// example: `data.Sort(0, 2, 3, false)` will sort
// col0, col2, col3 descending
// example: `data.Sort(0, 2, true)` will sort
// col0, col2 ascending
func (data *Dataset) Sort(args ...any) {
colIDs := []int{}
asc := true
for _, arg := range args {
switch val := arg.(type) {
case int:
colIDs = append(colIDs, val)
case bool:
asc = val
}
}
less := func(i, j int) bool {
arrA := []string{}
arrB := []string{}
var a, b string
for _, colID := range colIDs {
colType := data.Columns[colID].Type
valI := data.Rows[i][colID]
valJ := data.Rows[j][colID]
if colType.IsInteger() {
// zero pad for correct sorting
a = fmt.Sprintf("%20d", valI)
b = fmt.Sprintf("%20d", valJ)
} else if colType.IsDecimal() {
// zero pad for correct sorting
a = fmt.Sprintf("%20.9f", valI)
b = fmt.Sprintf("%20.9f", valJ)
} else {
a = data.Sp.CastToString(colID, valI, colType)
b = data.Sp.CastToString(colID, valJ, colType)
}
arrA = append(arrA, a)
arrB = append(arrB, b)
}
if asc {
return strings.Join(arrA, "-") < strings.Join(arrB, "-")
}
return strings.Join(arrA, "-") > strings.Join(arrB, "-")
}
sort.SliceStable(data.Rows, less)
}
// Print pretty prints the data with a limit
// 0 is unlimited
func (data *Dataset) Print(limit int) {
tf := "2006-01-02 15:04:05"
T := table.NewWriter()
header := table.Row{}
for _, val := range data.Columns.Names() {
header = append(header, val)
}
T.AppendHeader(header)
limited := false
for j, row := range data.Rows {
for i, col := range data.Columns {
sVal := cast.ToString(row[i])
switch {
case col.IsDatetime() || (strings.HasPrefix(sVal, "20") && strings.HasSuffix(sVal, "Z")):
val, err := data.Sp.CastToTime(row[i])
if err != nil {
row[i] = sVal
} else {
row[i] = val.Format(tf)
}
case col.IsNumber():
row[i] = humanize.Comma(cast.ToInt64(row[i]))
default:
row[i] = sVal
}
}
T.AppendRow(row)
if limit > 0 && j+1 == limit {
limited = true
break
}
}
println(T.Render())
if limited {
g.Warn("results were limited to %d rows.", limit)
}
}
// WriteCsv writes to a writer
func (data *Dataset) WriteCsv(dest io.Writer) (tbw int, err error) {
w := csv.NewWriter(dest)
defer w.Flush()
tbw, err = w.Write(data.GetFields())
if err != nil {
return tbw, g.Error(err, "error write row to csv file")
}
for _, row := range data.Rows {
rec := make([]string, len(row))
for i, val := range row {
rec[i] = data.Sp.CastToString(i, val, data.Columns[i].Type)
}
bw, err := w.Write(rec)
if err != nil {
return tbw, g.Error(err, "error write row to csv file")
}
tbw = tbw + bw
}
return
}
// GetFields return the fields of the Data
func (data *Dataset) GetFields(lower ...bool) []string {
Lower := false
if len(lower) > 0 {
Lower = lower[0]
}
fields := make([]string, len(data.Columns))
for j, column := range data.Columns {
if Lower {
fields[j] = strings.ToLower(column.Name)
} else {
fields[j] = column.Name
}
}
return fields
}
// SetFields sets the fields/columns of the Datastream
func (data *Dataset) SetFields(fields []string) {
if data.Columns == nil || len(data.Columns) != len(fields) {
data.Columns = make(Columns, len(fields))
}
for i, field := range fields {
data.Columns[i].Name = field
data.Columns[i].Position = i + 1
}
}
// Append appends a new row
func (data *Dataset) Append(row []interface{}) {
data.Rows = append(data.Rows, row)
}
// Stream returns a datastream of the dataset
func (data *Dataset) Stream() *Datastream {
rows := MakeRowsChan()
nextFunc := func(it *Iterator) bool {
for it.Row = range rows {
return true
}
return false
}
ds := NewDatastreamIt(context.Background(), data.Columns, nextFunc)
ds.it.IsCasted = true
ds.Inferred = data.Inferred
ds.Sp = data.Sp
ds.Sp.ds = ds
go func() {
defer close(rows)
for _, row := range data.Rows {
rows <- row
}
}()
err := ds.Start()
if err != nil {
ds.Context.CaptureErr(err)
}
return ds
}
// FirstVal returns the first value from the first row
func (data *Dataset) FirstVal() interface{} {
if len(data.Rows) > 0 && len(data.Rows[0]) > 0 {
return data.Rows[0][0]
}
return nil
}
// FirstRow returns the first row
func (data *Dataset) FirstRow() []interface{} {
if len(data.Rows) > 0 {
return data.Rows[0]
}
return nil
}
// ColValues returns the values of a one column as array
func (data *Dataset) ColValues(col int) []interface{} {
vals := make([]interface{}, len(data.Rows))
for i, row := range data.Rows {
vals[i] = row[col]
}
return vals
}
// Pick returns a new dataset with specified columns
func (data *Dataset) Pick(colNames ...string) (nData Dataset) {
nData = NewDataset(Columns{})
nData.SetFields(colNames)
for _, rec := range data.Records() {
row := []any{}
for _, colName := range colNames {
row = append(row, rec[strings.ToLower(colName)])
}
nData.Append(row)
}
return nData
}
// ColValuesStr returns the values of a one column as array or string
func (data *Dataset) ColValuesStr(col int) []string {
vals := make([]string, len(data.Rows))
for i, row := range data.Rows {
vals[i] = data.Sp.CastToString(i, row[col], data.Columns[col].Type)
}
return vals
}
// Records return rows of maps
func (data *Dataset) Records(lower ...bool) []map[string]interface{} {
Lower := true
if len(lower) > 0 {
Lower = lower[0]
}
records := make([]map[string]interface{}, len(data.Rows))
for i, row := range data.Rows {
rec := map[string]interface{}{}
for j, field := range data.GetFields(Lower) {
rec[field] = row[j]
}
records[i] = rec
}
return records
}
// Records return rows of maps or string values
func (data *Dataset) StringRecords(lower ...bool) []map[string]interface{} {
Lower := true
if len(lower) > 0 {
Lower = lower[0]
}
records := make([]map[string]interface{}, len(data.Rows))
for i, row := range data.Rows {
rec := map[string]interface{}{}
for j, field := range data.GetFields(Lower) {
rec[field] = cast.ToString(row[j])
}
records[i] = rec
}
return records
}
// ToJSONMap converst to a JSON object
func (data *Dataset) ToJSONMap() map[string]interface{} {
return g.M("headers", data.GetFields(), "rows", data.Rows)
}
// InferColumnTypes determines the columns types
func (data *Dataset) InferColumnTypes() {
var columns Columns
if len(data.Rows) == 0 {
g.Trace("skipping InferColumnTypes [no rows]")
return
}
for i, column := range data.Columns {
column.Type = lo.Ternary(column.Type == "", StringType, column.Type)
column.Stats = ColumnStats{
Min: math.MaxInt64,
Max: math.MinInt64,
MinLen: math.MaxInt32,
}
column.Position = i + 1
columns = append(columns, column)
}
// g.Trace("InferColumnTypes with sample size %d", SampleSize)
for i, row := range data.Rows {
if i >= SampleSize {
break
}
for j, val := range row {
val = data.Sp.ParseString(strings.TrimSpace(cast.ToString(val)), j)
columns[j].Stats.TotalCnt++
valStr := cast.ToString(val)
l := len(valStr)
if val == nil || l == 0 {
columns[j].Stats.NullCnt++
continue
} else {
if l > columns[j].Stats.MaxLen {
columns[j].Stats.MaxLen = l
}
if l < columns[j].Stats.MinLen {
columns[j].Stats.MinLen = l
}
}
switch val.(type) {
case time.Time:
columns[j].Stats.DateCnt++
case nil:
columns[j].Stats.NullCnt++
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
columns[j].Stats.IntCnt++
val0 := cast.ToInt64(val)
if val0 > columns[j].Stats.Max {
columns[j].Stats.Max = val0
}
if val0 < columns[j].Stats.Min {
columns[j].Stats.Min = val0
}
case float32, float64:
columns[j].Stats.DecCnt++
val0 := cast.ToInt64(val)
if val0 > columns[j].Stats.Max {
columns[j].Stats.Max = val0
}
if val0 < columns[j].Stats.Min {
columns[j].Stats.Min = val0
}
if strings.Contains(valStr, ".") {
decLen := len(strings.Split(cast.ToString(val), ".")[1])
if decLen > columns[j].Stats.MaxDecLen {
columns[j].Stats.MaxDecLen = decLen
}
}
case bool:
columns[j].Stats.BoolCnt++
case string, []uint8:
if looksLikeJson(valStr) {
var v interface{}
if err := g.Unmarshal(valStr, &v); err == nil {
columns[j].Stats.JsonCnt++
} else {
columns[j].Stats.StringCnt++
}
} else {
columns[j].Stats.StringCnt++
}
}
}
}
data.Columns = InferFromStats(columns, data.SafeInference, data.NoDebug)
// overwrite if found in config.columns
for i, col := range data.Columns {
if colType, found := data.Sp.config.columns[strings.ToLower(col.Name)]; found {
if colType.IsValid() {
data.Columns[i].Type = colType
} else {
g.Warn("Provided unknown column type (%s) for column '%s'. Using string.", colType, strings.ToLower(col.Name))
data.Columns[i].Type = StringType
}
}
}
data.Inferred = true
}
func looksLikeJson(s string) bool {
return (strings.HasPrefix(s, "{") && strings.HasSuffix(s, "}")) || (strings.HasPrefix(s, "[") && strings.HasSuffix(s, "]"))
}