/
show_iters.go
521 lines (455 loc) · 13.5 KB
/
show_iters.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
// Copyright 2023 Dolthub, 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 rowexec
import (
"fmt"
"io"
"strings"
"time"
"github.com/dolthub/go-mysql-server/sql"
"github.com/dolthub/go-mysql-server/sql/plan"
"github.com/dolthub/go-mysql-server/sql/types"
)
type describeIter struct {
schema sql.Schema
i int
}
func (i *describeIter) Next(ctx *sql.Context) (sql.Row, error) {
if i.i >= len(i.schema) {
return nil, io.EOF
}
f := i.schema[i.i]
i.i++
return sql.NewRow(f.Name, f.Type.String()), nil
}
func (i *describeIter) Close(*sql.Context) error {
return nil
}
type process struct {
id int64
user string
host string
db string
command string
time int64
state string
info string
}
func (p process) toRow() sql.Row {
var db interface{}
if p.db != "" {
db = p.db
}
return sql.NewRow(
p.id,
p.user,
p.host,
db,
p.command,
p.time,
p.state,
p.info,
)
}
// cc here: https://dev.mysql.com/doc/refman/8.0/en/show-table-status.html
func tableToStatusRow(table string, numRows uint64, dataLength uint64, collation sql.CollationID) sql.Row {
var avgLength float64 = 0
if numRows > 0 {
avgLength = float64(dataLength) / float64(numRows)
}
return sql.NewRow(
table, // Name
"InnoDB", // Engine
// This column is unused. With the removal of .frm files in MySQL 8.0, this
// column now reports a hardcoded value of 10, which is the last .frm file
// version used in MySQL 5.7.
"10", // Version
"Fixed", // Row_format
numRows, // Rows
uint64(avgLength), // Avg_row_length
dataLength, // Data_length
uint64(0), // Max_data_length (Unused for InnoDB)
int64(0), // Index_length
int64(0), // Data_free
nil, // Auto_increment (always null)
nil, // Create_time
nil, // Update_time
nil, // Check_time
collation.String(), // Collation
nil, // Checksum
nil, // Create_options
nil, // Comments
)
}
// generatePrivStrings creates a formatted GRANT <privilege_list> on <global/database/table> to <user@host> string
func generatePrivStrings(db, tbl, user string, privs []sql.PrivilegeType) string {
sb := strings.Builder{}
withGrantOption := ""
for i, priv := range privs {
privStr := priv.String()
if privStr == sql.PrivilegeType_GrantOption.String() {
if len(privs) > 1 {
withGrantOption = " WITH GRANT OPTION"
}
} else {
if i > 0 {
sb.WriteString(", ")
}
sb.WriteString(privStr)
}
}
// handle special case for empty global and database privileges
privStr := sb.String()
if len(privStr) == 0 {
if db == "*" {
privStr = "USAGE"
} else {
return ""
}
}
return fmt.Sprintf("GRANT %s ON %s.%s TO %s%s", privStr, db, tbl, user, withGrantOption)
}
// generateRoutinePrivStrings creates a formatted GRANT <PRILEDGE_LIST> on <ROUTINE_TYPE> <ROUTINE> to <user@host> string
func generateRoutinePrivStrings(db, routine, routine_type, user string, privs []sql.PrivilegeType) string {
privStrs := make([]string, 0, len(privs))
grantOption := ""
for _, priv := range privs {
if priv == sql.PrivilegeType_GrantOption {
grantOption = " WITH GRANT OPTION"
continue
}
privStr := priv.String()
privStrs = append(privStrs, privStr)
}
// This is kind of an odd word to insert in the output, but it's what MySQL does when you have no privileges other
// than Grant Options.
finalPrivStr := "USAGE"
if len(privStrs) > 0 {
finalPrivStr = strings.Join(privStrs, ", ")
}
return fmt.Sprintf("GRANT %s ON %s %s.%s TO %s%s", finalPrivStr, routine_type, db, routine, user, grantOption)
}
func newIndexesToShow(indexes []sql.Index) *indexesToShow {
return &indexesToShow{
indexes: indexes,
}
}
type indexesToShow struct {
indexes []sql.Index
pos int
epos int
}
type idxToShow struct {
index sql.Index
expression string
exPosition int
}
func (i *indexesToShow) next() (*idxToShow, error) {
if i.pos >= len(i.indexes) {
return nil, io.EOF
}
index := i.indexes[i.pos]
expressions := index.Expressions()
if i.epos >= len(expressions) {
i.pos++
if i.pos >= len(i.indexes) {
return nil, io.EOF
}
index = i.indexes[i.pos]
i.epos = 0
expressions = index.Expressions()
}
show := &idxToShow{
index: index,
expression: expressions[i.epos],
exPosition: i.epos,
}
i.epos++
return show, nil
}
type showIndexesIter struct {
table *plan.ResolvedTable
idxs *indexesToShow
}
func (i *showIndexesIter) Next(ctx *sql.Context) (sql.Row, error) {
show, err := i.idxs.next()
if err != nil {
return nil, err
}
var expression, columnName interface{}
columnName, expression = nil, show.expression
tbl := i.table
if err != nil {
return nil, err
}
nullable := ""
if col := plan.GetColumnFromIndexExpr(show.expression, tbl); col != nil {
columnName, expression = col.Name, nil
if col.Nullable {
nullable = "YES"
}
}
visible := "YES"
if x, ok := show.index.(sql.DriverIndex); ok && len(x.Driver()) > 0 {
if !ctx.GetIndexRegistry().CanUseIndex(x) {
visible = "NO"
}
}
nonUnique := 0
if !show.index.IsUnique() {
nonUnique = 1
}
return sql.NewRow(
show.index.Table(), // "Table" string
nonUnique, // "Non_unique" int32, Values [0, 1]
show.index.ID(), // "Key_name" string
show.exPosition+1, // "Seq_in_index" int32
columnName, // "Column_name" string
nil, // "Collation" string, Values [A, D, NULL]
int64(0), // "Cardinality" int64 (not calculated)
nil, // "Sub_part" int64
nil, // "Packed" string
nullable, // "Null" string, Values [YES, '']
show.index.IndexType(), // "Index_type" string
show.index.Comment(), // "Comment" string
"", // "Index_comment" string
visible, // "Visible" string, Values [YES, NO]
expression, // "Expression" string
), nil
}
func isFirstColInUniqueKey(s *plan.ShowColumns, col *sql.Column, table sql.Table) bool {
for _, idx := range s.Indexes {
if !idx.IsUnique() {
continue
}
firstIndexCol := plan.GetColumnFromIndexExpr(idx.Expressions()[0], table)
if firstIndexCol != nil && firstIndexCol.Name == col.Name {
return true
}
}
return false
}
func isFirstColInNonUniqueKey(s *plan.ShowColumns, col *sql.Column, table sql.Table) bool {
for _, idx := range s.Indexes {
if idx.IsUnique() {
continue
}
firstIndexCol := plan.GetColumnFromIndexExpr(idx.Expressions()[0], table)
if firstIndexCol != nil && firstIndexCol.Name == col.Name {
return true
}
}
return false
}
func (i *showIndexesIter) Close(*sql.Context) error {
return nil
}
type showCreateTablesIter struct {
table sql.Node
schema sql.Schema
didIteration bool
isView bool
indexes []sql.Index
checks sql.CheckConstraints
pkSchema sql.PrimaryKeySchema
}
func (i *showCreateTablesIter) Next(ctx *sql.Context) (sql.Row, error) {
if i.didIteration {
return nil, io.EOF
}
i.didIteration = true
var row sql.Row
switch table := i.table.(type) {
case *plan.ResolvedTable:
// MySQL behavior is to allow show create table for views, but not show create view for tables.
if i.isView {
return nil, plan.ErrNotView.New(table.Name())
}
composedCreateTableStatement, err := i.produceCreateTableStatement(ctx, table.Table, i.schema, i.pkSchema)
if err != nil {
return nil, err
}
row = sql.NewRow(
table.Name(), // "Table" string
composedCreateTableStatement, // "Create Table" string
)
case *plan.SubqueryAlias:
characterSetClient, err := ctx.GetSessionVariable(ctx, "character_set_client")
if err != nil {
return nil, err
}
collationConnection, err := ctx.GetSessionVariable(ctx, "collation_connection")
if err != nil {
return nil, err
}
row = sql.NewRow(
table.Name(), // "View" string
produceCreateViewStatement(table), // "Create View" string
characterSetClient,
collationConnection,
)
default:
panic(fmt.Sprintf("unexpected type %T", i.table))
}
return row, nil
}
type NameAndSchema interface {
sql.Nameable
Schema() sql.Schema
}
func (i *showCreateTablesIter) produceCreateTableStatement(ctx *sql.Context, table sql.Table, schema sql.Schema, pkSchema sql.PrimaryKeySchema) (string, error) {
colStmts := make([]string, len(schema))
var primaryKeyCols []string
var pkOrdinals []int
if len(pkSchema.Schema) > 0 {
pkOrdinals = pkSchema.PkOrdinals
}
// Statement creation parts for each column
tableCollation := table.Collation()
for i, col := range schema {
var colDefaultStr string
// TODO: The columns that are rendered in defaults should be backticked
if col.Default != nil && col.Generated == nil {
// TODO : string literals should have character set introducer
colDefaultStr = col.Default.String()
if colDefaultStr != "NULL" && col.Default.IsLiteral() && !types.IsTime(col.Default.Type()) && !types.IsText(col.Default.Type()) {
v, err := col.Default.Eval(ctx, nil)
if err != nil {
return "", err
}
colDefaultStr = fmt.Sprintf("'%v'", v)
}
}
var onUpdateStr string
if col.OnUpdate != nil {
onUpdateStr = col.OnUpdate.String()
if onUpdateStr != "NULL" && col.OnUpdate.IsLiteral() && !types.IsTime(col.OnUpdate.Type()) && !types.IsText(col.OnUpdate.Type()) {
v, err := col.OnUpdate.Eval(ctx, nil)
if err != nil {
return "", err
}
onUpdateStr = fmt.Sprintf("'%v'", v)
}
}
if col.PrimaryKey && len(pkSchema.Schema) == 0 {
pkOrdinals = append(pkOrdinals, i)
}
colStmts[i] = sql.GenerateCreateTableColumnDefinition(col, colDefaultStr, onUpdateStr, tableCollation)
}
for _, i := range pkOrdinals {
primaryKeyCols = append(primaryKeyCols, schema[i].Name)
}
if len(primaryKeyCols) > 0 {
colStmts = append(colStmts, sql.GenerateCreateTablePrimaryKeyDefinition(primaryKeyCols))
}
for _, index := range i.indexes {
// The primary key may or may not be declared as an index by the table; don't print it twice.
if index.ID() == "PRIMARY" {
continue
}
prefixLengths := index.PrefixLengths()
var indexCols []string
for i, expr := range index.Expressions() {
col := plan.GetColumnFromIndexExpr(expr, table)
if col != nil {
indexDef := sql.QuoteIdentifier(col.Name)
if len(prefixLengths) > i && prefixLengths[i] != 0 {
indexDef += fmt.Sprintf("(%v)", prefixLengths[i])
}
indexCols = append(indexCols, indexDef)
}
}
colStmts = append(colStmts, sql.GenerateCreateTableIndexDefinition(index.IsUnique(), index.IsSpatial(),
index.IsFullText(), index.ID(), indexCols, index.Comment()))
}
fkt, err := getForeignKeyTable(table)
if err == nil && fkt != nil {
fks, err := fkt.GetDeclaredForeignKeys(ctx)
if err != nil {
return "", err
}
for _, fk := range fks {
onDelete := ""
if len(fk.OnDelete) > 0 && fk.OnDelete != sql.ForeignKeyReferentialAction_DefaultAction {
onDelete = string(fk.OnDelete)
}
onUpdate := ""
if len(fk.OnUpdate) > 0 && fk.OnUpdate != sql.ForeignKeyReferentialAction_DefaultAction {
onUpdate = string(fk.OnUpdate)
}
colStmts = append(colStmts, sql.GenerateCreateTableForiegnKeyDefinition(fk.Name, fk.Columns, fk.ParentTable, fk.ParentColumns, onDelete, onUpdate))
}
}
if i.checks != nil {
for _, check := range i.checks {
colStmts = append(colStmts, sql.GenerateCreateTableCheckConstraintClause(check.Name, check.Expr.String(), check.Enforced))
}
}
comment := ""
if commentedTable, ok := table.(sql.CommentedTable); ok {
comment = commentedTable.Comment()
}
autoInc := ""
if tbl := getAutoIncrementTable(table); tbl != nil {
autoIncVal, err := tbl.PeekNextAutoIncrementValue(ctx)
// TODO: possible to get ErrNoAutoIncrementCol here, so we just ignore
if err != nil && err.Error() != sql.ErrNoAutoIncrementCol.Error() {
return "", err
}
if autoIncVal > 1 {
autoInc = fmt.Sprintf("%v", autoIncVal)
}
}
return sql.GenerateCreateTableStatement(table.Name(), colStmts, autoInc, table.Collation().CharacterSet().Name(), table.Collation().Name(), comment), nil
}
func produceCreateViewStatement(view *plan.SubqueryAlias) string {
return fmt.Sprintf(
"CREATE VIEW `%s` AS %s",
view.Name(),
view.TextDefinition,
)
}
func (i *showCreateTablesIter) Close(*sql.Context) error {
return nil
}
func getForeignKeyTable(t sql.Table) (sql.ForeignKeyTable, error) {
switch t := t.(type) {
case sql.ForeignKeyTable:
return t, nil
case sql.TableWrapper:
return getForeignKeyTable(t.Underlying())
case *plan.ResolvedTable:
return getForeignKeyTable(t.Table)
default:
return nil, sql.ErrNoForeignKeySupport.New(t.Name())
}
}
func getAutoIncrementTable(t sql.Table) sql.AutoIncrementTable {
switch t := t.(type) {
case sql.AutoIncrementTable:
return t
case sql.TableWrapper:
return getAutoIncrementTable(t.Underlying())
case *plan.ResolvedTable:
return getAutoIncrementTable(t.Table)
default:
return nil
}
}
func formatReplicaStatusTimestamp(t *time.Time) string {
if t == nil {
return ""
}
return t.Format(time.UnixDate)
}