vitess.io/vitess@v0.16.2/go/vt/vtadmin/vtsql/fakevtsql/conn.go (about) 1 /* 2 Copyright 2020 The Vitess Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package fakevtsql 18 19 import ( 20 "context" 21 "database/sql/driver" 22 "errors" 23 "fmt" 24 "strings" 25 26 "github.com/stretchr/testify/assert" 27 28 "vitess.io/vitess/go/vt/topo/topoproto" 29 "vitess.io/vitess/go/vt/vtadmin/vtadminproto" 30 31 vtadminpb "vitess.io/vitess/go/vt/proto/vtadmin" 32 ) 33 34 var ( 35 // ErrConnClosed is returend when attempting to query a closed connection. 36 // It is the identical message to vtsql.ErrConnClosed, but redefined to 37 // prevent an import cycle in package vtsql's tests. 38 ErrConnClosed = errors.New("use of closed connection") 39 // ErrUnrecognizedQuery is returned when QueryCnotext is given a query 40 // string the mock is not set up to handle. 41 ErrUnrecognizedQuery = errors.New("unrecognized query") 42 ) 43 44 type conn struct { 45 tablets []*vtadminpb.Tablet 46 shouldErr bool 47 } 48 49 var ( 50 _ driver.Conn = (*conn)(nil) 51 _ driver.QueryerContext = (*conn)(nil) 52 ) 53 54 func (c *conn) Begin() (driver.Tx, error) { 55 return nil, nil 56 } 57 58 func (c *conn) Close() error { 59 return nil 60 } 61 62 func (c *conn) Prepare(query string) (driver.Stmt, error) { 63 return nil, nil 64 } 65 66 func (c *conn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) { 67 if c.shouldErr { 68 return nil, assert.AnError 69 } 70 71 if c == nil { 72 return nil, ErrConnClosed 73 } 74 75 switch strings.ToLower(query) { 76 case "show vitess_tablets", "show tablets": 77 columns := []string{"Cell", "Keyspace", "Shard", "TabletType", "ServingState", "Alias", "Hostname", "PrimaryTermStartTime"} 78 vals := [][]any{} 79 80 for _, tablet := range c.tablets { 81 vals = append(vals, []any{ 82 tablet.Tablet.Alias.Cell, 83 tablet.Tablet.Keyspace, 84 tablet.Tablet.Shard, 85 topoproto.TabletTypeLString(tablet.Tablet.Type), 86 vtadminproto.TabletServingStateString(tablet.State), 87 topoproto.TabletAliasString(tablet.Tablet.Alias), 88 tablet.Tablet.Hostname, 89 "", // (TODO:@amason) use real values here 90 }) 91 } 92 93 return &rows{ 94 cols: columns, 95 vals: vals, 96 pos: 0, 97 closed: false, 98 }, nil 99 } 100 101 return nil, fmt.Errorf("%w: %q %v", ErrUnrecognizedQuery, query, args) 102 }