-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
Copy pathsql.go
1519 lines (1422 loc) · 51.1 KB
/
sql.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 2020 PingCAP, Inc. Licensed under Apache-2.0.
package export
import (
"bytes"
"context"
"database/sql"
"encoding/json"
"fmt"
"io"
"math"
"net/url"
"strconv"
"strings"
"github.com/go-sql-driver/mysql"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
"go.uber.org/multierr"
"go.uber.org/zap"
"github.com/pingcap/tidb/br/pkg/version"
dbconfig "github.com/pingcap/tidb/config"
tcontext "github.com/pingcap/tidb/dumpling/context"
"github.com/pingcap/tidb/dumpling/log"
"github.com/pingcap/tidb/errno"
"github.com/pingcap/tidb/parser/model"
"github.com/pingcap/tidb/store/helper"
)
const (
orderByTiDBRowID = "ORDER BY `_tidb_rowid`"
)
type listTableType int
const (
listTableByInfoSchema listTableType = iota
listTableByShowFullTables
listTableByShowTableStatus
)
// ShowDatabases shows the databases of a database server.
func ShowDatabases(db *sql.Conn) ([]string, error) {
var res oneStrColumnTable
if err := simpleQuery(db, "SHOW DATABASES", res.handleOneRow); err != nil {
return nil, err
}
return res.data, nil
}
// ShowTables shows the tables of a database, the caller should use the correct database.
func ShowTables(db *sql.Conn) ([]string, error) {
var res oneStrColumnTable
if err := simpleQuery(db, "SHOW TABLES", res.handleOneRow); err != nil {
return nil, err
}
return res.data, nil
}
// ShowCreateDatabase constructs the create database SQL for a specified database
// returns (createDatabaseSQL, error)
func ShowCreateDatabase(tctx *tcontext.Context, db *BaseConn, database string) (string, error) {
var oneRow [2]string
handleOneRow := func(rows *sql.Rows) error {
return rows.Scan(&oneRow[0], &oneRow[1])
}
query := fmt.Sprintf("SHOW CREATE DATABASE `%s`", escapeString(database))
err := db.QuerySQL(tctx, handleOneRow, func() {
oneRow[0], oneRow[1] = "", ""
}, query)
if multiErrs := multierr.Errors(err); len(multiErrs) > 0 {
for _, multiErr := range multiErrs {
if mysqlErr, ok := errors.Cause(multiErr).(*mysql.MySQLError); ok {
// Falling back to simple create statement for MemSQL/SingleStore, because of this:
// ERROR 1706 (HY000): Feature 'SHOW CREATE DATABASE' is not supported by MemSQL.
if strings.Contains(mysqlErr.Error(), "SHOW CREATE DATABASE") {
return fmt.Sprintf("CREATE DATABASE `%s`", escapeString(database)), nil
}
}
}
}
return oneRow[1], err
}
// ShowCreateTable constructs the create table SQL for a specified table
// returns (createTableSQL, error)
func ShowCreateTable(tctx *tcontext.Context, db *BaseConn, database, table string) (string, error) {
var oneRow [2]string
handleOneRow := func(rows *sql.Rows) error {
return rows.Scan(&oneRow[0], &oneRow[1])
}
query := fmt.Sprintf("SHOW CREATE TABLE `%s`.`%s`", escapeString(database), escapeString(table))
err := db.QuerySQL(tctx, handleOneRow, func() {
oneRow[0], oneRow[1] = "", ""
}, query)
if err != nil {
return "", err
}
return oneRow[1], nil
}
// ShowCreatePlacementPolicy constructs the create policy SQL for a specified table
// returns (createPolicySQL, error)
func ShowCreatePlacementPolicy(tctx *tcontext.Context, db *BaseConn, policy string) (string, error) {
var oneRow [2]string
handleOneRow := func(rows *sql.Rows) error {
return rows.Scan(&oneRow[0], &oneRow[1])
}
query := fmt.Sprintf("SHOW CREATE PLACEMENT POLICY `%s`", escapeString(policy))
err := db.QuerySQL(tctx, handleOneRow, func() {
oneRow[0], oneRow[1] = "", ""
}, query)
return oneRow[1], err
}
// ShowCreateView constructs the create view SQL for a specified view
// returns (createFakeTableSQL, createViewSQL, error)
func ShowCreateView(tctx *tcontext.Context, db *BaseConn, database, view string) (createFakeTableSQL string, createRealViewSQL string, err error) {
var fieldNames []string
handleFieldRow := func(rows *sql.Rows) error {
var oneRow [6]sql.NullString
scanErr := rows.Scan(&oneRow[0], &oneRow[1], &oneRow[2], &oneRow[3], &oneRow[4], &oneRow[5])
if scanErr != nil {
return errors.Trace(scanErr)
}
if oneRow[0].Valid {
fieldNames = append(fieldNames, fmt.Sprintf("`%s` int", escapeString(oneRow[0].String)))
}
return nil
}
var oneRow [4]string
handleOneRow := func(rows *sql.Rows) error {
return rows.Scan(&oneRow[0], &oneRow[1], &oneRow[2], &oneRow[3])
}
var createTableSQL, createViewSQL strings.Builder
// Build createTableSQL
query := fmt.Sprintf("SHOW FIELDS FROM `%s`.`%s`", escapeString(database), escapeString(view))
err = db.QuerySQL(tctx, handleFieldRow, func() {
fieldNames = []string{}
}, query)
if err != nil {
return "", "", err
}
fmt.Fprintf(&createTableSQL, "CREATE TABLE `%s`(\n", escapeString(view))
createTableSQL.WriteString(strings.Join(fieldNames, ",\n"))
createTableSQL.WriteString("\n)ENGINE=MyISAM;\n")
// Build createViewSQL
fmt.Fprintf(&createViewSQL, "DROP TABLE IF EXISTS `%s`;\n", escapeString(view))
fmt.Fprintf(&createViewSQL, "DROP VIEW IF EXISTS `%s`;\n", escapeString(view))
query = fmt.Sprintf("SHOW CREATE VIEW `%s`.`%s`", escapeString(database), escapeString(view))
err = db.QuerySQL(tctx, handleOneRow, func() {
for i := range oneRow {
oneRow[i] = ""
}
}, query)
if err != nil {
return "", "", err
}
// The result for `show create view` SQL
// mysql> show create view v1;
// +------+-------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+
// | View | Create View | character_set_client | collation_connection |
// +------+-------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+
// | v1 | CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `v1` (`a`) AS SELECT `t`.`a` AS `a` FROM `test`.`t` | utf8 | utf8_general_ci |
// +------+-------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+
SetCharset(&createViewSQL, oneRow[2], oneRow[3])
createViewSQL.WriteString(oneRow[1])
createViewSQL.WriteString(";\n")
RestoreCharset(&createViewSQL)
return createTableSQL.String(), createViewSQL.String(), nil
}
// ShowCreateSequence constructs the create sequence SQL for a specified sequence
// returns (createSequenceSQL, error)
func ShowCreateSequence(tctx *tcontext.Context, db *BaseConn, database, sequence string, conf *Config) (string, error) {
var oneRow [2]string
handleOneRow := func(rows *sql.Rows) error {
return rows.Scan(&oneRow[0], &oneRow[1])
}
var (
createSequenceSQL strings.Builder
nextNotCachedValue int64
)
query := fmt.Sprintf("SHOW CREATE SEQUENCE `%s`.`%s`", escapeString(database), escapeString(sequence))
err := db.QuerySQL(tctx, handleOneRow, func() {
oneRow[0], oneRow[1] = "", ""
}, query)
if err != nil {
return "", err
}
createSequenceSQL.WriteString(oneRow[1])
createSequenceSQL.WriteString(";\n")
switch conf.ServerInfo.ServerType {
case version.ServerTypeTiDB:
// Get next not allocated auto increment id of the whole cluster
query := fmt.Sprintf("SHOW TABLE `%s`.`%s` NEXT_ROW_ID", escapeString(database), escapeString(sequence))
results, err := db.QuerySQLWithColumns(tctx, []string{"NEXT_GLOBAL_ROW_ID", "ID_TYPE"}, query)
if err != nil {
return "", err
}
for _, oneRow := range results {
nextGlobalRowId, idType := oneRow[0], oneRow[1]
if idType == "SEQUENCE" {
nextNotCachedValue, _ = strconv.ParseInt(nextGlobalRowId, 10, 64)
}
}
fmt.Fprintf(&createSequenceSQL, "SELECT SETVAL(`%s`,%d);\n", escapeString(sequence), nextNotCachedValue)
case version.ServerTypeMariaDB:
var oneRow1 string
handleOneRow1 := func(rows *sql.Rows) error {
return rows.Scan(&oneRow1)
}
query := fmt.Sprintf("SELECT NEXT_NOT_CACHED_VALUE FROM `%s`.`%s`", escapeString(database), escapeString(sequence))
err := db.QuerySQL(tctx, handleOneRow1, func() {
oneRow1 = ""
}, query)
if err != nil {
return "", err
}
nextNotCachedValue, _ = strconv.ParseInt(oneRow1, 10, 64)
fmt.Fprintf(&createSequenceSQL, "SELECT SETVAL(`%s`,%d);\n", escapeString(sequence), nextNotCachedValue)
}
return createSequenceSQL.String(), nil
}
// SetCharset builds the set charset SQLs
func SetCharset(w *strings.Builder, characterSet, collationConnection string) {
w.WriteString("SET @PREV_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT;\n")
w.WriteString("SET @PREV_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS;\n")
w.WriteString("SET @PREV_COLLATION_CONNECTION=@@COLLATION_CONNECTION;\n")
fmt.Fprintf(w, "SET character_set_client = %s;\n", characterSet)
fmt.Fprintf(w, "SET character_set_results = %s;\n", characterSet)
fmt.Fprintf(w, "SET collation_connection = %s;\n", collationConnection)
}
// RestoreCharset builds the restore charset SQLs
func RestoreCharset(w io.StringWriter) {
_, _ = w.WriteString("SET character_set_client = @PREV_CHARACTER_SET_CLIENT;\n")
_, _ = w.WriteString("SET character_set_results = @PREV_CHARACTER_SET_RESULTS;\n")
_, _ = w.WriteString("SET collation_connection = @PREV_COLLATION_CONNECTION;\n")
}
// ListAllDatabasesTables lists all the databases and tables from the database
// listTableByInfoSchema list tables by table information_schema in MySQL
// listTableByShowTableStatus has better performance than listTableByInfoSchema
// listTableByShowFullTables is used in mysql8 version [8.0.3,8.0.23), more details can be found in the comments of func matchMysqlBugversion
func ListAllDatabasesTables(tctx *tcontext.Context, db *sql.Conn, databaseNames []string,
listType listTableType, tableTypes ...TableType) (DatabaseTables, error) { // revive:disable-line:flag-parameter
dbTables := DatabaseTables{}
var (
schema, table, tableTypeStr string
tableType TableType
avgRowLength uint64
err error
)
tableTypeConditions := make([]string, len(tableTypes))
for i, tableType := range tableTypes {
tableTypeConditions[i] = fmt.Sprintf("TABLE_TYPE='%s'", tableType)
}
switch listType {
case listTableByInfoSchema:
query := fmt.Sprintf("SELECT TABLE_SCHEMA,TABLE_NAME,TABLE_TYPE,AVG_ROW_LENGTH FROM INFORMATION_SCHEMA.TABLES WHERE %s", strings.Join(tableTypeConditions, " OR "))
for _, schema := range databaseNames {
dbTables[schema] = make([]*TableInfo, 0)
}
if err = simpleQueryWithArgs(tctx, db, func(rows *sql.Rows) error {
var (
sqlAvgRowLength sql.NullInt64
err2 error
)
if err2 = rows.Scan(&schema, &table, &tableTypeStr, &sqlAvgRowLength); err != nil {
return errors.Trace(err2)
}
tableType, err2 = ParseTableType(tableTypeStr)
if err2 != nil {
return errors.Trace(err2)
}
if sqlAvgRowLength.Valid {
avgRowLength = uint64(sqlAvgRowLength.Int64)
} else {
avgRowLength = 0
}
// only append tables to schemas in databaseNames
if _, ok := dbTables[schema]; ok {
dbTables[schema] = append(dbTables[schema], &TableInfo{table, avgRowLength, tableType})
}
return nil
}, query); err != nil {
return nil, errors.Annotatef(err, "sql: %s", query)
}
case listTableByShowFullTables:
for _, schema = range databaseNames {
dbTables[schema] = make([]*TableInfo, 0)
query := fmt.Sprintf("SHOW FULL TABLES FROM `%s` WHERE %s",
escapeString(schema), strings.Join(tableTypeConditions, " OR "))
if err = simpleQueryWithArgs(tctx, db, func(rows *sql.Rows) error {
var err2 error
if err2 = rows.Scan(&table, &tableTypeStr); err != nil {
return errors.Trace(err2)
}
tableType, err2 = ParseTableType(tableTypeStr)
if err2 != nil {
return errors.Trace(err2)
}
avgRowLength = 0 // can't get avgRowLength from the result of `show full tables` so hardcode to 0 here
dbTables[schema] = append(dbTables[schema], &TableInfo{table, avgRowLength, tableType})
return nil
}, query); err != nil {
return nil, errors.Annotatef(err, "sql: %s", query)
}
}
default:
const queryTemplate = "SHOW TABLE STATUS FROM `%s`"
selectedTableType := make(map[TableType]struct{})
for _, tableType = range tableTypes {
selectedTableType[tableType] = struct{}{}
}
for _, schema = range databaseNames {
dbTables[schema] = make([]*TableInfo, 0)
query := fmt.Sprintf(queryTemplate, escapeString(schema))
rows, err := db.QueryContext(tctx, query)
if err != nil {
return nil, errors.Annotatef(err, "sql: %s", query)
}
results, err := GetSpecifiedColumnValuesAndClose(rows, "NAME", "ENGINE", "AVG_ROW_LENGTH", "COMMENT")
if err != nil {
return nil, errors.Annotatef(err, "sql: %s", query)
}
for _, oneRow := range results {
table, engine, avgRowLengthStr, comment := oneRow[0], oneRow[1], oneRow[2], oneRow[3]
if avgRowLengthStr != "" {
avgRowLength, err = strconv.ParseUint(avgRowLengthStr, 10, 64)
if err != nil {
return nil, errors.Annotatef(err, "sql: %s", query)
}
} else {
avgRowLength = 0
}
tableType = TableTypeBase
if engine == "" && (comment == "" || comment == TableTypeViewStr) {
tableType = TableTypeView
} else if engine == "" {
tctx.L().Warn("invalid table without engine found", zap.String("database", schema), zap.String("table", table))
continue
}
if _, ok := selectedTableType[tableType]; !ok {
continue
}
dbTables[schema] = append(dbTables[schema], &TableInfo{table, avgRowLength, tableType})
}
}
}
return dbTables, nil
}
func ListAllPlacementPolicyNames(tctx *tcontext.Context, db *BaseConn) ([]string, error) {
var policyList []string
var policy string
const query = "select distinct policy_name from information_schema.placement_policies where policy_name is not null;"
err := db.QuerySQL(tctx, func(rows *sql.Rows) error {
err := rows.Scan(&policy)
if err != nil {
return errors.Trace(err)
}
policyList = append(policyList, policy)
return nil
}, func() {
policyList = policyList[:0]
}, query)
return policyList, errors.Annotatef(err, "sql: %s", query)
}
// SelectVersion gets the version information from the database server
func SelectVersion(db *sql.DB) (string, error) {
var versionInfo string
const query = "SELECT version()"
row := db.QueryRow(query)
err := row.Scan(&versionInfo)
if err != nil {
return "", errors.Annotatef(err, "sql: %s", query)
}
return versionInfo, nil
}
// SelectAllFromTable dumps data serialized from a specified table
func SelectAllFromTable(conf *Config, meta TableMeta, partition, orderByClause string) TableDataIR {
database, table := meta.DatabaseName(), meta.TableName()
selectedField, selectLen := meta.SelectedField(), meta.SelectedLen()
query := buildSelectQuery(database, table, selectedField, partition, buildWhereCondition(conf, ""), orderByClause)
return &tableData{
query: query,
colLen: selectLen,
}
}
func buildSelectQuery(database, table, fields, partition, where, orderByClause string) string {
var query strings.Builder
query.WriteString("SELECT ")
if fields == "" {
// If all of the columns are generated,
// we need to make sure the query is valid.
fields = "''"
}
query.WriteString(fields)
query.WriteString(" FROM `")
query.WriteString(escapeString(database))
query.WriteString("`.`")
query.WriteString(escapeString(table))
query.WriteByte('`')
if partition != "" {
query.WriteString(" PARTITION(`")
query.WriteString(escapeString(partition))
query.WriteString("`)")
}
if where != "" {
query.WriteString(" ")
query.WriteString(where)
}
if orderByClause != "" {
query.WriteString(" ")
query.WriteString(orderByClause)
}
return query.String()
}
func buildOrderByClause(tctx *tcontext.Context, conf *Config, db *BaseConn, database, table string, hasImplicitRowID bool) (string, error) { // revive:disable-line:flag-parameter
if !conf.SortByPk {
return "", nil
}
if hasImplicitRowID {
return orderByTiDBRowID, nil
}
cols, err := GetPrimaryKeyColumns(tctx, db, database, table)
if err != nil {
return "", errors.Trace(err)
}
return buildOrderByClauseString(cols), nil
}
// SelectTiDBRowID checks whether this table has _tidb_rowid column
func SelectTiDBRowID(tctx *tcontext.Context, db *BaseConn, database, table string) (bool, error) {
tiDBRowIDQuery := fmt.Sprintf("SELECT _tidb_rowid from `%s`.`%s` LIMIT 1", escapeString(database), escapeString(table))
hasImplictRowID := false
err := db.ExecSQL(tctx, func(_ sql.Result, err error) error {
if err != nil {
hasImplictRowID = false
errMsg := strings.ToLower(err.Error())
if strings.Contains(errMsg, fmt.Sprintf("%d", errno.ErrBadField)) {
return nil
}
return errors.Annotatef(err, "sql: %s", tiDBRowIDQuery)
}
hasImplictRowID = true
return nil
}, tiDBRowIDQuery)
return hasImplictRowID, err
}
// GetSuitableRows gets suitable rows for each table
func GetSuitableRows(avgRowLength uint64) uint64 {
const (
defaultRows = 200000
maxRows = 1000000
bytesPerFile = 128 * 1024 * 1024 // 128MB per file by default
)
if avgRowLength == 0 {
return defaultRows
}
estimateRows := bytesPerFile / avgRowLength
if estimateRows > maxRows {
return maxRows
}
return estimateRows
}
// GetColumnTypes gets *sql.ColumnTypes from a specified table
func GetColumnTypes(tctx *tcontext.Context, db *BaseConn, fields, database, table string) ([]*sql.ColumnType, error) {
query := fmt.Sprintf("SELECT %s FROM `%s`.`%s` LIMIT 1", fields, escapeString(database), escapeString(table))
var colTypes []*sql.ColumnType
err := db.QuerySQL(tctx, func(rows *sql.Rows) error {
var err error
colTypes, err = rows.ColumnTypes()
if err == nil {
err = rows.Close()
}
failpoint.Inject("ChaosBrokenMetaConn", func(_ failpoint.Value) {
failpoint.Return(errors.New("connection is closed"))
})
return errors.Annotatef(err, "sql: %s", query)
}, func() {
colTypes = nil
}, query)
if err != nil {
return nil, err
}
return colTypes, nil
}
// GetPrimaryKeyAndColumnTypes gets all primary columns and their types in ordinal order
func GetPrimaryKeyAndColumnTypes(tctx *tcontext.Context, conn *BaseConn, meta TableMeta) ([]string, []string, error) {
var (
colNames, colTypes []string
err error
)
colNames, err = GetPrimaryKeyColumns(tctx, conn, meta.DatabaseName(), meta.TableName())
if err != nil {
return nil, nil, err
}
colName2Type := string2Map(meta.ColumnNames(), meta.ColumnTypes())
colTypes = make([]string, len(colNames))
for i, colName := range colNames {
colTypes[i] = colName2Type[colName]
}
return colNames, colTypes, nil
}
// GetPrimaryKeyColumns gets all primary columns in ordinal order
func GetPrimaryKeyColumns(tctx *tcontext.Context, db *BaseConn, database, table string) ([]string, error) {
priKeyColsQuery := fmt.Sprintf("SHOW INDEX FROM `%s`.`%s`", escapeString(database), escapeString(table))
results, err := db.QuerySQLWithColumns(tctx, []string{"KEY_NAME", "COLUMN_NAME"}, priKeyColsQuery)
if err != nil {
return nil, err
}
cols := make([]string, 0, len(results))
for _, oneRow := range results {
keyName, columnName := oneRow[0], oneRow[1]
if keyName == "PRIMARY" {
cols = append(cols, columnName)
}
}
return cols, nil
}
// getNumericIndex picks up indices according to the following priority:
// primary key > unique key with the smallest count > key with the max cardinality
// primary key with multi cols is before unique key with single col because we will sort result by primary keys
func getNumericIndex(tctx *tcontext.Context, db *BaseConn, meta TableMeta) (string, error) {
database, table := meta.DatabaseName(), meta.TableName()
colName2Type := string2Map(meta.ColumnNames(), meta.ColumnTypes())
keyQuery := fmt.Sprintf("SHOW INDEX FROM `%s`.`%s`", escapeString(database), escapeString(table))
results, err := db.QuerySQLWithColumns(tctx, []string{"NON_UNIQUE", "SEQ_IN_INDEX", "KEY_NAME", "COLUMN_NAME", "CARDINALITY"}, keyQuery)
if err != nil {
return "", err
}
type keyColumnPair struct {
colName string
count uint64
}
var (
uniqueKeyMap = map[string]keyColumnPair{} // unique key name -> key column name, unique key columns count
keyColumn string
maxCardinality int64 = -1
)
// check primary key first, then unique key
for _, oneRow := range results {
nonUnique, seqInIndex, keyName, colName, cardinality := oneRow[0], oneRow[1], oneRow[2], oneRow[3], oneRow[4]
// only try pick the first column, because the second column of pk/uk in where condition will trigger a full table scan
if seqInIndex != "1" {
if pair, ok := uniqueKeyMap[keyName]; ok {
seqInIndexInt, err := strconv.ParseUint(seqInIndex, 10, 64)
if err == nil && seqInIndexInt > pair.count {
uniqueKeyMap[keyName] = keyColumnPair{pair.colName, seqInIndexInt}
}
}
continue
}
_, numberColumn := dataTypeInt[colName2Type[colName]]
if numberColumn {
switch {
case keyName == "PRIMARY":
return colName, nil
case nonUnique == "0":
uniqueKeyMap[keyName] = keyColumnPair{colName, 1}
// pick index column with max cardinality when there is no unique index
case len(uniqueKeyMap) == 0:
cardinalityInt, err := strconv.ParseInt(cardinality, 10, 64)
if err == nil && cardinalityInt > maxCardinality {
keyColumn = colName
maxCardinality = cardinalityInt
}
}
}
}
if len(uniqueKeyMap) > 0 {
var (
minCols uint64 = math.MaxUint64
uniqueKeyColumn string
)
for _, pair := range uniqueKeyMap {
if pair.count < minCols {
uniqueKeyColumn = pair.colName
minCols = pair.count
}
}
return uniqueKeyColumn, nil
}
return keyColumn, nil
}
// FlushTableWithReadLock flush tables with read lock
func FlushTableWithReadLock(ctx context.Context, db *sql.Conn) error {
const ftwrlQuery = "FLUSH TABLES WITH READ LOCK"
_, err := db.ExecContext(ctx, ftwrlQuery)
return errors.Annotatef(err, "sql: %s", ftwrlQuery)
}
// LockTables locks table with read lock
func LockTables(ctx context.Context, db *sql.Conn, database, table string) error {
lockTableQuery := fmt.Sprintf("LOCK TABLES `%s`.`%s` READ", escapeString(database), escapeString(table))
_, err := db.ExecContext(ctx, lockTableQuery)
return errors.Annotatef(err, "sql: %s", lockTableQuery)
}
// UnlockTables unlocks all tables' lock
func UnlockTables(ctx context.Context, db *sql.Conn) error {
const unlockTableQuery = "UNLOCK TABLES"
_, err := db.ExecContext(ctx, unlockTableQuery)
return errors.Annotatef(err, "sql: %s", unlockTableQuery)
}
// ShowMasterStatus get SHOW MASTER STATUS result from database
func ShowMasterStatus(db *sql.Conn) ([]string, error) {
var oneRow []string
handleOneRow := func(rows *sql.Rows) error {
cols, err := rows.Columns()
if err != nil {
return errors.Trace(err)
}
fieldNum := len(cols)
oneRow = make([]string, fieldNum)
addr := make([]interface{}, fieldNum)
for i := range oneRow {
addr[i] = &oneRow[i]
}
return rows.Scan(addr...)
}
const showMasterStatusQuery = "SHOW MASTER STATUS"
err := simpleQuery(db, showMasterStatusQuery, handleOneRow)
if err != nil {
return nil, errors.Annotatef(err, "sql: %s", showMasterStatusQuery)
}
return oneRow, nil
}
// GetSpecifiedColumnValueAndClose get columns' values whose name is equal to columnName and close the given rows
func GetSpecifiedColumnValueAndClose(rows *sql.Rows, columnName string) ([]string, error) {
if rows == nil {
return []string{}, nil
}
defer rows.Close()
columnName = strings.ToUpper(columnName)
var strs []string
columns, _ := rows.Columns()
addr := make([]interface{}, len(columns))
oneRow := make([]sql.NullString, len(columns))
fieldIndex := -1
for i, col := range columns {
if strings.ToUpper(col) == columnName {
fieldIndex = i
}
addr[i] = &oneRow[i]
}
if fieldIndex == -1 {
return strs, nil
}
for rows.Next() {
err := rows.Scan(addr...)
if err != nil {
return strs, errors.Trace(err)
}
if oneRow[fieldIndex].Valid {
strs = append(strs, oneRow[fieldIndex].String)
}
}
return strs, errors.Trace(rows.Err())
}
// GetSpecifiedColumnValuesAndClose get columns' values whose name is equal to columnName
func GetSpecifiedColumnValuesAndClose(rows *sql.Rows, columnName ...string) ([][]string, error) {
if rows == nil {
return [][]string{}, nil
}
defer rows.Close()
var strs [][]string
columns, err := rows.Columns()
if err != nil {
return strs, errors.Trace(err)
}
addr := make([]interface{}, len(columns))
oneRow := make([]sql.NullString, len(columns))
fieldIndexMp := make(map[int]int)
for i, col := range columns {
addr[i] = &oneRow[i]
for j, name := range columnName {
if strings.ToUpper(col) == name {
fieldIndexMp[i] = j
}
}
}
if len(fieldIndexMp) == 0 {
return strs, nil
}
for rows.Next() {
err := rows.Scan(addr...)
if err != nil {
return strs, errors.Trace(err)
}
written := false
tmpStr := make([]string, len(columnName))
for colPos, namePos := range fieldIndexMp {
if oneRow[colPos].Valid {
written = true
tmpStr[namePos] = oneRow[colPos].String
}
}
if written {
strs = append(strs, tmpStr)
}
}
return strs, errors.Trace(rows.Err())
}
// GetPdAddrs gets PD address from TiDB
func GetPdAddrs(tctx *tcontext.Context, db *sql.DB) ([]string, error) {
const query = "SELECT * FROM information_schema.cluster_info where type = 'pd';"
rows, err := db.QueryContext(tctx, query)
if err != nil {
return []string{}, errors.Annotatef(err, "sql: %s", query)
}
pdAddrs, err := GetSpecifiedColumnValueAndClose(rows, "STATUS_ADDRESS")
return pdAddrs, errors.Annotatef(err, "sql: %s", query)
}
// GetTiDBDDLIDs gets DDL IDs from TiDB
func GetTiDBDDLIDs(tctx *tcontext.Context, db *sql.DB) ([]string, error) {
const query = "SELECT * FROM information_schema.tidb_servers_info;"
rows, err := db.QueryContext(tctx, query)
if err != nil {
return []string{}, errors.Annotatef(err, "sql: %s", query)
}
ddlIDs, err := GetSpecifiedColumnValueAndClose(rows, "DDL_ID")
return ddlIDs, errors.Annotatef(err, "sql: %s", query)
}
// getTiDBConfig gets tidb config from TiDB server
// @@tidb_config details doc https://docs.pingcap.com/tidb/stable/system-variables#tidb_config
// this variable exists at least from v2.0.0, so this works in most existing tidb instances
func getTiDBConfig(db *sql.Conn) (dbconfig.Config, error) {
const query = "SELECT @@tidb_config;"
var (
tidbConfig dbconfig.Config
tidbConfigBytes []byte
)
row := db.QueryRowContext(context.Background(), query)
err := row.Scan(&tidbConfigBytes)
if err != nil {
return tidbConfig, errors.Annotatef(err, "sql: %s", query)
}
err = json.Unmarshal(tidbConfigBytes, &tidbConfig)
return tidbConfig, errors.Annotatef(err, "sql: %s", query)
}
// CheckTiDBWithTiKV use sql to check whether current TiDB has TiKV
func CheckTiDBWithTiKV(db *sql.DB) (bool, error) {
conn, err := db.Conn(context.Background())
if err == nil {
defer conn.Close()
tidbConfig, err := getTiDBConfig(conn)
if err == nil {
return tidbConfig.Store == "tikv", nil
}
}
var count int
const query = "SELECT COUNT(1) as c FROM MYSQL.TiDB WHERE VARIABLE_NAME='tikv_gc_safe_point'"
row := db.QueryRow(query)
err = row.Scan(&count)
if err != nil {
// still return true here. Because sometimes users may not have privileges for MySQL.TiDB database
// In most production cases TiDB has TiKV
return true, errors.Annotatef(err, "sql: %s", query)
}
return count > 0, nil
}
// CheckIfSeqExists use sql to check whether sequence exists
func CheckIfSeqExists(db *sql.Conn) (bool, error) {
var count int
const query = "SELECT COUNT(1) as c FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='SEQUENCE'"
row := db.QueryRowContext(context.Background(), query)
err := row.Scan(&count)
if err != nil {
return false, errors.Annotatef(err, "sql: %s", query)
}
return count > 0, nil
}
// CheckTiDBEnableTableLock use sql variable to check whether current TiDB has TiKV
func CheckTiDBEnableTableLock(db *sql.Conn) (bool, error) {
tidbConfig, err := getTiDBConfig(db)
if err != nil {
return false, err
}
return tidbConfig.EnableTableLock, nil
}
func getSnapshot(db *sql.Conn) (string, error) {
str, err := ShowMasterStatus(db)
if err != nil {
return "", err
}
return str[snapshotFieldIndex], nil
}
func isUnknownSystemVariableErr(err error) bool {
return strings.Contains(err.Error(), "Unknown system variable")
}
// resetDBWithSessionParams will return a new sql.DB as a replacement for input `db` with new session parameters.
// If returned error is nil, the input `db` will be closed.
func resetDBWithSessionParams(tctx *tcontext.Context, db *sql.DB, dsn string, params map[string]interface{}) (*sql.DB, error) {
support := make(map[string]interface{})
for k, v := range params {
var pv interface{}
if str, ok := v.(string); ok {
if pvi, err := strconv.ParseInt(str, 10, 64); err == nil {
pv = pvi
} else if pvf, err := strconv.ParseFloat(str, 64); err == nil {
pv = pvf
} else {
pv = str
}
} else {
pv = v
}
s := fmt.Sprintf("SET SESSION %s = ?", k)
_, err := db.ExecContext(tctx, s, pv)
if err != nil {
if isUnknownSystemVariableErr(err) {
tctx.L().Info("session variable is not supported by db", zap.String("variable", k), zap.Reflect("value", v))
continue
}
return nil, errors.Trace(err)
}
support[k] = pv
}
for k, v := range support {
var s string
// Wrap string with quote to handle string with space. For example, '2020-10-20 13:41:40'
// For --params argument, quote doesn't matter because it doesn't affect the actual value
if str, ok := v.(string); ok {
s = wrapStringWith(str, "'")
} else {
s = fmt.Sprintf("%v", v)
}
dsn += fmt.Sprintf("&%s=%s", k, url.QueryEscape(s))
}
db.Close()
newDB, err := sql.Open("mysql", dsn)
if err == nil {
// ping to make sure all session parameters are set correctly
err = newDB.PingContext(tctx)
if err != nil {
newDB.Close()
}
}
return newDB, errors.Trace(err)
}
func createConnWithConsistency(ctx context.Context, db *sql.DB, repeatableRead bool) (*sql.Conn, error) {
conn, err := db.Conn(ctx)
if err != nil {
return nil, errors.Trace(err)
}
var query string
if repeatableRead {
query = "SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ"
_, err = conn.ExecContext(ctx, query)
if err != nil {
return nil, errors.Annotatef(err, "sql: %s", query)
}
}
query = "START TRANSACTION /*!40108 WITH CONSISTENT SNAPSHOT */"
_, err = conn.ExecContext(ctx, query)
if err != nil {
// Some MySQL Compatible databases like Vitess and MemSQL/SingleStore
// are newer than 4.1.8 (the version comment) but don't actually support
// `WITH CONSISTENT SNAPSHOT`. So retry without that if the statement fails.
query = "START TRANSACTION"
_, err = conn.ExecContext(ctx, query)
if err != nil {
return nil, errors.Annotatef(err, "sql: %s", query)
}
}
return conn, nil
}
// buildSelectField returns the selecting fields' string(joined by comma(`,`)),
// and the number of writable fields.
func buildSelectField(tctx *tcontext.Context, db *BaseConn, dbName, tableName string, completeInsert bool) (string, int, error) { // revive:disable-line:flag-parameter
query := fmt.Sprintf("SHOW COLUMNS FROM `%s`.`%s`", escapeString(dbName), escapeString(tableName))
results, err := db.QuerySQLWithColumns(tctx, []string{"FIELD", "EXTRA"}, query)
if err != nil {
return "", 0, err
}
availableFields := make([]string, 0)
hasGenerateColumn := false
for _, oneRow := range results {
fieldName, extra := oneRow[0], oneRow[1]
switch extra {
case "STORED GENERATED", "VIRTUAL GENERATED":
hasGenerateColumn = true
continue
}
availableFields = append(availableFields, wrapBackTicks(escapeString(fieldName)))
}
if completeInsert || hasGenerateColumn {
return strings.Join(availableFields, ","), len(availableFields), nil
}
return "*", len(availableFields), nil
}
func buildWhereClauses(handleColNames []string, handleVals [][]string) []string {
if len(handleColNames) == 0 || len(handleVals) == 0 {
return nil
}
quotaCols := make([]string, len(handleColNames))
for i, s := range handleColNames {
quotaCols[i] = fmt.Sprintf("`%s`", escapeString(s))
}
where := make([]string, 0, len(handleVals)+1)
buf := &bytes.Buffer{}
buildCompareClause(buf, quotaCols, handleVals[0], less, false)
where = append(where, buf.String())
buf.Reset()
for i := 1; i < len(handleVals); i++ {
low, up := handleVals[i-1], handleVals[i]
buildBetweenClause(buf, quotaCols, low, up)
where = append(where, buf.String())
buf.Reset()
}
buildCompareClause(buf, quotaCols, handleVals[len(handleVals)-1], greater, true)
where = append(where, buf.String())
buf.Reset()
return where
}
// return greater than TableRangeScan where clause
// the result doesn't contain brackets
const (
greater = '>'
less = '<'
equal = '='
)
// buildCompareClause build clause with specified bounds. Usually we will use the following two conditions:
// (compare, writeEqual) == (less, false), return quotaCols < bound clause. In other words, (-inf, bound)
// (compare, writeEqual) == (greater, true), return quotaCols >= bound clause. In other words, [bound, +inf)
func buildCompareClause(buf *bytes.Buffer, quotaCols []string, bound []string, compare byte, writeEqual bool) { // revive:disable-line:flag-parameter
for i, col := range quotaCols {
if i > 0 {
buf.WriteString("or(")
}
for j := 0; j < i; j++ {
buf.WriteString(quotaCols[j])
buf.WriteByte(equal)
buf.WriteString(bound[j])
buf.WriteString(" and ")
}
buf.WriteString(col)
buf.WriteByte(compare)
if writeEqual && i == len(quotaCols)-1 {
buf.WriteByte(equal)
}
buf.WriteString(bound[i])
if i > 0 {
buf.WriteByte(')')
} else if i != len(quotaCols)-1 {
buf.WriteByte(' ')
}
}
}