Debian Codegraph @

surrogate-keys.go

raw symbols SCIP
1 package csv
2
3 import (
4 "github.com/wildducktheories/go-csv/utils"
5
6 "crypto/md5"
7 "fmt"
8 )
9
10 // Given a header-prefixed input stream of CSV records and the specification of a natural key (NaturalKeys)
11 // generate an augmented, header-prefixed, output stream of CSV records which contains a surrogate
12 // key (SurrogateKey) that is derived from the MD5 sum of the natural key.
13 //
14 // The surrogate key is constructed by calculating the MD5 hash of the string representation of a CSV record that contains the fields of the natural key
15 // of each record.
16 //
17 // For example, given the following input CSV stream which has a natural key of Date,Amount,Sequence
18 // Date,Amount,Description,Sequence
19 // 2014/12/31,100.0,Payment
20 // 2014/12/31,100.0,Payment,1
21 // 2014/12/31,85.0,Payment
22 //
23 // generate an additional column, KeyMD5, containing a surrogate key that represents the natural key.
24 //
25 // Date,Amount,Description,Sequence,KeyMD5
26 // 2014/12/31,100.0,Payment,"",bead7c34cf0828efb8a240e262e7afea
27 // 2014/12/31,100.0,Payment,1,cc8ab528163236eb1aa4004202ee1935
28 // 2014/12/31,85.0,Payment,"",8f4d3a8a05031256a4fa4cf1fadd757b
29 //
30 type SurrogateKeysProcess struct {
31 NaturalKeys []string
32 SurrogateKey string
33 }
34
35 func (p *SurrogateKeysProcess) Run(reader Reader, builder WriterBuilder, errCh chan<- error) {
36 errCh <- func() (err error) {
37 defer reader.Close()
38
39 naturalKeys := p.NaturalKeys
40 surrogateKey := p.SurrogateKey
41
42 // create a stream from the header
43 dataHeader := reader.Header()
44
45 i, a, _ := utils.Intersect(naturalKeys, dataHeader)
46 if len(a) > 0 {
47 return fmt.Errorf("%s does not exist in the data header", Format(a))
48 }
49
50 i, a, _ = utils.Intersect([]string{surrogateKey}, dataHeader)
51 if len(i) != 0 {
52 return fmt.Errorf("%s already exists in data header", i[0])
53 }
54
55 // create a new output stream
56 augmentedHeader := make([]string, len(dataHeader)+1)
57 copy(augmentedHeader, dataHeader)
58 augmentedHeader[len(dataHeader)] = surrogateKey
59
60 writer := builder(augmentedHeader)
61 defer writer.Close(err)
62 for data := range reader.C() {
63 augmentedData := writer.Blank()
64 key := make([]string, len(naturalKeys))
65 for i, h := range naturalKeys {
66 key[i] = data.Get(h)
67 }
68 formattedKey := Format(key)
69
70 hash := fmt.Sprintf("%x", md5.Sum([]byte(formattedKey)))
71 augmentedData.PutAll(data)
72 augmentedData.Put(surrogateKey, hash)
73 if err := writer.Write(augmentedData); err != nil {
74 return err
75 }
76 }
77 return reader.Error()
78 }()
79 }