-
Notifications
You must be signed in to change notification settings - Fork 3
/
batch.go
317 lines (265 loc) · 8.01 KB
/
batch.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
package qbcli
import (
"encoding/csv"
"errors"
"fmt"
"io"
"os"
"sort"
"strconv"
"time"
"github.com/QuickBase/quickbase-cli/qbclient"
)
// ExportOptions are the options read through the command line.
type ExportOptions struct {
TableID string `validate:"required" cliutil:"option=table-id"`
Filepath string `cliutil:"option=file usage='file the data is exported to'"`
BatchSize int `cliutil:"option=batch-size default=10000"`
Delay int `cliutil:"option=delay"`
// Fields []int `cliutil:"option=fields"`
}
// Export exports data from a Quickbase table into an io.Writer.
func Export(qb *qbclient.Client, opts *ExportOptions) error {
var file io.Writer
if opts.Filepath != "" {
var err error
file, err = os.OpenFile(opts.Filepath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return fmt.Errorf("error opening file: %w", err)
}
} else {
file = os.Stdout
}
// Get the table's fields.
fields, err := GetTableSchema(qb, opts.TableID)
if err != nil {
return fmt.Errorf("error getting table metadata: %w", err)
}
// Build a list of every fid.
fids := []int{}
for _, field := range fields {
fids = append(fids, field.FieldID)
}
sort.Ints(fids)
writer := csv.NewWriter(file)
defer writer.Flush()
// Write the header.
header := make([]string, len(fids))
for idx, fid := range fids {
header[idx] = fields[fid].Label
}
writer.Write(header)
// Batch read records.
size := opts.BatchSize
skip := 0
for {
// Query records, sorted by record ID.
qri := &qbclient.QueryRecordsInput{
Select: fids,
From: opts.TableID,
SortBy: []*qbclient.QueryRecordsInputSortBy{
{FieldID: 3, Order: qbclient.SortByASC},
},
Options: &qbclient.QueryRecordsInputOptions{
Top: size,
Skip: skip,
},
}
qro, err := qb.QueryRecords(qri)
if err != nil {
return fmt.Errorf("error querying records: %w", err)
}
// Write the row data.
for _, record := range qro.Data {
row := make([]string, len(fids))
for idx, fid := range fids {
row[idx] = record[fid].Value.String()
}
writer.Write(row)
}
// Flush the buffer.
writer.Flush()
if err = writer.Error(); err != nil {
return err
}
// Increment skip for next page, break if on last page.
skip += size
if skip >= qro.Metadata.TotalRecords {
break
}
// Delay before the next API call.
if opts.Delay > 0 {
time.Sleep(time.Duration(opts.Delay) * time.Millisecond)
}
}
return nil
}
// ImportOptions are the options read through the command line.
type ImportOptions struct {
TableID string `validate:"required" cliutil:"option=table-id"`
Filepath string `cliutil:"option=file usage='file the data is imported from'"`
BatchSize int `cliutil:"option=batch-size default=10000"`
Map map[string]string `cliutil:"option=map"`
Delay int `cliutil:"option=delay"`
Timeout int `cliutil:"option=timeout default=5 usage='timeout in seconds waiting for data to be read from stdin'"`
MergeFieldID int `cliutil:"option=merge-field-id"`
// Fields []int `cliutil:"option=fields"`
}
// Import imports data from an io.Reader into a Quickbase table.
func Import(qb *qbclient.Client, opts *ImportOptions) (*qbclient.InsertRecordsOutputMetadata, error) {
metadata := &qbclient.InsertRecordsOutputMetadata{
CreatedRecordIDs: []int{},
LineErrors: map[string][]string{},
TotalNumberOfRecordsProcessed: 0,
UnchangedRecordIDs: []int{},
UpdatedRecordIDs: []int{},
}
var file io.Reader
if opts.Filepath != "" {
var err error
file, err = os.Open(opts.Filepath)
if err != nil {
return metadata, fmt.Errorf("error opening file: %w", err)
}
} else {
file = os.Stdin
if err := waitStdin(opts.Timeout); err != nil {
return metadata, err
}
}
// Get the table's fields.
fields, err := GetTableSchema(qb, opts.TableID)
if err != nil {
return metadata, fmt.Errorf("error getting table metadata: %w", err)
}
// Build a map of field label to fid.
lmap := make(map[string]int, len(fields))
for _, field := range fields {
lmap[field.Label] = field.FieldID
}
reader := csv.NewReader(file)
fmap := []int{}
// Batch write records.
line := 0
eof := false
records := []map[int]*qbclient.InsertRecordsInputData{}
for {
// Read each record from the CSV data.
// TODO better error handling.
row, err := reader.Read()
if err == io.EOF {
eof = true
} else if err != nil {
return metadata, fmt.Errorf("error reading line %v: %w", line, err)
}
// If first line, map the header to field IDs.
// Otherwise, build the data records.
if !eof {
if line == 0 {
for _, label := range row {
// Check the field label map first.
if destLabel, ok := opts.Map[label]; ok {
label = destLabel
}
// Now get the field ID.
fid, ok := lmap[label]
if !ok {
return metadata, fmt.Errorf("%s field not in destination table", label)
}
// Append the fid from the field map.
fmap = append(fmap, fid)
}
} else {
record := make(map[int]*qbclient.InsertRecordsInputData)
for idx, data := range row {
// TODO defensive coding ...
fid := fmap[idx]
// We cannot insert record metadata.
if fid != 3 && fid <= 5 {
continue
}
// Skip the record ID if it isn't the merge field.
if fid == 3 && opts.MergeFieldID != 3 {
continue
}
// TODO defensive coding ...
ftype := fields[fid].Type
// Create a *qbclient.Value from the string value and field type.
val, err := qbclient.NewValueFromString(data, ftype)
if err != nil {
return metadata, fmt.Errorf("value invalid for field %v: %w", fid, err)
}
// Add the value to the record .
record[fid] = &qbclient.InsertRecordsInputData{Value: val}
}
records = append(records, record)
}
}
// Write the batch if we hit the batch size of the end of the data set.
if len(records) >= opts.BatchSize || (len(records) > 0 && eof) {
input := &qbclient.InsertRecordsInput{
To: opts.TableID,
Data: records,
MergeFieldID: opts.MergeFieldID,
}
iro, err := qb.InsertRecords(input)
if err != nil {
return metadata, fmt.Errorf("error inserting records: %w", err)
}
// Empty the records for the next batch.
rlen := len(records)
records = []map[int]*qbclient.InsertRecordsInputData{}
metadata.CreatedRecordIDs = append(metadata.CreatedRecordIDs, iro.Metadata.CreatedRecordIDs...)
metadata.TotalNumberOfRecordsProcessed += iro.Metadata.TotalNumberOfRecordsProcessed
metadata.UnchangedRecordIDs = append(metadata.UnchangedRecordIDs, iro.Metadata.UnchangedRecordIDs...)
metadata.UpdatedRecordIDs = append(metadata.UpdatedRecordIDs, iro.Metadata.UpdatedRecordIDs...)
// Merging the line errors isn't so simple.
for k, v := range iro.Metadata.LineErrors {
n, err := strconv.Atoi(k)
if err != nil {
return metadata, fmt.Errorf("%s: expecting lineErrors key to be an integer", k)
}
// This works no matter the batch size, but I have no idea why
// we have to subtract 1 from n when eof is true. If this is
// buggy, blame cpliakas@quickbase.com.
n = line - rlen + n
if eof {
n--
}
metadata.LineErrors[strconv.Itoa(n)] = v
}
// Delay before the next API call.
if opts.Delay > 0 && !eof {
time.Sleep(time.Duration(opts.Delay) * time.Millisecond)
}
}
// Break if we are at the end of the file.
if eof {
break
}
line++
}
return metadata, nil
}
// TODO move this to cliutil.
func waitStdin(wiat int) error {
tick := time.Tick(100 * time.Millisecond)
timeout := time.After(time.Duration(wiat) * time.Second)
done := make(chan bool, 1)
for {
select {
case <-tick:
stat, err := os.Stdin.Stat()
if err != nil {
return fmt.Errorf("error getting info for stdin: %w", err)
}
if stat.Size() > 0 {
done <- true
}
case <-done:
return nil
case <-timeout:
return errors.New("timeout: no data read from stdin")
}
}
}