-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathloader.go
More file actions
64 lines (53 loc) · 1.55 KB
/
Copy pathloader.go
File metadata and controls
64 lines (53 loc) · 1.55 KB
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
package bqin
import (
"context"
"fmt"
"cloud.google.com/go/bigquery"
"github.com/kayac/bqin/internal/logger"
"github.com/pkg/errors"
"google.golang.org/api/option"
)
type Loader struct {
opts []option.ClientOption
}
func NewLoader(opts ...option.ClientOption) *Loader {
return &Loader{
opts: opts,
}
}
type LoadingJob struct {
GCSRef *bigquery.GCSReference
*LoadingDestination
CreateDisposition bigquery.TableCreateDisposition
WriteDisposition bigquery.TableWriteDisposition
}
func NewLoadingJob(dest *LoadingDestination, objectURIs ...string) *LoadingJob {
return &LoadingJob{
GCSRef: bigquery.NewGCSReference(objectURIs...),
LoadingDestination: dest,
CreateDisposition: bigquery.CreateIfNeeded,
WriteDisposition: bigquery.WriteAppend,
}
}
func (job *LoadingJob) String() string {
return fmt.Sprintf("load to %s", job.LoadingDestination)
}
func (l *Loader) Load(ctx context.Context, job *LoadingJob) error {
bq, err := bigquery.NewClient(ctx, job.ProjectID, l.opts...)
if err != nil {
return errors.Wrap(err, "can not get bigquery client")
}
loader := bq.Dataset(job.Dataset).Table(job.Table).LoaderFrom(job.GCSRef)
loader.CreateDisposition = job.CreateDisposition
loader.WriteDisposition = job.WriteDisposition
bqjob, err := loader.Run(ctx)
if err != nil {
return errors.Wrap(err, "create job failed")
}
logger.Debugf("create load job successed. jon_id=%s", bqjob.ID())
status, err := bqjob.Wait(ctx)
if err != nil {
return errors.Wrap(err, "can not wait job")
}
return errors.Wrap(status.Err(), "load job failed")
}