-
Notifications
You must be signed in to change notification settings - Fork 5.8k
/
infoschema_reader.go
3912 lines (3689 loc) · 124 KB
/
infoschema_reader.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 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 executor
import (
"bytes"
"context"
"encoding/hex"
"encoding/json"
"fmt"
"math"
"slices"
"strconv"
"strings"
"time"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
"github.com/pingcap/kvproto/pkg/deadlock"
"github.com/pingcap/kvproto/pkg/kvrpcpb"
rmpb "github.com/pingcap/kvproto/pkg/resource_manager"
"github.com/pingcap/tidb/pkg/ddl/label"
"github.com/pingcap/tidb/pkg/ddl/placement"
"github.com/pingcap/tidb/pkg/domain"
"github.com/pingcap/tidb/pkg/domain/infosync"
"github.com/pingcap/tidb/pkg/errno"
"github.com/pingcap/tidb/pkg/executor/internal/exec"
"github.com/pingcap/tidb/pkg/executor/internal/pdhelper"
"github.com/pingcap/tidb/pkg/expression"
"github.com/pingcap/tidb/pkg/infoschema"
"github.com/pingcap/tidb/pkg/keyspace"
"github.com/pingcap/tidb/pkg/kv"
"github.com/pingcap/tidb/pkg/meta/autoid"
"github.com/pingcap/tidb/pkg/meta/model"
"github.com/pingcap/tidb/pkg/parser"
"github.com/pingcap/tidb/pkg/parser/charset"
pmodel "github.com/pingcap/tidb/pkg/parser/model"
"github.com/pingcap/tidb/pkg/parser/mysql"
plannercore "github.com/pingcap/tidb/pkg/planner/core"
"github.com/pingcap/tidb/pkg/planner/core/base"
"github.com/pingcap/tidb/pkg/privilege"
"github.com/pingcap/tidb/pkg/privilege/privileges"
"github.com/pingcap/tidb/pkg/resourcegroup/runaway"
"github.com/pingcap/tidb/pkg/session/txninfo"
"github.com/pingcap/tidb/pkg/sessionctx"
"github.com/pingcap/tidb/pkg/sessionctx/variable"
"github.com/pingcap/tidb/pkg/sessiontxn"
"github.com/pingcap/tidb/pkg/statistics"
"github.com/pingcap/tidb/pkg/statistics/handle/cache"
"github.com/pingcap/tidb/pkg/store/helper"
"github.com/pingcap/tidb/pkg/table"
"github.com/pingcap/tidb/pkg/tablecodec"
"github.com/pingcap/tidb/pkg/types"
"github.com/pingcap/tidb/pkg/util"
"github.com/pingcap/tidb/pkg/util/chunk"
"github.com/pingcap/tidb/pkg/util/codec"
"github.com/pingcap/tidb/pkg/util/collate"
"github.com/pingcap/tidb/pkg/util/dbterror/plannererrors"
"github.com/pingcap/tidb/pkg/util/deadlockhistory"
"github.com/pingcap/tidb/pkg/util/execdetails"
"github.com/pingcap/tidb/pkg/util/hint"
"github.com/pingcap/tidb/pkg/util/intest"
"github.com/pingcap/tidb/pkg/util/keydecoder"
"github.com/pingcap/tidb/pkg/util/logutil"
"github.com/pingcap/tidb/pkg/util/memory"
"github.com/pingcap/tidb/pkg/util/resourcegrouptag"
"github.com/pingcap/tidb/pkg/util/sem"
"github.com/pingcap/tidb/pkg/util/servermemorylimit"
"github.com/pingcap/tidb/pkg/util/set"
"github.com/pingcap/tidb/pkg/util/stringutil"
"github.com/pingcap/tidb/pkg/util/syncutil"
"github.com/tikv/client-go/v2/tikv"
"github.com/tikv/client-go/v2/tikvrpc"
"github.com/tikv/client-go/v2/txnkv/txnlock"
pd "github.com/tikv/pd/client/http"
"go.uber.org/zap"
)
var lowerPrimaryKeyName = strings.ToLower(mysql.PrimaryKeyName)
type memtableRetriever struct {
dummyCloser
table *model.TableInfo
columns []*model.ColumnInfo
rows [][]types.Datum
rowIdx int
retrieved bool
initialized bool
extractor base.MemTablePredicateExtractor
is infoschema.InfoSchema
memTracker *memory.Tracker
}
// retrieve implements the infoschemaRetriever interface
func (e *memtableRetriever) retrieve(ctx context.Context, sctx sessionctx.Context) ([][]types.Datum, error) {
if e.table.Name.O == infoschema.TableClusterInfo && !hasPriv(sctx, mysql.ProcessPriv) {
return nil, plannererrors.ErrSpecificAccessDenied.GenWithStackByArgs("PROCESS")
}
if e.retrieved {
return nil, nil
}
// Cache the ret full rows in schemataRetriever
if !e.initialized {
is := sctx.GetInfoSchema().(infoschema.InfoSchema)
e.is = is
var err error
switch e.table.Name.O {
case infoschema.TableSchemata:
err = e.setDataFromSchemata(sctx)
case infoschema.TableStatistics:
err = e.setDataForStatistics(ctx, sctx)
case infoschema.TableTables:
err = e.setDataFromTables(ctx, sctx)
case infoschema.TableReferConst:
err = e.setDataFromReferConst(ctx, sctx)
case infoschema.TableSequences:
err = e.setDataFromSequences(ctx, sctx)
case infoschema.TablePartitions:
err = e.setDataFromPartitions(ctx, sctx)
case infoschema.TableClusterInfo:
err = e.dataForTiDBClusterInfo(sctx)
case infoschema.TableAnalyzeStatus:
err = e.setDataForAnalyzeStatus(ctx, sctx)
case infoschema.TableTiDBIndexes:
err = e.setDataFromIndexes(ctx, sctx)
case infoschema.TableViews:
err = e.setDataFromViews(ctx, sctx)
case infoschema.TableEngines:
e.setDataFromEngines()
case infoschema.TableCharacterSets:
e.setDataFromCharacterSets()
case infoschema.TableCollations:
e.setDataFromCollations()
case infoschema.TableKeyColumn:
err = e.setDataFromKeyColumnUsage(ctx, sctx)
case infoschema.TableMetricTables:
e.setDataForMetricTables()
case infoschema.TableProfiling:
e.setDataForPseudoProfiling(sctx)
case infoschema.TableCollationCharacterSetApplicability:
e.dataForCollationCharacterSetApplicability()
case infoschema.TableProcesslist:
e.setDataForProcessList(sctx)
case infoschema.ClusterTableProcesslist:
err = e.setDataForClusterProcessList(sctx)
case infoschema.TableUserPrivileges:
e.setDataFromUserPrivileges(sctx)
case infoschema.TableTiKVRegionStatus:
err = e.setDataForTiKVRegionStatus(ctx, sctx)
case infoschema.TableTiDBHotRegions:
err = e.setDataForTiDBHotRegions(ctx, sctx)
case infoschema.TableConstraints:
err = e.setDataFromTableConstraints(ctx, sctx)
case infoschema.TableSessionVar:
e.rows, err = infoschema.GetDataFromSessionVariables(ctx, sctx)
case infoschema.TableTiDBServersInfo:
err = e.setDataForServersInfo(sctx)
case infoschema.TableTiFlashReplica:
err = e.dataForTableTiFlashReplica(ctx, sctx)
case infoschema.TableTiKVStoreStatus:
err = e.dataForTiKVStoreStatus(ctx, sctx)
case infoschema.TableClientErrorsSummaryGlobal,
infoschema.TableClientErrorsSummaryByUser,
infoschema.TableClientErrorsSummaryByHost:
err = e.setDataForClientErrorsSummary(sctx, e.table.Name.O)
case infoschema.TableAttributes:
err = e.setDataForAttributes(ctx, sctx, is)
case infoschema.TablePlacementPolicies:
err = e.setDataFromPlacementPolicies(sctx)
case infoschema.TableTrxSummary:
err = e.setDataForTrxSummary(sctx)
case infoschema.ClusterTableTrxSummary:
err = e.setDataForClusterTrxSummary(sctx)
case infoschema.TableVariablesInfo:
err = e.setDataForVariablesInfo(sctx)
case infoschema.TableUserAttributes:
err = e.setDataForUserAttributes(ctx, sctx)
case infoschema.TableMemoryUsage:
err = e.setDataForMemoryUsage()
case infoschema.ClusterTableMemoryUsage:
err = e.setDataForClusterMemoryUsage(sctx)
case infoschema.TableMemoryUsageOpsHistory:
err = e.setDataForMemoryUsageOpsHistory()
case infoschema.ClusterTableMemoryUsageOpsHistory:
err = e.setDataForClusterMemoryUsageOpsHistory(sctx)
case infoschema.TableResourceGroups:
err = e.setDataFromResourceGroups()
case infoschema.TableRunawayWatches:
err = e.setDataFromRunawayWatches(sctx)
case infoschema.TableCheckConstraints:
err = e.setDataFromCheckConstraints(ctx, sctx)
case infoschema.TableTiDBCheckConstraints:
err = e.setDataFromTiDBCheckConstraints(ctx, sctx)
case infoschema.TableKeywords:
err = e.setDataFromKeywords()
case infoschema.TableTiDBIndexUsage:
err = e.setDataFromIndexUsage(ctx, sctx)
case infoschema.ClusterTableTiDBIndexUsage:
err = e.setDataFromClusterIndexUsage(ctx, sctx)
}
if err != nil {
return nil, err
}
e.initialized = true
if e.memTracker != nil {
e.memTracker.Consume(calculateDatumsSize(e.rows))
}
}
// Adjust the amount of each return
maxCount := 1024
retCount := maxCount
if e.rowIdx+maxCount > len(e.rows) {
retCount = len(e.rows) - e.rowIdx
e.retrieved = true
}
ret := make([][]types.Datum, retCount)
for i := e.rowIdx; i < e.rowIdx+retCount; i++ {
ret[i-e.rowIdx] = e.rows[i]
}
e.rowIdx += retCount
return adjustColumns(ret, e.columns, e.table), nil
}
func getAutoIncrementID(
is infoschema.InfoSchema,
sctx sessionctx.Context,
tblInfo *model.TableInfo,
) int64 {
tbl, ok := is.TableByID(context.Background(), tblInfo.ID)
if !ok {
return 0
}
return tbl.Allocators(sctx.GetTableCtx()).Get(autoid.AutoIncrementType).Base() + 1
}
func hasPriv(ctx sessionctx.Context, priv mysql.PrivilegeType) bool {
pm := privilege.GetPrivilegeManager(ctx)
if pm == nil {
// internal session created with createSession doesn't has the PrivilegeManager. For most experienced cases before,
// we use it like this:
// ```
// checker := privilege.GetPrivilegeManager(ctx)
// if checker != nil && !checker.RequestVerification(ctx.GetSessionVars().ActiveRoles, schema.Name.L, table.Name.L, "", mysql.AllPrivMask) {
// continue
// }
// do something.
// ```
// So once the privilege manager is nil, it's a signature of internal sql, so just passing the checker through.
return true
}
return pm.RequestVerification(ctx.GetSessionVars().ActiveRoles, "", "", "", priv)
}
func (e *memtableRetriever) setDataForVariablesInfo(ctx sessionctx.Context) error {
sysVars := variable.GetSysVars()
rows := make([][]types.Datum, 0, len(sysVars))
for _, sv := range sysVars {
if infoschema.SysVarHiddenForSem(ctx, sv.Name) {
continue
}
currentVal, err := ctx.GetSessionVars().GetSessionOrGlobalSystemVar(context.Background(), sv.Name)
if err != nil {
currentVal = ""
}
isNoop := "NO"
if sv.IsNoop {
isNoop = "YES"
}
defVal := sv.Value
if sv.HasGlobalScope() {
defVal = variable.GlobalSystemVariableInitialValue(sv.Name, defVal)
}
row := types.MakeDatums(
sv.Name, // VARIABLE_NAME
sv.Scope.String(), // VARIABLE_SCOPE
defVal, // DEFAULT_VALUE
currentVal, // CURRENT_VALUE
sv.MinValue, // MIN_VALUE
sv.MaxValue, // MAX_VALUE
nil, // POSSIBLE_VALUES
isNoop, // IS_NOOP
)
// min and max value is only supported for numeric types
if !(sv.Type == variable.TypeUnsigned || sv.Type == variable.TypeInt || sv.Type == variable.TypeFloat) {
row[4].SetNull()
row[5].SetNull()
}
if sv.Type == variable.TypeEnum {
possibleValues := strings.Join(sv.PossibleValues, ",")
row[6].SetString(possibleValues, mysql.DefaultCollationName)
}
rows = append(rows, row)
}
e.rows = rows
return nil
}
func (e *memtableRetriever) setDataForUserAttributes(ctx context.Context, sctx sessionctx.Context) error {
exec := sctx.GetRestrictedSQLExecutor()
chunkRows, _, err := exec.ExecRestrictedSQL(ctx, nil, `SELECT user, host, JSON_UNQUOTE(JSON_EXTRACT(user_attributes, '$.metadata')) FROM mysql.user`)
if err != nil {
return err
}
if len(chunkRows) == 0 {
return nil
}
rows := make([][]types.Datum, 0, len(chunkRows))
for _, chunkRow := range chunkRows {
if chunkRow.Len() != 3 {
continue
}
user := chunkRow.GetString(0)
host := chunkRow.GetString(1)
// Compatible with results in MySQL
var attribute any
if attribute = chunkRow.GetString(2); attribute == "" {
attribute = nil
}
row := types.MakeDatums(user, host, attribute)
rows = append(rows, row)
}
e.rows = rows
return nil
}
func (e *memtableRetriever) setDataFromSchemata(ctx sessionctx.Context) error {
checker := privilege.GetPrivilegeManager(ctx)
ex, ok := e.extractor.(*plannercore.InfoSchemaSchemataExtractor)
if !ok {
return errors.Errorf("wrong extractor type: %T, expected InfoSchemaSchemataExtractor", e.extractor)
}
if ex.SkipRequest {
return nil
}
schemas := ex.ListSchemas(e.is)
rows := make([][]types.Datum, 0, len(schemas))
for _, schemaName := range schemas {
schema, _ := e.is.SchemaByName(schemaName)
charset := mysql.DefaultCharset
collation := mysql.DefaultCollationName
if len(schema.Charset) > 0 {
charset = schema.Charset // Overwrite default
}
if len(schema.Collate) > 0 {
collation = schema.Collate // Overwrite default
}
var policyName any
if schema.PlacementPolicyRef != nil {
policyName = schema.PlacementPolicyRef.Name.O
}
if checker != nil && !checker.RequestVerification(ctx.GetSessionVars().ActiveRoles, schema.Name.L, "", "", mysql.AllPrivMask) {
continue
}
record := types.MakeDatums(
infoschema.CatalogVal, // CATALOG_NAME
schema.Name.O, // SCHEMA_NAME
charset, // DEFAULT_CHARACTER_SET_NAME
collation, // DEFAULT_COLLATION_NAME
nil, // SQL_PATH
policyName, // TIDB_PLACEMENT_POLICY_NAME
)
rows = append(rows, record)
}
e.rows = rows
return nil
}
func (e *memtableRetriever) setDataForStatistics(ctx context.Context, sctx sessionctx.Context) error {
checker := privilege.GetPrivilegeManager(sctx)
ex, ok := e.extractor.(*plannercore.InfoSchemaStatisticsExtractor)
if !ok {
return errors.Errorf("wrong extractor type: %T, expected InfoSchemaStatisticsExtractor", e.extractor)
}
if ex.SkipRequest {
return nil
}
schemas, tables, err := ex.ListSchemasAndTables(ctx, e.is)
if err != nil {
return errors.Trace(err)
}
for i, table := range tables {
schema := schemas[i]
if checker != nil && !checker.RequestVerification(sctx.GetSessionVars().ActiveRoles, schema.L, table.Name.L, "", mysql.AllPrivMask) {
continue
}
e.setDataForStatisticsInTable(schema, table, ex)
}
return nil
}
func (e *memtableRetriever) setDataForStatisticsInTable(
schema pmodel.CIStr,
table *model.TableInfo,
ex *plannercore.InfoSchemaStatisticsExtractor,
) {
var rows [][]types.Datum
if table.PKIsHandle && ex.HasPrimaryKey() {
for _, col := range table.Columns {
if mysql.HasPriKeyFlag(col.GetFlag()) {
record := types.MakeDatums(
infoschema.CatalogVal, // TABLE_CATALOG
schema.O, // TABLE_SCHEMA
table.Name.O, // TABLE_NAME
"0", // NON_UNIQUE
schema.O, // INDEX_SCHEMA
"PRIMARY", // INDEX_NAME
1, // SEQ_IN_INDEX
col.Name.O, // COLUMN_NAME
"A", // COLLATION
0, // CARDINALITY
nil, // SUB_PART
nil, // PACKED
"", // NULLABLE
"BTREE", // INDEX_TYPE
"", // COMMENT
"", // INDEX_COMMENT
"YES", // IS_VISIBLE
nil, // Expression
)
rows = append(rows, record)
}
}
}
nameToCol := make(map[string]*model.ColumnInfo, len(table.Columns))
for _, c := range table.Columns {
nameToCol[c.Name.L] = c
}
for _, index := range table.Indices {
if !ex.HasIndex(index.Name.L) {
continue
}
nonUnique := "1"
if index.Unique {
nonUnique = "0"
}
for i, key := range index.Columns {
col := nameToCol[key.Name.L]
nullable := "YES"
if mysql.HasNotNullFlag(col.GetFlag()) {
nullable = ""
}
visible := "YES"
if index.Invisible {
visible = "NO"
}
colName := col.Name.O
var expression any
expression = nil
tblCol := table.Columns[col.Offset]
if tblCol.Hidden {
colName = "NULL"
expression = tblCol.GeneratedExprString
}
var subPart any
if key.Length != types.UnspecifiedLength {
subPart = key.Length
}
record := types.MakeDatums(
infoschema.CatalogVal, // TABLE_CATALOG
schema.O, // TABLE_SCHEMA
table.Name.O, // TABLE_NAME
nonUnique, // NON_UNIQUE
schema.O, // INDEX_SCHEMA
index.Name.O, // INDEX_NAME
i+1, // SEQ_IN_INDEX
colName, // COLUMN_NAME
"A", // COLLATION
0, // CARDINALITY
subPart, // SUB_PART
nil, // PACKED
nullable, // NULLABLE
"BTREE", // INDEX_TYPE
"", // COMMENT
index.Comment, // INDEX_COMMENT
visible, // IS_VISIBLE
expression, // Expression
)
rows = append(rows, record)
}
}
e.rows = append(e.rows, rows...)
}
func (e *memtableRetriever) setDataFromReferConst(ctx context.Context, sctx sessionctx.Context) error {
checker := privilege.GetPrivilegeManager(sctx)
var rows [][]types.Datum
ex, ok := e.extractor.(*plannercore.InfoSchemaReferConstExtractor)
if !ok {
return errors.Errorf("wrong extractor type: %T, expected InfoSchemaReferConstExtractor", e.extractor)
}
if ex.SkipRequest {
return nil
}
schemas, tables, err := ex.ListSchemasAndTables(ctx, e.is)
if err != nil {
return errors.Trace(err)
}
for i, table := range tables {
schema := schemas[i]
if !table.IsBaseTable() {
continue
}
if checker != nil && !checker.RequestVerification(sctx.GetSessionVars().ActiveRoles, schema.L, table.Name.L, "", mysql.AllPrivMask) {
continue
}
for _, fk := range table.ForeignKeys {
if ok && !ex.HasConstraint(fk.Name.L) {
continue
}
updateRule, deleteRule := "NO ACTION", "NO ACTION"
if pmodel.ReferOptionType(fk.OnUpdate) != 0 {
updateRule = pmodel.ReferOptionType(fk.OnUpdate).String()
}
if pmodel.ReferOptionType(fk.OnDelete) != 0 {
deleteRule = pmodel.ReferOptionType(fk.OnDelete).String()
}
record := types.MakeDatums(
infoschema.CatalogVal, // CONSTRAINT_CATALOG
schema.O, // CONSTRAINT_SCHEMA
fk.Name.O, // CONSTRAINT_NAME
infoschema.CatalogVal, // UNIQUE_CONSTRAINT_CATALOG
schema.O, // UNIQUE_CONSTRAINT_SCHEMA
"PRIMARY", // UNIQUE_CONSTRAINT_NAME
"NONE", // MATCH_OPTION
updateRule, // UPDATE_RULE
deleteRule, // DELETE_RULE
table.Name.O, // TABLE_NAME
fk.RefTable.O, // REFERENCED_TABLE_NAME
)
rows = append(rows, record)
}
}
e.rows = rows
return nil
}
func (e *memtableRetriever) updateStatsCacheIfNeed() bool {
for _, col := range e.columns {
// only the following columns need stats cache.
if col.Name.O == "AVG_ROW_LENGTH" || col.Name.O == "DATA_LENGTH" || col.Name.O == "INDEX_LENGTH" || col.Name.O == "TABLE_ROWS" {
return true
}
}
return false
}
func (e *memtableRetriever) setDataFromOneTable(
sctx sessionctx.Context,
loc *time.Location,
checker privilege.Manager,
schema pmodel.CIStr,
table *model.TableInfo,
rows [][]types.Datum,
useStatsCache bool,
) ([][]types.Datum, error) {
collation := table.Collate
if collation == "" {
collation = mysql.DefaultCollationName
}
createTime := types.NewTime(types.FromGoTime(table.GetUpdateTime().In(loc)), mysql.TypeDatetime, types.DefaultFsp)
createOptions := ""
if checker != nil && !checker.RequestVerification(sctx.GetSessionVars().ActiveRoles, schema.L, table.Name.L, "", mysql.AllPrivMask) {
return rows, nil
}
pkType := "NONCLUSTERED"
if !table.IsView() {
if table.GetPartitionInfo() != nil {
createOptions = "partitioned"
} else if table.TableCacheStatusType == model.TableCacheStatusEnable {
createOptions = "cached=on"
}
var autoIncID any
hasAutoIncID, _ := infoschema.HasAutoIncrementColumn(table)
if hasAutoIncID {
autoIncID = getAutoIncrementID(e.is, sctx, table)
}
tableType := "BASE TABLE"
if util.IsSystemView(schema.L) {
tableType = "SYSTEM VIEW"
}
if table.IsSequence() {
tableType = "SEQUENCE"
}
if table.HasClusteredIndex() {
pkType = "CLUSTERED"
}
shardingInfo := infoschema.GetShardingInfo(schema, table)
var policyName any
if table.PlacementPolicyRef != nil {
policyName = table.PlacementPolicyRef.Name.O
}
var rowCount, avgRowLength, dataLength, indexLength uint64
if useStatsCache {
if table.GetPartitionInfo() == nil {
err := cache.TableRowStatsCache.UpdateByID(sctx, table.ID)
if err != nil {
return rows, err
}
} else {
// needs to update all partitions for partition table.
for _, pi := range table.GetPartitionInfo().Definitions {
err := cache.TableRowStatsCache.UpdateByID(sctx, pi.ID)
if err != nil {
return rows, err
}
}
}
rowCount, avgRowLength, dataLength, indexLength = cache.TableRowStatsCache.EstimateDataLength(table)
}
record := types.MakeDatums(
infoschema.CatalogVal, // TABLE_CATALOG
schema.O, // TABLE_SCHEMA
table.Name.O, // TABLE_NAME
tableType, // TABLE_TYPE
"InnoDB", // ENGINE
uint64(10), // VERSION
"Compact", // ROW_FORMAT
rowCount, // TABLE_ROWS
avgRowLength, // AVG_ROW_LENGTH
dataLength, // DATA_LENGTH
uint64(0), // MAX_DATA_LENGTH
indexLength, // INDEX_LENGTH
uint64(0), // DATA_FREE
autoIncID, // AUTO_INCREMENT
createTime, // CREATE_TIME
nil, // UPDATE_TIME
nil, // CHECK_TIME
collation, // TABLE_COLLATION
nil, // CHECKSUM
createOptions, // CREATE_OPTIONS
table.Comment, // TABLE_COMMENT
table.ID, // TIDB_TABLE_ID
shardingInfo, // TIDB_ROW_ID_SHARDING_INFO
pkType, // TIDB_PK_TYPE
policyName, // TIDB_PLACEMENT_POLICY_NAME
)
rows = append(rows, record)
} else {
record := types.MakeDatums(
infoschema.CatalogVal, // TABLE_CATALOG
schema.O, // TABLE_SCHEMA
table.Name.O, // TABLE_NAME
"VIEW", // TABLE_TYPE
nil, // ENGINE
nil, // VERSION
nil, // ROW_FORMAT
nil, // TABLE_ROWS
nil, // AVG_ROW_LENGTH
nil, // DATA_LENGTH
nil, // MAX_DATA_LENGTH
nil, // INDEX_LENGTH
nil, // DATA_FREE
nil, // AUTO_INCREMENT
createTime, // CREATE_TIME
nil, // UPDATE_TIME
nil, // CHECK_TIME
nil, // TABLE_COLLATION
nil, // CHECKSUM
nil, // CREATE_OPTIONS
"VIEW", // TABLE_COMMENT
table.ID, // TIDB_TABLE_ID
nil, // TIDB_ROW_ID_SHARDING_INFO
pkType, // TIDB_PK_TYPE
nil, // TIDB_PLACEMENT_POLICY_NAME
)
rows = append(rows, record)
}
return rows, nil
}
func onlySchemaOrTableColumns(columns []*model.ColumnInfo) bool {
if len(columns) <= 3 {
for _, colInfo := range columns {
switch colInfo.Name.L {
case "table_schema":
case "table_name":
case "table_catalog":
default:
return false
}
}
return true
}
return false
}
func (e *memtableRetriever) setDataFromTables(ctx context.Context, sctx sessionctx.Context) error {
var rows [][]types.Datum
checker := privilege.GetPrivilegeManager(sctx)
ex, ok := e.extractor.(*plannercore.InfoSchemaTablesExtractor)
if !ok {
return errors.Errorf("wrong extractor type: %T, expected InfoSchemaTablesExtractor", e.extractor)
}
if ex.SkipRequest {
return nil
}
// Special optimize for queries on infoschema v2 like:
// select count(table_schema) from INFORMATION_SCHEMA.TABLES
// select count(*) from INFORMATION_SCHEMA.TABLES
// select table_schema, table_name from INFORMATION_SCHEMA.TABLES
// column pruning in general is not supported here.
if onlySchemaOrTableColumns(e.columns) {
is := e.is
if raw, ok := is.(*infoschema.SessionExtendedInfoSchema); ok {
is = raw.InfoSchema
}
v2, ok := is.(interface {
IterateAllTableItems(visit func(infoschema.TableItem) bool)
})
if ok {
if x := ctx.Value("cover-check"); x != nil {
// The interface assertion is too tricky, so we add test to cover here.
// To ensure that if implementation changes one day, we can catch it.
slot := x.(*bool)
*slot = true
}
v2.IterateAllTableItems(func(t infoschema.TableItem) bool {
if !ex.HasTableName(t.TableName.L) {
return true
}
if !ex.HasTableSchema(t.DBName.L) {
return true
}
if checker != nil && !checker.RequestVerification(sctx.GetSessionVars().ActiveRoles, t.DBName.L, t.TableName.L, "", mysql.SelectPriv) {
return true
}
record := types.MakeDatums(
infoschema.CatalogVal, // TABLE_CATALOG
t.DBName.O, // TABLE_SCHEMA
t.TableName.O, // TABLE_NAME
nil, // TABLE_TYPE
nil, // ENGINE
nil, // VERSION
nil, // ROW_FORMAT
nil, // TABLE_ROWS
nil, // AVG_ROW_LENGTH
nil, // DATA_LENGTH
nil, // MAX_DATA_LENGTH
nil, // INDEX_LENGTH
nil, // DATA_FREE
nil, // AUTO_INCREMENT
nil, // CREATE_TIME
nil, // UPDATE_TIME
nil, // CHECK_TIME
nil, // TABLE_COLLATION
nil, // CHECKSUM
nil, // CREATE_OPTIONS
nil, // TABLE_COMMENT
nil, // TIDB_TABLE_ID
nil, // TIDB_ROW_ID_SHARDING_INFO
nil, // TIDB_PK_TYPE
nil, // TIDB_PLACEMENT_POLICY_NAME
)
rows = append(rows, record)
return true
})
e.rows = rows
return nil
}
}
// Normal code path.
schemas, tables, err := ex.ListSchemasAndTables(ctx, e.is)
if err != nil {
return errors.Trace(err)
}
useStatsCache := e.updateStatsCacheIfNeed()
loc := sctx.GetSessionVars().TimeZone
if loc == nil {
loc = time.Local
}
for i, table := range tables {
rows, err = e.setDataFromOneTable(sctx, loc, checker, schemas[i], table, rows, useStatsCache)
if err != nil {
return errors.Trace(err)
}
}
e.rows = rows
return nil
}
// Data for inforation_schema.CHECK_CONSTRAINTS
// This is standards (ISO/IEC 9075-11) compliant and is compatible with the implementation in MySQL as well.
func (e *memtableRetriever) setDataFromCheckConstraints(ctx context.Context, sctx sessionctx.Context) error {
var rows [][]types.Datum
checker := privilege.GetPrivilegeManager(sctx)
ex, ok := e.extractor.(*plannercore.InfoSchemaCheckConstraintsExtractor)
if !ok {
return errors.Errorf("wrong extractor type: %T, expected InfoSchemaCheckConstraintsExtractor", e.extractor)
}
if ex.SkipRequest {
return nil
}
for _, schema := range ex.ListSchemas(e.is) {
tables, err := e.is.SchemaTableInfos(ctx, schema)
if err != nil {
return errors.Trace(err)
}
for _, table := range tables {
if len(table.Constraints) > 0 {
if checker != nil && !checker.RequestVerification(sctx.GetSessionVars().ActiveRoles, schema.L, table.Name.L, "", mysql.SelectPriv) {
continue
}
for _, constraint := range table.Constraints {
if constraint.State != model.StatePublic {
continue
}
if ok && !ex.HasConstraint(constraint.Name.L) {
continue
}
record := types.MakeDatums(
infoschema.CatalogVal, // CONSTRAINT_CATALOG
schema.O, // CONSTRAINT_SCHEMA
constraint.Name.O, // CONSTRAINT_NAME
fmt.Sprintf("(%s)", constraint.ExprString), // CHECK_CLAUSE
)
rows = append(rows, record)
}
}
}
}
e.rows = rows
return nil
}
// Data for inforation_schema.TIDB_CHECK_CONSTRAINTS
// This has non-standard TiDB specific extensions.
func (e *memtableRetriever) setDataFromTiDBCheckConstraints(ctx context.Context, sctx sessionctx.Context) error {
var rows [][]types.Datum
checker := privilege.GetPrivilegeManager(sctx)
ex, ok := e.extractor.(*plannercore.InfoSchemaTiDBCheckConstraintsExtractor)
if !ok {
return errors.Errorf("wrong extractor type: %T, expected InfoSchemaTiDBCheckConstraintsExtractor", e.extractor)
}
if ex.SkipRequest {
return nil
}
schemas, tables, err := ex.ListSchemasAndTables(ctx, e.is)
if err != nil {
return errors.Trace(err)
}
for i, table := range tables {
schema := schemas[i]
if len(table.Constraints) > 0 {
if checker != nil && !checker.RequestVerification(sctx.GetSessionVars().ActiveRoles, schema.L, table.Name.L, "", mysql.SelectPriv) {
continue
}
for _, constraint := range table.Constraints {
if constraint.State != model.StatePublic {
continue
}
if ok && !ex.HasConstraint(constraint.Name.L) {
continue
}
record := types.MakeDatums(
infoschema.CatalogVal, // CONSTRAINT_CATALOG
schema.O, // CONSTRAINT_SCHEMA
constraint.Name.O, // CONSTRAINT_NAME
fmt.Sprintf("(%s)", constraint.ExprString), // CHECK_CLAUSE
table.Name.O, // TABLE_NAME
table.ID, // TABLE_ID
)
rows = append(rows, record)
}
}
}
e.rows = rows
return nil
}
type hugeMemTableRetriever struct {
dummyCloser
extractor *plannercore.InfoSchemaColumnsExtractor
table *model.TableInfo
columns []*model.ColumnInfo
retrieved bool
initialized bool
rows [][]types.Datum
dbs []pmodel.CIStr
curTables []*model.TableInfo
dbsIdx int
tblIdx int
viewMu syncutil.RWMutex
viewSchemaMap map[int64]*expression.Schema // table id to view schema
viewOutputNamesMap map[int64]types.NameSlice // table id to view output names
batch int
is infoschema.InfoSchema
}
// retrieve implements the infoschemaRetriever interface
func (e *hugeMemTableRetriever) retrieve(ctx context.Context, sctx sessionctx.Context) ([][]types.Datum, error) {
if e.extractor.SkipRequest {
e.retrieved = true
}
if e.retrieved {
return nil, nil
}
if !e.initialized {
e.is = sessiontxn.GetTxnManager(sctx).GetTxnInfoSchema()
e.dbs = e.extractor.ListSchemas(e.is)
e.initialized = true
e.rows = make([][]types.Datum, 0, 1024)
e.batch = 1024
}
var err error
if e.table.Name.O == infoschema.TableColumns {
err = e.setDataForColumns(ctx, sctx)
}
if err != nil {
return nil, err
}
e.retrieved = len(e.rows) == 0
return adjustColumns(e.rows, e.columns, e.table), nil
}
func (e *hugeMemTableRetriever) setDataForColumns(ctx context.Context, sctx sessionctx.Context) error {
checker := privilege.GetPrivilegeManager(sctx)
e.rows = e.rows[:0]
for ; e.dbsIdx < len(e.dbs); e.dbsIdx++ {
schema := e.dbs[e.dbsIdx]
var table *model.TableInfo
if len(e.curTables) == 0 {
tables, err := e.extractor.ListTables(ctx, schema, e.is)
if err != nil {
return errors.Trace(err)
}
e.curTables = tables
}
for e.tblIdx < len(e.curTables) {
table = e.curTables[e.tblIdx]
e.tblIdx++
if e.setDataForColumnsWithOneTable(ctx, sctx, schema, table, checker) {
return nil
}
}
e.tblIdx = 0
e.curTables = e.curTables[:0]
}
return nil
}
func (e *hugeMemTableRetriever) setDataForColumnsWithOneTable(
ctx context.Context,
sctx sessionctx.Context,
schema pmodel.CIStr,
table *model.TableInfo,
checker privilege.Manager) bool {
hasPrivs := false
var priv mysql.PrivilegeType
if checker != nil {
for _, p := range mysql.AllColumnPrivs {
if checker.RequestVerification(sctx.GetSessionVars().ActiveRoles, schema.L, table.Name.L, "", p) {
hasPrivs = true
priv |= p
}
}
if !hasPrivs {
return false
}
}
e.dataForColumnsInTable(ctx, sctx, schema, table, priv)
return len(e.rows) >= e.batch
}
func (e *hugeMemTableRetriever) dataForColumnsInTable(
ctx context.Context,