forked from Tencent/APIJSON
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAbstractSQLConfig.java
executable file
·3525 lines (3079 loc) · 129 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 (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
This source code is licensed under the Apache License Version 2.0.*/
package apijson.orm;
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_DATASOURCE;
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_RAW;
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.JSONResponse;
import apijson.Log;
import apijson.NotNull;
import apijson.RequestMethod;
import apijson.RequestRole;
import apijson.SQL;
import apijson.StringUtil;
import apijson.orm.exception.NotExistException;
import apijson.orm.model.Access;
import apijson.orm.model.Column;
import apijson.orm.model.Document;
import apijson.orm.model.ExtendedProperty;
import apijson.orm.model.Function;
import apijson.orm.model.PgAttribute;
import apijson.orm.model.PgClass;
import apijson.orm.model.Request;
import apijson.orm.model.Response;
import apijson.orm.model.SysColumn;
import apijson.orm.model.SysTable;
import apijson.orm.model.Table;
import apijson.orm.model.TestRecord;
/**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 ";
// * 和 / 不能同时出现,防止 /* */ 段注释! # 和 -- 不能出现,防止行注释! ; 不能出现,防止隔断SQL语句!空格不能出现,防止 CRUD,DROP,SHOW TABLES等语句!
private static final Pattern PATTERN_RANGE;
private static final Pattern PATTERN_FUNCTION;
/**
* 表名映射,隐藏真实表名,对安全要求很高的表可以这么做
*/
public static final Map<String, String> TABLE_KEY_MAP;
public static final List<String> CONFIG_TABLE_LIST;
public static final List<String> DATABASE_LIST;
// 自定义原始 SQL 片段 Map<key, substring>:当 substring 为 null 时忽略;当 substring 为 "" 时整个 value 是 raw SQL;其它情况则只是 substring 这段为 raw SQL
public static final Map<String, String> RAW_MAP;
// 允许调用的 SQL 函数:当 substring 为 null 时忽略;当 substring 为 "" 时整个 value 是 raw SQL;其它情况则只是 substring 这段为 raw SQL
public static final Map<String, String> SQL_FUNCTION_MAP;
static { // 凡是 SQL 边界符、分隔符、注释符 都不允许,例如 ' " ` ( ) ; # -- ,以免拼接 SQL 时被注入意外可执行指令
PATTERN_RANGE = Pattern.compile("^[0-9%,!=\\<\\>/\\.\\+\\-\\*\\^]+$"); // ^[a-zA-Z0-9_*%!=<>(),"]+$ 导致 exists(select*from(Comment)) 通过!
PATTERN_FUNCTION = Pattern.compile("^[A-Za-z0-9%,:_@&~!=\\<\\>\\|\\[\\]\\{\\} /\\.\\+\\-\\*\\^\\?\\$]+$"); //TODO 改成更好的正则,校验前面为单词,中间为操作符,后面为值
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);
CONFIG_TABLE_LIST = new ArrayList<>(); // Table, Column 等是系统表 AbstractVerifier.SYSTEM_ACCESS_MAP.keySet());
CONFIG_TABLE_LIST.add(Function.class.getSimpleName());
CONFIG_TABLE_LIST.add(Request.class.getSimpleName());
CONFIG_TABLE_LIST.add(Response.class.getSimpleName());
CONFIG_TABLE_LIST.add(Access.class.getSimpleName());
CONFIG_TABLE_LIST.add(Document.class.getSimpleName());
CONFIG_TABLE_LIST.add(TestRecord.class.getSimpleName());
DATABASE_LIST = new ArrayList<>();
DATABASE_LIST.add(DATABASE_MYSQL);
DATABASE_LIST.add(DATABASE_POSTGRESQL);
DATABASE_LIST.add(DATABASE_SQLSERVER);
DATABASE_LIST.add(DATABASE_ORACLE);
DATABASE_LIST.add(DATABASE_DB2);
RAW_MAP = new LinkedHashMap<>(); // 保证顺序,避免配置冲突等意外情况
SQL_FUNCTION_MAP = new LinkedHashMap<>(); // 保证顺序,避免配置冲突等意外情况
// MySQL 字符串函数
SQL_FUNCTION_MAP.put("ascii", ""); // ASCII(s) 返回字符串 s 的第一个字符的 ASCII 码。
SQL_FUNCTION_MAP.put("char_length", ""); // CHAR_LENGTH(s) 返回字符串 s 的字符数
SQL_FUNCTION_MAP.put("character_length", ""); // CHARACTER_LENGTH(s) 返回字符串 s 的字符数
SQL_FUNCTION_MAP.put("concat", ""); // CONCAT(s1, s2...sn) 字符串 s1,s2 等多个字符串合并为一个字符串
SQL_FUNCTION_MAP.put("concat_ws", ""); // CONCAT_WS(x, s1, s2...sn) 同 CONCAT(s1, s2 ...) 函数,但是每个字符串之间要加上 x,x 可以是分隔符
SQL_FUNCTION_MAP.put("field", ""); // FIELD(s, s1, s2...) 返回第一个字符串 s 在字符串列表 (s1, s2...)中的位置
SQL_FUNCTION_MAP.put("find_in_set", ""); // FIND_IN_SET(s1, s2) 返回在字符串s2中与s1匹配的字符串的位置
SQL_FUNCTION_MAP.put("format", ""); // FORMAT(x, n) 函数可以将数字 x 进行格式化 "#,###.##", 将 x 保留到小数点后 n 位,最后一位四舍五入。
SQL_FUNCTION_MAP.put("insert", ""); // INSERT(s1, x, len, s2) 字符串 s2 替换 s1 的 x 位置开始长度为 len 的字符串
SQL_FUNCTION_MAP.put("locate", ""); // LOCATE(s1, s) 从字符串 s 中获取 s1 的开始位置
SQL_FUNCTION_MAP.put("lcase", ""); // LCASE(s) 将字符串 s 的所有字母变成小写字母
SQL_FUNCTION_MAP.put("left", ""); // LEFT(s, n) 返回字符串 s 的前 n 个字符
SQL_FUNCTION_MAP.put("length", ""); // LENGTH(s) 返回字符串 s 的字符数
SQL_FUNCTION_MAP.put("lower", ""); // LOWER(s) 将字符串 s 的所有字母变成小写字母
SQL_FUNCTION_MAP.put("lpad", ""); // LPAD(s1, len, s2) 在字符串 s1 的开始处填充字符串 s2,使字符串长度达到 len
SQL_FUNCTION_MAP.put("ltrim", ""); // LTRIM(s) 去掉字符串 s 开始处的空格
SQL_FUNCTION_MAP.put("mid", ""); // MID(s, n, len) 从字符串 s 的 n 位置截取长度为 len 的子字符串,同 SUBSTRING(s, n, len)
SQL_FUNCTION_MAP.put("position", ""); // POSITION(s, s1); 从字符串 s 中获取 s1 的开始位置
SQL_FUNCTION_MAP.put("repeat", ""); // REPEAT(s, n) 将字符串 s 重复 n 次
SQL_FUNCTION_MAP.put("replace", ""); // REPLACE(s, s1, s2) 将字符串 s2 替代字符串 s 中的字符串 s1
SQL_FUNCTION_MAP.put("reverse", ""); // REVERSE(s); // ) 将字符串s的顺序反过来
SQL_FUNCTION_MAP.put("right", ""); // RIGHT(s, n) 返回字符串 s 的后 n 个字符
SQL_FUNCTION_MAP.put("rpad", ""); // RPAD(s1, len, s2) 在字符串 s1 的结尾处添加字符串 s2,使字符串的长度达到 len
SQL_FUNCTION_MAP.put("rtrim", ""); // RTRIM", ""); // ) 去掉字符串 s 结尾处的空格
SQL_FUNCTION_MAP.put("space", ""); // SPACE(n) 返回 n 个空格
SQL_FUNCTION_MAP.put("strcmp", ""); // STRCMP(s1, s2) 比较字符串 s1 和 s2,如果 s1 与 s2 相等返回 0 ,如果 s1>s2 返回 1,如果 s1<s2 返回 -1
SQL_FUNCTION_MAP.put("substr", ""); // SUBSTR(s, start, length) 从字符串 s 的 start 位置截取长度为 length 的子字符串
SQL_FUNCTION_MAP.put("substring", ""); // STRING(s, start, length)) 从字符串 s 的 start 位置截取长度为 length 的子字符串
SQL_FUNCTION_MAP.put("substring_index", ""); // SUBSTRING_INDEX(s, delimiter, number) 返回从字符串 s 的第 number 个出现的分隔符 delimiter 之后的子串。
SQL_FUNCTION_MAP.put("trim", ""); // TRIM(s) 去掉字符串 s 开始和结尾处的空格
SQL_FUNCTION_MAP.put("ucase", ""); // UCASE(s) 将字符串转换为大写
SQL_FUNCTION_MAP.put("upper", ""); // UPPER(s) 将字符串转换为大写
// MySQL 数字函数
SQL_FUNCTION_MAP.put("abs", ""); // ABS(x) 返回 x 的绝对值
SQL_FUNCTION_MAP.put("acos", ""); // ACOS(x) 求 x 的反余弦值(参数是弧度)
SQL_FUNCTION_MAP.put("asin", ""); // ASIN(x) 求反正弦值(参数是弧度)
SQL_FUNCTION_MAP.put("atan", ""); // ATAN(x) 求反正切值(参数是弧度)
SQL_FUNCTION_MAP.put("atan2", ""); // ATAN2(n, m) 求反正切值(参数是弧度)
SQL_FUNCTION_MAP.put("avg", ""); // AVG(expression) 返回一个表达式的平均值,expression 是一个字段
SQL_FUNCTION_MAP.put("ceil", ""); // CEIL(x) 返回大于或等于 x 的最小整数
SQL_FUNCTION_MAP.put("ceiling", ""); // CEILING(x) 返回大于或等于 x 的最小整数
SQL_FUNCTION_MAP.put("cos", ""); // COS(x) 求余弦值(参数是弧度)
SQL_FUNCTION_MAP.put("cot", ""); // COT(x) 求余切值(参数是弧度)
SQL_FUNCTION_MAP.put("count", ""); // COUNT(expression) 返回查询的记录总数,expression 参数是一个字段或者 * 号
SQL_FUNCTION_MAP.put("degrees", ""); // DEGREES(x) 将弧度转换为角度
SQL_FUNCTION_MAP.put("div", ""); // n DIV m 整除,n 为被除数,m 为除数
SQL_FUNCTION_MAP.put("exp", ""); // EXP(x) 返回 e 的 x 次方
SQL_FUNCTION_MAP.put("floor", ""); // FLOOR(x) 返回小于或等于 x 的最大整数
SQL_FUNCTION_MAP.put("greatest", ""); // GREATEST(expr1, expr2, expr3, ...) 返回列表中的最大值
SQL_FUNCTION_MAP.put("least", ""); // LEAST(expr1, expr2, expr3, ...) 返回列表中的最小值
SQL_FUNCTION_MAP.put("ln", ""); // 2); LN 返回数字的自然对数,以 e 为底。
SQL_FUNCTION_MAP.put("log", ""); // LOG(x) 或 LOG(base, x) 返回自然对数(以 e 为底的对数),如果带有 base 参数,则 base 为指定带底数。
SQL_FUNCTION_MAP.put("log10", ""); // LOG10(x) 返回以 10 为底的对数
SQL_FUNCTION_MAP.put("log2", ""); // LOG2(x) 返回以 2 为底的对数
SQL_FUNCTION_MAP.put("max", ""); // MAX(expression) 返回字段 expression 中的最大值
SQL_FUNCTION_MAP.put("min", ""); // MIN(expression) 返回字段 expression 中的最小值
SQL_FUNCTION_MAP.put("mod", ""); // MOD(x,y) 返回 x 除以 y 以后的余数
SQL_FUNCTION_MAP.put("pi", ""); // PI() 返回圆周率(3.141593)
SQL_FUNCTION_MAP.put("pow", ""); // POW(x,y) 返回 x 的 y 次方
SQL_FUNCTION_MAP.put("power", ""); // POWER(x,y) 返回 x 的 y 次方
SQL_FUNCTION_MAP.put("radians", ""); // RADIANS(x) 将角度转换为弧度
SQL_FUNCTION_MAP.put("rand", ""); // RAND() 返回 0 到 1 的随机数
SQL_FUNCTION_MAP.put("round", ""); // ROUND(x) 返回离 x 最近的整数
SQL_FUNCTION_MAP.put("sign", ""); // SIGN(x) 返回 x 的符号,x 是负数、0、正数分别返回 -1、0 和 1
SQL_FUNCTION_MAP.put("sin", ""); // SIN(x) 求正弦值(参数是弧度)
SQL_FUNCTION_MAP.put("sqrt", ""); // SQRT(x) 返回x的平方根
SQL_FUNCTION_MAP.put("sum", ""); // SUM(expression) 返回指定字段的总和
SQL_FUNCTION_MAP.put("tan", ""); // TAN(x) 求正切值(参数是弧度)
SQL_FUNCTION_MAP.put("truncate", ""); // TRUNCATE(x,y) 返回数值 x 保留到小数点后 y 位的值(与 ROUND 最大的区别是不会进行四舍五入)
// MySQL 时间与日期函数
SQL_FUNCTION_MAP.put("adddate", ""); // ADDDATE(d,n) 计算起始日期 d 加上 n 天的日期
SQL_FUNCTION_MAP.put("addtime", ""); // ADDTIME(t,n) n 是一个时间表达式,时间 t 加上时间表达式 n
SQL_FUNCTION_MAP.put("curdate", ""); // CURDATE() 返回当前日期
SQL_FUNCTION_MAP.put("current_date", ""); // CURRENT_DATE() 返回当前日期
SQL_FUNCTION_MAP.put("current_time", ""); // CURRENT_TIME 返回当前时间
SQL_FUNCTION_MAP.put("current_timestamp", ""); // CURRENT_TIMESTAMP() 返回当前日期和时间
SQL_FUNCTION_MAP.put("curtime", ""); // CURTIME() 返回当前时间
SQL_FUNCTION_MAP.put("date", ""); // DATE() 从日期或日期时间表达式中提取日期值
SQL_FUNCTION_MAP.put("datediff", ""); // DATEDIFF(d1,d2) 计算日期 d1->d2 之间相隔的天数
SQL_FUNCTION_MAP.put("date_add", ""); // DATE_ADD(d,INTERVAL expr type) 计算起始日期 d 加上一个时间段后的日期
SQL_FUNCTION_MAP.put("date_format", ""); // DATE_FORMAT(d,f) 按表达式 f的要求显示日期 d
SQL_FUNCTION_MAP.put("date_sub", ""); // DATE_SUB(date,INTERVAL expr type) 函数从日期减去指定的时间间隔。
SQL_FUNCTION_MAP.put("day", ""); // DAY(d) 返回日期值 d 的日期部分
SQL_FUNCTION_MAP.put("dayname", ""); // DAYNAME(d) 返回日期 d 是星期几,如 Monday,Tuesday
SQL_FUNCTION_MAP.put("dayofmonth", ""); // DAYOFMONTH(d) 计算日期 d 是本月的第几天
SQL_FUNCTION_MAP.put("dayofweek", ""); // DAYOFWEEK(d) 日期 d 今天是星期几,1 星期日,2 星期一,以此类推
SQL_FUNCTION_MAP.put("dayofyear", ""); // DAYOFYEAR(d) 计算日期 d 是本年的第几天
SQL_FUNCTION_MAP.put("extract", ""); // EXTRACT(type FROM d) 从日期 d 中获取指定的值,type 指定返回的值。
SQL_FUNCTION_MAP.put("from_days", ""); // FROM_DAYS(n) 计算从 0000 年 1 月 1 日开始 n 天后的日期
SQL_FUNCTION_MAP.put("hour", ""); // 'HOUR(t) 返回 t 中的小时值
SQL_FUNCTION_MAP.put("last_day", ""); // LAST_DAY(d) 返回给给定日期的那一月份的最后一天
SQL_FUNCTION_MAP.put("localtime", ""); // LOCALTIME() 返回当前日期和时间
SQL_FUNCTION_MAP.put("localtimestamp", ""); // LOCALTIMESTAMP() 返回当前日期和时间
SQL_FUNCTION_MAP.put("makedate", ""); // MAKEDATE(year, day-of-year) 基于给定参数年份 year 和所在年中的天数序号 day-of-year 返回一个日期
SQL_FUNCTION_MAP.put("maketime", ""); // MAKETIME(hour, minute, second) 组合时间,参数分别为小时、分钟、秒
SQL_FUNCTION_MAP.put("microsecond", ""); // MICROSECOND(date) 返回日期参数所对应的微秒数
SQL_FUNCTION_MAP.put("minute", ""); // MINUTE(t) 返回 t 中的分钟值
SQL_FUNCTION_MAP.put("monthname", ""); // MONTHNAME(d) 返回日期当中的月份名称,如 November
SQL_FUNCTION_MAP.put("month", ""); // MONTH(d) 返回日期d中的月份值,1 到 12
SQL_FUNCTION_MAP.put("now", ""); // NOW() 返回当前日期和时间
SQL_FUNCTION_MAP.put("period_add", ""); // PERIOD_ADD(period, number) 为 年-月 组合日期添加一个时段
SQL_FUNCTION_MAP.put("period_diff", ""); // PERIOD_DIFF(period1, period2) 返回两个时段之间的月份差值
SQL_FUNCTION_MAP.put("quarter", ""); // QUARTER(d) 返回日期d是第几季节,返回 1 到 4
SQL_FUNCTION_MAP.put("second", ""); // SECOND(t) 返回 t 中的秒钟值
SQL_FUNCTION_MAP.put("sec_to_time", ""); // SEC_TO_TIME", ""); // ) 将以秒为单位的时间 s 转换为时分秒的格式
SQL_FUNCTION_MAP.put("str_to_date", ""); // STR_TO_DATE", ""); // tring, format_mask) 将字符串转变为日期
SQL_FUNCTION_MAP.put("subdate", ""); // SUBDATE(d,n) 日期 d 减去 n 天后的日期
SQL_FUNCTION_MAP.put("subtime", ""); // SUBTIME(t,n) 时间 t 减去 n 秒的时间
SQL_FUNCTION_MAP.put("sysdate", ""); // SYSDATE() 返回当前日期和时间
SQL_FUNCTION_MAP.put("time", ""); // TIME(expression) 提取传入表达式的时间部分
SQL_FUNCTION_MAP.put("time_format", ""); // TIME_FORMAT(t,f) 按表达式 f 的要求显示时间 t
SQL_FUNCTION_MAP.put("time_to_sec", ""); // TIME_TO_SEC(t) 将时间 t 转换为秒
SQL_FUNCTION_MAP.put("timediff", ""); // TIMEDIFF(time1, time2) 计算时间差值
SQL_FUNCTION_MAP.put("timestamp", ""); // TIMESTAMP(expression, interval) 单个参数时,函数返回日期或日期时间表达式;有2个参数时,将参数加和
SQL_FUNCTION_MAP.put("to_days", ""); // TO_DAYS(d) 计算日期 d 距离 0000 年 1 月 1 日的天数
SQL_FUNCTION_MAP.put("week", ""); // WEEK(d) 计算日期 d 是本年的第几个星期,范围是 0 到 53
SQL_FUNCTION_MAP.put("weekday", ""); // WEEKDAY(d) 日期 d 是星期几,0 表示星期一,1 表示星期二
SQL_FUNCTION_MAP.put("weekofyear", ""); // WEEKOFYEAR(d) 计算日期 d 是本年的第几个星期,范围是 0 到 53
SQL_FUNCTION_MAP.put("year", ""); // YEAR(d) 返回年份
SQL_FUNCTION_MAP.put("yearweek", ""); // YEARWEEK(date, mode) 返回年份及第几周(0到53),mode 中 0 表示周天,1表示周一,以此类推
SQL_FUNCTION_MAP.put("unix_timestamp", ""); // UNIX_TIMESTAMP(date) 获取UNIX时间戳函数,返回一个以 UNIX 时间戳为基础的无符号整数
SQL_FUNCTION_MAP.put("from_unixtime", ""); // FROM_UNIXTIME(date) 将 UNIX 时间戳转换为时间格式,与UNIX_TIMESTAMP互为反函数
// MYSQL JSON 函数
SQL_FUNCTION_MAP.put("json_append", ""); // JSON_APPEND(json_doc, path, val[, path, val] ...)) 插入JSON数组
SQL_FUNCTION_MAP.put("json_array", ""); // JSON_ARRAY(val1, val2...) 创建JSON数组
SQL_FUNCTION_MAP.put("json_array_append", ""); // JSON_ARRAY_APPEND(json_doc, val) 将数据附加到JSON文档
SQL_FUNCTION_MAP.put("json_array_insert", ""); // JSON_ARRAY_INSERT(json_doc, val) 插入JSON数组
SQL_FUNCTION_MAP.put("json_contains", ""); // JSON_CONTAINS(json_doc, val) JSON文档是否在路径中包含特定对象
SQL_FUNCTION_MAP.put("json_contains_path", ""); // JSON_CONTAINS_PATH(json_doc, path) JSON文档是否在路径中包含任何数据
SQL_FUNCTION_MAP.put("json_depth", ""); // JSON_DEPTH(json_doc) JSON文档的最大深度
SQL_FUNCTION_MAP.put("json_extract", ""); // JSON_EXTRACT(json_doc, path) 从JSON文档返回数据
SQL_FUNCTION_MAP.put("json_insert", ""); // JSON_INSERT(json_doc, val) 将数据插入JSON文档
SQL_FUNCTION_MAP.put("json_keys", ""); // JSON_KEYS(json_doc[, path]) JSON文档中的键数组
SQL_FUNCTION_MAP.put("json_length", ""); // JSON_LENGTH(json_doc) JSON文档中的元素数
SQL_FUNCTION_MAP.put("json_merge", ""); // JSON_MERGE(json_doc1, json_doc2) (已弃用) 合并JSON文档,保留重复的键。JSON_MERGE_PRESERVE()的已弃用同义词
SQL_FUNCTION_MAP.put("json_merge_patch", ""); // JSON_MERGE_PATCH(json_doc1, json_doc2) 合并JSON文档,替换重复键的值
SQL_FUNCTION_MAP.put("json_merge_preserve", ""); // JSON_MERGE_PRESERVE(json_doc1, json_doc2) 合并JSON文档,保留重复的键
SQL_FUNCTION_MAP.put("json_object", ""); // JSON_OBJECT(key1, val1, key2, val2...) 创建JSON对象
SQL_FUNCTION_MAP.put("json_overlaps", ""); // JSON_OVERLAPS(json_doc1, json_doc2) (引入8.0.17) 比较两个JSON文档,如果它们具有相同的键值对或数组元素,则返回TRUE(1),否则返回FALSE(0)
SQL_FUNCTION_MAP.put("json_pretty", ""); // JSON_PRETTY(json_doc) 以易于阅读的格式打印JSON文档
SQL_FUNCTION_MAP.put("json_quote", ""); // JSON_QUOTE(json_doc1) 引用JSON文档
SQL_FUNCTION_MAP.put("json_remove", ""); // JSON_REMOVE(json_doc1, path) 从JSON文档中删除数据
SQL_FUNCTION_MAP.put("json_replace", ""); // JSON_REPLACE(json_doc1, val1, val2) 替换JSON文档中的值
SQL_FUNCTION_MAP.put("json_schema_valid", ""); // JSON_SCHEMA_VALID(json_doc) (引入8.0.17) 根据JSON模式验证JSON文档;如果文档针对架构进行验证,则返回TRUE / 1;否则,则返回FALSE / 0
SQL_FUNCTION_MAP.put("json_schema_validation_report", ""); // JSON_SCHEMA_VALIDATION_REPORT(json_doc, mode) (引入8.0.17) 根据JSON模式验证JSON文档;以JSON格式返回有关验证结果的报告,包括成功或失败以及失败原因
SQL_FUNCTION_MAP.put("json_search", ""); // JSON_SEARCH(json_doc, val) JSON文档中值的路径
SQL_FUNCTION_MAP.put("json_set", ""); // JSON_SET(json_doc, val) 将数据插入JSON文档
// SQL_FUNCTION_MAP.put("json_storage_free", ""); // JSON_STORAGE_FREE() 部分更新后,JSON列值的二进制表示形式中的可用空间
// SQL_FUNCTION_MAP.put("json_storage_size", ""); // JSON_STORAGE_SIZE() 用于存储JSON文档的二进制表示的空间
SQL_FUNCTION_MAP.put("json_table", ""); // JSON_TABLE() 从JSON表达式返回数据作为关系表
SQL_FUNCTION_MAP.put("json_type", ""); // JSON_TYPE(json_doc) JSON值类型
SQL_FUNCTION_MAP.put("json_unquote", ""); // JSON_UNQUOTE(json_doc) 取消引用JSON值
SQL_FUNCTION_MAP.put("json_valid", ""); // JSON_VALID(json_doc) JSON值是否有效
SQL_FUNCTION_MAP.put("json_arrayagg", ""); // JSON_ARRAYAGG(key) 将每个表达式转换为 JSON 值,然后返回一个包含这些 JSON 值的 JSON 数组
SQL_FUNCTION_MAP.put("json_objectagg", ""); // JSON_OBJECTAGG(key, val)) 将每个表达式转换为 JSON 值,然后返回一个包含这些 JSON 值的 JSON 对象
// MySQL 高级函数
// SQL_FUNCTION_MAP.put("bin", ""); // BIN(x) 返回 x 的二进制编码
// SQL_FUNCTION_MAP.put("binary", ""); // BINARY(s) 将字符串 s 转换为二进制字符串
SQL_FUNCTION_MAP.put("case", ""); // CASE 表示函数开始,END 表示函数结束。如果 condition1 成立,则返回 result1, 如果 condition2 成立,则返回 result2,当全部不成立则返回 result,而当有一个成立之后,后面的就不执行了。
SQL_FUNCTION_MAP.put("cast", ""); // CAST(x AS type) 转换数据类型
SQL_FUNCTION_MAP.put("coalesce", ""); // COALESCE(expr1, expr2, ...., expr_n) 返回参数中的第一个非空表达式(从左向右)
// SQL_FUNCTION_MAP.put("conv", ""); // CONV(x,f1,f2) 返回 f1 进制数变成 f2 进制数
// SQL_FUNCTION_MAP.put("convert", ""); // CONVERT(s, cs) 函数将字符串 s 的字符集变成 cs
SQL_FUNCTION_MAP.put("if", ""); // IF(expr,v1,v2) 如果表达式 expr 成立,返回结果 v1;否则,返回结果 v2。
SQL_FUNCTION_MAP.put("ifnull", ""); // IFNULL(v1,v2) 如果 v1 的值不为 NULL,则返回 v1,否则返回 v2。
SQL_FUNCTION_MAP.put("isnull", ""); // ISNULL(expression) 判断表达式是否为 NULL
SQL_FUNCTION_MAP.put("nullif", ""); // NULLIF(expr1, expr2) 比较两个字符串,如果字符串 expr1 与 expr2 相等 返回 NULL,否则返回 expr1
SQL_FUNCTION_MAP.put("group_concat", ""); // GROUP_CONCAT([DISTINCT], s1, s2...)
}
@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 datasource; //数据源
private String table; //表名
private String alias; //表别名
private String group; //分组方式的字符串数组,','分隔
private String having; //聚合函数的字符串数组,','分隔
private String order; //排序方式的字符串数组,','分隔
private List<String> raw; //需要保留原始 SQL 的字段,','分隔
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 boolean isDb2() {
return isDb2(getSQLDatabase());
}
public static boolean isDb2(String db) {
return DATABASE_DB2.equals(db);
}
@Override
public String getQuote() {
return isMySQL() ? "`" : "\"";
}
@Override
public String getSchema() {
return schema;
}
/**
* @param sqlTable
* @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;
}
@Override
public String getDatasource() {
return datasource;
}
@Override
public SQLConfig setDatasource(String datasource) {
this.datasource = datasource;
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.getOuterConfig() : 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;
}
/**TODO @having 改为默认 | 或连接,且支持 @having: { "key1>": 1, "key{}": "length(key2)>0", "@combine": "key1,key2" }
* @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.getOuterConfig() : 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;
}
}
}
String[] keys = StringUtil.split(getHaving(), ";");
if (keys == null || keys.length <= 0) {
return StringUtil.isEmpty(joinHaving, true) ? "" : (hasPrefix ? " HAVING " : "") + joinHaving;
}
String quote = getQuote();
String tableAlias = getAliasWithQuote();
List<String> raw = getRaw();
boolean containRaw = raw != null && raw.contains(KEY_HAVING);
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];
if (containRaw) {
try {
String rawSQL = getRawSQL(KEY_HAVING, expression);
if (rawSQL != null) {
keys[i] = rawSQL;
continue;
}
} catch (Exception e) {
Log.e(TAG, "newSQLConfig rawColumnSQL == null >> try { "
+ " String rawSQL = ((AbstractSQLConfig) config).getRawSQL(KEY_COLUMN, fk); ... "
+ "} catch (Exception e) = " + e.getMessage());
}
}
if (expression.length() > 50) {
throw new UnsupportedOperationException("@having:value 的 value 中字符串 " + expression + " 不合法!"
+ "不允许传超过 50 个字符的函数或表达式!请用 @raw 简化传参!");
}
int start = expression.indexOf("(");
if (start < 0) {
if (isPrepared() && PATTERN_FUNCTION.matcher(expression).matches() == false) {
throw new UnsupportedOperationException("字符串 " + expression + " 不合法!"
+ "预编译模式下 @having:\"column?value;function(arg0,arg1,...)?value...\""
+ " 中 column?value 必须符合正则表达式 " + PATTERN_FUNCTION + " 且不包含连续减号 -- !不允许空格!");
}
continue;
}
int end = expression.lastIndexOf(")");
if (start >= end) {
throw new IllegalArgumentException("字符 " + expression + " 不合法!"
+ "@having:value 中 value 里的 SQL函数必须为 function(arg0,arg1,...) 这种格式!");
}
method = expression.substring(0, start);
if (method.isEmpty() == false) {
if (SQL_FUNCTION_MAP == null || SQL_FUNCTION_MAP.isEmpty()) {
if (StringUtil.isName(method) == false) {
throw new IllegalArgumentException("字符 " + method + " 不合法!"
+ "预编译模式下 @having:\"column?value;function(arg0,arg1,...)?value...\""
+ " 中 function 必须符合小写英文单词的 SQL 函数名格式!");
}
}
else if (SQL_FUNCTION_MAP.containsKey(method) == false) {
throw new IllegalArgumentException("字符 " + method + " 不合法!"
+ "预编译模式下 @column:\"column0,column1:alias;function0(arg0,arg1,...);function1(...):alias...\""
+ " 中 function 必须符合小写英文单词的 SQL 函数名格式!且必须是后端允许调用的 SQL 函数!");
}
}
suffix = expression.substring(end + 1, expression.length());
if (isPrepared() && (((String) suffix).contains("--") || ((String) suffix).contains("/*") || PATTERN_RANGE.matcher((String) suffix).matches() == false)) {
throw new UnsupportedOperationException("字符串 " + suffix + " 不合法!"
+ "预编译模式下 @having:\"column?value;function(arg0,arg1,...)?value...\""
+ " 中 ?value 必须符合正则表达式 " + PATTERN_RANGE + " 且不包含连续减号 -- 或注释符 /* !不允许多余的空格!");
}
String[] ckeys = StringUtil.split(expression.substring(start + 1, end));
if (ckeys != null) {
for (int j = 0; j < ckeys.length; j++) {
String origin = ckeys[j];
if (isPrepared()) {
if (origin.startsWith("_") || origin.contains("--") || PATTERN_FUNCTION.matcher(origin).matches() == false) {
throw new IllegalArgumentException("字符 " + ckeys[j] + " 不合法!"
+ "预编译模式下 @having:\"column?value;function(arg0,arg1,...)?value...\""
+ " 中所有 column, arg 都必须是1个不以 _ 开头的单词 或者 符合正则表达式 " + PATTERN_FUNCTION + " 且不包含连续减号 -- !不允许多余的空格!");
}
}
//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();
}
ckeys[j] = (isName && isKeyPrefix() ? tableAlias + "." : "") + origin;
}
}
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.getOuterConfig() : 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());
// SELECT * FROM sys.Moment ORDER BY userId ASC, rand(); 前面的 userId ASC 和后面的 rand() 都有效
// if ("rand()".equals(order)) {
// return (hasPrefix ? " ORDER BY " : "") + StringUtil.concat(order, joinOrder, ", ");
// }
if (getCount() > 0 && (isOracle() || isSQLServer() || isDb2())) { // Oracle, SQL Server, DB2 的 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 + "+";
// }
}
String[] keys = StringUtil.split(order);
if (keys == null || keys.length <= 0) {
return StringUtil.isEmpty(joinOrder, true) ? "" : (hasPrefix ? " ORDER BY " : "") + joinOrder;
}
for (int i = 0; i < keys.length; i++) {
String item = keys[i];
if ("rand()".equals(item)) {
continue;
}
int index = item.endsWith("+") ? item.length() - 1 : -1; //StringUtil.split返回数组中,子项不会有null
String sort;
if (index < 0) {
index = item.endsWith("-") ? item.length() - 1 : -1;
sort = index <= 0 ? "" : " DESC ";
}
else {
sort = " ASC ";
}
String origin = index < 0 ? item : item.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 中 " + item + " 不合法! value 里面用 , 分割的"
+ "每一项必须是 随机函数 rand() 或 column+ / column- 且其中 column 必须是 1 个单词!并且不要有多余的空格!");
}
}
keys[i] = getKey(origin) + sort;
}
return (hasPrefix ? " ORDER BY " : "") + StringUtil.concat(StringUtil.getString(keys), joinOrder, ", ");
}
@Override
public List<String> getRaw() {
return raw;
}
@Override
public SQLConfig setRaw(List<String> raw) {
this.raw = raw;
return this;
}
/**获取原始 SQL 片段
* @param key
* @param value
* @return
* @throws Exception
*/
@Override
public String getRawSQL(String key, Object value) throws Exception {
List<String> rawList = getRaw();
boolean containRaw = rawList != null && rawList.contains(key);
if (containRaw && value instanceof String == false) {
throw new UnsupportedOperationException("@raw:value 的 value 中 " + key + " 不合法!"
+ "对应的 " + key + ":value 中 value 类型只能为 String!");
}
String rawSQL = containRaw ? RAW_MAP.get(value) : null;
if (containRaw) {
if (rawSQL == null) {
throw new UnsupportedOperationException("@raw:value 的 value 中 " + key + " 不合法!"
+ "对应的 " + key + ":value 中 value 值 " + value + " 未在后端 RAW_MAP 中配置 !");
}
if ("".equals(rawSQL)) {
return (String) value;
}
}
return rawSQL;
}
@Override
public List<String> getJson() {
return json;
}
@Override
public AbstractSQLConfig setJson(List<String> json) {
this.json = json;