forked from vitessio/vitess
-
Notifications
You must be signed in to change notification settings - Fork 1
/
conn.go
336 lines (290 loc) · 8.32 KB
/
conn.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
// Copyright 2015, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package fakesqldb provides a fake implementation of sqldb.Conn
package fakesqldb
import (
"fmt"
"math/rand"
"regexp"
"strings"
"sync"
"time"
"github.com/youtube/vitess/go/sqldb"
"github.com/youtube/vitess/go/sqltypes"
binlogdatapb "github.com/youtube/vitess/go/vt/proto/binlogdata"
querypb "github.com/youtube/vitess/go/vt/proto/query"
)
// Conn provides a fake implementation of sqldb.Conn.
type Conn struct {
db *DB
isClosed bool
id int64
curQueryResult *sqltypes.Result
curQueryRow int64
charset *binlogdatapb.Charset
}
// DB is a fake database and all its methods are thread safe.
type DB struct {
Name string
isConnFail bool
data map[string]*sqltypes.Result
rejectedData map[string]error
patternData []exprResult
queryCalled map[string]int
mu sync.Mutex
}
type exprResult struct {
expr *regexp.Regexp
result *sqltypes.Result
}
// AddQuery adds a query and its expected result.
func (db *DB) AddQuery(query string, expectedResult *sqltypes.Result) {
result := &sqltypes.Result{}
*result = *expectedResult
db.mu.Lock()
defer db.mu.Unlock()
key := strings.ToLower(query)
db.data[key] = result
db.queryCalled[key] = 0
}
// AddQueryPattern adds an expected result for a set of queries.
// These patterns are checked if no exact matches from AddQuery() are found.
// This function forces the addition of begin/end anchors (^$) and turns on
// case-insensitive matching mode.
func (db *DB) AddQueryPattern(queryPattern string, expectedResult *sqltypes.Result) {
expr := regexp.MustCompile("(?is)^" + queryPattern + "$")
result := *expectedResult
db.mu.Lock()
defer db.mu.Unlock()
db.patternData = append(db.patternData, exprResult{expr, &result})
}
// GetQuery gets a query from the fake DB.
func (db *DB) GetQuery(query string) (*sqltypes.Result, bool) {
db.mu.Lock()
defer db.mu.Unlock()
// Check explicit queries from AddQuery().
key := strings.ToLower(query)
result, ok := db.data[key]
db.queryCalled[key]++
if ok {
return result, ok
}
// Check query patterns from AddQueryPattern().
for _, pat := range db.patternData {
if pat.expr.MatchString(query) {
return pat.result, true
}
}
// Nothing matched.
return nil, false
}
// DeleteQuery deletes query from the fake DB.
func (db *DB) DeleteQuery(query string) {
db.mu.Lock()
defer db.mu.Unlock()
key := strings.ToLower(query)
delete(db.data, key)
delete(db.queryCalled, key)
}
// AddRejectedQuery adds a query which will be rejected at execution time.
func (db *DB) AddRejectedQuery(query string, err error) {
db.mu.Lock()
defer db.mu.Unlock()
db.rejectedData[strings.ToLower(query)] = err
}
// DeleteRejectedQuery deletes query from the fake DB.
func (db *DB) DeleteRejectedQuery(query string) {
db.mu.Lock()
defer db.mu.Unlock()
delete(db.rejectedData, strings.ToLower(query))
}
// GetQueryCalledNum returns how many times db executes a certain query.
func (db *DB) GetQueryCalledNum(query string) int {
db.mu.Lock()
defer db.mu.Unlock()
num, ok := db.queryCalled[strings.ToLower(query)]
if !ok {
return 0
}
return num
}
// EnableConnFail makes connection to this fake DB fail.
func (db *DB) EnableConnFail() {
db.mu.Lock()
defer db.mu.Unlock()
db.isConnFail = true
}
// DisableConnFail makes connection to this fake DB success.
func (db *DB) DisableConnFail() {
db.mu.Lock()
defer db.mu.Unlock()
db.isConnFail = false
}
// IsConnFail tests whether there is a connection failure.
func (db *DB) IsConnFail() bool {
db.mu.Lock()
defer db.mu.Unlock()
return db.isConnFail
}
// NewFakeSQLDBConn creates a new FakeSqlDBConn instance
func NewFakeSQLDBConn(db *DB) *Conn {
return &Conn{
db: db,
isClosed: false,
id: rand.Int63(),
}
}
// ExecuteFetch executes the query on the connection
func (conn *Conn) ExecuteFetch(query string, maxrows int, wantfields bool) (*sqltypes.Result, error) {
if conn.db.IsConnFail() {
return nil, newConnError()
}
if conn.IsClosed() {
return nil, fmt.Errorf("connection is closed")
}
if err, ok := conn.db.rejectedData[query]; ok {
return nil, err
}
result, ok := conn.db.GetQuery(query)
if !ok {
return nil, fmt.Errorf("query: %s is not supported", query)
}
qr := &sqltypes.Result{}
qr.RowsAffected = result.RowsAffected
qr.InsertID = result.InsertID
if qr.RowsAffected > uint64(maxrows) {
return nil, fmt.Errorf("row count exceeded %d", maxrows)
}
if wantfields {
qr.Fields = make([]*querypb.Field, len(result.Fields))
copy(qr.Fields, result.Fields)
}
rows := make([][]sqltypes.Value, 0, len(result.Rows))
for _, r := range result.Rows {
rows = append(rows, r)
}
qr.Rows = rows
return qr, nil
}
// ExecuteFetchMap returns a map from column names to cell data for a query
// that should return exactly 1 row.
func (conn *Conn) ExecuteFetchMap(query string) (map[string]string, error) {
if conn.db.IsConnFail() {
return nil, newConnError()
}
qr, err := conn.ExecuteFetch(query, 1, true)
if err != nil {
return nil, err
}
if len(qr.Rows) != 1 {
return nil, fmt.Errorf("query %#v returned %d rows, expected 1", query, len(qr.Rows))
}
if len(qr.Fields) != len(qr.Rows[0]) {
return nil, fmt.Errorf("query %#v returned %d column names, expected %d", query, len(qr.Fields), len(qr.Rows[0]))
}
rowMap := make(map[string]string)
for i, value := range qr.Rows[0] {
rowMap[qr.Fields[i].Name] = value.String()
}
return rowMap, nil
}
// ExecuteStreamFetch starts a streaming query to db server. Use FetchNext
// on the Connection until it returns nil or error
func (conn *Conn) ExecuteStreamFetch(query string) error {
if conn.db.IsConnFail() {
return newConnError()
}
if conn.IsClosed() {
return fmt.Errorf("connection is closed")
}
if err, ok := conn.db.rejectedData[query]; ok {
return err
}
result, ok := conn.db.GetQuery(query)
if !ok {
return fmt.Errorf("query: %s is not supported", query)
}
conn.curQueryResult = result
conn.curQueryRow = 0
return nil
}
// Close closes the db connection
func (conn *Conn) Close() {
conn.isClosed = true
}
// IsClosed returns if the connection was ever closed
func (conn *Conn) IsClosed() bool {
return conn.isClosed
}
// CloseResult finishes the result set
func (conn *Conn) CloseResult() {
}
// Shutdown invokes the low-level shutdown call on the socket associated with
// a connection to stop ongoing communication.
func (conn *Conn) Shutdown() {
}
// Fields returns the current fields description for the query
func (conn *Conn) Fields() ([]*querypb.Field, error) {
return make([]*querypb.Field, 0), nil
}
// ID returns the connection id.
func (conn *Conn) ID() int64 {
return conn.id
}
// FetchNext returns the next row for a query
func (conn *Conn) FetchNext() ([]sqltypes.Value, error) {
rowCount := int64(len(conn.curQueryResult.Rows))
if conn.curQueryResult == nil || rowCount <= conn.curQueryRow {
return nil, nil
}
row := conn.curQueryResult.Rows[conn.curQueryRow]
conn.curQueryRow++
return row, nil
}
// ReadPacket reads a raw packet from the connection.
func (conn *Conn) ReadPacket() ([]byte, error) {
return []byte{}, nil
}
// SendCommand sends a raw command to the db server.
func (conn *Conn) SendCommand(command uint32, data []byte) error {
return nil
}
// GetCharset returns the current numerical values of the per-session character
// set variables.
func (conn *Conn) GetCharset() (cs *binlogdatapb.Charset, err error) {
return conn.charset, nil
}
// SetCharset changes the per-session character set variables.
func (conn *Conn) SetCharset(cs *binlogdatapb.Charset) error {
conn.charset = cs
return nil
}
// Register registers a fake implementation of sqldb.Conn and returns its registered name
func Register() *DB {
name := fmt.Sprintf("fake-%d", rand.Int63())
db := &DB{
Name: name,
data: make(map[string]*sqltypes.Result),
rejectedData: make(map[string]error),
queryCalled: make(map[string]int),
}
sqldb.Register(name, func(sqldb.ConnParams) (sqldb.Conn, error) {
if db.IsConnFail() {
return nil, newConnError()
}
return NewFakeSQLDBConn(db), nil
})
return db
}
func newConnError() error {
return &sqldb.SQLError{
Num: 2012,
Message: "connection fail",
Query: "",
}
}
var _ (sqldb.Conn) = (*Conn)(nil)
func init() {
rand.Seed(time.Now().UnixNano())
}