-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
Copy pathshow.go
2249 lines (2082 loc) · 71.7 KB
/
show.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 2016 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"
gjson "encoding/json"
"fmt"
"math"
"sort"
"strconv"
"strings"
"time"
"github.com/docker/go-units"
"github.com/pingcap/errors"
"github.com/pingcap/tidb/bindinfo"
"github.com/pingcap/tidb/br/pkg/utils"
"github.com/pingcap/tidb/config"
"github.com/pingcap/tidb/ddl"
"github.com/pingcap/tidb/domain"
"github.com/pingcap/tidb/domain/infosync"
"github.com/pingcap/tidb/executor/asyncloaddata"
"github.com/pingcap/tidb/expression"
"github.com/pingcap/tidb/infoschema"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/meta/autoid"
"github.com/pingcap/tidb/parser"
"github.com/pingcap/tidb/parser/ast"
"github.com/pingcap/tidb/parser/auth"
"github.com/pingcap/tidb/parser/charset"
parserformat "github.com/pingcap/tidb/parser/format"
"github.com/pingcap/tidb/parser/model"
"github.com/pingcap/tidb/parser/mysql"
"github.com/pingcap/tidb/parser/terror"
"github.com/pingcap/tidb/parser/tidb"
field_types "github.com/pingcap/tidb/parser/types"
plannercore "github.com/pingcap/tidb/planner/core"
"github.com/pingcap/tidb/plugin"
"github.com/pingcap/tidb/privilege"
"github.com/pingcap/tidb/privilege/privileges"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/sessionctx/sessionstates"
"github.com/pingcap/tidb/sessionctx/stmtctx"
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/store/helper"
"github.com/pingcap/tidb/table"
"github.com/pingcap/tidb/table/tables"
"github.com/pingcap/tidb/tidb-binlog/node"
"github.com/pingcap/tidb/types"
"github.com/pingcap/tidb/util"
"github.com/pingcap/tidb/util/chunk"
"github.com/pingcap/tidb/util/collate"
"github.com/pingcap/tidb/util/dbterror/exeerrors"
"github.com/pingcap/tidb/util/etcd"
"github.com/pingcap/tidb/util/format"
"github.com/pingcap/tidb/util/hack"
"github.com/pingcap/tidb/util/hint"
"github.com/pingcap/tidb/util/logutil"
"github.com/pingcap/tidb/util/mathutil"
"github.com/pingcap/tidb/util/memory"
"github.com/pingcap/tidb/util/sem"
"github.com/pingcap/tidb/util/set"
"github.com/pingcap/tidb/util/sqlexec"
"github.com/pingcap/tidb/util/stringutil"
"go.uber.org/zap"
"golang.org/x/exp/slices"
)
var etcdDialTimeout = 5 * time.Second
// ShowExec represents a show executor.
type ShowExec struct {
baseExecutor
Tp ast.ShowStmtType // Databases/Tables/Columns/....
DBName model.CIStr
Table *ast.TableName // Used for showing columns.
Partition model.CIStr // Used for showing partition
Column *ast.ColumnName // Used for `desc table column`.
IndexName model.CIStr // Used for show table regions.
ResourceGroupName model.CIStr // Used for showing resource group
Flag int // Some flag parsed from sql, such as FULL.
Roles []*auth.RoleIdentity // Used for show grants.
User *auth.UserIdentity // Used by show grants, show create user.
Extractor plannercore.ShowPredicateExtractor
is infoschema.InfoSchema
CountWarningsOrErrors bool // Used for showing count(*) warnings | errors
result *chunk.Chunk
cursor int
Full bool
IfNotExists bool // Used for `show create database if not exists`
GlobalScope bool // GlobalScope is used by show variables
Extended bool // Used for `show extended columns from ...`
LoadDataJobID *int64
}
type showTableRegionRowItem struct {
regionMeta
schedulingConstraints string
schedulingState string
}
// Next implements the Executor Next interface.
func (e *ShowExec) Next(ctx context.Context, req *chunk.Chunk) error {
req.GrowAndReset(e.maxChunkSize)
if e.result == nil {
e.result = newFirstChunk(e)
err := e.fetchAll(ctx)
if err != nil {
return errors.Trace(err)
}
iter := chunk.NewIterator4Chunk(e.result)
for colIdx := 0; colIdx < e.Schema().Len(); colIdx++ {
retType := e.Schema().Columns[colIdx].RetType
if !types.IsTypeVarchar(retType.GetType()) {
continue
}
for row := iter.Begin(); row != iter.End(); row = iter.Next() {
if valLen := len(row.GetString(colIdx)); retType.GetFlen() < valLen {
retType.SetFlen(valLen)
}
}
}
}
if e.cursor >= e.result.NumRows() {
return nil
}
numCurBatch := mathutil.Min(req.Capacity(), e.result.NumRows()-e.cursor)
req.Append(e.result, e.cursor, e.cursor+numCurBatch)
e.cursor += numCurBatch
return nil
}
func (e *ShowExec) fetchAll(ctx context.Context) error {
// Temporary disables select limit to avoid miss the result.
// Because some of below fetch show result stmt functions will generate
// a SQL stmt and then execute the new SQL stmt to do the fetch result task
// for the up-level show stmt.
// Here, the problem is the new SQL stmt will be influenced by SelectLimit value
// and return a limited result set back to up level show stmt. This, in fact, may
// cause a filter effect on result set that may exclude the qualified record outside of
// result set.
// Finally, when above result set, may not include qualified record, is returned to up
// level show stmt's selection, which really applies the filter operation on returned
// result set, it may return empty result to client.
oldSelectLimit := e.ctx.GetSessionVars().SelectLimit
e.ctx.GetSessionVars().SelectLimit = math.MaxUint64
defer func() {
// Restore session Var SelectLimit value.
e.ctx.GetSessionVars().SelectLimit = oldSelectLimit
}()
switch e.Tp {
case ast.ShowCharset:
return e.fetchShowCharset()
case ast.ShowCollation:
return e.fetchShowCollation()
case ast.ShowColumns:
return e.fetchShowColumns(ctx)
case ast.ShowConfig:
return e.fetchShowClusterConfigs(ctx)
case ast.ShowCreateTable:
return e.fetchShowCreateTable()
case ast.ShowCreateSequence:
return e.fetchShowCreateSequence()
case ast.ShowCreateUser:
return e.fetchShowCreateUser(ctx)
case ast.ShowCreateView:
return e.fetchShowCreateView()
case ast.ShowCreateDatabase:
return e.fetchShowCreateDatabase()
case ast.ShowCreatePlacementPolicy:
return e.fetchShowCreatePlacementPolicy()
case ast.ShowCreateResourceGroup:
return e.fetchShowCreateResourceGroup()
case ast.ShowDatabases:
return e.fetchShowDatabases()
case ast.ShowDrainerStatus:
return e.fetchShowPumpOrDrainerStatus(node.DrainerNode)
case ast.ShowEngines:
return e.fetchShowEngines(ctx)
case ast.ShowGrants:
return e.fetchShowGrants()
case ast.ShowIndex:
return e.fetchShowIndex()
case ast.ShowProcedureStatus:
return e.fetchShowProcedureStatus()
case ast.ShowPumpStatus:
return e.fetchShowPumpOrDrainerStatus(node.PumpNode)
case ast.ShowStatus:
return e.fetchShowStatus()
case ast.ShowTables:
return e.fetchShowTables()
case ast.ShowOpenTables:
return e.fetchShowOpenTables()
case ast.ShowTableStatus:
return e.fetchShowTableStatus(ctx)
case ast.ShowTriggers:
return e.fetchShowTriggers()
case ast.ShowVariables:
return e.fetchShowVariables(ctx)
case ast.ShowWarnings:
return e.fetchShowWarnings(false)
case ast.ShowErrors:
return e.fetchShowWarnings(true)
case ast.ShowProcessList:
return e.fetchShowProcessList()
case ast.ShowEvents:
// empty result
case ast.ShowStatsExtended:
return e.fetchShowStatsExtended()
case ast.ShowStatsMeta:
return e.fetchShowStatsMeta()
case ast.ShowStatsHistograms:
return e.fetchShowStatsHistogram()
case ast.ShowStatsBuckets:
return e.fetchShowStatsBuckets()
case ast.ShowStatsTopN:
return e.fetchShowStatsTopN()
case ast.ShowStatsHealthy:
e.fetchShowStatsHealthy()
return nil
case ast.ShowStatsLocked:
return e.fetchShowStatsLocked()
case ast.ShowHistogramsInFlight:
e.fetchShowHistogramsInFlight()
return nil
case ast.ShowColumnStatsUsage:
return e.fetchShowColumnStatsUsage()
case ast.ShowPlugins:
return e.fetchShowPlugins()
case ast.ShowProfiles:
// empty result
case ast.ShowMasterStatus:
return e.fetchShowMasterStatus()
case ast.ShowPrivileges:
return e.fetchShowPrivileges()
case ast.ShowBindings:
return e.fetchShowBind()
case ast.ShowBindingCacheStatus:
return e.fetchShowBindingCacheStatus(ctx)
case ast.ShowAnalyzeStatus:
return e.fetchShowAnalyzeStatus()
case ast.ShowRegions:
return e.fetchShowTableRegions(ctx)
case ast.ShowBuiltins:
return e.fetchShowBuiltins()
case ast.ShowBackups:
return e.fetchShowBRIE(ast.BRIEKindBackup)
case ast.ShowRestores:
return e.fetchShowBRIE(ast.BRIEKindRestore)
case ast.ShowPlacementLabels:
return e.fetchShowPlacementLabels(ctx)
case ast.ShowPlacement:
return e.fetchShowPlacement(ctx)
case ast.ShowPlacementForDatabase:
return e.fetchShowPlacementForDB(ctx)
case ast.ShowPlacementForTable:
return e.fetchShowPlacementForTable(ctx)
case ast.ShowPlacementForPartition:
return e.fetchShowPlacementForPartition(ctx)
case ast.ShowSessionStates:
return e.fetchShowSessionStates(ctx)
case ast.ShowLoadDataJobs:
return e.fetchShowLoadDataJobs(ctx)
}
return nil
}
// visibleChecker checks if a stmt is visible for a certain user.
type visibleChecker struct {
defaultDB string
ctx sessionctx.Context
is infoschema.InfoSchema
manager privilege.Manager
ok bool
}
func (v *visibleChecker) Enter(in ast.Node) (out ast.Node, skipChildren bool) {
switch x := in.(type) {
case *ast.TableName:
schema := x.Schema.L
if schema == "" {
schema = v.defaultDB
}
if !v.is.TableExists(model.NewCIStr(schema), x.Name) {
return in, true
}
activeRoles := v.ctx.GetSessionVars().ActiveRoles
if v.manager != nil && !v.manager.RequestVerification(activeRoles, schema, x.Name.L, "", mysql.SelectPriv) {
v.ok = false
}
return in, true
}
return in, false
}
func (v *visibleChecker) Leave(in ast.Node) (out ast.Node, ok bool) {
return in, true
}
func (e *ShowExec) fetchShowBind() error {
var tmp []*bindinfo.BindRecord
if !e.GlobalScope {
handle := e.ctx.Value(bindinfo.SessionBindInfoKeyType).(*bindinfo.SessionHandle)
tmp = handle.GetAllBindRecord()
} else {
tmp = domain.GetDomain(e.ctx).BindHandle().GetAllBindRecord()
}
bindRecords := make([]*bindinfo.BindRecord, 0)
for _, bindRecord := range tmp {
bindRecords = append(bindRecords, bindRecord.Copy())
}
// Remove the invalid bindRecord.
ind := 0
for _, bindData := range bindRecords {
if len(bindData.Bindings) > 0 {
bindRecords[ind] = bindData
ind++
}
}
bindRecords = bindRecords[:ind]
parser := parser.New()
for _, bindData := range bindRecords {
// For the same origin_sql, sort the bindings according to their update time.
sort.Slice(bindData.Bindings, func(i int, j int) bool {
cmpResult := bindData.Bindings[i].UpdateTime.Compare(bindData.Bindings[j].UpdateTime)
if cmpResult == 0 {
// Because the create time must be different, the result of sorting is stable.
cmpResult = bindData.Bindings[i].CreateTime.Compare(bindData.Bindings[j].CreateTime)
}
return cmpResult > 0
})
}
// For the different origin_sql, sort the bindRecords according to their max update time.
sort.Slice(bindRecords, func(i int, j int) bool {
cmpResult := bindRecords[i].Bindings[0].UpdateTime.Compare(bindRecords[j].Bindings[0].UpdateTime)
if cmpResult == 0 {
// Because the create time must be different, the result of sorting is stable.
cmpResult = bindRecords[i].Bindings[0].CreateTime.Compare(bindRecords[j].Bindings[0].CreateTime)
}
return cmpResult > 0
})
for _, bindData := range bindRecords {
for _, hint := range bindData.Bindings {
stmt, err := parser.ParseOneStmt(hint.BindSQL, hint.Charset, hint.Collation)
if err != nil {
return err
}
checker := visibleChecker{
defaultDB: bindData.Db,
ctx: e.ctx,
is: e.is,
manager: privilege.GetPrivilegeManager(e.ctx),
ok: true,
}
stmt.Accept(&checker)
if !checker.ok {
continue
}
e.appendRow([]interface{}{
bindData.OriginalSQL,
hint.BindSQL,
bindData.Db,
hint.Status,
hint.CreateTime,
hint.UpdateTime,
hint.Charset,
hint.Collation,
hint.Source,
hint.SQLDigest,
hint.PlanDigest,
})
}
}
return nil
}
func (e *ShowExec) fetchShowBindingCacheStatus(ctx context.Context) error {
exec := e.ctx.(sqlexec.RestrictedSQLExecutor)
ctx = kv.WithInternalSourceType(ctx, kv.InternalTxnBindInfo)
rows, _, err := exec.ExecRestrictedSQL(ctx, nil, fmt.Sprintf("SELECT count(*) FROM mysql.bind_info where status = '%s' or status = '%s';", bindinfo.Enabled, bindinfo.Using))
if err != nil {
return errors.Trace(err)
}
handle := domain.GetDomain(e.ctx).BindHandle()
bindRecords := handle.GetAllBindRecord()
numBindings := 0
for _, bindRecord := range bindRecords {
for _, binding := range bindRecord.Bindings {
if binding.IsBindingEnabled() {
numBindings++
}
}
}
memUsage := handle.GetMemUsage()
memCapacity := handle.GetMemCapacity()
e.appendRow([]interface{}{
numBindings,
rows[0].GetInt64(0),
memory.FormatBytes(memUsage),
memory.FormatBytes(memCapacity),
})
return nil
}
func (e *ShowExec) fetchShowEngines(ctx context.Context) error {
ctx = kv.WithInternalSourceType(ctx, kv.InternalTxnMeta)
exec := e.ctx.(sqlexec.RestrictedSQLExecutor)
rows, _, err := exec.ExecRestrictedSQL(ctx, nil, `SELECT * FROM information_schema.engines`)
if err != nil {
return errors.Trace(err)
}
e.result.AppendRows(rows)
return nil
}
// moveInfoSchemaToFront moves information_schema to the first, and the others are sorted in the origin ascending order.
func moveInfoSchemaToFront(dbs []string) {
if len(dbs) > 0 && strings.EqualFold(dbs[0], "INFORMATION_SCHEMA") {
return
}
i := sort.SearchStrings(dbs, "INFORMATION_SCHEMA")
if i < len(dbs) && strings.EqualFold(dbs[i], "INFORMATION_SCHEMA") {
copy(dbs[1:i+1], dbs[0:i])
dbs[0] = "INFORMATION_SCHEMA"
}
}
func (e *ShowExec) fetchShowDatabases() error {
dbs := e.is.AllSchemaNames()
checker := privilege.GetPrivilegeManager(e.ctx)
slices.Sort(dbs)
var (
fieldPatternsLike collate.WildcardPattern
fieldFilter string
)
if e.Extractor != nil {
fieldFilter = e.Extractor.Field()
fieldPatternsLike = e.Extractor.FieldPatternLike()
}
// let information_schema be the first database
moveInfoSchemaToFront(dbs)
for _, d := range dbs {
if checker != nil && !checker.DBIsVisible(e.ctx.GetSessionVars().ActiveRoles, d) {
continue
} else if fieldFilter != "" && strings.ToLower(d) != fieldFilter {
continue
} else if fieldPatternsLike != nil && !fieldPatternsLike.DoMatch(strings.ToLower(d)) {
continue
}
e.appendRow([]interface{}{
d,
})
}
return nil
}
func (e *ShowExec) fetchShowProcessList() error {
sm := e.ctx.GetSessionManager()
if sm == nil {
return nil
}
loginUser, activeRoles := e.ctx.GetSessionVars().User, e.ctx.GetSessionVars().ActiveRoles
var hasProcessPriv bool
if pm := privilege.GetPrivilegeManager(e.ctx); pm != nil {
if pm.RequestVerification(activeRoles, "", "", "", mysql.ProcessPriv) {
hasProcessPriv = true
}
}
pl := sm.ShowProcessList()
for _, pi := range pl {
// If you have the PROCESS privilege, you can see all threads.
// Otherwise, you can see only your own threads.
if !hasProcessPriv && pi.User != loginUser.Username {
continue
}
row := pi.ToRowForShow(e.Full)
e.appendRow(row)
}
return nil
}
func (e *ShowExec) fetchShowOpenTables() error {
// TiDB has no concept like mysql's "table cache" and "open table"
// For simplicity, we just return an empty result with the same structure as MySQL's SHOW OPEN TABLES
return nil
}
func (e *ShowExec) fetchShowTables() error {
checker := privilege.GetPrivilegeManager(e.ctx)
if checker != nil && e.ctx.GetSessionVars().User != nil {
if !checker.DBIsVisible(e.ctx.GetSessionVars().ActiveRoles, e.DBName.O) {
return e.dbAccessDenied()
}
}
if !e.is.SchemaExists(e.DBName) {
return exeerrors.ErrBadDB.GenWithStackByArgs(e.DBName)
}
// sort for tables
schemaTables := e.is.SchemaTables(e.DBName)
tableNames := make([]string, 0, len(schemaTables))
activeRoles := e.ctx.GetSessionVars().ActiveRoles
var (
tableTypes = make(map[string]string)
fieldPatternsLike collate.WildcardPattern
fieldFilter string
)
if e.Extractor != nil {
fieldFilter = e.Extractor.Field()
fieldPatternsLike = e.Extractor.FieldPatternLike()
}
for _, v := range schemaTables {
// Test with mysql.AllPrivMask means any privilege would be OK.
// TODO: Should consider column privileges, which also make a table visible.
if checker != nil && !checker.RequestVerification(activeRoles, e.DBName.O, v.Meta().Name.O, "", mysql.AllPrivMask) {
continue
} else if fieldFilter != "" && v.Meta().Name.L != fieldFilter {
continue
} else if fieldPatternsLike != nil && !fieldPatternsLike.DoMatch(v.Meta().Name.L) {
continue
}
tableNames = append(tableNames, v.Meta().Name.O)
if v.Meta().IsView() {
tableTypes[v.Meta().Name.O] = "VIEW"
} else if v.Meta().IsSequence() {
tableTypes[v.Meta().Name.O] = "SEQUENCE"
} else if util.IsSystemView(e.DBName.L) {
tableTypes[v.Meta().Name.O] = "SYSTEM VIEW"
} else {
tableTypes[v.Meta().Name.O] = "BASE TABLE"
}
}
slices.Sort(tableNames)
for _, v := range tableNames {
if e.Full {
e.appendRow([]interface{}{v, tableTypes[v]})
} else {
e.appendRow([]interface{}{v})
}
}
return nil
}
func (e *ShowExec) fetchShowTableStatus(ctx context.Context) error {
checker := privilege.GetPrivilegeManager(e.ctx)
if checker != nil && e.ctx.GetSessionVars().User != nil {
if !checker.DBIsVisible(e.ctx.GetSessionVars().ActiveRoles, e.DBName.O) {
return e.dbAccessDenied()
}
}
if !e.is.SchemaExists(e.DBName) {
return exeerrors.ErrBadDB.GenWithStackByArgs(e.DBName)
}
exec := e.ctx.(sqlexec.RestrictedSQLExecutor)
ctx = kv.WithInternalSourceType(ctx, kv.InternalTxnStats)
var snapshot uint64
txn, err := e.ctx.Txn(false)
if err != nil {
return errors.Trace(err)
}
if txn.Valid() {
snapshot = txn.StartTS()
}
if e.ctx.GetSessionVars().SnapshotTS != 0 {
snapshot = e.ctx.GetSessionVars().SnapshotTS
}
rows, _, err := exec.ExecRestrictedSQL(ctx, []sqlexec.OptionFuncAlias{sqlexec.ExecOptionWithSnapshot(snapshot), sqlexec.ExecOptionUseCurSession},
`SELECT table_name, engine, version, row_format, table_rows,
avg_row_length, data_length, max_data_length, index_length,
data_free, auto_increment, create_time, update_time, check_time,
table_collation, IFNULL(checksum,''), create_options, table_comment
FROM information_schema.tables
WHERE lower(table_schema)=%? ORDER BY table_name`, e.DBName.L)
if err != nil {
return errors.Trace(err)
}
var (
fieldPatternsLike collate.WildcardPattern
fieldFilter string
)
if e.Extractor != nil {
fieldFilter = e.Extractor.Field()
fieldPatternsLike = e.Extractor.FieldPatternLike()
}
activeRoles := e.ctx.GetSessionVars().ActiveRoles
for _, row := range rows {
tableName := row.GetString(0)
if checker != nil && !checker.RequestVerification(activeRoles, e.DBName.O, tableName, "", mysql.AllPrivMask) {
continue
} else if fieldFilter != "" && strings.ToLower(tableName) != fieldFilter {
continue
} else if fieldPatternsLike != nil && !fieldPatternsLike.DoMatch(strings.ToLower(tableName)) {
continue
}
e.result.AppendRow(row)
}
return nil
}
func (e *ShowExec) fetchShowColumns(ctx context.Context) error {
tb, err := e.getTable()
if err != nil {
return errors.Trace(err)
}
var (
fieldPatternsLike collate.WildcardPattern
fieldFilter string
)
if e.Extractor != nil {
fieldFilter = e.Extractor.Field()
fieldPatternsLike = e.Extractor.FieldPatternLike()
}
checker := privilege.GetPrivilegeManager(e.ctx)
activeRoles := e.ctx.GetSessionVars().ActiveRoles
if checker != nil && e.ctx.GetSessionVars().User != nil && !checker.RequestVerification(activeRoles, e.DBName.O, tb.Meta().Name.O, "", mysql.InsertPriv|mysql.SelectPriv|mysql.UpdatePriv|mysql.ReferencesPriv) {
return e.tableAccessDenied("SELECT", tb.Meta().Name.O)
}
var cols []*table.Column
// The optional EXTENDED keyword causes the output to include information about hidden columns that MySQL uses internally and are not accessible by users.
// See https://dev.mysql.com/doc/refman/8.0/en/show-columns.html
if e.Extended {
cols = tb.Cols()
} else {
cols = tb.VisibleCols()
}
if err := tryFillViewColumnType(ctx, e.ctx, e.is, e.DBName, tb.Meta()); err != nil {
return err
}
for _, col := range cols {
if fieldFilter != "" && col.Name.L != fieldFilter {
continue
} else if fieldPatternsLike != nil && !fieldPatternsLike.DoMatch(col.Name.L) {
continue
}
desc := table.NewColDesc(col)
var columnDefault interface{}
if desc.DefaultValue != nil {
// SHOW COLUMNS result expects string value
defaultValStr := fmt.Sprintf("%v", desc.DefaultValue)
// If column is timestamp, and default value is not current_timestamp, should convert the default value to the current session time zone.
if col.GetType() == mysql.TypeTimestamp && defaultValStr != types.ZeroDatetimeStr && !strings.HasPrefix(strings.ToUpper(defaultValStr), strings.ToUpper(ast.CurrentTimestamp)) {
timeValue, err := table.GetColDefaultValue(e.ctx, col.ToInfo())
if err != nil {
return errors.Trace(err)
}
defaultValStr = timeValue.GetMysqlTime().String()
}
if col.GetType() == mysql.TypeBit {
defaultValBinaryLiteral := types.BinaryLiteral(defaultValStr)
columnDefault = defaultValBinaryLiteral.ToBitLiteralString(true)
} else {
columnDefault = defaultValStr
}
}
// The FULL keyword causes the output to include the column collation and comments,
// as well as the privileges you have for each column.
if e.Full {
e.appendRow([]interface{}{
desc.Field,
desc.Type,
desc.Collation,
desc.Null,
desc.Key,
columnDefault,
desc.Extra,
desc.Privileges,
desc.Comment,
})
} else {
e.appendRow([]interface{}{
desc.Field,
desc.Type,
desc.Null,
desc.Key,
columnDefault,
desc.Extra,
})
}
}
return nil
}
func (e *ShowExec) fetchShowIndex() error {
tb, err := e.getTable()
if err != nil {
return errors.Trace(err)
}
checker := privilege.GetPrivilegeManager(e.ctx)
activeRoles := e.ctx.GetSessionVars().ActiveRoles
if checker != nil && e.ctx.GetSessionVars().User != nil && !checker.RequestVerification(activeRoles, e.DBName.O, tb.Meta().Name.O, "", mysql.AllPrivMask) {
return e.tableAccessDenied("SELECT", tb.Meta().Name.O)
}
if tb.Meta().PKIsHandle {
var pkCol *table.Column
for _, col := range tb.Cols() {
if mysql.HasPriKeyFlag(col.GetFlag()) {
pkCol = col
break
}
}
e.appendRow([]interface{}{
tb.Meta().Name.O, // Table
0, // Non_unique
"PRIMARY", // Key_name
1, // Seq_in_index
pkCol.Name.O, // Column_name
"A", // Collation
0, // Cardinality
nil, // Sub_part
nil, // Packed
"", // Null
"BTREE", // Index_type
"", // Comment
"", // Index_comment
"YES", // Index_visible
nil, // Expression
"YES", // Clustered
})
}
for _, idx := range tb.Indices() {
idxInfo := idx.Meta()
if idxInfo.State != model.StatePublic {
continue
}
isClustered := "NO"
if tb.Meta().IsCommonHandle && idxInfo.Primary {
isClustered = "YES"
}
for i, col := range idxInfo.Columns {
nonUniq := 1
if idx.Meta().Unique {
nonUniq = 0
}
var subPart interface{}
if col.Length != types.UnspecifiedLength {
subPart = col.Length
}
tblCol := tb.Meta().Columns[col.Offset]
nullVal := "YES"
if mysql.HasNotNullFlag(tblCol.GetFlag()) {
nullVal = ""
}
visible := "YES"
if idx.Meta().Invisible {
visible = "NO"
}
colName := col.Name.O
var expression interface{}
if tblCol.Hidden {
colName = "NULL"
expression = tblCol.GeneratedExprString
}
e.appendRow([]interface{}{
tb.Meta().Name.O, // Table
nonUniq, // Non_unique
idx.Meta().Name.O, // Key_name
i + 1, // Seq_in_index
colName, // Column_name
"A", // Collation
0, // Cardinality
subPart, // Sub_part
nil, // Packed
nullVal, // Null
idx.Meta().Tp.String(), // Index_type
"", // Comment
idx.Meta().Comment, // Index_comment
visible, // Index_visible
expression, // Expression
isClustered, // Clustered
})
}
}
return nil
}
// fetchShowCharset gets all charset information and fill them into e.rows.
// See http://dev.mysql.com/doc/refman/5.7/en/show-character-set.html
func (e *ShowExec) fetchShowCharset() error {
descs := charset.GetSupportedCharsets()
for _, desc := range descs {
e.appendRow([]interface{}{
desc.Name,
desc.Desc,
desc.DefaultCollation,
desc.Maxlen,
})
}
return nil
}
func (e *ShowExec) fetchShowMasterStatus() error {
tso := e.ctx.GetSessionVars().TxnCtx.StartTS
e.appendRow([]interface{}{"tidb-binlog", tso, "", "", ""})
return nil
}
func (e *ShowExec) fetchShowVariables(ctx context.Context) (err error) {
var (
value string
sessionVars = e.ctx.GetSessionVars()
)
var (
fieldPatternsLike collate.WildcardPattern
fieldFilter string
)
if e.Extractor != nil {
fieldFilter = e.Extractor.Field()
fieldPatternsLike = e.Extractor.FieldPatternLike()
}
if e.GlobalScope {
// Collect global scope variables,
// 1. Exclude the variables of ScopeSession in variable.SysVars;
// 2. If the variable is ScopeNone, it's a read-only variable, return the default value of it,
// otherwise, fetch the value from table `mysql.Global_Variables`.
for _, v := range variable.GetSysVars() {
if v.Scope != variable.ScopeSession {
if v.IsNoop && !variable.EnableNoopVariables.Load() {
continue
}
if fieldFilter != "" && v.Name != fieldFilter {
continue
} else if fieldPatternsLike != nil && !fieldPatternsLike.DoMatch(v.Name) {
continue
}
if infoschema.SysVarHiddenForSem(e.ctx, v.Name) {
continue
}
value, err = sessionVars.GetGlobalSystemVar(ctx, v.Name)
if err != nil {
return errors.Trace(err)
}
e.appendRow([]interface{}{v.Name, value})
}
}
return nil
}
// Collect session scope variables,
// If it is a session only variable, use the default value defined in code,
// otherwise, fetch the value from table `mysql.Global_Variables`.
for _, v := range variable.GetSysVars() {
if v.IsNoop && !variable.EnableNoopVariables.Load() {
continue
}
if fieldFilter != "" && v.Name != fieldFilter {
continue
} else if fieldPatternsLike != nil && !fieldPatternsLike.DoMatch(v.Name) {
continue
}
if infoschema.SysVarHiddenForSem(e.ctx, v.Name) {
continue
}
value, err = sessionVars.GetSessionOrGlobalSystemVar(context.Background(), v.Name)
if err != nil {
return errors.Trace(err)
}
e.appendRow([]interface{}{v.Name, value})
}
return nil
}
func (e *ShowExec) fetchShowStatus() error {
sessionVars := e.ctx.GetSessionVars()
statusVars, err := variable.GetStatusVars(sessionVars)
if err != nil {
return errors.Trace(err)
}
checker := privilege.GetPrivilegeManager(e.ctx)
for status, v := range statusVars {
if e.GlobalScope && v.Scope == variable.ScopeSession {
continue
}
// Skip invisible status vars if permission fails.
if sem.IsEnabled() && sem.IsInvisibleStatusVar(status) {
if checker == nil || !checker.RequestDynamicVerification(sessionVars.ActiveRoles, "RESTRICTED_STATUS_ADMIN", false) {
continue
}
}
switch v.Value.(type) {
case []interface{}, nil:
v.Value = fmt.Sprintf("%v", v.Value)
}
value, err := types.ToString(v.Value)
if err != nil {
return errors.Trace(err)
}
e.appendRow([]interface{}{status, value})
}
return nil
}
func getDefaultCollate(charsetName string) string {
ch, err := charset.GetCharsetInfo(charsetName)
if err != nil {
// The charset is invalid, return server default.
return mysql.DefaultCollationName
}
return ch.DefaultCollation
}
// ConstructResultOfShowCreateTable constructs the result for show create table.
func ConstructResultOfShowCreateTable(ctx sessionctx.Context, tableInfo *model.TableInfo, allocators autoid.Allocators, buf *bytes.Buffer) (err error) {
if tableInfo.IsView() {
fetchShowCreateTable4View(ctx, tableInfo, buf)
return nil
}
if tableInfo.IsSequence() {
ConstructResultOfShowCreateSequence(ctx, tableInfo, buf)
return nil
}
tblCharset := tableInfo.Charset
if len(tblCharset) == 0 {
tblCharset = mysql.DefaultCharset
}
tblCollate := tableInfo.Collate
// Set default collate if collate is not specified.
if len(tblCollate) == 0 {
tblCollate = getDefaultCollate(tblCharset)
}
sqlMode := ctx.GetSessionVars().SQLMode
tableName := stringutil.Escape(tableInfo.Name.O, sqlMode)
switch tableInfo.TempTableType {
case model.TempTableGlobal:
fmt.Fprintf(buf, "CREATE GLOBAL TEMPORARY TABLE %s (\n", tableName)
case model.TempTableLocal:
fmt.Fprintf(buf, "CREATE TEMPORARY TABLE %s (\n", tableName)
default:
fmt.Fprintf(buf, "CREATE TABLE %s (\n", tableName)
}
var pkCol *model.ColumnInfo
var hasAutoIncID bool
needAddComma := false
for i, col := range tableInfo.Cols() {
if col.Hidden {
continue
}
if needAddComma {
buf.WriteString(",\n")
}
fmt.Fprintf(buf, " %s %s", stringutil.Escape(col.Name.O, sqlMode), col.GetTypeDesc())
if field_types.HasCharset(&col.FieldType) {
if col.GetCharset() != tblCharset {
fmt.Fprintf(buf, " CHARACTER SET %s", col.GetCharset())
}
if col.GetCollate() != tblCollate {
fmt.Fprintf(buf, " COLLATE %s", col.GetCollate())
} else {
defcol, err := charset.GetDefaultCollation(col.GetCharset())
if err == nil && defcol != col.GetCollate() {
fmt.Fprintf(buf, " COLLATE %s", col.GetCollate())
}