-
Notifications
You must be signed in to change notification settings - Fork 0
/
bigquery.go
134 lines (85 loc) · 2.31 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
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
package xk6_bigquery
import (
"context"
"encoding/json"
"fmt"
"log"
"cloud.google.com/go/bigquery"
"go.k6.io/k6/js/modules"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
)
func init() {
modules.Register("k6/x/bigquery", new(BQ))
}
type BQ struct {
}
type Datasets struct {
Data []string `json:"data"`
}
type QueryResponse struct{
Data []bigquery.Value `json:"data"`
}
func (c *BQ) NewClient(serviceAccount string) *bigquery.Client {
client,err := bigquery.NewClient(context.Background(),"moonlit-poetry-327116",option.WithCredentialsFile(serviceAccount))
if err != nil{
println("Connection Error",err.Error())
}
return client
}
func (r *BQ) GetDatasets(bqclient *bigquery.Client) string {
it := bqclient.Datasets(context.Background())
datasets := []string{}
for {
dataset, err := it.Next()
if err == iterator.Done {
break
}
datasets = append(datasets, dataset.DatasetID)
}
sets := Datasets{Data: datasets}
bytes, err := json.Marshal(sets)
if err != nil {
panic("Error Occured receiving datasets "+err.Error())
}
return string(bytes)
}
func(r *BQ) Query(bqclient *bigquery.Client, query string){
q := bqclient.Query(query)
it, err := q.Read(context.Background())
if err != nil {
panic("Error occured fetching query "+ err.Error())
}
for {
var values []bigquery.Value
err := it.Next(&values)
if err == iterator.Done {
break
}
if err != nil {
panic("Error occured fetching query "+ err.Error())
}
fmt.Println("Query executed here are rows ",values)
}
}
func(r *BQ) DataLoader(bqclient *bigquery.Client, dataset string, gsbucket string,table string){
myDataset := bqclient.Dataset(dataset)
gcsRef := bigquery.NewGCSReference(gsbucket)
gcsRef.AllowJaggedRows = true
loader := myDataset.Table(table).LoaderFrom(gcsRef)
loader.CreateDisposition = bigquery.CreateNever
job, err := loader.Run(context.Background())
if err != nil {
panic("Job Loader Configuration Failed "+ err.Error())
}
status, err2 := job.Status(context.Background())
if err2 != nil {
panic("Job Loader Configuration Failed"+ err.Error())
}
if status.Done() {
if status.Err() != nil {
log.Fatalf("Job failed with error %v", status.Err())
}
fmt.Println("Job was success data has been loaded")
}
}