forked from CanonicalLtd/go-grpc-sql
-
Notifications
You must be signed in to change notification settings - Fork 1
/
driver.go
90 lines (78 loc) · 2.21 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
// Copyright 2021 The Godror Authors.
// Copyright 2017, 2018 Canonical Ltd.
//
// SPDX-License-Identifier: Apache-2.0
// Package grpcsql exposes a SQL database over a gRPC endpoint.
package grpcsql
import (
"database/sql/driver"
"fmt"
"time"
"github.com/godror/go-grpc-sql/internal/protocol"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// 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, fmt.Errorf("gRPC grpcConnection failed: %w", err)
}
// TODO: make the number of retries and timeout configurable
var conn *Conn
var lastErr error
for i := 0; i < 3; i++ {
grpcClient := protocol.NewSQLClient(grpcConn)
grpcConnClient, err := grpcClient.Conn(context.Background())
if err == nil {
lastErr = nil
conn = &Conn{
grpcConn: grpcConn,
grpcConnClient: grpcConnClient,
}
break
}
if status.Code(err) != codes.Unavailable {
return nil, fmt.Errorf("gRPC conn method failed: %w", err)
}
lastErr = err
time.Sleep(time.Duration(i) * time.Second)
}
if lastErr != nil {
return nil, fmt.Errorf("gRPC conn method failed: %w", lastErr)
}
if _, err := conn.exec(protocol.NewRequestOpen(name)); err != nil {
return nil, fmt.Errorf("gRPC could not send open request: %w", err)
}
return conn, nil
}