-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
query_executor.go
1267 lines (1154 loc) · 41.6 KB
/
query_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 2019 The Vitess Authors.
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 tabletserver
import (
"context"
"fmt"
"io"
"strings"
"sync"
"time"
"google.golang.org/protobuf/proto"
"vitess.io/vitess/go/mysql"
"vitess.io/vitess/go/mysql/collations"
"vitess.io/vitess/go/pools"
"vitess.io/vitess/go/sqltypes"
"vitess.io/vitess/go/trace"
"vitess.io/vitess/go/vt/callerid"
"vitess.io/vitess/go/vt/callinfo"
"vitess.io/vitess/go/vt/log"
"vitess.io/vitess/go/vt/schema"
"vitess.io/vitess/go/vt/sqlparser"
"vitess.io/vitess/go/vt/tableacl"
"vitess.io/vitess/go/vt/vterrors"
"vitess.io/vitess/go/vt/vtgate/evalengine"
"vitess.io/vitess/go/vt/vttablet/tabletserver/connpool"
p "vitess.io/vitess/go/vt/vttablet/tabletserver/planbuilder"
"vitess.io/vitess/go/vt/vttablet/tabletserver/rules"
"vitess.io/vitess/go/vt/vttablet/tabletserver/tabletenv"
querypb "vitess.io/vitess/go/vt/proto/query"
topodatapb "vitess.io/vitess/go/vt/proto/topodata"
vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc"
)
// QueryExecutor is used for executing a query request.
type QueryExecutor struct {
query string
marginComments sqlparser.MarginComments
bindVars map[string]*querypb.BindVariable
connID int64
options *querypb.ExecuteOptions
plan *TabletPlan
ctx context.Context
logStats *tabletenv.LogStats
tsv *TabletServer
tabletType topodatapb.TabletType
setting *pools.Setting
}
const (
streamRowsSize = 256
maxQueryBufferDuration = 10 * time.Second
)
var (
streamResultPool = sync.Pool{New: func() any {
return &sqltypes.Result{
Rows: make([][]sqltypes.Value, 0, streamRowsSize),
}
}}
sequenceFields = []*querypb.Field{
{
Name: "nextval",
Type: sqltypes.Int64,
},
}
)
func returnStreamResult(result *sqltypes.Result) error {
// only return large results slices to the pool
if cap(result.Rows) >= streamRowsSize {
rows := result.Rows[:0]
*result = sqltypes.Result{}
result.Rows = rows
streamResultPool.Put(result)
}
return nil
}
func allocStreamResult() *sqltypes.Result {
return streamResultPool.Get().(*sqltypes.Result)
}
func (qre *QueryExecutor) shouldConsolidate() bool {
co := qre.options.GetConsolidator()
switch co {
case querypb.ExecuteOptions_CONSOLIDATOR_DISABLED:
return false
case querypb.ExecuteOptions_CONSOLIDATOR_ENABLED:
return true
case querypb.ExecuteOptions_CONSOLIDATOR_ENABLED_REPLICAS:
return qre.tabletType != topodatapb.TabletType_PRIMARY
default:
cm := qre.tsv.qe.consolidatorMode.Get()
return cm == tabletenv.Enable || (cm == tabletenv.NotOnPrimary && qre.tabletType != topodatapb.TabletType_PRIMARY)
}
}
// Execute performs a non-streaming query execution.
func (qre *QueryExecutor) Execute() (reply *sqltypes.Result, err error) {
planName := qre.plan.PlanID.String()
qre.logStats.PlanType = planName
defer func(start time.Time) {
duration := time.Since(start)
qre.tsv.stats.QueryTimings.Add(planName, duration)
qre.recordUserQuery("Execute", int64(duration))
mysqlTime := qre.logStats.MysqlResponseTime
tableName := qre.plan.TableName().String()
if tableName == "" {
tableName = "Join"
}
if reply == nil {
qre.tsv.qe.AddStats(qre.plan.PlanID, tableName, 1, duration, mysqlTime, 0, 0, 1)
qre.plan.AddStats(1, duration, mysqlTime, 0, 0, 1)
return
}
qre.tsv.qe.AddStats(qre.plan.PlanID, tableName, 1, duration, mysqlTime, int64(reply.RowsAffected), int64(len(reply.Rows)), 0)
qre.plan.AddStats(1, duration, mysqlTime, reply.RowsAffected, uint64(len(reply.Rows)), 0)
qre.logStats.RowsAffected = int(reply.RowsAffected)
qre.logStats.Rows = reply.Rows
qre.tsv.Stats().ResultHistogram.Add(int64(len(reply.Rows)))
}(time.Now())
if err = qre.checkPermissions(); err != nil {
return nil, err
}
if qre.plan.PlanID == p.PlanNextval {
return qre.execNextval()
}
if qre.connID != 0 {
var conn *StatefulConnection
// Need upfront connection for DMLs and transactions
conn, err = qre.tsv.te.txPool.GetAndLock(qre.connID, "for query")
if err != nil {
return nil, err
}
defer conn.Unlock()
if qre.setting != nil {
if err = conn.ApplySetting(qre.ctx, qre.setting); err != nil {
return nil, vterrors.Wrap(err, "failed to execute system setting on the connection")
}
}
return qre.txConnExec(conn)
}
switch qre.plan.PlanID {
case p.PlanSelect, p.PlanSelectImpossible, p.PlanShow:
maxrows := qre.getSelectLimit()
qre.bindVars["#maxLimit"] = sqltypes.Int64BindVariable(maxrows + 1)
if qre.bindVars[sqltypes.BvReplaceSchemaName] != nil {
qre.bindVars[sqltypes.BvSchemaName] = sqltypes.StringBindVariable(qre.tsv.config.DB.DBName)
}
qr, err := qre.execSelect()
if err != nil {
return nil, err
}
if err := qre.verifyRowCount(int64(len(qr.Rows)), maxrows); err != nil {
return nil, err
}
return qr, nil
case p.PlanOtherRead, p.PlanOtherAdmin, p.PlanFlush, p.PlanSavepoint, p.PlanRelease, p.PlanSRollback:
return qre.execOther()
case p.PlanInsert, p.PlanUpdate, p.PlanDelete, p.PlanInsertMessage, p.PlanDDL, p.PlanLoad:
return qre.execAutocommit(qre.txConnExec)
case p.PlanViewDDL:
switch qre.plan.FullStmt.(type) {
case *sqlparser.DropView:
return qre.execAutocommit(qre.execDropViewDDL)
default:
return qre.execAsTransaction(qre.execViewDDL)
}
case p.PlanUpdateLimit, p.PlanDeleteLimit:
return qre.execAsTransaction(qre.txConnExec)
case p.PlanCallProc:
return qre.execCallProc()
case p.PlanAlterMigration:
return qre.execAlterMigration()
case p.PlanRevertMigration:
return qre.execRevertMigration()
case p.PlanShowMigrationLogs:
return qre.execShowMigrationLogs()
case p.PlanShowThrottledApps:
return qre.execShowThrottledApps()
case p.PlanShowThrottlerStatus:
return qre.execShowThrottlerStatus()
case p.PlanSet:
if qre.setting == nil {
return nil, vterrors.Errorf(vtrpcpb.Code_FAILED_PRECONDITION, "[BUG] %s not allowed without setting connection", qre.query)
}
// The execution is not required as this setting will be applied when any other query type is executed.
return &sqltypes.Result{}, nil
}
return nil, vterrors.Errorf(vtrpcpb.Code_INTERNAL, "[BUG] %s unexpected plan type", qre.plan.PlanID.String())
}
func (qre *QueryExecutor) execAutocommit(f func(conn *StatefulConnection) (*sqltypes.Result, error)) (reply *sqltypes.Result, err error) {
if qre.options == nil {
qre.options = &querypb.ExecuteOptions{}
} else {
qre.options = proto.Clone(qre.options).(*querypb.ExecuteOptions)
}
qre.options.TransactionIsolation = querypb.ExecuteOptions_AUTOCOMMIT
conn, _, _, err := qre.tsv.te.txPool.Begin(qre.ctx, qre.options, false, 0, nil, qre.setting)
if err != nil {
return nil, err
}
defer qre.tsv.te.txPool.RollbackAndRelease(qre.ctx, conn)
return f(conn)
}
func (qre *QueryExecutor) execAsTransaction(f func(conn *StatefulConnection) (*sqltypes.Result, error)) (*sqltypes.Result, error) {
conn, beginSQL, _, err := qre.tsv.te.txPool.Begin(qre.ctx, qre.options, false, 0, nil, qre.setting)
if err != nil {
return nil, err
}
defer qre.tsv.te.txPool.RollbackAndRelease(qre.ctx, conn)
qre.logStats.AddRewrittenSQL(beginSQL, time.Now())
result, err := f(conn)
if err != nil {
// dbConn is nil, it means the transaction was aborted.
// If so, we should not relog the rollback.
// TODO(sougou): these txPool functions should take the logstats
// and log any statements they issue. This needs to be done as
// a separate refactor because it impacts lot of code.
if conn.IsInTransaction() {
defer qre.logStats.AddRewrittenSQL("rollback", time.Now())
}
return nil, err
}
defer qre.logStats.AddRewrittenSQL("commit", time.Now())
if _, err := qre.tsv.te.txPool.Commit(qre.ctx, conn); err != nil {
return nil, err
}
return result, nil
}
func (qre *QueryExecutor) txConnExec(conn *StatefulConnection) (*sqltypes.Result, error) {
switch qre.plan.PlanID {
case p.PlanInsert, p.PlanUpdate, p.PlanDelete, p.PlanSet:
return qre.txFetch(conn, true)
case p.PlanInsertMessage:
qre.bindVars["#time_now"] = sqltypes.Int64BindVariable(time.Now().UnixNano())
return qre.txFetch(conn, true)
case p.PlanUpdateLimit, p.PlanDeleteLimit:
return qre.execDMLLimit(conn)
case p.PlanOtherRead, p.PlanOtherAdmin, p.PlanFlush:
return qre.execStatefulConn(conn, qre.query, true)
case p.PlanSavepoint, p.PlanRelease, p.PlanSRollback:
return qre.execStatefulConn(conn, qre.query, true)
case p.PlanSelect, p.PlanSelectImpossible, p.PlanShow, p.PlanSelectLockFunc:
maxrows := qre.getSelectLimit()
qre.bindVars["#maxLimit"] = sqltypes.Int64BindVariable(maxrows + 1)
if qre.bindVars[sqltypes.BvReplaceSchemaName] != nil {
qre.bindVars[sqltypes.BvSchemaName] = sqltypes.StringBindVariable(qre.tsv.config.DB.DBName)
}
qr, err := qre.txFetch(conn, false)
if err != nil {
return nil, err
}
if err := qre.verifyRowCount(int64(len(qr.Rows)), maxrows); err != nil {
return nil, err
}
return qr, nil
case p.PlanDDL:
return qre.execDDL(conn)
case p.PlanLoad:
return qre.execLoad(conn)
case p.PlanCallProc:
return qre.execProc(conn)
}
return nil, vterrors.Errorf(vtrpcpb.Code_INTERNAL, "[BUG] %s unexpected plan type", qre.plan.PlanID.String())
}
func (qre *QueryExecutor) execViewDDL(conn *StatefulConnection) (*sqltypes.Result, error) {
var err error
switch stmt := qre.plan.FullStmt.(type) {
case *sqlparser.CreateView:
_, err = qre.execCreateViewDDL(conn, stmt)
case *sqlparser.AlterView:
_, err = qre.execAlterViewDDL(conn, stmt)
default:
err = vterrors.Errorf(vtrpcpb.Code_INTERNAL, "BUG: unexpected view DDL type: %T", qre.plan.FullStmt)
}
if err != nil {
return nil, err
}
// We need to use a different connection for executing the DDL on MySQL
// because the previous DMLs are running in a transaction and we don't want to autocommit
// those changes.
ddlConn, err := qre.getConn()
if err != nil {
return nil, err
}
defer ddlConn.Recycle()
// If MySQL fails, then we will Rollback the changes.
return ddlConn.Exec(qre.ctx, sqlparser.String(qre.plan.FullStmt), 1000, true)
}
func (qre *QueryExecutor) execCreateViewDDL(conn *StatefulConnection, stmt *sqlparser.CreateView) (*sqltypes.Result, error) {
bindVars := generateBindVarsForViewDDLInsert(stmt)
sql, _, err := qre.generateFinalSQL(qre.plan.FullQuery, bindVars)
if err != nil {
return nil, err
}
qr, err := execWithDDLView(qre.ctx, conn, sql)
if err != nil {
sqlErr, isSQLErr := mysql.NewSQLErrorFromError(err).(*mysql.SQLError)
// If it is a MySQL error and its code is of duplicate entry,
// then we would return duplicate create view error.
if isSQLErr && sqlErr.Number() == mysql.ERDupEntry {
return nil, vterrors.Errorf(vtrpcpb.Code_ALREADY_EXISTS, "Table '%s' already exists", stmt.ViewName.Name.String())
}
return nil, err
}
return qr, nil
}
func (qre *QueryExecutor) execAlterViewDDL(conn *StatefulConnection, stmt *sqlparser.AlterView) (*sqltypes.Result, error) {
createViewDDL := &sqlparser.CreateView{
ViewName: stmt.ViewName,
Algorithm: stmt.Algorithm,
Definer: stmt.Definer,
Security: stmt.Security,
Columns: stmt.Columns,
Select: stmt.Select,
CheckOption: stmt.CheckOption,
Comments: stmt.Comments,
}
bindVars := generateBindVarsForViewDDLInsert(createViewDDL)
sql, _, err := qre.generateFinalSQL(qre.plan.FullQuery, bindVars)
if err != nil {
return nil, err
}
qr, err := execWithDDLView(qre.ctx, conn, sql)
if err != nil {
return nil, err
}
if qr.RowsAffected == 0 {
return nil, vterrors.Errorf(vtrpcpb.Code_NOT_FOUND, "Table '%s' does not exist", stmt.ViewName.Name.String())
}
return qr, nil
}
func (qre *QueryExecutor) execDropViewDDL(conn *StatefulConnection) (*sqltypes.Result, error) {
viewsMap := make(map[string]int)
stmt := qre.plan.FullStmt.(*sqlparser.DropView)
var viewNames []string
for pos, view := range stmt.FromTables {
viewName := view.Name.String()
if _, exists := viewsMap[viewName]; exists {
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "Not unique view: '%s'", viewName)
}
viewNames = append(viewNames, viewName)
viewsMap[viewName] = pos
}
viewNamesBV, err := sqltypes.BuildBindVariable(viewNames)
if err != nil {
return nil, err
}
bindVars := map[string]*querypb.BindVariable{
"table_name": viewNamesBV,
}
sql, _, err := qre.generateFinalSQL(qre.plan.FullQuery, bindVars)
if err != nil {
return nil, err
}
_, err = execWithDDLView(qre.ctx, conn, sql)
if err != nil {
return nil, err
}
// Drop the view on MySQL too.
return conn.Exec(qre.ctx, sqlparser.String(qre.plan.FullStmt), 1000, true)
}
func execWithDDLView(ctx context.Context, conn *StatefulConnection, sql string) (*sqltypes.Result, error) {
return conn.Exec(ctx, sql, 10000, true)
}
// Stream performs a streaming query execution.
func (qre *QueryExecutor) Stream(callback StreamCallback) error {
qre.logStats.PlanType = qre.plan.PlanID.String()
defer func(start time.Time) {
qre.tsv.stats.QueryTimings.Record(qre.plan.PlanID.String(), start)
qre.recordUserQuery("Stream", int64(time.Since(start)))
}(time.Now())
if err := qre.checkPermissions(); err != nil {
return err
}
switch qre.plan.PlanID {
case p.PlanSelectStream:
if qre.bindVars[sqltypes.BvReplaceSchemaName] != nil {
qre.bindVars[sqltypes.BvSchemaName] = sqltypes.StringBindVariable(qre.tsv.config.DB.DBName)
}
}
sql, sqlWithoutComments, err := qre.generateFinalSQL(qre.plan.FullQuery, qre.bindVars)
if err != nil {
return err
}
var replaceKeyspace string
if sqltypes.IncludeFieldsOrDefault(qre.options) == querypb.ExecuteOptions_ALL && qre.tsv.sm.target.Keyspace != qre.tsv.config.DB.DBName {
replaceKeyspace = qre.tsv.sm.target.Keyspace
}
if consolidator := qre.tsv.qe.streamConsolidator; consolidator != nil {
if qre.connID == 0 && qre.plan.PlanID == p.PlanSelectStream && qre.shouldConsolidate() {
return consolidator.Consolidate(qre.tsv.stats.WaitTimings, qre.logStats, sqlWithoutComments, callback,
func(callback StreamCallback) error {
dbConn, err := qre.getStreamConn()
if err != nil {
return err
}
defer dbConn.Recycle()
return qre.execStreamSQL(dbConn, qre.connID != 0, sql, func(result *sqltypes.Result) error {
// this stream result is potentially used by more than one client, so
// the consolidator will return it to the pool once it knows it's no longer
// being shared
if replaceKeyspace != "" {
result.ReplaceKeyspace(replaceKeyspace)
}
return callback(result)
})
})
}
}
// if we have a transaction id, let's use the txPool for this query
var conn *connpool.DBConn
if qre.connID != 0 {
txConn, err := qre.tsv.te.txPool.GetAndLock(qre.connID, "for streaming query")
if err != nil {
return err
}
defer txConn.Unlock()
if qre.setting != nil {
if err = txConn.ApplySetting(qre.ctx, qre.setting); err != nil {
return vterrors.Wrap(err, "failed to execute system setting on the connection")
}
}
conn = txConn.UnderlyingDBConn()
} else {
dbConn, err := qre.getStreamConn()
if err != nil {
return err
}
defer dbConn.Recycle()
conn = dbConn
}
return qre.execStreamSQL(conn, qre.connID != 0, sql, func(result *sqltypes.Result) error {
// this stream result is only used by the calling client, so it can be
// returned to the pool once the callback has fully returned
defer returnStreamResult(result)
if replaceKeyspace != "" {
result.ReplaceKeyspace(replaceKeyspace)
}
return callback(result)
})
}
// MessageStream streams messages from a message table.
func (qre *QueryExecutor) MessageStream(callback StreamCallback) error {
qre.logStats.OriginalSQL = qre.query
qre.logStats.PlanType = qre.plan.PlanID.String()
defer func(start time.Time) {
qre.tsv.stats.QueryTimings.Record(qre.plan.PlanID.String(), start)
qre.recordUserQuery("MessageStream", int64(time.Since(start)))
}(time.Now())
if err := qre.checkPermissions(); err != nil {
return err
}
done, err := qre.tsv.messager.Subscribe(qre.ctx, qre.plan.TableName().String(), func(r *sqltypes.Result) error {
select {
case <-qre.ctx.Done():
return io.EOF
default:
}
return callback(r)
})
if err != nil {
return err
}
<-done
return nil
}
// checkPermissions returns an error if the query does not pass all checks
// (denied query, table ACL).
func (qre *QueryExecutor) checkPermissions() error {
// Skip permissions check if the context is local.
if tabletenv.IsLocalContext(qre.ctx) {
return nil
}
// Check if the query relates to a table that is in the denylist.
remoteAddr := ""
username := ""
ci, ok := callinfo.FromContext(qre.ctx)
if ok {
remoteAddr = ci.RemoteAddr()
username = ci.Username()
}
bufferingTimeoutCtx, cancel := context.WithTimeout(qre.ctx, maxQueryBufferDuration)
defer cancel()
action, ruleCancelCtx, desc := qre.plan.Rules.GetAction(remoteAddr, username, qre.bindVars, qre.marginComments)
switch action {
case rules.QRFail:
return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "disallowed due to rule: %s", desc)
case rules.QRFailRetry:
return vterrors.Errorf(vtrpcpb.Code_FAILED_PRECONDITION, "disallowed due to rule: %s", desc)
case rules.QRBuffer:
if ruleCancelCtx != nil {
// We buffer up to some timeout. The timeout is determined by ctx.Done().
// If we're not at timeout yet, we fail the query
select {
case <-ruleCancelCtx.Done():
// good! We have buffered the query, and buffering is completed
case <-bufferingTimeoutCtx.Done():
// Sorry, timeout while waiting for buffering to complete
return vterrors.Errorf(vtrpcpb.Code_FAILED_PRECONDITION, "buffer timeout in rule: %s", desc)
}
}
default:
// no rules against this query. Good to proceed
}
// Skip ACL check for queries against the dummy dual table
if qre.plan.TableName().String() == "dual" {
return nil
}
// Skip the ACL check if the connecting user is an exempted superuser.
if qre.tsv.qe.exemptACL != nil && qre.tsv.qe.exemptACL.IsMember(&querypb.VTGateCallerID{Username: username}) {
qre.tsv.qe.tableaclExemptCount.Add(1)
return nil
}
callerID := callerid.ImmediateCallerIDFromContext(qre.ctx)
if callerID == nil {
if qre.tsv.qe.strictTableACL {
return vterrors.Errorf(vtrpcpb.Code_UNAUTHENTICATED, "missing caller id")
}
return nil
}
// Skip the ACL check if the caller id is an exempted superuser.
if qre.tsv.qe.exemptACL != nil && qre.tsv.qe.exemptACL.IsMember(callerID) {
qre.tsv.qe.tableaclExemptCount.Add(1)
return nil
}
for i, auth := range qre.plan.Authorized {
if err := qre.checkAccess(auth, qre.plan.Permissions[i].TableName, callerID); err != nil {
return err
}
}
return nil
}
func (qre *QueryExecutor) checkAccess(authorized *tableacl.ACLResult, tableName string, callerID *querypb.VTGateCallerID) error {
statsKey := []string{tableName, authorized.GroupName, qre.plan.PlanID.String(), callerID.Username}
if !authorized.IsMember(callerID) {
if qre.tsv.qe.enableTableACLDryRun {
qre.tsv.Stats().TableaclPseudoDenied.Add(statsKey, 1)
return nil
}
// Skip ACL check for queries against the dummy dual table
if tableName == "dual" {
return nil
}
if qre.tsv.qe.strictTableACL {
groupStr := ""
if len(callerID.Groups) > 0 {
groupStr = fmt.Sprintf(", in groups [%s],", strings.Join(callerID.Groups, ", "))
}
errStr := fmt.Sprintf("%s command denied to user '%s'%s for table '%s' (ACL check error)", qre.plan.PlanID.String(), callerID.Username, groupStr, tableName)
qre.tsv.Stats().TableaclDenied.Add(statsKey, 1)
qre.tsv.qe.accessCheckerLogger.Infof("%s", errStr)
return vterrors.Errorf(vtrpcpb.Code_PERMISSION_DENIED, "%s", errStr)
}
return nil
}
qre.tsv.Stats().TableaclAllowed.Add(statsKey, 1)
return nil
}
func (qre *QueryExecutor) execDDL(conn *StatefulConnection) (*sqltypes.Result, error) {
// Let's see if this is a normal DDL statement or an Online DDL statement.
// An Online DDL statement is identified by /*vt+ .. */ comment with expected directives, like uuid etc.
if onlineDDL, err := schema.OnlineDDLFromCommentedStatement(qre.plan.FullStmt); err == nil {
// Parsing is successful.
if !onlineDDL.Strategy.IsDirect() {
// This is an online DDL.
return qre.tsv.onlineDDLExecutor.SubmitMigration(qre.ctx, qre.plan.FullStmt)
}
}
isTemporaryTable := false
if ddlStmt, ok := qre.plan.FullStmt.(sqlparser.DDLStatement); ok {
isTemporaryTable = ddlStmt.IsTemporary()
}
if !isTemporaryTable {
// Temporary tables are limited to the session creating them. There is no need to Reload()
// the table because other connections will not be able to see the table anyway.
defer func() {
// Call se.Reload() with includeStats=false as obtaining table
// size stats involves joining `information_schema.tables`,
// which can be very costly on systems with a large number of
// tables.
//
// Instead of synchronously recalculating table size stats
// after every DDL, let them be outdated until the periodic
// schema reload fixes it.
if err := qre.tsv.se.ReloadAtEx(qre.ctx, mysql.Position{}, false); err != nil {
log.Errorf("failed to reload schema %v", err)
}
}()
}
sql := qre.query
// If FullQuery is not nil, then the DDL query was fully parsed
// and we should use the ast to generate the query instead.
if qre.plan.FullQuery != nil {
var err error
sql, _, err = qre.generateFinalSQL(qre.plan.FullQuery, qre.bindVars)
if err != nil {
return nil, err
}
}
result, err := qre.execStatefulConn(conn, sql, true)
if err != nil {
return nil, err
}
// Only perform this operation when the connection has transaction open.
// TODO: This actually does not retain the old transaction. We should see how to provide correct behaviour to client.
if conn.txProps != nil {
err = qre.BeginAgain(qre.ctx, conn)
if err != nil {
return nil, err
}
}
return result, nil
}
func (qre *QueryExecutor) execLoad(conn *StatefulConnection) (*sqltypes.Result, error) {
result, err := qre.execStatefulConn(conn, qre.query, true)
if err != nil {
return nil, err
}
return result, nil
}
// BeginAgain commits the existing transaction and begins a new one
func (*QueryExecutor) BeginAgain(ctx context.Context, dc *StatefulConnection) error {
if dc.IsClosed() || dc.TxProperties().Autocommit {
return nil
}
if _, err := dc.Exec(ctx, "commit", 1, false); err != nil {
return err
}
if _, err := dc.Exec(ctx, "begin", 1, false); err != nil {
return err
}
return nil
}
func (qre *QueryExecutor) execNextval() (*sqltypes.Result, error) {
env := evalengine.EnvWithBindVars(qre.bindVars, collations.Unknown)
result, err := env.Evaluate(qre.plan.NextCount)
if err != nil {
return nil, err
}
tableName := qre.plan.TableName()
v := result.Value()
inc, err := v.ToInt64()
if err != nil || inc < 1 {
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "invalid increment for sequence %s: %s", tableName, v.String())
}
t := qre.plan.Table
t.SequenceInfo.Lock()
defer t.SequenceInfo.Unlock()
if t.SequenceInfo.NextVal == 0 || t.SequenceInfo.NextVal+inc > t.SequenceInfo.LastVal {
_, err := qre.execAsTransaction(func(conn *StatefulConnection) (*sqltypes.Result, error) {
query := fmt.Sprintf("select next_id, cache from %s where id = 0 for update", sqlparser.String(tableName))
qr, err := qre.execStatefulConn(conn, query, false)
if err != nil {
return nil, err
}
if len(qr.Rows) != 1 {
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "unexpected rows from reading sequence %s (possible mis-route): %d", tableName, len(qr.Rows))
}
nextID, err := evalengine.ToInt64(qr.Rows[0][0])
if err != nil {
return nil, vterrors.Wrapf(err, "error loading sequence %s", tableName)
}
// If LastVal does not match next ID, then either:
// VTTablet just started, and we're initializing the cache, or
// Someone reset the id underneath us.
if t.SequenceInfo.LastVal != nextID {
if nextID < t.SequenceInfo.LastVal {
log.Warningf("Sequence next ID value %v is below the currently cached max %v, updating it to max", nextID, t.SequenceInfo.LastVal)
nextID = t.SequenceInfo.LastVal
}
t.SequenceInfo.NextVal = nextID
t.SequenceInfo.LastVal = nextID
}
cache, err := evalengine.ToInt64(qr.Rows[0][1])
if err != nil {
return nil, vterrors.Wrapf(err, "error loading sequence %s", tableName)
}
if cache < 1 {
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "invalid cache value for sequence %s: %d", tableName, cache)
}
newLast := nextID + cache
for newLast < t.SequenceInfo.NextVal+inc {
newLast += cache
}
query = fmt.Sprintf("update %s set next_id = %d where id = 0", sqlparser.String(tableName), newLast)
conn.TxProperties().RecordQuery(query)
_, err = qre.execStatefulConn(conn, query, false)
if err != nil {
return nil, err
}
t.SequenceInfo.LastVal = newLast
return nil, nil
})
if err != nil {
return nil, err
}
}
ret := t.SequenceInfo.NextVal
t.SequenceInfo.NextVal += inc
return &sqltypes.Result{
Fields: sequenceFields,
Rows: [][]sqltypes.Value{{
sqltypes.NewInt64(ret),
}},
}, nil
}
// execSelect sends a query to mysql only if another identical query is not running. Otherwise, it waits and
// reuses the result. If the plan is missing field info, it sends the query to mysql requesting full info.
func (qre *QueryExecutor) execSelect() (*sqltypes.Result, error) {
sql, sqlWithoutComments, err := qre.generateFinalSQL(qre.plan.FullQuery, qre.bindVars)
if err != nil {
return nil, err
}
// Check tablet type.
if qre.shouldConsolidate() {
q, original := qre.tsv.qe.consolidator.Create(sqlWithoutComments)
if original {
defer q.Broadcast()
conn, err := qre.getConn()
if err != nil {
q.Err = err
} else {
defer conn.Recycle()
q.Result, q.Err = qre.execDBConn(conn, sql, true)
}
} else {
qre.logStats.QuerySources |= tabletenv.QuerySourceConsolidator
startTime := time.Now()
q.Wait()
qre.tsv.stats.WaitTimings.Record("Consolidations", startTime)
}
if q.Err != nil {
return nil, q.Err
}
return q.Result.(*sqltypes.Result), nil
}
conn, err := qre.getConn()
if err != nil {
return nil, err
}
defer conn.Recycle()
res, err := qre.execDBConn(conn, sql, true)
if err != nil {
return nil, err
}
return res, nil
}
func (qre *QueryExecutor) execDMLLimit(conn *StatefulConnection) (*sqltypes.Result, error) {
maxrows := qre.tsv.qe.maxResultSize.Get()
qre.bindVars["#maxLimit"] = sqltypes.Int64BindVariable(maxrows + 1)
result, err := qre.txFetch(conn, true)
if err != nil {
return nil, err
}
if err := qre.verifyRowCount(int64(result.RowsAffected), maxrows); err != nil {
defer qre.logStats.AddRewrittenSQL("rollback", time.Now())
_ = qre.tsv.te.txPool.Rollback(qre.ctx, conn)
return nil, err
}
return result, nil
}
func (qre *QueryExecutor) verifyRowCount(count, maxrows int64) error {
if count > maxrows {
callerID := callerid.ImmediateCallerIDFromContext(qre.ctx)
return vterrors.Errorf(vtrpcpb.Code_ABORTED, "caller id: %s: row count exceeded %d", callerID.Username, maxrows)
}
warnThreshold := qre.tsv.qe.warnResultSize.Get()
if warnThreshold > 0 && count > warnThreshold {
callerID := callerid.ImmediateCallerIDFromContext(qre.ctx)
qre.tsv.Stats().Warnings.Add("ResultsExceeded", 1)
log.Warningf("caller id: %s row count %v exceeds warning threshold %v: %q", callerID.Username, count, warnThreshold, queryAsString(qre.plan.FullQuery.Query, qre.bindVars, qre.tsv.Config().SanitizeLogMessages))
}
return nil
}
func (qre *QueryExecutor) execOther() (*sqltypes.Result, error) {
conn, err := qre.getConn()
if err != nil {
return nil, err
}
defer conn.Recycle()
return qre.execDBConn(conn, qre.query, true)
}
func (qre *QueryExecutor) getConn() (*connpool.DBConn, error) {
span, ctx := trace.NewSpan(qre.ctx, "QueryExecutor.getConn")
defer span.Finish()
start := time.Now()
conn, err := qre.tsv.qe.conns.Get(ctx, qre.setting)
switch err {
case nil:
qre.logStats.WaitingForConnection += time.Since(start)
return conn, nil
case connpool.ErrConnPoolClosed:
return nil, err
}
return nil, err
}
func (qre *QueryExecutor) getStreamConn() (*connpool.DBConn, error) {
span, ctx := trace.NewSpan(qre.ctx, "QueryExecutor.getStreamConn")
defer span.Finish()
start := time.Now()
conn, err := qre.tsv.qe.streamConns.Get(ctx, qre.setting)
switch err {
case nil:
qre.logStats.WaitingForConnection += time.Since(start)
return conn, nil
case connpool.ErrConnPoolClosed:
return nil, err
}
return nil, err
}
// txFetch fetches from a TxConnection.
func (qre *QueryExecutor) txFetch(conn *StatefulConnection, record bool) (*sqltypes.Result, error) {
sql, _, err := qre.generateFinalSQL(qre.plan.FullQuery, qre.bindVars)
if err != nil {
return nil, err
}
qr, err := qre.execStatefulConn(conn, sql, true)
if err != nil {
return nil, err
}
// Only record successful queries.
if record {
conn.TxProperties().RecordQuery(sql)
}
return qr, nil
}
func (qre *QueryExecutor) generateFinalSQL(parsedQuery *sqlparser.ParsedQuery, bindVars map[string]*querypb.BindVariable) (string, string, error) {
query, err := parsedQuery.GenerateQuery(bindVars, nil)
if err != nil {
return "", "", vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%s", err)
}
if qre.tsv.config.AnnotateQueries {
username := callerid.GetPrincipal(callerid.EffectiveCallerIDFromContext(qre.ctx))
if username == "" {
username = callerid.GetUsername(callerid.ImmediateCallerIDFromContext(qre.ctx))
}
var buf strings.Builder
tabletTypeStr := qre.tsv.sm.target.TabletType.String()
buf.Grow(8 + len(username) + len(tabletTypeStr))
buf.WriteString("/* ")
buf.WriteString(username)
buf.WriteString("@")
buf.WriteString(tabletTypeStr)
buf.WriteString(" */ ")
buf.WriteString(qre.marginComments.Leading)
qre.marginComments.Leading = buf.String()
}
if qre.marginComments.Leading == "" && qre.marginComments.Trailing == "" {
return query, query, nil
}
var buf strings.Builder
buf.Grow(len(qre.marginComments.Leading) + len(query) + len(qre.marginComments.Trailing))
buf.WriteString(qre.marginComments.Leading)
buf.WriteString(query)
buf.WriteString(qre.marginComments.Trailing)
return buf.String(), query, nil
}
func rewriteOUTParamError(err error) error {
sqlErr, ok := err.(*mysql.SQLError)
if !ok {
return err
}
if sqlErr.Num == mysql.ErSPNotVarArg {
return vterrors.Errorf(vtrpcpb.Code_UNIMPLEMENTED, "OUT and INOUT parameters are not supported")
}
return err
}
func (qre *QueryExecutor) execCallProc() (*sqltypes.Result, error) {
conn, err := qre.getConn()
if err != nil {
return nil, err
}
defer conn.Recycle()
sql, _, err := qre.generateFinalSQL(qre.plan.FullQuery, qre.bindVars)
if err != nil {
return nil, err
}
qr, err := qre.execDBConn(conn, sql, true)
if err != nil {
return nil, rewriteOUTParamError(err)
}
if !qr.IsMoreResultsExists() {
if qr.IsInTransaction() {
conn.Close()
return nil, vterrors.New(vtrpcpb.Code_CANCELED, "Transaction not concluded inside the stored procedure, leaking transaction from stored procedure is not allowed")
}
return qr, nil
}
err = qre.drainResultSetOnConn(conn)
if err != nil {
return nil, err
}
return nil, vterrors.New(vtrpcpb.Code_UNIMPLEMENTED, "Multi-Resultset not supported in stored procedure")
}
func (qre *QueryExecutor) execProc(conn *StatefulConnection) (*sqltypes.Result, error) {
beforeInTx := conn.IsInTransaction()
sql, _, err := qre.generateFinalSQL(qre.plan.FullQuery, qre.bindVars)
if err != nil {
return nil, err
}
qr, err := qre.execStatefulConn(conn, sql, true)
if err != nil {
return nil, rewriteOUTParamError(err)
}
if !qr.IsMoreResultsExists() {
afterInTx := qr.IsInTransaction()
if beforeInTx != afterInTx {
conn.Close()