-
Notifications
You must be signed in to change notification settings - Fork 5.8k
/
preprocess.go
1737 lines (1612 loc) · 52.6 KB
/
preprocess.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 2015 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 core
import (
"context"
"fmt"
"math"
"strings"
"github.com/pingcap/errors"
"github.com/pingcap/tidb/config"
"github.com/pingcap/tidb/ddl"
"github.com/pingcap/tidb/domain"
"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/format"
"github.com/pingcap/tidb/parser/model"
"github.com/pingcap/tidb/parser/mysql"
"github.com/pingcap/tidb/parser/terror"
"github.com/pingcap/tidb/privilege"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/sessiontxn"
"github.com/pingcap/tidb/table"
"github.com/pingcap/tidb/table/temptable"
"github.com/pingcap/tidb/types"
driver "github.com/pingcap/tidb/types/parser_driver"
"github.com/pingcap/tidb/util"
"github.com/pingcap/tidb/util/domainutil"
utilparser "github.com/pingcap/tidb/util/parser"
)
// PreprocessOpt presents optional parameters to `Preprocess` method.
type PreprocessOpt func(*preprocessor)
// InPrepare is a PreprocessOpt that indicates preprocess is executing under prepare statement.
func InPrepare(p *preprocessor) {
p.flag |= inPrepare
}
// InTxnRetry is a PreprocessOpt that indicates preprocess is executing under transaction retry.
func InTxnRetry(p *preprocessor) {
p.flag |= inTxnRetry
}
// InitTxnContextProvider is a PreprocessOpt that indicates preprocess should init transaction's context
func InitTxnContextProvider(p *preprocessor) {
p.flag |= initTxnContextProvider
}
// WithPreprocessorReturn returns a PreprocessOpt to initialize the PreprocessorReturn.
func WithPreprocessorReturn(ret *PreprocessorReturn) PreprocessOpt {
return func(p *preprocessor) {
p.PreprocessorReturn = ret
}
}
// WithExecuteInfoSchemaUpdate return a PreprocessOpt to update the `Execute` infoSchema under some conditions.
func WithExecuteInfoSchemaUpdate(pe *PreprocessExecuteISUpdate) PreprocessOpt {
return func(p *preprocessor) {
p.PreprocessExecuteISUpdate = pe
}
}
// TryAddExtraLimit trys to add an extra limit for SELECT or UNION statement when sql_select_limit is set.
func TryAddExtraLimit(ctx sessionctx.Context, node ast.StmtNode) ast.StmtNode {
if ctx.GetSessionVars().SelectLimit == math.MaxUint64 || ctx.GetSessionVars().InRestrictedSQL {
return node
}
if explain, ok := node.(*ast.ExplainStmt); ok {
explain.Stmt = TryAddExtraLimit(ctx, explain.Stmt)
return explain
} else if sel, ok := node.(*ast.SelectStmt); ok {
if sel.Limit != nil || sel.SelectIntoOpt != nil {
return node
}
newSel := *sel
newSel.Limit = &ast.Limit{
Count: ast.NewValueExpr(ctx.GetSessionVars().SelectLimit, "", ""),
}
return &newSel
} else if setOprStmt, ok := node.(*ast.SetOprStmt); ok {
if setOprStmt.Limit != nil {
return node
}
newSetOpr := *setOprStmt
newSetOpr.Limit = &ast.Limit{
Count: ast.NewValueExpr(ctx.GetSessionVars().SelectLimit, "", ""),
}
return &newSetOpr
}
return node
}
// Preprocess resolves table names of the node, and checks some statements' validation.
// preprocessReturn used to extract the infoschema for the tableName and the timestamp from the asof clause.
func Preprocess(ctx sessionctx.Context, node ast.Node, preprocessOpt ...PreprocessOpt) error {
v := preprocessor{ctx: ctx, tableAliasInJoin: make([]map[string]interface{}, 0), withName: make(map[string]interface{})}
for _, optFn := range preprocessOpt {
optFn(&v)
}
// PreprocessorReturn must be non-nil before preprocessing
if v.PreprocessorReturn == nil {
v.PreprocessorReturn = &PreprocessorReturn{}
}
node.Accept(&v)
// InfoSchema must be non-nil after preprocessing
v.ensureInfoSchema()
v.initTxnContextProviderIfNecessary(node)
return errors.Trace(v.err)
}
type preprocessorFlag uint8
const (
// inPrepare is set when visiting in prepare statement.
inPrepare preprocessorFlag = 1 << iota
// inTxnRetry is set when visiting in transaction retry.
inTxnRetry
// inCreateOrDropTable is set when visiting create/drop table statement.
inCreateOrDropTable
// parentIsJoin is set when visiting node's parent is join.
parentIsJoin
// inRepairTable is set when visiting a repair table statement.
inRepairTable
// inSequenceFunction is set when visiting a sequence function.
// This flag indicates the tableName in these function should be checked as sequence object.
inSequenceFunction
// initTxnContextProvider is set when we should init txn context in preprocess
initTxnContextProvider
)
// Make linter happy.
var _ = PreprocessorReturn{}.initedLastSnapshotTS
// PreprocessorReturn is used to retain information obtained in the preprocessor.
type PreprocessorReturn struct {
initedLastSnapshotTS bool
IsStaleness bool
SnapshotTSEvaluator func(sessionctx.Context) (uint64, error)
// LastSnapshotTS is the last evaluated snapshotTS if any
// otherwise it defaults to zero
LastSnapshotTS uint64
InfoSchema infoschema.InfoSchema
ReadReplicaScope string
}
// PreprocessExecuteISUpdate is used to update information schema for special Execute statement in the preprocessor.
type PreprocessExecuteISUpdate struct {
ExecuteInfoSchemaUpdate func(node ast.Node, sctx sessionctx.Context) infoschema.InfoSchema
Node ast.Node
}
// preprocessor is an ast.Visitor that preprocess
// ast Nodes parsed from parser.
type preprocessor struct {
ctx sessionctx.Context
flag preprocessorFlag
stmtTp byte
showTp ast.ShowStmtType
// tableAliasInJoin is a stack that keeps the table alias names for joins.
// len(tableAliasInJoin) may bigger than 1 because the left/right child of join may be subquery that contains `JOIN`
tableAliasInJoin []map[string]interface{}
withName map[string]interface{}
// values that may be returned
*PreprocessorReturn
*PreprocessExecuteISUpdate
err error
}
func (p *preprocessor) Enter(in ast.Node) (out ast.Node, skipChildren bool) {
switch node := in.(type) {
case *ast.AdminStmt:
p.checkAdminCheckTableGrammar(node)
case *ast.DeleteStmt:
p.stmtTp = TypeDelete
case *ast.SelectStmt:
p.stmtTp = TypeSelect
case *ast.UpdateStmt:
p.stmtTp = TypeUpdate
case *ast.InsertStmt:
p.stmtTp = TypeInsert
// handle the insert table name imminently
// insert into t with t ..., the insert can not see t here. We should hand it before the CTE statement
p.handleTableName(node.Table.TableRefs.Left.(*ast.TableSource).Source.(*ast.TableName))
case *ast.ExecuteStmt:
p.stmtTp = TypeExecute
p.resolveExecuteStmt(node)
case *ast.CreateTableStmt:
p.stmtTp = TypeCreate
p.flag |= inCreateOrDropTable
p.resolveCreateTableStmt(node)
p.checkCreateTableGrammar(node)
case *ast.CreateViewStmt:
p.stmtTp = TypeCreate
p.flag |= inCreateOrDropTable
p.checkCreateViewGrammar(node)
p.checkCreateViewWithSelectGrammar(node)
case *ast.DropTableStmt:
p.flag |= inCreateOrDropTable
p.stmtTp = TypeDrop
p.checkDropTableGrammar(node)
case *ast.RenameTableStmt:
p.stmtTp = TypeRename
p.flag |= inCreateOrDropTable
p.checkRenameTableGrammar(node)
case *ast.CreateIndexStmt:
p.stmtTp = TypeCreate
p.checkCreateIndexGrammar(node)
case *ast.AlterTableStmt:
p.stmtTp = TypeAlter
p.resolveAlterTableStmt(node)
p.checkAlterTableGrammar(node)
case *ast.CreateDatabaseStmt:
p.stmtTp = TypeCreate
p.checkCreateDatabaseGrammar(node)
case *ast.AlterDatabaseStmt:
p.stmtTp = TypeAlter
p.checkAlterDatabaseGrammar(node)
case *ast.DropDatabaseStmt:
p.stmtTp = TypeDrop
p.checkDropDatabaseGrammar(node)
case *ast.ShowStmt:
p.stmtTp = TypeShow
p.showTp = node.Tp
p.resolveShowStmt(node)
case *ast.SetOprSelectList:
p.checkSetOprSelectList(node)
case *ast.DeleteTableList:
p.stmtTp = TypeDelete
return in, true
case *ast.Join:
p.checkNonUniqTableAlias(node)
case *ast.CreateBindingStmt:
p.stmtTp = TypeCreate
EraseLastSemicolon(node.OriginNode)
EraseLastSemicolon(node.HintedNode)
p.checkBindGrammar(node.OriginNode, node.HintedNode, p.ctx.GetSessionVars().CurrentDB)
return in, true
case *ast.DropBindingStmt:
p.stmtTp = TypeDrop
EraseLastSemicolon(node.OriginNode)
if node.HintedNode != nil {
EraseLastSemicolon(node.HintedNode)
p.checkBindGrammar(node.OriginNode, node.HintedNode, p.ctx.GetSessionVars().CurrentDB)
}
return in, true
case *ast.RecoverTableStmt, *ast.FlashBackTableStmt:
// The specified table in recover table statement maybe already been dropped.
// So skip check table name here, otherwise, recover table [table_name] syntax will return
// table not exists error. But recover table statement is use to recover the dropped table. So skip children here.
return in, true
case *ast.RepairTableStmt:
p.stmtTp = TypeRepair
// The RepairTable should consist of the logic for creating tables and renaming tables.
p.flag |= inRepairTable
p.checkRepairTableGrammar(node)
case *ast.CreateSequenceStmt:
p.stmtTp = TypeCreate
p.flag |= inCreateOrDropTable
p.resolveCreateSequenceStmt(node)
case *ast.DropSequenceStmt:
p.stmtTp = TypeDrop
p.flag |= inCreateOrDropTable
p.checkDropSequenceGrammar(node)
case *ast.FuncCastExpr:
p.checkFuncCastExpr(node)
case *ast.FuncCallExpr:
if node.FnName.L == ast.NextVal || node.FnName.L == ast.LastVal || node.FnName.L == ast.SetVal {
p.flag |= inSequenceFunction
}
case *ast.BRIEStmt:
if node.Kind == ast.BRIEKindRestore {
p.flag |= inCreateOrDropTable
}
case *ast.TableSource:
isModeOracle := p.ctx.GetSessionVars().SQLMode&mysql.ModeOracle != 0
if _, ok := node.Source.(*ast.SelectStmt); ok && !isModeOracle && len(node.AsName.L) == 0 {
p.err = ddl.ErrDerivedMustHaveAlias.GenWithStackByArgs()
}
if v, ok := node.Source.(*ast.TableName); ok && v.TableSample != nil {
switch v.TableSample.SampleMethod {
case ast.SampleMethodTypeTiDBRegion:
default:
p.err = expression.ErrInvalidTableSample.GenWithStackByArgs("Only supports REGIONS sampling method")
}
}
case *ast.GroupByClause:
p.checkGroupBy(node)
case *ast.WithClause:
for _, cte := range node.CTEs {
p.withName[cte.Name.L] = struct{}{}
}
case *ast.BeginStmt:
// If the begin statement was like following:
// start transaction read only as of timestamp ....
// then we need set StmtCtx.IsStaleness as true in order to avoid take tso in PrepareTSFuture.
if node.AsOf != nil {
p.ctx.GetSessionVars().StmtCtx.IsStaleness = true
p.IsStaleness = true
} else if p.ctx.GetSessionVars().TxnReadTS.PeakTxnReadTS() > 0 {
// If the begin statement was like following:
// set transaction read only as of timestamp ...
// begin
// then we need set StmtCtx.IsStaleness as true in order to avoid take tso in PrepareTSFuture.
p.ctx.GetSessionVars().StmtCtx.IsStaleness = true
p.IsStaleness = true
}
default:
p.flag &= ^parentIsJoin
}
return in, p.err != nil
}
// EraseLastSemicolon removes last semicolon of sql.
func EraseLastSemicolon(stmt ast.StmtNode) {
sql := stmt.Text()
if len(sql) > 0 && sql[len(sql)-1] == ';' {
stmt.SetText(nil, sql[:len(sql)-1])
}
}
// EraseLastSemicolonInSQL removes last semicolon of the SQL.
func EraseLastSemicolonInSQL(sql string) string {
if len(sql) > 0 && sql[len(sql)-1] == ';' {
return sql[:len(sql)-1]
}
return sql
}
const (
// TypeInvalid for unexpected types.
TypeInvalid byte = iota
// TypeSelect for SelectStmt.
TypeSelect
// TypeSetOpr for SetOprStmt.
TypeSetOpr
// TypeDelete for DeleteStmt.
TypeDelete
// TypeUpdate for UpdateStmt.
TypeUpdate
// TypeInsert for InsertStmt.
TypeInsert
// TypeDrop for DropStmt
TypeDrop
// TypeCreate for CreateStmt
TypeCreate
// TypeAlter for AlterStmt
TypeAlter
// TypeRename for RenameStmt
TypeRename
// TypeRepair for RepairStmt
TypeRepair
// TypeShow for ShowStmt
TypeShow
// TypeExecute for ExecuteStmt
TypeExecute
)
func bindableStmtType(node ast.StmtNode) byte {
switch node.(type) {
case *ast.SelectStmt:
return TypeSelect
case *ast.SetOprStmt:
return TypeSetOpr
case *ast.DeleteStmt:
return TypeDelete
case *ast.UpdateStmt:
return TypeUpdate
case *ast.InsertStmt:
return TypeInsert
}
return TypeInvalid
}
func (p *preprocessor) tableByName(tn *ast.TableName) (table.Table, error) {
currentDB := p.ctx.GetSessionVars().CurrentDB
if tn.Schema.String() != "" {
currentDB = tn.Schema.L
}
if currentDB == "" {
return nil, errors.Trace(ErrNoDB)
}
sName := model.NewCIStr(currentDB)
is := p.ensureInfoSchema()
// for 'SHOW CREATE VIEW/SEQUENCE ...' statement, ignore local temporary tables.
if p.stmtTp == TypeShow && (p.showTp == ast.ShowCreateView || p.showTp == ast.ShowCreateSequence) {
is = temptable.DetachLocalTemporaryTableInfoSchema(is)
}
tbl, err := is.TableByName(sName, tn.Name)
if err != nil {
// We should never leak that the table doesn't exist (i.e. attach ErrTableNotExists)
// unless we know that the user has permissions to it, should it exist.
// By checking here, this makes all SELECT/SHOW/INSERT/UPDATE/DELETE statements safe.
currentUser, activeRoles := p.ctx.GetSessionVars().User, p.ctx.GetSessionVars().ActiveRoles
if pm := privilege.GetPrivilegeManager(p.ctx); pm != nil {
if !pm.RequestVerification(activeRoles, sName.L, tn.Name.O, "", mysql.AllPrivMask) {
u := currentUser.Username
h := currentUser.Hostname
if currentUser.AuthHostname != "" {
u = currentUser.AuthUsername
h = currentUser.AuthHostname
}
return nil, ErrTableaccessDenied.GenWithStackByArgs(p.stmtType(), u, h, tn.Name.O)
}
}
return nil, err
}
return tbl, err
}
func (p *preprocessor) checkBindGrammar(originNode, hintedNode ast.StmtNode, defaultDB string) {
origTp := bindableStmtType(originNode)
hintedTp := bindableStmtType(hintedNode)
if origTp == TypeInvalid || hintedTp == TypeInvalid {
p.err = errors.Errorf("create binding doesn't support this type of query")
return
}
if origTp != hintedTp {
p.err = errors.Errorf("hinted sql and original sql have different query types")
return
}
if origTp == TypeInsert {
origInsert, hintedInsert := originNode.(*ast.InsertStmt), hintedNode.(*ast.InsertStmt)
if origInsert.Select == nil || hintedInsert.Select == nil {
p.err = errors.Errorf("create binding only supports INSERT / REPLACE INTO SELECT")
return
}
}
// Check the bind operation is not on any temporary table.
tblNames := extractTableList(originNode, nil, false)
for _, tn := range tblNames {
tbl, err := p.tableByName(tn)
if err != nil {
// If the operation is order is: drop table -> drop binding
// The table doesn't exist, it is not an error.
if terror.ErrorEqual(err, infoschema.ErrTableNotExists) {
continue
}
p.err = err
return
}
if tbl.Meta().TempTableType != model.TempTableNone {
p.err = ddl.ErrOptOnTemporaryTable.GenWithStackByArgs("create binding")
return
}
tableInfo := tbl.Meta()
dbInfo, _ := p.ensureInfoSchema().SchemaByTable(tableInfo)
tn.TableInfo = tableInfo
tn.DBInfo = dbInfo
}
originSQL := parser.Normalize(utilparser.RestoreWithDefaultDB(originNode, defaultDB, originNode.Text()))
hintedSQL := parser.Normalize(utilparser.RestoreWithDefaultDB(hintedNode, defaultDB, hintedNode.Text()))
if originSQL != hintedSQL {
p.err = errors.Errorf("hinted sql and origin sql don't match when hinted sql erase the hint info, after erase hint info, originSQL:%s, hintedSQL:%s", originSQL, hintedSQL)
}
}
func (p *preprocessor) Leave(in ast.Node) (out ast.Node, ok bool) {
switch x := in.(type) {
case *ast.CreateTableStmt:
p.flag &= ^inCreateOrDropTable
p.checkAutoIncrement(x)
p.checkContainDotColumn(x)
case *ast.CreateViewStmt:
p.flag &= ^inCreateOrDropTable
case *ast.DropTableStmt, *ast.AlterTableStmt, *ast.RenameTableStmt:
p.flag &= ^inCreateOrDropTable
case *driver.ParamMarkerExpr:
if p.flag&inPrepare == 0 {
p.err = parser.ErrSyntax.GenWithStack("syntax error, unexpected '?'")
return
}
case *ast.ExplainStmt:
if _, ok := x.Stmt.(*ast.ShowStmt); ok {
break
}
valid := false
for i, length := 0, len(types.ExplainFormats); i < length; i++ {
if strings.ToLower(x.Format) == types.ExplainFormats[i] {
valid = true
break
}
}
if !valid {
p.err = ErrUnknownExplainFormat.GenWithStackByArgs(x.Format)
}
case *ast.TableName:
p.handleTableName(x)
case *ast.Join:
if len(p.tableAliasInJoin) > 0 {
p.tableAliasInJoin = p.tableAliasInJoin[:len(p.tableAliasInJoin)-1]
}
case *ast.FuncCallExpr:
// The arguments for builtin NAME_CONST should be constants
// See https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_name-const for details
if x.FnName.L == ast.NameConst {
if len(x.Args) != 2 {
p.err = expression.ErrIncorrectParameterCount.GenWithStackByArgs(x.FnName.L)
} else {
_, isValueExpr1 := x.Args[0].(*driver.ValueExpr)
isValueExpr2 := false
switch x.Args[1].(type) {
case *driver.ValueExpr, *ast.UnaryOperationExpr:
isValueExpr2 = true
}
if !isValueExpr1 || !isValueExpr2 {
p.err = ErrWrongArguments.GenWithStackByArgs("NAME_CONST")
}
}
break
}
// no need sleep when retry transaction and avoid unexpect sleep caused by retry.
if p.flag&inTxnRetry > 0 && x.FnName.L == ast.Sleep {
if len(x.Args) == 1 {
x.Args[0] = ast.NewValueExpr(0, "", "")
}
}
if x.FnName.L == ast.NextVal || x.FnName.L == ast.LastVal || x.FnName.L == ast.SetVal {
p.flag &= ^inSequenceFunction
}
case *ast.RepairTableStmt:
p.flag &= ^inRepairTable
case *ast.CreateSequenceStmt:
p.flag &= ^inCreateOrDropTable
case *ast.BRIEStmt:
if x.Kind == ast.BRIEKindRestore {
p.flag &= ^inCreateOrDropTable
}
}
return in, p.err == nil
}
func checkAutoIncrementOp(colDef *ast.ColumnDef, index int) (bool, error) {
var hasAutoIncrement bool
if colDef.Options[index].Tp == ast.ColumnOptionAutoIncrement {
hasAutoIncrement = true
if len(colDef.Options) == index+1 {
return hasAutoIncrement, nil
}
for _, op := range colDef.Options[index+1:] {
if op.Tp == ast.ColumnOptionDefaultValue {
if tmp, ok := op.Expr.(*driver.ValueExpr); ok {
if !tmp.Datum.IsNull() {
return hasAutoIncrement, errors.Errorf("Invalid default value for '%s'", colDef.Name.Name.O)
}
}
}
}
}
if colDef.Options[index].Tp == ast.ColumnOptionDefaultValue && len(colDef.Options) != index+1 {
if tmp, ok := colDef.Options[index].Expr.(*driver.ValueExpr); ok {
if tmp.Datum.IsNull() {
return hasAutoIncrement, nil
}
}
for _, op := range colDef.Options[index+1:] {
if op.Tp == ast.ColumnOptionAutoIncrement {
return hasAutoIncrement, errors.Errorf("Invalid default value for '%s'", colDef.Name.Name.O)
}
}
}
return hasAutoIncrement, nil
}
func isConstraintKeyTp(constraints []*ast.Constraint, colDef *ast.ColumnDef) bool {
for _, c := range constraints {
if c.Keys[0].Expr != nil {
continue
}
// If the constraint as follows: primary key(c1, c2)
// we only support c1 column can be auto_increment.
if colDef.Name.Name.L != c.Keys[0].Column.Name.L {
continue
}
switch c.Tp {
case ast.ConstraintPrimaryKey, ast.ConstraintKey, ast.ConstraintIndex,
ast.ConstraintUniq, ast.ConstraintUniqIndex, ast.ConstraintUniqKey:
return true
}
}
return false
}
func (p *preprocessor) checkAutoIncrement(stmt *ast.CreateTableStmt) {
autoIncrementCols := make(map[*ast.ColumnDef]bool)
for _, colDef := range stmt.Cols {
var hasAutoIncrement bool
var isKey bool
for i, op := range colDef.Options {
ok, err := checkAutoIncrementOp(colDef, i)
if err != nil {
p.err = err
return
}
if ok {
hasAutoIncrement = true
}
switch op.Tp {
case ast.ColumnOptionPrimaryKey, ast.ColumnOptionUniqKey:
isKey = true
}
}
if hasAutoIncrement {
autoIncrementCols[colDef] = isKey
}
}
if len(autoIncrementCols) < 1 {
return
}
if len(autoIncrementCols) > 1 {
p.err = autoid.ErrWrongAutoKey.GenWithStackByArgs()
return
}
// Only have one auto_increment col.
for col, isKey := range autoIncrementCols {
if !isKey {
isKey = isConstraintKeyTp(stmt.Constraints, col)
}
autoIncrementMustBeKey := true
for _, opt := range stmt.Options {
if opt.Tp == ast.TableOptionEngine && strings.EqualFold(opt.StrValue, "MyISAM") {
autoIncrementMustBeKey = false
}
}
if autoIncrementMustBeKey && !isKey {
p.err = autoid.ErrWrongAutoKey.GenWithStackByArgs()
}
switch col.Tp.Tp {
case mysql.TypeTiny, mysql.TypeShort, mysql.TypeLong,
mysql.TypeFloat, mysql.TypeDouble, mysql.TypeLonglong, mysql.TypeInt24:
default:
p.err = errors.Errorf("Incorrect column specifier for column '%s'", col.Name.Name.O)
}
}
}
// checkSetOprSelectList checks union's selectList.
// refer: https://dev.mysql.com/doc/refman/5.7/en/union.html
// https://mariadb.com/kb/en/intersect/
// https://mariadb.com/kb/en/except/
// "To apply ORDER BY or LIMIT to an individual SELECT, place the clause inside the parentheses that enclose the SELECT."
func (p *preprocessor) checkSetOprSelectList(stmt *ast.SetOprSelectList) {
for _, sel := range stmt.Selects[:len(stmt.Selects)-1] {
switch s := sel.(type) {
case *ast.SelectStmt:
if s.SelectIntoOpt != nil {
p.err = ErrWrongUsage.GenWithStackByArgs("UNION", "INTO")
return
}
if s.IsInBraces {
continue
}
if s.Limit != nil {
p.err = ErrWrongUsage.GenWithStackByArgs("UNION", "LIMIT")
return
}
if s.OrderBy != nil {
p.err = ErrWrongUsage.GenWithStackByArgs("UNION", "ORDER BY")
return
}
case *ast.SetOprSelectList:
p.checkSetOprSelectList(s)
}
}
}
func (p *preprocessor) checkCreateDatabaseGrammar(stmt *ast.CreateDatabaseStmt) {
if isIncorrectName(stmt.Name) {
p.err = ddl.ErrWrongDBName.GenWithStackByArgs(stmt.Name)
}
}
func (p *preprocessor) checkAlterDatabaseGrammar(stmt *ast.AlterDatabaseStmt) {
// for 'ALTER DATABASE' statement, database name can be empty to alter default database.
if isIncorrectName(stmt.Name) && !stmt.AlterDefaultDatabase {
p.err = ddl.ErrWrongDBName.GenWithStackByArgs(stmt.Name)
}
}
func (p *preprocessor) checkDropDatabaseGrammar(stmt *ast.DropDatabaseStmt) {
if isIncorrectName(stmt.Name) {
p.err = ddl.ErrWrongDBName.GenWithStackByArgs(stmt.Name)
}
}
func (p *preprocessor) checkAdminCheckTableGrammar(stmt *ast.AdminStmt) {
for _, table := range stmt.Tables {
tableInfo, err := p.tableByName(table)
if err != nil {
p.err = err
return
}
tempTableType := tableInfo.Meta().TempTableType
if (stmt.Tp == ast.AdminCheckTable || stmt.Tp == ast.AdminChecksumTable || stmt.Tp == ast.AdminCheckIndex) && tempTableType != model.TempTableNone {
if stmt.Tp == ast.AdminChecksumTable {
p.err = ErrOptOnTemporaryTable.GenWithStackByArgs("admin checksum table")
} else if stmt.Tp == ast.AdminCheckTable {
p.err = ErrOptOnTemporaryTable.GenWithStackByArgs("admin check table")
} else {
p.err = ErrOptOnTemporaryTable.GenWithStackByArgs("admin check index")
}
return
}
}
}
func (p *preprocessor) checkCreateTableGrammar(stmt *ast.CreateTableStmt) {
if stmt.ReferTable != nil {
schema := model.NewCIStr(p.ctx.GetSessionVars().CurrentDB)
if stmt.ReferTable.Schema.String() != "" {
schema = stmt.ReferTable.Schema
}
// get the infoschema from the context.
tableInfo, err := p.ensureInfoSchema().TableByName(schema, stmt.ReferTable.Name)
if err != nil {
p.err = err
return
}
tableMetaInfo := tableInfo.Meta()
if tableMetaInfo.TempTableType != model.TempTableNone {
p.err = ErrOptOnTemporaryTable.GenWithStackByArgs("create table like")
return
}
if stmt.TemporaryKeyword != ast.TemporaryNone {
err := checkReferInfoForTemporaryTable(tableMetaInfo)
if err != nil {
p.err = err
return
}
}
}
if stmt.TemporaryKeyword != ast.TemporaryNone {
for _, opt := range stmt.Options {
switch opt.Tp {
case ast.TableOptionShardRowID:
p.err = ErrOptOnTemporaryTable.GenWithStackByArgs("shard_row_id_bits")
return
case ast.TableOptionPlacementPolicy:
p.err = ErrOptOnTemporaryTable.GenWithStackByArgs("PLACEMENT")
return
}
}
}
tName := stmt.Table.Name.String()
if isIncorrectName(tName) {
p.err = ddl.ErrWrongTableName.GenWithStackByArgs(tName)
return
}
countPrimaryKey := 0
for _, colDef := range stmt.Cols {
if err := checkColumn(colDef); err != nil {
p.err = err
return
}
isPrimary, err := checkColumnOptions(stmt.TemporaryKeyword != ast.TemporaryNone, colDef.Options)
if err != nil {
p.err = err
return
}
countPrimaryKey += isPrimary
if countPrimaryKey > 1 {
p.err = infoschema.ErrMultiplePriKey
return
}
}
for _, constraint := range stmt.Constraints {
switch tp := constraint.Tp; tp {
case ast.ConstraintKey, ast.ConstraintIndex, ast.ConstraintUniq, ast.ConstraintUniqKey, ast.ConstraintUniqIndex:
err := checkIndexInfo(constraint.Name, constraint.Keys)
if err != nil {
p.err = err
return
}
if constraint.IsEmptyIndex {
p.err = ddl.ErrWrongNameForIndex.GenWithStackByArgs(constraint.Name)
return
}
case ast.ConstraintPrimaryKey:
if countPrimaryKey > 0 {
p.err = infoschema.ErrMultiplePriKey
return
}
countPrimaryKey++
err := checkIndexInfo(constraint.Name, constraint.Keys)
if err != nil {
p.err = err
return
}
}
}
if p.err = checkUnsupportedTableOptions(stmt.Options); p.err != nil {
return
}
if stmt.Select != nil {
// FIXME: a temp error noticing 'not implemented' (issue 4754)
p.err = errors.New("'CREATE TABLE ... SELECT' is not implemented yet")
return
} else if len(stmt.Cols) == 0 && stmt.ReferTable == nil {
p.err = ddl.ErrTableMustHaveColumns
return
}
}
func (p *preprocessor) checkCreateViewGrammar(stmt *ast.CreateViewStmt) {
vName := stmt.ViewName.Name.String()
if isIncorrectName(vName) {
p.err = ddl.ErrWrongTableName.GenWithStackByArgs(vName)
return
}
for _, col := range stmt.Cols {
if isIncorrectName(col.String()) {
p.err = ddl.ErrWrongColumnName.GenWithStackByArgs(col)
return
}
}
}
func (p *preprocessor) checkCreateViewWithSelect(stmt ast.Node) {
switch s := stmt.(type) {
case *ast.SelectStmt:
if s.SelectIntoOpt != nil {
p.err = ddl.ErrViewSelectClause.GenWithStackByArgs("INFO")
return
}
if s.LockInfo != nil && s.LockInfo.LockType != ast.SelectLockNone {
s.LockInfo.LockType = ast.SelectLockNone
return
}
case *ast.SetOprSelectList:
for _, sel := range s.Selects {
p.checkCreateViewWithSelect(sel)
}
}
}
func (p *preprocessor) checkCreateViewWithSelectGrammar(stmt *ast.CreateViewStmt) {
switch stmt := stmt.Select.(type) {
case *ast.SelectStmt:
p.checkCreateViewWithSelect(stmt)
case *ast.SetOprStmt:
for _, selectStmt := range stmt.SelectList.Selects {
p.checkCreateViewWithSelect(selectStmt)
if p.err != nil {
return
}
}
}
}
func (p *preprocessor) checkDropSequenceGrammar(stmt *ast.DropSequenceStmt) {
p.checkDropTableNames(stmt.Sequences)
}
func (p *preprocessor) checkDropTableGrammar(stmt *ast.DropTableStmt) {
p.checkDropTableNames(stmt.Tables)
if stmt.TemporaryKeyword != ast.TemporaryNone {
p.checkDropTemporaryTableGrammar(stmt)
}
}
func (p *preprocessor) checkDropTemporaryTableGrammar(stmt *ast.DropTableStmt) {
currentDB := model.NewCIStr(p.ctx.GetSessionVars().CurrentDB)
for _, t := range stmt.Tables {
if isIncorrectName(t.Name.String()) {
p.err = ddl.ErrWrongTableName.GenWithStackByArgs(t.Name.String())
return
}
schema := t.Schema
if schema.L == "" {
schema = currentDB
}
tbl, err := p.ensureInfoSchema().TableByName(schema, t.Name)
if infoschema.ErrTableNotExists.Equal(err) {
// Non-exist table will be checked in ddl executor
continue
}
if err != nil {
p.err = err
return
}
tblInfo := tbl.Meta()
if stmt.TemporaryKeyword == ast.TemporaryGlobal && tblInfo.TempTableType != model.TempTableGlobal {
p.err = ErrDropTableOnTemporaryTable
return
}
}
}
func (p *preprocessor) checkDropTableNames(tables []*ast.TableName) {
for _, t := range tables {
if isIncorrectName(t.Name.String()) {
p.err = ddl.ErrWrongTableName.GenWithStackByArgs(t.Name.String())
return
}
}
}
func (p *preprocessor) checkNonUniqTableAlias(stmt *ast.Join) {
if p.flag&parentIsJoin == 0 {
p.tableAliasInJoin = append(p.tableAliasInJoin, make(map[string]interface{}))
}
tableAliases := p.tableAliasInJoin[len(p.tableAliasInJoin)-1]
isOracleMode := p.ctx.GetSessionVars().SQLMode&mysql.ModeOracle != 0
if !isOracleMode {
if err := isTableAliasDuplicate(stmt.Left, tableAliases); err != nil {
p.err = err
return
}
if err := isTableAliasDuplicate(stmt.Right, tableAliases); err != nil {
p.err = err
return
}
}
p.flag |= parentIsJoin
}
func isTableAliasDuplicate(node ast.ResultSetNode, tableAliases map[string]interface{}) error {
if ts, ok := node.(*ast.TableSource); ok {
tabName := ts.AsName
if tabName.L == "" {
if tableNode, ok := ts.Source.(*ast.TableName); ok {
if tableNode.Schema.L != "" {
tabName = model.NewCIStr(fmt.Sprintf("%s.%s", tableNode.Schema.L, tableNode.Name.L))
} else {
tabName = tableNode.Name
}
}
}
_, exists := tableAliases[tabName.L]
if len(tabName.L) != 0 && exists {
return ErrNonUniqTable.GenWithStackByArgs(tabName)
}
tableAliases[tabName.L] = nil
}
return nil
}
func checkColumnOptions(isTempTable bool, ops []*ast.ColumnOption) (int, error) {
isPrimary, isGenerated, isStored := 0, 0, false
for _, op := range ops {
switch op.Tp {
case ast.ColumnOptionPrimaryKey:
isPrimary = 1
case ast.ColumnOptionGenerated:
isGenerated = 1
isStored = op.Stored
case ast.ColumnOptionAutoRandom:
if isTempTable {
return isPrimary, ErrOptOnTemporaryTable.GenWithStackByArgs("auto_random")
}
}
}
if isPrimary > 0 && isGenerated > 0 && !isStored {
return isPrimary, ErrUnsupportedOnGeneratedColumn.GenWithStackByArgs("Defining a virtual generated column as primary key")
}