-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloader.go
60 lines (46 loc) · 1.38 KB
/
loader.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
package bqloader
import (
"bytes"
"context"
"encoding/csv"
"cloud.google.com/go/bigquery"
"golang.org/x/xerrors"
)
// Loader loads projected data into a destination such as BigQuery.
type Loader interface {
Load(context.Context, [][]string) error
}
type defaultLoader struct {
table *bigquery.Table
}
func newDefaultLoader(ctx context.Context, project, dataset, table string) (Loader, error) {
bq, err := bigquery.NewClient(ctx, project)
if err != nil {
return nil, xerrors.Errorf("failed to build bigquery client for %s.%s.%s: %w",
project, dataset, table, err)
}
t := bq.Dataset(dataset).Table(table)
return &defaultLoader{table: t}, nil
}
func (l *defaultLoader) Load(ctx context.Context, records [][]string) error {
buf := &bytes.Buffer{}
if err := csv.NewWriter(buf).WriteAll(records); err != nil {
return xerrors.Errorf("failed to write csv into buffer: %w", err)
}
rs := bigquery.NewReaderSource(buf)
rs.AllowQuotedNewlines = true
loader := l.table.LoaderFrom(rs)
loader.LoadConfig.CreateDisposition = bigquery.CreateNever
job, err := loader.Run(ctx)
if err != nil {
return xerrors.Errorf("failed to run bigquery load job: %w", err)
}
status, err := job.Wait(ctx)
if err != nil {
return xerrors.Errorf("failed to wait bigquery job: %w", err)
}
if status.Err() != nil {
return xerrors.Errorf("bigquery load job failed: %w", status.Err())
}
return nil
}