forked from talariadb/talaria
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbigquery.go
69 lines (60 loc) · 1.59 KB
/
bigquery.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
package bigquery
import (
"bytes"
"context"
"cloud.google.com/go/bigquery"
"github.com/kelindar/talaria/internal/encoding/key"
"github.com/kelindar/talaria/internal/monitor/errors"
)
// Writer represents a writer for Google Cloud Storage.
type Writer struct {
dataset string
table *bigquery.Table
client *bigquery.Client
context context.Context
}
// New creates a new writer.
func New(project, dataset, table string) (*Writer, error) {
ctx := context.Background()
client, err := bigquery.NewClient(ctx, project)
if err != nil {
return nil, errors.Newf("bigquery: %v", err)
}
tableRef := client.Dataset(dataset).Table(table)
return &Writer{
dataset: dataset,
table: tableRef,
client: client,
context: ctx,
}, nil
}
// Write writes the data to the sink.
func (w *Writer) Write(key key.Key, val []byte) error {
source := bigquery.NewReaderSource(bytes.NewReader(val))
source.FileConfig = bigquery.FileConfig{
SourceFormat: bigquery.DataFormat("ORC"),
AutoDetect: false,
IgnoreUnknownValues: true,
MaxBadRecords: 0,
}
// Run the loader
loader := w.table.LoaderFrom(source)
ctx := context.Background()
job, err := loader.Run(ctx)
if err != nil {
return errors.Internal("bigquery: unable to run a job", err)
}
// Wait for the job to complete
status, err := job.Wait(ctx)
if err != nil {
return errors.Internal("bigquery: unable to write", err)
}
if err := status.Err(); err != nil {
return errors.Internal("bigquery: unable to write", err)
}
return nil
}
// Close closes the writer.
func (w *Writer) Close() error {
return w.client.Close()
}