forked from pingcap/tidb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshow.go
1293 lines (1192 loc) · 39.4 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package executor
import (
"bytes"
"context"
"fmt"
"sort"
"strconv"
"strings"
"time"
"github.com/cznic/mathutil"
"github.com/pingcap/errors"
"github.com/pingcap/parser/ast"
"github.com/pingcap/parser/auth"
"github.com/pingcap/parser/charset"
"github.com/pingcap/parser/model"
"github.com/pingcap/parser/mysql"
"github.com/pingcap/parser/terror"
"github.com/pingcap/tidb-tools/pkg/etcd"
"github.com/pingcap/tidb-tools/pkg/utils"
"github.com/pingcap/tidb-tools/tidb-binlog/node"
"github.com/pingcap/tidb/bindinfo"
"github.com/pingcap/tidb/config"
"github.com/pingcap/tidb/domain"
"github.com/pingcap/tidb/infoschema"
"github.com/pingcap/tidb/kv"
plannercore "github.com/pingcap/tidb/planner/core"
"github.com/pingcap/tidb/plugin"
"github.com/pingcap/tidb/privilege"
"github.com/pingcap/tidb/sessionctx/stmtctx"
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/store/tikv"
"github.com/pingcap/tidb/table"
"github.com/pingcap/tidb/types"
"github.com/pingcap/tidb/types/json"
"github.com/pingcap/tidb/util/chunk"
"github.com/pingcap/tidb/util/format"
"github.com/pingcap/tidb/util/sqlexec"
)
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.
Column *ast.ColumnName // Used for `desc table column`.
IndexName model.CIStr // Used for show table regions.
Flag int // Some flag parsed from sql, such as FULL.
Full bool
User *auth.UserIdentity // Used by show grants, show create user.
Roles []*auth.RoleIdentity // Used for show grants.
IfNotExists bool // Used for `show create database if not exists`
// GlobalScope is used by show variables
GlobalScope bool
is infoschema.InfoSchema
result *chunk.Chunk
cursor int
}
// 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.Tp) {
continue
}
for row := iter.Begin(); row != iter.End(); row = iter.Next() {
if valLen := len(row.GetString(colIdx)); retType.Flen < valLen {
retType.Flen = 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 {
switch e.Tp {
case ast.ShowCharset:
return e.fetchShowCharset()
case ast.ShowCollation:
return e.fetchShowCollation()
case ast.ShowColumns:
return e.fetchShowColumns(ctx)
case ast.ShowCreateTable:
return e.fetchShowCreateTable()
case ast.ShowCreateUser:
return e.fetchShowCreateUser()
case ast.ShowCreateView:
return e.fetchShowCreateView()
case ast.ShowCreateDatabase:
return e.fetchShowCreateDatabase()
case ast.ShowDatabases:
return e.fetchShowDatabases()
case ast.ShowDrainerStatus:
return e.fetchShowPumpOrDrainerStatus(node.DrainerNode)
case ast.ShowEngines:
return e.fetchShowEngines()
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()
case ast.ShowTriggers:
return e.fetchShowTriggers()
case ast.ShowVariables:
return e.fetchShowVariables()
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.ShowStatsMeta:
return e.fetchShowStatsMeta()
case ast.ShowStatsHistograms:
return e.fetchShowStatsHistogram()
case ast.ShowStatsBuckets:
return e.fetchShowStatsBuckets()
case ast.ShowStatsHealthy:
e.fetchShowStatsHealthy()
return nil
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.ShowAnalyzeStatus:
e.fetchShowAnalyzeStatus()
return nil
case ast.ShowRegions:
return e.fetchShowTableRegions()
}
return nil
}
func (e *ShowExec) fetchShowBind() error {
var bindRecords []*bindinfo.BindMeta
if !e.GlobalScope {
handle := e.ctx.Value(bindinfo.SessionBindInfoKeyType).(*bindinfo.SessionHandle)
bindRecords = handle.GetAllBindRecord()
} else {
bindRecords = domain.GetDomain(e.ctx).BindHandle().GetAllBindRecord()
}
for _, bindData := range bindRecords {
e.appendRow([]interface{}{
bindData.OriginalSQL,
bindData.BindSQL,
bindData.Db,
bindData.Status,
bindData.CreateTime,
bindData.UpdateTime,
bindData.Charset,
bindData.Collation,
})
}
return nil
}
func (e *ShowExec) fetchShowEngines() error {
sql := `SELECT * FROM information_schema.engines`
rows, _, err := e.ctx.(sqlexec.RestrictedSQLExecutor).ExecRestrictedSQL(e.ctx, sql)
if err != nil {
return errors.Trace(err)
}
for _, row := range rows {
e.result.AppendRow(row)
}
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)
sort.Strings(dbs)
// let information_schema be the first database
moveInfoSchemaToFront(dbs)
for _, d := range dbs {
if checker != nil && !checker.DBIsVisible(e.ctx.GetSessionVars().ActiveRoles, 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 ErrBadDB.GenWithStackByArgs(e.DBName)
}
// sort for tables
tableNames := make([]string, 0, len(e.is.SchemaTables(e.DBName)))
activeRoles := e.ctx.GetSessionVars().ActiveRoles
var tableTypes = make(map[string]string)
for _, v := range e.is.SchemaTables(e.DBName) {
// 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
}
tableNames = append(tableNames, v.Meta().Name.O)
if v.Meta().IsView() {
tableTypes[v.Meta().Name.O] = "VIEW"
} else {
tableTypes[v.Meta().Name.O] = "BASE TABLE"
}
}
sort.Strings(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() 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 ErrBadDB.GenWithStackByArgs(e.DBName)
}
sql := fmt.Sprintf(`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 table_schema='%s' ORDER BY table_name`, e.DBName)
rows, _, err := e.ctx.(sqlexec.RestrictedSQLExecutor).ExecRestrictedSQL(e.ctx, sql)
if err != nil {
return errors.Trace(err)
}
activeRoles := e.ctx.GetSessionVars().ActiveRoles
for _, row := range rows {
if checker != nil && !checker.RequestVerification(activeRoles, e.DBName.O, row.GetString(0), "", mysql.AllPrivMask) {
continue
}
e.result.AppendRow(row)
}
return nil
}
func createOptions(tb *model.TableInfo) string {
if tb.GetPartitionInfo() != nil {
return "partitioned"
}
return ""
}
func (e *ShowExec) fetchShowColumns(ctx context.Context) 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)
}
cols := tb.Cols()
if tb.Meta().IsView() {
// Because view's undertable's column could change or recreate, so view's column type may change overtime.
// To avoid this situation we need to generate a logical plan and extract current column types from Schema.
planBuilder := plannercore.NewPlanBuilder(e.ctx, e.is)
viewLogicalPlan, err := planBuilder.BuildDataSourceFromView(ctx, e.DBName, tb.Meta())
if err != nil {
return err
}
viewSchema := viewLogicalPlan.Schema()
for _, col := range cols {
viewColumn := viewSchema.FindColumnByName(col.Name.L)
if viewColumn != nil {
col.FieldType = *viewColumn.GetType()
}
}
}
for _, col := range cols {
if e.Column != nil && e.Column.Name.L != 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.Tp == 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.Tp == 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.Flag) {
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
})
}
for _, idx := range tb.Indices() {
idxInfo := idx.Meta()
if idxInfo.State != model.StatePublic {
continue
}
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
}
e.appendRow([]interface{}{
tb.Meta().Name.O, // Table
nonUniq, // Non_unique
idx.Meta().Name.O, // Key_name
i + 1, // Seq_in_index
col.Name.O, // Column_name
"A", // Collation
0, // Cardinality
subPart, // Sub_part
nil, // Packed
"YES", // Null
idx.Meta().Tp.String(), // Index_type
"", // Comment
idx.Meta().Comment, // Index_comment
})
}
}
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() (err error) {
var (
value string
ok bool
sessionVars = e.ctx.GetSessionVars()
unreachedVars = make([]string, 0, len(variable.SysVars))
)
for _, v := range variable.SysVars {
if !e.GlobalScope {
// For a session scope variable,
// 1. try to fetch value from SessionVars.Systems;
// 2. if this variable is session-only, fetch value from SysVars
// otherwise, fetch the value from table `mysql.Global_Variables`.
value, ok, err = variable.GetSessionOnlySysVars(sessionVars, v.Name)
} else {
// If the scope of a system variable is ScopeNone,
// it's a read-only variable, so we return the default value of it.
// Otherwise, we have to fetch the values from table `mysql.Global_Variables` for global variable names.
value, ok, err = variable.GetScopeNoneSystemVar(v.Name)
}
if err != nil {
return errors.Trace(err)
}
if !ok {
unreachedVars = append(unreachedVars, v.Name)
continue
}
e.appendRow([]interface{}{v.Name, value})
}
if len(unreachedVars) != 0 {
systemVars, err := sessionVars.GlobalVarsAccessor.GetAllSysVars()
if err != nil {
return errors.Trace(err)
}
for _, varName := range unreachedVars {
varValue, ok := systemVars[varName]
if !ok {
varValue = variable.SysVars[varName].Value
}
e.appendRow([]interface{}{varName, varValue})
}
}
return nil
}
func (e *ShowExec) fetchShowStatus() error {
sessionVars := e.ctx.GetSessionVars()
statusVars, err := variable.GetStatusVars(sessionVars)
if err != nil {
return errors.Trace(err)
}
for status, v := range statusVars {
if e.GlobalScope && v.Scope == variable.ScopeSession {
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 {
for _, c := range charset.GetSupportedCharsets() {
if strings.EqualFold(c.Name, charsetName) {
return c.DefaultCollation
}
}
return ""
}
// escape the identifier for pretty-printing.
// For instance, the identifier "foo `bar`" will become "`foo ``bar```".
// The sqlMode controls whether to escape with backquotes (`) or double quotes
// (`"`) depending on whether mysql.ModeANSIQuotes is enabled.
func escape(cis model.CIStr, sqlMode mysql.SQLMode) string {
var quote string
if sqlMode&mysql.ModeANSIQuotes != 0 {
quote = `"`
} else {
quote = "`"
}
return quote + strings.Replace(cis.O, quote, quote+quote, -1) + quote
}
func (e *ShowExec) fetchShowCreateTable() error {
tb, err := e.getTable()
if err != nil {
return errors.Trace(err)
}
sqlMode := e.ctx.GetSessionVars().SQLMode
// TODO: let the result more like MySQL.
var buf bytes.Buffer
if tb.Meta().IsView() {
e.fetchShowCreateTable4View(tb.Meta(), &buf)
e.appendRow([]interface{}{tb.Meta().Name.O, buf.String(), tb.Meta().Charset, tb.Meta().Collate})
return nil
}
tblCharset := tb.Meta().Charset
if len(tblCharset) == 0 {
tblCharset = mysql.DefaultCharset
}
tblCollate := tb.Meta().Collate
// Set default collate if collate is not specified.
if len(tblCollate) == 0 {
tblCollate = getDefaultCollate(tblCharset)
}
fmt.Fprintf(&buf, "CREATE TABLE %s (\n", escape(tb.Meta().Name, sqlMode))
var pkCol *table.Column
var hasAutoIncID bool
for i, col := range tb.Cols() {
fmt.Fprintf(&buf, " %s %s", escape(col.Name, sqlMode), col.GetTypeDesc())
if col.Charset != "binary" {
if col.Charset != tblCharset || col.Collate != tblCollate {
fmt.Fprintf(&buf, " CHARACTER SET %s COLLATE %s", col.Charset, col.Collate)
}
}
if col.IsGenerated() {
// It's a generated column.
fmt.Fprintf(&buf, " GENERATED ALWAYS AS (%s)", col.GeneratedExprString)
if col.GeneratedStored {
buf.WriteString(" STORED")
} else {
buf.WriteString(" VIRTUAL")
}
}
if mysql.HasAutoIncrementFlag(col.Flag) {
hasAutoIncID = true
buf.WriteString(" NOT NULL AUTO_INCREMENT")
} else {
if mysql.HasNotNullFlag(col.Flag) {
buf.WriteString(" NOT NULL")
}
// default values are not shown for generated columns in MySQL
if !mysql.HasNoDefaultValueFlag(col.Flag) && !col.IsGenerated() {
defaultValue := col.GetDefaultValue()
switch defaultValue {
case nil:
if !mysql.HasNotNullFlag(col.Flag) {
if col.Tp == mysql.TypeTimestamp {
buf.WriteString(" NULL")
}
buf.WriteString(" DEFAULT NULL")
}
case "CURRENT_TIMESTAMP":
buf.WriteString(" DEFAULT CURRENT_TIMESTAMP")
if col.Decimal > 0 {
buf.WriteString(fmt.Sprintf("(%d)", col.Decimal))
}
default:
defaultValStr := fmt.Sprintf("%v", 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.Tp == mysql.TypeTimestamp && defaultValStr != types.ZeroDatetimeStr {
timeValue, err := table.GetColDefaultValue(e.ctx, col.ToInfo())
if err != nil {
return errors.Trace(err)
}
defaultValStr = timeValue.GetMysqlTime().String()
}
if col.Tp == mysql.TypeBit {
defaultValBinaryLiteral := types.BinaryLiteral(defaultValStr)
fmt.Fprintf(&buf, " DEFAULT %s", defaultValBinaryLiteral.ToBitLiteralString(true))
} else {
fmt.Fprintf(&buf, " DEFAULT '%s'", format.OutputFormat(defaultValStr))
}
}
}
if mysql.HasOnUpdateNowFlag(col.Flag) {
buf.WriteString(" ON UPDATE CURRENT_TIMESTAMP")
buf.WriteString(table.OptionalFsp(&col.FieldType))
}
}
if len(col.Comment) > 0 {
fmt.Fprintf(&buf, " COMMENT '%s'", format.OutputFormat(col.Comment))
}
if i != len(tb.Cols())-1 {
buf.WriteString(",\n")
}
if tb.Meta().PKIsHandle && mysql.HasPriKeyFlag(col.Flag) {
pkCol = col
}
}
if pkCol != nil {
// If PKIsHanle, pk info is not in tb.Indices(). We should handle it here.
buf.WriteString(",\n")
fmt.Fprintf(&buf, " PRIMARY KEY (%s)", escape(pkCol.Name, sqlMode))
}
publicIndices := make([]table.Index, 0, len(tb.Indices()))
for _, idx := range tb.Indices() {
if idx.Meta().State == model.StatePublic {
publicIndices = append(publicIndices, idx)
}
}
if len(publicIndices) > 0 {
buf.WriteString(",\n")
}
for i, idx := range publicIndices {
idxInfo := idx.Meta()
if idxInfo.Primary {
buf.WriteString(" PRIMARY KEY ")
} else if idxInfo.Unique {
fmt.Fprintf(&buf, " UNIQUE KEY %s ", escape(idxInfo.Name, sqlMode))
} else {
fmt.Fprintf(&buf, " KEY %s ", escape(idxInfo.Name, sqlMode))
}
cols := make([]string, 0, len(idxInfo.Columns))
for _, c := range idxInfo.Columns {
colInfo := escape(c.Name, sqlMode)
if c.Length != types.UnspecifiedLength {
colInfo = fmt.Sprintf("%s(%s)", colInfo, strconv.Itoa(c.Length))
}
cols = append(cols, colInfo)
}
fmt.Fprintf(&buf, "(%s)", strings.Join(cols, ","))
if i != len(publicIndices)-1 {
buf.WriteString(",\n")
}
}
buf.WriteString("\n")
buf.WriteString(") ENGINE=InnoDB")
// Because we only support case sensitive utf8_bin collate, we need to explicitly set the default charset and collation
// to make it work on MySQL server which has default collate utf8_general_ci.
if len(tblCollate) == 0 {
// If we can not find default collate for the given charset,
// do not show the collate part.
fmt.Fprintf(&buf, " DEFAULT CHARSET=%s", tblCharset)
} else {
fmt.Fprintf(&buf, " DEFAULT CHARSET=%s COLLATE=%s", tblCharset, tblCollate)
}
// Displayed if the compression typed is set.
if len(tb.Meta().Compression) != 0 {
fmt.Fprintf(&buf, " COMPRESSION='%s'", tb.Meta().Compression)
}
if hasAutoIncID {
autoIncID, err := tb.Allocator(e.ctx).NextGlobalAutoID(tb.Meta().ID)
if err != nil {
return errors.Trace(err)
}
// It's campatible with MySQL.
if autoIncID > 1 {
fmt.Fprintf(&buf, " AUTO_INCREMENT=%d", autoIncID)
}
}
if tb.Meta().ShardRowIDBits > 0 {
fmt.Fprintf(&buf, "/*!90000 SHARD_ROW_ID_BITS=%d ", tb.Meta().ShardRowIDBits)
if tb.Meta().PreSplitRegions > 0 {
fmt.Fprintf(&buf, "PRE_SPLIT_REGIONS=%d ", tb.Meta().PreSplitRegions)
}
buf.WriteString("*/")
}
if len(tb.Meta().Comment) > 0 {
fmt.Fprintf(&buf, " COMMENT='%s'", format.OutputFormat(tb.Meta().Comment))
}
// add partition info here.
appendPartitionInfo(tb.Meta().Partition, &buf)
e.appendRow([]interface{}{tb.Meta().Name.O, buf.String()})
return nil
}
func (e *ShowExec) fetchShowCreateView() error {
db, ok := e.is.SchemaByName(e.DBName)
if !ok {
return infoschema.ErrDatabaseNotExists.GenWithStackByArgs(e.DBName.O)
}
tb, err := e.getTable()
if err != nil {
return errors.Trace(err)
}
if !tb.Meta().IsView() {
return ErrWrongObject.GenWithStackByArgs(db.Name.O, tb.Meta().Name.O, "VIEW")
}
var buf bytes.Buffer
e.fetchShowCreateTable4View(tb.Meta(), &buf)
e.appendRow([]interface{}{tb.Meta().Name.O, buf.String(), tb.Meta().Charset, tb.Meta().Collate})
return nil
}
func (e *ShowExec) fetchShowCreateTable4View(tb *model.TableInfo, buf *bytes.Buffer) {
sqlMode := e.ctx.GetSessionVars().SQLMode
fmt.Fprintf(buf, "CREATE ALGORITHM=%s ", tb.View.Algorithm.String())
fmt.Fprintf(buf, "DEFINER=%s@%s ", escape(model.NewCIStr(tb.View.Definer.Username), sqlMode), escape(model.NewCIStr(tb.View.Definer.Hostname), sqlMode))
fmt.Fprintf(buf, "SQL SECURITY %s ", tb.View.Security.String())
fmt.Fprintf(buf, "VIEW %s (", escape(tb.Name, sqlMode))
for i, col := range tb.Columns {
fmt.Fprintf(buf, "%s", escape(col.Name, sqlMode))
if i < len(tb.Columns)-1 {
fmt.Fprintf(buf, ", ")
}
}
fmt.Fprintf(buf, ") AS %s", tb.View.SelectStmt)
}
func appendPartitionInfo(partitionInfo *model.PartitionInfo, buf *bytes.Buffer) {
if partitionInfo == nil {
return
}
if partitionInfo.Type == model.PartitionTypeHash {
fmt.Fprintf(buf, "\nPARTITION BY HASH( %s )", partitionInfo.Expr)
fmt.Fprintf(buf, "\nPARTITIONS %d", partitionInfo.Num)
return
}
// this if statement takes care of range columns case
if partitionInfo.Columns != nil && partitionInfo.Type == model.PartitionTypeRange {
buf.WriteString("\nPARTITION BY RANGE COLUMNS(")
for i, col := range partitionInfo.Columns {
buf.WriteString(col.L)
if i < len(partitionInfo.Columns)-1 {
buf.WriteString(",")
}
}
buf.WriteString(") (\n")
} else {
fmt.Fprintf(buf, "\nPARTITION BY %s ( %s ) (\n", partitionInfo.Type.String(), partitionInfo.Expr)
}
for i, def := range partitionInfo.Definitions {
lessThans := strings.Join(def.LessThan, ",")
fmt.Fprintf(buf, " PARTITION %s VALUES LESS THAN (%s)", def.Name, lessThans)
if i < len(partitionInfo.Definitions)-1 {
buf.WriteString(",\n")
} else {
buf.WriteString("\n")
}
}
buf.WriteString(")")
}
// fetchShowCreateDatabase composes show create database result.
func (e *ShowExec) fetchShowCreateDatabase() error {
checker := privilege.GetPrivilegeManager(e.ctx)
if checker != nil && e.ctx.GetSessionVars().User != nil {
if !checker.DBIsVisible(e.ctx.GetSessionVars().ActiveRoles, e.DBName.String()) {
return e.dbAccessDenied()
}
}
db, ok := e.is.SchemaByName(e.DBName)
if !ok {
return infoschema.ErrDatabaseNotExists.GenWithStackByArgs(e.DBName.O)
}
sqlMode := e.ctx.GetSessionVars().SQLMode
var buf bytes.Buffer
var ifNotExists string
if e.IfNotExists {
ifNotExists = "/*!32312 IF NOT EXISTS*/ "
}
fmt.Fprintf(&buf, "CREATE DATABASE %s%s", ifNotExists, escape(db.Name, sqlMode))
if s := db.Charset; len(s) > 0 {
fmt.Fprintf(&buf, " /*!40100 DEFAULT CHARACTER SET %s */", s)
}
e.appendRow([]interface{}{db.Name.O, buf.String()})
return nil
}
func (e *ShowExec) fetchShowCollation() error {
collations := charset.GetSupportedCollations()
for _, v := range collations {
isDefault := ""
if v.IsDefault {
isDefault = "Yes"
}
e.appendRow([]interface{}{
v.Name,
v.CharsetName,
v.ID,
isDefault,
"Yes",
1,
})
}
return nil
}
// fetchShowCreateUser composes show create create user result.
func (e *ShowExec) fetchShowCreateUser() error {
checker := privilege.GetPrivilegeManager(e.ctx)
if checker == nil {
return errors.New("miss privilege checker")
}
userName, hostName := e.User.Username, e.User.Hostname
sessVars := e.ctx.GetSessionVars()
if e.User.CurrentUser {
userName = sessVars.User.AuthUsername
hostName = sessVars.User.AuthHostname
} else {
// Show create user requires the SELECT privilege on mysql.user.
// Ref https://dev.mysql.com/doc/refman/5.7/en/show-create-user.html
activeRoles := sessVars.ActiveRoles
if !checker.RequestVerification(activeRoles, mysql.SystemDB, mysql.UserTable, "", mysql.SelectPriv) {
return e.tableAccessDenied("SELECT", mysql.UserTable)
}
}
sql := fmt.Sprintf(`SELECT * FROM %s.%s WHERE User='%s' AND Host='%s';`,
mysql.SystemDB, mysql.UserTable, userName, hostName)
rows, _, err := e.ctx.(sqlexec.RestrictedSQLExecutor).ExecRestrictedSQL(e.ctx, sql)
if err != nil {
return errors.Trace(err)
}
if len(rows) == 0 {
return ErrCannotUser.GenWithStackByArgs("SHOW CREATE USER",
fmt.Sprintf("'%s'@'%s'", e.User.Username, e.User.Hostname))
}
showStr := fmt.Sprintf("CREATE USER '%s'@'%s' IDENTIFIED WITH 'mysql_native_password' AS '%s' REQUIRE NONE PASSWORD EXPIRE DEFAULT ACCOUNT UNLOCK",
e.User.Username, e.User.Hostname, checker.GetEncodedPassword(e.User.Username, e.User.Hostname))
e.appendRow([]interface{}{showStr})
return nil
}
func (e *ShowExec) fetchShowGrants() error {
// Get checker
checker := privilege.GetPrivilegeManager(e.ctx)
if checker == nil {
return errors.New("miss privilege checker")
}
for _, r := range e.Roles {
if r.Hostname == "" {
r.Hostname = "%"
}
if !checker.FindEdge(e.ctx, r, e.User) {
return ErrRoleNotGranted.GenWithStackByArgs(r.String(), e.User.String())
}
}
gs, err := checker.ShowGrants(e.ctx, e.User, e.Roles)
if err != nil {
return errors.Trace(err)
}
for _, g := range gs {
e.appendRow([]interface{}{g})