This repository has been archived by the owner on Apr 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bigquery.go
82 lines (61 loc) · 1.91 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
70
71
72
73
74
75
76
77
78
79
80
81
82
package bq
import (
"context"
"cloud.google.com/go/bigquery"
log "github.com/sirupsen/logrus"
"github.com/tufin/espresso/env"
"golang.org/x/oauth2/google"
"google.golang.org/api/option"
)
const (
EnvKeyBQToken = "BIGQUERY_KEY"
)
type Client interface {
QueryIterator(q string, params []bigquery.QueryParameter) (Iterator, error)
}
type ClientImpl struct {
bqClient *bigquery.Client
}
func NewClient(gcpProjectID string) Client {
if key := env.GetSensitive(EnvKeyBQToken); key != "" {
conf, err := google.JWTConfigFromJSON([]byte(key), bigquery.Scope)
if err != nil {
log.Fatalf("failed to config big-query JWT with %v", err)
}
ctx := context.Background()
client, err := bigquery.NewClient(ctx, gcpProjectID, option.WithTokenSource(conf.TokenSource(ctx)))
if err != nil {
log.Fatalf("failed to create bigquery client with %v", err)
}
return &ClientImpl{bqClient: client}
}
client, err := bigquery.NewClient(context.Background(), gcpProjectID)
if err != nil {
log.Fatalf("failed to create bigquery client without token with %v", err)
}
return &ClientImpl{bqClient: client}
}
func (client *ClientImpl) QueryIterator(q string, params []bigquery.QueryParameter) (Iterator, error) {
query := client.bqClient.Query(q)
query.Parameters = params
rowIterator, err := query.Read(context.Background())
if err != nil {
return nil, err
}
return newRawIterator(rowIterator), err
}
func (client *ClientImpl) Query(q string) error {
_, err := client.bqClient.Query(q).Read(context.Background())
return err
}
func (client *ClientImpl) GetQueryStats(q string, params []bigquery.QueryParameter) (*bigquery.JobStatistics, error) {
query := client.bqClient.Query(q)
query.Parameters = params
query.QueryConfig.DryRun = true
job, err := query.Run(context.Background())
if err != nil {
log.Errorf("get query stats failed with %v", err)
return nil, err
}
return job.LastStatus().Statistics, nil
}