Repository navigation
Expand file tree
/
Copy pathAbstractSQLConfig.java
More file actions
executable file
·1355 lines (1214 loc) · 40.4 KB
/
Copy pathAbstractSQLConfig.java
File metadata and controls
executable file
·1355 lines (1214 loc) · 40.4 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_ABOUT;
import static zuo.biao.apijson.JSONObject.KEY_COLUMN;
import static zuo.biao.apijson.JSONObject.KEY_CONDITION;
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_USER_ID;
import static zuo.biao.apijson.JSONObject.KEY_USER_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.RequestMethod.DELETE;
import static zuo.biao.apijson.RequestMethod.GET;
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 com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import zuo.biao.apijson.Log;
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 = "SQLConfig";
/**
* 表名映射,隐藏真实表名,对安全要求很高的表可以这么做
*/
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 long id; //Table的id
private RequestMethod method; //操作方法
/**
* TODO 被关联的表通过就忽略关联的表?(这个不行 User:{"sex@":"/Comment/toId"})
*/
private RequestRole role; //发送请求的用户的角色
private String schema; //Table所在的数据库
private String table; //Table名
private boolean about; //关于,返回数据库表的信息,包括表说明和字段说明
private String group; //分组方式的字符串数组,','分隔
private String having; //聚合函数的字符串数组,','分隔
private String order; //排序方式的字符串数组,','分隔
private String column; //Table内字段名(或函数名,仅查询操作可用)的字符串数组,','分隔
private String values; //对应Table内字段的值的字符串数组,','分隔
private Map<String, Object> content; //Request内容,key:value形式,column = content.keySet(),values = content.values()
private Map<String, Object> where; //筛选条件,key:value形式
//array item <<<<<<<<<<
private int count; //Table数量
private int page; //Table所在页码
private int position; //Table在[]中的位置
private int query; //JSONRequest.query
private int type; //ObjectParser.type
//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 long getId() {
return id;
}
@Override
public AbstractSQLConfig setId(long 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 getSchema() {
String sqlTable = getSQLTable();
if (sqlTable != null && sqlTable.startsWith("`")) {
return SCHEMA_INFORMATION;
}
return schema;
}
@Override
public AbstractSQLConfig setSchema(String schema) {
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() {
return TABLE_KEY_MAP.containsKey(table) ? TABLE_KEY_MAP.get(table) : table;
}
@JSONField(serialize = false)
@Override
public String getTablePath() {
return getSchema() + "." + getSQLTable();
}
@Override
public AbstractSQLConfig setTable(String table) {
this.table = table;
return this;
}
@Override
public boolean isAbout() {
return about;
}
@Override
public AbstractSQLConfig setAbout(boolean about) {
this.about = about;
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() {
group = StringUtil.getTrimedString(group);
return group.isEmpty() ? "" : " GROUP BY " + group;
}
@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;
}
@JSONField(serialize = false)
public String getHavingString() {
having = StringUtil.getTrimedString(having);
return having.isEmpty() ? "" : " HAVING " + having;
}
@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() {
order = StringUtil.getTrimedString(order);
if (order.isEmpty()) {
return "";
}
if (order.contains("+")) {//replace没有包含的replacement会崩溃
order = order.replaceAll("\\+", " ASC ");
}
if (order.contains("-")) {
order = order.replaceAll("-", " DESC ");
}
return " ORDER BY " + order;
}
@Override
public String getColumn() {
return column;
}
public AbstractSQLConfig setColumn(String... keys) {
return setColumn(StringUtil.getString(keys));
}
@Override
public AbstractSQLConfig setColumn(String column) {
this.column = column;
return this;
}
@JSONField(serialize = false)
public String getColumnString() throws NotExistException {
switch (getMethod()) {
case HEAD:
case HEADS:
return SQL.count(column);
case POST:
if (StringUtil.isEmpty(column, true)) {
throw new NotExistException(TAG + "getColumnString getMethod() = POST"
+ " >> StringUtil.isEmpty(column, true)");
}
return "(" + column + ")";
default:
column = StringUtil.getString(column);
if (column.isEmpty()) {
return "*";
}
return column.contains(":") == false ? column : column.replaceAll(":", " AS ");//不能在这里改,后续还要用到:
}
}
@Override
public String getValues() {
return values;
}
@JSONField(serialize = false)
public String getValuesString() {
return values;
}
public AbstractSQLConfig setValues(String[][] valuess) {
String s = "";
if (valuess != null && valuess.length > 0) {
String[] items = new String[valuess.length];
for (int i = 0; i < valuess.length; i++) {
items[i] = "(" + StringUtil.getString(valuess[i]) + ")";
}
s = StringUtil.getString(items);
}
return setValues(s);
}
@Override
public AbstractSQLConfig setValues(String values) {
this.values = values;
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 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 " + getOffset(page, count) + ", " + count;
}
//WHERE <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
@Override
public Map<String, Object> getWhere() {
return where;
}
@Override
public AbstractSQLConfig setWhere(Map<String, Object> where) {
this.where = where;
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) {
if (key != null) {
if (where == null) {
where = new LinkedHashMap<String, Object>();
}
where.put(key, value);
}
return this;
}
/**获取WHERE
* @return
* @throws Exception
*/
@JSONField(serialize = false)
public String getWhereString() throws Exception {
return getWhereString(getMethod(), getWhere(), ! isTest());
}
/**获取WHERE
* @param method
* @param where
* @return
* @throws Exception
*/
public static String getWhereString(RequestMethod method, Map<String, Object> where, boolean verifyName) throws Exception {
Map<String, Object> where2 = where == null || where.isEmpty() ? null : new LinkedHashMap<String, Object>();
if (where2 == null) {
return "";
}
//强制排序,把id,id{},userId,userId{}放最前面,保证安全、优化性能
Object id = where.remove(KEY_ID);
Object idIn = where.remove(KEY_ID_IN);
Object userId = where.remove(KEY_USER_ID);
Object userIdIn = where.remove(KEY_USER_ID_IN);
where2.put(KEY_ID, id);
where2.put(KEY_ID_IN, idIn);
where2.put(KEY_USER_ID, userId);
where2.put(KEY_USER_ID_IN, userIdIn);
where2.putAll(where);
Set<Entry<String, Object>> set = where2.entrySet();
boolean isFirst = true;
String condition;
String whereString = "";
for (Entry<String, Object> entry : set) {
if (entry == null) {
continue;
}
condition = getWhereItem(entry.getKey(), entry.getValue(), method, verifyName);
if (StringUtil.isEmpty(condition, true)) {//避免SQL条件连接错误
continue;
}
whereString += (isFirst ? "" : AND) + "(" + condition + ")";
isFirst = false;
}
//还原where,后续可能用到
where.put(KEY_ID, id);
where.put(KEY_ID_IN, idIn);
where.put(KEY_USER_ID, userId);
where.put(KEY_USER_ID_IN, userIdIn);
String s = whereString.isEmpty() ? "" : " WHERE " + whereString;
if (s.isEmpty() && RequestMethod.isQueryMethod(method) == false) {
throw new UnsupportedOperationException("写操作请求必须带条件!!!");
}
return s;
}
/**
* @param key
* @param value
* @param method
* @param verifyName
* @return
* @throws Exception
*/
private static String getWhereItem(String key, Object value
, RequestMethod method, boolean verifyName) throws Exception {
Log.d(TAG, "getWhereItem key = " + key);
//避免筛选到全部 value = key == null ? null : where.get(key);
if (key == null || value == null || key.startsWith("@") || key.endsWith("()")) {//关键字||方法, +或-直接报错
Log.d(TAG, "getWhereItem key == null || value == null"
+ " || key.startsWith(@) || key.endsWith(()) >> continue;");
return null;
}
if (key.endsWith("@")) {//引用
// key = key.substring(0, key.lastIndexOf("@"));
throw new IllegalArgumentException(TAG + ".getWhereItem: 字符 " + key + " 不合法!");
}
int keyType;
if (key.endsWith("$")) {
keyType = 1;
}
else if (key.endsWith("?")) {
keyType = 2;
}
else if (key.endsWith("{}")) {
keyType = 3;
}
else if (key.endsWith("<>")) {
keyType = 4;
}
else { //else绝对不能省,避免再次踩坑! keyType = 0; 写在for循环外面都没注意!
keyType = 0;
}
key = getRealKey(method, key, false, true, verifyName);
switch (keyType) {
case 1:
return getSearchString(key, value);
case 2:
return getRegExpString(key, value);
case 3:
return getRangeString(key, value);
case 4:
return getContainString(key, value);
default:
return (key + "='" + value + "'");
}
}
//$ search <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/**search key match value
* @param in
* @return {@link #getSearchString(String, Object[], int)}
* @throws IllegalArgumentException
*/
public static String getSearchString(String key, Object value) throws IllegalArgumentException {
if (value == null) {
return "";
}
Logic logic = new Logic(key);
key = logic.getKey();
Log.i(TAG, "getRangeString key = " + key);
JSONArray arr = newJSONArray(value);
if (arr.isEmpty()) {
return "";
}
return getSearchString(key, arr.toArray(), logic.getType());
}
/**search key match values
* @param in
* @return LOGIC [ key LIKE 'values[i]' ]
* @throws IllegalArgumentException
*/
public static String getSearchString(String key, Object[] values, int type) throws IllegalArgumentException {
if (values == null || values.length <= 0) {
return "";
}
String condition = "";
for (int i = 0; i < values.length; i++) {
if (values[i] instanceof String == false) {
throw new IllegalArgumentException(key + "$\":value 中value只能为String或JSONArray<String>!");
}
condition += (i <= 0 ? "" : (Logic.isAnd(type) ? AND : OR)) + getLikeString(key, values[i]);
}
return getCondition(Logic.isNot(type), condition);
}
/**WHERE key LIKE 'value'
* @param key endsWith("!") ? key = key.substring(0, key.length() - 1) + NOT;
* @param value
* @return key LIKE 'value'
*/
public static String getLikeString(String key, Object value) {
return key + " LIKE '" + value + "'";
}
//$ search >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//$ search <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/**search key match RegExps value
* @param in
* @return {@link #getRegExpString(String, Object[], int)}
* @throws IllegalArgumentException
*/
public static String getRegExpString(String key, Object value) throws IllegalArgumentException {
if (value == null) {
return "";
}
Logic logic = new Logic(key);
key = logic.getKey();
Log.i(TAG, "getRangeString key = " + key);
JSONArray arr = newJSONArray(value);
if (arr.isEmpty()) {
return "";
}
return getRegExpString(key, arr.toArray(), logic.getType());
}
/**search key match RegExp values
* @param in
* @return LOGIC [ key REGEXP 'values[i]' ]
* @throws IllegalArgumentException
*/
public static String getRegExpString(String key, Object[] values, int type) throws IllegalArgumentException {
if (values == null || values.length <= 0) {
return "";
}
String condition = "";
for (int i = 0; i < values.length; i++) {
if (values[i] instanceof String == false) {
throw new IllegalArgumentException(key + "$\":value 中value只能为String或JSONArray<String>!");
}
condition += (i <= 0 ? "" : (Logic.isAnd(type) ? AND : OR)) + getRegExpString(key, (String) values[i]);
}
return getCondition(Logic.isNot(type), condition);
}
/**WHERE key REGEXP 'value'
* @param key
* @param value
* @return key REGEXP 'value'
*/
public static String getRegExpString(String key, String value) {
return key + " REGEXP '" + value + "'";
}
//$ search >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//{} range <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/**WHERE key > 'key0' AND key <= 'key1' AND ...
* @param key
* @param range "condition0,condition1..."
* @return key condition0 AND key condition1 AND ...
* @throws Exception
*/
public static String getRangeString(String key, Object range) throws Exception {
Log.i(TAG, "getRangeString key = " + key);
if (range == null) {//依赖的对象都没有给出有效值,这个存在无意义。如果是客户端传的,那就能在客户端确定了。
throw new NotExistException(TAG + "getRangeString(" + key + ", " + range
+ ") range == null");
}
Logic logic = new Logic(key);
key = logic.getKey();
Log.i(TAG, "getRangeString key = " + key);
if (range instanceof List) {
if (logic.isOr() || logic.isNot()) {
return key + getInString(key, ((List<?>) range).toArray(), logic.isNot());
}
throw new IllegalArgumentException(key + "{}\":[] 中key末尾的逻辑运算符只能用'|','!'中的一种 !");
}
if (range instanceof String) {//非Number类型需要客户端拼接成 < 'value0', >= 'value1'这种
String[] conditions = StringUtil.split((String) range);
String condition = "";
if (conditions != null) {
int index;
for (int i = 0; i < conditions.length; i++) {//对函数条件length(key)<=5这种不再在开头加key
index = conditions[i] == null ? -1 : conditions[i].indexOf("(");
condition += ((i <= 0 ? "" : (logic.isAnd() ? AND : OR))//连接方式
+ (index >= 0 && index < conditions[i].indexOf(")") ? "" : key + " ")//函数和非函数条件
+ conditions[i]);//单个条件
}
}
if (condition.isEmpty()) {
return "";
}
return getCondition(logic.isNot(), condition);
}
throw new IllegalArgumentException(key + "{}:range 类型为" + range.getClass().getSimpleName()
+ "!range只能是 用','分隔条件的字符串 或者 可取选项JSONArray!");
}
/**WHERE key IN ('key0', 'key1', ... )
* @param in
* @return IN ('key0', 'key1', ... )
* @throws NotExistException
*/
public static String getInString(String key, Object[] in, boolean not) throws NotExistException {
String condition = "";
if (in != null) {//返回 "" 会导致 id:[] 空值时效果和没有筛选id一样!
for (int i = 0; i < in.length; i++) {
condition += ((i > 0 ? "," : "") + "'" + in[i] + "'");
}
}
if (condition.isEmpty()) {//条件如果存在必须执行,不能忽略。条件为空会导致出错,又很难保证条件不为空(@:条件),所以还是这样好
throw new NotExistException(TAG + ".getInString(" + key + ", [], " + not
+ ") >> condition.isEmpty() >> IN()");
}
return (not ? NOT : "") + " IN (" + condition + ")";
}
//{} range >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//<> contain <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/**WHERE key contains value
* @param key
* @param value
* @return {@link #getContainString(String, Object[], int)}
* @throws NotExistException
*/
public static String getContainString(String key, Object value) throws NotExistException {
if (value == null) {
return "";
}
Logic logic = new Logic(key);
key = logic.getKey();
Log.i(TAG, "getRangeString key = " + key);
//TODO 直接调Like性能最好!
return getContainString(key, newJSONArray(value).toArray(), logic.getType());
}
/**WHERE key contains childs
* @param key
* @param childs null ? "" : (empty ? no child : contains childs)
* @param type |, &, !
* @return LOGIC [ ( key LIKE '[" + childs[i] + "]' OR key LIKE '[" + childs[i] + ", %'
* OR key LIKE '%, " + childs[i] + ", %' OR key LIKE '%, " + childs[i] + "]' ) ]
* @throws IllegalArgumentException
*/
public static String getContainString(String key, Object[] childs, int type) throws IllegalArgumentException {
String condition = "";
if (childs != null) {
for (int i = 0; i < childs.length; i++) {
if (childs[i] != null) {
if (childs[i] instanceof JSON) {
throw new IllegalArgumentException(key + "<>\":value 中value类型不能为JSON!");
}
if (childs[i] instanceof String) {
childs[i] = "\"" + childs[i] + "\"";
}
condition += (i <= 0 ? "" : (Logic.isAnd(type) ? AND : OR))
+ "(" + getSearchString(
key
, new String[]{
"[" + childs[i] + "]", //全等
"[" + childs[i] + ", %", //开始
"%, " + childs[i] + ", %", //中间
"%, " + childs[i] + "]" //末尾
}
, Logic.TYPE_OR
) + ")";
}
}
if (condition.isEmpty()) {
condition = (SQL.isEmpty(key, true) + OR + getLikeString(key, "[]"));
}
}
if (condition.isEmpty()) {
return "";
}
return getCondition(Logic.isNot(type), condition);
}
//<> contain >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
/**拼接条件
* @param not
* @param condition
* @return
*/
private static String getCondition(boolean not, String condition) {
return not ? NOT + "(" + condition + ")" : condition;
}
/**转为JSONArray
* @param tv
* @return
*/
@NotNull
public static JSONArray newJSONArray(Object obj) {
JSONArray array = new JSONArray();
if (obj != null) {
if (obj instanceof Collection) {
array.addAll((Collection<?>) obj);
} else {
array.add(obj);
}
}
return array;
}
//WHERE >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//SET <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/**获取SET
* @return
* @throws Exception
*/
@JSONField(serialize = false)
public String getSetString() throws Exception {
return getSetString(getMethod(), getContent(), ! isTest());
}
/**获取SET
* @param method
* @param content
* @return
* @throws Exception
*/
public static String getSetString(RequestMethod method, Map<String, Object> content, boolean verifyName) throws Exception {
Set<String> set = content == null ? null : content.keySet();
if (set != null && set.size() > 0) {
String setString = "";
boolean isFirst = true;
int keyType = 0;// 0 - =; 1 - +, 2 - -
Object value;
for (String key : set) {
//避免筛选到全部 value = key == null ? null : content.get(key);
if (key == null || KEY_ID.equals(key)) {
continue;
}
if (key.endsWith("+")) {
keyType = 1;
} else if (key.endsWith("-")) {
keyType = 2;
}
value = content.get(key);
key = getRealKey(method, key, false, true, verifyName);
setString += (isFirst ? "" : ", ") + (key + "=" + (keyType == 1 ? getAddString(key, value) : (keyType == 2
? getRemoveString(key, value) : "'" + value + "'") ) );
isFirst = false;
}
if (setString.isEmpty()) {
throw new NotExistException(TAG + "getSetString >> setString.isEmpty()");
}
return " SET " + setString;
}
return "";
}
/**SET key = CONCAT (key, 'value')
* @param key
* @param value
* @return CONCAT (key, 'value')
* @throws IllegalArgumentException
*/
public static String getAddString(String key, Object value) throws IllegalArgumentException {
if (value instanceof Number) {
return key + " + " + value;
}
if (value instanceof String) {
return " CONCAT (" + key + ", '" + value + "') ";
}
throw new IllegalArgumentException(key + "+ 对应的值 " + value + " 不是Number,String,Array中的任何一种!");
}
/**SET key = replace(key, 'value', '')
* @param key
* @param value
* @return REPLACE (key, 'value', '')
* @throws IllegalArgumentException
*/
public static String getRemoveString(String key, Object value) throws IllegalArgumentException {
if (value instanceof Number) {
return key + " - " + value;
}
if (value instanceof String) {
return SQL.replace(key, (String) value, "");// " replace(" + key + ", '" + value + "', '') ";
}
throw new IllegalArgumentException(key + "- 对应的值 " + value + " 不是Number,String,Array中的任何一种!");
}
//SET >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
/**
* @return
* @throws Exception
*/
@JSONField(serialize = false)
@Override
public String getSQL() throws Exception {
return getSQL(this);
}
/**
* @param config
* @return
* @throws Exception
*/
public static String getSQL(AbstractSQLConfig config) throws Exception {
String tablePath = config == null ? null : config.getTablePath();
if (StringUtil.isNotEmpty(tablePath, true) == false) {
Log.i(TAG, "getSQL StringUtil.isNotEmpty(tablePath, true) == false >> return null;");
return null;
}
switch (config.getMethod()) {
case POST:
return "INSERT INTO " + tablePath + config.getColumnString() + " VALUES" + config.getValuesString();
case PUT:
return "UPDATE " + tablePath + config.getSetString() + config.getWhereString();
case DELETE: