forked from xwb1989/sqlparser
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathast_rewriting.go
555 lines (494 loc) · 15.5 KB
/
ast_rewriting.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
/*
Copyright 2020 The Vitess Authors.
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 sqlparser
import (
"strconv"
"strings"
querypb "vitess.io/vitess/go/vt/proto/query"
vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc"
"vitess.io/vitess/go/vt/sysvars"
"vitess.io/vitess/go/vt/vterrors"
)
var HasValueSubQueryBaseName = []byte("__sq_has_values")
// SQLSelectLimitUnset default value for sql_select_limit not set.
const SQLSelectLimitUnset = -1
// RewriteASTResult contains the rewritten ast and meta information about it
type RewriteASTResult struct {
*BindVarNeeds
AST Statement // The rewritten AST
}
type VSchemaViews interface {
FindView(name TableName) SelectStatement
}
// PrepareAST will normalize the query
func PrepareAST(
in Statement,
reservedVars *ReservedVars,
bindVars map[string]*querypb.BindVariable,
parameterize bool,
keyspace string,
selectLimit int,
setVarComment string,
sysVars map[string]string,
fkChecksState *bool,
views VSchemaViews,
) (*RewriteASTResult, error) {
if parameterize {
err := Normalize(in, reservedVars, bindVars)
if err != nil {
return nil, err
}
}
return RewriteAST(in, keyspace, selectLimit, setVarComment, sysVars, fkChecksState, views)
}
// RewriteAST rewrites the whole AST, replacing function calls and adding column aliases to queries.
// SET_VAR comments are also added to the AST if required.
func RewriteAST(
in Statement,
keyspace string,
selectLimit int,
setVarComment string,
sysVars map[string]string,
fkChecksState *bool,
views VSchemaViews,
) (*RewriteASTResult, error) {
er := newASTRewriter(keyspace, selectLimit, setVarComment, sysVars, fkChecksState, views)
er.shouldRewriteDatabaseFunc = shouldRewriteDatabaseFunc(in)
result := SafeRewrite(in, er.rewriteDown, er.rewriteUp)
if er.err != nil {
return nil, er.err
}
out, ok := result.(Statement)
if !ok {
return nil, vterrors.Errorf(vtrpcpb.Code_INTERNAL, "statement rewriting returned a non statement: %s", String(out))
}
r := &RewriteASTResult{
AST: out,
BindVarNeeds: er.bindVars,
}
return r, nil
}
func shouldRewriteDatabaseFunc(in Statement) bool {
selct, ok := in.(*Select)
if !ok {
return false
}
if len(selct.From) != 1 {
return false
}
aliasedTable, ok := selct.From[0].(*AliasedTableExpr)
if !ok {
return false
}
tableName, ok := aliasedTable.Expr.(TableName)
if !ok {
return false
}
return tableName.Name.String() == "dual"
}
type astRewriter struct {
bindVars *BindVarNeeds
shouldRewriteDatabaseFunc bool
err error
// we need to know this to make a decision if we can safely rewrite JOIN USING => JOIN ON
hasStarInSelect bool
keyspace string
selectLimit int
setVarComment string
fkChecksState *bool
sysVars map[string]string
views VSchemaViews
}
func newASTRewriter(keyspace string, selectLimit int, setVarComment string, sysVars map[string]string, fkChecksState *bool, views VSchemaViews) *astRewriter {
return &astRewriter{
bindVars: &BindVarNeeds{},
keyspace: keyspace,
selectLimit: selectLimit,
setVarComment: setVarComment,
fkChecksState: fkChecksState,
sysVars: sysVars,
views: views,
}
}
const (
// LastInsertIDName is a reserved bind var name for last_insert_id()
LastInsertIDName = "__lastInsertId"
// DBVarName is a reserved bind var name for database()
DBVarName = "__vtdbname"
// FoundRowsName is a reserved bind var name for found_rows()
FoundRowsName = "__vtfrows"
// RowCountName is a reserved bind var name for row_count()
RowCountName = "__vtrcount"
// UserDefinedVariableName is what we prepend bind var names for user defined variables
UserDefinedVariableName = "__vtudv"
)
func (er *astRewriter) rewriteAliasedExpr(node *AliasedExpr) (*BindVarNeeds, error) {
inner := newASTRewriter(er.keyspace, er.selectLimit, er.setVarComment, er.sysVars, nil, er.views)
inner.shouldRewriteDatabaseFunc = er.shouldRewriteDatabaseFunc
tmp := SafeRewrite(node.Expr, inner.rewriteDown, inner.rewriteUp)
newExpr, ok := tmp.(Expr)
if !ok {
return nil, vterrors.Errorf(vtrpcpb.Code_INTERNAL, "failed to rewrite AST. function expected to return Expr returned a %s", String(tmp))
}
node.Expr = newExpr
return inner.bindVars, nil
}
func (er *astRewriter) rewriteDown(node SQLNode, _ SQLNode) bool {
switch node := node.(type) {
case *Select:
er.visitSelect(node)
case *PrepareStmt, *ExecuteStmt:
return false // nothing to rewrite here.
}
return true
}
func (er *astRewriter) rewriteUp(cursor *Cursor) bool {
// Add SET_VAR comment to this node if it supports it and is needed
if supportOptimizerHint, supportsOptimizerHint := cursor.Node().(SupportOptimizerHint); supportsOptimizerHint {
if er.setVarComment != "" {
newComments, err := supportOptimizerHint.GetParsedComments().AddQueryHint(er.setVarComment)
if err != nil {
er.err = err
return false
}
supportOptimizerHint.SetComments(newComments)
}
if er.fkChecksState != nil {
newComments := supportOptimizerHint.GetParsedComments().SetMySQLSetVarValue(sysvars.ForeignKeyChecks, FkChecksStateString(er.fkChecksState))
supportOptimizerHint.SetComments(newComments)
}
}
switch node := cursor.Node().(type) {
case *Union:
er.rewriteUnion(node)
case *FuncExpr:
er.funcRewrite(cursor, node)
case *Variable:
er.rewriteVariable(cursor, node)
case *Subquery:
er.unnestSubQueries(cursor, node)
case *NotExpr:
er.rewriteNotExpr(cursor, node)
case *AliasedTableExpr:
er.rewriteAliasedTable(cursor, node)
case *ShowBasic:
er.rewriteShowBasic(node)
case *ExistsExpr:
er.existsRewrite(cursor, node)
case DistinctableAggr:
er.rewriteDistinctableAggr(cursor, node)
}
return true
}
func (er *astRewriter) rewriteUnion(node *Union) {
// set select limit if explicitly not set when sql_select_limit is set on the connection.
if er.selectLimit > 0 && node.Limit == nil {
node.Limit = &Limit{Rowcount: NewIntLiteral(strconv.Itoa(er.selectLimit))}
}
}
func (er *astRewriter) rewriteAliasedTable(cursor *Cursor, node *AliasedTableExpr) {
aliasTableName, ok := node.Expr.(TableName)
if !ok {
return
}
// Qualifier should not be added to dual table
tblName := aliasTableName.Name.String()
if tblName == "dual" {
return
}
if SystemSchema(er.keyspace) {
if aliasTableName.Qualifier.IsEmpty() {
aliasTableName.Qualifier = NewIdentifierCS(er.keyspace)
node.Expr = aliasTableName
cursor.Replace(node)
}
return
}
// Could we be dealing with a view?
if er.views == nil {
return
}
view := er.views.FindView(aliasTableName)
if view == nil {
return
}
// Aha! It's a view. Let's replace it with a derived table
node.Expr = &DerivedTable{Select: CloneSelectStatement(view)}
if node.As.IsEmpty() {
node.As = NewIdentifierCS(tblName)
}
}
func (er *astRewriter) rewriteShowBasic(node *ShowBasic) {
if node.Command == VariableGlobal || node.Command == VariableSession {
varsToAdd := sysvars.GetInterestingVariables()
for _, sysVar := range varsToAdd {
er.bindVars.AddSysVar(sysVar)
}
}
}
func (er *astRewriter) rewriteNotExpr(cursor *Cursor, node *NotExpr) {
switch inner := node.Expr.(type) {
case *ComparisonExpr:
// not col = 42 => col != 42
// not col > 42 => col <= 42
// etc
canChange, inverse := inverseOp(inner.Operator)
if canChange {
inner.Operator = inverse
cursor.Replace(inner)
}
case *NotExpr:
// not not true => true
cursor.Replace(inner.Expr)
case BoolVal:
// not true => false
inner = !inner
cursor.Replace(inner)
}
}
func (er *astRewriter) rewriteVariable(cursor *Cursor, node *Variable) {
// Iff we are in SET, we want to change the scope of variables if a modifier has been set
// and only on the lhs of the assignment:
// set session sql_mode = @someElse
// here we need to change the scope of `sql_mode` and not of `@someElse`
if v, isSet := cursor.Parent().(*SetExpr); isSet && v.Var == node {
return
}
switch node.Scope {
case VariableScope:
er.udvRewrite(cursor, node)
case GlobalScope, SessionScope, NextTxScope:
er.sysVarRewrite(cursor, node)
}
}
func (er *astRewriter) visitSelect(node *Select) {
for _, col := range node.SelectExprs {
if _, hasStar := col.(*StarExpr); hasStar {
er.hasStarInSelect = true
continue
}
aliasedExpr, ok := col.(*AliasedExpr)
if !ok || aliasedExpr.As.NotEmpty() {
continue
}
buf := NewTrackedBuffer(nil)
aliasedExpr.Expr.Format(buf)
// select last_insert_id() -> select :__lastInsertId as `last_insert_id()`
innerBindVarNeeds, err := er.rewriteAliasedExpr(aliasedExpr)
if err != nil {
er.err = err
return
}
if innerBindVarNeeds.HasRewrites() {
aliasedExpr.As = NewIdentifierCI(buf.String())
}
er.bindVars.MergeWith(innerBindVarNeeds)
}
// set select limit if explicitly not set when sql_select_limit is set on the connection.
if er.selectLimit > 0 && node.Limit == nil {
node.Limit = &Limit{Rowcount: NewIntLiteral(strconv.Itoa(er.selectLimit))}
}
}
func inverseOp(i ComparisonExprOperator) (bool, ComparisonExprOperator) {
switch i {
case EqualOp:
return true, NotEqualOp
case LessThanOp:
return true, GreaterEqualOp
case GreaterThanOp:
return true, LessEqualOp
case LessEqualOp:
return true, GreaterThanOp
case GreaterEqualOp:
return true, LessThanOp
case NotEqualOp:
return true, EqualOp
case InOp:
return true, NotInOp
case NotInOp:
return true, InOp
case LikeOp:
return true, NotLikeOp
case NotLikeOp:
return true, LikeOp
case RegexpOp:
return true, NotRegexpOp
case NotRegexpOp:
return true, RegexpOp
}
return false, i
}
func (er *astRewriter) sysVarRewrite(cursor *Cursor, node *Variable) {
lowered := node.Name.Lowered()
var found bool
if er.sysVars != nil {
_, found = er.sysVars[lowered]
}
switch lowered {
case sysvars.Autocommit.Name,
sysvars.Charset.Name,
sysvars.ClientFoundRows.Name,
sysvars.DDLStrategy.Name,
sysvars.MigrationContext.Name,
sysvars.Names.Name,
sysvars.TransactionMode.Name,
sysvars.ReadAfterWriteGTID.Name,
sysvars.ReadAfterWriteTimeOut.Name,
sysvars.SessionEnableSystemSettings.Name,
sysvars.SessionTrackGTIDs.Name,
sysvars.SessionUUID.Name,
sysvars.SkipQueryPlanCache.Name,
sysvars.Socket.Name,
sysvars.SQLSelectLimit.Name,
sysvars.Version.Name,
sysvars.VersionComment.Name,
sysvars.QueryTimeout.Name,
sysvars.Workload.Name:
found = true
}
if found {
cursor.Replace(bindVarExpression("__vt" + lowered))
er.bindVars.AddSysVar(lowered)
}
}
func (er *astRewriter) udvRewrite(cursor *Cursor, node *Variable) {
udv := strings.ToLower(node.Name.CompliantName())
cursor.Replace(bindVarExpression(UserDefinedVariableName + udv))
er.bindVars.AddUserDefVar(udv)
}
var funcRewrites = map[string]string{
"last_insert_id": LastInsertIDName,
"database": DBVarName,
"schema": DBVarName,
"found_rows": FoundRowsName,
"row_count": RowCountName,
}
func (er *astRewriter) funcRewrite(cursor *Cursor, node *FuncExpr) {
lowered := node.Name.Lowered()
if lowered == "last_insert_id" && len(node.Exprs) > 0 {
// if we are dealing with is LAST_INSERT_ID() with an argument, we don't need to rewrite it.
// with an argument, this is an identity function that will update the session state and
// sets the correct fields in the OK TCP packet that we send back
return
}
bindVar, found := funcRewrites[lowered]
if !found || (bindVar == DBVarName && !er.shouldRewriteDatabaseFunc) {
return
}
if len(node.Exprs) > 0 {
er.err = vterrors.Errorf(vtrpcpb.Code_UNIMPLEMENTED, "Argument to %s() not supported", lowered)
return
}
cursor.Replace(bindVarExpression(bindVar))
er.bindVars.AddFuncResult(bindVar)
}
func (er *astRewriter) unnestSubQueries(cursor *Cursor, subquery *Subquery) {
if _, isExists := cursor.Parent().(*ExistsExpr); isExists {
return
}
sel, isSimpleSelect := subquery.Select.(*Select)
if !isSimpleSelect {
return
}
if len(sel.SelectExprs) != 1 ||
len(sel.OrderBy) != 0 ||
sel.GroupBy != nil ||
len(sel.From) != 1 ||
sel.Where != nil ||
sel.Having != nil ||
sel.Limit != nil || sel.Lock != NoLock {
return
}
aliasedTable, ok := sel.From[0].(*AliasedTableExpr)
if !ok {
return
}
table, ok := aliasedTable.Expr.(TableName)
if !ok || table.Name.String() != "dual" {
return
}
expr, ok := sel.SelectExprs[0].(*AliasedExpr)
if !ok {
return
}
_, isColName := expr.Expr.(*ColName)
if isColName {
// If we find a single col-name in a `dual` subquery, we can be pretty sure the user is returning a column
// already projected.
// `select 1 as x, (select x)`
// is perfectly valid - any aliased columns to the left are available inside subquery scopes
return
}
er.bindVars.NoteRewrite()
// we need to make sure that the inner expression also gets rewritten,
// so we fire off another rewriter traversal here
rewritten := SafeRewrite(expr.Expr, er.rewriteDown, er.rewriteUp)
// Here we need to handle the subquery rewrite in case in occurs in an IN clause
// For example, SELECT id FROM user WHERE id IN (SELECT 1 FROM DUAL)
// Here we cannot rewrite the query to SELECT id FROM user WHERE id IN 1, since that is syntactically wrong
// We must rewrite it to SELECT id FROM user WHERE id IN (1)
// Find more cases in the test file
rewrittenExpr, isExpr := rewritten.(Expr)
_, isColTuple := rewritten.(ColTuple)
comparisonExpr, isCompExpr := cursor.Parent().(*ComparisonExpr)
// Check that the parent is a comparison operator with IN or NOT IN operation.
// Also, if rewritten is already a ColTuple (like a subquery), then we do not need this
// We also need to check that rewritten is an Expr, if it is then we can rewrite it as a ValTuple
if isCompExpr && (comparisonExpr.Operator == InOp || comparisonExpr.Operator == NotInOp) && !isColTuple && isExpr {
cursor.Replace(ValTuple{rewrittenExpr})
return
}
cursor.Replace(rewritten)
}
func (er *astRewriter) existsRewrite(cursor *Cursor, node *ExistsExpr) {
sel, ok := node.Subquery.Select.(*Select)
if !ok {
return
}
if sel.Having != nil {
// If the query has HAVING, we can't take any shortcuts
return
}
if sel.GroupBy == nil && sel.SelectExprs.AllAggregation() {
// in these situations, we are guaranteed to always get a non-empty result,
// so we can replace the EXISTS with a literal true
cursor.Replace(BoolVal(true))
}
// If we are not doing HAVING, we can safely replace all select expressions with a
// single `1` and remove any grouping
sel.SelectExprs = SelectExprs{
&AliasedExpr{Expr: NewIntLiteral("1")},
}
sel.GroupBy = nil
}
// rewriteDistinctableAggr removed Distinct from Max and Min Aggregations as it does not impact the result. But, makes the plan simpler.
func (er *astRewriter) rewriteDistinctableAggr(cursor *Cursor, node DistinctableAggr) {
if !node.IsDistinct() {
return
}
switch aggr := node.(type) {
case *Max, *Min:
aggr.SetDistinct(false)
er.bindVars.NoteRewrite()
}
}
func bindVarExpression(name string) Expr {
return NewArgument(name)
}
// SystemSchema returns true if the schema passed is system schema
func SystemSchema(schema string) bool {
return strings.EqualFold(schema, "information_schema") ||
strings.EqualFold(schema, "performance_schema") ||
strings.EqualFold(schema, "sys") ||
strings.EqualFold(schema, "mysql")
}