-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdoc.go
More file actions
940 lines (632 loc) · 38 KB
/
Copy pathdoc.go
File metadata and controls
940 lines (632 loc) · 38 KB
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
// © 2017-2026 Osvaldo Gago
/*
The Go package simplecsv is a library to handle csv files without using a database.
Some notes:
- all read methods return the value in the csv and a second true/false value that is true if the value exists
- all write methods that change the csv return the changed csv and a true/false value if the operation was successful
- all cells are strings
- methods that return a SimpleCsv never modify the original csv and share no data with it: the returned csv is an independent copy, and get methods like GetRow and GetHeaders return copies
- Simplecsv works with comma separated csv files.
- header names (the first row) must be unique, like database columns. Creating a csv with duplicate headers, reading a file whose first row has duplicate headers, or renaming a header to a name that already exists is rejected. This guarantees that name-based lookups (GetCellByField, FindInField, SortByField, GetRowAsMap, the *FromMap functions, etc.) address exactly one column.
- all rows have the same number of cells as the header row (uniform row width). Reading a ragged file (rows with more or fewer fields than the header row) is rejected with an error, and Write methods that add or set rows reject a row whose length is not the header width. This makes "the number of columns" unambiguous and keeps AddRow, SetRow, the *FromMap functions, joins, OnlyThisFields, etc. consistent.
- ReadCsv, ReadCsvFile, ReadCsvFileE and ReadCsvFileComma read the whole input into memory. Use ReadCsvLimit with positive record and byte limits for large or attacker-controlled input.
- find and match (FindInColumn, FindInField, MatchInColumn, MatchInField) are case-insensitive by default: Foo = foo = FOO. Use the *CaseSensitive variants (FindInColumnCaseSensitive, FindInFieldCaseSensitive, MatchInColumnCaseSensitive, MatchInFieldCaseSensitive) when case matters.
- header names require at least one column: CreateEmptyCsv and OnlyThisFields reject an empty header list.
- CSV / formula injection: values that begin with =, +, -, @, a tab, a carriage return, a line feed, or the full-width variants =, +, -, @ are interpreted as formulas by spreadsheet applications (Excel, LibreOffice Calc, Google Sheets). The Write* functions write values verbatim and so do not neutralize such values, because escaping changes data. When the csv may contain attacker-controlled data (exported logs, form input, scraped content) and may be opened in a spreadsheet, call SanitizeFormulas first to prefix those cells with a single quote '; callers that do not want their bytes changed should not call it.
- writes are atomic and not world-readable: WriteCsvFile / WriteCsvFileE / WriteCsvFileComma write the csv to a temporary file in the same directory as the destination and then rename it over the destination, so a failed or interrupted write cannot truncate or corrupt the destination. The file (new or overwritten) ends up with mode 0600 (owner-readable only); callers that need different permissions can os.Chmod the result. Because the destination is replaced with os.Rename rather than opened, a symlink planted at the destination is replaced instead of followed.
* CSV FILE *
READ
Reads file and parses as a SimpleCsv object. `fileRead` is false if there's an error reading the file or parsing the CSV, if the file's header row contains duplicate names (headers must be unique), or if the file is ragged (rows with a different number of fields than the header row are rejected; uniform row width is an invariant).
var x simplecsv.SimpleCsv
x, fileRead = simplecsv.ReadCsvFile("my1file.csv")
All read functions (file-based and reader-based, limited or not) strip a UTF-8
byte order mark (BOM) from the first cell of the first row if present. Excel
and many Windows tools write one (EF BB BF) at the start of the file; without
stripping, the first header would become "\ufeffid" and every field lookup
would silently fail. Only the first cell of the first row is touched.
CREATE
Create empty file and define csv headers. Header names must be unique; if they
are not, the returned error is non-nil:
var u simplecsv.SimpleCsv
var err error
u, err = simplecsv.CreateEmptyCsv([]string{"Age", "Gender", "ID"})
if err != nil {
log.Fatal(err)
}
`MustCreateEmptyCsv` is the same but panics when the headers are invalid
(empty or duplicated). Handy in tests and small scripts where a valid header
list is part of the program, not a runtime condition:
u = simplecsv.MustCreateEmptyCsv([]string{"Age", "Gender", "ID"})
WRITE
Write the SimpleCsv object to my2file.csv. If there's an error, `wasWritten` is false.
wasWritten := u.WriteCsvFile("my2file.csv")
The write is atomic (the csv is written to a temp file in the same directory
and renamed over the destination, so a failed or interrupted write cannot
corrupt the destination), the file ends up with mode 0600 (owner-readable
only), and a symlink at the destination is replaced rather than followed.
SANITIZE (CSV / FORMULA INJECTION)
The Write* functions write values verbatim. A value that begins with `=`, `+`,
`-`, `@`, a tab, a carriage return, a line feed, or the full-width variants
`=`, `+`, `-`, `@` is interpreted as a formula by spreadsheet applications
(Excel, LibreOffice Calc, Google Sheets), and can be used to execute commands
or read other cells when the file is opened. This is a real risk when the csv
contains data that may be attacker-controlled (exported logs, form input,
scraped content) and is later opened in a spreadsheet.
`SanitizeFormulas` returns an independent copy of the csv in which every such
cell is prefixed with a single quote `'` (the spreadsheet convention), so the
value is treated as text. Escaping changes data (for example `-5` becomes
`'-5`, though the spreadsheet hides the quote and displays `-5` as text), so
sanitizing is opt-in. The original csv is not modified.
safe := u.SanitizeFormulas()
wasWritten := safe.WriteCsvFile("export.csv")
err := safe.WriteTo(os.Stdout, ',')
ERRORS
`ReadCsvFileE` and `WriteCsvFileE` work like `ReadCsvFile` and `WriteCsvFile` but return an error with the reason of the failure:
x, err = simplecsv.ReadCsvFileE("my1file.csv")
err := u.WriteCsvFileE("my2file.csv")
The joins, `GroupBy` and `Concat` have their own `E` variants; see ERROR
VARIANTS below.
`ReadCsv` and the file-reading wrappers read the whole input into memory. For
large or attacker-controlled input, `ReadCsvLimit` reads one record at a time
and rejects input over the configured limits. `maxRecords` includes the header
row, `maxBytes` limits input bytes, zero disables the corresponding limit, and
negative limits are rejected:
file, err := os.Open("large.csv")
if err != nil {
log.Fatal(err)
}
defer file.Close()
x, err := simplecsv.ReadCsvLimit(file, ',', 10000, 10*1024*1024)
if err != nil {
log.Fatal(err)
}
DELIMITERS, READERS AND WRITERS
Simplecsv uses `,` as the default field separator, but it can read and write files with other separators, like `;` or tabs, and it can read from any io.Reader and write to any io.Writer:
x, err = simplecsv.ReadCsvFileComma("semicolonfile.csv", ';')
x, err = simplecsv.ReadCsv(os.Stdin, '\t')
err = x.WriteCsvFileComma("semicolonfile.csv", ';')
err = x.WriteTo(os.Stdout, ',')
* HEADERS *
The cells of the first row are considered headers.
GET
Get all headers:
headers := x.GetHeaders()
Get header at position one (second position as it starts from 0):
headerName, headerExists := x.GetHeader(1)
Get header position: (it returns `-1` if the header does not exist)
position := x.GetHeaderPosition("Gender")
RENAME
Rename header: (old header, new header)
x, headerExists := x.RenameHeader("ID", "IDnumber")
`headerExists` is false if the old header does not exist, or if `IDnumber`
already exists as another column: header names must stay unique, so a rename
that would produce a duplicate is rejected. Renaming a header to its own name
is a no-op and is allowed.
* ROWS *
GET
Get number of rows:
numberOfRows := x.GetNumberRows()
Get second row:
row, rowExists := x.GetRow(1)
Get second row as a map:
row, rowExists := x.GetRowAsMap(1)
ADD
Add a slice to a row. The slice must have the same size as the CSV number of columns. If not wasSuccessful is false.
x, wasSuccessful = x.AddRow([]string{"24", "M", "2986732"})
Add row from map: (If the map keys don't exist as columns, the value will be discarded. If a key does not exist, it will create empty cells.)
mymap := make(map[string]string)
mymap["Age"] = "62"
mymap["Gender"] = "F"
mymap["ID"] = "6463246"
x, wasAdded = x.AddRowFromMap(mymap)
SET
Set second row (1) from a slice. The length of the slice must be the same as the number of columns and the row must already exist. If there’s an error `wasSet` is false.
x, wasSet = x.SetRow(1, []string{"45", "F", "8356138"})
Set second row from map: If the map keys don't exist as columns, the value will be discarded. If a key does not exist, it will create empty cells.)
mymap2 := make(map[string]string)
mymap2["Age"] = "62"
mymap2["Gender"] = "F"
mymap2["ID"] = "6463246"
x, wasAdded = x.SetRowFromMap(1, mymap2)
UPDATE
Unlike `SetRowFromMap`, `UpdateRowCellsFromMap` does not erase the cells value just because the column names are not keys in the map. It updates the cells that have the column name in the map and maintains the value of all the others.
To update the age in row 1:
mymap3 := make(map[string]string)
mymap3["Age"] = "63"
x, wasUpdated = x.UpdateRowCellsFromMap(1, mymap3)
DELETE
Delete second row: (If the row number is invalid, `wasDeleted` is false)
x, wasDeleted = x.DeleteRow(1)
DATA ROWS
Get the number of data rows, excluding the header row (unlike
`GetNumberRows`, which includes it):
numberOfDataRows := x.GetNumberDataRows()
Get all the data rows as copies (the header row is not included; changes
to the returned rows don't affect the csv):
dataRows := x.GetDataRows()
Iterate over the data rows without touching the header: `EachDataRow` calls
`fn` once per data row, in csv order, with the row index (starting at 1), a
copy of the row, and a map view of it (header name to cell value). Mutating
the row or the map inside `fn` does not affect the csv. `fn` may return
`false` to stop the iteration early:
x.EachDataRow(func(rowIndex int, row []string, asMap map[string]string) bool {
if asMap["status"] == "stop" {
return false // stop the iteration
}
fmt.Printf("row %d: %v\n", rowIndex, row)
return true
})
SLICE
`Head` returns the header row plus the first `n` data rows (or all of them
if there are fewer). `n` negative or zero means no data rows:
sample := x.Head(10)
`Tail` returns the header row plus the last `n` data rows:
recent := x.Tail(10)
`SliceRows` returns the header row plus the data rows whose csv row index
is in `[start, end)` (half-open, data rows start at index 1). `end` beyond
the last row is clamped. `wasSliced` is false if the csv is empty,
`start < 1` or `end < start`:
x, wasSliced = x.SliceRows(1, 3) // data rows 1 and 2
APPEND
`AppendRows` appends the data rows of another csv with the same headers
(same names, same order). `wasAppended` is false if either csv is empty or
the headers differ:
x, wasAppended = x.AppendRows(anotherCsv)
CONCAT
`Concat` stacks several csvs vertically in one call: the first non-empty
csv supplies the headers and every csv with a header row must have the
same headers (same names, same order); empty csvs are skipped. If there is
no non-empty csv or the headers differ, it returns nil and false:
combined, ok := simplecsv.Concat(day1, day2, day3)
CONCAT BY NAME
Monthly or vendor exports often add or reorder columns, and strict `Concat`
rejects them. `ConcatByName` stacks csvs vertically aligning the columns by
header name instead of by position: the result header row is the header row
of the first non-empty csv, followed by the header names that only appear in
later csvs, in order of first appearance. Each data row is copied with the
value of each column placed under its header name, and an empty string where
the csv has no column with that name. `ok` is false if there is no non-empty
csv, or a csv has duplicate header names (the result would be ambiguous).
When every csv has the same headers in the same order, `ConcatByName` is
equivalent to `Concat`:
january, _ := simplecsv.ReadCsvFile("january.csv") // columns: id, name
february, _ := simplecsv.ReadCsvFile("february.csv") // columns: name, bonus
combined, ok := simplecsv.ConcatByName(january, february)
DEDUPLICATE
`Unique` removes exact duplicate data rows: for each full row (all
columns) only the first occurrence is kept, in csv order. The header row
is kept:
unique := x.Unique()
`UniqueByFields` removes data rows that share the same key built from the
named columns; the first row per key is kept. `wasUnique` is false if the
csv is empty, no fields are given, or a field name does not exist:
x, wasUnique = x.UniqueByFields("email")
x, wasUnique = x.UniqueByFields("country", "city")
* DISTINCT AND COUNTS *
`Distinct` returns the distinct values of the data cells of a column, in
order of first appearance. The header cell is never included and the
returned slice is a copy:
values, wasRead := x.Distinct("Country")
`wasRead` is false if the csv is empty or the field name does not exist. A
csv with only the header row returns an empty slice and true.
`ValueCounts` returns a new csv with the fixed headers `value` and `count`:
one row per distinct value of the column, in order of first appearance,
with the number of data rows that have that value, as a decimal string.
The header cell is never counted and the original csv is not modified:
counts, wasRead := x.ValueCounts("Country")
`wasRead` is false if the csv is empty or the field name does not exist; in
that case a copy of the csv is returned.
`FacetCount` returns a map that counts how many times each string appears in
the data cells of a column. The header cell is never counted. Case does not
matter by default: `Foo`, `foo` and `FOO` are counted together under the
lower-case key `foo`:
counts, wasRead := x.FacetCount("Country")
`wasRead` is false if the csv is empty, the field name is empty, or the
field name does not exist; in that case an empty map is returned. A csv
with only the header row returns an empty map and true.
`FacetCountCaseSensitive` is the same but case matters: `Foo`, `foo` and
`FOO` are counted as separate entries:
counts, wasRead = x.FacetCountCaseSensitive("Country")
* GROUP BY *
`GroupBy` collapses the data rows into one output row per group, where a
group is all the data rows whose key fields have the same values. The
output header row is the key field names followed by the `As` name of each
aggregation; each output data row is the key values followed by one cell
per aggregation. Groups appear in order of first occurrence:
type Agg struct {
Field string // source column; ignored for AggCount
Op AggOp
As string // output header; required; must be unique among keys+As
}
The aggregation operations are:
- `AggCount` counts the data rows of the group. `Field` is ignored and may
be empty.
- `AggSum` adds the `Field` cells parsed with `strconv.ParseFloat`; cells
that don't parse as numbers count as 0.
- `AggMin` / `AggMax` use only finite numeric cells (NaN and infinities are
skipped); a group without any finite numeric cell produces an empty cell.
- `AggFirst` / `AggLast` take the `Field` value of the first and last data
row of the group.
- `AggJoin` joins the non-empty `Field` values of the group with ",".
Numeric results are formatted with `strconv.FormatFloat(f, 'f', -1, 64)`,
so integers have no decimal noise:
summary, wasGrouped := sales.GroupBy(
[]string{"country"},
[]Agg{{Op: AggCount, As: "orders"}, {Field: "amount", Op: AggSum, As: "total"}},
)
`wasGrouped` is false if the csv is empty, no keys or no aggregations are
given, a key or aggregation field does not exist, an `As` name is empty or
duplicates another key or `As` name, or an aggregation operation is not one
of the `AggOp` constants; in that case a copy of the csv is returned.
* CELLS *
GET
Get value of the cell in the second column, second row:
cellValue, cellExists := x.GetCell(1, 1)
Get the value of the cell in the column "Age", second row:
cellValue, cellExists := x.GetCellByField("Age", 1)
SET
Change the value of the cell in the first column (0) and the second row (1) to "27":
x, wasChanged = x.SetCell(0, 1, "27")
The same, using the column name instead of the column position:
x, wasChanged = x.SetCellByField("Age", 1, "27")
REPLACE IN FIELD
Replace the data cells of a column whose value is exactly equal to `old`
(case-sensitive, whole cell) with `new`. The header cell is not modified.
Useful to fix known bad values (`N/A` to empty) or rename codes:
x, wasReplaced = x.ReplaceInField("Status", "N/A", "")
TRIM
Remove the surrounding whitespace of every cell, including the header
cells, with strings.TrimSpace:
x, wasTrimmed = x.TrimSpace()
`wasTrimmed` is false if trimming makes two header names equal: header
names must stay unique.
* COLUMNS *
ADD
Add a column at the end of the CSV:
x, wasSuccessful = x.AddEmptyColumn("NewColumn")
REMOVE
Remove the column at position 1 (second column, because it's zero based):
x, wasRemoved = x.RemoveColumn(1)
Remove a column by name:
x, wasRemoved = x.RemoveColumnByName("Gender")
GET COLUMN VALUES
Get a copy of all the data cells of a column, skipping the header cell.
The returned slice is a copy: changes to it don't affect the csv.
`columnExists` is false if the csv is empty or the column position is not
valid:
columnCells, columnExists := x.GetColumn(1)
columnCells, fieldExists := x.GetColumnByField("Age")
SET COLUMN VALUES
Replace the data cells of a column with a slice. The slice must have the
same length as the number of data rows (the csv length minus the header
row), because every data row must keep exactly one cell in the column.
The header cell is not modified:
x, wasSet = x.SetColumn(1, []string{"24", "62", "45"})
x, wasSet = x.SetColumnByField("Age", []string{"24", "62", "45"})
MAP COLUMN VALUES
Transform the data cells of a column with a function. The function
receives the cell value and the csv row index (1 for the first data row);
the header cell is not transformed. The original csv is not modified:
x, wasMapped = x.MapColumnByField("Name", func(value string, row int) string {
return strings.ToUpper(value)
})
FILL COLUMN VALUES
Set every data cell of a column to the same value. Useful for constants
and defaults:
x, wasFilled = x.FillColumnByField("Source", "import")
* COLUMN SHAPE *
ADD AT POSITION
`AddEmptyColumnAt` inserts an empty column at a position: `index` is the
position of the new column and must be between 0 and the number of columns
(inclusive; inserting at the number of columns appends, like
`AddEmptyColumn`). The header cell of the new column is `columnName` and
every data cell is empty:
x, wasAdded = x.AddEmptyColumnAt("Source", 0)
x, wasAdded = x.AddEmptyColumnAt("Notes", 3)
`wasAdded` is false if the csv is empty, the column name already exists or
`index` is out of range.
ADD WITH VALUES
`AddColumnByField` appends a column with the header name `columnName` and
the given data cells. The values slice must have the same length as the
number of data rows (the csv length minus the header row), because every
data row must keep exactly one cell in the column; a csv with only the
header row takes an empty values slice. The values are copied:
x, wasAdded = x.AddColumnByField("Total", []string{"24", "62", "45"})
`wasAdded` is false if the csv is empty, the column name already exists or
the length of the values slice does not match the number of data rows.
COMPUTE FROM ROW MAP
`AddComputedColumn` appends a column whose data cells are computed by a
function from the values of the other columns. The function is called once
per data row, in csv order, with a map from header name to cell value: the
map is built fresh for every row and is a copy, so the callback can read
field names instead of column indexes, and mutating the map does not affect
the csv. The string the function returns becomes the cell of the new
column:
x, wasComputed = x.AddComputedColumn("full_name", func(row map[string]string) string {
return row["first"] + " " + row["last"]
})
`wasComputed` is false if the csv is empty or the column name already
exists; in that case a copy of the csv is returned. A csv with only the
header row takes the new header cell only and the function is not called.
RENAME BATCH
`RenameHeaders` renames several headers in one call. Every key of the map
must be an existing header, and the result must not contain duplicate
header names: a rename fails if a key does not exist, two keys map to the
same new name, or a renamed column collides with a header that is not
renamed. The renames are applied simultaneously, so a swap ("a" -> "b",
"b" -> "a") is applied correctly and map iteration order does not matter:
x, wasRenamed = x.RenameHeaders(map[string]string{"ID": "IdNumber", "Date": "Fecha"})
`wasRenamed` is false if the csv is empty or the renamed headers would
contain duplicates. Renaming a header to its own name is a no-op for that
column, and an empty map is a no-op that succeeds.
MOVE
`MoveColumn` moves the column with the header name `columnName` to position
`newIndex` (0 to the number of columns minus 1), shifting the columns in
between: the header and data cells of the moved column move together:
x, wasMoved = x.MoveColumn("Age", 0)
`wasMoved` is false if the csv is empty, the column name does not exist or
`newIndex` is out of range. Moving a column to its own position is a no-op
and succeeds.
SPLIT A FIELD
`SplitField` replaces the column with the header name `name` by
`len(newNames)` new columns in its position. Every data cell is split on
`sep` with `strings.Split`, and the parts fill the new columns in order: if
a cell has fewer parts than `newNames`, the remaining new columns get empty
cells; if it has more parts, the extra parts are dropped. The original
column is removed, so a new name may reuse it but must not collide with any
other header:
x, wasSplit = x.SplitField("coord", ",", []string{"lat", "lon"})
x, wasSplit = x.SplitField("last;first", ";", []string{"last", "first"})
`wasSplit` is false if the csv is empty, the field name does not exist,
`newNames` is empty or contains duplicates, or a new name collides with
another header.
COMBINE FIELDS
`CombineFields` appends a column with the header name `as` whose data cells
join the values of the named columns with `sep` (via `strings.Join`). The
source columns stay in place:
x, wasCombined = x.CombineFields([]string{"first", "last"}, " ", "full_name")
x, wasCombined = x.CombineFields([]string{"country", "sku"}, "-", "country_sku")
`wasCombined` is false if the csv is empty, `names` is empty, a name does
not exist, `names` repeats a field, or `as` already exists as a header.
* FIND *
FIND IN COLUMN
Find the word "27" in the first column (column 0):
rowsWithWord, validColumn := x.FindInColumn(0, "27")
It returns a slice of row numbers (int) where you can find the word in the column position. Please note that in simplecsv all cells are strings.
If it doesn't find the value, it returns an empty slice.
In `FindInColumn` and in `FindInField` case does not matter. Foo = foo = FOO.
FIND IN FIELD
The same as `FindInColumn` but using a column/field name instead of position. Please note that `FindInField`, unlike `FindInColumn` never includes the header in the search result.
rowsWithWord, validFieldName := x.FindInField("Age", "27")
If the field name does not exist, the second value returned (`validFieldName`) is false.
MATCH IN COLUMN
Find where results match a regular expression in the third column (column 2):
rowsWithWord, areParamsOk := x.MatchInColumn(2, "p([a-z]+)ch$")
Use ^ and $ in the regular expression to match exact results.
Matching is case-insensitive by default: Foo = foo = FOO. (This is achieved by prefixing the (?i) flag to the expression; you can still re-enable case-sensitivity inside the pattern with (?-i), or use MatchInColumnCaseSensitive for the whole match.)
MATCH IN FIELD
Same as with MatchInColumn, but with a field (column name). Find where results match a regular expression in the column "ID":
rowsWithWord, areParamsOk := x.MatchInField("ID", "p([a-z]+)ch$")
Please note that `MatchInField`, unlike `MatchInColumn` never includes the header in the search result.
Matching is case-insensitive by default: Foo = foo = FOO.
CASE SENSITIVE FIND
`FindInColumn`, `FindInField`, `MatchInColumn` and `MatchInField` ignore case by default. Use the `*CaseSensitive` variants when case matters:
rowsWithWord, validFieldName = x.FindInFieldCaseSensitive("Name", "Ana")
rowsWithWord, areParamsOk = x.MatchInFieldCaseSensitive("ID", "p([a-z]+)ch$")
* SORT *
SORT BY FIELD
Sorts the csv by a column name and returns a new sorted csv. The header row stays at the top and the original csv is not modified. Finite numbers are sorted numerically among themselves and appear before non-numeric values (including NaN and Inf), which are sorted as strings. The sort is stable.
sortedCsv, fieldExists := x.SortByField("Age", true)
SORT BY COLUMN
The same as `SortByField` but using a column position. It sorts all the rows, including the first one:
sortedCsv, validColumn := x.SortByColumn(0, true)
SORT BY MULTIPLE FIELDS
Sorts the csv by several columns, one level per field in order, like `ORDER
BY` in SQL: a later field is only compared when every earlier field compares
equal. The header row stays at the top and the original csv is not modified.
Each field uses the same ordering as `SortByField` (finite numbers
numerically, other values as strings), and the sort is stable. An empty
`ascending` sorts every field ascending; otherwise it has one bool per field
(`true` ascending, `false` descending):
sortedCsv, wereFieldsFound := x.SortByFields([]string{"Country", "City"}, nil)
sortedCsv, wereFieldsFound = x.SortByFields([]string{"Country", "City"}, []bool{true, false})
`wereFieldsFound` is false if the csv is empty, no fields are given, a field
name does not exist, or the length of `ascending` is neither 0 nor the
number of fields; in that case a copy of the csv is returned.
SORT AN INDEX
`SortIndex` returns a sorted copy of an index:
sortedIndex := simplecsv.SortIndex([]int{5, 1, 3})
* FILTER ROWS *
`FilterRows` returns a new csv with the rows where the predicate function returns true. If `header` is true, the first row is kept as the header:
adults := x.FilterRows(func(row []string) bool {
age, _ := strconv.Atoi(row[1])
return age >= 18
}, true)
FIELD FILTERS
`FilterByField` keeps the data rows where the predicate returns true for the
named column. The header cell is never passed to the predicate, and the
field name is used instead of a column index:
adults, wasFiltered := x.FilterByField("age", func(value string) bool {
n, _ := strconv.Atoi(value)
return n >= 18
})
`Where` keeps the data rows where the named column is exactly equal to
`value` (case-sensitive). `wasWhere` is false if the csv is empty or the
field name does not exist:
active, wasWhere := x.Where("status", "active")
`WhereFold` is the same but case-insensitive: `Active`, `active` and
`ACTIVE` all match:
active, wasWhereFold := x.WhereFold("status", "active")
* JOIN *
INNER JOIN
`JoinByField` joins two csvs by a common field and returns a new csv with the rows where the field has the same value in both csvs. The result has all the columns of the first csv, followed by the columns of the second csv except the join column. Non-join columns of the second csv must not share names with columns of the first; a collision is rejected so headers stay unique. If a join value shows up more than once, all combinations of rows are in the result. Values are compared exactly: case matters. The source csvs are not modified.
people, _ := simplecsv.ReadCsvFile("people.csv") // columns: ID, Name
ages, _ := simplecsv.ReadCsvFile("ages.csv") // columns: ID, Age
joined, fieldExistsInBoth := people.JoinByField(ages, "ID")
`fieldExistsInBoth` is false if the field does not exist in one of the csvs.
LEFT JOIN
`LeftJoinByField` is like `JoinByField`, but the rows of the first csv without a match in the second one are also in the result, with empty cells in the columns of the second csv:
joined, fieldExistsInBoth := people.LeftJoinByField(ages, "ID")
JOIN ON DIFFERENT KEY NAMES
Real files rarely share the same key name (`id` vs `customer_id`). `Join`
and `LeftJoin` join by one field name per csv, so no rename is needed: the
result is the same as joining on a common name. The join column of the
second csv is dropped from the result; the join column of the first csv is
kept.
orders, _ := simplecsv.ReadCsvFile("orders.csv") // columns: id, amount
joined, bothFieldsExist := people.Join(orders, "id", "customer_id")
`bothFieldsExist` is false if one of the fields does not exist in its csv.
`LeftJoin` is like `Join`, but the rows of the first csv without a match in
the second one are also in the result, with empty cells in the columns of the
second csv:
joined, bothFieldsExist := people.LeftJoin(orders, "id", "customer_id")
RIGHT JOIN
`RightJoin` is like `Join`, but every row of the second csv is in the result:
rows without a match in the first csv are included with empty cells in the
columns of the first csv, and rows of the first csv without a match are
dropped. The rows of the second csv that had no match are appended at the
end. Use it when the second file is the driver (e.g. a master product list):
joined, bothFieldsExist := people.RightJoin(orders, "id", "customer_id")
FULL JOIN
`FullJoin` is like `Join`, but every row of both csvs is in the result: rows
without a match are included with empty cells in the columns of the other
side. Use it to find unmatched keys on either side without two passes:
joined, bothFieldsExist := people.FullJoin(orders, "id", "customer_id")
SAME NAME JOIN
`RightJoinByField` and `FullJoinByField` are the same-name variants of
`RightJoin` and `FullJoin`, like `JoinByField`:
joined, fieldExistsInBoth := people.RightJoinByField(ages, "ID")
joined, fieldExistsInBoth := people.FullJoinByField(ages, "ID")
JOIN ON MULTIPLE COLUMNS
`JoinOn`, `LeftJoinOn`, `RightJoinOn` and `FullJoinOn` join on several
columns at once, for composite keys like `country` + `sku` or `date` +
`store`. The i-th name of the first list must be a column of the first csv,
the i-th name of the second list a column of the second csv, and the two
lists must have the same length (at least one name). A row of the first csv
is joined to a row of the second when the values of all its left key columns
are exactly equal to the values of the corresponding right key columns
(case matters). The join key is built with a length-prefixed encoding, so
values containing separators cannot collide. All the right key columns are
dropped from the result; the left key columns are kept. `wasJoined` is false
if a csv is empty, the lists have different lengths or are empty, a field
does not exist in its csv, or the result headers would collide:
orders, _ := simplecsv.ReadCsvFile("orders.csv") // columns: country, sku, amount
prices, _ := simplecsv.ReadCsvFile("prices.csv") // columns: country, sku, price
joined, wasJoined := orders.JoinOn(prices, []string{"country", "sku"}, []string{"country", "sku"})
`LeftJoinOn` is like `JoinOn`, but the rows of the first csv without a match
are also in the result, with empty cells in the columns of the second csv.
`RightJoinOn` keeps every row of the second csv, appending the unmatched
ones at the end with empty cells in the columns of the first csv. `FullJoinOn`
keeps every row of both csvs, with empty cells on the unmatched side. When
both field lists have a single name, the `*On` functions are equivalent to
their `Join` / `LeftJoin` / `RightJoin` / `FullJoin` counterparts.
MERGE COLUMNS
Sometimes two csvs are already row-aligned (same order, same length) and
only need their columns glued side by side; a join would be wrong or
wasteful. `MergeColumns` places the columns of other next to the columns of
s, row by row: the result header row is the header row of s followed by the
header row of other, and each result data row is the data row of s followed
by the data row of other in the same position. Both csvs must have the same
number of rows (header included); padding is not allowed. No header name of
other may collide with a header name of s, so header names stay unique.
`wasMerged` is false if a csv is empty, the row counts differ, or the result
headers would collide:
customers, _ := simplecsv.ReadCsvFile("customers.csv") // columns: id, name
emails, _ := simplecsv.ReadCsvFile("emails.csv") // columns: email, verified
merged, wasMerged := customers.MergeColumns(emails)
DIFF
"What changed between yesterday's export and today's?" `DiffByKey` compares
the data rows of s (left) and other (right), keyed by the values of the
column with the header name key. It returns three new csvs:
- `added`: the data rows of other whose key is not present in s, with
other's header row
- `removed`: the data rows of s whose key is not present in other, with
s's header row
- `changed`: the data rows of s whose key is present in other but whose
full row differs, with s's header row and s's values (join on the key if
you need the right-side values)
Each result keeps the rows in order of appearance in its source csv and is
an independent csv, so it can be written out or inspected on its own. The
key values must be unique within each csv: a key repeated in s or in other
makes the diff ambiguous, and it returns nil, nil, nil and false. It also
returns nil, nil, nil and false if either csv is empty or the key is not a
header name in either csv. A csv with only the header row is a valid input:
all the other side's data rows are then `added` or `removed`:
yesterday, _ := simplecsv.ReadCsvFile("yesterday.csv")
today, _ := simplecsv.ReadCsvFile("today.csv")
added, removed, changed, ok := yesterday.DiffByKey(today, "id")
* ERROR VARIANTS *
A boolean `ok` tells you that something failed but not why: "did the join
fail because a field is missing or because the result headers would
collide?" The `E` variants of the functions where the reason matters most
return an error instead, with a message prefixed with `simplecsv:` that
describes the problem. The bool-returning functions are unchanged, and the
`E` variants return the same csv the bool variants return on failure (an
independent copy of the receiver for methods; nil for `ConcatE` and
`ConcatByNameE`):
joined, err := people.JoinE(orders, "id", "customer_id")
if err != nil {
log.Fatal(err) // e.g. simplecsv: cannot join: key field "customer_id" not found in the right csv
}
- `JoinE` / `LeftJoinE` work like `Join` / `LeftJoin`. The error says which
csv is empty, which key field is missing in which csv, or which right
columns would collide with left columns:
joined, err := people.LeftJoinE(orders, "id", "customer_id")
if err != nil {
log.Fatal(err)
}
- `GroupByE` works like `GroupBy`. The error says whether the csv is empty,
no keys or aggregations are given, a key appears more than once, a key or
aggregation field does not exist, an `As` name is empty or duplicates
another key or `As` name, or an aggregation operation is invalid:
summary, err := sales.GroupByE(
[]string{"country"},
[]Agg{{Field: "amount", Op: AggSum, As: "total"}},
)
if err != nil {
log.Fatal(err)
}
- `ConcatE` / `ConcatByNameE` work like `Concat` / `ConcatByName`. The
error says whether no csv has a header row, a csv has different headers
(`ConcatE`), or a csv has duplicate header names (`ConcatByNameE`):
combined, err := simplecsv.ConcatE(day1, day2, day3)
if err != nil {
log.Fatal(err)
}
* BOOLEAN FUNCTIONS *
Use boolean functions AND, OR and NOT to combine indexes and produce other complex indexes that point to rows in the csv. Very useful to produce search results.
Indexes are slices of row numbers (integers between 0 or 1 and the length of the csv -1). The indexes returned by OrIndex, AndIndex and NotIndex are sorted in ascending order.
OR
The `OrIndex` function accepts any number of operands. With no operands it
returns an empty slice; with one operand it returns a sorted, de-duplicated
copy. With 2 or more operands it returns their union:
var w []int
w = simplecsv.OrIndex(a, b)
w = simplecsv.OrIndex(a, b, c, d, e)
AND
The `AndIndex` function accepts any number of operands. With no operands it
returns an empty slice; with one operand it returns a sorted, de-duplicated
copy. With 2 or more operands it returns their intersection:
var p []int
p = simplecsv.AndIndex(a, b)
p = simplecsv.AndIndex(a, b, c, d, e)
NOT
The code below returns the negative of the index `g`, between row 1 and row 4. If `g` is an index with the values `{1, 2}` the negative of `g` is `{3, 4}`. Because 3 and 4 are the integers between 1 and 4 that are not in `g`.
var g []int
min := 1
max := 4
p = simplecsv.NotIndex(g, min, max)
Note: For csvs with headers the min value is usually 1 and for csvs without headers the min value is usually 0.
* ONLY *
Only are 2 functions to simplify and sort a csv.
ONLY THIS ROWS
It removes rows that are not in the index and reorders a CSV by the index order. If header is true, it starts by the csv header. Note: if header is true and the index contains 0, the header row appears twice in the result (once as the header, once as row 0).
newIndex := []int{1, 3}
header := true
x, _ = x.OnlyThisRows(newIndex, header)
ONLY THIS FIELDS
Removes fields that are not in the list of fields, reorders the CSV by the list of fields and adds fields that do not exist as blank fields.
fieldsList := []string{"Age", "ID"}
x, _ = x.OnlyThisFields(fieldsList)
*/
package simplecsv