forked from dolthub/vitess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
executor.go
1394 lines (1252 loc) · 45.7 KB
/
executor.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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
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 vtgate
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
"sort"
"strings"
"sync"
"time"
"golang.org/x/net/context"
"vitess.io/vitess/go/acl"
"vitess.io/vitess/go/cache"
"vitess.io/vitess/go/mysql"
"vitess.io/vitess/go/sqltypes"
"vitess.io/vitess/go/stats"
"vitess.io/vitess/go/vt/callerid"
"vitess.io/vitess/go/vt/key"
"vitess.io/vitess/go/vt/log"
"vitess.io/vitess/go/vt/sqlannotation"
"vitess.io/vitess/go/vt/sqlparser"
"vitess.io/vitess/go/vt/srvtopo"
"vitess.io/vitess/go/vt/topo/topoproto"
"vitess.io/vitess/go/vt/topotools"
"vitess.io/vitess/go/vt/vterrors"
"vitess.io/vitess/go/vt/vtgate/engine"
"vitess.io/vitess/go/vt/vtgate/planbuilder"
"vitess.io/vitess/go/vt/vtgate/vindexes"
"vitess.io/vitess/go/vt/vtgate/vschemaacl"
querypb "vitess.io/vitess/go/vt/proto/query"
topodatapb "vitess.io/vitess/go/vt/proto/topodata"
vtgatepb "vitess.io/vitess/go/vt/proto/vtgate"
vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc"
)
var (
errNoKeyspace = vterrors.Errorf(vtrpcpb.Code_FAILED_PRECONDITION, "no keyspace in database name specified. Supported database name format (items in <> are optional): keyspace<:shard><@type> or keyspace<[range]><@type>")
defaultTabletType topodatapb.TabletType
queriesProcessed = stats.NewCountersWithSingleLabel("QueriesProcessed", "Queries processed at vtgate by plan type", "Plan")
queriesRouted = stats.NewCountersWithSingleLabel("QueriesRouted", "Queries routed from vtgate to vttablet by plan type", "Plan")
)
func init() {
topoproto.TabletTypeVar(&defaultTabletType, "default_tablet_type", topodatapb.TabletType_MASTER, "The default tablet type to set for queries, when one is not explicitly selected")
}
// Executor is the engine that executes queries by utilizing
// the abilities of the underlying vttablets.
type Executor struct {
serv srvtopo.Server
cell string
resolver *Resolver
scatterConn *ScatterConn
txConn *TxConn
mu sync.Mutex
vschema *vindexes.VSchema
normalize bool
streamSize int
legacyAutocommit bool
plans *cache.LRUCache
vschemaStats *VSchemaStats
vm VSchemaManager
}
var executorOnce sync.Once
// NewExecutor creates a new Executor.
func NewExecutor(ctx context.Context, serv srvtopo.Server, cell, statsName string, resolver *Resolver, normalize bool, streamSize int, queryPlanCacheSize int64, legacyAutocommit bool) *Executor {
e := &Executor{
serv: serv,
cell: cell,
resolver: resolver,
scatterConn: resolver.scatterConn,
txConn: resolver.scatterConn.txConn,
plans: cache.NewLRUCache(queryPlanCacheSize),
normalize: normalize,
streamSize: streamSize,
legacyAutocommit: legacyAutocommit,
}
vschemaacl.Init()
e.vm = VSchemaManager{e: e}
e.vm.watchSrvVSchema(ctx, cell)
executorOnce.Do(func() {
stats.NewGaugeFunc("QueryPlanCacheLength", "Query plan cache length", e.plans.Length)
stats.NewGaugeFunc("QueryPlanCacheSize", "Query plan cache size", e.plans.Size)
stats.NewGaugeFunc("QueryPlanCacheCapacity", "Query plan cache capacity", e.plans.Capacity)
stats.NewCounterFunc("QueryPlanCacheEvictions", "Query plan cache evictions", e.plans.Evictions)
stats.Publish("QueryPlanCacheOldest", stats.StringFunc(func() string {
return fmt.Sprintf("%v", e.plans.Oldest())
}))
http.Handle("/debug/query_plans", e)
http.Handle("/debug/vschema", e)
})
return e
}
// Execute executes a non-streaming query.
func (e *Executor) Execute(ctx context.Context, method string, safeSession *SafeSession, sql string, bindVars map[string]*querypb.BindVariable) (result *sqltypes.Result, err error) {
logStats := NewLogStats(ctx, method, sql, bindVars)
result, err = e.execute(ctx, safeSession, sql, bindVars, logStats)
logStats.Error = err
// The mysql plugin runs an implicit rollback whenever a connection closes.
// To avoid spamming the log with no-op rollback records, ignore it if
// it was a no-op record (i.e. didn't issue any queries)
if !(logStats.StmtType == "ROLLBACK" && logStats.ShardQueries == 0) {
logStats.Send()
}
return result, err
}
func (e *Executor) execute(ctx context.Context, safeSession *SafeSession, sql string, bindVars map[string]*querypb.BindVariable, logStats *LogStats) (*sqltypes.Result, error) {
// Start an implicit transaction if necessary.
// TODO(sougou): deprecate legacyMode after all users are migrated out.
if !e.legacyAutocommit && !safeSession.Autocommit && !safeSession.InTransaction() {
if err := e.txConn.Begin(ctx, safeSession); err != nil {
return nil, err
}
}
destKeyspace, destTabletType, dest, err := e.ParseDestinationTarget(safeSession.TargetString)
if err != nil {
return nil, err
}
if safeSession.InTransaction() && destTabletType != topodatapb.TabletType_MASTER {
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "transactions are supported only for master tablet types, current type: %v", destTabletType)
}
if bindVars == nil {
bindVars = make(map[string]*querypb.BindVariable)
}
stmtType := sqlparser.Preview(sql)
logStats.StmtType = sqlparser.StmtType(stmtType)
// Mysql warnings are scoped to the current session, but are
// cleared when a "non-diagnostic statement" is executed:
// https://dev.mysql.com/doc/refman/8.0/en/show-warnings.html
//
// To emulate this behavior, clear warnings from the session
// for all statements _except_ SHOW, so that SHOW WARNINGS
// can actually return them.
if stmtType != sqlparser.StmtShow {
safeSession.ClearWarnings()
}
switch stmtType {
case sqlparser.StmtSelect:
return e.handleExec(ctx, safeSession, sql, bindVars, destKeyspace, destTabletType, dest, logStats)
case sqlparser.StmtInsert, sqlparser.StmtReplace, sqlparser.StmtUpdate, sqlparser.StmtDelete:
safeSession := safeSession
// In legacy mode, we ignore autocommit settings.
if e.legacyAutocommit {
return e.handleExec(ctx, safeSession, sql, bindVars, destKeyspace, destTabletType, dest, logStats)
}
mustCommit := false
if safeSession.Autocommit && !safeSession.InTransaction() {
mustCommit = true
if err := e.txConn.Begin(ctx, safeSession); err != nil {
return nil, err
}
// The defer acts as a failsafe. If commit was successful,
// the rollback will be a no-op.
defer e.txConn.Rollback(ctx, safeSession)
}
// The SetAutocommitable flag should be same as mustCommit.
// If we started a transaction because of autocommit, then mustCommit
// will be true, which means that we can autocommit. If we were already
// in a transaction, it means that the app started it, or we are being
// called recursively. If so, we cannot autocommit because whatever we
// do is likely not final.
// The control flow is such that autocommitable can only be turned on
// at the beginning, but never after.
safeSession.SetAutocommitable(mustCommit)
qr, err := e.handleExec(ctx, safeSession, sql, bindVars, destKeyspace, destTabletType, dest, logStats)
if err != nil {
return nil, err
}
if mustCommit {
commitStart := time.Now()
if err = e.txConn.Commit(ctx, safeSession); err != nil {
return nil, err
}
logStats.CommitTime = time.Since(commitStart)
}
return qr, nil
case sqlparser.StmtDDL:
return e.handleDDL(ctx, safeSession, sql, bindVars, dest, destKeyspace, destTabletType, logStats)
case sqlparser.StmtBegin:
return e.handleBegin(ctx, safeSession, sql, bindVars, destTabletType, logStats)
case sqlparser.StmtCommit:
return e.handleCommit(ctx, safeSession, sql, bindVars, logStats)
case sqlparser.StmtRollback:
return e.handleRollback(ctx, safeSession, sql, bindVars, logStats)
case sqlparser.StmtSet:
return e.handleSet(ctx, safeSession, sql, bindVars, logStats)
case sqlparser.StmtShow:
return e.handleShow(ctx, safeSession, sql, bindVars, dest, destKeyspace, destTabletType, logStats)
case sqlparser.StmtUse:
return e.handleUse(ctx, safeSession, sql, bindVars)
case sqlparser.StmtOther:
return e.handleOther(ctx, safeSession, sql, bindVars, dest, destKeyspace, destTabletType, logStats)
case sqlparser.StmtComment:
return e.handleComment(sql)
}
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "unrecognized statement: %s", sql)
}
func (e *Executor) handleExec(ctx context.Context, safeSession *SafeSession, sql string, bindVars map[string]*querypb.BindVariable, destKeyspace string, destTabletType topodatapb.TabletType, dest key.Destination, logStats *LogStats) (*sqltypes.Result, error) {
if dest != nil {
// V1 mode or V3 mode with a forced shard or range target
// TODO(sougou): change this flow to go through V3 functions
// which will allow us to benefit from the autocommitable flag.
queriesProcessed.Add("ShardDirect", 1)
if destKeyspace == "" {
return nil, errNoKeyspace
}
switch dest.(type) {
case key.DestinationExactKeyRange:
stmtType := sqlparser.Preview(sql)
if stmtType == sqlparser.StmtInsert {
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "range queries not supported for inserts: %s", safeSession.TargetString)
}
}
execStart := time.Now()
sql = sqlannotation.AnnotateIfDML(sql, nil)
if e.normalize {
query, comments := sqlparser.SplitMarginComments(sql)
stmt, err := sqlparser.Parse(query)
if err != nil {
return nil, err
}
sqlparser.Normalize(stmt, bindVars, "vtg")
normalized := sqlparser.String(stmt)
sql = comments.Leading + normalized + comments.Trailing
}
logStats.PlanTime = execStart.Sub(logStats.StartTime)
logStats.SQL = sql
logStats.BindVariables = bindVars
result, err := e.destinationExec(ctx, safeSession, sql, bindVars, dest, destKeyspace, destTabletType, logStats)
logStats.ExecuteTime = time.Now().Sub(execStart)
queriesRouted.Add("ShardDirect", int64(logStats.ShardQueries))
return result, err
}
// V3 mode.
query, comments := sqlparser.SplitMarginComments(sql)
vcursor := newVCursorImpl(ctx, safeSession, destKeyspace, destTabletType, comments, e, logStats)
plan, err := e.getPlan(
vcursor,
query,
comments,
bindVars,
skipQueryPlanCache(safeSession),
logStats,
)
execStart := time.Now()
logStats.PlanTime = execStart.Sub(logStats.StartTime)
if err != nil {
logStats.Error = err
return nil, err
}
qr, err := plan.Instructions.Execute(vcursor, bindVars, true)
logStats.ExecuteTime = time.Since(execStart)
queriesProcessed.Add(plan.Instructions.RouteType(), 1)
queriesRouted.Add(plan.Instructions.RouteType(), int64(logStats.ShardQueries))
var errCount uint64
if err != nil {
logStats.Error = err
errCount = 1
} else {
logStats.RowsAffected = qr.RowsAffected
}
// Check if there was partial DML execution. If so, rollback the transaction.
if err != nil && safeSession.InTransaction() && vcursor.hasPartialDML {
_ = e.txConn.Rollback(ctx, safeSession)
err = vterrors.Errorf(vtrpcpb.Code_ABORTED, "transaction rolled back due to partial DML execution: %v", err)
}
plan.AddStats(1, time.Since(logStats.StartTime), uint64(logStats.ShardQueries), logStats.RowsAffected, errCount)
return qr, err
}
func (e *Executor) destinationExec(ctx context.Context, safeSession *SafeSession, sql string, bindVars map[string]*querypb.BindVariable, dest key.Destination, destKeyspace string, destTabletType topodatapb.TabletType, logStats *LogStats) (*sqltypes.Result, error) {
return e.resolver.Execute(ctx, sql, bindVars, destKeyspace, destTabletType, dest, safeSession.Session, false /* notInTransaction */, safeSession.Options, logStats)
}
func (e *Executor) handleDDL(ctx context.Context, safeSession *SafeSession, sql string, bindVars map[string]*querypb.BindVariable, dest key.Destination, destKeyspace string, destTabletType topodatapb.TabletType, logStats *LogStats) (*sqltypes.Result, error) {
// Parse the statement to handle vindex operations
// If the statement failed to be properly parsed, fall through anyway
// to broadcast the ddl to all shards.
stmt, _ := sqlparser.Parse(sql)
ddl, ok := stmt.(*sqlparser.DDL)
if ok {
execStart := time.Now()
logStats.PlanTime = execStart.Sub(logStats.StartTime)
switch ddl.Action {
case sqlparser.CreateVindexStr,
sqlparser.AddVschemaTableStr,
sqlparser.DropVschemaTableStr,
sqlparser.AddColVindexStr,
sqlparser.DropColVindexStr:
err := e.handleVSchemaDDL(ctx, safeSession, dest, destKeyspace, destTabletType, ddl, logStats)
logStats.ExecuteTime = time.Since(execStart)
return &sqltypes.Result{}, err
default:
// fallthrough to broadcast the ddl to all shards
}
}
if destKeyspace == "" {
return nil, errNoKeyspace
}
if dest == nil {
dest = key.DestinationAllShards{}
}
execStart := time.Now()
logStats.PlanTime = execStart.Sub(logStats.StartTime)
result, err := e.destinationExec(ctx, safeSession, sql, bindVars, dest, destKeyspace, destTabletType, logStats)
logStats.ExecuteTime = time.Since(execStart)
queriesProcessed.Add("DDL", 1)
queriesRouted.Add("DDL", int64(logStats.ShardQueries))
return result, err
}
func (e *Executor) handleVSchemaDDL(ctx context.Context, safeSession *SafeSession, dest key.Destination, destKeyspace string, destTabletType topodatapb.TabletType, ddl *sqlparser.DDL, logStats *LogStats) error {
vschema := e.vm.GetCurrentSrvVschema()
if vschema == nil {
return vterrors.Errorf(vtrpcpb.Code_INTERNAL, "vschema not loaded")
}
allowed := vschemaacl.Authorized(callerid.ImmediateCallerIDFromContext(ctx))
if !allowed {
return vterrors.Errorf(vtrpcpb.Code_PERMISSION_DENIED, "not authorized to perform vschema operations")
}
// Resolve the keyspace either from the table qualifier or the target keyspace
var ksName string
if !ddl.Table.IsEmpty() {
ksName = ddl.Table.Qualifier.String()
}
if ksName == "" {
ksName = destKeyspace
}
if ksName == "" {
return errNoKeyspace
}
ks, _ := vschema.Keyspaces[ksName]
ks, err := topotools.ApplyVSchemaDDL(ksName, ks, ddl)
if err != nil {
return err
}
vschema.Keyspaces[ksName] = ks
return e.vm.UpdateVSchema(ctx, ksName, vschema)
}
func (e *Executor) handleBegin(ctx context.Context, safeSession *SafeSession, sql string, bindVars map[string]*querypb.BindVariable, destTabletType topodatapb.TabletType, logStats *LogStats) (*sqltypes.Result, error) {
if destTabletType != topodatapb.TabletType_MASTER {
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "transactions are supported only for master tablet types, current type: %v", destTabletType)
}
execStart := time.Now()
logStats.PlanTime = execStart.Sub(logStats.StartTime)
err := e.txConn.Begin(ctx, safeSession)
logStats.ExecuteTime = time.Since(execStart)
queriesProcessed.Add("Begin", 1)
return &sqltypes.Result{}, err
}
func (e *Executor) handleCommit(ctx context.Context, safeSession *SafeSession, sql string, bindVars map[string]*querypb.BindVariable, logStats *LogStats) (*sqltypes.Result, error) {
execStart := time.Now()
logStats.PlanTime = execStart.Sub(logStats.StartTime)
logStats.ShardQueries = uint32(len(safeSession.ShardSessions))
queriesProcessed.Add("Commit", 1)
queriesRouted.Add("Commit", int64(logStats.ShardQueries))
err := e.txConn.Commit(ctx, safeSession)
logStats.CommitTime = time.Since(execStart)
return &sqltypes.Result{}, err
}
func (e *Executor) handleRollback(ctx context.Context, safeSession *SafeSession, sql string, bindVars map[string]*querypb.BindVariable, logStats *LogStats) (*sqltypes.Result, error) {
execStart := time.Now()
logStats.PlanTime = execStart.Sub(logStats.StartTime)
logStats.ShardQueries = uint32(len(safeSession.ShardSessions))
queriesProcessed.Add("Rollback", 1)
queriesRouted.Add("Rollback", int64(logStats.ShardQueries))
err := e.txConn.Rollback(ctx, safeSession)
logStats.CommitTime = time.Since(execStart)
return &sqltypes.Result{}, err
}
func (e *Executor) handleSet(ctx context.Context, safeSession *SafeSession, sql string, bindVars map[string]*querypb.BindVariable, logStats *LogStats) (*sqltypes.Result, error) {
vals, scope, err := sqlparser.ExtractSetValues(sql)
execStart := time.Now()
logStats.PlanTime = execStart.Sub(logStats.StartTime)
defer func() {
logStats.ExecuteTime = time.Since(execStart)
}()
if err != nil {
return &sqltypes.Result{}, vterrors.New(vtrpcpb.Code_INVALID_ARGUMENT, err.Error())
}
if scope == sqlparser.GlobalStr {
return &sqltypes.Result{}, vterrors.New(vtrpcpb.Code_INVALID_ARGUMENT, "unsupported in set: global")
}
for k, v := range vals {
if k.Scope == sqlparser.GlobalStr {
return &sqltypes.Result{}, vterrors.New(vtrpcpb.Code_INVALID_ARGUMENT, "unsupported in set: global")
}
switch k.Key {
case "autocommit":
val, err := validateSetOnOff(v, k.Key)
if err != nil {
return nil, err
}
switch val {
case 0:
safeSession.Autocommit = false
case 1:
if safeSession.InTransaction() {
if err := e.txConn.Commit(ctx, safeSession); err != nil {
return nil, err
}
}
safeSession.Autocommit = true
default:
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "unexpected value for autocommit: %d", val)
}
case "client_found_rows":
val, ok := v.(int64)
if !ok {
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "unexpected value type for client_found_rows: %T", v)
}
if safeSession.Options == nil {
safeSession.Options = &querypb.ExecuteOptions{}
}
switch val {
case 0:
safeSession.Options.ClientFoundRows = false
case 1:
safeSession.Options.ClientFoundRows = true
default:
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "unexpected value for client_found_rows: %d", val)
}
case "skip_query_plan_cache":
val, ok := v.(int64)
if !ok {
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "unexpected value type for skip_query_plan_cache: %T", v)
}
if safeSession.Options == nil {
safeSession.Options = &querypb.ExecuteOptions{}
}
switch val {
case 0:
safeSession.Options.SkipQueryPlanCache = false
case 1:
safeSession.Options.SkipQueryPlanCache = true
default:
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "unexpected value for skip_query_plan_cache: %d", val)
}
case "sql_safe_updates":
val, err := validateSetOnOff(v, k.Key)
if err != nil {
return nil, err
}
switch val {
case 0, 1:
// no op
default:
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "unexpected value for sql_safe_updates: %d", val)
}
case "transaction_mode":
val, ok := v.(string)
if !ok {
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "unexpected value type for transaction_mode: %T", v)
}
out, ok := vtgatepb.TransactionMode_value[strings.ToUpper(val)]
if !ok {
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "invalid transaction_mode: %s", val)
}
safeSession.TransactionMode = vtgatepb.TransactionMode(out)
case sqlparser.TransactionStr:
// Parser ensures it's well-formed.
// TODO: This is a NOP, modeled off of tx_isolation and tx_read_only. It's incredibly
// dangerous that it's a NOP, but fixing that is left to. Note that vtqueryservice needs
// to be updated as well:
// https://github.com/vitessio/vitess/issues/4127
case "tx_isolation":
val, ok := v.(string)
if !ok {
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "unexpected value type for tx_isolation: %T", v)
}
switch val {
case "repeatable read", "read committed", "read uncommitted", "serializable":
// TODO (4127): This is a dangerous NOP.
default:
return nil, fmt.Errorf("unexpected value for tx_isolation: %v", val)
}
case "tx_read_only":
val, err := validateSetOnOff(v, k.Key)
if err != nil {
return nil, err
}
switch val {
case 0, 1:
// TODO (4127): This is a dangerous NOP.
default:
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "unexpected value for tx_read_only: %d", val)
}
case "workload":
val, ok := v.(string)
if !ok {
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "unexpected value type for workload: %T", v)
}
out, ok := querypb.ExecuteOptions_Workload_value[strings.ToUpper(val)]
if !ok {
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "invalid workload: %s", val)
}
if safeSession.Options == nil {
safeSession.Options = &querypb.ExecuteOptions{}
}
safeSession.Options.Workload = querypb.ExecuteOptions_Workload(out)
case "sql_select_limit":
var val int64
switch cast := v.(type) {
case int64:
val = cast
case string:
if !strings.EqualFold(cast, "default") {
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "unexpected string value for sql_select_limit: %v", v)
}
default:
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "unexpected value type for sql_select_limit: %T", v)
}
if safeSession.Options == nil {
safeSession.Options = &querypb.ExecuteOptions{}
}
safeSession.Options.SqlSelectLimit = val
case "sql_auto_is_null":
val, ok := v.(int64)
if !ok {
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "unexpected value type for sql_auto_is_null: %T", v)
}
switch val {
case 0:
// This is the default setting for MySQL. Do nothing.
case 1:
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "sql_auto_is_null is not currently supported")
default:
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "unexpected value for sql_auto_is_null: %d", val)
}
case "character_set_results":
// This is a statement that mysql-connector-j sends at the beginning. We return a canned response for it.
switch v {
case nil, "utf8", "utf8mb4", "latin1":
default:
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "disallowed value for character_set_results: %v", v)
}
case "wait_timeout":
_, ok := v.(int64)
if !ok {
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "unexpected value type for wait_timeout: %T", v)
}
case "net_write_timeout", "net_read_timeout", "lc_messages", "collation_connection":
log.Warningf("Ignored inapplicable SET %v = %v", k, v)
warnings.Add("IgnoredSet", 1)
case "charset", "names":
val, ok := v.(string)
if !ok {
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "unexpected value type for charset/names: %T", v)
}
switch val {
case "", "utf8", "utf8mb4", "latin1", "default":
break
default:
return nil, fmt.Errorf("unexpected value for charset/names: %v", val)
}
default:
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "unsupported construct: %s", sql)
}
}
return &sqltypes.Result{}, nil
}
func validateSetOnOff(v interface{}, typ string) (int64, error) {
var val int64
switch v := v.(type) {
case int64:
val = v
case string:
lcaseV := strings.ToLower(v)
if lcaseV == "on" {
val = 1
} else if lcaseV == "off" {
val = 0
} else {
return -1, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "unexpected value for %s: %s", typ, v)
}
default:
return -1, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "unexpected value type for %s: %T", typ, v)
}
return val, nil
}
func (e *Executor) handleShow(ctx context.Context, safeSession *SafeSession, sql string, bindVars map[string]*querypb.BindVariable, dest key.Destination, destKeyspace string, destTabletType topodatapb.TabletType, logStats *LogStats) (*sqltypes.Result, error) {
stmt, err := sqlparser.Parse(sql)
if err != nil {
return nil, err
}
show, ok := stmt.(*sqlparser.Show)
if !ok {
// This code is unreachable.
return nil, vterrors.Errorf(vtrpcpb.Code_INTERNAL, "unrecognized SHOW statement: %v", sql)
}
execStart := time.Now()
defer func() { logStats.ExecuteTime = time.Since(execStart) }()
switch show.Type {
case sqlparser.KeywordString(sqlparser.COLLATION), sqlparser.KeywordString(sqlparser.VARIABLES):
if destKeyspace == "" {
keyspaces, err := e.resolver.resolver.GetAllKeyspaces(ctx)
if err != nil {
return nil, err
}
if len(keyspaces) == 0 {
return nil, vterrors.Errorf(vtrpcpb.Code_FAILED_PRECONDITION, "no keyspaces available")
}
return e.handleOther(ctx, safeSession, sql, bindVars, dest, keyspaces[0], destTabletType, logStats)
}
// for STATUS, return empty result set
case sqlparser.KeywordString(sqlparser.STATUS):
return &sqltypes.Result{
Fields: buildVarCharFields("Variable_name", "Value"),
Rows: make([][]sqltypes.Value, 0, 2),
RowsAffected: 0,
}, nil
// for ENGINES, we want to return just InnoDB
case sqlparser.KeywordString(sqlparser.ENGINES):
rows := make([][]sqltypes.Value, 0, 6)
row := buildVarCharRow(
"InnoDB",
"DEFAULT",
"Supports transactions, row-level locking, and foreign keys",
"YES",
"YES",
"YES")
rows = append(rows, row)
return &sqltypes.Result{
Fields: buildVarCharFields("Engine", "Support", "Comment", "Transactions", "XA", "Savepoints"),
Rows: rows,
RowsAffected: 1,
}, nil
// for PLUGINS, return InnoDb + mysql_native_password
case sqlparser.KeywordString(sqlparser.PLUGINS):
rows := make([][]sqltypes.Value, 0, 5)
row := buildVarCharRow(
"InnoDB",
"ACTIVE",
"STORAGE ENGINE",
"NULL",
"GPL")
rows = append(rows, row)
return &sqltypes.Result{
Fields: buildVarCharFields("Name", "Status", "Type", "Library", "License"),
Rows: rows,
RowsAffected: 1,
}, nil
// CHARSET & CHARACTER SET return utf8mb4 & utf8
case sqlparser.KeywordString(sqlparser.CHARSET):
fields := buildVarCharFields("Charset", "Description", "Default collation")
maxLenField := &querypb.Field{Name: "Maxlen", Type: sqltypes.Int32}
fields = append(fields, maxLenField)
rows := make([][]sqltypes.Value, 0, 4)
row0 := buildVarCharRow(
"utf8",
"UTF-8 Unicode",
"utf8_general_ci")
row0 = append(row0, sqltypes.NewInt32(3))
row1 := buildVarCharRow(
"utf8mb4",
"UTF-8 Unicode",
"utf8mb4_general_ci")
row1 = append(row1, sqltypes.NewInt32(4))
rows = append(rows, row0, row1)
return &sqltypes.Result{
Fields: fields,
Rows: rows,
RowsAffected: 2,
}, nil
case sqlparser.KeywordString(sqlparser.TABLES):
if show.ShowTablesOpt != nil && show.ShowTablesOpt.DbName != "" {
show.ShowTablesOpt.DbName = ""
}
sql = sqlparser.String(show)
case sqlparser.KeywordString(sqlparser.DATABASES), sqlparser.KeywordString(sqlparser.VITESS_KEYSPACES):
keyspaces, err := e.resolver.resolver.GetAllKeyspaces(ctx)
if err != nil {
return nil, err
}
rows := make([][]sqltypes.Value, len(keyspaces))
for i, v := range keyspaces {
rows[i] = buildVarCharRow(v)
}
return &sqltypes.Result{
Fields: buildVarCharFields("Databases"),
Rows: rows,
RowsAffected: uint64(len(rows)),
}, nil
case sqlparser.KeywordString(sqlparser.VITESS_SHARDS):
keyspaces, err := e.resolver.resolver.GetAllKeyspaces(ctx)
if err != nil {
return nil, err
}
var rows [][]sqltypes.Value
for _, keyspace := range keyspaces {
_, _, shards, err := e.resolver.resolver.GetKeyspaceShards(ctx, keyspace, destTabletType)
if err != nil {
// There might be a misconfigured keyspace or no shards in the keyspace.
// Skip any errors and move on.
continue
}
for _, shard := range shards {
rows = append(rows, buildVarCharRow(topoproto.KeyspaceShardString(keyspace, shard.Name)))
}
}
return &sqltypes.Result{
Fields: buildVarCharFields("Shards"),
Rows: rows,
RowsAffected: uint64(len(rows)),
}, nil
case sqlparser.KeywordString(sqlparser.VITESS_TABLETS):
var rows [][]sqltypes.Value
stats := e.scatterConn.healthCheck.CacheStatus()
for _, s := range stats {
for _, ts := range s.TabletsStats {
state := "SERVING"
if !ts.Serving {
state = "NOT_SERVING"
}
rows = append(rows, buildVarCharRow(
s.Cell,
s.Target.Keyspace,
s.Target.Shard,
ts.Target.TabletType.String(),
state,
topoproto.TabletAliasString(ts.Tablet.Alias),
ts.Tablet.Hostname,
))
}
}
return &sqltypes.Result{
Fields: buildVarCharFields("Cell", "Keyspace", "Shard", "TabletType", "State", "Alias", "Hostname"),
Rows: rows,
RowsAffected: uint64(len(rows)),
}, nil
case sqlparser.KeywordString(sqlparser.VITESS_TARGET):
var rows [][]sqltypes.Value
rows = append(rows, buildVarCharRow(safeSession.TargetString))
return &sqltypes.Result{
Fields: buildVarCharFields("Target"),
Rows: rows,
RowsAffected: uint64(len(rows)),
}, nil
case "vschema tables":
if destKeyspace == "" {
return nil, errNoKeyspace
}
ks, ok := e.VSchema().Keyspaces[destKeyspace]
if !ok {
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "keyspace %s not found in vschema", destKeyspace)
}
var tables []string
for name := range ks.Tables {
tables = append(tables, name)
}
sort.Strings(tables)
rows := make([][]sqltypes.Value, len(tables))
for i, v := range tables {
rows[i] = buildVarCharRow(v)
}
return &sqltypes.Result{
Fields: buildVarCharFields("Tables"),
Rows: rows,
RowsAffected: uint64(len(rows)),
}, nil
case "vschema vindexes":
vschema := e.vm.GetCurrentSrvVschema()
if vschema == nil {
return nil, vterrors.Errorf(vtrpcpb.Code_INTERNAL, "vschema not loaded")
}
rows := make([][]sqltypes.Value, 0, 16)
if show.HasOnTable() {
// If the table reference is not fully qualified, then
// pull the keyspace from the session. Fail if the keyspace
// isn't specified or isn't valid, or if the table isn't
// known.
ksName := show.OnTable.Qualifier.String()
if ksName == "" {
ksName = destKeyspace
}
ks, ok := vschema.Keyspaces[ksName]
if !ok {
return nil, errNoKeyspace
}
tableName := show.OnTable.Name.String()
table, ok := ks.Tables[tableName]
if !ok {
return nil, vterrors.Errorf(vtrpcpb.Code_INTERNAL, "table `%s` does not exist in keyspace `%s`", tableName, ksName)
}
for _, colVindex := range table.ColumnVindexes {
vindex, ok := ks.Vindexes[colVindex.GetName()]
columns := colVindex.GetColumns()
if len(columns) == 0 {
columns = []string{colVindex.GetColumn()}
}
if ok {
params := make([]string, 0, 4)
for k, v := range vindex.GetParams() {
params = append(params, fmt.Sprintf("%s=%s", k, v))
}
sort.Strings(params)
rows = append(rows, buildVarCharRow(strings.Join(columns, ", "), colVindex.GetName(), vindex.GetType(), strings.Join(params, "; "), vindex.GetOwner()))
} else {
rows = append(rows, buildVarCharRow(strings.Join(columns, ", "), colVindex.GetName(), "", "", ""))
}
}
return &sqltypes.Result{
Fields: buildVarCharFields("Columns", "Name", "Type", "Params", "Owner"),
Rows: rows,
RowsAffected: uint64(len(rows)),
}, nil
}
// For the query interface to be stable we need to sort
// for each of the map iterations
ksNames := make([]string, 0, len(vschema.Keyspaces))
for name := range vschema.Keyspaces {
ksNames = append(ksNames, name)
}
sort.Strings(ksNames)
for _, ksName := range ksNames {
ks, _ := vschema.Keyspaces[ksName]
vindexNames := make([]string, 0, len(ks.Vindexes))
for name := range ks.Vindexes {
vindexNames = append(vindexNames, name)
}
sort.Strings(vindexNames)
for _, vindexName := range vindexNames {
vindex, _ := ks.Vindexes[vindexName]
params := make([]string, 0, 4)
for k, v := range vindex.GetParams() {
params = append(params, fmt.Sprintf("%s=%s", k, v))
}
sort.Strings(params)
rows = append(rows, buildVarCharRow(ksName, vindexName, vindex.GetType(), strings.Join(params, "; "), vindex.GetOwner()))
}
}
return &sqltypes.Result{
Fields: buildVarCharFields("Keyspace", "Name", "Type", "Params", "Owner"),
Rows: rows,
RowsAffected: uint64(len(rows)),
}, nil
case sqlparser.KeywordString(sqlparser.WARNINGS):
fields := []*querypb.Field{
{Name: "Level", Type: sqltypes.VarChar},
{Name: "Type", Type: sqltypes.Uint16},
{Name: "Message", Type: sqltypes.VarChar},
}
rows := make([][]sqltypes.Value, 0, 0)
if safeSession.Warnings != nil {
for _, warning := range safeSession.Warnings {
rows = append(rows, []sqltypes.Value{
sqltypes.NewVarChar("Warning"),
sqltypes.NewUint32(warning.Code),
sqltypes.NewVarChar(warning.Message),
})
}
}
return &sqltypes.Result{
Fields: fields,
Rows: rows,
}, nil
}
// Any other show statement is passed through
return e.handleOther(ctx, safeSession, sql, bindVars, dest, destKeyspace, destTabletType, logStats)
}
func (e *Executor) handleUse(ctx context.Context, safeSession *SafeSession, sql string, bindVars map[string]*querypb.BindVariable) (*sqltypes.Result, error) {
stmt, err := sqlparser.Parse(sql)
if err != nil {
return nil, err
}
use, ok := stmt.(*sqlparser.Use)
if !ok {
// This code is unreachable.
return nil, vterrors.Errorf(vtrpcpb.Code_INTERNAL, "unrecognized USE statement: %v", sql)
}
destKeyspace, destTabletType, _, err := e.ParseDestinationTarget(use.DBName.String())
if err != nil {
return nil, err
}
if _, ok := e.VSchema().Keyspaces[destKeyspace]; destKeyspace != "" && !ok {
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "invalid keyspace provided: %s", destKeyspace)
}
if safeSession.InTransaction() && destTabletType != topodatapb.TabletType_MASTER {
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "cannot change to a non-master type in the middle of a transaction: %v", destTabletType)
}
safeSession.TargetString = use.DBName.String()
return &sqltypes.Result{}, nil
}
func (e *Executor) handleOther(ctx context.Context, safeSession *SafeSession, sql string, bindVars map[string]*querypb.BindVariable, dest key.Destination, destKeyspace string, destTabletType topodatapb.TabletType, logStats *LogStats) (*sqltypes.Result, error) {
if destKeyspace == "" {
return nil, errNoKeyspace
}
if dest == nil {
// shardExec will re-resolve this a bit later.
rss, err := e.resolver.resolver.ResolveDestination(ctx, destKeyspace, destTabletType, key.DestinationAnyShard{})
if err != nil {
return nil, err