This repository has been archived by the owner on Mar 10, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
driver.go
77 lines (66 loc) · 1.88 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
package grpcsql
import (
"database/sql/driver"
"time"
"github.com/CanonicalLtd/go-grpc-sql/internal/protocol"
"github.com/pkg/errors"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
)
// Driver implements the database/sql/driver interface and executes the
// relevant statements over gRPC.
type Driver struct {
dialer Dialer
}
// NewDriver creates a new gRPC SQL driver for creating connections to backend
// gateways.
func NewDriver(dialer Dialer) *Driver {
return &Driver{
dialer: dialer,
}
}
// Dialer is a function that can create a gRPC connection.
type Dialer func() (conn *grpc.ClientConn, err error)
// Open a new connection against a gRPC SQL server.
//
// To establish the gRPC connection, the dialer passed to NewDriver() will
// used.
//
// The given data source name must be one that the driver attached to the
//remote Gateway can understand.
func (d *Driver) Open(name string) (driver.Conn, error) {
conn, err := dial(d.dialer, name)
if err != nil {
return nil, err
}
return conn, nil
}
// Create a new connection to a gRPC endpoint.
func dial(dialer Dialer, name string) (*Conn, error) {
grpcConn, err := dialer()
if err != nil {
return nil, errors.Wrapf(err, "gRPC grpcConnection failed")
}
// TODO: make the number of retries and timeout configurable
var conn *Conn
for i := 0; i < 3; i++ {
grpcClient := protocol.NewSQLClient(grpcConn)
grpcConnClient, err := grpcClient.Conn(context.Background())
if err != nil {
if grpc.Code(err) == codes.Unavailable && i != 2 {
time.Sleep(time.Second)
continue
}
return nil, errors.Wrapf(err, "gRPC conn method failed")
}
conn = &Conn{
grpcConn: grpcConn,
grpcConnClient: grpcConnClient,
}
}
if _, err := conn.exec(protocol.NewRequestOpen(name)); err != nil {
return nil, errors.Wrapf(err, "gRPC could not send open request")
}
return conn, nil
}