forked from go-gorm/bigquery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdriver.go
112 lines (91 loc) · 2.19 KB
/
driver.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
package driver
import (
"context"
"database/sql/driver"
"fmt"
"net/url"
"strings"
"cloud.google.com/go/bigquery"
"google.golang.org/api/option"
)
type bigQueryDriver struct {
}
type bigQueryConfig struct {
projectID string
location string
dataSet string
scopes []string
endpoint string
disableAuth bool
}
func (b bigQueryDriver) Open(uri string) (driver.Conn, error) {
if uri == "scanner" {
return &scannerConnection{}, nil
}
config, err := configFromUri(uri)
if err != nil {
return nil, err
}
ctx := context.Background()
opts := []option.ClientOption{}
if len(config.scopes) > 0 {
opts = append(opts, option.WithScopes(config.scopes...))
}
if config.endpoint != "" {
opts = append(opts, option.WithEndpoint(config.endpoint))
}
if config.disableAuth {
opts = append(opts, option.WithoutAuthentication())
}
client, err := bigquery.NewClient(ctx, config.projectID, opts...)
if err != nil {
return nil, err
}
return &bigQueryConnection{
ctx: ctx,
client: client,
config: *config,
}, nil
}
func configFromUri(uri string) (*bigQueryConfig, error) {
u, err := url.Parse(uri)
if err != nil {
return nil, invalidConnectionStringError(uri)
}
if u.Scheme != "bigquery" {
return nil, fmt.Errorf("invalid prefix, expected bigquery:// got: %s", uri)
}
if u.Hostname() == "" {
return nil, invalidConnectionStringError(uri)
}
fields := strings.Split(strings.TrimPrefix(u.Path, "/"), "/")
if len(fields) > 2 {
return nil, invalidConnectionStringError(uri)
}
// Check if dataset was provided
datasetName := ""
if len(fields) >= 1 {
datasetName = fields[len(fields)-1]
}
config := &bigQueryConfig{
projectID: u.Hostname(),
dataSet: datasetName,
scopes: getScopes(u.Query()),
endpoint: u.Query().Get("endpoint"),
disableAuth: u.Query().Get("disable_auth") == "true",
}
if len(fields) == 2 {
config.location = fields[0]
}
return config, nil
}
func getScopes(query url.Values) []string {
q := strings.Trim(query.Get("scopes"), ",")
if q == "" {
return []string{}
}
return strings.Split(q, ",")
}
func invalidConnectionStringError(uri string) error {
return fmt.Errorf("invalid connection string: %s", uri)
}