forked from pingcap/tidb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathddl_test.go
1161 lines (980 loc) · 29.4 KB
/
ddl_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 2015 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 ddltest
import (
goctx "context"
"database/sql"
"database/sql/driver"
"flag"
"fmt"
"math/rand"
"os"
"os/exec"
"reflect"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
_ "github.com/go-sql-driver/mysql"
"github.com/pingcap/errors"
"github.com/pingcap/log"
"github.com/pingcap/tidb/config"
"github.com/pingcap/tidb/domain"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/parser/model"
"github.com/pingcap/tidb/parser/terror"
"github.com/pingcap/tidb/session"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/sessiontxn"
"github.com/pingcap/tidb/store"
tidbdriver "github.com/pingcap/tidb/store/driver"
"github.com/pingcap/tidb/table"
"github.com/pingcap/tidb/table/tables"
"github.com/pingcap/tidb/testkit"
"github.com/pingcap/tidb/types"
"github.com/stretchr/testify/require"
"go.uber.org/zap"
)
var (
etcd = flag.String("etcd", "127.0.0.1:2379", "etcd path")
tidbIP = flag.String("tidb_ip", "127.0.0.1", "tidb-server ip address")
tikvPath = flag.String("tikv_path", "", "tikv path")
lease = flag.Int("lease", 1, "DDL schema lease time, seconds")
serverNum = flag.Int("server_num", 3, "Maximum running tidb server")
startPort = flag.Int("start_port", 5000, "First tidb-server listening port")
statusPort = flag.Int("status_port", 8000, "First tidb-server status port")
logLevel = flag.String("L", "error", "log level")
ddlServerLogLevel = flag.String("ddl_log_level", "fatal", "DDL server log level")
dataNum = flag.Int("n", 100, "minimal test dataset for a table")
enableRestart = flag.Bool("enable_restart", true, "whether random restart servers for tests")
)
type server struct {
*exec.Cmd
logFP *os.File
db *sql.DB
addr string
}
type ddlSuite struct {
store kv.Storage
dom *domain.Domain
s session.Session
ctx sessionctx.Context
m sync.Mutex
procs []*server
wg sync.WaitGroup
quit chan struct{}
retryCount int
}
func createDDLSuite(t *testing.T) (s *ddlSuite) {
var err error
s = new(ddlSuite)
s.quit = make(chan struct{})
s.store, err = store.New(fmt.Sprintf("tikv://%s%s", *etcd, *tikvPath))
require.NoError(t, err)
// Make sure the schema lease of this session is equal to other TiDB servers'.
session.SetSchemaLease(time.Duration(*lease) * time.Second)
s.dom, err = session.BootstrapSession(s.store)
require.NoError(t, err)
s.s, err = session.CreateSession(s.store)
require.NoError(t, err)
s.ctx = s.s.(sessionctx.Context)
goCtx := goctx.Background()
_, err = s.s.Execute(goCtx, "create database if not exists test_ddl")
require.NoError(t, err)
s.Bootstrap(t)
// Stop current DDL worker, so that we can't be the owner now.
err = domain.GetDomain(s.ctx).DDL().Stop()
require.NoError(t, err)
config.GetGlobalConfig().Instance.TiDBEnableDDL.Store(false)
session.ResetStoreForWithTiKVTest(s.store)
s.dom.Close()
require.NoError(t, s.store.Close())
s.store, err = store.New(fmt.Sprintf("tikv://%s%s", *etcd, *tikvPath))
require.NoError(t, err)
s.s, err = session.CreateSession(s.store)
require.NoError(t, err)
s.dom, err = session.BootstrapSession(s.store)
require.NoError(t, err)
s.ctx = s.s.(sessionctx.Context)
_, err = s.s.Execute(goCtx, "use test_ddl")
require.NoError(t, err)
addEnvPath("..")
// Start multi tidb servers
s.procs = make([]*server, *serverNum)
// Set server restart retry count.
s.retryCount = 20
createLogFiles(t, *serverNum)
err = s.startServers()
require.NoError(t, err)
s.wg.Add(1)
go s.restartServerRegularly()
return
}
// restartServerRegularly restarts a tidb server regularly.
func (s *ddlSuite) restartServerRegularly() {
defer s.wg.Done()
var err error
after := *lease * (6 + randomIntn(6))
for {
select {
case <-time.After(time.Duration(after) * time.Second):
if *enableRestart {
err = s.restartServerRand()
if err != nil {
log.Fatal("restartServerRand failed", zap.Error(err))
}
}
case <-s.quit:
return
}
}
}
func (s *ddlSuite) teardown(t *testing.T) {
close(s.quit)
s.wg.Wait()
s.dom.Close()
// TODO: Remove these logs after testing.
quitCh := make(chan struct{})
go func() {
select {
case <-time.After(100 * time.Second):
log.Error("testing timeout", zap.Stack("stack"))
case <-quitCh:
}
}()
err := s.store.Close()
require.NoError(t, err)
close(quitCh)
err = s.stopServers()
require.NoError(t, err)
}
func (s *ddlSuite) startServers() (err error) {
s.m.Lock()
defer s.m.Unlock()
for i := 0; i < len(s.procs); i++ {
if s.procs[i] != nil {
continue
}
// Open log file.
logFP, err := os.OpenFile(fmt.Sprintf("%s%d", logFilePrefix, i), os.O_RDWR, 0766)
if err != nil {
return errors.Trace(err)
}
s.procs[i], err = s.startServer(i, logFP)
if err != nil {
return errors.Trace(err)
}
}
return nil
}
func (s *ddlSuite) killServer(proc *os.Process) error {
// Make sure this tidb is killed, and it makes the next tidb that has the same port as this one start quickly.
err := proc.Kill()
if err != nil {
log.Error("kill server failed", zap.Error(err))
return errors.Trace(err)
}
_, err = proc.Wait()
if err != nil {
log.Error("kill server, wait failed", zap.Error(err))
return errors.Trace(err)
}
time.Sleep(1 * time.Second)
return nil
}
func (s *ddlSuite) stopServers() error {
s.m.Lock()
defer s.m.Unlock()
for i := 0; i < len(s.procs); i++ {
if proc := s.procs[i]; proc != nil {
if proc.db != nil {
if err := proc.db.Close(); err != nil {
return err
}
}
err := s.killServer(proc.Process)
if err != nil {
return errors.Trace(err)
}
s.procs[i] = nil
}
}
return nil
}
var logFilePrefix = "tidb_log_file_"
func createLogFiles(t *testing.T, length int) {
for i := 0; i < length; i++ {
fp, err := os.Create(fmt.Sprintf("%s%d", logFilePrefix, i))
if err != nil {
require.NoError(t, err)
}
require.NoError(t, fp.Close())
}
}
func (s *ddlSuite) startServer(i int, fp *os.File) (*server, error) {
cmd := exec.Command("ddltest_tidb-server",
"--store=tikv",
fmt.Sprintf("-L=%s", *ddlServerLogLevel),
fmt.Sprintf("--path=%s%s", *etcd, *tikvPath),
fmt.Sprintf("-P=%d", *startPort+i),
fmt.Sprintf("--status=%d", *statusPort+i),
fmt.Sprintf("--lease=%d", *lease))
cmd.Stderr = fp
cmd.Stdout = fp
err := cmd.Start()
if err != nil {
return nil, errors.Trace(err)
}
time.Sleep(500 * time.Millisecond)
// Make sure tidb server process is started.
ps := fmt.Sprintf("ps -aux|grep ddltest_tidb|grep %d", *startPort+i)
output, _ := exec.Command("sh", "-c", ps).Output()
if !strings.Contains(string(output), "ddltest_tidb-server") {
time.Sleep(1 * time.Second)
}
// Open database.
var db *sql.DB
addr := fmt.Sprintf("%s:%d", *tidbIP, *startPort+i)
sleepTime := time.Millisecond * 250
startTime := time.Now()
for i := 0; i < s.retryCount; i++ {
db, err = sql.Open("mysql", fmt.Sprintf("root@(%s)/test_ddl", addr))
if err != nil {
log.Warn("open addr failed", zap.String("addr", addr), zap.Int("retry count", i), zap.Error(err))
continue
}
err = db.Ping()
if err == nil {
break
}
log.Warn("ping addr failed", zap.String("addr", addr), zap.Int("retry count", i), zap.Error(err))
err = db.Close()
if err != nil {
log.Warn("close db failed", zap.Int("retry count", i), zap.Error(err))
break
}
time.Sleep(sleepTime)
sleepTime += sleepTime
}
if err != nil {
log.Error("restart server addr failed",
zap.String("addr", addr),
zap.Duration("take time", time.Since(startTime)),
zap.Error(err),
)
return nil, errors.Trace(err)
}
db.SetMaxOpenConns(10)
_, err = db.Exec("use test_ddl")
if err != nil {
return nil, errors.Trace(err)
}
log.Info("start server ok", zap.String("addr", addr), zap.Error(err))
return &server{
Cmd: cmd,
db: db,
addr: addr,
logFP: fp,
}, nil
}
func (s *ddlSuite) restartServerRand() error {
i := rand.Intn(*serverNum)
s.m.Lock()
defer s.m.Unlock()
if s.procs[i] == nil {
return nil
}
server := s.procs[i]
s.procs[i] = nil
log.Warn("begin to restart", zap.String("addr", server.addr))
err := s.killServer(server.Process)
if err != nil {
return errors.Trace(err)
}
s.procs[i], err = s.startServer(i, server.logFP)
return errors.Trace(err)
}
func isRetryError(err error) bool {
if err == nil {
return false
}
if terror.ErrorEqual(err, driver.ErrBadConn) ||
strings.Contains(err.Error(), "connection refused") ||
strings.Contains(err.Error(), "getsockopt: connection reset by peer") ||
strings.Contains(err.Error(), "KV error safe to retry") ||
strings.Contains(err.Error(), "try again later") ||
strings.Contains(err.Error(), "invalid connection") {
return true
}
// TODO: Check the specific columns number.
if strings.Contains(err.Error(), "Column count doesn't match value count at row") {
log.Warn("err", zap.Error(err))
return false
}
log.Error("can not retry", zap.Error(err))
return false
}
func (s *ddlSuite) exec(query string, args ...interface{}) (sql.Result, error) {
for {
server := s.getServer()
r, err := server.db.Exec(query, args...)
if isRetryError(err) {
log.Error("exec in server, retry",
zap.String("query", query),
zap.String("addr", server.addr),
zap.Error(err),
)
continue
}
return r, err
}
}
func (s *ddlSuite) mustExec(query string, args ...interface{}) sql.Result {
r, err := s.exec(query, args...)
if err != nil {
log.Fatal("[mustExec fail]query",
zap.String("query", query),
zap.Any("args", args),
zap.Error(err),
)
}
return r
}
func (s *ddlSuite) execInsert(query string, args ...interface{}) sql.Result {
for {
r, err := s.exec(query, args...)
if err == nil {
return r
}
if *enableRestart {
// If you use enable random restart servers, we should ignore key exists error.
if strings.Contains(err.Error(), "Duplicate entry") &&
strings.Contains(err.Error(), "for key") {
return r
}
}
log.Fatal("[execInsert fail]query",
zap.String("query", query),
zap.Any("args", args),
zap.Error(err),
)
}
}
func (s *ddlSuite) query(query string, args ...interface{}) (*sql.Rows, error) {
for {
server := s.getServer()
r, err := server.db.Query(query, args...)
if isRetryError(err) {
log.Error("query in server, retry",
zap.String("query", query),
zap.String("addr", server.addr),
zap.Error(err),
)
continue
}
return r, err
}
}
func (s *ddlSuite) getServer() *server {
s.m.Lock()
defer s.m.Unlock()
for i := 0; i < 20; i++ {
i := rand.Intn(*serverNum)
if s.procs[i] != nil {
return s.procs[i]
}
}
log.Fatal("try to get server too many times")
return nil
}
// runDDL executes the DDL query, returns a channel so that you can use it to wait DDL finished.
func (s *ddlSuite) runDDL(sql string) chan error {
done := make(chan error, 1)
go func() {
_, err := s.s.Execute(goctx.Background(), sql)
// We must wait 2 * lease time to guarantee all servers update the schema.
if err == nil {
time.Sleep(time.Duration(*lease) * time.Second * 2)
}
done <- err
}()
return done
}
func (s *ddlSuite) getTable(t *testing.T, name string) table.Table {
tbl, err := domain.GetDomain(s.ctx).InfoSchema().TableByName(model.NewCIStr("test_ddl"), model.NewCIStr(name))
require.NoError(t, err)
return tbl
}
func dumpRows(t *testing.T, rows *sql.Rows) [][]interface{} {
cols, err := rows.Columns()
require.NoError(t, err)
var ay [][]interface{}
for rows.Next() {
v := make([]interface{}, len(cols))
for i := range v {
v[i] = new(interface{})
}
err = rows.Scan(v...)
require.NoError(t, err)
for i := range v {
v[i] = *(v[i].(*interface{}))
}
ay = append(ay, v)
}
require.NoError(t, rows.Close())
require.NoErrorf(t, rows.Err(), "%v", ay)
return ay
}
func matchRows(t *testing.T, rows *sql.Rows, expected [][]interface{}) {
ay := dumpRows(t, rows)
require.Equalf(t, len(expected), len(ay), "%v", expected)
for i := range ay {
match(t, ay[i], expected[i]...)
}
}
func match(t *testing.T, row []interface{}, expected ...interface{}) {
require.Equal(t, len(expected), len(row))
for i := range row {
if row[i] == nil {
require.Nil(t, expected[i])
continue
}
got, err := types.ToString(row[i])
require.NoError(t, err)
need, err := types.ToString(expected[i])
require.NoError(t, err)
require.Equal(t, need, got)
}
}
func (s *ddlSuite) Bootstrap(t *testing.T) {
tk := testkit.NewTestKit(t, s.store)
tk.MustExec("use test_ddl")
tk.MustExec("drop table if exists test_index, test_column, test_insert, test_conflict_insert, " +
"test_update, test_conflict_update, test_delete, test_conflict_delete, test_mixed, test_inc")
tk.MustExec("create table test_index (c int, c1 bigint, c2 double, c3 varchar(256), primary key(c))")
tk.MustExec("create table test_column (c1 int, c2 int, primary key(c1))")
tk.MustExec("create table test_insert (c1 int, c2 int, primary key(c1))")
tk.MustExec("create table test_conflict_insert (c1 int, c2 int, primary key(c1))")
tk.MustExec("create table test_update (c1 int, c2 int, primary key(c1))")
tk.MustExec("create table test_conflict_update (c1 int, c2 int, primary key(c1))")
tk.MustExec("create table test_delete (c1 int, c2 int, primary key(c1))")
tk.MustExec("create table test_conflict_delete (c1 int, c2 int, primary key(c1))")
tk.MustExec("create table test_mixed (c1 int, c2 int, primary key(c1))")
tk.MustExec("create table test_inc (c1 int, c2 int, primary key(c1))")
tk.Session().GetSessionVars().EnableClusteredIndex = variable.ClusteredIndexDefModeOn
tk.MustExec("drop table if exists test_insert_common, test_conflict_insert_common, " +
"test_update_common, test_conflict_update_common, test_delete_common, test_conflict_delete_common, " +
"test_mixed_common, test_inc_common")
tk.MustExec("create table test_insert_common (c1 int, c2 int, primary key(c1, c2))")
tk.MustExec("create table test_conflict_insert_common (c1 int, c2 int, primary key(c1, c2))")
tk.MustExec("create table test_update_common (c1 int, c2 int, primary key(c1, c2))")
tk.MustExec("create table test_conflict_update_common (c1 int, c2 int, primary key(c1, c2))")
tk.MustExec("create table test_delete_common (c1 int, c2 int, primary key(c1, c2))")
tk.MustExec("create table test_conflict_delete_common (c1 int, c2 int, primary key(c1, c2))")
tk.MustExec("create table test_mixed_common (c1 int, c2 int, primary key(c1, c2))")
tk.MustExec("create table test_inc_common (c1 int, c2 int, primary key(c1, c2))")
tk.Session().GetSessionVars().EnableClusteredIndex = variable.ClusteredIndexDefModeIntOnly
}
func TestSimple(t *testing.T) {
s := createDDLSuite(t)
defer s.teardown(t)
t.Run("Basic", func(t *testing.T) {
done := s.runDDL("create table if not exists test_simple (c1 int, c2 int, c3 int)")
err := <-done
require.NoError(t, err)
_, err = s.exec("insert into test_simple values (1, 1, 1)")
require.NoError(t, err)
rows, err := s.query("select c1 from test_simple limit 1")
require.NoError(t, err)
matchRows(t, rows, [][]interface{}{{1}})
done = s.runDDL("drop table if exists test_simple")
err = <-done
require.NoError(t, err)
})
t.Run("Mixed", func(t *testing.T) {
tests := []struct {
name string
}{
{"test_mixed"},
{"test_mixed_common"},
}
for _, test := range tests {
tblName := test.name
t.Run(test.name, func(t *testing.T) {
workerNum := 10
rowCount := 10000
batch := rowCount / workerNum
start := time.Now()
var wg sync.WaitGroup
wg.Add(workerNum)
for i := 0; i < workerNum; i++ {
go func(i int) {
defer wg.Done()
for j := 0; j < batch; j++ {
k := batch*i + j
s.execInsert(fmt.Sprintf("insert into %s values (%d, %d)", tblName, k, k))
}
}(i)
}
wg.Wait()
end := time.Now()
fmt.Printf("[TestSimpleMixed][Insert][Time Cost]%v\n", end.Sub(start))
start = time.Now()
rowID := int64(rowCount)
defaultValue := int64(-1)
wg.Add(workerNum)
for i := 0; i < workerNum; i++ {
go func() {
defer wg.Done()
for j := 0; j < batch; j++ {
key := atomic.AddInt64(&rowID, 1)
s.execInsert(fmt.Sprintf("insert into %s values (%d, %d)", tblName, key, key))
key = int64(randomNum(rowCount))
s.mustExec(fmt.Sprintf("update %s set c2 = %d where c1 = %d", tblName, defaultValue, key))
key = int64(randomNum(rowCount))
s.mustExec(fmt.Sprintf("delete from %s where c1 = %d", tblName, key))
}
}()
}
wg.Wait()
end = time.Now()
fmt.Printf("[TestSimpleMixed][Mixed][Time Cost]%v\n", end.Sub(start))
ctx := s.ctx
err := sessiontxn.NewTxn(goctx.Background(), ctx)
require.NoError(t, err)
tbl := s.getTable(t, tblName)
updateCount := int64(0)
insertCount := int64(0)
err = tables.IterRecords(tbl, ctx, tbl.Cols(), func(_ kv.Handle, data []types.Datum, cols []*table.Column) (bool, error) {
if reflect.DeepEqual(data[1].GetValue(), data[0].GetValue()) {
insertCount++
} else if reflect.DeepEqual(data[1].GetValue(), defaultValue) && data[0].GetInt64() < int64(rowCount) {
updateCount++
} else {
log.Fatal("[TestSimpleMixed fail]invalid row", zap.Any("row", data))
}
return true, nil
})
require.NoError(t, err)
deleteCount := atomic.LoadInt64(&rowID) - insertCount - updateCount
require.Greater(t, insertCount, int64(0))
require.Greater(t, updateCount, int64(0))
require.Greater(t, deleteCount, int64(0))
})
}
})
t.Run("Inc", func(t *testing.T) {
tests := []struct {
name string
}{
{"test_inc"},
{"test_inc_common"},
}
for _, test := range tests {
tblName := test.name
t.Run(test.name, func(t *testing.T) {
workerNum := 10
rowCount := 1000
batch := rowCount / workerNum
start := time.Now()
var wg sync.WaitGroup
wg.Add(workerNum)
for i := 0; i < workerNum; i++ {
go func(i int) {
defer wg.Done()
for j := 0; j < batch; j++ {
k := batch*i + j
s.execInsert(fmt.Sprintf("insert into %s values (%d, %d)", tblName, k, k))
}
}(i)
}
wg.Wait()
end := time.Now()
fmt.Printf("[TestSimpleInc][Insert][Time Cost]%v\n", end.Sub(start))
start = time.Now()
wg.Add(workerNum)
for i := 0; i < workerNum; i++ {
go func() {
defer wg.Done()
for j := 0; j < batch; j++ {
s.mustExec(fmt.Sprintf("update %s set c2 = c2 + 1 where c1 = 0", tblName))
}
}()
}
wg.Wait()
end = time.Now()
fmt.Printf("[TestSimpleInc][Update][Time Cost]%v\n", end.Sub(start))
ctx := s.ctx
err := sessiontxn.NewTxn(goctx.Background(), ctx)
require.NoError(t, err)
tbl := s.getTable(t, "test_inc")
err = tables.IterRecords(tbl, ctx, tbl.Cols(), func(_ kv.Handle, data []types.Datum, cols []*table.Column) (bool, error) {
if reflect.DeepEqual(data[0].GetValue(), int64(0)) {
if *enableRestart {
require.GreaterOrEqual(t, data[1].GetValue(), int64(rowCount))
} else {
require.Equal(t, int64(rowCount), data[1].GetValue())
}
} else {
require.Equal(t, data[1].GetValue(), data[0].GetValue())
}
return true, nil
})
require.NoError(t, err)
})
}
})
}
func TestSimpleInsert(t *testing.T) {
s := createDDLSuite(t)
defer s.teardown(t)
t.Run("Basic", func(t *testing.T) {
tests := []struct {
name string
}{
{"test_insert"},
{"test_insert_common"},
}
for _, test := range tests {
tblName := test.name
t.Run(test.name, func(t *testing.T) {
workerNum := 10
rowCount := 10000
batch := rowCount / workerNum
start := time.Now()
var wg sync.WaitGroup
wg.Add(workerNum)
for i := 0; i < workerNum; i++ {
go func(i int) {
defer wg.Done()
for j := 0; j < batch; j++ {
k := batch*i + j
s.execInsert(fmt.Sprintf("insert into %s values (%d, %d)", tblName, k, k))
}
}(i)
}
wg.Wait()
end := time.Now()
fmt.Printf("[TestSimpleInsert][Time Cost]%v\n", end.Sub(start))
ctx := s.ctx
err := sessiontxn.NewTxn(goctx.Background(), ctx)
require.NoError(t, err)
tbl := s.getTable(t, "test_insert")
handles := kv.NewHandleMap()
err = tables.IterRecords(tbl, ctx, tbl.Cols(), func(h kv.Handle, data []types.Datum, cols []*table.Column) (bool, error) {
handles.Set(h, struct{}{})
require.Equal(t, data[1].GetValue(), data[0].GetValue())
return true, nil
})
require.NoError(t, err)
require.Equal(t, rowCount, handles.Len())
})
}
})
t.Run("Conflict", func(t *testing.T) {
tests := []struct {
name string
}{
{"test_conflict_insert"},
{"test_conflict_insert_common"},
}
for _, test := range tests {
tblName := test.name
t.Run(test.name, func(t *testing.T) {
var mu sync.Mutex
keysMap := make(map[int64]int64)
workerNum := 10
rowCount := 10000
batch := rowCount / workerNum
start := time.Now()
var wg sync.WaitGroup
wg.Add(workerNum)
for i := 0; i < workerNum; i++ {
go func() {
defer wg.Done()
for j := 0; j < batch; j++ {
k := randomNum(rowCount)
_, _ = s.exec(fmt.Sprintf("insert into %s values (%d, %d)", tblName, k, k))
mu.Lock()
keysMap[int64(k)] = int64(k)
mu.Unlock()
}
}()
}
wg.Wait()
end := time.Now()
fmt.Printf("[TestSimpleConflictInsert][Time Cost]%v\n", end.Sub(start))
ctx := s.ctx
err := sessiontxn.NewTxn(goctx.Background(), ctx)
require.NoError(t, err)
tbl := s.getTable(t, tblName)
handles := kv.NewHandleMap()
err = tables.IterRecords(tbl, ctx, tbl.Cols(), func(h kv.Handle, data []types.Datum, cols []*table.Column) (bool, error) {
handles.Set(h, struct{}{})
require.Contains(t, keysMap, data[0].GetValue())
require.Equal(t, data[1].GetValue(), data[0].GetValue())
return true, nil
})
require.NoError(t, err)
require.Len(t, keysMap, handles.Len())
})
}
})
}
func TestSimpleUpdate(t *testing.T) {
s := createDDLSuite(t)
defer s.teardown(t)
t.Run("Basic", func(t *testing.T) {
tests := []struct {
name string
}{
{"test_update"},
{"test_update_common"},
}
for _, test := range tests {
tblName := test.name
t.Run(test.name, func(t *testing.T) {
var mu sync.Mutex
keysMap := make(map[int64]int64)
workerNum := 10
rowCount := 10000
batch := rowCount / workerNum
start := time.Now()
var wg sync.WaitGroup
wg.Add(workerNum)
for i := 0; i < workerNum; i++ {
go func(i int) {
defer wg.Done()
for j := 0; j < batch; j++ {
k := batch*i + j
s.execInsert(fmt.Sprintf("insert into %s values (%d, %d)", tblName, k, k))
v := randomNum(rowCount)
s.mustExec(fmt.Sprintf("update %s set c2 = %d where c1 = %d", tblName, v, k))
mu.Lock()
keysMap[int64(k)] = int64(v)
mu.Unlock()
}
}(i)
}
wg.Wait()
end := time.Now()
fmt.Printf("[TestSimpleUpdate][Time Cost]%v\n", end.Sub(start))
ctx := s.ctx
err := sessiontxn.NewTxn(goctx.Background(), ctx)
require.NoError(t, err)
tbl := s.getTable(t, tblName)
handles := kv.NewHandleMap()
err = tables.IterRecords(tbl, ctx, tbl.Cols(), func(h kv.Handle, data []types.Datum, cols []*table.Column) (bool, error) {
handles.Set(h, struct{}{})
key := data[0].GetInt64()
require.Equal(t, keysMap[key], data[1].GetValue())
return true, nil
})
require.NoError(t, err)
require.Equal(t, rowCount, handles.Len())
})
}
})
t.Run("Conflict", func(t *testing.T) {
tests := []struct {
name string
}{
{"test_conflict_update"},
{"test_conflict_update_common"},
}
for _, test := range tests {
tblName := test.name
t.Run(test.name, func(t *testing.T) {
var mu sync.Mutex
keysMap := make(map[int64]int64)
workerNum := 10
rowCount := 10000
batch := rowCount / workerNum
start := time.Now()
var wg sync.WaitGroup
wg.Add(workerNum)
for i := 0; i < workerNum; i++ {
go func(i int) {
defer wg.Done()
for j := 0; j < batch; j++ {
k := batch*i + j
s.execInsert(fmt.Sprintf("insert into %s values (%d, %d)", tblName, k, k))
mu.Lock()
keysMap[int64(k)] = int64(k)
mu.Unlock()
}
}(i)
}
wg.Wait()
end := time.Now()
fmt.Printf("[TestSimpleConflictUpdate][Insert][Time Cost]%v\n", end.Sub(start))
start = time.Now()
defaultValue := int64(-1)
wg.Add(workerNum)
for i := 0; i < workerNum; i++ {
go func() {
defer wg.Done()
for j := 0; j < batch; j++ {
k := randomNum(rowCount)
s.mustExec(fmt.Sprintf("update %s set c2 = %d where c1 = %d", tblName, defaultValue, k))
mu.Lock()
keysMap[int64(k)] = defaultValue
mu.Unlock()
}
}()
}
wg.Wait()
end = time.Now()
fmt.Printf("[TestSimpleConflictUpdate][Update][Time Cost]%v\n", end.Sub(start))
ctx := s.ctx
err := sessiontxn.NewTxn(goctx.Background(), ctx)
require.NoError(t, err)