forked from Tencent/APIJSON
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbstractSQLConfig.java
More file actions
executable file
·2404 lines (2096 loc) · 76.7 KB
/
AbstractSQLConfig.java
File metadata and controls
executable file
·2404 lines (2096 loc) · 76.7 KB
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 zuo.biao.apijson.server;
import static zuo.biao.apijson.JSONObject.KEY_COLUMN;
import static zuo.biao.apijson.JSONObject.KEY_COMBINE;
import static zuo.biao.apijson.JSONObject.KEY_DATABASE;
import static zuo.biao.apijson.JSONObject.KEY_FROM;
import static zuo.biao.apijson.JSONObject.KEY_GROUP;
import static zuo.biao.apijson.JSONObject.KEY_HAVING;
import static zuo.biao.apijson.JSONObject.KEY_ID;
import static zuo.biao.apijson.JSONObject.KEY_ID_IN;
import static zuo.biao.apijson.JSONObject.KEY_ORDER;
import static zuo.biao.apijson.JSONObject.KEY_ROLE;
import static zuo.biao.apijson.JSONObject.KEY_SCHEMA;
import static zuo.biao.apijson.JSONObject.KEY_USER_ID;
import static zuo.biao.apijson.JSONObject.KEY_USER_ID_IN;
import static zuo.biao.apijson.RequestMethod.DELETE;
import static zuo.biao.apijson.RequestMethod.GET;
import static zuo.biao.apijson.RequestMethod.GETS;
import static zuo.biao.apijson.RequestMethod.HEADS;
import static zuo.biao.apijson.RequestMethod.POST;
import static zuo.biao.apijson.RequestMethod.PUT;
import static zuo.biao.apijson.SQL.AND;
import static zuo.biao.apijson.SQL.NOT;
import static zuo.biao.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 com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import zuo.biao.apijson.JSON;
import zuo.biao.apijson.Log;
import zuo.biao.apijson.NotNull;
import zuo.biao.apijson.RequestMethod;
import zuo.biao.apijson.RequestRole;
import zuo.biao.apijson.SQL;
import zuo.biao.apijson.StringUtil;
import zuo.biao.apijson.server.exception.NotExistException;
import zuo.biao.apijson.server.model.Column;
import zuo.biao.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 final Map<String, String> TABLE_KEY_MAP;
static {
TABLE_KEY_MAP = new HashMap<String, String>();
TABLE_KEY_MAP.put(Table.class.getSimpleName(), Table.TAG);
TABLE_KEY_MAP.put(Column.class.getSimpleName(), Column.TAG);
}
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 String database; //表所在的数据库类型
private String schema; //表所在的数据库名
private String table; //表名
private String alias; //表别名
private String group; //分组方式的字符串数组,','分隔
private String having; //聚合函数的字符串数组,','分隔
private String order; //排序方式的字符串数组,','分隔
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 List<Join> joinList; //连表 配置列表
//array item >>>>>>>>>>
private boolean test; //测试
private boolean cacheStatic; //静态缓存
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 String getDatabase() {
return database;
}
@Override
public SQLConfig setDatabase(String database) {
this.database = database;
return this;
}
@Override
public String getQuote() {
return DATABASE_POSTGRESQL.equals(getDatabase()) ? "\"" : "`";
}
@Override
public String getSchema() {
String sqlTable = getSQLTable();
if (StringUtil.isEmpty(schema, true) && (Table.TAG.equals(sqlTable) || Column.TAG.equals(sqlTable)) ) {
return SCHEMA_INFORMATION;
}
return schema;
}
@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.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();
return q + getSchema() + q + "." + q + getSQLTable() + q + ( isKeyPrefix() ? " AS " + getAlias() : "");
}
@Override
public AbstractSQLConfig setTable(String table) { //Table已经在Parser中校验,所以这里不用防SQL注入
this.table = table;
return this;
}
@Override
public String getAlias() {
if (StringUtil.isEmpty(alias, true)) {
alias = getTable();
}
String q = getQuote();
//getTable 不能小写,因为Verifier用大小写敏感的名称判断权限
//如果要强制小写,则可在子类重写这个方法再 toLowerCase return q + (DATABASE_POSTGRESQL.equals(getDatabase()) ? alias.toLowerCase() : alias) + q;
return q + alias + q;
}
@Override
public AbstractSQLConfig setAlias(String alias) {
this.alias = alias;
return this;
}
@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() {
//TODO 加上子表的group
group = StringUtil.getTrimedString(group);
if (group.isEmpty()) {
return "";
}
String[] keys = StringUtil.split(group);
if (keys == null || keys.length <= 0) {
return "";
}
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 " GROUP BY " + StringUtil.getString(keys);
}
@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() {
having = StringUtil.getTrimedString(having);
if(having.isEmpty()) {
return "";
}
String[] keys = StringUtil.split(having, ";");
if (keys == null || keys.length <= 0) {
return "";
}
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;
}
return " HAVING " + StringUtil.getString(keys, AND); //TODO 支持 OR, NOT 参考 @combine:"&key0,|key1,!key2"
}
@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() {
//TODO 加上子表的order
order = StringUtil.getTrimedString(order);
if (order.isEmpty()) {
return "";
}
if (order.contains("+")) {//replace没有包含的replacement会崩溃
order = order.replaceAll("\\+", " ASC ");
}
if (order.contains("-")) {
order = order.replaceAll("-", " DESC ");
}
//TODO column, order, group 都改用 List<String> 存储!!!,并且每个字段都要加 Table. 前缀!
String[] keys = StringUtil.split(order);
if (keys == null || keys.length <= 0) {
return "";
}
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 " ORDER BY " + StringUtil.getString(keys);
}
@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) {
for (String c : column) {
if (StringUtil.isName(c) == false) {
throw new IllegalArgumentException("HEAD请求: @column:value 中 value里面用 , 分割的每一项都必须是1个单词!");
}
}
}
return SQL.count(column != null && column.size() == 1 ? getKey(column.get(0)) : "*");
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);
String joinColumn = "";
if (isQuery && joinList != null) {
SQLConfig cfg;
String c;
boolean first = true;
for (Join j : joinList) {
if (j.isAppJoin()) {
continue;
}
cfg = j.getJoinConfig();
cfg.setAlias(cfg.getTable());
c = ((AbstractSQLConfig) cfg).getColumnString(true);
if (StringUtil.isEmpty(c, true) == false) {
joinColumn += (first ? "" : ", ") + c;
}
inSQLJoin = true;
first = false;
}
}
String tableAlias = getAlias();
// 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);
if (StringUtil.isName(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) {
String origin;
String alias;
int index;
for (int j = 0; j < ckeys.length; j++) {
index = ckeys[j].lastIndexOf(":"); //StringUtil.split返回数组中,子项不会有null
origin = index < 0 ? ckeys[j] : ckeys[j].substring(0, index);
alias = index < 0 ? null : ckeys[j].substring(index + 1);
if (isPrepared()) {
if (isColumn) {
if (StringUtil.isName(origin) == false || (alias != null && StringUtil.isName(alias) == false)) {
throw new IllegalArgumentException("GET请求: 预编译模式下 @column:value 中 value里面用 , 分割的每一项"
+ " column:alias 中 column 必须是1个单词!如果有alias,则alias也必须为1个单词!并且不要有多余的空格!");
}
}
else {
if ((StringUtil.isName(ckeys[j]) == false || ckeys[j].startsWith("_"))) {
throw new IllegalArgumentException("字符 " + ckeys[j] + " 不合法!"
+ "预编译模式下 @column:\"column0,column1:alias;function0(arg0,arg1,...);function1(...):alias...\""
+ " 中所有 arg 都必须是1个不以 _ 开头的单词!并且不要有空格!");
}
}
}
//JOIN 副表不再在外层加副表名前缀 userId AS `Commet.userId`, 而是直接 userId AS `userId`
origin = quote + origin + quote;
if (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 (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);
return (c.contains(":") == false ? c : c.replaceAll(":", " AS ")) + (StringUtil.isEmpty(joinColumn, true) ? "" : ", " + joinColumn);//不能在这里改,后续还要用到:
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() {
return page;
}
@Override
public AbstractSQLConfig setPage(int page) {
this.page = page;
return this;
}
@Override
public int getPosition() {
return position;
}
@Override
public AbstractSQLConfig setPosition(int position) {
this.position = position;
return this;
}
@Override
public int getQuery() {
return query;
}
@Override
public AbstractSQLConfig setQuery(int query) {
this.query = query;
return this;
}
@Override
public int getType() {
return type;
}
@Override
public AbstractSQLConfig setType(int type) {
this.type = type;
return this;
}
@Override
public List<Join> getJoinList() {
return joinList;
}
@Override
public SQLConfig setJoinList(List<Join> joinList) {
this.joinList = joinList;
return this;
}
@Override
public boolean hasJoin() {
return joinList != null && joinList.isEmpty() == false;
}
@Override
public boolean isTest() {
return test;
}
@Override
public AbstractSQLConfig setTest(boolean test) {
this.test = test;
return this;
}
@Override
public boolean isCacheStatic() {
return cacheStatic;
}
@Override
public AbstractSQLConfig setCacheStatic(boolean cacheStatic) {
this.cacheStatic = cacheStatic;
return this;
}
/**获取初始位置offset
* @return
*/
@JSONField(serialize = false)
public int getOffset() {
return getOffset(getPage(), getCount());
}
/**获取初始位置offset
* @param page
* @param count
* @return
*/
public static int getOffset(int page, int count) {
return page*count;
}
/**获取限制数量
* @return
*/
@JSONField(serialize = false)
public String getLimitString() {
return getLimitString(getPage(), getCount());// + 1);
}
/**获取限制数量
* @param limit
* @return
*/
public static String getLimitString(int page, int count) {
return count <= 0 ? "" : " LIMIT " + count + " OFFSET " + getOffset(page, count);
}
//WHERE <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
@Override
public Map<String, Object> getWhere() {
return where;
}
@Override
public AbstractSQLConfig setWhere(Map<String, Object> where) {
this.where = where;
return this;
}
@NotNull
@Override
public Map<String, List<String>> getCombine() {
List<String> andList = combine == null ? null : combine.get("&");
if (andList == null) {
andList = where == null ? new ArrayList<String>() : new ArrayList<String>(where.keySet());
if (combine == null) {
combine = new HashMap<>();
}
combine.put("&", andList);
}
return combine;
}
@Override
public AbstractSQLConfig setCombine(Map<String, List<String>> combine) {
this.combine = combine;
return this;
}
/**
* noFunctionChar = false
* @param key
* @return
*/
@JSONField(serialize = false)
@Override
public Object getWhere(String key) {
return getWhere(key, false);
}
/**
* @param key
* @param exactMatch
* @return
*/
@JSONField(serialize = false)
@Override
public Object getWhere(String key, boolean exactMatch) {
if (exactMatch) {
return where == null ? null : where.get(key);
}
Set<String> set = key == null || where == null ? null : where.keySet();
if (set != null) {
synchronized (where) {
if (where != null) {
int index;
for (String k : set) {
index = k.indexOf(key);
if (index >= 0 && StringUtil.isName(k.substring(index)) == false) {
return where.get(k);
}
}
}
}
}
return null;
}
@Override
public AbstractSQLConfig putWhere(String key, Object value, boolean prior) {
if (key != null) {
if (where == null) {
where = new LinkedHashMap<String, Object>();
}
if (value == null) {
where.remove(key);
} else {
where.put(key, value);
}
combine = getCombine();
List<String> andList = combine.get("&");
if (value == null) {
andList.remove(key);
}
else if (andList == null || andList.contains(key) == false) {
int i = 0;
if (andList == null) {
andList = new ArrayList<>();
}
else if (prior && andList.isEmpty() == false) {
if (andList.contains(KEY_ID)) {
i ++;
}
if (andList.contains(KEY_ID_IN)) {
i ++;
}
if (andList.contains(KEY_USER_ID)) {
i ++;
}
if (andList.contains(KEY_USER_ID_IN)) {
i ++;
}
}
if (prior) {
andList.add(i, key); //userId的优先级不能比id高 0, key);
} else {
andList.add(key); //AbstractSQLExecutor.onPutColumn里getSQL,要保证缓存的SQL和查询的SQL里 where 的 key:value 顺序一致
}
}
combine.put("&", andList);
}
return this;
}
/**获取WHERE
* @return
* @throws Exception
*/
@JSONField(serialize = false)
@Override
public String getWhereString(boolean hasPrefix) throws Exception {
return getWhereString(hasPrefix, getMethod(), getWhere(), getCombine(), getJoinList(), ! isTest());
}
/**获取WHERE
* @param method
* @param where
* @return
* @throws Exception
*/
@JSONField(serialize = false)
public String getWhereString(boolean hasPrefix, RequestMethod method, Map<String, Object> where, Map<String, List<String>> combine, List<Join> joinList, boolean verifyName) throws Exception {
Set<Entry<String, List<String>>> combineSet = combine == null ? null : combine.entrySet();
if (combineSet == null || combineSet.isEmpty()) {
Log.w(TAG, "getWhereString combineSet == null || combineSet.isEmpty() >> return \"\";");
return "";
}
List<String> keyList;
String whereString = "";
boolean isCombineFirst = true;
int logic;
boolean isItemFirst;
String c;
String cs;
for (Entry<String, List<String>> ce : combineSet) {
keyList = ce == null ? null : ce.getValue();
if (keyList == null || keyList.isEmpty()) {
continue;
}
if ("|".equals(ce.getKey())) {
logic = Logic.TYPE_OR;
}
else if ("!".equals(ce.getKey())) {
logic = Logic.TYPE_NOT;
}
else {
logic = Logic.TYPE_AND;
}
isItemFirst = true;
cs = "";
for (String key : keyList) {
c = getWhereItem(key, where.get(key), method, verifyName);
if (StringUtil.isEmpty(c, true)) {//避免SQL条件连接错误
continue;
}