-
Notifications
You must be signed in to change notification settings - Fork 3
/
csvplus.go
1291 lines (1046 loc) · 32.3 KB
/
csvplus.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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (c) 2016,2017,2018,2019 Maxim Konakov
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Package csvplus extends the standard Go encoding/csv package with fluent
// interface, lazy stream processing operations, indices and joins.
package csvplus
import (
"bytes"
"encoding/csv"
"encoding/gob"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"sort"
"strconv"
"strings"
"unsafe"
)
/*
Row represents one line from a data source like a .csv file.
Each Row is a map from column names to the string values under that columns on the current line.
It is assumed that each column has a unique name.
In a .csv file, the column names may either come from the first line of the file ("expected header"),
or they can be set-up via configuration of the reader object ("assumed header").
Using meaningful column names instead of indices is usually more convenient when the columns get rearranged
during the execution of the processing pipeline.
*/
type Row map[string]string
// HasColumn is a predicate returning 'true' when the specified column is present.
func (row Row) HasColumn(col string) (found bool) {
_, found = row[col]
return
}
// SafeGetValue returns the value under the specified column, if present, otherwise it returns the
// substitution value.
func (row Row) SafeGetValue(col, subst string) string {
if value, found := row[col]; found {
return value
}
return subst
}
// Header returns a slice of all column names, sorted via sort.Strings.
func (row Row) Header() []string {
r := make([]string, 0, len(row))
for col := range row {
r = append(r, col)
}
sort.Strings(r)
return r
}
// String returns a string representation of the Row.
func (row Row) String() string {
if len(row) == 0 {
return "{}"
}
header := row.Header() // make order predictable
buff := append(append(append(append([]byte(`{ "`), header[0]...), `" : "`...), row[header[0]]...), '"')
for _, col := range header[1:] {
buff = append(append(append(append(append(buff, `, "`...), col...), `" : "`...), row[col]...), '"')
}
buff = append(buff, " }"...)
return *(*string)(unsafe.Pointer(&buff))
}
// SelectExisting takes a list of column names and returns a new Row
// containing only those columns from the list that are present in the current Row.
func (row Row) SelectExisting(cols ...string) Row {
r := make(map[string]string, len(cols))
for _, name := range cols {
if val, found := row[name]; found {
r[name] = val
}
}
return r
}
// Select takes a list of column names and returns a new Row
// containing only the specified columns, or an error if any column is not present.
func (row Row) Select(cols ...string) (Row, error) {
r := make(map[string]string, len(cols))
for _, name := range cols {
var found bool
if r[name], found = row[name]; !found {
return nil, fmt.Errorf(`Missing column %q`, name)
}
}
return r, nil
}
// SelectValues takes a list of column names and returns a slice of their
// corresponding values, or an error if any column is not present.
func (row Row) SelectValues(cols ...string) ([]string, error) {
r := make([]string, len(cols))
for i, name := range cols {
var found bool
if r[i], found = row[name]; !found {
return nil, fmt.Errorf(`Missing column %q`, name)
}
}
return r, nil
}
// Clone returns a copy of the current Row.
func (row Row) Clone() Row {
r := make(map[string]string, len(row))
for k, v := range row {
r[k] = v
}
return r
}
// ValueAsInt returns the value of the given column converted to integer type, or an error.
// The column must be present on the row.
func (row Row) ValueAsInt(column string) (res int, err error) {
var val string
var found bool
if val, found = row[column]; !found {
err = fmt.Errorf(`Missing column %q`, column)
return
}
if res, err = strconv.Atoi(val); err != nil {
if e, ok := err.(*strconv.NumError); ok {
err = fmt.Errorf(`Column %q: Cannot convert %q to integer: %s`, column, val, e.Err)
} else {
err = fmt.Errorf(`Column %q: %s`, column, err)
}
}
return
}
// ValueAsFloat64 returns the value of the given column converted to floating point type, or an error.
// The column must be present on the row.
func (row Row) ValueAsFloat64(column string) (res float64, err error) {
var val string
var found bool
if val, found = row[column]; !found {
err = fmt.Errorf(`Missing column %q`, column)
return
}
if res, err = strconv.ParseFloat(val, 64); err != nil {
if e, ok := err.(*strconv.NumError); ok {
err = fmt.Errorf(`Column %q: Cannot convert %q to float: %s`, column, val, e.Err)
} else {
err = fmt.Errorf(`Column %q: %s`, column, err.Error())
}
}
return
}
// RowFunc is the function type used when iterating Rows.
type RowFunc func(Row) error
// DataSource is the iterator type used throughout this library. The iterator
// calls the given RowFunc once per each row. The iteration continues until
// either the data source is exhausted or the supplied RowFunc returns a non-nil error, in
// which case the error is returned back to the caller of the iterator. A special case of io.EOF simply
// stops the iteration and the iterator function returns nil error.
type DataSource func(RowFunc) error
// TakeRows converts a slice of Rows to a DataSource.
func TakeRows(rows []Row) DataSource {
return func(fn RowFunc) error {
return iterate(rows, fn)
}
}
// the core iteration
func iterate(rows []Row, fn RowFunc) (err error) {
var row Row
var i int
for i, row = range rows {
if err = fn(row.Clone()); err != nil {
break
}
}
switch err {
case nil:
// nothing to do
case io.EOF:
err = nil // end of iteration
default:
// wrap error
err = &DataSourceError{
Line: uint64(i),
Err: err,
}
}
return
}
// Take converts anything with Iterate() method to a DataSource.
func Take(src interface {
Iterate(fn RowFunc) error
}) DataSource {
return src.Iterate
}
// Transform is the most generic operation on a Row. It takes a function that
// maps a Row to another Row and an error. Any error returned from that function
// stops the iteration, otherwise the returned Row, if not empty, gets passed
// down to the next stage of the processing pipeline.
func (src DataSource) Transform(trans func(Row) (Row, error)) DataSource {
return func(fn RowFunc) error {
return src(func(row Row) (err error) {
if row, err = trans(row); err == nil && len(row) > 0 {
err = fn(row)
}
return
})
}
}
// Filter takes a predicate which, when applied to a Row, decides if that Row
// should be passed down for further processing. The predicate should return 'true' to pass the Row.
func (src DataSource) Filter(pred func(Row) bool) DataSource {
return func(fn RowFunc) error {
return src(func(row Row) (err error) {
if pred(row) {
err = fn(row)
}
return
})
}
}
// Map takes a function which gets applied to each Row when the source is iterated over. The function
// may return a modified input Row, or an entirely new Row.
func (src DataSource) Map(mf func(Row) Row) DataSource {
return func(fn RowFunc) error {
return src(func(row Row) error {
return fn(mf(row))
})
}
}
// Validate takes a function which checks every Row upon iteration and returns an error
// if the validation fails. The iteration stops at the first error encountered.
func (src DataSource) Validate(vf func(Row) error) DataSource {
return func(fn RowFunc) error {
return src(func(row Row) (err error) {
if err = vf(row); err == nil {
err = fn(row)
}
return
})
}
}
// Top specifies the number of Rows to pass down the pipeline before stopping the iteration.
func (src DataSource) Top(n uint64) DataSource {
return func(fn RowFunc) error {
counter := n
return src(func(row Row) error {
if counter == 0 {
return io.EOF
}
counter--
return fn(row)
})
}
}
// Drop specifies the number of Rows to ignore before passing the remaining rows down the pipeline.
func (src DataSource) Drop(n uint64) DataSource {
return func(fn RowFunc) error {
counter := n
return src(func(row Row) error {
if counter == 0 {
return fn(row)
}
counter--
return nil
})
}
}
// TakeWhile takes a predicate which gets applied to each Row upon iteration.
// The iteration stops when the predicate returns 'false'.
func (src DataSource) TakeWhile(pred func(Row) bool) DataSource {
return func(fn RowFunc) error {
var done bool
return src(func(row Row) error {
if done = (done || !pred(row)); done {
return io.EOF
}
return fn(row)
})
}
}
// DropWhile ignores all the Rows for as long as the specified predicate is true;
// afterwards all the remaining Rows are passed down the pipeline.
func (src DataSource) DropWhile(pred func(Row) bool) DataSource {
return func(fn RowFunc) error {
var yield bool
return src(func(row Row) (err error) {
if yield = (yield || !pred(row)); yield {
err = fn(row)
}
return
})
}
}
// ToCsv iterates the data source and writes the selected columns in .csv format to the given io.Writer.
// The data are written in the "canonical" form with the header on the first line and with all the lines
// having the same number of fields, using default settings for the underlying csv.Writer.
func (src DataSource) ToCsv(out io.Writer, columns ...string) (err error) {
if len(columns) == 0 {
panic("Empty column list in ToCsv() function")
}
w := csv.NewWriter(out)
// header
if err = w.Write(columns); err == nil {
// rows
err = src(func(row Row) (e error) {
var values []string
if values, e = row.SelectValues(columns...); e == nil {
e = w.Write(values)
}
return
})
}
if err == nil {
w.Flush()
err = w.Error()
}
return
}
// ToCsvFile iterates the data source and writes the selected columns in .csv format to the given file.
// The data are written in the "canonical" form with the header on the first line and with all the lines
// having the same number of fields, using default settings for the underlying csv.Writer.
func (src DataSource) ToCsvFile(name string, columns ...string) error {
return writeFile(name, func(file io.Writer) error {
return src.ToCsv(file, columns...)
})
}
// call the given function with the file stream open for writing
func writeFile(name string, fn func(io.Writer) error) (err error) {
var file *os.File
if file, err = os.Create(name); err != nil {
return
}
defer func() {
if p := recover(); p != nil {
file.Close()
os.Remove(name)
panic(p)
}
if e := file.Close(); e != nil && err == nil {
err = e
}
if err != nil {
os.Remove(name)
}
}()
err = fn(file)
return
}
// ToJSON iterates over the data source and writes all Rows to the given io.Writer in JSON format.
func (src DataSource) ToJSON(out io.Writer) (err error) {
var buff bytes.Buffer
buff.WriteByte('[')
count := uint64(0)
enc := json.NewEncoder(&buff)
enc.SetIndent("", "")
enc.SetEscapeHTML(false)
err = src(func(row Row) (e error) {
if count++; count != 1 {
buff.WriteByte(',')
}
if e = enc.Encode(row); e == nil && buff.Len() > 10000 {
_, e = buff.WriteTo(out)
}
return
})
if err == nil {
buff.WriteByte(']')
_, err = buff.WriteTo(out)
}
return
}
// ToJSONFile iterates over the data source and writes all Rows to the given file in JSON format.
func (src DataSource) ToJSONFile(name string) error {
return writeFile(name, src.ToJSON)
}
// ToRows iterates the DataSource storing the result in a slice of Rows.
func (src DataSource) ToRows() (rows []Row, err error) {
err = src(func(row Row) error {
rows = append(rows, row)
return nil
})
return
}
// DropColumns removes the specifies columns from each row.
func (src DataSource) DropColumns(columns ...string) DataSource {
if len(columns) == 0 {
panic("No columns specified in DropColumns()")
}
return func(fn RowFunc) error {
return src(func(row Row) error {
for _, col := range columns {
delete(row, col)
}
return fn(row)
})
}
}
// SelectColumns leaves only the specified columns on each row. It is an error
// if any such column does not exist.
func (src DataSource) SelectColumns(columns ...string) DataSource {
if len(columns) == 0 {
panic("No columns specified in SelectColumns()")
}
return func(fn RowFunc) error {
return src(func(row Row) (err error) {
if row, err = row.Select(columns...); err == nil {
err = fn(row)
}
return
})
}
}
// IndexOn iterates the input source, building index on the specified columns.
// Columns are taken from the specified list from left to the right.
func (src DataSource) IndexOn(columns ...string) (*Index, error) {
return createIndex(src, columns)
}
// UniqueIndexOn iterates the input source, building unique index on the specified columns.
// Columns are taken from the specified list from left to the right.
func (src DataSource) UniqueIndexOn(columns ...string) (*Index, error) {
return createUniqueIndex(src, columns)
}
// Join returns a DataSource which is a join between the current DataSource and the specified
// Index. The specified columns are matched against those from the index, in the order of specification.
// Empty 'columns' list yields a join on the columns from the Index (aka "natural join") which all must
// exist in the current DataSource.
// Each row in the resulting table contains all the columns from both the current table and the index.
// This is a lazy operation, the actual join is performed only when the resulting table is iterated over.
func (src DataSource) Join(index *Index, columns ...string) DataSource {
if len(columns) == 0 {
columns = index.impl.columns
} else if len(columns) > len(index.impl.columns) {
panic("Too many source columns in Join()")
}
return func(fn RowFunc) error {
return src(func(row Row) (err error) {
var values []string
if values, err = row.SelectValues(columns...); err == nil {
n := len(index.impl.rows)
for i := index.impl.first(values); i < n && !index.impl.cmp(i, values, false); i++ {
if err = fn(mergeRows(index.impl.rows[i], row)); err != nil {
break
}
}
}
return
})
}
}
func mergeRows(left, right Row) Row {
r := make(map[string]string, len(left)+len(right))
for k, v := range left {
r[k] = v
}
for k, v := range right {
r[k] = v
}
return r
}
// Except returns a table containing all the rows not in the specified Index, unchanged. The specified
// columns are matched against those from the index, in the order of specification. If no columns
// are specified then the columns list is taken from the index.
func (src DataSource) Except(index *Index, columns ...string) DataSource {
if len(columns) == 0 {
columns = index.impl.columns
} else if len(columns) > len(index.impl.columns) {
panic("Too many source columns in Except()")
}
return func(fn RowFunc) error {
return src(func(row Row) (err error) {
var values []string
if values, err = row.SelectValues(columns...); err == nil {
if !index.impl.has(values) {
err = fn(row)
}
}
return
})
}
}
// Index is a sorted collection of Rows with O(log(n)) complexity of search
// on the indexed columns. Iteration over the Index yields a sequence of Rows sorted on the index.
type Index struct {
impl indexImpl
}
// Iterate iterates over all rows of the index. The rows are sorted by the values of the columns
// specified when the Index was created.
func (index *Index) Iterate(fn RowFunc) error {
return iterate(index.impl.rows, fn)
}
// Find returns a DataSource of all Rows from the Index that match the specified values
// in the indexed columns, left to the right. The number of specified values may be less than
// the number of the indexed columns.
func (index *Index) Find(values ...string) DataSource {
return TakeRows(index.impl.find(values))
}
// SubIndex returns an Index containing only the rows where the values of the
// indexed columns match the supplied values, left to the right. The number of specified values
// must be less than the number of indexed columns.
func (index *Index) SubIndex(values ...string) *Index {
if len(values) >= len(index.impl.columns) {
panic("Too many values in SubIndex()")
}
return &Index{indexImpl{
rows: index.impl.find(values),
columns: index.impl.columns[len(values):],
}}
}
// ResolveDuplicates calls the specified function once per each pack of duplicates with the same key.
// The specified function must not modify its parameter and is expected to do one of the following:
//
// - Select and return one row from the input list. The row will be used as the only row with its key;
//
// - Return an empty row. The entire set of rows will be ignored;
//
// - Return an error which will be passed back to the caller of ResolveDuplicates().
func (index *Index) ResolveDuplicates(resolve func(rows []Row) (Row, error)) error {
return index.impl.dedup(resolve)
}
// WriteTo writes the index to the specified file.
func (index *Index) WriteTo(fileName string) (err error) {
var file *os.File
if file, err = os.Create(fileName); err != nil {
return
}
defer func() {
if e := file.Close(); e != nil || err != nil {
os.Remove(fileName)
if err == nil {
err = e
}
}
}()
enc := gob.NewEncoder(file)
if err = enc.Encode(index.impl.columns); err == nil {
err = enc.Encode(index.impl.rows)
}
return
}
// LoadIndex reads the index from the specified file.
func LoadIndex(fileName string) (*Index, error) {
var file *os.File
var err error
if file, err = os.Open(fileName); err != nil {
return nil, err
}
defer file.Close()
index := new(Index)
dec := gob.NewDecoder(file)
if err = dec.Decode(&index.impl.columns); err != nil {
return nil, err
}
if err = dec.Decode(&index.impl.rows); err != nil {
return nil, err
}
return index, nil
}
func createIndex(src DataSource, columns []string) (*Index, error) {
switch len(columns) {
case 0:
panic("Empty column list in CreateIndex()")
case 1:
// do nothing
default:
if !allColumnsUnique(columns) {
panic("Duplicate column name(s) in CreateIndex()")
}
}
index := &Index{indexImpl{columns: columns}}
// copy Rows with validation
if err := src(func(row Row) error {
for _, col := range columns {
if !row.HasColumn(col) {
return fmt.Errorf(`Missing column %q while creating an index`, col)
}
}
index.impl.rows = append(index.impl.rows, row)
return nil
}); err != nil {
return nil, err
}
// sort
sort.Sort(&index.impl)
return index, nil
}
func createUniqueIndex(src DataSource, columns []string) (index *Index, err error) {
// create index
if index, err = createIndex(src, columns); err != nil || len(index.impl.rows) < 2 {
return
}
// check for duplicates by linear search; not the best idea.
rows := index.impl.rows
for i := 1; i < len(rows); i++ {
if equalRows(columns, rows[i-1], rows[i]) {
return nil, errors.New("Duplicate value while creating unique index: " + rows[i].SelectExisting(columns...).String())
}
}
return
}
// compare the specified columns from the two rows
func equalRows(columns []string, r1, r2 Row) bool {
for _, col := range columns {
if r1[col] != r2[col] {
return false
}
}
return true
}
// check if all the column names from the specified list are unique
func allColumnsUnique(columns []string) bool {
set := make(map[string]struct{}, len(columns))
for _, col := range columns {
if _, found := set[col]; found {
return false
}
set[col] = struct{}{}
}
return true
}
// index implementation
type indexImpl struct {
rows []Row
columns []string
}
// functions required by sort.Sort()
func (index *indexImpl) Len() int { return len(index.rows) }
func (index *indexImpl) Swap(i, j int) { index.rows[i], index.rows[j] = index.rows[j], index.rows[i] }
func (index *indexImpl) Less(i, j int) bool {
left, right := index.rows[i], index.rows[j]
for _, col := range index.columns {
switch strings.Compare(left[col], right[col]) {
case -1:
return true
case 1:
return false
}
}
return false
}
// deduplication
func (index *indexImpl) dedup(resolve func(rows []Row) (Row, error)) (err error) {
// find first duplicate
var lower int
for lower = 1; lower < len(index.rows); lower++ {
if equalRows(index.columns, index.rows[lower-1], index.rows[lower]) {
break
}
}
if lower == len(index.rows) {
return
}
dest := lower - 1
// loop: find index of the first row with another key, resolve, then find next duplicate
for lower < len(index.rows) {
// the duplicate is in [lower-1, upper[ range
values, _ := index.rows[lower].SelectValues(index.columns...)
upper := lower + sort.Search(len(index.rows)-lower, func(i int) bool {
return index.cmp(lower+i, values, false)
})
// resolve
var row Row
if row, err = resolve(index.rows[lower-1 : upper]); err != nil {
return
}
lower = upper + 1
// store the chosen row if not 'empty'
if len(row) >= len(index.columns) {
index.rows[dest] = row
dest++
}
// find next duplicate
for lower < len(index.rows) {
if equalRows(index.columns, index.rows[lower-1], index.rows[lower]) {
break
}
index.rows[dest] = index.rows[lower-1]
lower++
dest++
}
}
if err == nil {
index.rows = index.rows[:dest]
}
return
}
// search on the index
func (index *indexImpl) find(values []string) []Row {
// check boundaries
if len(values) == 0 {
return index.rows
}
if len(values) > len(index.columns) {
panic("Too many columns in indexImpl.find()")
}
// get bounds
upper := sort.Search(len(index.rows), func(i int) bool {
return index.cmp(i, values, false)
})
lower := sort.Search(upper, func(i int) bool {
return index.cmp(i, values, true)
})
// done
return index.rows[lower:upper]
}
func (index *indexImpl) first(values []string) int {
return sort.Search(len(index.rows), func(i int) bool {
return index.cmp(i, values, true)
})
}
func (index *indexImpl) has(values []string) bool {
// find the lowest index
i := index.first(values)
// check if the row at the lowest index matches the values
return i < len(index.rows) && !index.cmp(i, values, false)
}
func (index *indexImpl) cmp(i int, values []string, eq bool) bool {
row := index.rows[i]
for j, val := range values {
switch strings.Compare(row[index.columns[j]], val) {
case 1:
return true
case -1:
return false
}
}
return eq
}
// Reader is iterable csv reader. The iteration is performed in its Iterate() method, which
// may only be invoked once per each instance of the Reader.
type Reader struct {
source maker
delimiter, comment rune
numFields int
lazyQuotes, trimLeadingSpace bool
header map[string]int
headerFromFirstRow bool
}
type maker = func() (io.Reader, func(), error)
// FromReader constructs a new csv reader from the given io.Reader, with default settings.
func FromReader(input io.Reader) *Reader {
return makeReader(func() (io.Reader, func(), error) {
return input, func() {}, nil
})
}
// FromReadCloser constructs a new csv reader from the given io.ReadCloser, with default settings.
func FromReadCloser(input io.ReadCloser) *Reader {
return makeReader(func() (io.Reader, func(), error) {
return input, func() { input.Close() }, nil
})
}
// FromFile constructs a new csv reader bound to the specified file, with default settings.
func FromFile(name string) *Reader {
return makeReader(func() (io.Reader, func(), error) {
file, err := os.Open(name)
if err != nil {
return nil, nil, err
}
return file, func() { file.Close() }, nil
})
}
func makeReader(fn maker) *Reader {
return &Reader{
source: fn,
delimiter: ',',
headerFromFirstRow: true,
}
}
// Delimiter sets the symbol to be used as a field delimiter.
func (r *Reader) Delimiter(c rune) *Reader {
r.delimiter = c
return r
}
// CommentChar sets the symbol that starts a comment.
func (r *Reader) CommentChar(c rune) *Reader {
r.comment = c
return r
}
// LazyQuotes specifies that a quote may appear in an unquoted field and a
// non-doubled quote may appear in a quoted field of the input.
func (r *Reader) LazyQuotes() *Reader {
r.lazyQuotes = true
return r
}
// TrimLeadingSpace specifies that the leading white space in a field should be ignored.
func (r *Reader) TrimLeadingSpace() *Reader {
r.trimLeadingSpace = true
return r
}
// AssumeHeader sets the header for those input sources that do not have their column
// names specified on the first row. The header specification is a map
// from the assigned column names to their corresponding column indices.
func (r *Reader) AssumeHeader(spec map[string]int) *Reader {
if len(spec) == 0 {
panic("Empty header spec")