-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Copy pathAbstractSQLConfig.java
executable file
·2923 lines (2539 loc) · 92.8 KB
/
AbstractSQLConfig.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 ©2016 TommyLemon(https://github.com/TommyLemon/APIJSON)
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 apijson.server;
import static apijson.JSONObject.KEY_CACHE;
import static apijson.JSONObject.KEY_COLUMN;
import static apijson.JSONObject.KEY_COMBINE;
import static apijson.JSONObject.KEY_DATABASE;
import static apijson.JSONObject.KEY_EXPLAIN;
import static apijson.JSONObject.KEY_FROM;
import static apijson.JSONObject.KEY_GROUP;
import static apijson.JSONObject.KEY_HAVING;
import static apijson.JSONObject.KEY_ID;
import static apijson.JSONObject.KEY_JSON;
import static apijson.JSONObject.KEY_ORDER;
import static apijson.JSONObject.KEY_ROLE;
import static apijson.JSONObject.KEY_SCHEMA;
import static apijson.JSONObject.KEY_USER_ID;
import static apijson.RequestMethod.DELETE;
import static apijson.RequestMethod.GET;
import static apijson.RequestMethod.GETS;
import static apijson.RequestMethod.HEADS;
import static apijson.RequestMethod.POST;
import static apijson.RequestMethod.PUT;
import static apijson.SQL.AND;
import static apijson.SQL.NOT;
import static apijson.SQL.OR;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Pattern;
import javax.activation.UnsupportedDataTypeException;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import apijson.JSON;
import apijson.Log;
import apijson.NotNull;
import apijson.RequestMethod;
import apijson.RequestRole;
import apijson.SQL;
import apijson.StringUtil;
import apijson.server.exception.NotExistException;
import apijson.server.model.Column;
import apijson.server.model.ExtendedProperty;
import apijson.server.model.PgAttribute;
import apijson.server.model.PgClass;
import apijson.server.model.SysColumn;
import apijson.server.model.SysTable;
import apijson.server.model.Table;
/**config sql for JSON Request
* @author Lemon
*/
public abstract class AbstractSQLConfig implements SQLConfig {
private static final String TAG = "AbstractSQLConfig";
public static String DEFAULT_DATABASE = DATABASE_MYSQL;
public static String DEFAULT_SCHEMA = "sys";
public static String PREFFIX_DISTINCT = "DISTINCT ";
/**
* 表名映射,隐藏真实表名,对安全要求很高的表可以这么做
*/
public static final Map<String, String> TABLE_KEY_MAP;
public static final List<String> DATABASE_LIST;
// 自定义where条件拼接
public static final Map<String, String> RAW_MAP;
static {
TABLE_KEY_MAP = new HashMap<String, String>();
TABLE_KEY_MAP.put(Table.class.getSimpleName(), Table.TABLE_NAME);
TABLE_KEY_MAP.put(Column.class.getSimpleName(), Column.TABLE_NAME);
TABLE_KEY_MAP.put(PgClass.class.getSimpleName(), PgClass.TABLE_NAME);
TABLE_KEY_MAP.put(PgAttribute.class.getSimpleName(), PgAttribute.TABLE_NAME);
TABLE_KEY_MAP.put(SysTable.class.getSimpleName(), SysTable.TABLE_NAME);
TABLE_KEY_MAP.put(SysColumn.class.getSimpleName(), SysColumn.TABLE_NAME);
TABLE_KEY_MAP.put(ExtendedProperty.class.getSimpleName(), ExtendedProperty.TABLE_NAME);
DATABASE_LIST = new ArrayList<>();
DATABASE_LIST.add(DATABASE_MYSQL);
DATABASE_LIST.add(DATABASE_POSTGRESQL);
DATABASE_LIST.add(DATABASE_SQLSERVER);
DATABASE_LIST.add(DATABASE_ORACLE);
RAW_MAP = new HashMap<>();
}
@Override
public boolean limitSQLCount() {
return Log.DEBUG == false || AbstractVerifier.SYSTEM_ACCESS_MAP.containsKey(getTable()) == false;
}
@NotNull
@Override
public String getIdKey() {
return KEY_ID;
}
@NotNull
@Override
public String getUserIdKey() {
return KEY_USER_ID;
}
private Object id; //Table的id
private RequestMethod method; //操作方法
private boolean prepared = true; //预编译
private boolean main = true;
/**
* TODO 被关联的表通过就忽略关联的表?(这个不行 User:{"sex@":"/Comment/toId"})
*/
private RequestRole role; //发送请求的用户的角色
private boolean distinct = false;
private String database; //表所在的数据库类型
private String schema; //表所在的数据库名
private String table; //表名
private String alias; //表别名
private String group; //分组方式的字符串数组,','分隔
private String having; //聚合函数的字符串数组,','分隔
private String order; //排序方式的字符串数组,','分隔
private List<String> json; //需要转为 JSON 的字段,','分隔
private Subquery from; //子查询临时表
private List<String> column; //表内字段名(或函数名,仅查询操作可用)的字符串数组,','分隔
private List<List<Object>> values; //对应表内字段的值的字符串数组,','分隔
private Map<String, Object> content; //Request内容,key:value形式,column = content.keySet(),values = content.values()
private Map<String, Object> where; //筛选条件,key:value形式
private Map<String, List<String>> combine; //条件组合,{ "&":[key], "|":[key], "!":[key] }
//array item <<<<<<<<<<
private int count; //Table数量
private int page; //Table所在页码
private int position; //Table在[]中的位置
private int query; //JSONRequest.query
private int type; //ObjectParser.type
private int cache;
private boolean explain;
private List<Join> joinList; //连表 配置列表
//array item >>>>>>>>>>
private boolean test; //测试
private String procedure;
public SQLConfig setProcedure(String procedure) {
this.procedure = procedure;
return this;
}
public String getProcedure() {
return procedure;
}
public AbstractSQLConfig(RequestMethod method) {
setMethod(method);
}
public AbstractSQLConfig(RequestMethod method, String table) {
this(method);
setTable(table);
}
public AbstractSQLConfig(RequestMethod method, int count, int page) {
this(method);
setCount(count);
setPage(page);
}
@NotNull
@Override
public RequestMethod getMethod() {
if (method == null) {
method = GET;
}
return method;
}
@Override
public AbstractSQLConfig setMethod(RequestMethod method) {
this.method = method;
return this;
}
@Override
public boolean isPrepared() {
return prepared;
}
@Override
public AbstractSQLConfig setPrepared(boolean prepared) {
this.prepared = prepared;
return this;
}
@Override
public boolean isMain() {
return main;
}
@Override
public AbstractSQLConfig setMain(boolean main) {
this.main = main;
return this;
}
@Override
public Object getId() {
return id;
}
@Override
public AbstractSQLConfig setId(Object id) {
this.id = id;
return this;
}
@Override
public RequestRole getRole() {
//不能 @NotNull , AbstractParser#getSQLObject 内当getRole() == null时填充默认值
return role;
}
public AbstractSQLConfig setRole(String roleName) throws Exception {
return setRole(RequestRole.get(roleName));
}
@Override
public AbstractSQLConfig setRole(RequestRole role) {
this.role = role;
return this;
}
@Override
public boolean isDistinct() {
return distinct;
}
@Override
public SQLConfig setDistinct(boolean distinct) {
this.distinct = distinct;
return this;
}
@Override
public String getDatabase() {
return database;
}
@Override
public SQLConfig setDatabase(String database) {
this.database = database;
return this;
}
/**
* @return db == null ? DEFAULT_DATABASE : db
*/
@NotNull
public String getSQLDatabase() {
String db = getDatabase();
return db == null ? DEFAULT_DATABASE : db; // "" 表示已设置,不需要用全局默认的 StringUtil.isEmpty(db, false)) {
}
@Override
public boolean isMySQL() {
return isMySQL(getSQLDatabase());
}
public static boolean isMySQL(String db) {
return DATABASE_MYSQL.equals(db);
}
@Override
public boolean isPostgreSQL() {
return isPostgreSQL(getSQLDatabase());
}
public static boolean isPostgreSQL(String db) {
return DATABASE_POSTGRESQL.equals(db);
}
@Override
public boolean isSQLServer() {
return isSQLServer(getSQLDatabase());
}
public static boolean isSQLServer(String db) {
return DATABASE_SQLSERVER.equals(db);
}
@Override
public boolean isOracle() {
return isOracle(getSQLDatabase());
}
public static boolean isOracle(String db) {
return DATABASE_ORACLE.equals(db);
}
@Override
public String getQuote() {
return isMySQL() ? "`" : "\"";
}
@Override
public String getSchema() {
return schema;
}
/**
* @return
*/
@NotNull
public String getSQLSchema() {
String table = getTable();
//强制,避免因为全局默认的 @schema 自动填充进来,导致这几个类的 schema 为 sys 等其它值
if (Table.TAG.equals(table) || Column.TAG.equals(table)) {
return SCHEMA_INFORMATION; //MySQL, PostgreSQL, SQL Server 都有的
}
if (PgClass.TAG.equals(table) || PgAttribute.TAG.equals(table)) {
return ""; //PostgreSQL 的 pg_class 和 pg_attribute 表好像不属于任何 Schema
}
if (SysTable.TAG.equals(table) || SysColumn.TAG.equals(table) || ExtendedProperty.TAG.equals(table)) {
return SCHEMA_SYS; //SQL Server 在 sys 中的属性比 information_schema 中的要全,能拿到注释
}
String sch = getSchema();
return sch == null ? DEFAULT_SCHEMA : sch;
}
@Override
public AbstractSQLConfig setSchema(String schema) {
if (schema != null) {
String quote = getQuote();
String s = schema.startsWith(quote) && schema.endsWith(quote) ? schema.substring(1, schema.length() - 1) : schema;
if (StringUtil.isEmpty(s, true) == false && StringUtil.isName(s) == false) {
throw new IllegalArgumentException("@schema:value 中value必须是1个单词!");
}
}
this.schema = schema;
return this;
}
/**请求传进来的Table名
* @return
* @see {@link #getSQLTable()}
*/
@Override
public String getTable() {
return table;
}
/**数据库里的真实Table名
* 通过 {@link #TABLE_KEY_MAP} 映射
* @return
*/
@JSONField(serialize = false)
@Override
public String getSQLTable() {
// String t = TABLE_KEY_MAP.containsKey(table) ? TABLE_KEY_MAP.get(table) : table;
//如果要强制小写,则可在子类重写这个方法再 toLowerCase return DATABASE_POSTGRESQL.equals(getDatabase()) ? t.toLowerCase() : t;
return TABLE_KEY_MAP.containsKey(table) ? TABLE_KEY_MAP.get(table) : table;
}
@JSONField(serialize = false)
@Override
public String getTablePath() {
String q = getQuote();
String sch = getSQLSchema();
String sqlTable = getSQLTable();
return (StringUtil.isEmpty(sch, true) ? "" : q + sch + q + ".") + q + sqlTable + q + ( isKeyPrefix() ? " AS " + getAliasWithQuote() : "");
}
@Override
public AbstractSQLConfig setTable(String table) { //Table已经在Parser中校验,所以这里不用防SQL注入
this.table = table;
return this;
}
@Override
public String getAlias() {
return alias;
}
@Override
public AbstractSQLConfig setAlias(String alias) {
this.alias = alias;
return this;
}
public String getAliasWithQuote() {
String a = getAlias();
if (StringUtil.isEmpty(a, true)) {
a = getTable();
}
String q = getQuote();
//getTable 不能小写,因为Verifier用大小写敏感的名称判断权限
//如果要强制小写,则可在子类重写这个方法再 toLowerCase return q + (DATABASE_POSTGRESQL.equals(getDatabase()) ? a.toLowerCase() : a) + q;
return q + a + q;
}
@Override
public String getGroup() {
return group;
}
public AbstractSQLConfig setGroup(String... keys) {
return setGroup(StringUtil.getString(keys));
}
@Override
public AbstractSQLConfig setGroup(String group) {
this.group = group;
return this;
}
@JSONField(serialize = false)
public String getGroupString(boolean hasPrefix) {
//加上子表的 group
String joinGroup = "";
if (joinList != null) {
SQLConfig cfg;
String c;
boolean first = true;
for (Join j : joinList) {
if (j.isAppJoin()) {
continue;
}
cfg = j.isLeftOrRightJoin() ? j.getOutterConfig() : j.getJoinConfig();
if (StringUtil.isEmpty(cfg.getAlias(), true)) {
cfg.setAlias(cfg.getTable());
}
c = ((AbstractSQLConfig) cfg).getGroupString(false);
if (StringUtil.isEmpty(c, true) == false) {
joinGroup += (first ? "" : ", ") + c;
first = false;
}
}
}
group = StringUtil.getTrimedString(group);
String[] keys = StringUtil.split(group);
if (keys == null || keys.length <= 0) {
return StringUtil.isEmpty(joinGroup, true) ? "" : (hasPrefix ? " GROUP BY " : "") + joinGroup;
}
for (int i = 0; i < keys.length; i++) {
if (isPrepared()) { //不能通过 ? 来代替,因为SQLExecutor statement.setString后 GROUP BY 'userId' 有单引号,只能返回一条数据,必须去掉单引号才行!
if (StringUtil.isName(keys[i]) == false) {
throw new IllegalArgumentException("@group:value 中 value里面用 , 分割的每一项都必须是1个单词!并且不要有空格!");
}
}
keys[i] = getKey(keys[i]);
}
return (hasPrefix ? " GROUP BY " : "") + StringUtil.concat(StringUtil.getString(keys), joinGroup, ", ");
}
@Override
public String getHaving() {
return having;
}
public AbstractSQLConfig setHaving(String... conditions) {
return setHaving(StringUtil.getString(conditions));
}
@Override
public AbstractSQLConfig setHaving(String having) {
this.having = having;
return this;
}
/**
* @return HAVING conditoin0 AND condition1 OR condition2 ...
*/
@JSONField(serialize = false)
public String getHavingString(boolean hasPrefix) {
//加上子表的 having
String joinHaving = "";
if (joinList != null) {
SQLConfig cfg;
String c;
boolean first = true;
for (Join j : joinList) {
if (j.isAppJoin()) {
continue;
}
cfg = j.isLeftOrRightJoin() ? j.getOutterConfig() : j.getJoinConfig();
if (StringUtil.isEmpty(cfg.getAlias(), true)) {
cfg.setAlias(cfg.getTable());
}
c = ((AbstractSQLConfig) cfg).getHavingString(false);
if (StringUtil.isEmpty(c, true) == false) {
joinHaving += (first ? "" : ", ") + c;
first = false;
}
}
}
having = StringUtil.getTrimedString(having);
String[] keys = StringUtil.split(having, ";");
if (keys == null || keys.length <= 0) {
return StringUtil.isEmpty(joinHaving, true) ? "" : (hasPrefix ? " HAVING " : "") + joinHaving;
}
String expression;
String method;
//暂时不允许 String prefix;
String suffix;
//fun0(arg0,arg1,...);fun1(arg0,arg1,...)
for (int i = 0; i < keys.length; i++) {
//fun(arg0,arg1,...)
expression = keys[i];
int start = expression.indexOf("(");
if (start < 0) {
if (isPrepared() && PATTERN_HAVING.matcher(expression).matches() == false) {
throw new UnsupportedOperationException("字符串 " + expression + " 不合法!"
+ "预编译模式下 @having:\"column?value;function(arg0,arg1,...)?value...\""
+ " 中 column?value 必须符合正则表达式 ^[A-Za-z0-9%!=<>]+$ !不允许空格!");
}
continue;
}
int end = expression.indexOf(")");
if (start >= end) {
throw new IllegalArgumentException("字符 " + expression + " 不合法!"
+ "@having:value 中 value 里的 SQL函数必须为 function(arg0,arg1,...) 这种格式!");
}
method = expression.substring(0, start);
if (StringUtil.isName(method) == false) {
throw new IllegalArgumentException("字符 " + method + " 不合法!"
+ "预编译模式下 @having:\"column?value;function(arg0,arg1,...)?value...\""
+ " 中SQL函数名 function 必须符合正则表达式 ^[0-9a-zA-Z_]+$ !");
}
suffix = expression.substring(end + 1, expression.length());
if (isPrepared() && PATTERN_HAVING_SUFFIX.matcher((String) suffix).matches() == false) {
throw new UnsupportedOperationException("字符串 " + suffix + " 不合法!"
+ "预编译模式下 @having:\"column?value;function(arg0,arg1,...)?value...\""
+ " 中 ?value 必须符合正则表达式 ^[0-9%!=<>]+$ !不允许空格!");
}
String[] ckeys = StringUtil.split(expression.substring(start + 1, end));
if (ckeys != null) {
for (int j = 0; j < ckeys.length; j++) {
if (isPrepared() && (StringUtil.isName(ckeys[j]) == false || ckeys[j].startsWith("_"))) {
throw new IllegalArgumentException("字符 " + ckeys[j] + " 不合法!"
+ "预编译模式下 @having:\"column?value;function(arg0,arg1,...)?value...\""
+ " 中所有 arg 都必须是1个不以 _ 开头的单词!并且不要有空格!");
}
ckeys[j] = getKey(ckeys[j]);
}
}
keys[i] = method + "(" + StringUtil.getString(ckeys) + ")" + suffix;
}
//TODO 支持 OR, NOT 参考 @combine:"&key0,|key1,!key2"
return (hasPrefix ? " HAVING " : "") + StringUtil.concat(StringUtil.getString(keys, AND), joinHaving, AND);
}
@Override
public String getOrder() {
return order;
}
public AbstractSQLConfig setOrder(String... conditions) {
return setOrder(StringUtil.getString(conditions));
}
@Override
public AbstractSQLConfig setOrder(String order) {
this.order = order;
return this;
}
@JSONField(serialize = false)
public String getOrderString(boolean hasPrefix) {
//加上子表的 order
String joinOrder = "";
if (joinList != null) {
SQLConfig cfg;
String c;
boolean first = true;
for (Join j : joinList) {
if (j.isAppJoin()) {
continue;
}
cfg = j.isLeftOrRightJoin() ? j.getOutterConfig() : j.getJoinConfig();
if (StringUtil.isEmpty(cfg.getAlias(), true)) {
cfg.setAlias(cfg.getTable());
}
c = ((AbstractSQLConfig) cfg).getOrderString(false);
if (StringUtil.isEmpty(c, true) == false) {
joinOrder += (first ? "" : ", ") + c;
first = false;
}
}
}
String order = StringUtil.getTrimedString(getOrder());
if (getCount() > 0 && (isOracle() || isSQLServer())) { // Oracle 和 SQL Server 的 OFFSET 必须加 ORDER BY
// String[] ss = StringUtil.split(order);
if (StringUtil.isEmpty(order, true)) { //SQL Server 子查询内必须指定 OFFSET 才能用 ORDER BY
String idKey = getIdKey();
if (StringUtil.isEmpty(idKey, true)) {
idKey = "id"; //ORDER BY NULL 不行,SQL Server 会报错,必须要有排序,才能使用 OFFSET FETCH,如果没有 idKey,请求中指定 @order 即可
}
order = idKey; //让数据库调控默认升序还是降序 + "+";
}
//不用这么全面,毕竟没有语法问题还浪费性能,如果有其它问题,让前端传的 JSON 直接加上 @order 来解决
// boolean contains = false;
// if (ss != null) {
// for (String s : ss) {
// if (s != null && s.startsWith(idKey)) {
// s = s.substring(idKey.length());
// if ("+".equals(s) || "-".equals(s)) {// || " ASC ".equals(s) || " DESC ".equals(s)) {
// contains = true;
// break;
// }
// }
// }
// }
// if (contains == false) {
// order = (ss == null || ss.length <= 0 ? "" : order + ",") + idKey + "+";
// }
}
if (order.contains("+")) {//replace没有包含的replacement会崩溃
order = order.replaceAll("\\+", " ASC ");
}
if (order.contains("-")) {
order = order.replaceAll("-", " DESC ");
}
String[] keys = StringUtil.split(order);
if (keys == null || keys.length <= 0) {
return StringUtil.isEmpty(joinOrder, true) ? "" : (hasPrefix ? " ORDER BY " : "") + joinOrder;
}
String origin;
String sort;
int index;
for (int i = 0; i < keys.length; i++) {
index = keys[i].trim().endsWith(" ASC") ? keys[i].lastIndexOf(" ASC") : -1; //StringUtil.split返回数组中,子项不会有null
if (index < 0) {
index = keys[i].trim().endsWith(" DESC") ? keys[i].lastIndexOf(" DESC") : -1;
sort = index <= 0 ? "" : " DESC ";
} else {
sort = " ASC ";
}
origin = index < 0 ? keys[i] : keys[i].substring(0, index);
if (isPrepared()) { //不能通过 ? 来代替,SELECT 'id','name' 返回的就是 id:"id", name:"name",而不是数据库里的值!
//这里既不对origin trim,也不对 ASC/DESC ignoreCase,希望前端严格传没有任何空格的字符串过来,减少传输数据量,节约服务器性能
if (StringUtil.isName(origin) == false) {
throw new IllegalArgumentException("预编译模式下 @order:value 中 value里面用 , 分割的每一项"
+ " column+ / column- 中 column必须是1个单词!并且不要有多余的空格!");
}
}
keys[i] = getKey(origin) + sort;
}
return (hasPrefix ? " ORDER BY " : "") + StringUtil.concat(StringUtil.getString(keys), joinOrder, ", ");
}
@Override
public List<String> getJson() {
return json;
}
@Override
public AbstractSQLConfig setJson(List<String> json) {
this.json = json;
return this;
}
@Override
public Subquery getFrom() {
return from;
}
@Override
public AbstractSQLConfig setFrom(Subquery from) {
this.from = from;
return this;
}
@Override
public List<String> getColumn() {
return column;
}
@Override
public AbstractSQLConfig setColumn(List<String> column) {
this.column = column;
return this;
}
@JSONField(serialize = false)
public String getColumnString() throws Exception {
return getColumnString(false);
}
@JSONField(serialize = false)
public String getColumnString(boolean inSQLJoin) throws Exception {
switch (getMethod()) {
case HEAD:
case HEADS: //StringUtil.isEmpty(column, true) || column.contains(",") 时SQL.count(column)会return "*"
if (isPrepared() && column != null) {
String origin;
String alias;
int index;
for (String c : column) {
index = c.lastIndexOf(":"); //StringUtil.split返回数组中,子项不会有null
origin = index < 0 ? c : c.substring(0, index);
alias = index < 0 ? null : c.substring(index + 1);
if (StringUtil.isName(origin) == false || (alias != null && StringUtil.isName(alias) == false)) {
throw new IllegalArgumentException("HEAD请求: 预编译模式下 @column:value 中 value里面用 , 分割的每一项"
+ " column:alias 中 column 必须是1个单词!如果有alias,则alias也必须为1个单词!并且不要有多余的空格!");
}
}
}
return SQL.count(column != null && column.size() == 1 ? getKey(Pair.parseEntry(column.get(0), true).getKey()) : "*");
case POST:
if (column == null || column.isEmpty()) {
throw new IllegalArgumentException("POST 请求必须在Table内设置要保存的 key:value !");
}
String s = "";
boolean pfirst = true;
for (String c : column) {
if (isPrepared() && StringUtil.isName(c) == false) { //不能通过 ? 来代替,SELECT 'id','name' 返回的就是 id:"id", name:"name",而不是数据库里的值!
throw new IllegalArgumentException("POST请求: 每一个 key:value 中的key都必须是1个单词!");
}
s += ((pfirst ? "" : ",") + getKey(c));
pfirst = false;
}
return "(" + s + ")";
case GET:
case GETS:
boolean isQuery = RequestMethod.isQueryMethod(method); //TODO 这个有啥用?上面应是 getMethod 的值 GET 和 GETS 了。
String joinColumn = "";
if (isQuery && joinList != null) {
SQLConfig ecfg;
SQLConfig cfg;
String c;
boolean first = true;
for (Join j : joinList) {
if (j.isAppJoin()) {
continue;
}
ecfg = j.getOutterConfig();
if (ecfg != null && ecfg.getColumn() != null) { //优先级更高
cfg = ecfg;
}
else {
cfg = j.getJoinConfig();
}
if (StringUtil.isEmpty(cfg.getAlias(), true)) {
cfg.setAlias(cfg.getTable());
}
c = ((AbstractSQLConfig) cfg).getColumnString(true);
if (StringUtil.isEmpty(c, true) == false) {
joinColumn += (first ? "" : ", ") + c;
first = false;
}
inSQLJoin = true;
}
}
String tableAlias = getAliasWithQuote();
// String c = StringUtil.getString(column); //id,name;json_length(contactIdList):contactCount;...
String[] keys = column == null ? null : column.toArray(new String[]{}); //StringUtil.split(c, ";");
if (keys == null || keys.length <= 0) {
boolean noColumn = column != null && inSQLJoin;
String mc = isKeyPrefix() == false ? (noColumn ? "" : "*") : (noColumn ? "" : tableAlias + ".*");
return StringUtil.concat(mc, joinColumn, ", ", true);
}
String expression;
String method = null;
//...;fun0(arg0,arg1,...):fun0;fun1(arg0,arg1,...):fun1;...
for (int i = 0; i < keys.length; i++) {
//fun(arg0,arg1,...)
expression = keys[i];
int start = expression.indexOf("(");
int end = 0;
if (start >= 0) {
end = expression.indexOf(")");
if (start >= end) {
throw new IllegalArgumentException("字符 " + expression + " 不合法!"
+ "@having:value 中 value 里的 SQL函数必须为 function(arg0,arg1,...) 这种格式!");
}
method = expression.substring(0, start);
boolean distinct = i <= 0 && method.startsWith(PREFFIX_DISTINCT);
if (StringUtil.isName(distinct ? method.substring(PREFFIX_DISTINCT.length()) : method) == false) {
throw new IllegalArgumentException("字符 " + method + " 不合法!"
+ "预编译模式下 @column:\"column0,column1:alias;function0(arg0,arg1,...);function1(...):alias...\""
+ " 中SQL函数名 function 必须符合正则表达式 ^[0-9a-zA-Z_]+$ !");
}
}
boolean isColumn = start < 0;
String[] ckeys = StringUtil.split(isColumn ? expression : expression.substring(start + 1, end));
String quote = getQuote();
// if (isPrepared()) { //不能通过 ? 来代替,SELECT 'id','name' 返回的就是 id:"id", name:"name",而不是数据库里的值!
if (ckeys != null && ckeys.length > 0) {
boolean distinct;
String origin;
String alias;
int index;
for (int j = 0; j < ckeys.length; j++) {
index = isColumn ? ckeys[j].lastIndexOf(":") : -1; //StringUtil.split返回数组中,子项不会有null
origin = index < 0 ? ckeys[j] : ckeys[j].substring(0, index);
alias = index < 0 ? null : ckeys[j].substring(index + 1);
distinct = j <= 0 && origin.startsWith(PREFFIX_DISTINCT);
if (distinct) {
origin = origin.substring(PREFFIX_DISTINCT.length());
}
if (isPrepared()) {
if (isColumn) {
if (StringUtil.isName(origin) == false || (alias != null && StringUtil.isName(alias) == false)) {
throw new IllegalArgumentException("字符 " + ckeys[j] + " 不合法!"
+ "预编译模式下 @column:value 中 value里面用 , 分割的每一项"
+ " column:alias 中 column 必须是1个单词!如果有alias,则alias也必须为1个单词!"
+ "DISTINCT 必须全大写,且后面必须有且只有 1 个空格!其它情况不允许空格!");
}
}
else {
// if ((StringUtil.isName(origin) == false || origin.startsWith("_"))) {
if (origin.startsWith("_") || PATTERN_FUNCTION.matcher(origin).matches() == false) {
throw new IllegalArgumentException("字符 " + ckeys[j] + " 不合法!"
+ "预编译模式下 @column:\"column0,column1:alias;function0(arg0,arg1,...);function1(...):alias...\""
+ " 中所有 arg 都必须是1个不以 _ 开头的单词 或者符合正则表达式 " + PATTERN_FUNCTION + " !DISTINCT 必须全大写,且后面必须有且只有 1 个空格!其它情况不允许空格!");
}
}
}
//JOIN 副表不再在外层加副表名前缀 userId AS `Commet.userId`, 而是直接 userId AS `userId`
boolean isName = false;
if (StringUtil.isNumer(origin)) {
//do nothing
}
else if (StringUtil.isName(origin)) {
origin = quote + origin + quote;
isName = true;
}
else {
origin = getValue(origin).toString();
}
if (isName && isKeyPrefix()) {
ckeys[j] = tableAlias + "." + origin;
// if (isColumn) {
// ckeys[j] += " AS " + quote + (isMain() ? "" : tableAlias + ".") + (StringUtil.isEmpty(alias, true) ? origin : alias) + quote;
// }
if (isColumn && StringUtil.isEmpty(alias, true) == false) {
ckeys[j] += " AS " + quote + alias + quote;
}
} else {
ckeys[j] = origin + (StringUtil.isEmpty(alias, true) ? "" : " AS " + quote + alias + quote);
}
if (distinct) {
ckeys[j] = PREFFIX_DISTINCT + ckeys[j];
}
}
// }
}
if (isColumn) {
keys[i] = StringUtil.getString(ckeys);
}
else {
String suffix = expression.substring(end + 1, expression.length()); //:contactCount
String alias = suffix.startsWith(":") ? suffix.substring(1) : null; //contactCount
if (StringUtil.isEmpty(alias, true)) {
if (suffix.isEmpty() == false) {
throw new IllegalArgumentException("GET请求: 预编译模式下 @column:value 中 value里面用 ; 分割的每一项"
+ " function(arg0,arg1,...):alias 中 alias 如果有就必须是1个单词!并且不要有多余的空格!");
}
}
else {
if (StringUtil.isEmpty(alias, true) == false && StringUtil.isName(alias) == false) {
throw new IllegalArgumentException("GET请求: 预编译模式下 @column:value 中 value里面用 ; 分割的每一项"
+ " function(arg0,arg1,...):alias 中 alias 必须是1个单词!并且不要有多余的空格!");
}
}
String origin = method + "(" + StringUtil.getString(ckeys) + ")";
// if (isKeyPrefix()) {
// keys[i] = origin + " AS " + quote + (isMain() ? "" : tableAlias + ".") + (StringUtil.isEmpty(alias, true) ? method : alias) + quote;
// }
// else {
keys[i] = origin + (StringUtil.isEmpty(alias, true) ? "" : " AS " + quote + alias + quote);
// }
}
}
String c = StringUtil.getString(keys);
c = c + (StringUtil.isEmpty(joinColumn, true) ? "" : ", " + joinColumn);//不能在这里改,后续还要用到:
return isMain() && isDistinct() ? PREFFIX_DISTINCT + c : c;
default:
throw new UnsupportedOperationException(
"服务器内部错误:getColumnString 不支持 " + RequestMethod.getName(getMethod())
+ " 等 [GET,GETS,HEAD,HEADS,POST] 外的ReuqestMethod!"
);
}
}
@Override
public List<List<Object>> getValues() {
return values;
}
@JSONField(serialize = false)
public String getValuesString() {
String s = "";
if (values != null && values.size() > 0) {
Object[] items = new Object[values.size()];
List<Object> vs;
for (int i = 0; i < values.size(); i++) {
vs = values.get(i);
if (vs == null) {
continue;
}
items[i] = "(";
for (int j = 0; j < vs.size(); j++) {
items[i] += ((j <= 0 ? "" : ",") + getValue(vs.get(j)));
}
items[i] += ")";
}
s = StringUtil.getString(items);
}
return s;
}
@Override
public AbstractSQLConfig setValues(List<List<Object>> valuess) {
this.values = valuess;
return this;
}
@Override
public Map<String, Object> getContent() {
return content;
}
@Override
public AbstractSQLConfig setContent(Map<String, Object> content) {
this.content = content;
return this;
}
@Override
public int getCount() {
return count;
}
@Override
public AbstractSQLConfig setCount(int count) {
this.count = count;
return this;
}
@Override
public int getPage() {