forked from vitessio/vitess
-
Notifications
You must be signed in to change notification settings - Fork 1
/
driver.go
339 lines (288 loc) · 8.29 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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
/*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package vitessdriver
import (
"context"
"database/sql"
"database/sql/driver"
"encoding/json"
"errors"
"vitess.io/vitess/go/vt/vtgate/vtgateconn"
)
var (
errNoIntermixing = errors.New("named and positional arguments intermixing disallowed")
errIsolationUnsupported = errors.New("isolation levels are not supported")
)
// Type-check interfaces.
var (
_ driver.QueryerContext = &conn{}
_ driver.ExecerContext = &conn{}
_ driver.StmtQueryContext = &stmt{}
_ driver.StmtExecContext = &stmt{}
)
func init() {
sql.Register("vitess", drv{})
}
// Open is a Vitess helper function for sql.Open().
//
// It opens a database connection to vtgate running at "address".
func Open(address, target string) (*sql.DB, error) {
c := Configuration{
Address: address,
Target: target,
}
return OpenWithConfiguration(c)
}
// OpenForStreaming is the same as Open() but uses streaming RPCs to retrieve
// the results.
//
// The streaming mode is recommended for large results.
func OpenForStreaming(address, target string) (*sql.DB, error) {
c := Configuration{
Address: address,
Target: target,
Streaming: true,
}
return OpenWithConfiguration(c)
}
// OpenWithConfiguration is the generic Vitess helper function for sql.Open().
//
// It allows to pass in a Configuration struct to control all possible
// settings of the Vitess Go SQL driver.
func OpenWithConfiguration(c Configuration) (*sql.DB, error) {
json, err := c.toJSON()
if err != nil {
return nil, err
}
return sql.Open("vitess", json)
}
type drv struct {
}
// Open implements the database/sql/driver.Driver interface.
//
// For "name", the Vitess driver requires that a JSON object is passed in.
//
// Instead of using this call and passing in a hand-crafted JSON string, it's
// recommended to use the public Vitess helper functions like
// Open(), OpenShard() or OpenWithConfiguration() instead. These will generate
// the required JSON string behind the scenes for you.
//
// Example for a JSON string:
//
// {"protocol": "grpc", "address": "localhost:1111", "target": "@master"}
//
// For a description of the available fields, see the Configuration struct.
func (d drv) Open(name string) (driver.Conn, error) {
c := &conn{}
err := json.Unmarshal([]byte(name), c)
if err != nil {
return nil, err
}
if c.convert, err = newConverter(&c.Configuration); err != nil {
return nil, err
}
if err = c.dial(); err != nil {
return nil, err
}
return c, nil
}
// Configuration holds all Vitess driver settings.
//
// Fields with documented default values do not have to be set explicitly.
type Configuration struct {
// Protocol is the name of the vtgate RPC client implementation.
// Note: In open-source "grpc" is the recommended implementation.
//
// Default: "grpc"
Protocol string
// Address must point to a vtgate instance.
//
// Format: hostname:port
Address string
// Target specifies the default target.
Target string
// Streaming is true when streaming RPCs are used.
// Recommended for large results.
// Default: false
Streaming bool
// DefaultLocation is the timezone string that will be used
// when converting DATETIME and DATE into time.Time.
// This setting has no effect if ConvertDatetime is not set.
// Default: UTC
DefaultLocation string
}
// toJSON converts Configuration to the JSON string which is required by the
// Vitess driver. Default values for empty fields will be set.
func (c Configuration) toJSON() (string, error) {
c.setDefaults()
jsonBytes, err := json.Marshal(c)
if err != nil {
return "", err
}
return string(jsonBytes), nil
}
// setDefaults sets the default values for empty fields.
func (c *Configuration) setDefaults() {
if c.Protocol == "" {
c.Protocol = "grpc"
}
}
type conn struct {
Configuration
convert *converter
conn *vtgateconn.VTGateConn
session *vtgateconn.VTGateSession
}
func (c *conn) dial() error {
var err error
if c.Protocol == "" {
c.conn, err = vtgateconn.Dial(context.Background(), c.Address)
} else {
c.conn, err = vtgateconn.DialProtocol(context.Background(), c.Protocol, c.Address)
}
if err != nil {
return err
}
c.session = c.conn.Session(c.Target, nil)
return nil
}
func (c *conn) Prepare(query string) (driver.Stmt, error) {
return &stmt{c: c, query: query}, nil
}
func (c *conn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) {
return c.Prepare(query)
}
func (c *conn) Close() error {
c.conn.Close()
return nil
}
func (c *conn) Begin() (driver.Tx, error) {
if _, err := c.Exec("begin", nil); err != nil {
return nil, err
}
return c, nil
}
func (c *conn) BeginTx(_ context.Context, opts driver.TxOptions) (driver.Tx, error) {
// We don't use the context. The function signature accepts the context
// to signal to the driver that it's allowed to call Rollback on Cancel.
if opts.Isolation != driver.IsolationLevel(0) || opts.ReadOnly {
return nil, errIsolationUnsupported
}
return c.Begin()
}
func (c *conn) Commit() error {
_, err := c.Exec("commit", nil)
return err
}
func (c *conn) Rollback() error {
_, err := c.Exec("rollback", nil)
return err
}
func (c *conn) Exec(query string, args []driver.Value) (driver.Result, error) {
ctx := context.TODO()
if c.Streaming {
return nil, errors.New("Exec not allowed for streaming connections")
}
bindVars, err := c.convert.buildBindVars(args)
if err != nil {
return nil, err
}
qr, err := c.session.Execute(ctx, query, bindVars)
if err != nil {
return nil, err
}
return result{int64(qr.InsertID), int64(qr.RowsAffected)}, nil
}
func (c *conn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) {
if c.Streaming {
return nil, errors.New("Exec not allowed for streaming connections")
}
bv, err := c.convert.bindVarsFromNamedValues(args)
if err != nil {
return nil, err
}
qr, err := c.session.Execute(ctx, query, bv)
if err != nil {
return nil, err
}
return result{int64(qr.InsertID), int64(qr.RowsAffected)}, nil
}
func (c *conn) Query(query string, args []driver.Value) (driver.Rows, error) {
ctx := context.TODO()
bindVars, err := c.convert.buildBindVars(args)
if err != nil {
return nil, err
}
if c.Streaming {
stream, err := c.session.StreamExecute(ctx, query, bindVars)
if err != nil {
return nil, err
}
return newStreamingRows(stream, c.convert), nil
}
qr, err := c.session.Execute(ctx, query, bindVars)
if err != nil {
return nil, err
}
return newRows(qr, c.convert), nil
}
func (c *conn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) {
bv, err := c.convert.bindVarsFromNamedValues(args)
if err != nil {
return nil, err
}
if c.Streaming {
stream, err := c.session.StreamExecute(ctx, query, bv)
if err != nil {
return nil, err
}
return newStreamingRows(stream, c.convert), nil
}
qr, err := c.session.Execute(ctx, query, bv)
if err != nil {
return nil, err
}
return newRows(qr, c.convert), nil
}
type stmt struct {
c *conn
query string
}
func (s *stmt) Close() error {
return nil
}
func (s *stmt) NumInput() int {
// -1 = Golang sql won't sanity check argument counts before Exec or Query.
return -1
}
func (s *stmt) Exec(args []driver.Value) (driver.Result, error) {
return s.c.Exec(s.query, args)
}
func (s *stmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error) {
return s.c.ExecContext(ctx, s.query, args)
}
func (s *stmt) Query(args []driver.Value) (driver.Rows, error) {
return s.c.Query(s.query, args)
}
func (s *stmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) {
return s.c.QueryContext(ctx, s.query, args)
}
type result struct {
insertid, rowsaffected int64
}
func (r result) LastInsertId() (int64, error) {
return r.insertid, nil
}
func (r result) RowsAffected() (int64, error) {
return r.rowsaffected, nil
}