-
Notifications
You must be signed in to change notification settings - Fork 5
/
csv.go
357 lines (285 loc) · 6.74 KB
/
csv.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
// This module implements a CSV reader for reading facts from CSV-like formatted data.
//
// The following fields are supported:
//
// - Domain - The domain the fact will be asserted in. This is only required for bulk-formatted data, otherwise it is ignored.
// - Operation - The operation to apply to this fact. Optional, defaults to "assert".
// - Valid Time - The time this fact should be considered valid. This is separate from the "database time" which denotes when the fact was physically added. Optional, defaults to "now".
// - Entity Domain - The domain of the entity. Optional, defaults to the fact domain.
// - Entity - The local name of the attribute.
// - Attribute Domain - The domain of the attribute. Optional, defaults to the fact domain.
// - Attribute - The local name of the attribute.
// - Value Domain - The domain of the value. Optional, defaults to the fact domain.
// - Value - The local name of the value.
//
// As noted, most of these fields are optional so they do not need to be included in the file. To do this, a header must be present using the above names to denote the field a column corresponds to. For example, this is a valid file:
//
// entity,attribute,value
// bill,likes,soccer
// bill,likes,fútbol
// soccer,is,fútbol
//
// Applying this to the domain "sports", this will expand out to:
//
// domain,operation,time,entity domain,entity,attribute domain,attribute,value domain,value
// sports,assert,now,sports,bill,sports,likes,sports,soccer
// sports,assert,now,sports,bill,sports,likes,sports,fútbol
// sports,assert,now,sports,soccer,sports,is,sports,fútbol
//
// The time "now" will be transaction time when it is committed to the database.
//
// At a minimum, the entity, attribute, and value fields must be present.
package origins
import (
"encoding/csv"
"errors"
"fmt"
"io"
"strings"
"github.com/Sirupsen/logrus"
"github.com/chop-dbhi/origins/chrono"
)
var (
ErrHeaderRequired = errors.New("A header is required with field names.")
ErrRequiredFields = errors.New("The entity, attribute, and value fields are required.")
)
var csvHeader = []string{
"domain",
"operation",
"transaction",
"time",
"entity_domain",
"entity",
"attribute_domain",
"attribute",
"value_domain",
"value",
}
// parseHeader normalizes the header fields so they can be mapped to the
func parseHeader(r []string) (map[string]int, error) {
h := make(map[string]int, len(r))
var e, a, v bool
for i, f := range r {
if f == "" {
continue
}
f = strings.ToLower(f)
f = strings.TrimLeft(f, "# ")
f = strings.Replace(f, " ", "_", -1)
switch f {
case "entity":
e = true
case "attribute":
a = true
case "value":
v = true
}
// Alias
if f == "valid_time" {
f = "time"
}
h[f] = i
}
if !e || !a || !v {
return nil, ErrRequiredFields
}
return h, nil
}
// isEmptyRecord returns true if all of the values are empty strings.
func isEmptyRecord(r []string) bool {
for _, v := range r {
if v != "" {
return false
}
}
return true
}
type CSVReader struct {
reader *csv.Reader
header map[string]int
fact *Fact
err error
}
func (r *CSVReader) parse(record []string) (*Fact, error) {
// Map row values to fact fields.
var (
ok bool
err error
idx, rlen int
val string
dom string
f = Fact{}
)
rlen = len(record)
// Domain
if idx, ok = r.header["domain"]; ok && idx < rlen {
f.Domain = record[idx]
}
// Operation
if idx, ok = r.header["operation"]; ok && idx < rlen {
op, err := ParseOperation(record[idx])
if err != nil {
logrus.Error(err)
return nil, err
}
f.Operation = op
}
// Valid time
if idx, ok = r.header["time"]; ok && idx < rlen {
val = record[idx]
if val != "" {
t, err := chrono.Parse(val)
if err != nil {
logrus.Error(err)
return nil, err
}
f.Time = t
}
}
var ident *Ident
// Entity
idx, _ = r.header["entity"]
val = record[idx]
if idx, ok = r.header["entity_domain"]; ok && idx < rlen {
dom = record[idx]
} else {
dom = ""
}
if ident, err = NewIdent(dom, val); err != nil {
return nil, err
}
f.Entity = ident
// Attribute
idx, _ = r.header["attribute"]
val = record[idx]
if idx, ok = r.header["attribute_domain"]; ok && idx < rlen {
dom = record[idx]
} else {
dom = ""
}
if ident, err = NewIdent(dom, val); err != nil {
return nil, err
}
f.Attribute = ident
// Value
idx, _ = r.header["value"]
val = record[idx]
if idx, ok = r.header["value_domain"]; ok && idx < rlen {
dom = record[idx]
} else {
dom = ""
}
if ident, err = NewIdent(dom, val); err != nil {
return nil, err
}
f.Value = ident
return &f, nil
}
// scan reads the CSV file for the next fact.
func (r *CSVReader) next() (*Fact, error) {
var (
err error
record []string
fact *Fact
)
// Logic defined in a loop to skip comments.
for {
record, err = r.reader.Read()
if err != nil {
break
}
// Line with all empty strings.
if isEmptyRecord(record) {
continue
}
if record[0] != "" && record[0][0] == '#' {
continue
}
// Parse first non-comment line as header
if r.header == nil {
h, err := parseHeader(record)
if err != nil {
break
}
r.header = h
continue
}
fact, err = r.parse(record)
break
}
if err != nil && err != io.EOF {
logrus.Error("csv:", err)
}
return fact, err
}
// Next returns the next fact in the stream.
func (r *CSVReader) Next() *Fact {
if r.err != nil {
return nil
}
// Scan for the next fact and queue it.
f, err := r.next()
// Error reading the next fact.
if err != nil {
r.err = err
return nil
}
return f
}
// Err returns the error produced while reading.
func (r *CSVReader) Err() error {
// EOF is an implementation detail of the underlying stream.
if r.err == io.EOF {
return nil
}
return r.err
}
func NewCSVReader(r io.Reader) *CSVReader {
cr := csv.NewReader(r)
// Set CSV parameters
cr.LazyQuotes = true
cr.TrimLeadingSpace = true
// Fixed set of fields are required, however they are variable based
// on the header.
cr.FieldsPerRecord = -1
return &CSVReader{
reader: cr,
}
}
type CSVWriter struct {
writer *csv.Writer
started bool
}
func (w *CSVWriter) Write(f *Fact) error {
if !w.started {
w.writer.Write(csvHeader)
w.started = true
}
// Encode empty transaction as a empty string.
var txs string
if f.Transaction > 0 {
txs = fmt.Sprint(f.Transaction)
}
w.writer.Write([]string{
f.Domain,
f.Operation.String(),
txs,
chrono.Format(f.Time),
f.Entity.Domain,
f.Entity.Name,
f.Attribute.Domain,
f.Attribute.Name,
f.Value.Domain,
f.Value.Name,
})
return w.writer.Error()
}
func (w *CSVWriter) Flush() error {
w.writer.Flush()
return w.writer.Error()
}
func NewCSVWriter(w io.Writer) *CSVWriter {
return &CSVWriter{
writer: csv.NewWriter(w),
}
}