forked from XiaoMi/soar
/
rewrite.go
1728 lines (1583 loc) · 47.8 KB
/
rewrite.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 2018 Xiaomi, 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 ast
import (
"bytes"
"encoding/json"
"fmt"
"reflect"
"regexp"
"strings"
"github.com/XiaoMi/soar/common"
"github.com/kr/pretty"
"vitess.io/vitess/go/vt/sqlparser"
)
// Rule SQL重写规则
type Rule struct {
Name string `json:"Name"`
Description string `json:"Description"`
Original string `json:"Original"` // 错误示范。为空或"暂不支持"不会出现在list-rewrite-rules中
Suggest string `json:"Suggest"` // 正确示范。
Func func(*Rewrite) *Rewrite `json:"-"` // 如果不定义Func需要多条SQL联动改写
}
// RewriteRules SQL重写规则,注意这个规则是有序的,先后顺序不能乱
var RewriteRules = []Rule{
{
Name: "dml2select",
Description: "将数据库更新请求转换为只读查询请求,便于执行EXPLAIN",
Original: "DELETE FROM film WHERE length > 100",
Suggest: "select * from film where length > 100",
Func: (*Rewrite).RewriteDML2Select,
},
{
Name: "star2columns",
Description: "为SELECT *补全表的列信息",
Original: "SELECT * FROM film",
Suggest: "select film.film_id, film.title from film",
Func: (*Rewrite).RewriteStar2Columns,
},
{
Name: "insertcolumns",
Description: "为INSERT补全表的列信息",
Original: "insert into film values(1,2,3,4,5)",
Suggest: "insert into film(film_id, title, description, release_year, language_id) values (1, 2, 3, 4, 5)",
Func: (*Rewrite).RewriteInsertColumns,
},
{
Name: "having",
Description: "将查询的HAVING子句改写为WHERE中的查询条件",
Original: "SELECT state, COUNT(*) FROM Drivers GROUP BY state HAVING state IN ('GA', 'TX') ORDER BY state",
Suggest: "select state, COUNT(*) from Drivers where state in ('GA', 'TX') group by state order by state asc",
Func: (*Rewrite).RewriteHaving,
},
{
Name: "orderbynull",
Description: "如果GROUP BY语句不指定ORDER BY条件会导致无谓的排序产生,如果不需要排序建议添加ORDER BY NULL",
Original: "SELECT sum(col1) FROM tbl GROUP BY col",
Suggest: "select sum(col1) from tbl group by col order by null",
Func: (*Rewrite).RewriteAddOrderByNull,
},
{
Name: "unionall",
Description: "可以接受重复的时间,使用UNION ALL替代UNION以提高查询效率",
Original: "select country_id from city union select country_id from country",
Suggest: "select country_id from city union all select country_id from country",
Func: (*Rewrite).RewriteUnionAll,
},
{
Name: "or2in",
Description: "将同一列不同条件的OR查询转写为IN查询",
Original: "select country_id from city where col1 = 1 or (col2 = 1 or col2 = 2 ) or col1 = 3;",
Suggest: "select country_id from city where (col2 in (1, 2)) or col1 in (1, 3);",
Func: (*Rewrite).RewriteOr2In,
},
{
Name: "innull",
Description: "如果IN条件中可能有NULL值而又想匹配NULL值时,建议添加OR col IS NULL",
Original: "暂不支持",
Suggest: "暂不支持",
Func: (*Rewrite).RewriteInNull,
},
// 把所有跟or相关的重写完之后才进行or转union的重写
{
Name: "or2union",
Description: "将不同列的OR查询转为UNION查询,建议结合unionall重写策略一起使用",
Original: "暂不支持",
Suggest: "暂不支持",
Func: (*Rewrite).RewriteOr2Union,
},
{
Name: "dmlorderby",
Description: "删除DML更新操作中无意义的ORDER BY",
Original: "DELETE FROM tbl WHERE col1=1 ORDER BY col",
Suggest: "delete from tbl where col1 = 1",
Func: (*Rewrite).RewriteRemoveDMLOrderBy,
},
/*
{
Name: "groupbyconst",
Description: "删除无意义的GROUP BY常量",
Original: "SELECT sum(col1) FROM tbl GROUP BY 1;",
Suggest: "select sum(col1) from tbl",
Func: (*Rewrite).RewriteGroupByConst,
},
*/
{
Name: "sub2join",
Description: "将子查询转换为JOIN查询",
Original: "暂不支持",
Suggest: "暂不支持",
Func: (*Rewrite).RewriteSubQuery2Join,
},
{
Name: "join2sub",
Description: "将JOIN查询转换为子查询",
Original: "暂不支持",
Suggest: "暂不支持",
Func: (*Rewrite).RewriteJoin2SubQuery,
},
{
Name: "distinctstar",
Description: "DISTINCT *对有主键的表没有意义,可以将DISTINCT删掉",
Original: "SELECT DISTINCT * FROM film;",
Suggest: "SELECT * FROM film",
Func: (*Rewrite).RewriteDistinctStar,
},
{
Name: "standard",
Description: "SQL标准化,如:关键字转换为小写",
Original: "SELECT sum(col1) FROM tbl GROUP BY 1;",
Suggest: "select sum(col1) from tbl group by 1",
Func: (*Rewrite).RewriteStandard,
},
{
Name: "mergealter",
Description: "合并同一张表的多条ALTER语句",
Original: "ALTER TABLE t2 DROP COLUMN c;ALTER TABLE t2 DROP COLUMN d;",
Suggest: "ALTER TABLE t2 DROP COLUMN c, DROP COLUMN d;",
},
{
Name: "alwaystrue",
Description: "删除无用的恒真判断条件",
Original: "SELECT count(col) FROM tbl where 'a'= 'a' or ('b' = 'b' and a = 'b');",
Suggest: "select count(col) from tbl where (a = 'b');",
Func: (*Rewrite).RewriteAlwaysTrue,
},
{
Name: "countstar",
Description: "不建议使用COUNT(col)或COUNT(常量),建议改写为COUNT(*)",
Original: "SELECT count(col) FROM tbl GROUP BY 1;",
Suggest: "SELECT count(*) FROM tbl GROUP BY 1;",
Func: (*Rewrite).RewriteCountStar,
},
{
Name: "innodb",
Description: "建表时建议使用InnoDB引擎,非InnoDB引擎表自动转InnoDB",
Original: "CREATE TABLE t1(id bigint(20) NOT NULL AUTO_INCREMENT);",
Suggest: "create table t1 (\n\tid bigint(20) not null auto_increment\n) ENGINE=InnoDB;",
Func: (*Rewrite).RewriteInnoDB,
},
{
Name: "autoincrement",
Description: "将autoincrement初始化为1",
Original: "CREATE TABLE t1(id bigint(20) NOT NULL AUTO_INCREMENT) ENGINE=InnoDB AUTO_INCREMENT=123802;",
Suggest: "create table t1(id bigint(20) not null auto_increment) ENGINE=InnoDB auto_increment=1;",
Func: (*Rewrite).RewriteAutoIncrement,
},
{
Name: "intwidth",
Description: "整型数据类型修改默认显示宽度",
Original: "create table t1 (id int(20) not null auto_increment) ENGINE=InnoDB;",
Suggest: "create table t1 (id int(10) not null auto_increment) ENGINE=InnoDB;",
Func: (*Rewrite).RewriteIntWidth,
},
{
Name: "truncate",
Description: "不带WHERE条件的DELETE操作建议修改为TRUNCATE",
Original: "DELETE FROM tbl",
Suggest: "truncate table tbl",
Func: (*Rewrite).RewriteTruncate,
},
{
Name: "rmparenthesis",
Description: "去除没有意义的括号",
Original: "select col from table where (col = 1);",
Suggest: "select col from table where col = 1;",
Func: (*Rewrite).RewriteRmParenthesis,
},
// delimiter要放在最后,不然补不上
{
Name: "delimiter",
Description: "补全DELIMITER",
Original: "use sakila",
Suggest: "use sakila;",
Func: (*Rewrite).RewriteDelimiter,
},
// TODO in to exists
// TODO exists to in
}
// ListRewriteRules 打印SQL重写规则
func ListRewriteRules(rules []Rule) {
switch common.Config.ReportType {
case "json":
js, err := json.MarshalIndent(rules, "", " ")
if err == nil {
fmt.Println(string(js))
}
default:
fmt.Print("# 重写规则\n\n[toc]\n\n")
for _, r := range rules {
if !common.Config.Verbose && (r.Original == "" || r.Original == "暂不支持") {
continue
}
fmt.Print("## ", common.MarkdownEscape(r.Name),
"\n* **Description**:", r.Description+"\n",
"\n* **Original**:\n\n```sql\n", r.Original, "\n```\n",
"\n* **Suggest**:\n\n```sql\n", r.Suggest, "\n```\n")
}
}
}
// Rewrite 用于重写SQL
type Rewrite struct {
SQL string
NewSQL string
Stmt sqlparser.Statement
Columns common.TableColumns
}
// NewRewrite 返回一个*Rewrite对象,如果SQL无法被正常解析,将错误输出到日志中,返回一个nil
func NewRewrite(sql string) *Rewrite {
stmt, err := sqlparser.Parse(sql)
if err != nil {
common.Log.Error(err.Error(), sql)
return nil
}
return &Rewrite{
SQL: sql,
Stmt: stmt,
}
}
// Rewrite 入口函数
func (rw *Rewrite) Rewrite() *Rewrite {
defer func() {
if err := recover(); err != nil {
common.Log.Error("Query rewrite Error: %s, maybe hit a bug.\nQuery: %s \nAST: %s",
err, rw.SQL, pretty.Sprint(rw.Stmt))
return
}
}()
for _, rule := range RewriteRules {
if RewriteRuleMatch(rule.Name) && rule.Func != nil {
rule.Func(rw)
common.Log.Debug("Rewrite Rule:%s Output NewSQL: %s", rule.Name, rw.NewSQL)
}
}
if rw.NewSQL == "" {
rw.NewSQL = rw.SQL
}
rw.Stmt, _ = sqlparser.Parse(rw.NewSQL)
// TODO: 重新前后返回结果一致性对比
// TODO: 前后SQL性能对比
return rw
}
// RewriteDelimiter delimiter: 补分号,可以指定不同的DELIMITER
func (rw *Rewrite) RewriteDelimiter() *Rewrite {
if rw.NewSQL != "" {
rw.NewSQL = strings.TrimSuffix(rw.NewSQL, common.Config.Delimiter) + common.Config.Delimiter
} else {
rw.NewSQL = strings.TrimSuffix(rw.SQL, common.Config.Delimiter) + common.Config.Delimiter
}
return rw
}
// RewriteStandard standard: 使用vitess提供的String功能将抽象语法树转写回SQL,注意:这可能转写失败。
func (rw *Rewrite) RewriteStandard() *Rewrite {
if _, err := sqlparser.Parse(rw.SQL); err == nil {
rw.NewSQL = sqlparser.String(rw.Stmt)
}
return rw
}
// RewriteAlwaysTrue alwaystrue: 删除恒真条件
func (rw *Rewrite) RewriteAlwaysTrue() (reWriter *Rewrite) {
array := NewNodeList(rw.Stmt)
tNode := array.Head
for {
omitAwaysTrue(tNode)
tNode = tNode.Next
if tNode == nil {
break
}
}
rw.NewSQL = sqlparser.String(rw.Stmt)
return rw
}
// isAlwaysTrue 用于判断ComparisonExpr是否是恒真
func isAlwaysTrue(expr *sqlparser.ComparisonExpr) bool {
if expr == nil {
return true
}
var result bool
switch expr.Operator {
case "<>":
expr.Operator = "!="
case "<=>":
expr.Operator = "="
case ">=", "<=", "!=", "=":
default:
return false
}
var left []byte
var right []byte
// left
switch l := expr.Left.(type) {
case *sqlparser.SQLVal:
left = l.Val
default:
return false
}
// right
switch r := expr.Right.(type) {
case *sqlparser.SQLVal:
right = r.Val
default:
return false
}
switch expr.Operator {
case "=":
result = bytes.Equal(left, right)
case "!=":
result = !bytes.Equal(left, right)
case ">":
result = bytes.Compare(left, right) > 0
case ">=":
result = bytes.Compare(left, right) >= 0
case "<":
result = bytes.Compare(left, right) < 0
case "<=":
result = bytes.Compare(left, right) <= 0
default:
result = false
}
return result
}
// omitAwaysTrue 移除AST中的恒真条件
func omitAwaysTrue(node *NodeItem) {
if node == nil {
return
}
switch self := node.Self.(type) {
case *sqlparser.Where:
if self != nil {
switch cond := self.Expr.(type) {
case *sqlparser.ComparisonExpr:
if isAlwaysTrue(cond) {
self.Expr = nil
}
case *sqlparser.ParenExpr:
if cond.Expr == nil {
self.Expr = nil
}
}
}
case *sqlparser.ParenExpr:
if self != nil {
switch cond := self.Expr.(type) {
case *sqlparser.ComparisonExpr:
if isAlwaysTrue(cond) {
self.Expr = nil
}
}
}
case *sqlparser.AndExpr:
if self != nil {
var tmp sqlparser.Expr
isRightTrue := false
isLeftTrue := false
tmp = nil
// 查看左树的情况
switch l := self.Left.(type) {
case *sqlparser.ComparisonExpr:
if isAlwaysTrue(l) {
self.Left = nil
isLeftTrue = true
tmp = self.Right
}
case *sqlparser.ParenExpr:
if l.Expr == nil {
self.Left = nil
isLeftTrue = true
tmp = self.Right
}
default:
if l == nil {
isLeftTrue = true
tmp = self.Right
}
}
// 查看右树的情况
switch r := self.Right.(type) {
case *sqlparser.ComparisonExpr:
if isAlwaysTrue(r) {
self.Right = nil
isRightTrue = true
tmp = self.Left
}
case *sqlparser.ParenExpr:
if r.Expr == nil {
self.Right = nil
isRightTrue = true
tmp = self.Left
}
default:
if r == nil {
isRightTrue = true
tmp = self.Left
}
}
if isRightTrue && isLeftTrue {
tmp = nil
} else if !isLeftTrue && !isRightTrue {
return
}
// 根据类型开始替换节点
switch l := node.Prev.Self.(type) {
case *sqlparser.Where:
l.Expr = tmp
case *sqlparser.ParenExpr:
l.Expr = tmp
case *sqlparser.AndExpr:
if l.Left == self {
l.Left = tmp
} else if l.Right == self {
l.Right = tmp
}
case *sqlparser.OrExpr:
if l.Left == self {
l.Left = tmp
} else if l.Right == self {
l.Right = tmp
}
default:
// 未匹配到对应数据类型则从链表中移除该节点
err := node.Array.Remove(node.Prev)
common.LogIfError(err, "")
}
}
case *sqlparser.OrExpr:
// 与AndExpr相同
if self != nil {
var tmp sqlparser.Expr
isRightTrue := false
isLeftTrue := false
tmp = nil
switch l := self.Left.(type) {
case *sqlparser.ComparisonExpr:
if isAlwaysTrue(l) {
self.Left = nil
isLeftTrue = true
tmp = self.Right
}
case *sqlparser.ParenExpr:
if l.Expr == nil {
self.Left = nil
isLeftTrue = true
tmp = self.Right
}
default:
if l == nil {
isLeftTrue = true
tmp = self.Right
}
}
switch r := self.Right.(type) {
case *sqlparser.ComparisonExpr:
if isAlwaysTrue(r) {
self.Right = nil
isRightTrue = true
tmp = self.Left
}
case *sqlparser.ParenExpr:
if r.Expr == nil {
self.Right = nil
isRightTrue = true
tmp = self.Left
}
default:
if r == nil {
isRightTrue = true
tmp = self.Left
}
}
if isRightTrue && isLeftTrue {
tmp = nil
} else if !isLeftTrue && !isRightTrue {
return
}
switch l := node.Prev.Self.(type) {
case *sqlparser.Where:
l.Expr = tmp
case *sqlparser.ParenExpr:
l.Expr = tmp
case *sqlparser.AndExpr:
if l.Left == self {
l.Left = tmp
} else if l.Right == self {
l.Right = tmp
}
case *sqlparser.OrExpr:
if l.Left == self {
l.Left = tmp
} else if l.Right == self {
l.Right = tmp
}
default:
err := node.Array.Remove(node.Prev)
common.LogIfError(err, "")
}
}
}
omitAwaysTrue(node.Prev)
}
// RewriteCountStar countstar: 将COUNT(col)改写为COUNT(*)
// COUNT(DISTINCT col)不能替换为COUNT(*)
func (rw *Rewrite) RewriteCountStar() *Rewrite {
err := sqlparser.Walk(func(node sqlparser.SQLNode) (kontinue bool, err error) {
switch f := node.(type) {
case *sqlparser.FuncExpr:
if strings.ToLower(f.Name.String()) == "count" && len(f.Exprs) > 0 {
switch colExpr := f.Exprs[0].(type) {
case *sqlparser.AliasedExpr:
switch col := colExpr.Expr.(type) {
case *sqlparser.ColName:
f.Exprs[0] = &sqlparser.StarExpr{TableName: col.Qualifier}
}
}
}
}
return true, nil
}, rw.Stmt)
common.LogIfError(err, "")
rw.NewSQL = sqlparser.String(rw.Stmt)
return rw
}
// RewriteInnoDB innodb: 为未指定Engine的表默认添加InnoDB引擎,将其他存储引擎转为InnoDB
func (rw *Rewrite) RewriteInnoDB() *Rewrite {
switch create := rw.Stmt.(type) {
case *sqlparser.DDL:
if create.Action != "create" {
return rw
}
if strings.Contains(strings.ToLower(create.TableSpec.Options), "engine=") {
reg := regexp.MustCompile(`(?i)engine=[a-z]+`)
create.TableSpec.Options = reg.ReplaceAllString(create.TableSpec.Options, "ENGINE=InnoDB ")
} else {
create.TableSpec.Options = " ENGINE=InnoDB " + create.TableSpec.Options
}
}
rw.NewSQL = sqlparser.String(rw.Stmt)
return rw
}
// RewriteAutoIncrement autoincrement: 将auto_increment设置为1
func (rw *Rewrite) RewriteAutoIncrement() *Rewrite {
switch create := rw.Stmt.(type) {
case *sqlparser.DDL:
if create.Action != "create" || create.TableSpec == nil {
return rw
}
if strings.Contains(strings.ToLower(create.TableSpec.Options), "auto_increment=") {
reg := regexp.MustCompile(`(?i)auto_increment=[0-9]+`)
create.TableSpec.Options = reg.ReplaceAllString(create.TableSpec.Options, "auto_increment=1 ")
}
}
rw.NewSQL = sqlparser.String(rw.Stmt)
return rw
}
// RewriteIntWidth intwidth: int类型转为int(10),bigint类型转为bigint(20)
func (rw *Rewrite) RewriteIntWidth() *Rewrite {
switch create := rw.Stmt.(type) {
case *sqlparser.DDL:
if create.Action != "create" || create.TableSpec == nil {
return rw
}
for _, col := range create.TableSpec.Columns {
switch col.Type.Type {
case "int", "integer":
if col.Type.Length != nil &&
(string(col.Type.Length.Val) != "10" && string(col.Type.Length.Val) != "11") {
col.Type.Length = sqlparser.NewIntVal([]byte("10"))
}
case "bigint":
if col.Type.Length != nil && string(col.Type.Length.Val) != "20" || col.Type.Length == nil {
col.Type.Length = sqlparser.NewIntVal([]byte("20"))
}
default:
}
}
}
rw.NewSQL = sqlparser.String(rw.Stmt)
return rw
}
// RewriteStar2Columns star2columns: 对应COL.001,SELECT补全*指代的列名
func (rw *Rewrite) RewriteStar2Columns() *Rewrite {
// 如果未配置mysql环境或从环境中获取失败,*不进行替换
if common.Config.TestDSN.Disable || len(rw.Columns) == 0 {
common.Log.Debug("(rw *Rewrite) RewriteStar2Columns(): Rewrite failed. TestDSN.Disable: %v, len(rw.Columns):%d",
common.Config.TestDSN.Disable, len(rw.Columns))
return rw
}
err := sqlparser.Walk(func(node sqlparser.SQLNode) (kontinue bool, err error) {
switch n := node.(type) {
case *sqlparser.Select:
// select * 可能出现的情况:
// 1. select * from tb;
// 2. select * from tb1,tb2;
// 3. select tb1.* from tb1;
// 4. select tb1.*,tb2.col from tb1,tb2;
// 5. select db.tb1.* from tb1;
// 6. select db.tb1.*,db.tb2.col from db.tb1,db.tb2;
newSelectExprs := make(sqlparser.SelectExprs, 0)
for _, expr := range n.SelectExprs {
switch e := expr.(type) {
case *sqlparser.StarExpr:
// 一般情况下最外层循环不会超过两层
for _, tables := range rw.Columns {
for _, cols := range tables {
for _, col := range cols {
newExpr := &sqlparser.AliasedExpr{
Expr: &sqlparser.ColName{
Metadata: nil,
Name: sqlparser.NewColIdent(col.Name),
Qualifier: sqlparser.TableName{
Name: sqlparser.NewTableIdent(col.Table),
// 因为不建议跨DB的查询,所以这里的db前缀将不进行补齐
Qualifier: sqlparser.TableIdent{},
},
},
As: sqlparser.ColIdent{},
}
if e.TableName.Name.IsEmpty() {
// 情况1,2
newSelectExprs = append(newSelectExprs, newExpr)
} else {
// 其他情况下只有在匹配表名的时候才会进行替换
if e.TableName.Name.String() == col.Table {
newSelectExprs = append(newSelectExprs, newExpr)
}
}
}
}
}
default:
newSelectExprs = append(newSelectExprs, e)
}
}
n.SelectExprs = newSelectExprs
}
return true, nil
}, rw.Stmt)
common.LogIfError(err, "")
rw.NewSQL = sqlparser.String(rw.Stmt)
return rw
}
// RewriteInsertColumns insertcolumns: 对应COL.002,INSERT补全列名
func (rw *Rewrite) RewriteInsertColumns() *Rewrite {
switch insert := rw.Stmt.(type) {
case *sqlparser.Insert:
switch insert.Action {
case "insert", "replace":
if insert.Columns != nil {
return rw
}
newColumns := make(sqlparser.Columns, 0)
db := insert.Table.Qualifier.String()
table := insert.Table.Name.String()
// 支持INSERT/REPLACE INTO VALUES形式,支持INSERT/REPLACE INTO SELECT
colCount := 0
switch v := insert.Rows.(type) {
case sqlparser.Values:
if len(v) > 0 {
colCount = len(v[0])
}
case *sqlparser.Select:
if l := len(v.SelectExprs); l > 0 {
colCount = l
}
}
// 开始对ast进行替换,补全前N列
counter := 0
for dbName, tb := range rw.Columns {
for tbName, cols := range tb {
for _, col := range cols {
// 只有全部列补全完成的时候才会替换ast
if counter == colCount {
insert.Columns = newColumns
rw.NewSQL = sqlparser.String(rw.Stmt)
return rw
}
if db != "" {
// 指定了DB的时候,只能怼指定DB的列
if db == dbName && table == tbName {
newColumns = append(newColumns, sqlparser.NewColIdent(col.Name))
counter++
}
} else {
// 没有指定DB的时候,将column中的列按顺序往里怼
if table == tbName {
newColumns = append(newColumns, sqlparser.NewColIdent(col.Name))
counter++
}
}
}
}
}
}
}
return rw
}
// RewriteHaving having: 对应CLA.013,使用WHERE过滤条件替代HAVING
func (rw *Rewrite) RewriteHaving() *Rewrite {
err := sqlparser.Walk(func(node sqlparser.SQLNode) (kontinue bool, err error) {
switch n := node.(type) {
case *sqlparser.Select:
if n.Having != nil {
if n.Where == nil {
// WHERE条件为空直接用HAVING替代WHERE即可
n.Where = n.Having
} else {
// WHERE条件不为空,需要对已有的条件进行括号保护,然后再AND+HAVING
n.Where = &sqlparser.Where{
Expr: &sqlparser.AndExpr{
Left: &sqlparser.ParenExpr{
Expr: n.Where.Expr,
},
Right: n.Having.Expr,
},
}
}
// 别忘了重置HAVING和Where.Type
n.Where.Type = "where"
n.Having = nil
}
}
return true, nil
}, rw.Stmt)
common.LogIfError(err, "")
rw.NewSQL = sqlparser.String(rw.Stmt)
return rw
}
// RewriteAddOrderByNull orderbynull: 对应CLA.008,GROUP BY无排序要求时添加ORDER BY NULL
func (rw *Rewrite) RewriteAddOrderByNull() *Rewrite {
err := sqlparser.Walk(func(node sqlparser.SQLNode) (kontinue bool, err error) {
switch n := node.(type) {
case *sqlparser.Select:
if n.GroupBy != nil && n.OrderBy == nil {
n.OrderBy = sqlparser.OrderBy{
&sqlparser.Order{
Expr: &sqlparser.NullVal{},
Direction: "asc",
},
}
}
}
return true, nil
}, rw.Stmt)
common.LogIfError(err, "")
rw.NewSQL = sqlparser.String(rw.Stmt)
return rw
}
// RewriteOr2Union or2union: 将OR查询转写为UNION ALL TODO: 暂无对应HeuristicRules
// https://sqlperformance.com/2014/09/sql-plan/rewriting-queries-improve-performance
func (rw *Rewrite) RewriteOr2Union() *Rewrite {
return rw
}
// RewriteUnionAll unionall: 不介意重复数据的情况下使用union all替换union
func (rw *Rewrite) RewriteUnionAll() *Rewrite {
err := sqlparser.Walk(func(node sqlparser.SQLNode) (kontinue bool, err error) {
switch n := node.(type) {
case *sqlparser.Union:
n.Type = "union all"
}
return true, nil
}, rw.Stmt)
common.LogIfError(err, "")
rw.NewSQL = sqlparser.String(rw.Stmt)
return rw
}
// RewriteOr2In or2in: 同一列的OR过滤条件使用IN()替代,如果值有相等的会进行合并
func (rw *Rewrite) RewriteOr2In() *Rewrite {
// 通过AST生成node的双向链表,链表顺序为书写顺序
nodeList := NewNodeList(rw.Stmt)
tNode := nodeList.First()
for {
tNode.or2in()
if tNode.Next == nil {
break
}
tNode = tNode.Next
}
rw.NewSQL = sqlparser.String(rw.Stmt)
return rw
}
// or2in 用于将or转换成in
func (node *NodeItem) or2in() {
if node == nil || node.Self == nil {
return
}
switch selfNode := node.Self.(type) {
case *sqlparser.OrExpr:
newExpr := mergeExprs(selfNode.Left, selfNode.Right)
if newExpr != nil {
// or 自身两个节点可以合并的情况下,将父节点中的expr替换成新的
switch pre := node.Prev.Self.(type) {
case *sqlparser.OrExpr:
if pre.Left == node.Self {
node.Self = newExpr
pre.Left = newExpr
} else if pre.Right == node.Self {
node.Self = newExpr
pre.Right = newExpr
}
case *sqlparser.AndExpr:
if pre.Left == node.Self {
node.Self = newExpr
pre.Left = newExpr
} else if pre.Right == node.Self {
node.Self = newExpr
pre.Right = newExpr
}
case *sqlparser.Where:
node.Self = newExpr
pre.Expr = newExpr
case *sqlparser.ParenExpr:
// 如果SQL书写中带了括号,暂不会进行跨括号的合并,TODO:无意义括号打平,加个rewrite rule
node.Self = newExpr
pre.Expr = newExpr
}
} else {
// or 自身两个节点如不可以合并,则检测是否可以与父节点合并
// 与父节点的合并不能跨越and、括号等,可能会改变语义
// 检查自身左右节点是否能与上层节点中合并,or只能与or合并
switch pre := node.Prev.Self.(type) {
case *sqlparser.OrExpr:
// AST中如果出现复合条件,则一定在左树,所以只需要判断左边就可以
if pre.Left == selfNode {
switch n := pre.Right.(type) {
case *sqlparser.ComparisonExpr:
newLeftExpr := mergeExprs(selfNode.Left, n)
newRightExpr := mergeExprs(selfNode.Right, n)
// newLeftExpr 与 newRightExpr 一定有一个是nil,
// 否则说明该orExpr下的两个节点可合并,可以通过最后的向前递归合并pre节点中的expr
if newLeftExpr == nil || newRightExpr == nil {
if newLeftExpr != nil {
pre.Right = newLeftExpr
pre.Left = selfNode.Right
err := node.Array.Remove(node)
common.LogIfError(err, "")
}
if newRightExpr != nil {
pre.Right = newRightExpr
pre.Left = selfNode.Left
err := node.Array.Remove(node)
common.LogIfError(err, "")
}
}
}
}
}
}
}
// 逆向合并由更改AST后产生的新的可合并节点
node.Prev.or2in()
}
// mergeExprs 将两个属于同一个列的ComparisonExpr合并成一个,如果不能合并则返回nil
func mergeExprs(left, right sqlparser.Expr) *sqlparser.ComparisonExpr {
// 用于对比两个列是否相同
colInLeft := ""
colInRight := ""
lOperator := ""
rOperator := ""
// 用于存放expr左右子树中的值
var values []sqlparser.SQLNode
// SQL中使用到的列
var colName *sqlparser.ColName
// 左子树
switch l := left.(type) {
case *sqlparser.ComparisonExpr:
// 获取列名
colName, colInLeft = getColumnName(l.Left)
// 获取值
if colInLeft != "" {
switch v := l.Right.(type) {
case *sqlparser.SQLVal, sqlparser.ValTuple, *sqlparser.BoolVal, *sqlparser.NullVal:
values = append(values, v)
}
}
// 获取operator
lOperator = l.Operator
default:
return nil
}
// 右子树
switch r := right.(type) {
case *sqlparser.ComparisonExpr:
// 获取列名
if colName.Name.String() != "" {
common.Log.Warn("colName shouldn't has value, but now it's %s", colName.Name.String())
}
colName, colInRight = getColumnName(r.Left)
// 获取值
if colInRight != "" {
switch v := r.Right.(type) {