Debian Codegraph @

uniquify.go

raw symbols SCIP
1 package csv
2
3 import (
4 "fmt"
5 "github.com/wildducktheories/go-csv/utils"
6 )
7
8 // Given a header-prefixed input stream of CSV records and the specification of a partial key (PartialKey)
9 // formed from one or more of the fields, generate an augmented, header-prefixed, stream of CSV records
10 // such that the augmented key of each output record is unique. The field used to ensure uniqueness is
11 // specified by the AdditionalKey option.
12 //
13 // For example, given the following input with the partial key Date,Amount
14 //
15 // Date,Amount,Description
16 // 2014/12/31,100.0,Payment
17 // 2014/12/31,100.0,Payment
18 // 2014/12/31,85.0,Payment
19 //
20 // Generate an additional column, Sequence, such that the augmented key Date,Amount,Sequence is unique
21 // for all input records.
22 //
23 // Date,Amount,Description,Sequence
24 // 2014/12/31,100.0,Payment,
25 // 2014/12/31,100.0,Payment,1
26 // 2014/12/31,85.0,Payment,
27 type UniquifyProcess struct {
28 PartialKeys []string
29 AdditionalKey string
30 }
31
32 func (p *UniquifyProcess) Run(reader Reader, builder WriterBuilder, errCh chan<- error) { // check that the partial keys exist in the dataHeader
33 defer reader.Close()
34 var line = 0
35 var failed = true
36 var err error
37
38 defer func() {
39 if failed {
40 if err == nil {
41 err = fmt.Errorf("failed at line: %d", line+1)
42 } else {
43 err = fmt.Errorf("failed at line: %d: %s", line+1, err)
44 }
45 }
46 errCh <- err
47 }()
48
49 partialKeys := p.PartialKeys
50 additionalKey := p.AdditionalKey
51
52 line = 1
53
54 // create a stream from the header
55 dataHeader := reader.Header()
56
57 i, a, _ := utils.Intersect(partialKeys, dataHeader)
58 if len(a) > 0 {
59 err = fmt.Errorf("%s does not exist in the data header", Format(a))
60 return
61 }
62
63 i, a, _ = utils.Intersect([]string{additionalKey}, dataHeader)
64 if len(i) != 0 {
65 err = fmt.Errorf("%s already exists in data header", i[0])
66 return
67 }
68
69 augmentedHeader := make([]string, len(dataHeader)+1)
70 copy(augmentedHeader, dataHeader)
71 augmentedHeader[len(dataHeader)] = additionalKey
72
73 keys := make(map[string]int)
74
75 writer := builder(augmentedHeader)
76 defer writer.Close(err)
77
78 for data := range reader.C() {
79 line++
80 augmentedData := writer.Blank()
81 key := make([]string, len(partialKeys))
82 for i, h := range partialKeys {
83 key[i] = data.Get(h)
84 }
85 formattedKey := Format(key)
86 additionalKeyValue, ok := keys[formattedKey]
87 if !ok {
88 additionalKeyValue = 0
89 } else {
90 additionalKeyValue++
91 }
92 keys[formattedKey] = additionalKeyValue
93 augmentedData.PutAll(data)
94 if additionalKeyValue > 0 {
95 augmentedData.Put(additionalKey, fmt.Sprintf("%d", additionalKeyValue))
96 }
97 writer.Write(augmentedData)
98 }
99 failed = false
100 err = reader.Error()
101 }