forked from pingcap/tidb
/
prepare_test.go
2784 lines (2480 loc) · 123 KB
/
prepare_test.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 2018 PingCAP, 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 core_test
import (
"context"
"fmt"
"math"
"math/rand"
"strconv"
"strings"
"testing"
"time"
"github.com/pingcap/tidb/executor"
"github.com/pingcap/tidb/expression"
"github.com/pingcap/tidb/infoschema"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/metrics"
"github.com/pingcap/tidb/parser"
"github.com/pingcap/tidb/parser/auth"
"github.com/pingcap/tidb/parser/terror"
"github.com/pingcap/tidb/planner/core"
"github.com/pingcap/tidb/session"
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/testkit"
"github.com/pingcap/tidb/util/hint"
"github.com/pingcap/tidb/util/kvcache"
"github.com/prometheus/client_golang/prometheus"
dto "github.com/prometheus/client_model/go"
"github.com/stretchr/testify/require"
)
func TestPointGetPreparedPlan4PlanCache(t *testing.T) {
store := testkit.CreateMockStore(t)
tk1 := testkit.NewTestKit(t, store)
tk1.MustExec(`set tidb_enable_prepared_plan_cache=1`)
tk1.MustExec("drop database if exists ps_text")
defer tk1.MustExec("drop database if exists ps_text")
tk1.MustExec("create database ps_text")
tk1.MustExec("use ps_text")
tk1.MustExec(`create table t (a int, b int, c int,
primary key k_a(a),
unique key k_b(b))`)
tk1.MustExec("insert into t values (1, 1, 1)")
tk1.MustExec("insert into t values (2, 2, 2)")
tk1.MustExec("insert into t values (3, 3, 3)")
pspk1Id, _, _, err := tk1.Session().PrepareStmt("select * from t where a = ?")
require.NoError(t, err)
tk1.Session().GetSessionVars().PreparedStmts[pspk1Id].(*core.PlanCacheStmt).PreparedAst.UseCache = false
ctx := context.Background()
// first time plan generated
_, err = tk1.Session().ExecutePreparedStmt(ctx, pspk1Id, expression.Args2Expressions4Test(0))
require.NoError(t, err)
// using the generated plan but with different params
_, err = tk1.Session().ExecutePreparedStmt(ctx, pspk1Id, expression.Args2Expressions4Test(nil))
require.NoError(t, err)
}
func TestPreparePointGetWithDML(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec(`set tidb_enable_prepared_plan_cache=1`)
tk.MustExec(`use test`)
tk.MustExec(`drop table if exists t`)
tk.MustExec(`create table t(a int, unique key(a))`)
tk.MustExec(`insert into t values(1), (2)`)
// txn1 left a cached plan
tk.MustExec(`begin`)
tk.MustExec(`prepare stmt from 'update t set a = ? where a = ?'`)
tk.MustExec(`set @a=1`)
tk.MustExec(`execute stmt using @a, @a`)
tk.MustExec(`commit`)
// txn2 can reuse the cached plan generated by txn1 directly
tk.MustExec(`begin`)
tk.MustExec(`prepare stmt from 'update t set a = ? where a = ?'`)
tk.MustExec(`set @a=2`)
tk.MustExec(`execute stmt using @a, @a`) // can reuse the cached plan directly
tk.MustQuery(`select @@last_plan_from_cache`).Check(testkit.Rows("1"))
tk.MustExec(`rollback`)
}
func TestPrepareIgnoreCloseStmtCmd(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec(`set tidb_enable_prepared_plan_cache=1`)
tk.MustExec(`use test`)
tk.MustExec(`drop table if exists t`)
tk.MustExec(`create table t(a int, unique key(a))`)
// disable the ignore-stmt-cmd
tk.MustExec(`set @@tidb_ignore_prepared_cache_close_stmt=0`)
tk.MustQuery(`select @@tidb_ignore_prepared_cache_close_stmt`).Check(testkit.Rows("0"))
tk.MustExec(`prepare stmt from 'select * from t'`)
tk.MustQuery(`execute stmt`).Check(testkit.Rows())
tk.MustQuery(`execute stmt`).Check(testkit.Rows())
tk.MustQuery(`select @@last_plan_from_cache`).Check(testkit.Rows("1"))
tk.MustExec(`deallocate prepare stmt`) // close/deallocate this stmt
tk.MustExec(`prepare stmt from 'select * from t'`)
tk.MustQuery(`execute stmt`).Check(testkit.Rows())
tk.MustQuery(`select @@last_plan_from_cache`).Check(testkit.Rows("0")) // cannot reuse last plan since it is closed
// enable the ignore-stmt-cmd
tk.MustExec(`set tidb_ignore_prepared_cache_close_stmt=1`)
tk.MustQuery(`select @@tidb_ignore_prepared_cache_close_stmt`).Check(testkit.Rows("1"))
tk.MustExec(`prepare stmt from 'select * from t'`)
tk.MustQuery(`execute stmt`).Check(testkit.Rows())
tk.MustQuery(`execute stmt`).Check(testkit.Rows())
tk.MustQuery(`select @@last_plan_from_cache`).Check(testkit.Rows("1"))
tk.MustExec(`deallocate prepare stmt`) // close/deallocate this stmt
tk.MustExec(`prepare stmt from 'select * from t'`)
tk.MustQuery(`execute stmt`).Check(testkit.Rows())
tk.MustQuery(`select @@last_plan_from_cache`).Check(testkit.Rows("1")) // can reuse last plan since last close-cmd was ignored
}
func TestRandomFlushPlanCache(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec(`set tidb_enable_prepared_plan_cache=1`)
tk2 := testkit.NewTestKit(t, store)
var err error
tk.MustExec("use test")
tk.MustExec("drop table if exists t1")
tk.MustExec("drop table if exists t2")
tk.MustExec("create table t1(id int, a int, b int, key(a))")
tk.MustExec("create table t2(id int, a int, b int, key(a))")
tk.MustExec("prepare stmt1 from 'SELECT * from t1,t2 where t1.id = t2.id';")
tk.MustExec("prepare stmt2 from 'SELECT * from t1';")
tk.MustExec("prepare stmt3 from 'SELECT * from t1 where id = 1';")
tk.MustExec("prepare stmt4 from 'SELECT * from t2';")
tk.MustExec("prepare stmt5 from 'SELECT * from t2 where id = 1';")
tk2.MustExec("use test")
tk2.MustExec("prepare stmt1 from 'SELECT * from t1,t2 where t1.id = t2.id';")
tk2.MustExec("prepare stmt2 from 'SELECT * from t1';")
tk2.MustExec("prepare stmt3 from 'SELECT * from t1 where id = 1';")
tk2.MustExec("prepare stmt4 from 'SELECT * from t2';")
tk2.MustExec("prepare stmt5 from 'SELECT * from t2 where id = 1';")
prepareNum := 5
execStmts := make([]string, 0, prepareNum)
for i := 1; i <= prepareNum; i++ {
execStmt := fmt.Sprintf("execute stmt%d", i)
execStmts = append(execStmts, execStmt)
}
rand.Seed(time.Now().Unix())
for i := 0; i < 10; i++ {
// Warm up to make sure all the plans are in the cache.
for _, execStmt := range execStmts {
tk.MustExec(execStmt)
tk.MustExec(execStmt)
tk.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("1"))
tk2.MustExec(execStmt)
tk2.MustExec(execStmt)
tk2.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("1"))
}
for j := 0; j < 10; j++ {
session1PC, session2PC := "1", "1"
// random to flush the plan cache
randNum := rand.Intn(10)
if randNum == 0 {
session1PC, session2PC = "0", "0"
if j%2 == 0 {
err = tk.ExecToErr("admin flush instance plan_cache;")
} else {
err = tk2.ExecToErr("admin flush instance plan_cache;")
}
require.NoError(t, err)
} else if randNum == 1 {
session1PC = "0"
err = tk.ExecToErr("admin flush session plan_cache;")
require.NoError(t, err)
} else if randNum == 2 {
session2PC = "0"
err = tk2.ExecToErr("admin flush session plan_cache;")
require.NoError(t, err)
}
for _, execStmt := range execStmts {
tk.MustExec(execStmt)
tk.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows(session1PC))
tk2.MustExec(execStmt)
tk2.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows(session2PC))
}
}
err = tk.ExecToErr("admin flush instance plan_cache;")
require.NoError(t, err)
}
err = tk.ExecToErr("admin flush global plan_cache;")
require.EqualError(t, err, "Do not support the 'admin flush global scope.'")
}
func TestFlushPlanCache(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec(`set tidb_enable_prepared_plan_cache=1`)
tk2 := testkit.NewTestKit(t, store)
tk.MustExec("use test")
tk.MustExec("drop table if exists t1")
tk.MustExec("drop table if exists t2")
tk.MustExec("create table t1(id int, a int, b int, key(a))")
tk.MustExec("create table t2(id int, a int, b int, key(a))")
tk.MustExec("prepare stmt1 from 'SELECT * from t1,t2 where t1.id = t2.id';")
tk.MustExec("execute stmt1;")
tk.MustExec("execute stmt1;")
tk.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("1"))
tk.MustExec("prepare stmt2 from 'SELECT * from t1';")
tk.MustExec("execute stmt2;")
tk.MustExec("execute stmt2;")
tk.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("1"))
tk.MustExec("prepare stmt3 from 'SELECT * from t1 where id = 1';")
tk.MustExec("execute stmt3;")
tk.MustExec("execute stmt3;")
tk.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("1"))
tk2.MustExec("use test")
tk2.MustExec("drop table if exists t1")
tk2.MustExec("drop table if exists t2")
tk2.MustExec("create table t1(id int, a int, b int, key(a))")
tk2.MustExec("create table t2(id int, a int, b int, key(a))")
tk2.MustExec("prepare stmt1 from 'SELECT * from t1,t2 where t1.id = t2.id';")
tk2.MustExec("execute stmt1;")
tk2.MustExec("execute stmt1;")
tk2.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("1"))
tk2.MustExec("prepare stmt2 from 'SELECT * from t1';")
tk2.MustExec("execute stmt2;")
tk2.MustExec("execute stmt2;")
tk2.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("1"))
tk2.MustExec("prepare stmt3 from 'SELECT * from t1 where id = 1';")
tk2.MustExec("execute stmt3;")
tk2.MustExec("execute stmt3;")
tk2.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("1"))
tk.MustExec("admin flush session plan_cache;")
tk.MustExec("execute stmt1;")
tk.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
tk.MustExec("execute stmt2;")
tk.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
tk.MustExec("execute stmt3;")
tk.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
tk2.MustExec("execute stmt1;")
tk2.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("1"))
tk2.MustExec("execute stmt2;")
tk2.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("1"))
tk2.MustExec("execute stmt3;")
tk2.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("1"))
tk.MustExec("execute stmt1;")
tk.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("1"))
tk.MustExec("execute stmt2;")
tk.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("1"))
tk.MustExec("execute stmt3;")
tk.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("1"))
tk2.MustExec("admin flush instance plan_cache;")
tk2.MustExec("execute stmt1;")
tk2.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
tk2.MustExec("execute stmt2;")
tk2.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
tk2.MustExec("execute stmt3;")
tk2.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
tk.MustExec("execute stmt1;")
tk.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
tk.MustExec("execute stmt2;")
tk.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
tk.MustExec("execute stmt3;")
tk.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
err := tk.ExecToErr("admin flush global plan_cache;")
require.EqualError(t, err, "Do not support the 'admin flush global scope.'")
}
func TestFlushPlanCacheWithoutPCEnable(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
tk2 := testkit.NewTestKit(t, store)
tk.MustExec(`set tidb_enable_prepared_plan_cache=0`)
tk2.MustExec(`set tidb_enable_prepared_plan_cache=0`)
tk.MustExec("use test")
tk.MustExec("drop table if exists t1")
tk.MustExec("drop table if exists t2")
tk.MustExec("create table t1(id int, a int, b int, key(a))")
tk.MustExec("create table t2(id int, a int, b int, key(a))")
tk.MustExec("prepare stmt1 from 'SELECT * from t1,t2 where t1.id = t2.id';")
tk.MustExec("execute stmt1;")
tk.MustExec("execute stmt1;")
tk.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
tk.MustExec("prepare stmt2 from 'SELECT * from t1';")
tk.MustExec("execute stmt2;")
tk.MustExec("execute stmt2;")
tk.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
tk.MustExec("prepare stmt3 from 'SELECT * from t1 where id = 1';")
tk.MustExec("execute stmt3;")
tk.MustExec("execute stmt3;")
tk.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
tk2.MustExec("use test")
tk2.MustExec("drop table if exists t1")
tk2.MustExec("drop table if exists t2")
tk2.MustExec("create table t1(id int, a int, b int, key(a))")
tk2.MustExec("create table t2(id int, a int, b int, key(a))")
tk2.MustExec("prepare stmt1 from 'SELECT * from t1,t2 where t1.id = t2.id';")
tk2.MustExec("execute stmt1;")
tk2.MustExec("execute stmt1;")
tk2.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
tk2.MustExec("prepare stmt2 from 'SELECT * from t1';")
tk2.MustExec("execute stmt2;")
tk2.MustExec("execute stmt2;")
tk2.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
tk2.MustExec("prepare stmt3 from 'SELECT * from t1 where id = 1';")
tk2.MustExec("execute stmt3;")
tk2.MustExec("execute stmt3;")
tk2.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
tk.MustExec("admin flush session plan_cache;")
tk.MustQuery("show warnings;").Check(testkit.Rows("Warning 1105 The plan cache is disable. So there no need to flush the plan cache"))
tk.MustExec("execute stmt1;")
tk.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
tk.MustExec("execute stmt2;")
tk.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
tk.MustExec("execute stmt3;")
tk.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
tk2.MustExec("execute stmt1;")
tk2.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
tk2.MustExec("execute stmt2;")
tk2.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
tk2.MustExec("execute stmt3;")
tk2.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
tk.MustExec("execute stmt1;")
tk.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
tk.MustExec("execute stmt2;")
tk.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
tk.MustExec("execute stmt3;")
tk.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
tk2.MustExec("admin flush instance plan_cache;")
tk2.MustQuery("show warnings;").Check(testkit.Rows("Warning 1105 The plan cache is disable. So there no need to flush the plan cache"))
tk2.MustExec("execute stmt1;")
tk2.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
tk2.MustExec("execute stmt2;")
tk2.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
tk2.MustExec("execute stmt3;")
tk2.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
tk.MustExec("execute stmt1;")
tk.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
tk.MustExec("execute stmt2;")
tk.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
tk.MustExec("execute stmt3;")
tk.MustQuery("select @@last_plan_from_cache").Check(testkit.Rows("0"))
err := tk.ExecToErr("admin flush global plan_cache;")
require.EqualError(t, err, "Do not support the 'admin flush global scope.'")
}
func TestPrepareCache(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec(`set tidb_enable_prepared_plan_cache=1`)
tk.MustExec("use test")
tk.MustExec("drop table if exists t")
tk.MustExec("create table t(a int primary key, b int, c int, index idx1(b, a), index idx2(b))")
tk.MustExec("insert into t values(1, 1, 1), (2, 2, 2), (3, 3, 3), (4, 4, 4), (5, 5, 5), (6, 1, 2)")
tk.MustExec(`prepare stmt1 from "select * from t use index(idx1) where a = ? and b = ?"`)
tk.MustExec(`prepare stmt2 from "select a, b from t use index(idx2) where b = ?"`)
tk.MustExec(`prepare stmt3 from "select * from t where a = ?"`)
tk.MustExec("set @a=1, @b=1")
// When executing one statement at the first time, we don't use cache, so we need to execute it at least twice to test the cache.
tk.MustQuery("execute stmt1 using @a, @b").Check(testkit.Rows("1 1 1"))
tk.MustQuery("execute stmt1 using @a, @b").Check(testkit.Rows("1 1 1"))
tk.MustQuery("execute stmt2 using @b").Check(testkit.Rows("1 1", "6 1"))
tk.MustQuery("execute stmt2 using @b").Check(testkit.Rows("1 1", "6 1"))
tk.MustQuery("execute stmt3 using @a").Check(testkit.Rows("1 1 1"))
tk.MustQuery("execute stmt3 using @a").Check(testkit.Rows("1 1 1"))
tk.MustExec(`prepare stmt4 from "select * from t where a > ?"`)
tk.MustExec("set @a=3")
tk.MustQuery("execute stmt4 using @a").Check(testkit.Rows("4 4 4", "5 5 5", "6 1 2"))
tk.MustQuery("execute stmt4 using @a").Check(testkit.Rows("4 4 4", "5 5 5", "6 1 2"))
tk.MustExec(`prepare stmt5 from "select c from t order by c"`)
tk.MustQuery("execute stmt5").Check(testkit.Rows("1", "2", "2", "3", "4", "5"))
tk.MustQuery("execute stmt5").Check(testkit.Rows("1", "2", "2", "3", "4", "5"))
tk.MustExec(`prepare stmt6 from "select distinct a from t order by a"`)
tk.MustQuery("execute stmt6").Check(testkit.Rows("1", "2", "3", "4", "5", "6"))
tk.MustQuery("execute stmt6").Check(testkit.Rows("1", "2", "3", "4", "5", "6"))
// test privilege change
rootSe := tk.Session()
tk.MustExec("drop table if exists tp")
tk.MustExec(`create table tp(c1 int, c2 int, primary key (c1))`)
tk.MustExec(`insert into tp values(1, 1), (2, 2), (3, 3)`)
tk.MustExec(`create user 'u_tp'@'localhost'`)
tk.MustExec(`grant select on test.tp to u_tp@'localhost';`)
// user u_tp
userSess := newSession(t, store, "test")
require.True(t, userSess.Auth(&auth.UserIdentity{Username: "u_tp", Hostname: "localhost"}, nil, nil))
mustExec(t, userSess, `prepare ps_stp_r from 'select * from tp where c1 > ?'`)
mustExec(t, userSess, `set @p2 = 2`)
tk.SetSession(userSess)
tk.MustQuery(`execute ps_stp_r using @p2`).Check(testkit.Rows("3 3"))
tk.MustQuery(`execute ps_stp_r using @p2`).Check(testkit.Rows("3 3"))
tk.MustQuery(`execute ps_stp_r using @p2`).Check(testkit.Rows("3 3"))
// root revoke
tk.SetSession(rootSe)
tk.MustExec(`revoke all on test.tp from 'u_tp'@'localhost';`)
// user u_tp
tk.SetSession(userSess)
_, err := tk.Exec(`execute ps_stp_r using @p2`)
require.Error(t, err)
// grant again
tk.SetSession(rootSe)
tk.MustExec(`grant select on test.tp to u_tp@'localhost';`)
// user u_tp
tk.SetSession(userSess)
tk.MustQuery(`execute ps_stp_r using @p2`).Check(testkit.Rows("3 3"))
tk.MustQuery(`execute ps_stp_r using @p2`).Check(testkit.Rows("3 3"))
// restore
tk.SetSession(rootSe)
tk.MustExec("drop table if exists tp")
tk.MustExec(`DROP USER 'u_tp'@'localhost';`)
}
func TestPrepareCacheIndexScan(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec(`set tidb_enable_prepared_plan_cache=1`)
tk.MustExec("use test")
tk.MustExec("drop table if exists t")
tk.MustExec("create table t(a int, b int, c int, primary key (a, b))")
tk.MustExec("insert into t values(1, 1, 2), (1, 2, 3), (1, 3, 3), (2, 1, 2), (2, 2, 3), (2, 3, 3)")
tk.MustExec(`prepare stmt1 from "select a, c from t where a = ? and c = ?"`)
tk.MustExec("set @a=1, @b=3")
// When executing one statement at the first time, we don't use cache, so we need to execute it at least twice to test the cache.
tk.MustQuery("execute stmt1 using @a, @b").Check(testkit.Rows("1 3", "1 3"))
tk.MustQuery("execute stmt1 using @a, @b").Check(testkit.Rows("1 3", "1 3"))
}
// dtype: tinyint, unsigned, float, decimal, year
// rtype: null, valid, out-of-range, invalid, str, exists
func randValue(tk *testkit.TestKit, tbl, col, dtype, rtype string) string {
if rtype == "" {
rtypes := []string{"null", "valid", "out-of-range", "invalid", "str", "exists"}
rtype = rtypes[rand.Intn(len(rtypes))]
}
if rtype == "null" {
return "null"
}
if rtype == "exists" {
res := tk.MustQuery(fmt.Sprintf("select %v from %v limit 1", col, tbl)).Rows()[0][0].(string)
if res == "<nil>" {
res = "null"
}
return res
}
switch dtype {
case "tinyint":
switch rtype {
case "valid":
return fmt.Sprintf("%v", -128+rand.Intn(256))
case "out-of-range":
return fmt.Sprintf("%v", 128+rand.Intn(1024))
case "invalid":
return "'invalid-tinyint'"
case "str":
return fmt.Sprintf("'%v'", -128+rand.Intn(256))
}
case "unsigned":
switch rtype {
case "valid":
return fmt.Sprintf("%v", rand.Intn(4294967295))
case "out-of-range":
return fmt.Sprintf("-%v", rand.Intn(4294967295))
case "invalid":
return "'invalid-unsigned-int'"
case "str":
return fmt.Sprintf("'%v'", rand.Intn(4294967295))
}
case "float":
switch rtype {
case "valid":
return fmt.Sprintf("%v%.4fE%v", []string{"+", "-"}[rand.Intn(2)], rand.Float32(), rand.Intn(38))
case "out-of-range":
return fmt.Sprintf("%v%.4fE%v", []string{"+", "-"}[rand.Intn(2)], rand.Float32(), rand.Intn(100)+38)
case "invalid":
return "'invalid-float'"
case "str":
return fmt.Sprintf("'%v%.4fE%v'", []string{"+", "-"}[rand.Intn(2)], rand.Float32(), rand.Intn(38))
}
case "decimal": // (10,2)
switch rtype {
case "valid":
return fmt.Sprintf("%v%v.%v", []string{"+", "-"}[rand.Intn(2)], rand.Intn(99999999), rand.Intn(100))
case "out-of-range":
switch rand.Intn(2) {
case 0:
return fmt.Sprintf("%v%v.%v", []string{"+", "-"}[rand.Intn(2)], rand.Intn(99999999), rand.Intn(100000)+100000)
case 1:
return fmt.Sprintf("%v%v.%v", []string{"+", "-"}[rand.Intn(2)], rand.Intn(99999999)+99999999+1, rand.Intn(100))
}
case "invalid":
return "'invalid-decimal'"
case "str":
return fmt.Sprintf("'%v%v.%v'", []string{"+", "-"}[rand.Intn(2)], rand.Intn(99999999), rand.Intn(100))
}
case "year":
switch rtype {
case "valid":
return fmt.Sprintf("%v", 1901+rand.Intn(2155-1901))
case "out-of-range":
return fmt.Sprintf("%v", 2156+rand.Intn(2155-1901))
case "invalid":
return "'invalid-year'"
case "str":
return fmt.Sprintf("'%v'", 1901+rand.Intn(2155-1901))
}
}
return "'invalid-type-" + dtype + "'"
}
func TestPrepareCacheChangingParamType(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec(`set tidb_enable_prepared_plan_cache=1`)
tk.MustExec(`use test`)
tk.MustExec(`drop table if exists t_tinyint, t_unsigned, t_float, t_decimal, t_year`)
tk.MustExec(`create table t_tinyint (a tinyint, b tinyint, key(a))`)
tk.MustExec(`create table t_unsigned (a int unsigned, b int unsigned, key(a))`)
tk.MustExec(`create table t_float(a float, b float, key(a))`)
tk.MustExec(`create table t_decimal(a decimal(10,2), b decimal(10,2), key(a))`)
tk.MustExec(`create table t_year(a year, b year, key(a))`)
for _, dtype := range []string{"tinyint", "unsigned", "float", "decimal", "year"} {
tbl := "t_" + dtype
for i := 0; i < 10; i++ {
tk.MustExec(fmt.Sprintf("insert into %v values (%v, %v)", tbl, randValue(nil, "", "", dtype, "valid"), randValue(nil, "", "", dtype, "valid")))
}
tk.MustExec(fmt.Sprintf("insert into %v values (null, null)", tbl))
tk.MustExec(fmt.Sprintf("insert into %v values (%v, null)", tbl, randValue(nil, "", "", dtype, "valid")))
tk.MustExec(fmt.Sprintf("insert into %v values (null, %v)", tbl, randValue(nil, "", "", dtype, "valid")))
for round := 0; round < 10; round++ {
tk.MustExec(fmt.Sprintf(`prepare s1 from 'select * from %v where a=?'`, tbl))
tk.MustExec(fmt.Sprintf(`prepare s2 from 'select * from %v where b=?'`, tbl))
tk.MustExec(fmt.Sprintf(`prepare s3 from 'select * from %v where a in (?, ?, ?)'`, tbl))
tk.MustExec(fmt.Sprintf(`prepare s4 from 'select * from %v where b in (?, ?, ?)'`, tbl))
tk.MustExec(fmt.Sprintf(`prepare s5 from 'select * from %v where a>?'`, tbl))
tk.MustExec(fmt.Sprintf(`prepare s6 from 'select * from %v where b>?'`, tbl))
tk.MustExec(fmt.Sprintf(`prepare s7 from 'select * from %v where a>? and b>?'`, tbl))
for query := 0; query < 10; query++ {
a1, a2, a3 := randValue(tk, tbl, "a", dtype, ""), randValue(tk, tbl, "a", dtype, ""), randValue(tk, tbl, "a", dtype, "")
b1, b2, b3 := randValue(tk, tbl, "b", dtype, ""), randValue(tk, tbl, "b", dtype, ""), randValue(tk, tbl, "b", dtype, "")
tk.MustExec(fmt.Sprintf(`set @a1=%v,@a2=%v,@a3=%v`, a1, a2, a3))
tk.MustExec(fmt.Sprintf(`set @b1=%v,@b2=%v,@b3=%v`, b1, b2, b3))
compareResult := func(sql1, sql2 string) {
raw, err := tk.Exec(sql1)
if err != nil {
require.Error(t, tk.ExecToErr(sql2))
return
}
rs := tk.ResultSetToResult(raw, fmt.Sprintf("sql1:%s, sql2:%v", sql1, sql2))
rs.Sort().Check(tk.MustQuery(sql2).Sort().Rows())
}
compareResult(`execute s1 using @a1`, fmt.Sprintf(`select * from %v where a=%v`, tbl, a1))
compareResult(`execute s2 using @b1`, fmt.Sprintf(`select * from %v where b=%v`, tbl, b1))
compareResult(`execute s3 using @a1,@a2,@a3`, fmt.Sprintf(`select * from %v where a in (%v,%v,%v)`, tbl, a1, a2, a3))
compareResult(`execute s4 using @b1,@b2,@b3`, fmt.Sprintf(`select * from %v where b in (%v,%v,%v)`, tbl, b1, b2, b3))
compareResult(`execute s5 using @a1`, fmt.Sprintf(`select * from %v where a>%v`, tbl, a1))
compareResult(`execute s6 using @b1`, fmt.Sprintf(`select * from %v where b>%v`, tbl, b1))
compareResult(`execute s7 using @a1,@b1`, fmt.Sprintf(`select * from %v where a>%v and b>%v`, tbl, a1, b1))
}
}
}
}
func TestPrepareCacheChangeCharsetCollation(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec(`set tidb_enable_prepared_plan_cache=1`)
tk.MustExec(`use test`)
tk.MustExec(`drop table if exists t`)
tk.MustExec(`create table t (a varchar(64))`)
tk.MustExec(`set character_set_connection=utf8`)
tk.MustExec(`prepare s from 'select * from t where a=?'`)
tk.MustExec(`set @x='a'`)
tk.MustExec(`execute s using @x`)
tk.MustExec(`set @x='b'`)
tk.MustExec(`execute s using @x`)
tk.MustQuery(`select @@last_plan_from_cache`).Check(testkit.Rows("1"))
tk.MustExec(`set character_set_connection=latin1`)
tk.MustExec(`set @x='c'`)
tk.MustExec(`execute s using @x`)
tk.MustQuery(`select @@last_plan_from_cache`).Check(testkit.Rows("0")) // cannot reuse the previous plan since the charset is changed
tk.MustExec(`set @x='d'`)
tk.MustExec(`execute s using @x`)
tk.MustQuery(`select @@last_plan_from_cache`).Check(testkit.Rows("1"))
tk.MustExec(`set collation_connection=binary`)
tk.MustExec(`set @x='e'`)
tk.MustExec(`execute s using @x`)
tk.MustQuery(`select @@last_plan_from_cache`).Check(testkit.Rows("0")) // cannot reuse the previous plan since the collation is changed
tk.MustExec(`set @x='f'`)
tk.MustExec(`execute s using @x`)
tk.MustQuery(`select @@last_plan_from_cache`).Check(testkit.Rows("1"))
}
func TestPrepareCacheDeferredFunction(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec(`set tidb_enable_prepared_plan_cache=1`)
tk.MustExec("use test")
tk.MustExec("drop table if exists t1")
tk.MustExec("create table t1 (id int PRIMARY KEY, c1 TIMESTAMP(3) NOT NULL DEFAULT '2019-01-14 10:43:20', KEY idx1 (c1))")
tk.MustExec("prepare sel1 from 'select id, c1 from t1 where c1 < now(3)'")
sql1 := "execute sel1"
expectedPattern := `IndexReader\(Index\(t1.idx1\)\[\[-inf,[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1]) (2[0-3]|[01][0-9]):[0-5][0-9]:[0-5][0-9].[0-9][0-9][0-9]\)\]\)->Sel\(\[lt\(test.t1.c1, now\(3\)\)\]\)`
var cnt [2]float64
var planStr [2]string
metrics.ResettablePlanCacheCounterFortTest = true
metrics.PlanCacheCounter.Reset()
counter := metrics.PlanCacheCounter.WithLabelValues("prepare")
ctx := context.TODO()
p := parser.New()
p.SetParserConfig(parser.ParserConfig{EnableWindowFunction: true, EnableStrictDoubleTypeCheck: true})
for i := 0; i < 2; i++ {
stmt, err := p.ParseOneStmt(sql1, "", "")
require.NoError(t, err)
is := tk.Session().GetInfoSchema().(infoschema.InfoSchema)
builder, _ := core.NewPlanBuilder().Init(tk.Session(), is, &hint.BlockHintProcessor{})
p, err := builder.Build(ctx, stmt)
require.NoError(t, err)
execPlan, ok := p.(*core.Execute)
require.True(t, ok)
err = executor.ResetContextOfStmt(tk.Session(), stmt)
require.NoError(t, err)
plan, _, err := core.GetPlanFromSessionPlanCache(ctx, tk.Session(), false, is, execPlan.PrepStmt, execPlan.Params)
require.NoError(t, err)
planStr[i] = core.ToString(plan)
require.Regexpf(t, expectedPattern, planStr[i], "for %dth %s", i, sql1)
pb := &dto.Metric{}
err = counter.Write(pb)
require.NoError(t, err)
cnt[i] = pb.GetCounter().GetValue()
require.Equal(t, float64(i), cnt[i])
time.Sleep(time.Millisecond * 10)
}
require.Lessf(t, planStr[0], planStr[1], "plan 1: %v, plan 2: %v", planStr[0], planStr[1])
}
func TestPrepareCacheNow(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec(`set tidb_enable_prepared_plan_cache=1`)
tk.MustExec("use test")
tk.MustExec(`prepare stmt1 from "select now(), current_timestamp(), utc_timestamp(), unix_timestamp(), sleep(0.1), now(), current_timestamp(), utc_timestamp(), unix_timestamp()"`)
// When executing one statement at the first time, we don't usTestPrepareCacheDeferredFunctione cache, so we need to execute it at least twice to test the cache.
_ = tk.MustQuery("execute stmt1").Rows()
rs := tk.MustQuery("execute stmt1").Rows()
require.Equal(t, rs[0][5].(string), rs[0][0].(string))
require.Equal(t, rs[0][6].(string), rs[0][1].(string))
require.Equal(t, rs[0][7].(string), rs[0][2].(string))
require.Equal(t, rs[0][8].(string), rs[0][3].(string))
}
func TestPrepareOverMaxPreparedStmtCount(t *testing.T) {
t.Skip("unstable, skip it and fix it before 20210705")
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec("use test")
// test prepare and deallocate.
prePrepared := readGaugeInt(metrics.PreparedStmtGauge)
tk.MustExec(`prepare stmt1 from "select 1"`)
onePrepared := readGaugeInt(metrics.PreparedStmtGauge)
require.Equal(t, onePrepared, prePrepared+1)
tk.MustExec(`deallocate prepare stmt1`)
deallocPrepared := readGaugeInt(metrics.PreparedStmtGauge)
require.Equal(t, deallocPrepared, prePrepared)
// test change global limit and make it affected in test session.
tk.MustQuery("select @@max_prepared_stmt_count").Check(testkit.Rows("-1"))
tk.MustExec("set @@global.max_prepared_stmt_count = 2")
tk.MustQuery("select @@global.max_prepared_stmt_count").Check(testkit.Rows("2"))
// test close session to give up all prepared stmt
tk.MustExec(`prepare stmt2 from "select 1"`)
prePrepared = readGaugeInt(metrics.PreparedStmtGauge)
tk.Session().Close()
drawPrepared := readGaugeInt(metrics.PreparedStmtGauge)
require.Equal(t, drawPrepared, prePrepared-1)
// test meet max limit.
tk.RefreshSession()
tk.MustQuery("select @@max_prepared_stmt_count").Check(testkit.Rows("2"))
for i := 1; ; i++ {
prePrepared = readGaugeInt(metrics.PreparedStmtGauge)
if prePrepared >= 2 {
_, err := tk.Exec(`prepare stmt` + strconv.Itoa(i) + ` from "select 1"`)
require.True(t, terror.ErrorEqual(err, variable.ErrMaxPreparedStmtCountReached))
break
}
_, err := tk.Exec(`prepare stmt` + strconv.Itoa(i) + ` from "select 1"`)
require.NoError(t, err)
}
}
// unit test for issue https://github.com/pingcap/tidb/issues/8518
func TestPrepareTableAsNameOnGroupByWithCache(t *testing.T) {
t.Skip("unstable, skip it and fix it before 20210702")
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec(`set tidb_enable_prepared_plan_cache=1`)
tk.MustExec("use test")
tk.MustExec("drop table if exists t1")
tk.MustExec(`create table t1 (
id int(11) unsigned not null primary key auto_increment,
partner_id varchar(35) not null,
t1_status_id int(10) unsigned
);`)
tk.MustExec(`insert into t1 values ("1", "partner1", "10"), ("2", "partner2", "10"), ("3", "partner3", "10"), ("4", "partner4", "10");`)
tk.MustExec("drop table if exists t3")
tk.MustExec(`create table t3 (
id int(11) not null default '0',
preceding_id int(11) not null default '0',
primary key (id,preceding_id)
);`)
tk.MustExec(`prepare stmt from 'SELECT DISTINCT t1.partner_id
FROM t1
LEFT JOIN t3 ON t1.id = t3.id
LEFT JOIN t1 pp ON pp.id = t3.preceding_id
GROUP BY t1.id ;'`)
tk.MustQuery("execute stmt").Sort().Check(testkit.Rows("partner1", "partner2", "partner3", "partner4"))
}
func TestPrepareCachePointGetInsert(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec(`set tidb_enable_prepared_plan_cache=1`)
tk.MustExec("use test")
tk.MustExec("drop table if exists t")
tk.MustExec("create table t1 (a int, b int, primary key(a))")
tk.MustExec("insert into t1 values (1, 1), (2, 2), (3, 3)")
tk.MustExec("create table t2 (a int, b int, primary key(a))")
tk.MustExec(`prepare stmt1 from "insert into t2 select * from t1 where a=?"`)
tk.MustExec("set @a=1")
tk.MustExec("execute stmt1 using @a")
tk.MustQuery(`select @@last_plan_from_cache`).Check(testkit.Rows("0"))
tk.MustQuery("select * from t2 order by a").Check(testkit.Rows("1 1"))
tk.MustExec("set @a=2")
tk.MustExec("execute stmt1 using @a")
tk.MustQuery(`select @@last_plan_from_cache`).Check(testkit.Rows("1"))
tk.MustQuery("select * from t2 order by a").Check(testkit.Rows("1 1", "2 2"))
tk.MustExec("set @a=3")
tk.MustExec("execute stmt1 using @a")
tk.MustQuery(`select @@last_plan_from_cache`).Check(testkit.Rows("1"))
tk.MustQuery("select * from t2 order by a").Check(testkit.Rows("1 1", "2 2", "3 3"))
}
func TestIssue31280(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec(`set tidb_enable_prepared_plan_cache=1`)
tk.MustExec("use test")
tk.MustExec("drop table if exists UK_MU15569;")
tk.MustExec("CREATE TABLE `UK_MU15569` (" +
"`COL1` varbinary(20) DEFAULT NULL," +
"`COL2` bit(16) DEFAULT NULL," +
"`COL3` time DEFAULT NULL," +
"`COL4` int(11) DEFAULT NULL," +
"UNIQUE KEY `U_M_COL4` (`COL1`(10),`COL2`)," +
"UNIQUE KEY `U_M_COL5` (`COL3`,`COL2`)" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;")
tk.MustExec("insert into UK_MU15569 values(0x1C4FDBA09B42D999AC3019B6A9C0C787FBA08446, 0xCA74, '-836:46:08', 735655453);")
tk.MustExec(`prepare stmt from 'select * from UK_MU15569 where col2 >= ? and col1 is not null and col3 = ?;';`)
tk.MustExec("set @a=-32373, @b='545:50:46.85487';")
// The tableDual plan can not be cached.
res := tk.MustQuery("execute stmt using @a,@b;")
require.Len(t, res.Rows(), 0)
tk.MustExec("set @a=-27225, @b='-836:46:08';")
res = tk.MustQuery("execute stmt using @a,@b;")
require.Len(t, res.Rows(), 1)
tk.MustQuery(`select @@last_plan_from_cache`).Check(testkit.Rows("0"))
tk.MustQuery("execute stmt using @a,@b;")
tk.MustQuery(`select @@last_plan_from_cache`).Check(testkit.Rows("1"))
res1 := tk.MustQuery("select * from UK_MU15569 where col2 >= -27225 and col1 is not null and col3 = '-836:46:08';")
require.Equal(t, res1.Rows(), res.Rows())
}
func TestIssue31375(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec(`set tidb_enable_prepared_plan_cache=1`)
tk.MustExec("use test")
tk.MustExec("drop table if exists IDT_MULTI15844STROBJSTROBJ;")
tk.MustExec("CREATE TABLE `IDT_MULTI15844STROBJSTROBJ` (" +
"`COL1` enum('bb','aa') DEFAULT NULL," +
"`COL2` smallint(41) DEFAULT NULL," +
"`COL3` year(4) DEFAULT NULL," +
"KEY `U_M_COL4` (`COL1`,`COL2`)," +
"KEY `U_M_COL5` (`COL3`,`COL2`)" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;")
tk.MustExec("insert into IDT_MULTI15844STROBJSTROBJ values('bb', -16994, 1987);")
tk.MustExec(`prepare stmt from 'SELECT/*+ HASH_JOIN(t1, t2) */ t2.* FROM IDT_MULTI15844STROBJSTROBJ t1 LEFT JOIN IDT_MULTI15844STROBJSTROBJ t2 ON t1.col1 = t2.col1 WHERE t1.col2 BETWEEN ? AND ? AND t1.col1 >= ?;';`)
tk.MustExec("set @a=752400293960, @b=258241896853, @c='none';")
// The tableDual plan can not be cached.
tk.MustQuery("execute stmt using @a,@b,@c;").Check(testkit.Rows())
tk.MustExec("set @a=-170756280585, @b=3756, @c='aa';")
tk.MustQuery("execute stmt using @a,@b,@c;").Check(testkit.Rows("bb -16994 1987"))
tk.MustQuery(`select @@last_plan_from_cache`).Check(testkit.Rows("0"))
tk.MustQuery("execute stmt using @a,@b,@c;")
tk.MustQuery(`select @@last_plan_from_cache`).Check(testkit.Rows("1"))
}
// nolint:unused
func readGaugeInt(g prometheus.Gauge) int {
ch := make(chan prometheus.Metric, 1)
g.Collect(ch)
m := <-ch
mm := &dto.Metric{}
err := m.Write(mm)
if err != nil {
panic(err)
}
return int(mm.GetGauge().GetValue())
}
// unit test for issue https://github.com/pingcap/tidb/issues/9478
func TestPrepareWithWindowFunction(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec("set @@tidb_enable_window_function = 1")
defer tk.MustExec("set @@tidb_enable_window_function = 0")
tk.MustExec("use test")
tk.MustExec("create table window_prepare(a int, b double)")
tk.MustExec("insert into window_prepare values(1, 1.1), (2, 1.9)")
tk.MustExec("prepare stmt1 from 'select row_number() over() from window_prepare';")
// Test the unnamed window can be executed successfully.
tk.MustQuery("execute stmt1").Check(testkit.Rows("1", "2"))
// Test the stmt can be prepared successfully.
tk.MustExec("prepare stmt2 from 'select count(a) over (order by a rows between ? preceding and ? preceding) from window_prepare'")
tk.MustExec("set @a=0, @b=1;")
tk.MustQuery("execute stmt2 using @a, @b").Check(testkit.Rows("0", "0"))
}
func TestPrepareWindowFunctionWithoutParamsCheck(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec(`set tidb_enable_prepared_plan_cache=0`)
tk.MustExec("set @@tidb_enable_window_function = 1")
defer tk.MustExec("set @@tidb_enable_window_function = 0")
tk.MustExec("use test")
tk.MustExec("CREATE TABLE t1 (d DOUBLE, id INT, sex CHAR(1), n INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(n));")
tk.MustExec("insert into t1(d, id, sex) values (1.0, 1, 'M'),(2.0, 2, 'F'),(3.0, 3, 'F'),(4.0, 4, 'F'),(5.0, 5, 'M')")
// prepare phase, we don't check the window function args.
tk.MustExec("prepare p from \"select id, sex, lead(id, ?) over () from t1\"")
// execute phase, we do check the window function args (param is initialized).
err := tk.ExecToErr("execute p using @p1")
require.NotNil(t, err)
require.EqualError(t, err, "[planner:1210]Incorrect arguments to lead")
tk.MustExec("set @p1 = 3")
// execute phase, we do check the window function args (param is valid).
tk.MustQuery("execute p using @p1").Check(testkit.Rows("1 M 4", "2 F 5", "3 F <nil>", "4 F <nil>", "5 M <nil>"))
// execute phase, we do check the window function args (param is invalid).
tk.MustExec("PREPARE p FROM \"SELECT id, sex, LEAD(id, ?) OVER (), ntile(?) over() FROM t1\"")
tk.MustExec("set @p2 = 3")
tk.MustQuery("execute p using @p1, @p2").Check(testkit.Rows("1 M 4 1", "2 F 5 1", "3 F <nil> 2", "4 F <nil> 2", "5 M <nil> 3"))
tk.MustExec("set @p2 = 0") // ntile doesn't allow param to be 0
err = tk.ExecToErr("execute p using @p1, @p2")
require.NotNil(t, err)
require.EqualError(t, err, "[planner:1210]Incorrect arguments to ntile")
}
func TestPrepareWithSnapshot(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
safePointName := "tikv_gc_safe_point"
safePointValue := "20060102-15:04:05 -0700"
safePointComment := "All versions after safe point can be accessed. (DO NOT EDIT)"
updateSafePoint := fmt.Sprintf(`INSERT INTO mysql.tidb VALUES ('%[1]s', '%[2]s', '%[3]s')
ON DUPLICATE KEY
UPDATE variable_value = '%[2]s', comment = '%[3]s'`, safePointName, safePointValue, safePointComment)
tk.MustExec(updateSafePoint)
tk.MustExec("use test")
tk.MustExec("drop table if exists t")
tk.MustExec("create table t(id int primary key, v int)")
tk.MustExec("insert into t select 1, 2")
tk.MustExec("begin")
ts := tk.MustQuery("select @@tidb_current_ts").Rows()[0][0].(string)
tk.MustExec("commit")
tk.MustExec("update t set v = 3 where id = 1")
tk.MustExec("prepare s1 from 'select * from t where id = 1';")
tk.MustExec("prepare s2 from 'select * from t';")
tk.MustExec("set @@tidb_snapshot = " + ts)
tk.MustQuery("execute s1").Check(testkit.Rows("1 2"))
tk.MustQuery("execute s2").Check(testkit.Rows("1 2"))
}
func TestPrepareForGroupByItems(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec("use test")
tk.MustExec("drop table if exists t")
tk.MustExec("create table t(id int, v int)")
tk.MustExec("insert into t(id, v) values(1, 2),(1, 2),(2, 3);")
tk.MustExec("prepare s1 from 'select max(v) from t group by floor(id/?)';")
tk.MustExec("set @a=2;")
tk.MustQuery("execute s1 using @a;").Sort().Check(testkit.Rows("2", "3"))
tk.MustExec("prepare s1 from 'select max(v) from t group by ?';")
tk.MustExec("set @a=2;")
err := tk.ExecToErr("execute s1 using @a;")
require.EqualError(t, err, "Unknown column '2' in 'group statement'")
tk.MustExec("set @a=2.0;")
tk.MustQuery("execute s1 using @a;").Check(testkit.Rows("3"))
}
func TestPrepareCacheForClusteredIndex(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec("use test")
tk.MustExec("create table t1(k varchar(100) primary key clustered, v1 int, v2 int)")
tk.MustExec("insert into t1 (k, v1, v2) values('a', 1, 2), ('b', 1, 1)")
tk.MustExec("create table t2(k varchar(100) primary key clustered, v int)")
tk.MustExec("insert into t2 (k, v) values('c', 100)")