forked from pingcap/tidb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver_test.go
1379 lines (1238 loc) · 44.5 KB
/
server_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,
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"database/sql"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"strconv"
"testing"
"time"
"github.com/go-sql-driver/mysql"
. "github.com/pingcap/check"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
"github.com/pingcap/log"
tmysql "github.com/pingcap/parser/mysql"
"github.com/pingcap/tidb/errno"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/util/logutil"
"github.com/pingcap/tidb/util/versioninfo"
"go.uber.org/zap"
)
var (
regression = true
)
func TestT(t *testing.T) {
CustomVerboseFlag = true
logLevel := os.Getenv("log_level")
logutil.InitZapLogger(logutil.NewLogConfig(logLevel, logutil.DefaultLogFormat, "", logutil.EmptyFileLogConfig, false))
TestingT(t)
}
type configOverrider func(*mysql.Config)
// testServerClient config server connect parameters and provider several
// method to communicate with server and run tests
type testServerClient struct {
port uint
statusPort uint
statusScheme string
}
// newTestServerClient return a testServerClient with unique address
func newTestServerClient() *testServerClient {
return &testServerClient{
port: 0,
statusPort: 0,
statusScheme: "http",
}
}
// statusURL return the full URL of a status path
func (cli *testServerClient) statusURL(path string) string {
return fmt.Sprintf("%s://localhost:%d%s", cli.statusScheme, cli.statusPort, path)
}
// fetchStatus exec http.Get to server status port
func (cli *testServerClient) fetchStatus(path string) (*http.Response, error) {
return http.Get(cli.statusURL(path))
}
// postStatus exec http.Port to server status port
func (cli *testServerClient) postStatus(path, contentType string, body io.Reader) (*http.Response, error) {
return http.Post(cli.statusURL(path), contentType, body)
}
// formStatus post a form request to server status address
func (cli *testServerClient) formStatus(path string, data url.Values) (*http.Response, error) {
return http.PostForm(cli.statusURL(path), data)
}
// getDSN generates a DSN string for MySQL connection.
func (cli *testServerClient) getDSN(overriders ...configOverrider) string {
config := mysql.NewConfig()
config.User = "root"
config.Net = "tcp"
config.Addr = fmt.Sprintf("127.0.0.1:%d", cli.port)
config.DBName = "test"
for _, overrider := range overriders {
if overrider != nil {
overrider(config)
}
}
return config.FormatDSN()
}
// runTests runs tests using the default database `test`.
func (cli *testServerClient) runTests(c *C, overrider configOverrider, tests ...func(dbt *DBTest)) {
db, err := sql.Open("mysql", cli.getDSN(overrider))
c.Assert(err, IsNil, Commentf("Error connecting"))
defer db.Close()
db.Exec("DROP TABLE IF EXISTS test")
dbt := &DBTest{c, db}
for _, test := range tests {
test(dbt)
dbt.db.Exec("DROP TABLE IF EXISTS test")
}
}
// runTestsOnNewDB runs tests using a specified database which will be created before the test and destroyed after the test.
func (cli *testServerClient) runTestsOnNewDB(c *C, overrider configOverrider, dbName string, tests ...func(dbt *DBTest)) {
dsn := cli.getDSN(overrider, func(config *mysql.Config) {
config.DBName = ""
})
db, err := sql.Open("mysql", dsn)
c.Assert(err, IsNil, Commentf("Error connecting"))
defer db.Close()
_, err = db.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS `%s`;", dbName))
if err != nil {
fmt.Println(err)
}
c.Assert(err, IsNil, Commentf("Error drop database %s: %s", dbName, err))
_, err = db.Exec(fmt.Sprintf("CREATE DATABASE `%s`;", dbName))
c.Assert(err, IsNil, Commentf("Error create database %s: %s", dbName, err))
defer func() {
_, err = db.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS `%s`;", dbName))
c.Assert(err, IsNil, Commentf("Error drop database %s: %s", dbName, err))
}()
_, err = db.Exec(fmt.Sprintf("USE `%s`;", dbName))
c.Assert(err, IsNil, Commentf("Error use database %s: %s", dbName, err))
dbt := &DBTest{c, db}
for _, test := range tests {
test(dbt)
dbt.db.Exec("DROP TABLE IF EXISTS test")
}
}
type DBTest struct {
*C
db *sql.DB
}
func (dbt *DBTest) fail(method, query string, err error) {
if len(query) > 300 {
query = "[query too large to print]"
}
dbt.Fatalf("Error on %s %s: %s", method, query, err.Error())
}
func (dbt *DBTest) mustPrepare(query string) *sql.Stmt {
stmt, err := dbt.db.Prepare(query)
dbt.Assert(err, IsNil, Commentf("Prepare %s", query))
return stmt
}
func (dbt *DBTest) mustExecPrepared(stmt *sql.Stmt, args ...interface{}) sql.Result {
res, err := stmt.Exec(args...)
dbt.Assert(err, IsNil, Commentf("Execute prepared with args: %s", args))
return res
}
func (dbt *DBTest) mustQueryPrepared(stmt *sql.Stmt, args ...interface{}) *sql.Rows {
rows, err := stmt.Query(args...)
dbt.Assert(err, IsNil, Commentf("Query prepared with args: %s", args))
return rows
}
func (dbt *DBTest) mustExec(query string, args ...interface{}) (res sql.Result) {
res, err := dbt.db.Exec(query, args...)
dbt.Assert(err, IsNil, Commentf("Exec %s", query))
return res
}
func (dbt *DBTest) mustQuery(query string, args ...interface{}) (rows *sql.Rows) {
rows, err := dbt.db.Query(query, args...)
dbt.Assert(err, IsNil, Commentf("Query %s", query))
return rows
}
func (dbt *DBTest) mustQueryRows(query string, args ...interface{}) {
rows := dbt.mustQuery(query, args...)
dbt.Assert(rows.Next(), IsTrue)
rows.Close()
}
func (cli *testServerClient) runTestRegression(c *C, overrider configOverrider, dbName string) {
cli.runTestsOnNewDB(c, overrider, dbName, func(dbt *DBTest) {
// Show the user
dbt.mustExec("select user()")
// Create Table
dbt.mustExec("CREATE TABLE test (val TINYINT)")
// Test for unexpected data
var out bool
rows := dbt.mustQuery("SELECT * FROM test")
dbt.Assert(rows.Next(), IsFalse, Commentf("unexpected data in empty table"))
// Create Data
res := dbt.mustExec("INSERT INTO test VALUES (1)")
// res := dbt.mustExec("INSERT INTO test VALUES (?)", 1)
count, err := res.RowsAffected()
dbt.Assert(err, IsNil)
dbt.Check(count, Equals, int64(1))
id, err := res.LastInsertId()
dbt.Assert(err, IsNil)
dbt.Check(id, Equals, int64(0))
// Read
rows = dbt.mustQuery("SELECT val FROM test")
if rows.Next() {
rows.Scan(&out)
dbt.Check(out, IsTrue)
dbt.Check(rows.Next(), IsFalse, Commentf("unexpected data"))
} else {
dbt.Error("no data")
}
rows.Close()
// Update
res = dbt.mustExec("UPDATE test SET val = 0 WHERE val = ?", 1)
count, err = res.RowsAffected()
dbt.Assert(err, IsNil)
dbt.Check(count, Equals, int64(1))
// Check Update
rows = dbt.mustQuery("SELECT val FROM test")
if rows.Next() {
rows.Scan(&out)
dbt.Check(out, IsFalse)
dbt.Check(rows.Next(), IsFalse, Commentf("unexpected data"))
} else {
dbt.Error("no data")
}
rows.Close()
// Delete
res = dbt.mustExec("DELETE FROM test WHERE val = 0")
// res = dbt.mustExec("DELETE FROM test WHERE val = ?", 0)
count, err = res.RowsAffected()
dbt.Assert(err, IsNil)
dbt.Check(count, Equals, int64(1))
// Check for unexpected rows
res = dbt.mustExec("DELETE FROM test")
count, err = res.RowsAffected()
dbt.Assert(err, IsNil)
dbt.Check(count, Equals, int64(0))
dbt.mustQueryRows("SELECT 1")
var b = make([]byte, 0)
if err := dbt.db.QueryRow("SELECT ?", b).Scan(&b); err != nil {
dbt.Fatal(err)
}
if b == nil {
dbt.Error("nil echo from non-nil input")
}
})
}
func (cli *testServerClient) runTestPrepareResultFieldType(t *C) {
var param int64 = 83
cli.runTests(t, nil, func(dbt *DBTest) {
stmt, err := dbt.db.Prepare(`SELECT ?`)
if err != nil {
dbt.Fatal(err)
}
defer stmt.Close()
row := stmt.QueryRow(param)
var result int64
err = row.Scan(&result)
if err != nil {
dbt.Fatal(err)
}
switch {
case result != param:
dbt.Fatal("Unexpected result value")
}
})
}
func (cli *testServerClient) runTestSpecialType(t *C) {
cli.runTestsOnNewDB(t, nil, "SpecialType", func(dbt *DBTest) {
dbt.mustExec("create table test (a decimal(10, 5), b datetime, c time, d bit(8))")
dbt.mustExec("insert test values (1.4, '2012-12-21 12:12:12', '4:23:34', b'1000')")
rows := dbt.mustQuery("select * from test where a > ?", 0)
t.Assert(rows.Next(), IsTrue)
var outA float64
var outB, outC string
var outD []byte
err := rows.Scan(&outA, &outB, &outC, &outD)
t.Assert(err, IsNil)
t.Assert(outA, Equals, 1.4)
t.Assert(outB, Equals, "2012-12-21 12:12:12")
t.Assert(outC, Equals, "04:23:34")
t.Assert(outD, BytesEquals, []byte{8})
})
}
func (cli *testServerClient) runTestClientWithCollation(t *C) {
cli.runTests(t, func(config *mysql.Config) {
config.Collation = "utf8mb4_general_ci"
}, func(dbt *DBTest) {
var name, charset, collation string
// check session variable collation_connection
rows := dbt.mustQuery("show variables like 'collation_connection'")
t.Assert(rows.Next(), IsTrue)
err := rows.Scan(&name, &collation)
t.Assert(err, IsNil)
t.Assert(collation, Equals, "utf8mb4_general_ci")
// check session variable character_set_client
rows = dbt.mustQuery("show variables like 'character_set_client'")
t.Assert(rows.Next(), IsTrue)
err = rows.Scan(&name, &charset)
t.Assert(err, IsNil)
t.Assert(charset, Equals, "utf8mb4")
// check session variable character_set_results
rows = dbt.mustQuery("show variables like 'character_set_results'")
t.Assert(rows.Next(), IsTrue)
err = rows.Scan(&name, &charset)
t.Assert(err, IsNil)
t.Assert(charset, Equals, "utf8mb4")
// check session variable character_set_connection
rows = dbt.mustQuery("show variables like 'character_set_connection'")
t.Assert(rows.Next(), IsTrue)
err = rows.Scan(&name, &charset)
t.Assert(err, IsNil)
t.Assert(charset, Equals, "utf8mb4")
})
}
func (cli *testServerClient) runTestPreparedString(t *C) {
cli.runTestsOnNewDB(t, nil, "PreparedString", func(dbt *DBTest) {
dbt.mustExec("create table test (a char(10), b char(10))")
dbt.mustExec("insert test values (?, ?)", "abcdeabcde", "abcde")
rows := dbt.mustQuery("select * from test where 1 = ?", 1)
t.Assert(rows.Next(), IsTrue)
var outA, outB string
err := rows.Scan(&outA, &outB)
t.Assert(err, IsNil)
t.Assert(outA, Equals, "abcdeabcde")
t.Assert(outB, Equals, "abcde")
})
}
// runTestPreparedTimestamp does not really cover binary timestamp format, because MySQL driver in golang
// does not use this format. MySQL driver in golang will convert the timestamp to a string.
// This case guarantees it could work.
func (cli *testServerClient) runTestPreparedTimestamp(t *C) {
cli.runTestsOnNewDB(t, nil, "prepared_timestamp", func(dbt *DBTest) {
dbt.mustExec("create table test (a timestamp, b time)")
dbt.mustExec("set time_zone='+00:00'")
insertStmt := dbt.mustPrepare("insert test values (?, ?)")
defer insertStmt.Close()
vts := time.Unix(1, 1)
vt := time.Unix(-1, 1)
dbt.mustExecPrepared(insertStmt, vts, vt)
selectStmt := dbt.mustPrepare("select * from test where a = ? and b = ?")
defer selectStmt.Close()
rows := dbt.mustQueryPrepared(selectStmt, vts, vt)
t.Assert(rows.Next(), IsTrue)
var outA, outB string
err := rows.Scan(&outA, &outB)
t.Assert(err, IsNil)
t.Assert(outA, Equals, "1970-01-01 00:00:01")
t.Assert(outB, Equals, "23:59:59")
})
}
func (cli *testServerClient) runTestLoadDataWithSelectIntoOutfile(c *C, server *Server) {
cli.runTestsOnNewDB(c, func(config *mysql.Config) {
config.AllowAllFiles = true
config.Params = map[string]string{"sql_mode": "''"}
}, "SelectIntoOutfile", func(dbt *DBTest) {
dbt.mustExec("create table t (i int, r real, d decimal(10, 5), s varchar(100), dt datetime, ts timestamp, j json)")
dbt.mustExec("insert into t values (1, 1.1, 0.1, 'a', '2000-01-01', '01:01:01', '[1]')")
dbt.mustExec("insert into t values (2, 2.2, 0.2, 'b', '2000-02-02', '02:02:02', '[1,2]')")
dbt.mustExec("insert into t values (null, null, null, null, '2000-03-03', '03:03:03', '[1,2,3]')")
dbt.mustExec("insert into t values (4, 4.4, 0.4, 'd', null, null, null)")
outfile := filepath.Join(os.TempDir(), fmt.Sprintf("select_into_outfile_%v_%d.csv", time.Now().UnixNano(), rand.Int()))
// On windows use fmt.Sprintf("%q") to escape \ for SQL,
// outfile may be 'C:\Users\genius\AppData\Local\Temp\select_into_outfile_1582732846769492000_8074605509026837941.csv'
// Without quote, after SQL escape it would become:
// 'C:UsersgeniusAppDataLocalTempselect_into_outfile_1582732846769492000_8074605509026837941.csv'
dbt.mustExec(fmt.Sprintf("select * from t into outfile %q", outfile))
defer func() {
c.Assert(os.Remove(outfile), IsNil)
}()
dbt.mustExec("create table t1 (i int, r real, d decimal(10, 5), s varchar(100), dt datetime, ts timestamp, j json)")
dbt.mustExec(fmt.Sprintf("load data local infile %q into table t1", outfile))
fetchResults := func(table string) [][]interface{} {
var res [][]interface{}
row := dbt.mustQuery("select * from " + table + " order by i")
for row.Next() {
r := make([]interface{}, 7)
c.Assert(row.Scan(&r[0], &r[1], &r[2], &r[3], &r[4], &r[5], &r[6]), IsNil)
res = append(res, r)
}
c.Assert(row.Close(), IsNil)
return res
}
res := fetchResults("t")
res1 := fetchResults("t1")
c.Assert(len(res), Equals, len(res1))
for i := range res {
for j := range res[i] {
// using Sprintf to avoid some uncomparable types
c.Assert(fmt.Sprintf("%v", res[i][j]), Equals, fmt.Sprintf("%v", res1[i][j]))
}
}
})
}
func (cli *testServerClient) runTestLoadData(c *C, server *Server) {
// create a file and write data.
path := "/tmp/load_data_test.csv"
fp, err := os.Create(path)
c.Assert(err, IsNil)
c.Assert(fp, NotNil)
defer func() {
err = fp.Close()
c.Assert(err, IsNil)
err = os.Remove(path)
c.Assert(err, IsNil)
}()
_, err = fp.WriteString("\n" +
"xxx row1_col1 - row1_col2 1abc\n" +
"xxx row2_col1 - row2_col2 \n" +
"xxxy row3_col1 - row3_col2 \n" +
"xxx row4_col1 - 900\n" +
"xxx row5_col1 - row5_col3")
c.Assert(err, IsNil)
originalTxnTotalSizeLimit := kv.TxnTotalSizeLimit
// If the MemBuffer can't be committed once in each batch, it will return an error like "transaction is too large".
kv.TxnTotalSizeLimit = 10240
defer func() { kv.TxnTotalSizeLimit = originalTxnTotalSizeLimit }()
// support ClientLocalFiles capability
cli.runTestsOnNewDB(c, func(config *mysql.Config) {
config.AllowAllFiles = true
config.Params = map[string]string{"sql_mode": "''"}
}, "LoadData", func(dbt *DBTest) {
dbt.mustExec("set @@tidb_dml_batch_size = 3")
dbt.mustExec("create table test (a varchar(255), b varchar(255) default 'default value', c int not null auto_increment, primary key(c))")
rs, err1 := dbt.db.Exec("load data local infile '/tmp/load_data_test.csv' into table test")
dbt.Assert(err1, IsNil)
lastID, err1 := rs.LastInsertId()
dbt.Assert(err1, IsNil)
dbt.Assert(lastID, Equals, int64(1))
affectedRows, err1 := rs.RowsAffected()
dbt.Assert(err1, IsNil)
dbt.Assert(affectedRows, Equals, int64(5))
var (
a string
b string
bb sql.NullString
cc int
)
rows := dbt.mustQuery("select * from test")
dbt.Check(rows.Next(), IsTrue, Commentf("unexpected data"))
err = rows.Scan(&a, &bb, &cc)
dbt.Check(err, IsNil)
dbt.Check(a, DeepEquals, "")
dbt.Check(bb.String, DeepEquals, "")
dbt.Check(cc, DeepEquals, 1)
dbt.Check(rows.Next(), IsTrue, Commentf("unexpected data"))
rows.Scan(&a, &b, &cc)
dbt.Check(a, DeepEquals, "xxx row2_col1")
dbt.Check(b, DeepEquals, "- row2_col2")
dbt.Check(cc, DeepEquals, 2)
dbt.Check(rows.Next(), IsTrue, Commentf("unexpected data"))
rows.Scan(&a, &b, &cc)
dbt.Check(a, DeepEquals, "xxxy row3_col1")
dbt.Check(b, DeepEquals, "- row3_col2")
dbt.Check(cc, DeepEquals, 3)
dbt.Check(rows.Next(), IsTrue, Commentf("unexpected data"))
rows.Scan(&a, &b, &cc)
dbt.Check(a, DeepEquals, "xxx row4_col1")
dbt.Check(b, DeepEquals, "- ")
dbt.Check(cc, DeepEquals, 4)
dbt.Check(rows.Next(), IsTrue, Commentf("unexpected data"))
rows.Scan(&a, &b, &cc)
dbt.Check(a, DeepEquals, "xxx row5_col1")
dbt.Check(b, DeepEquals, "- ")
dbt.Check(cc, DeepEquals, 5)
dbt.Check(rows.Next(), IsFalse, Commentf("unexpected data"))
rows.Close()
// specify faileds and lines
dbt.mustExec("delete from test")
dbt.mustExec("set @@tidb_dml_batch_size = 3")
rs, err = dbt.db.Exec("load data local infile '/tmp/load_data_test.csv' into table test fields terminated by '\t- ' lines starting by 'xxx ' terminated by '\n'")
dbt.Assert(err, IsNil)
lastID, err = rs.LastInsertId()
dbt.Assert(err, IsNil)
dbt.Assert(lastID, Equals, int64(6))
affectedRows, err = rs.RowsAffected()
dbt.Assert(err, IsNil)
dbt.Assert(affectedRows, Equals, int64(4))
rows = dbt.mustQuery("select * from test")
dbt.Check(rows.Next(), IsTrue, Commentf("unexpected data"))
rows.Scan(&a, &b, &cc)
dbt.Check(a, DeepEquals, "row1_col1")
dbt.Check(b, DeepEquals, "row1_col2\t1abc")
dbt.Check(cc, DeepEquals, 6)
dbt.Check(rows.Next(), IsTrue, Commentf("unexpected data"))
rows.Scan(&a, &b, &cc)
dbt.Check(a, DeepEquals, "row2_col1")
dbt.Check(b, DeepEquals, "row2_col2\t")
dbt.Check(cc, DeepEquals, 7)
dbt.Check(rows.Next(), IsTrue, Commentf("unexpected data"))
rows.Scan(&a, &b, &cc)
dbt.Check(a, DeepEquals, "row4_col1")
dbt.Check(b, DeepEquals, "\t\t900")
dbt.Check(cc, DeepEquals, 8)
dbt.Check(rows.Next(), IsTrue, Commentf("unexpected data"))
rows.Scan(&a, &b, &cc)
dbt.Check(a, DeepEquals, "row5_col1")
dbt.Check(b, DeepEquals, "\trow5_col3")
dbt.Check(cc, DeepEquals, 9)
dbt.Check(rows.Next(), IsFalse, Commentf("unexpected data"))
// infile size more than a packet size(16K)
dbt.mustExec("delete from test")
_, err = fp.WriteString("\n")
dbt.Assert(err, IsNil)
for i := 6; i <= 800; i++ {
_, err = fp.WriteString(fmt.Sprintf("xxx row%d_col1 - row%d_col2\n", i, i))
dbt.Assert(err, IsNil)
}
dbt.mustExec("set @@tidb_dml_batch_size = 3")
rs, err = dbt.db.Exec("load data local infile '/tmp/load_data_test.csv' into table test fields terminated by '\t- ' lines starting by 'xxx ' terminated by '\n'")
dbt.Assert(err, IsNil)
lastID, err = rs.LastInsertId()
dbt.Assert(err, IsNil)
dbt.Assert(lastID, Equals, int64(10))
affectedRows, err = rs.RowsAffected()
dbt.Assert(err, IsNil)
dbt.Assert(affectedRows, Equals, int64(799))
rows = dbt.mustQuery("select * from test")
dbt.Check(rows.Next(), IsTrue, Commentf("unexpected data"))
// don't support lines terminated is ""
dbt.mustExec("set @@tidb_dml_batch_size = 3")
_, err = dbt.db.Exec("load data local infile '/tmp/load_data_test.csv' into table test lines terminated by ''")
dbt.Assert(err, NotNil)
// infile doesn't exist
dbt.mustExec("set @@tidb_dml_batch_size = 3")
_, err = dbt.db.Exec("load data local infile '/tmp/nonexistence.csv' into table test")
dbt.Assert(err, NotNil)
})
err = fp.Close()
c.Assert(err, IsNil)
err = os.Remove(path)
c.Assert(err, IsNil)
fp, err = os.Create(path)
c.Assert(err, IsNil)
c.Assert(fp, NotNil)
// Test mixed unenclosed and enclosed fields.
_, err = fp.WriteString(
"\"abc\",123\n" +
"def,456,\n" +
"hig,\"789\",")
c.Assert(err, IsNil)
cli.runTestsOnNewDB(c, func(config *mysql.Config) {
config.AllowAllFiles = true
config.Params = map[string]string{"sql_mode": "''"}
}, "LoadData", func(dbt *DBTest) {
dbt.mustExec("create table test (str varchar(10) default null, i int default null)")
dbt.mustExec("set @@tidb_dml_batch_size = 3")
_, err1 := dbt.db.Exec(`load data local infile '/tmp/load_data_test.csv' into table test FIELDS TERMINATED BY ',' enclosed by '"'`)
dbt.Assert(err1, IsNil)
var (
str string
id int
)
rows := dbt.mustQuery("select * from test")
dbt.Check(rows.Next(), IsTrue, Commentf("unexpected data"))
err = rows.Scan(&str, &id)
dbt.Check(err, IsNil)
dbt.Check(str, DeepEquals, "abc")
dbt.Check(id, DeepEquals, 123)
dbt.Check(rows.Next(), IsTrue, Commentf("unexpected data"))
rows.Scan(&str, &id)
dbt.Check(str, DeepEquals, "def")
dbt.Check(id, DeepEquals, 456)
dbt.Check(rows.Next(), IsTrue, Commentf("unexpected data"))
rows.Scan(&str, &id)
dbt.Check(str, DeepEquals, "hig")
dbt.Check(id, DeepEquals, 789)
dbt.Check(rows.Next(), IsFalse, Commentf("unexpected data"))
dbt.mustExec("delete from test")
})
err = fp.Close()
c.Assert(err, IsNil)
err = os.Remove(path)
c.Assert(err, IsNil)
fp, err = os.Create(path)
c.Assert(err, IsNil)
c.Assert(fp, NotNil)
// Test irregular csv file.
_, err = fp.WriteString(
`,\N,NULL,,` + "\n" +
"00,0,000000,,\n" +
`2003-03-03, 20030303,030303,\N` + "\n")
c.Assert(err, IsNil)
cli.runTestsOnNewDB(c, func(config *mysql.Config) {
config.AllowAllFiles = true
config.Params = map[string]string{"sql_mode": "''"}
}, "LoadData", func(dbt *DBTest) {
dbt.mustExec("create table test (a date, b date, c date not null, d date)")
dbt.mustExec("set @@tidb_dml_batch_size = 3")
_, err1 := dbt.db.Exec(`load data local infile '/tmp/load_data_test.csv' into table test FIELDS TERMINATED BY ','`)
dbt.Assert(err1, IsNil)
var (
a sql.NullString
b sql.NullString
d sql.NullString
c sql.NullString
)
rows := dbt.mustQuery("select * from test")
dbt.Check(rows.Next(), IsTrue, Commentf("unexpected data"))
err = rows.Scan(&a, &b, &c, &d)
dbt.Check(err, IsNil)
dbt.Check(a.String, Equals, "0000-00-00")
dbt.Check(b.String, Equals, "")
dbt.Check(c.String, Equals, "0000-00-00")
dbt.Check(d.String, Equals, "0000-00-00")
dbt.Check(rows.Next(), IsTrue, Commentf("unexpected data"))
rows.Scan(&a, &b, &c, &d)
dbt.Check(a.String, Equals, "0000-00-00")
dbt.Check(b.String, Equals, "0000-00-00")
dbt.Check(c.String, Equals, "0000-00-00")
dbt.Check(d.String, Equals, "0000-00-00")
dbt.Check(rows.Next(), IsTrue, Commentf("unexpected data"))
rows.Scan(&a, &b, &c, &d)
dbt.Check(a.String, Equals, "2003-03-03")
dbt.Check(b.String, Equals, "2003-03-03")
dbt.Check(c.String, Equals, "2003-03-03")
dbt.Check(d.String, Equals, "")
dbt.Check(rows.Next(), IsFalse, Commentf("unexpected data"))
dbt.mustExec("delete from test")
})
err = fp.Close()
c.Assert(err, IsNil)
err = os.Remove(path)
c.Assert(err, IsNil)
fp, err = os.Create(path)
c.Assert(err, IsNil)
c.Assert(fp, NotNil)
// Test double enclosed.
_, err = fp.WriteString(
`"field1","field2"` + "\n" +
`"a""b","cd""ef"` + "\n" +
`"a"b",c"d"e` + "\n")
c.Assert(err, IsNil)
cli.runTestsOnNewDB(c, func(config *mysql.Config) {
config.AllowAllFiles = true
config.Params = map[string]string{"sql_mode": "''"}
}, "LoadData", func(dbt *DBTest) {
dbt.mustExec("create table test (a varchar(20), b varchar(20))")
dbt.mustExec("set @@tidb_dml_batch_size = 3")
_, err1 := dbt.db.Exec(`load data local infile '/tmp/load_data_test.csv' into table test FIELDS TERMINATED BY ',' enclosed by '"'`)
dbt.Assert(err1, IsNil)
var (
a sql.NullString
b sql.NullString
)
rows := dbt.mustQuery("select * from test")
dbt.Check(rows.Next(), IsTrue, Commentf("unexpected data"))
err = rows.Scan(&a, &b)
dbt.Check(err, IsNil)
dbt.Check(a.String, Equals, "field1")
dbt.Check(b.String, Equals, "field2")
dbt.Check(rows.Next(), IsTrue, Commentf("unexpected data"))
rows.Scan(&a, &b)
dbt.Check(a.String, Equals, `a"b`)
dbt.Check(b.String, Equals, `cd"ef`)
dbt.Check(rows.Next(), IsTrue, Commentf("unexpected data"))
rows.Scan(&a, &b)
dbt.Check(a.String, Equals, `a"b`)
dbt.Check(b.String, Equals, `c"d"e`)
dbt.Check(rows.Next(), IsFalse, Commentf("unexpected data"))
dbt.mustExec("delete from test")
})
err = fp.Close()
c.Assert(err, IsNil)
err = os.Remove(path)
c.Assert(err, IsNil)
fp, err = os.Create(path)
c.Assert(err, IsNil)
c.Assert(fp, NotNil)
// Test OPTIONALLY
_, err = fp.WriteString(
`"a,b,c` + "\n" +
`"1",2,"3"` + "\n")
c.Assert(err, IsNil)
cli.runTestsOnNewDB(c, func(config *mysql.Config) {
config.AllowAllFiles = true
}, "LoadData", func(dbt *DBTest) {
dbt.mustExec("create table test (id INT NOT NULL PRIMARY KEY, b INT, c varchar(10))")
dbt.mustExec("set @@tidb_dml_batch_size = 3")
_, err1 := dbt.db.Exec(`load data local infile '/tmp/load_data_test.csv' into table test FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' IGNORE 1 LINES`)
dbt.Assert(err1, IsNil)
var (
a int
b int
c sql.NullString
)
rows := dbt.mustQuery("select * from test")
dbt.Check(rows.Next(), IsTrue, Commentf("unexpected data"))
err = rows.Scan(&a, &b, &c)
dbt.Check(err, IsNil)
dbt.Check(a, Equals, 1)
dbt.Check(b, Equals, 2)
dbt.Check(c.String, Equals, "3")
dbt.Check(rows.Next(), IsFalse, Commentf("unexpected data"))
dbt.mustExec("delete from test")
})
// unsupport ClientLocalFiles capability
server.capability ^= tmysql.ClientLocalFiles
cli.runTestsOnNewDB(c, func(config *mysql.Config) {
config.AllowAllFiles = true
}, "LoadData", func(dbt *DBTest) {
dbt.mustExec("create table test (a varchar(255), b varchar(255) default 'default value', c int not null auto_increment, primary key(c))")
dbt.mustExec("set @@tidb_dml_batch_size = 3")
_, err = dbt.db.Exec("load data local infile '/tmp/load_data_test.csv' into table test")
dbt.Assert(err, NotNil)
checkErrorCode(c, err, errno.ErrNotAllowedCommand)
})
server.capability |= tmysql.ClientLocalFiles
err = fp.Close()
c.Assert(err, IsNil)
err = os.Remove(path)
c.Assert(err, IsNil)
fp, err = os.Create(path)
c.Assert(err, IsNil)
c.Assert(fp, NotNil)
// Test OPTIONALLY
_, err = fp.WriteString(
`1,2` + "\n" +
`3,4` + "\n")
c.Assert(err, IsNil)
cli.runTestsOnNewDB(c, func(config *mysql.Config) {
config.AllowAllFiles = true
config.Params = map[string]string{"sql_mode": "''"}
}, "LoadData", func(dbt *DBTest) {
dbt.mustExec("drop table if exists pn")
dbt.mustExec("create table pn (c1 int, c2 int)")
dbt.mustExec("set @@tidb_dml_batch_size = 1")
_, err1 := dbt.db.Exec(`load data local infile '/tmp/load_data_test.csv' into table pn FIELDS TERMINATED BY ','`)
dbt.Assert(err1, IsNil)
var (
a int
b int
)
rows := dbt.mustQuery("select * from pn")
dbt.Check(rows.Next(), IsTrue, Commentf("unexpected data"))
err = rows.Scan(&a, &b)
dbt.Check(err, IsNil)
dbt.Check(a, Equals, 1)
dbt.Check(b, Equals, 2)
dbt.Check(rows.Next(), IsTrue, Commentf("unexpected data"))
err = rows.Scan(&a, &b)
dbt.Check(err, IsNil)
dbt.Check(a, Equals, 3)
dbt.Check(b, Equals, 4)
dbt.Check(rows.Next(), IsFalse, Commentf("unexpected data"))
// fail error processing test
dbt.Assert(failpoint.Enable("github.com/pingcap/tidb/executor/commitOneTaskErr", "return"), IsNil)
_, err1 = dbt.db.Exec(`load data local infile '/tmp/load_data_test.csv' into table pn FIELDS TERMINATED BY ','`)
mysqlErr, ok := err1.(*mysql.MySQLError)
dbt.Assert(ok, IsTrue)
dbt.Assert(mysqlErr.Message, Equals, "mock commit one task error")
dbt.Assert(failpoint.Disable("github.com/pingcap/tidb/executor/commitOneTaskErr"), IsNil)
dbt.mustExec("drop table if exists pn")
})
err = fp.Close()
c.Assert(err, IsNil)
err = os.Remove(path)
c.Assert(err, IsNil)
fp, err = os.Create(path)
c.Assert(err, IsNil)
c.Assert(fp, NotNil)
// Test Column List Specification
_, err = fp.WriteString(
`1,2` + "\n" +
`3,4` + "\n")
c.Assert(err, IsNil)
cli.runTestsOnNewDB(c, func(config *mysql.Config) {
config.AllowAllFiles = true
config.Params = map[string]string{"sql_mode": "''"}
}, "LoadData", func(dbt *DBTest) {
dbt.mustExec("drop table if exists pn")
dbt.mustExec("create table pn (c1 int, c2 int)")
dbt.mustExec("set @@tidb_dml_batch_size = 1")
_, err1 := dbt.db.Exec(`load data local infile '/tmp/load_data_test.csv' into table pn FIELDS TERMINATED BY ',' (c1, c2)`)
dbt.Assert(err1, IsNil)
var (
a int
b int
)
rows := dbt.mustQuery("select * from pn")
dbt.Check(rows.Next(), IsTrue, Commentf("unexpected data"))
err = rows.Scan(&a, &b)
dbt.Check(err, IsNil)
dbt.Check(a, Equals, 1)
dbt.Check(b, Equals, 2)
dbt.Check(rows.Next(), IsTrue, Commentf("unexpected data"))
err = rows.Scan(&a, &b)
dbt.Check(err, IsNil)
dbt.Check(a, Equals, 3)
dbt.Check(b, Equals, 4)
dbt.Check(rows.Next(), IsFalse, Commentf("unexpected data"))
dbt.mustExec("drop table if exists pn")
})
err = fp.Close()
c.Assert(err, IsNil)
err = os.Remove(path)
c.Assert(err, IsNil)
fp, err = os.Create(path)
c.Assert(err, IsNil)
c.Assert(fp, NotNil)
// Test Column List Specification
_, err = fp.WriteString(
`1,2,3` + "\n" +
`4,5,6` + "\n")
c.Assert(err, IsNil)
cli.runTestsOnNewDB(c, func(config *mysql.Config) {
config.AllowAllFiles = true
config.Params = map[string]string{"sql_mode": "''"}
}, "LoadData", func(dbt *DBTest) {
dbt.mustExec("drop table if exists pn")
dbt.mustExec("create table pn (c1 int, c2 int, c3 int)")
dbt.mustExec("set @@tidb_dml_batch_size = 1")
_, err1 := dbt.db.Exec(`load data local infile '/tmp/load_data_test.csv' into table pn FIELDS TERMINATED BY ',' (c1, @dummy)`)
dbt.Assert(err1, IsNil)
var (
a int
b sql.NullString
c sql.NullString
)
rows := dbt.mustQuery("select * from pn")
dbt.Check(rows.Next(), IsTrue, Commentf("unexpected data"))
err = rows.Scan(&a, &b, &c)
dbt.Check(err, IsNil)
dbt.Check(a, Equals, 1)
dbt.Check(b.String, Equals, "")
dbt.Check(c.String, Equals, "")
dbt.Check(rows.Next(), IsTrue, Commentf("unexpected data"))
err = rows.Scan(&a, &b, &c)
dbt.Check(err, IsNil)
dbt.Check(a, Equals, 4)
dbt.Check(b.String, Equals, "")
dbt.Check(c.String, Equals, "")
dbt.Check(rows.Next(), IsFalse, Commentf("unexpected data"))
dbt.mustExec("drop table if exists pn")
})
err = fp.Close()
c.Assert(err, IsNil)
err = os.Remove(path)
c.Assert(err, IsNil)
fp, err = os.Create(path)
c.Assert(err, IsNil)
c.Assert(fp, NotNil)
// Test Input Preprocessing
_, err = fp.WriteString(
`1,2,3` + "\n" +
`4,5,6` + "\n")
c.Assert(err, IsNil)
cli.runTestsOnNewDB(c, func(config *mysql.Config) {
config.AllowAllFiles = true
config.Params = map[string]string{"sql_mode": "''"}
}, "LoadData", func(dbt *DBTest) {
dbt.mustExec("drop table if exists pn")
dbt.mustExec("create table pn (c1 int, c2 int, c3 int)")
dbt.mustExec("set @@tidb_dml_batch_size = 1")
_, err1 := dbt.db.Exec(`load data local infile '/tmp/load_data_test.csv' into table pn FIELDS TERMINATED BY ',' (c1, @val1, @val2) SET c3 = @val2 * 100, c2 = CAST(@val1 AS UNSIGNED)`)
dbt.Assert(err1, IsNil)
var (
a int
b int
c int
)
rows := dbt.mustQuery("select * from pn")
dbt.Check(rows.Next(), IsTrue, Commentf("unexpected data"))
err = rows.Scan(&a, &b, &c)
dbt.Check(err, IsNil)
dbt.Check(a, Equals, 1)
dbt.Check(b, Equals, 2)
dbt.Check(c, Equals, 300)
dbt.Check(rows.Next(), IsTrue, Commentf("unexpected data"))
err = rows.Scan(&a, &b, &c)
dbt.Check(err, IsNil)
dbt.Check(a, Equals, 4)
dbt.Check(b, Equals, 5)
dbt.Check(c, Equals, 600)
dbt.Check(rows.Next(), IsFalse, Commentf("unexpected data"))
dbt.mustExec("drop table if exists pn")
})
}
func (cli *testServerClient) runTestConcurrentUpdate(c *C) {
dbName := "Concurrent"
cli.runTestsOnNewDB(c, func(config *mysql.Config) {
config.Params = map[string]string{"sql_mode": "''"}
}, dbName, func(dbt *DBTest) {
dbt.mustExec("drop table if exists test2")
dbt.mustExec("create table test2 (a int, b int)")
dbt.mustExec("insert test2 values (1, 1)")
dbt.mustExec("set @@tidb_disable_txn_auto_retry = 0")
txn1, err := dbt.db.Begin()
c.Assert(err, IsNil)
_, err = txn1.Exec(fmt.Sprintf("USE `%s`;", dbName))
c.Assert(err, IsNil)
txn2, err := dbt.db.Begin()
c.Assert(err, IsNil)
_, err = txn2.Exec(fmt.Sprintf("USE `%s`;", dbName))
c.Assert(err, IsNil)
_, err = txn2.Exec("update test2 set a = a + 1 where b = 1")
c.Assert(err, IsNil)
err = txn2.Commit()
c.Assert(err, IsNil)
_, err = txn1.Exec("update test2 set a = a + 1 where b = 1")
c.Assert(err, IsNil)
err = txn1.Commit()
c.Assert(err, IsNil)
})