-
Notifications
You must be signed in to change notification settings - Fork 8.5k
/
SQLUtils.java
1833 lines (1525 loc) · 64.5 KB
/
SQLUtils.java
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 1999-2017 Alibaba Group Holding Ltd.
*
* 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 com.alibaba.druid.sql;
import com.alibaba.druid.DbType;
import com.alibaba.druid.sql.ast.*;
import com.alibaba.druid.sql.ast.expr.*;
import com.alibaba.druid.sql.ast.statement.*;
import com.alibaba.druid.sql.dialect.ads.visitor.AdsOutputVisitor;
import com.alibaba.druid.sql.dialect.antspark.visitor.AntsparkOutputVisitor;
import com.alibaba.druid.sql.dialect.antspark.visitor.AntsparkSchemaStatVisitor;
import com.alibaba.druid.sql.dialect.blink.vsitor.BlinkOutputVisitor;
import com.alibaba.druid.sql.dialect.clickhouse.visitor.ClickSchemaStatVisitor;
import com.alibaba.druid.sql.dialect.clickhouse.visitor.ClickhouseOutputVisitor;
import com.alibaba.druid.sql.dialect.db2.visitor.DB2OutputVisitor;
import com.alibaba.druid.sql.dialect.db2.visitor.DB2SchemaStatVisitor;
import com.alibaba.druid.sql.dialect.h2.visitor.H2OutputVisitor;
import com.alibaba.druid.sql.dialect.h2.visitor.H2SchemaStatVisitor;
import com.alibaba.druid.sql.dialect.hive.ast.HiveInsert;
import com.alibaba.druid.sql.dialect.hive.ast.HiveInsertStatement;
import com.alibaba.druid.sql.dialect.hive.stmt.HiveCreateTableStatement;
import com.alibaba.druid.sql.dialect.hive.visitor.HiveASTVisitorAdapter;
import com.alibaba.druid.sql.dialect.hive.visitor.HiveOutputVisitor;
import com.alibaba.druid.sql.dialect.hive.visitor.HiveSchemaStatVisitor;
import com.alibaba.druid.sql.dialect.mysql.ast.MySqlObject;
import com.alibaba.druid.sql.dialect.mysql.ast.clause.MySqlSelectIntoStatement;
import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlInsertStatement;
import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlSelectQueryBlock;
import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitorAdapter;
import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlOutputVisitor;
import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor;
import com.alibaba.druid.sql.dialect.odps.ast.OdpsCreateTableStatement;
import com.alibaba.druid.sql.dialect.odps.ast.OdpsSelectQueryBlock;
import com.alibaba.druid.sql.dialect.odps.visitor.OdpsASTVisitorAdapter;
import com.alibaba.druid.sql.dialect.odps.visitor.OdpsOutputVisitor;
import com.alibaba.druid.sql.dialect.odps.visitor.OdpsSchemaStatVisitor;
import com.alibaba.druid.sql.dialect.oracle.visitor.OracleASTVisitorAdapter;
import com.alibaba.druid.sql.dialect.oracle.visitor.OracleOutputVisitor;
import com.alibaba.druid.sql.dialect.oracle.visitor.OracleSchemaStatVisitor;
import com.alibaba.druid.sql.dialect.oracle.visitor.OracleToMySqlOutputVisitor;
import com.alibaba.druid.sql.dialect.oscar.visitor.OscarOutputVisitor;
import com.alibaba.druid.sql.dialect.postgresql.visitor.PGOutputVisitor;
import com.alibaba.druid.sql.dialect.postgresql.visitor.PGSchemaStatVisitor;
import com.alibaba.druid.sql.dialect.presto.visitor.PrestoOutputVisitor;
import com.alibaba.druid.sql.dialect.sqlserver.visitor.SQLServerOutputVisitor;
import com.alibaba.druid.sql.dialect.sqlserver.visitor.SQLServerSchemaStatVisitor;
import com.alibaba.druid.sql.parser.*;
import com.alibaba.druid.sql.repository.SchemaRepository;
import com.alibaba.druid.sql.visitor.*;
import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.alibaba.druid.util.*;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.function.Consumer;
import java.util.function.Predicate;
public class SQLUtils {
public static final Charset UTF8 = Charset.forName("UTF-8");
private static final SQLParserFeature[] FORMAT_DEFAULT_FEATURES = {
SQLParserFeature.KeepComments,
SQLParserFeature.EnableSQLBinaryOpExprGroup
};
public static FormatOption DEFAULT_FORMAT_OPTION = new FormatOption(true, true);
public static FormatOption DEFAULT_LCASE_FORMAT_OPTION
= new FormatOption(false, true);
private static final Log LOG = LogFactory.getLog(SQLUtils.class);
public static String toSQLString(SQLObject sqlObject, String dbType) {
return toSQLString(sqlObject, DbType.valueOf(dbType));
}
public static String toSQLString(SQLObject sqlObject, DbType dbType) {
return toSQLString(sqlObject, dbType, null, null);
}
public static String toSQLString(SQLObject sqlObject, DbType dbType, FormatOption option) {
return toSQLString(sqlObject, dbType, option, null);
}
public static String toSQLString(SQLObject sqlObject,
DbType dbType,
FormatOption option,
VisitorFeature... features) {
StringBuilder out = new StringBuilder();
SQLASTOutputVisitor visitor = createOutputVisitor(out, dbType);
if (option == null) {
option = DEFAULT_FORMAT_OPTION;
}
visitor.setUppCase(option.isUppCase());
visitor.setPrettyFormat(option.isPrettyFormat());
visitor.setParameterized(option.isParameterized());
int featuresValue = option.features;
if (features != null) {
for (VisitorFeature feature : features) {
visitor.config(feature, true);
featuresValue |= feature.mask;
}
}
visitor.setFeatures(featuresValue);
sqlObject.accept(visitor);
String sql = out.toString();
return sql;
}
public static String toSQLString(SQLObject obj) {
if (obj instanceof SQLStatement) {
SQLStatement stmt = (SQLStatement) obj;
return toSQLString(stmt, stmt.getDbType());
}
if (obj instanceof MySqlObject) {
return toMySqlString(obj);
}
StringBuilder out = new StringBuilder();
obj.accept(new SQLASTOutputVisitor(out));
String sql = out.toString();
return sql;
}
public static String toOdpsString(SQLObject sqlObject) {
return toOdpsString(sqlObject, null);
}
public static String toHiveString(SQLObject sqlObject) {
return toSQLString(sqlObject, DbType.odps);
}
public static String toOdpsString(SQLObject sqlObject, FormatOption option) {
return toSQLString(sqlObject, DbType.odps, option);
}
public static String toAntsparkString(SQLObject sqlObject) {
return toAntsparkString(sqlObject, null);
}
public static String toAntsparkString(SQLObject sqlObject, FormatOption option) {
return toSQLString(sqlObject, DbType.antspark, option);
}
public static String toMySqlString(SQLObject sqlObject) {
return toMySqlString(sqlObject, (FormatOption) null);
}
public static String toMySqlStringIfNotNull(SQLObject sqlObject, String defaultStr) {
if (sqlObject == null) {
return defaultStr;
}
return toMySqlString(sqlObject, (FormatOption) null);
}
public static String toMySqlString(SQLObject sqlObject, VisitorFeature... features) {
return toMySqlString(sqlObject, new FormatOption(features));
}
public static String toNormalizeMysqlString(SQLObject sqlObject) {
if (sqlObject != null) {
return SQLUtils.normalize(toSQLString(sqlObject, DbType.mysql));
}
return null;
}
public static String toMySqlString(SQLObject sqlObject, FormatOption option) {
return toSQLString(sqlObject, DbType.mysql, option);
}
public static SQLExpr toMySqlExpr(String sql) {
return toSQLExpr(sql, DbType.mysql);
}
public static String formatMySql(String sql) {
return format(sql, DbType.mysql);
}
public static String formatMySql(String sql, FormatOption option) {
return format(sql, DbType.mysql, option);
}
public static String formatOracle(String sql) {
return format(sql, DbType.oracle);
}
public static String formatOracle(String sql, FormatOption option) {
return format(sql, DbType.oracle, option);
}
public static String formatOdps(String sql) {
return format(sql, DbType.odps);
}
public static String formatPresto(String sql) {
return formatPresto(sql, null);
}
public static String formatPresto(String sql, FormatOption option) {
SQLParserFeature[] features = {SQLParserFeature.KeepComments,
SQLParserFeature.EnableSQLBinaryOpExprGroup,
SQLParserFeature.KeepNameQuotes};
return format(sql, DbType.mysql, null, option, features);
}
public static String formatHive(String sql) {
return format(sql, DbType.hive);
}
public static String formatOdps(String sql, FormatOption option) {
return format(sql, DbType.odps, option);
}
public static String formatHive(String sql, FormatOption option) {
return format(sql, DbType.hive, option);
}
public static String formatSQLServer(String sql) {
return format(sql, DbType.sqlserver);
}
public static String toOracleString(SQLObject sqlObject) {
return toOracleString(sqlObject, null);
}
public static String toOracleString(SQLObject sqlObject, FormatOption option) {
return toSQLString(sqlObject, DbType.oracle, option);
}
public static String toPGString(SQLObject sqlObject) {
return toPGString(sqlObject, null);
}
public static String toPGString(SQLObject sqlObject, FormatOption option) {
return toSQLString(sqlObject, DbType.postgresql, option);
}
public static String toDB2String(SQLObject sqlObject) {
return toDB2String(sqlObject, null);
}
public static String toDB2String(SQLObject sqlObject, FormatOption option) {
return toSQLString(sqlObject, DbType.db2, option);
}
public static String toSQLServerString(SQLObject sqlObject) {
return toSQLServerString(sqlObject, null);
}
public static String toSQLServerString(SQLObject sqlObject, FormatOption option) {
return toSQLString(sqlObject, DbType.sqlserver, option);
}
public static String formatPGSql(String sql, FormatOption option) {
return format(sql, DbType.postgresql, option);
}
public static SQLExpr toSQLExpr(String sql, DbType dbType) {
SQLExprParser parser = SQLParserUtils.createExprParser(sql, dbType);
SQLExpr expr = parser.expr();
if (parser.getLexer().token() != Token.EOF) {
throw new ParserException("illegal sql expr : " + sql + ", " + parser.getLexer().info());
}
return expr;
}
public static SQLSelectOrderByItem toOrderByItem(String sql, DbType dbType) {
SQLExprParser parser = SQLParserUtils.createExprParser(sql, dbType);
SQLSelectOrderByItem orderByItem = parser.parseSelectOrderByItem();
if (parser.getLexer().token() != Token.EOF) {
throw new ParserException("illegal sql expr : " + sql + ", " + parser.getLexer().info());
}
return orderByItem;
}
public static SQLUpdateSetItem toUpdateSetItem(String sql, DbType dbType) {
SQLExprParser parser = SQLParserUtils.createExprParser(sql, dbType);
SQLUpdateSetItem updateSetItem = parser.parseUpdateSetItem();
if (parser.getLexer().token() != Token.EOF) {
throw new ParserException("illegal sql expr : " + sql + ", " + parser.getLexer().info());
}
return updateSetItem;
}
public static SQLSelectItem toSelectItem(String sql, DbType dbType) {
SQLExprParser parser = SQLParserUtils.createExprParser(sql, dbType);
SQLSelectItem selectItem = parser.parseSelectItem();
if (parser.getLexer().token() != Token.EOF) {
throw new ParserException("illegal sql expr : " + sql + ", " + parser.getLexer().info());
}
return selectItem;
}
public static List<SQLStatement> toStatementList(String sql, DbType dbType) {
SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(sql, dbType);
return parser.parseStatementList();
}
public static SQLExpr toSQLExpr(String sql) {
return toSQLExpr(sql, null);
}
public static String format(String sql, String dbType) {
return format(sql, DbType.of(dbType));
}
public static String format(String sql, DbType dbType) {
return format(sql, dbType, null, null);
}
public static String format(String sql, DbType dbType, FormatOption option) {
return format(sql, dbType, null, option);
}
public static String format(String sql, DbType dbType, List<Object> parameters) {
return format(sql, dbType, parameters, null);
}
public static String format(String sql, DbType dbType, List<Object> parameters, FormatOption option) {
return format(sql, dbType, parameters, option, FORMAT_DEFAULT_FEATURES);
}
public static String format(String sql, DbType dbType, List<Object> parameters, FormatOption option,
SQLParserFeature[] features) {
try {
SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(sql, dbType, features);
List<SQLStatement> statementList = parser.parseStatementList();
return toSQLString(statementList, dbType, parameters, option);
} catch (ParserException ex) {
LOG.warn("rowFormat error", ex);
return sql;
}
}
public static String toSQLString(List<SQLStatement> statementList, DbType dbType) {
return toSQLString(statementList, dbType, (List<Object>) null);
}
public static String toSQLString(List<SQLStatement> statementList, DbType dbType, FormatOption option) {
return toSQLString(statementList, dbType, null, option);
}
public static String toSQLString(List<SQLStatement> statementList, DbType dbType, List<Object> parameters) {
return toSQLString(statementList, dbType, parameters, null, null);
}
public static String toSQLString(List<SQLStatement> statementList,
DbType dbType,
List<Object> parameters,
FormatOption option) {
return toSQLString(statementList, dbType, parameters, option, null);
}
public static String toSQLString(
List<SQLStatement> statementList,
DbType dbType,
List<Object> parameters,
FormatOption option,
Map<String, String> tableMapping
) {
StringBuilder out = new StringBuilder();
SQLASTOutputVisitor visitor = createFormatOutputVisitor(out, statementList, dbType);
if (parameters != null) {
visitor.setInputParameters(parameters);
}
if (option == null) {
option = DEFAULT_FORMAT_OPTION;
}
visitor.setFeatures(option.features);
if (tableMapping != null) {
visitor.setTableMapping(tableMapping);
}
boolean printStmtSeperator;
if (DbType.sqlserver == dbType) {
printStmtSeperator = false;
} else {
printStmtSeperator = DbType.oracle != dbType;
}
for (int i = 0, size = statementList.size(); i < size; i++) {
SQLStatement stmt = statementList.get(i);
if (i > 0) {
SQLStatement preStmt = statementList.get(i - 1);
if (printStmtSeperator && !preStmt.isAfterSemi()) {
visitor.print(";");
}
List<String> comments = preStmt.getAfterCommentsDirect();
if (comments != null) {
for (int j = 0; j < comments.size(); ++j) {
String comment = comments.get(j);
if (j != 0) {
visitor.println();
}
visitor.printComment(comment);
}
}
if (printStmtSeperator) {
visitor.println();
}
if (!(stmt instanceof SQLSetStatement)) {
visitor.println();
}
}
// {
// List<String> comments = stmt.getBeforeCommentsDirect();
// if (comments != null){
// for(String comment : comments) {
// visitor.printComment(comment);
// visitor.println();
// }
// }
// }
stmt.accept(visitor);
if (i == size - 1) {
List<String> comments = stmt.getAfterCommentsDirect();
if (comments != null) {
for (int j = 0; j < comments.size(); ++j) {
String comment = comments.get(j);
if (j != 0) {
visitor.println();
}
visitor.printComment(comment);
}
}
}
}
return out.toString();
}
public static SQLASTOutputVisitor createOutputVisitor(Appendable out, DbType dbType) {
return createFormatOutputVisitor(out, null, dbType);
}
public static SQLASTOutputVisitor createFormatOutputVisitor(Appendable out,
List<SQLStatement> statementList,
DbType dbType) {
if (dbType == null) {
if (statementList != null && statementList.size() > 0) {
dbType = statementList.get(0).getDbType();
}
if (dbType == null) {
dbType = DbType.other;
}
}
switch (dbType) {
case oracle:
case oceanbase_oracle:
if (statementList == null || statementList.size() == 1) {
return new OracleOutputVisitor(out, false);
} else {
return new OracleOutputVisitor(out, true);
}
case mysql:
case mariadb:
case tidb:
return new MySqlOutputVisitor(out);
case postgresql:
return new PGOutputVisitor(out);
case sqlserver:
case jtds:
return new SQLServerOutputVisitor(out);
case db2:
return new DB2OutputVisitor(out);
case odps:
return new OdpsOutputVisitor(out);
case h2:
return new H2OutputVisitor(out);
case hive:
return new HiveOutputVisitor(out);
case ads:
return new AdsOutputVisitor(out);
case blink:
return new BlinkOutputVisitor(out);
case antspark:
return new AntsparkOutputVisitor(out);
case presto:
return new PrestoOutputVisitor(out);
case clickhouse:
return new ClickhouseOutputVisitor(out);
case oscar:
return new OscarOutputVisitor(out);
default:
return new SQLASTOutputVisitor(out, dbType);
}
}
@Deprecated
public static SchemaStatVisitor createSchemaStatVisitor(List<SQLStatement> statementList, DbType dbType) {
return createSchemaStatVisitor(dbType);
}
public static SchemaStatVisitor createSchemaStatVisitor(DbType dbType) {
return createSchemaStatVisitor((SchemaRepository) null, dbType);
}
public static SchemaStatVisitor createSchemaStatVisitor(SchemaRepository repository) {
return createSchemaStatVisitor(repository, repository.getDbType());
}
public static SchemaStatVisitor createSchemaStatVisitor(SchemaRepository repository, DbType dbType) {
if (repository == null) {
repository = new SchemaRepository(dbType);
}
if (dbType == null) {
return new SchemaStatVisitor(repository);
}
switch (dbType) {
case oracle:
return new OracleSchemaStatVisitor(repository);
case mysql:
case mariadb:
case tidb:
case elastic_search:
return new MySqlSchemaStatVisitor(repository);
case postgresql:
return new PGSchemaStatVisitor(repository);
case sqlserver:
case jtds:
return new SQLServerSchemaStatVisitor(repository);
case db2:
return new DB2SchemaStatVisitor(repository);
case odps:
return new OdpsSchemaStatVisitor(repository);
case h2:
return new H2SchemaStatVisitor(repository);
case hive:
return new HiveSchemaStatVisitor(repository);
case antspark:
return new AntsparkSchemaStatVisitor(repository);
case clickhouse:
return new ClickSchemaStatVisitor(repository);
default:
return new SchemaStatVisitor(repository);
}
}
public static List<SQLStatement> parseStatements(String sql, String dbType, SQLParserFeature... features) {
return parseStatements(sql, DbType.of(dbType), features);
}
public static List<SQLStatement> parseStatements(String sql, DbType dbType, SQLParserFeature... features) {
SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(sql, dbType, features);
List<SQLStatement> stmtList = new ArrayList<SQLStatement>();
parser.parseStatementList(stmtList, -1, null);
if (parser.getLexer().token() != Token.EOF) {
throw new ParserException("syntax error : " + parser.getLexer().info());
}
return stmtList;
}
public static List<SQLStatement> parseStatements(String sql, DbType dbType, boolean keepComments) {
SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(sql, dbType, keepComments);
List<SQLStatement> stmtList = parser.parseStatementList();
if (parser.getLexer().token() != Token.EOF) {
throw new ParserException("syntax error. " + sql);
}
return stmtList;
}
public static List<SQLStatement> parseStatements(String sql, String dbType) {
return parseStatements(sql, dbType, new SQLParserFeature[0]);
}
public static List<SQLStatement> parseStatements(String sql, DbType dbType) {
return parseStatements(sql, dbType, new SQLParserFeature[0]);
}
public static SQLStatement parseSingleStatement(String sql, DbType dbType, boolean keepComments) {
SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(sql, dbType, keepComments);
List<SQLStatement> stmtList = parser.parseStatementList();
if (stmtList.size() > 1) {
throw new ParserException("multi-statement be found.");
}
if (parser.getLexer().token() != Token.EOF) {
throw new ParserException("syntax error. " + sql);
}
return stmtList.get(0);
}
public static SQLStatement parseSingleStatement(String sql, String dbType, SQLParserFeature... features) {
return parseSingleStatement(sql, DbType.of(dbType), features);
}
public static SQLStatement parseSingleStatement(String sql, DbType dbType, SQLParserFeature... features) {
SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(sql, dbType, features);
List<SQLStatement> stmtList = parser.parseStatementList();
if (stmtList.size() > 1) {
throw new ParserException("multi-statement be found.");
}
if (parser.getLexer().token() != Token.EOF) {
throw new ParserException("syntax error. " + sql);
}
return stmtList.get(0);
}
public static SQLStatement parseSingleMysqlStatement(String sql) {
return parseSingleStatement(sql, DbType.mysql, false);
}
/**
* @param columnName
* @param tableAlias
* @param pattern if pattern is null,it will be set {%Y-%m-%d %H:%i:%s} as mysql default value and set {yyyy-mm-dd
* hh24:mi:ss} as oracle default value
* @param dbType {@link DbType} if dbType is null ,it will be set the mysql as a default value
* @author owenludong.lud
*/
public static String buildToDate(String columnName, String tableAlias, String pattern, DbType dbType) {
StringBuilder sql = new StringBuilder();
if (StringUtils.isEmpty(columnName)) {
return "";
}
if (dbType == null) {
dbType = DbType.mysql;
}
String formatMethod = "";
if (JdbcUtils.isMysqlDbType(dbType)) {
formatMethod = "STR_TO_DATE";
if (StringUtils.isEmpty(pattern)) {
pattern = "%Y-%m-%d %H:%i:%s";
}
} else if (DbType.oracle == dbType) {
formatMethod = "TO_DATE";
if (StringUtils.isEmpty(pattern)) {
pattern = "yyyy-mm-dd hh24:mi:ss";
}
} else {
return "";
// expand date's handle method for other database
}
sql.append(formatMethod).append("(");
if (!StringUtils.isEmpty(tableAlias)) {
sql.append(tableAlias).append(".");
}
sql.append(columnName).append(",");
sql.append("'");
sql.append(pattern);
sql.append("')");
return sql.toString();
}
public static List<SQLExpr> split(SQLBinaryOpExpr x) {
return SQLBinaryOpExpr.split(x);
}
public static String translateOracleToMySql(String sql) {
List<SQLStatement> stmtList = toStatementList(sql, DbType.oracle);
StringBuilder out = new StringBuilder();
OracleToMySqlOutputVisitor visitor = new OracleToMySqlOutputVisitor(out, false);
for (int i = 0; i < stmtList.size(); ++i) {
stmtList.get(i).accept(visitor);
}
String mysqlSql = out.toString();
return mysqlSql;
}
public static String addCondition(String sql, String condition, DbType dbType) {
String result = addCondition(sql, condition, SQLBinaryOperator.BooleanAnd, false, dbType);
return result;
}
public static String addCondition(String sql, String condition, SQLBinaryOperator op, boolean left, DbType dbType) {
if (sql == null) {
throw new IllegalArgumentException("sql is null");
}
if (condition == null) {
return sql;
}
if (op == null) {
op = SQLBinaryOperator.BooleanAnd;
}
if (op != SQLBinaryOperator.BooleanAnd //
&& op != SQLBinaryOperator.BooleanOr) {
throw new IllegalArgumentException("add condition not support : " + op);
}
List<SQLStatement> stmtList = parseStatements(sql, dbType);
if (stmtList.isEmpty()) {
throw new IllegalArgumentException("not support empty-statement :" + sql);
}
if (stmtList.size() > 1) {
throw new IllegalArgumentException("not support multi-statement :" + sql);
}
SQLStatement stmt = stmtList.get(0);
SQLExpr conditionExpr = toSQLExpr(condition, dbType);
addCondition(stmt, op, conditionExpr, left);
return toSQLString(stmt, dbType);
}
public static void addCondition(SQLStatement stmt, SQLBinaryOperator op, SQLExpr condition, boolean left) {
if (stmt instanceof SQLSelectStatement) {
SQLSelectQuery query = ((SQLSelectStatement) stmt).getSelect().getQuery();
if (query instanceof SQLSelectQueryBlock) {
SQLSelectQueryBlock queryBlock = (SQLSelectQueryBlock) query;
SQLExpr newCondition = buildCondition(op, condition, left, queryBlock.getWhere());
queryBlock.setWhere(newCondition);
} else {
throw new IllegalArgumentException("add condition not support " + stmt.getClass().getName());
}
return;
}
if (stmt instanceof SQLDeleteStatement) {
SQLDeleteStatement delete = (SQLDeleteStatement) stmt;
SQLExpr newCondition = buildCondition(op, condition, left, delete.getWhere());
delete.setWhere(newCondition);
return;
}
if (stmt instanceof SQLUpdateStatement) {
SQLUpdateStatement update = (SQLUpdateStatement) stmt;
SQLExpr newCondition = buildCondition(op, condition, left, update.getWhere());
update.setWhere(newCondition);
return;
}
throw new IllegalArgumentException("add condition not support " + stmt.getClass().getName());
}
public static SQLExpr buildCondition(SQLBinaryOperator op, SQLExpr condition, boolean left, SQLExpr where) {
if (where == null) {
return condition;
}
SQLBinaryOpExpr newCondition;
if (left) {
newCondition = new SQLBinaryOpExpr(condition, op, where);
} else {
newCondition = new SQLBinaryOpExpr(where, op, condition);
}
return newCondition;
}
public static String addSelectItem(String selectSql, String expr, String alias, DbType dbType) {
return addSelectItem(selectSql, expr, alias, false, dbType);
}
public static void acceptBooleanOr(String sql, DbType dbType, Consumer<SQLBinaryOpExprGroup> consumer) {
acceptBinaryOpExprGroup(sql, dbType, consumer, e -> e.getOperator() == SQLBinaryOperator.BooleanOr);
}
public static void acceptBinaryOpExprGroup(String sql, DbType dbType, Consumer<SQLBinaryOpExprGroup> consumer, Predicate<SQLBinaryOpExprGroup> filter) {
if (sql == null || sql.isEmpty()) {
return;
}
List<SQLStatement> stmtList = new ArrayList<>();
try {
SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(sql, dbType, SQLParserFeature.EnableMultiUnion, SQLParserFeature.KeepComments, SQLParserFeature.EnableSQLBinaryOpExprGroup);
parser.parseStatementList(stmtList, -1, null);
} catch (Exception ignored) {
return;
}
SQLASTVisitor visitor;
switch (dbType) {
case odps:
visitor = new OdpsASTVisitorAdapter() {
@Override
public boolean visit(SQLBinaryOpExprGroup x) {
if (filter == null || filter.test(x)) {
consumer.accept(x);
}
return super.visit(x);
}
};
break;
default:
visitor = new SQLASTVisitorAdapter() {
@Override
public boolean visit(SQLBinaryOpExprGroup x) {
if (filter == null || filter.test(x)) {
consumer.accept(x);
}
return super.visit(x);
}
};
break;
}
for (SQLStatement stmt : stmtList) {
stmt.accept(visitor);
}
}
public static void acceptBinaryOpExpr(String sql, DbType dbType, Consumer<SQLBinaryOpExpr> consumer, Predicate<SQLBinaryOpExpr> filter) {
if (sql == null || sql.isEmpty()) {
return;
}
List<SQLStatement> stmtList = new ArrayList<>();
try {
SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(sql, dbType, SQLParserFeature.EnableMultiUnion, SQLParserFeature.KeepComments, SQLParserFeature.EnableSQLBinaryOpExprGroup);
parser.parseStatementList(stmtList, -1, null);
} catch (Exception ignored) {
return;
}
SQLASTVisitor visitor;
switch (dbType) {
case odps:
visitor = new OdpsASTVisitorAdapter() {
@Override
public boolean visit(SQLBinaryOpExpr x) {
if (filter == null || filter.test(x)) {
consumer.accept(x);
}
return super.visit(x);
}
};
break;
default:
visitor = new SQLASTVisitorAdapter() {
@Override
public boolean visit(SQLBinaryOpExpr x) {
if (filter == null || filter.test(x)) {
consumer.accept(x);
}
return super.visit(x);
}
};
break;
}
for (SQLStatement stmt : stmtList) {
stmt.accept(visitor);
}
}
public static void acceptSelectQueryBlock(String sql, DbType dbType, Consumer<SQLSelectQueryBlock> consumer, Predicate<SQLSelectQueryBlock> filter) {
if (sql == null || sql.isEmpty()) {
return;
}
List<SQLStatement> stmtList = new ArrayList<>();
try {
SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(sql, dbType, SQLParserFeature.EnableMultiUnion, SQLParserFeature.KeepComments, SQLParserFeature.EnableSQLBinaryOpExprGroup);
parser.parseStatementList(stmtList, -1, null);
} catch (Exception ignored) {
return;
}
SQLASTVisitor visitor;
switch (dbType) {
case odps:
visitor = new OdpsASTVisitorAdapter() {
@Override
public boolean visit(SQLSelectQueryBlock x) {
if (filter == null || filter.test(x)) {
consumer.accept(x);
}
return true;
}
@Override
public boolean visit(OdpsSelectQueryBlock x) {
if (filter == null || filter.test(x)) {
consumer.accept(x);
}
return true;
}
};
break;
case mysql:
visitor = new MySqlASTVisitorAdapter() {
@Override
public boolean visit(SQLSelectQueryBlock x) {
if (filter == null || filter.test(x)) {
consumer.accept(x);
}
return true;
}
@Override
public boolean visit(MySqlSelectQueryBlock x) {
if (filter == null || filter.test(x)) {
consumer.accept(x);
}
return true;
}
};
break;
default:
visitor = new SQLASTVisitorAdapter() {
@Override
public boolean visit(SQLSelectQueryBlock x) {
if (filter == null || filter.test(x)) {
consumer.accept(x);
}
return true;
}
};
break;
}
for (SQLStatement stmt : stmtList) {
stmt.accept(visitor);
}
}
public static void acceptAggregateFunction(String sql, DbType dbType, Consumer<SQLAggregateExpr> consumer, Predicate<SQLAggregateExpr> filter) {
if (sql == null || sql.isEmpty()) {
return;
}
List<SQLStatement> stmtList = new ArrayList<>();
try {
SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(sql, dbType, SQLParserFeature.EnableMultiUnion, SQLParserFeature.KeepComments, SQLParserFeature.EnableSQLBinaryOpExprGroup);
parser.parseStatementList(stmtList, -1, null);
} catch (Exception ignored) {
return;
}
SQLASTVisitor visitor;
switch (dbType) {
case odps:
visitor = new OdpsASTVisitorAdapter() {
@Override
public boolean visit(SQLAggregateExpr x) {
if (filter == null || filter.test(x)) {
consumer.accept(x);
}
return true;
}
};
break;
case mysql: