forked from fhirbase/fhirbase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
load.go
956 lines (721 loc) · 18.7 KB
/
load.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
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
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
package main
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"strings"
"text/tabwriter"
"time"
"compress/gzip"
"github.com/jackc/pgx"
"github.com/jackc/pgx/pgtype"
jsoniter "github.com/json-iterator/go"
"github.com/pkg/errors"
uuid "github.com/satori/go.uuid"
"github.com/urfave/cli"
"github.com/vbauerster/mpb"
"github.com/vbauerster/mpb/decor"
)
type bundleType int
type bundleFile struct {
file *os.File
gzr *gzip.Reader
}
func openFile(fileName string) (*bundleFile, error) {
result := new(bundleFile)
f, err := os.OpenFile(fileName, os.O_RDONLY, 0644)
if err != nil {
return nil, errors.Wrap(err, "cannot open bundle file")
}
result.file = f
gzr, err := gzip.NewReader(result.file)
if err != nil {
result.file.Seek(0, 0)
result.gzr = nil
} else {
result.gzr = gzr
}
return result, nil
}
func (bf *bundleFile) Read(p []byte) (n int, err error) {
if bf.gzr != nil {
return bf.gzr.Read(p)
}
return bf.file.Read(p)
}
func (bf *bundleFile) Close() {
defer bf.file.Close()
if bf.gzr != nil {
bf.gzr.Close()
}
}
func (bf *bundleFile) Rewind() {
bf.file.Seek(0, 0)
if bf.gzr != nil {
bf.gzr.Close()
bf.gzr.Reset(bf.file)
}
}
const (
ndjsonBundleType bundleType = iota
fhirBundleType
singleResourceBundleType
unknownBundleType
)
type bundle interface {
Next() (map[string]interface{}, error)
Close()
Count() int
}
type loaderCb func(curType string, duration time.Duration)
type loader interface {
Load(db *pgx.Conn, bndl bundle, cb loaderCb) error
}
type copyFromBundleSource struct {
bndl bundle
err error
res map[string]interface{}
cb loaderCb
currentRt string
prevTime time.Time
fhirVersion string
}
func isCompleteJSONObject(s string) bool {
numBraces := 0
inString := false
escaped := false
for _, b := range s {
if !escaped {
if !inString {
if b == '{' {
numBraces = numBraces + 1
} else if b == '}' {
numBraces = numBraces - 1
} else if b == '"' {
inString = true
}
} else {
if b == '"' {
inString = false
} else if b == '\\' {
escaped = true
}
}
} else {
escaped = false
}
}
return numBraces == 0
}
func guessJSONBundleType(r io.Reader) (bundleType, error) {
iter := jsoniter.Parse(jsoniter.ConfigFastest, r, 32*1024)
if iter.WhatIsNext() != jsoniter.ObjectValue {
return unknownBundleType, fmt.Errorf("Expecting to get JSON object at the root of the resource")
}
for k := iter.ReadObject(); k != ""; k = iter.ReadObject() {
if k == "resourceType" {
rt := iter.ReadString()
if rt == "Bundle" {
return fhirBundleType, nil
} else if rt != "" {
return singleResourceBundleType, nil
}
return unknownBundleType, nil
}
iter.Skip()
}
return fhirBundleType, nil
}
func guessBundleType(f io.Reader) (bundleType, error) {
rdr := bufio.NewReader(f)
firstLine, err := rdr.ReadString('\n')
if err != nil {
if err == io.EOF {
// only one line is available
return guessJSONBundleType(strings.NewReader(firstLine))
}
return unknownBundleType, err
}
secondLine, err := rdr.ReadString('\n')
if err != nil && err != io.EOF {
return unknownBundleType, err
}
if isCompleteJSONObject(firstLine) && isCompleteJSONObject(secondLine) {
return ndjsonBundleType, nil
}
return guessJSONBundleType(io.MultiReader(strings.NewReader(firstLine),
strings.NewReader(secondLine), rdr))
}
func newCopyFromBundleSource(bndl bundle, fhirVersion string, cb loaderCb) *copyFromBundleSource {
s := new(copyFromBundleSource)
s.bndl = bndl
s.err = nil
s.cb = cb
res, _ := bndl.Next()
rt, _ := res["resourceType"].(string)
s.res = res
s.currentRt = rt
s.prevTime = time.Now()
s.fhirVersion = fhirVersion
return s
}
func (s *copyFromBundleSource) Next() bool {
if s.res != nil {
return true
}
res, err := s.bndl.Next()
if err != nil {
s.res = nil
if err != io.EOF {
s.err = err
} else {
s.currentRt = ""
s.err = nil
}
return false
}
nextResourceType, _ := res["resourceType"].(string)
if nextResourceType != s.currentRt {
s.currentRt = nextResourceType
s.res = res
s.prevTime = time.Now()
s.err = nil
return false
}
s.res = res
s.err = nil
return true
}
func (s *copyFromBundleSource) ResourceType() string {
return s.currentRt
}
func (s *copyFromBundleSource) Values() ([]interface{}, error) {
if s.res != nil {
res := s.res
s.res = nil
res, err := doTransform(res, s.fhirVersion)
if err != nil {
return nil, errors.Wrap(err, "cannot perform transform")
}
id, ok := res["id"].(string)
if !ok {
id = uuid.NewV4().String()
}
d := time.Since(s.prevTime)
s.prevTime = time.Now()
s.cb(s.currentRt, d)
return []interface{}{id, 0, "created", res}, nil
}
return nil, fmt.Errorf("No resource in the source")
}
func (s *copyFromBundleSource) Err() error {
return s.err
}
type singleResourceBundle struct {
file *bundleFile
alreadyRead bool
}
func newSingleResourceBundle(f *bundleFile) (*singleResourceBundle, error) {
b := new(singleResourceBundle)
b.file = f
b.alreadyRead = false
return b, nil
}
func (b *singleResourceBundle) Close() {
b.file.Close()
}
func (b *singleResourceBundle) Count() int {
return 1
}
func (b *singleResourceBundle) Next() (map[string]interface{}, error) {
if b.alreadyRead {
return nil, io.EOF
}
content, err := ioutil.ReadAll(b.file)
if err != nil {
return nil, errors.Wrap(err, "cannot read file content")
}
iter := jsoniter.ConfigFastest.BorrowIterator(content)
defer jsoniter.ConfigFastest.ReturnIterator(iter)
res := iter.Read()
if res == nil {
return nil, errors.Wrap(iter.Error, "cannot read resource from file")
}
resMap, ok := res.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("got non-object value in the entries array")
}
b.alreadyRead = true
return resMap, nil
}
type ndjsonBundle struct {
count int
file *bundleFile
reader *bufio.Reader
curline int
}
type fhirBundle struct {
count int
file *bundleFile
curline int
iter *jsoniter.Iterator
}
func (b *fhirBundle) Close() {
b.file.Close()
}
func (b *fhirBundle) Count() int {
return b.count
}
func (b *fhirBundle) Next() (map[string]interface{}, error) {
if !b.iter.ReadArray() {
return nil, io.EOF
}
entry := b.iter.Read()
if entry == nil {
return nil, b.iter.Error
}
entryMap, ok := entry.(map[string]interface{})
if !ok {
fmt.Printf("%s: got non-object value in the entries array, skipping rest of the file\n", b.file.file.Name())
return nil, io.EOF
}
res, ok := entryMap["resource"]
if !ok {
fmt.Printf("%s: cannot get entry.resource attribute, skipping rest of the file\n", b.file.file.Name())
return nil, io.EOF
}
resMap, ok := res.(map[string]interface{})
if !ok {
fmt.Printf("%s: got non-object value at entry.resource, skipping rest of the file\n", b.file.file.Name())
return nil, io.EOF
}
return resMap, nil
}
func newFhirBundle(f *bundleFile) (*fhirBundle, error) {
var result fhirBundle
result.file = f
result.iter = jsoniter.Parse(jsoniter.ConfigFastest, result.file, 32*1024)
err := goToEntriesInFhirBundle(result.iter)
if err != nil {
return nil, errors.Wrap(err, "cannot find `entry` key in the bundle")
}
linesCount, err := countEntriesInBundle(result.iter)
result.file.Rewind()
result.iter.Reset(result.file)
if err != nil {
return nil, errors.Wrap(err, "cannot reset fhir bundle iterator")
}
err = goToEntriesInFhirBundle(result.iter)
if err != nil {
return nil, errors.Wrap(err, "cannot find `entry` key in the bundle")
}
result.count = linesCount
return &result, nil
}
func (b *ndjsonBundle) Close() {
b.file.Close()
}
func (b *ndjsonBundle) Count() int {
return b.count
}
func (b *ndjsonBundle) Next() (map[string]interface{}, error) {
line, err := b.reader.ReadBytes('\n')
iter := jsoniter.ConfigFastest.BorrowIterator(line)
defer jsoniter.ConfigFastest.ReturnIterator(iter)
if err != nil {
return nil, err
}
if iter.WhatIsNext() != jsoniter.ObjectValue {
fmt.Printf("%s: Expecting to get JSON object at the root of the resource, got `%s` at line %d, skipping rest of the file\n", b.file.file.Name(), strings.Trim(string(line), "\n"), b.curline)
return nil, io.EOF
}
b.curline++
result := iter.Read()
return result.(map[string]interface{}), iter.Error
}
func newNdjsonBundle(f *bundleFile) (*ndjsonBundle, error) {
var result ndjsonBundle
result.file = f
result.reader = bufio.NewReader(result.file)
linesCount, err := countLinesInReader(result.reader)
if err != nil {
return nil, errors.Wrap(err, "cannot count lines in ndjson bundle")
}
result.file.Rewind()
result.count = linesCount
return &result, nil
}
type multifileBundle struct {
count int
bundles []bundle
currentBndlIdx int
}
func newMultifileBundle(fileNames []string) (*multifileBundle, error) {
var result multifileBundle
result.bundles = make([]bundle, 0, len(fileNames))
result.count = 0
result.currentBndlIdx = 0
for _, fileName := range fileNames {
f, err := openFile(fileName)
if err != nil {
fmt.Printf("Cannot open %s: %v\n", fileName, err)
continue
}
bndlType, err := guessBundleType(f)
if err != nil {
fmt.Printf("Cannot determine type of %s: %v\n", fileName, err)
f.Close()
continue
}
f.Rewind()
var bndl bundle
if bndlType == ndjsonBundleType {
bndl, err = newNdjsonBundle(f)
} else if bndlType == fhirBundleType {
bndl, err = newFhirBundle(f)
} else if bndlType == singleResourceBundleType {
bndl, err = newSingleResourceBundle(f)
} else {
fmt.Printf("cannot create bundle for %s\n", fileName)
continue
}
if err != nil {
fmt.Printf("%s: cannot create bundle\n%e\n", f.file.Name(), err)
defer f.Close()
bndl = nil
}
if bndl != nil {
result.bundles = append(result.bundles, bndl)
result.count = result.count + bndl.Count()
}
}
return &result, nil
}
func (b *multifileBundle) Count() int {
return b.count
}
func (b *multifileBundle) Close() {
for _, bndl := range b.bundles {
if bndl != nil {
b.Close()
}
}
b.currentBndlIdx = -1
}
func (b *multifileBundle) Next() (map[string]interface{}, error) {
if b.currentBndlIdx >= len(b.bundles) {
return nil, io.EOF
}
currentBndl := b.bundles[b.currentBndlIdx]
// if b.currentBndl == nil {
// b.currentBndlIdx = b.currentBndlIdx + 1
// if b.currentBndlIdx > len(b.fileNames)-1 {
// return nil, io.EOF
// }
// currentBndl, err := newFhirBundle(b.fileNames[b.currentBndlIdx])
// if err != nil {
// b.currentBndlIdx = b.currentBndlIdx + 1
// return nil, errors.Wrap(err, "cannot create bundle")
// }
// b.currentBndl = currentBndl
// }
res, err := currentBndl.Next()
if err != nil {
if err == io.EOF {
currentBndl.Close()
b.bundles[b.currentBndlIdx] = nil
b.currentBndlIdx = b.currentBndlIdx + 1
return b.Next()
}
return nil, errors.Wrap(err, "cannot read next entry from bundle")
}
return res, nil
}
// PrintMemUsage outputs the current, total and OS memory being used. As well as the number
// of garage collection cycles completed.
func PrintMemUsage() {
var m runtime.MemStats
runtime.ReadMemStats(&m)
// For info on each, see: https://golang.org/pkg/runtime/#MemStats
fmt.Printf("Alloc = %v MiB", bToMb(m.Alloc))
fmt.Printf("\tTotalAlloc = %v MiB", bToMb(m.TotalAlloc))
fmt.Printf("\tSys = %v MiB", bToMb(m.Sys))
fmt.Printf("\tNumGC = %v\n\n", m.NumGC)
}
func bToMb(b uint64) uint64 {
return b / 1024 / 1024
}
func countLinesInReader(r io.Reader) (int, error) {
buf := make([]byte, 32*1024)
count := 0
lineSep := []byte{'\n'}
for {
c, err := r.Read(buf)
count += bytes.Count(buf[:c], lineSep)
switch {
case err == io.EOF:
return count, nil
case err != nil:
return count, err
}
}
}
func goToEntriesInFhirBundle(iter *jsoniter.Iterator) error {
if iter.WhatIsNext() != jsoniter.ObjectValue {
return fmt.Errorf("Expecting to get JSON object at the root of the FHIR Bundle")
}
curAttr := iter.ReadObject()
for curAttr != "" {
if curAttr == "entry" && iter.WhatIsNext() == jsoniter.ArrayValue {
return nil
}
iter.Skip()
curAttr = iter.ReadObject()
}
return io.EOF
}
func countEntriesInBundle(iter *jsoniter.Iterator) (int, error) {
count := 0
for iter.ReadArray() {
count = count + 1
iter.Skip()
}
return count, nil
}
type copyLoader struct {
fhirVersion string
}
type insertLoader struct {
fhirVersion string
}
type upInsertLoader struct {
fhirVersion string
}
func (l *copyLoader) Load(db *pgx.Conn, bndl bundle, cb loaderCb) error {
src := newCopyFromBundleSource(bndl, l.fhirVersion, cb)
for src.ResourceType() != "" {
tableName := strings.ToLower(src.ResourceType())
_, err := db.CopyFrom(pgx.Identifier{tableName}, []string{"id", "txid", "status", "resource"}, src)
if err != nil {
return errors.Wrap(err, "cannot perform COPY command")
}
}
return nil
}
func (l *upInsertLoader) Load(db *pgx.Conn, bndl bundle, cb loaderCb) error {
batch := db.BeginBatch()
curResource := uint(0)
totalCount := uint(bndl.Count())
batchSize := uint(200)
var err error
for err == nil {
startTime := time.Now()
var resource map[string]interface{}
resource, err = bndl.Next()
if err == nil {
transformedResource, err := doTransform(resource, l.fhirVersion)
if err != nil {
fmt.Printf("Error during FB transform: %v\n", err)
}
resourceType, _ := resource["resourceType"].(string)
id, ok := resource["id"].(string)
if !ok || id == "" {
batch.Queue("SELECT fhirbase_create($1)", []interface{}{transformedResource}, []pgtype.OID{pgtype.JSONBOID}, nil)
} else {
batch.Queue("SELECT fhirbase_update($1)", []interface{}{transformedResource}, []pgtype.OID{pgtype.JSONBOID}, nil)
}
if curResource%batchSize == 0 || curResource == totalCount-1 {
batch.Send(context.Background(), nil)
batch.Close()
if curResource != totalCount-1 {
batch = db.BeginBatch()
} else {
batch = nil
}
}
curResource++
cb(resourceType, time.Since(startTime))
}
}
if batch != nil {
batch.Send(context.Background(), nil)
batch.Close()
}
return nil
}
func (l *insertLoader) Load(db *pgx.Conn, bndl bundle, cb loaderCb) error {
batch := db.BeginBatch()
curResource := uint(0)
totalCount := uint(bndl.Count())
batchSize := uint(2000)
var err error
for err == nil {
startTime := time.Now()
var resource map[string]interface{}
resource, err = bndl.Next()
if err == nil {
transformedResource, err := doTransform(resource, l.fhirVersion)
if err != nil {
fmt.Printf("Error during FB transform: %v\n", err)
}
resourceType, _ := resource["resourceType"].(string)
tblName := strings.ToLower(resourceType)
id, ok := resource["id"].(string)
if !ok || id == "" {
batch.Queue(fmt.Sprintf("INSERT INTO %s (id, txid, status, resource) VALUES (gen_random_uuid()::text, 0, 'created', $1) ON CONFLICT (id) DO NOTHING", tblName), []interface{}{transformedResource}, []pgtype.OID{pgtype.JSONBOID}, nil)
} else {
batch.Queue(fmt.Sprintf("INSERT INTO %s (id, txid, status, resource) VALUES ($1, 0, 'created', $2) ON CONFLICT (id) DO NOTHING", tblName), []interface{}{id, transformedResource}, []pgtype.OID{pgtype.TextOID, pgtype.JSONBOID}, nil)
}
if curResource%batchSize == 0 || curResource == totalCount-1 {
batch.Send(context.Background(), nil)
batch.Close()
if curResource != totalCount-1 {
batch = db.BeginBatch()
} else {
batch = nil
}
}
curResource++
cb(resourceType, time.Since(startTime))
} else {
return err
}
}
if batch != nil {
batch.Send(context.Background(), nil)
batch.Close()
}
return nil
}
func prewalkDirs(fileNames []string) ([]string, error) {
result := make([]string, 0)
for _, fn := range fileNames {
fi, err := os.Stat(fn)
switch {
case err != nil:
return nil, err
case fi.IsDir():
err = filepath.Walk(fn, func(path string, info os.FileInfo, err error) error {
if err == nil && !info.IsDir() {
result = append(result, path)
}
return err
})
if err != nil {
return nil, err
}
default:
result = append(result, fn)
}
}
return result, nil
}
func loadFiles(files []string, ldr loader, memUsage bool) error {
db := GetConnection(nil)
defer db.Close()
startTime := time.Now()
bndl, err := newMultifileBundle(files)
if err != nil {
return err
}
totalCount := bndl.Count()
insertedCounts := make(map[string]uint)
currentIdx := 0
bars := mpb.New(
mpb.WithWidth(100),
)
bar := bars.AddBar(int64(totalCount),
mpb.AppendDecorators(
decor.Percentage(decor.WC{W: 3}),
decor.AverageETA(decor.ET_STYLE_MMSS, decor.WC{W: 6}),
),
mpb.PrependDecorators(decor.CountersNoUnit("%d / %d", decor.WC{W: 10})))
err = ldr.Load(db, bndl, func(curType string, duration time.Duration) {
if memUsage && currentIdx%3000 == 0 {
PrintMemUsage()
}
currentIdx = currentIdx + 1
insertedCounts[curType] = insertedCounts[curType] + 1
bar.IncrBy(1, duration)
})
if err != nil && err != io.EOF {
bars.Abort(bar, false)
return err
}
bars.Wait()
loadDuration := int(time.Since(startTime).Seconds())
submitLoadEvent(insertedCounts, loadDuration)
fmt.Printf("Done, inserted %d resources in %d seconds:\n", totalCount, loadDuration)
tblw := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', tabwriter.AlignRight)
for rt, cnt := range insertedCounts {
fmt.Fprintf(tblw, "%s\t %d\n", rt, cnt)
}
tblw.Flush()
return nil
}
// LoadCommand loads FHIR schema into database
func LoadCommand(c *cli.Context) error {
if c.NArg() == 0 {
cli.ShowCommandHelpAndExit(c, "load", 1)
return nil
}
var bulkLoad bool
if strings.HasPrefix(c.Args().Get(0), "http") {
bulkLoad = true
} else {
bulkLoad = false
}
fhirVersion := c.GlobalString("fhir")
mode := c.String("mode")
var ldr loader
if bulkLoad && !c.IsSet("mode") {
mode = "copy"
}
if mode != "copy" && mode != "insert" && mode != "upinsert" {
return fmt.Errorf("invalid value for --mode flag. Possible values are either 'copy','insert' or 'upinsert'")
}
if mode == "copy" {
ldr = ©Loader{
fhirVersion: fhirVersion,
}
} else if mode == "upinsert" {
ldr = &upInsertLoader{
fhirVersion: fhirVersion,
}
} else {
ldr = &insertLoader{
fhirVersion: fhirVersion,
}
}
memUsage := c.Bool("memusage")
if bulkLoad {
numWorkers := c.Uint("numdl")
acceptHdr := c.String("accept-header")
fileHndlrs, err := getBulkData(c.Args().Get(0), numWorkers, acceptHdr)
if err != nil {
return err
}
files := make([]string, 0, len(fileHndlrs))
defer func() {
for _, fn := range files {
os.Remove(fn)
}
}()
for _, f := range fileHndlrs {
files = append(files, f.Name())
f.Close()
}
return loadFiles(files, ldr, memUsage)
}
files, err := prewalkDirs(c.Args())
if err != nil {
return errors.Wrap(err, "cannot prewalk directories")
}
return loadFiles(files, ldr, memUsage)
}