/
FunctionMethods.java
1966 lines (1639 loc) · 70.5 KB
/
FunctionMethods.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
/*
* JBoss, Home of Professional Open Source.
* See the COPYRIGHT.txt file distributed with this work for information
* regarding copyright ownership. Some portions may be licensed
* to Red Hat, Inc. under one or more contributor license agreements.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*/
package org.teiid.query.function;
import java.io.FilterReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CodingErrorAction;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.TimeZone;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.crypto.spec.IvParameterSpec;
import org.teiid.api.exception.query.ExpressionEvaluationException;
import org.teiid.api.exception.query.FunctionExecutionException;
import org.teiid.api.exception.query.QueryMetadataException;
import org.teiid.client.util.ExceptionUtil;
import org.teiid.common.buffer.BlockedException;
import org.teiid.common.buffer.BufferManager;
import org.teiid.common.buffer.FileStore;
import org.teiid.common.buffer.FileStoreInputStreamFactory;
import org.teiid.core.CorePlugin;
import org.teiid.core.TeiidComponentException;
import org.teiid.core.crypto.CryptoException;
import org.teiid.core.crypto.SymmetricCryptor;
import org.teiid.core.types.*;
import org.teiid.core.types.InputStreamFactory.BlobInputStreamFactory;
import org.teiid.core.types.InputStreamFactory.ClobInputStreamFactory;
import org.teiid.core.types.InputStreamFactory.StorageMode;
import org.teiid.core.util.ObjectConverterUtil;
import org.teiid.core.util.PropertiesUtils;
import org.teiid.core.util.ReaderInputStream;
import org.teiid.core.util.StringUtil;
import org.teiid.core.util.TimestampWithTimezone;
import org.teiid.language.SQLConstants;
import org.teiid.language.SQLConstants.NonReserved;
import org.teiid.metadata.AbstractMetadataRecord;
import org.teiid.metadata.FunctionMethod.Determinism;
import org.teiid.query.QueryPlugin;
import org.teiid.query.function.metadata.FunctionCategoryConstants;
import org.teiid.query.metadata.MaterializationMetadataRepository;
import org.teiid.query.sql.symbol.GroupSymbol;
import org.teiid.query.sql.visitor.SQLStringVisitor;
import org.teiid.query.util.CommandContext;
import org.teiid.translator.SourceSystemFunctions;
/**
* Static method hooks for most of the function library.
*/
public final class FunctionMethods {
private static final class UpperLowerReader extends FilterReader {
int c1 = -1;
private boolean upper;
private UpperLowerReader(Reader in, boolean upper) {
super(in);
this.upper = upper;
}
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
if (len <= 0) {
if (len < 0) {
throw new IndexOutOfBoundsException();
} else if ((off < 0) || (off > cbuf.length)) {
throw new IndexOutOfBoundsException();
}
return 0;
}
int chars = 0;
while (chars <= len) {
int c = read();
if (c == -1) {
if (chars == 0) {
return -1;
}
break;
}
cbuf[off++] = (char)c;
chars++;
}
return chars;
}
@Override
public int read() throws IOException {
if (c1 != -1) {
int c = c1;
c1 = -1;
return c;
}
int c = super.read();
if ((char)c >= Character.MIN_HIGH_SURROGATE
&& (char)c <= Character.MAX_HIGH_SURROGATE) {
c1 = super.read();
if (Character.isLowSurrogate((char)c1)) {
int codePoint = Character.toCodePoint((char)c, (char)c1);
codePoint = modifyChar(codePoint);
int count = Character.charCount(codePoint);
if (count == 1) {
c1 = -1;
return codePoint;
}
char[] chars = Character.toChars(codePoint);
c1 = chars[1];
return chars[0];
}
c1 = modifyChar(c1);
}
return modifyChar(c);
}
private int modifyChar(int c) {
if (upper) {
return Character.toUpperCase(c);
}
return Character.toLowerCase(c);
}
}
private static final boolean CALENDAR_TIMESTAMPDIFF = PropertiesUtils.getBooleanProperty(System.getProperties(), "org.teiid.calendarTimestampDiff", true); //$NON-NLS-1$
public static final String AT = "@"; //$NON-NLS-1$
// ================== Function = plus =====================
public static int plus(int x, int y) throws FunctionExecutionException {
long result = (long)x + y;
if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
throw new FunctionExecutionException(QueryPlugin.Event.TEIID31169, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31169, result));
}
return (int)result;
}
public static long plus(long x, long y) throws FunctionExecutionException {
if (y > 0) {
if (x > Long.MAX_VALUE - y) {
throw new FunctionExecutionException(QueryPlugin.Event.TEIID31169, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31169, BigInteger.valueOf(x).add(BigInteger.valueOf(y))));
}
} else if (x < Long.MIN_VALUE - y) {
throw new FunctionExecutionException(QueryPlugin.Event.TEIID31169, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31169, BigInteger.valueOf(x).add(BigInteger.valueOf(y))));
}
return x + y;
}
public static float plus(float x, float y) {
return x + y;
}
public static double plus(double x, double y) {
return x + y;
}
public static Object plus(BigInteger x, BigInteger y) {
return x.add(y);
}
public static Object plus(BigDecimal x, BigDecimal y) {
return x.add(y);
}
// ================== Function = minus =====================
public static int minus(int x, int y) throws FunctionExecutionException {
long result = (long)x - y;
if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
throw new FunctionExecutionException(QueryPlugin.Event.TEIID31169, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31169, result));
}
return (int)result;
}
public static long minus(long x, long y) throws FunctionExecutionException {
if (y > 0) {
if (x < Long.MIN_VALUE + y) {
throw new FunctionExecutionException(QueryPlugin.Event.TEIID31169, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31169, BigInteger.valueOf(x).subtract(BigInteger.valueOf(y))));
}
} else if (x > Long.MAX_VALUE + y) {
throw new FunctionExecutionException(QueryPlugin.Event.TEIID31169, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31169, BigInteger.valueOf(x).subtract(BigInteger.valueOf(y))));
}
return x - y;
}
public static float minus(float x, float y) {
return x - y;
}
public static double minus(double x, double y) {
return x - y;
}
public static Object minus(BigInteger x, BigInteger y) {
return x.subtract(y);
}
public static Object minus(BigDecimal x, BigDecimal y) {
return x.subtract(y);
}
// ================== Function = multiply =====================
public static int multiply(int x, int y) throws FunctionExecutionException {
long result = (long)x * y;
if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
throw new FunctionExecutionException(QueryPlugin.Event.TEIID31169, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31169, result));
}
return (int)result;
}
public static long multiply(long x, long y) throws FunctionExecutionException {
if ((y > 0 && (x > Long.MAX_VALUE/y || x < Long.MIN_VALUE/y))
|| ((y < -1) && (x > Long.MIN_VALUE/y || x < Long.MAX_VALUE/y))
|| (y == -1 && x == Long.MIN_VALUE)) {
throw new FunctionExecutionException(QueryPlugin.Event.TEIID31169, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31169, BigInteger.valueOf(x).multiply(BigInteger.valueOf(y))));
}
return x * y;
}
public static float multiply(float x, float y) {
return x * y;
}
public static double multiply(double x, double y) {
return x * y;
}
public static Object multiply(BigInteger x, BigInteger y) {
return x.multiply(y);
}
public static Object multiply(BigDecimal x, BigDecimal y) {
return x.multiply(y);
}
// ================== Function = divide =====================
public static int divide(int x, int y) throws FunctionExecutionException {
if (x == Integer.MIN_VALUE && y == -1) {
throw new FunctionExecutionException(QueryPlugin.Event.TEIID31169, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31169, (long)Integer.MAX_VALUE + 1));
}
return x / y;
}
public static long divide(long x, long y) throws FunctionExecutionException {
if (x == Long.MIN_VALUE && y == -1) {
throw new FunctionExecutionException(QueryPlugin.Event.TEIID31169, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31169, BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.valueOf(1))));
}
return x / y;
}
public static float divide(float x, float y) {
return x / y;
}
public static double divide(double x, double y) {
return x / y;
}
public static Object divide(BigInteger x, BigInteger y) {
return x.divide(y);
}
private static final BigDecimal ZERO = new BigDecimal(0);
public static Object divide(BigDecimal x, BigDecimal y) {
BigDecimal bd = x.divide(y, Math.max(16, x.scale() + y.precision() + 1), RoundingMode.HALF_UP).stripTrailingZeros();
bd = bd.setScale(Math.max(x.scale(), bd.scale()));
if (bd.compareTo(ZERO) == 0) {
return ZERO;
}
return bd;
}
// ================== Function = abs =====================
public static int abs(int x) throws FunctionExecutionException {
if (x == Integer.MIN_VALUE) {
throw new FunctionExecutionException(QueryPlugin.Event.TEIID31169, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31169, (long)Integer.MAX_VALUE + 1));
}
return Math.abs(x);
}
public static long abs(long x) throws FunctionExecutionException {
if (x == Long.MIN_VALUE) {
throw new FunctionExecutionException(QueryPlugin.Event.TEIID31169, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31169, BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.valueOf(1))));
}
return Math.abs(x);
}
public static float abs(float x) {
return Math.abs(x);
}
public static double abs(double x) {
return Math.abs(x);
}
public static Object abs(BigInteger x) {
return x.abs();
}
public static Object abs(BigDecimal x) {
return x.abs();
}
// ================== Function = ceiling =====================
public static Object ceiling(Number x) {
return new Double(Math.ceil(x.doubleValue()));
}
// ================== Function = exp =====================
public static Object exp(Number x) {
return new Double(Math.exp(x.doubleValue()));
}
// ================== Function = floor =====================
public static Object floor(Number x) {
return new Double(Math.floor(x.doubleValue()));
}
// ================== Function = log =====================
public static Object log(Number x) {
return new Double(Math.log(x.doubleValue()));
}
// ================== Function = log10 =====================
private static final double log10baseE = Math.log(10);
public static Object log10(Number x) {
return new Double( Math.log(x.doubleValue()) / log10baseE);
}
// ================== Function = rand=====================
public static Object rand(CommandContext context, Integer seed) {
if(seed == null) {
return new Double(context.getNextRand());
}
return new Double(context.getNextRand(seed.longValue()));
}
public static Object rand(CommandContext context) {
return new Double(context.getNextRand());
}
// ================== Function = mod =====================
public static int mod(int x, int y) {
return x % y;
}
public static long mod(long x, long y) {
return x % y;
}
public static float mod(float x, float y) {
return x % y;
}
public static double mod(double x, double y) {
return x % y;
}
public static Object mod(BigInteger x, BigInteger y) {
return x.remainder(y);
}
public static Object mod(BigDecimal x, BigDecimal y) {
return x.remainder(y);
}
// ================== Function = power =====================
public static double power(double x, double y) {
return Math.pow(x, y);
}
public static BigInteger power(BigInteger x, int y) {
return x.pow(y);
}
public static BigDecimal power(BigDecimal x, int y) {
return x.pow(y);
}
public static int round(int number, int places) {
if(places < 0){
return round(new BigDecimal(number), places).intValue();
}
return number;
}
public static float round(float number, int places) {
return round(new BigDecimal(number), places).floatValue();
}
public static double round(double number, int places) {
return round(new BigDecimal(number), places).doubleValue();
}
public static BigDecimal round(BigDecimal bigDecimalNumber, int places) {
int scale = bigDecimalNumber.scale();
if (scale <= places) {
return bigDecimalNumber;
}
bigDecimalNumber = bigDecimalNumber.setScale(places,BigDecimal.ROUND_HALF_UP);
return bigDecimalNumber.setScale(scale,BigDecimal.ROUND_HALF_UP);
}
// ================== Function = sign =====================
public static Object sign(int x) {
return Integer.signum(x);
}
public static Object sign(long x) {
return Long.signum(x);
}
public static Object sign(float x) {
return Math.signum(x);
}
public static Object sign(double x) {
return Math.signum(x);
}
public static Object sign(BigInteger x) {
return new Integer(x.signum());
}
public static Object sign(BigDecimal x) {
return new Integer(x.signum());
}
// ================== Function = sqrt =====================
public static Object sqrt(Number x) {
return new Double( Math.sqrt(x.doubleValue()));
}
// ================== Function = currentDate =====================
public static Object currentDate() {
return TimestampWithTimezone.createDate(new Date());
}
// ================== Function = currentTime =====================
public static Object currentTime() {
return TimestampWithTimezone.createTime(new Date());
}
// ================== Function = currentTimestamp =====================
public static Object currentTimestamp() {
return new Timestamp(System.currentTimeMillis());
}
// ================== Helper for a bunch of date functions =====================
private static int getField(java.util.Date date, int field) {
Calendar cal = TimestampWithTimezone.getCalendar();
cal.setTime(date);
return cal.get(field);
}
// ================== Function = dayname =====================
static String[] dayNames;
static String[] monthNames;
public static Object dayName(Date x) {
return getDayNames()[getField(x, Calendar.DAY_OF_WEEK) - 1];
}
private static Locale getSymbolLocale() {
return PropertiesUtils.getBooleanProperty(System.getProperties(), "org.teiid.enDateNames", false)?Locale.ENGLISH:Locale.getDefault(); //$NON-NLS-1$
}
static String[] getMonthNames() {
if (monthNames == null) {
DateFormatSymbols dateFormatSymbols = DateFormatSymbols.getInstance(getSymbolLocale());
String[] months = dateFormatSymbols.getMonths();
monthNames = Arrays.copyOf(months, 12);
}
return monthNames;
}
static String[] getDayNames() {
if (dayNames == null) {
DateFormatSymbols dateFormatSymbols = DateFormatSymbols.getInstance(getSymbolLocale());
dayNames = Arrays.copyOfRange(dateFormatSymbols.getWeekdays(), 1, 8);
}
return dayNames;
}
// ================== Function = dayofmonth =====================
public static Object dayOfMonth(Date x) {
return Integer.valueOf(getField(x, Calendar.DATE));
}
// ================== Function = dayofweek =====================
public static int dayOfWeek(Date x) {
int result = getField(x, Calendar.DAY_OF_WEEK);
return result;
}
// ================== Function = dayofyear =====================
public static Object dayOfYear(Date x) {
return Integer.valueOf(getField(x, Calendar.DAY_OF_YEAR));
}
// ================== Function = hour =====================
public static Object hour(Date x) {
return Integer.valueOf(getField(x, Calendar.HOUR_OF_DAY));
}
// ================== Function = minute =====================
public static Object minute(Date x) {
return Integer.valueOf(getField(x, Calendar.MINUTE));
}
// ================== Function = month =====================
public static Object month(Date x) {
return Integer.valueOf(getField(x, Calendar.MONTH)+1);
}
// ================== Function = monthname =====================
public static Object monthName(Date x) {
return getMonthNames()[getField(x, Calendar.MONTH)];
}
// ================== Function = second =====================
public static Object second(Date x) {
return Integer.valueOf(getField(x, Calendar.SECOND));
}
// ================== Function = week =====================
public static int week(Date x) {
return getField(x, Calendar.WEEK_OF_YEAR);
}
// ================== Function = year =====================
public static Object year(Date x) {
return Integer.valueOf(getField(x, Calendar.YEAR));
}
// ================== Function = quarter =====================
public static Object quarter(Date date) {
int month = getField(date, Calendar.MONTH);
if (month > 11) {
throw new AssertionError("Invalid month for " + date); //$NON-NLS-1$
}
return Integer.valueOf(month/3 + 1);
}
public static Object from_unixtime(Integer count) {
return timestampAdd(NonReserved.SQL_TSI_SECOND, count, new Timestamp(0));
}
// ================== Function = timestampadd =====================
public static Object timestampAdd(String intervalType, Integer count, Timestamp timestamp) {
Calendar cal = TimestampWithTimezone.getCalendar();
int nanos = timestamp.getNanos();
cal.setTime(timestamp);
// case of interval = 1, fractional seconds (nanos), don't go to branches of addField()
if (intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_FRAC_SECOND)) {
int countValue = count.intValue();
nanos += countValue;
// Handle the case of nanos > 999,999,999 and increase the second.
// Since the count number is an interger, so the maximum is definite,
// and nanos/999,999,999 can at most be added to second
if ( nanos > 999999999) {
int addSecond = nanos / 999999999;
int leftNanos = nanos % 999999999;
cal.add(Calendar.SECOND, addSecond);
Timestamp ts = new Timestamp(cal.getTime().getTime());
ts.setNanos(leftNanos);
return ts;
}
// nanos <= 999,999,999
Timestamp ts = new Timestamp(cal.getTime().getTime());
ts.setNanos(nanos);
return ts;
}
// for interval from 2 to 9
addField(intervalType, count, cal);
Timestamp ts = new Timestamp(cal.getTime().getTime());
//rectify returned timestamp with original nanos
ts.setNanos(nanos);
return ts;
}
/** Helper method for timestampAdd method
* @param interval Integer
* @param count Integer
* @param cal Calendar instance
*/
private static void addField(String interval, Integer count, Calendar cal) {
int countValue = count.intValue();
if(interval.equalsIgnoreCase(NonReserved.SQL_TSI_FRAC_SECOND)) {
//nano seconds - should never get into this branch
} else if(interval.equalsIgnoreCase(NonReserved.SQL_TSI_SECOND)) {
cal.add(Calendar.SECOND, countValue);
} else if(interval.equalsIgnoreCase(NonReserved.SQL_TSI_MINUTE)) {
cal.add(Calendar.MINUTE, countValue);
} else if(interval.equalsIgnoreCase(NonReserved.SQL_TSI_HOUR)) {
cal.add(Calendar.HOUR_OF_DAY, countValue);
} else if(interval.equalsIgnoreCase(NonReserved.SQL_TSI_DAY)) {
cal.add(Calendar.DAY_OF_YEAR, countValue);
} else if(interval.equalsIgnoreCase(NonReserved.SQL_TSI_WEEK)) {
cal.add(Calendar.WEEK_OF_YEAR, countValue);
} else if(interval.equalsIgnoreCase(NonReserved.SQL_TSI_MONTH)) {
cal.add(Calendar.MONTH, countValue);
} else if(interval.equalsIgnoreCase(NonReserved.SQL_TSI_QUARTER)) {
cal.add(Calendar.MONTH, countValue*3);
} else if(interval.equalsIgnoreCase(NonReserved.SQL_TSI_YEAR)) {
cal.add(Calendar.YEAR, countValue);
}
}
// ================== Function = timestampdiff =====================
public static Long timestampDiff(String intervalType, Timestamp ts1Obj, Timestamp ts2Obj) throws FunctionExecutionException {
return timestampDiff(intervalType, ts1Obj, ts2Obj, CALENDAR_TIMESTAMPDIFF);
}
public static Long timestampDiff(String intervalType, Timestamp ts1Obj, Timestamp ts2Obj, boolean calendarBased) throws FunctionExecutionException {
long ts1 = ts1Obj.getTime() / 1000;
long ts2 = ts2Obj.getTime() / 1000;
long tsDiff = ts2 - ts1;
long count = 0;
if(intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_FRAC_SECOND)) {
if (Math.abs(tsDiff) > Integer.MAX_VALUE) {
throw new FunctionExecutionException(QueryPlugin.Event.TEIID31144, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31144));
}
count = tsDiff * 1000000000 + ts2Obj.getNanos() - ts1Obj.getNanos();
} else {
if(intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_SECOND)) {
count = tsDiff;
} else if (calendarBased) {
//alternative logic is needed to compute calendar differences
//which looks at elapsed date parts, not total time between
if(intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_MINUTE)) {
count = ts2 / 60 - ts1 / 60;
} else if(intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_HOUR)) {
TimeZone tz = TimestampWithTimezone.getCalendar().getTimeZone();
if (tz.getDSTSavings() > 0 || tz.getRawOffset() % 3600000 != 0) {
ts1 += tz.getOffset(ts1Obj.getTime())/1000;
ts2 += tz.getOffset(ts2Obj.getTime())/1000;
}
count = ts2 / (60*60) - ts1 / (60*60);
} else if(intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_DAY) || intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_WEEK)) {
TimeZone tz = TimestampWithTimezone.getCalendar().getTimeZone();
if (tz.getDSTSavings() > 0 || tz.getRawOffset() % 3600000 != 0) {
ts1 += tz.getOffset(ts1Obj.getTime())/1000;
ts2 += tz.getOffset(ts2Obj.getTime())/1000;
}
//since we are now effectively using GMT we can simply divide since the unix epoch starts at midnight.
count = ts2 / (60*60*24) - ts1 / (60*60*24);
if (intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_WEEK)) {
//TODO: this behavior matches SQL Server - but not Derby which expects only whole week
long days = count;
//whole weeks between the two dates
count = count/7;
//check for calendar difference assuming sunday as the first week day
if (days%7!=0) {
int day1 = dayOfWeek(ts1Obj);
int day2 = dayOfWeek(ts2Obj);
int diff = Integer.signum(day2 - day1);
if (diff > 0) {
if (tsDiff < 0) {
count--;
}
} else if (diff < 0) {
if (tsDiff > 0) {
count++;
}
}
}
}
} else if(intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_MONTH)) {
Calendar cal = TimestampWithTimezone.getCalendar();
cal.setTimeInMillis(ts1Obj.getTime());
int months1 = cal.get(Calendar.YEAR) * 12 + cal.get(Calendar.MONTH);
cal.setTimeInMillis(ts2Obj.getTime());
int months2 = cal.get(Calendar.YEAR) * 12 + cal.get(Calendar.MONTH);
count = months2 - months1;
} else if(intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_QUARTER)) {
Calendar cal = TimestampWithTimezone.getCalendar();
cal.setTimeInMillis(ts1Obj.getTime());
int quarters1 = cal.get(Calendar.YEAR) * 4 + cal.get(Calendar.MONTH)/3;
cal.setTimeInMillis(ts2Obj.getTime());
int quarters2 = cal.get(Calendar.YEAR) * 4 + cal.get(Calendar.MONTH)/3;
count = quarters2 - quarters1;
} else if(intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_YEAR)) {
Calendar cal = TimestampWithTimezone.getCalendar();
cal.setTimeInMillis(ts1Obj.getTime());
int years1 = cal.get(Calendar.YEAR);
cal.setTimeInMillis(ts2Obj.getTime());
int years2 = cal.get(Calendar.YEAR);
count = years2 - years1;
}
} else if(intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_MINUTE)) {
count = tsDiff / 60;
} else if(intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_HOUR)) {
count = tsDiff / (60*60);
} else if(intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_DAY)) {
count = tsDiff / (60*60*24);
} else if(intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_WEEK)) {
count = tsDiff / (60*60*24*7);
} else if(intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_MONTH)) {
count = tsDiff / (60*60*24*30);
} else if(intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_QUARTER)) {
count = tsDiff / (60*60*24*91);
} else if(intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_YEAR)) {
count = tsDiff / (60*60*24*365);
}
}
//TODO: long results are not consistent with other sources
/*if (calendarBased && ((count > 0 && count > Integer.MAX_VALUE) || (count < 0 && count < Integer.MIN_VALUE))) {
throw new FunctionExecutionException(QueryPlugin.Event.TEIID31136, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31136));
}*/
return Long.valueOf(count);
}
// ================== Function = timestampcreate =====================
/**
* This method truncates (ignores) figures
* @param interval
* @param timestamp1
* @param timestamp2
* @return
* @throws FunctionExecutionException
*/
public static Object timestampCreate(java.sql.Date date, Time time) {
Calendar tsCal = TimestampWithTimezone.getCalendar();
tsCal.setTime(time);
int hour = tsCal.get(Calendar.HOUR_OF_DAY);
int minute = tsCal.get(Calendar.MINUTE);
int second = tsCal.get(Calendar.SECOND);
tsCal.setTime(date);
tsCal.set(Calendar.HOUR_OF_DAY, hour);
tsCal.set(Calendar.MINUTE, minute);
tsCal.set(Calendar.SECOND, second);
return new Timestamp(tsCal.getTime().getTime());
}
// ================== Function = length =====================
public static Object length(String str) {
return str.length();
}
// ================== Function = concat =====================
public static String concat(String str1, String str2) {
return str1 + str2;
}
public static String concat2(String str1, String str2) {
if (str1 == null) {
if (str2 == null) {
return null;
}
return str2;
}
if (str2 == null) {
return str1;
}
return str1 + str2;
}
public static ClobType concat(CommandContext context, ClobType str1, ClobType str2) throws IOException, SQLException {
BufferManager bm = context.getBufferManager();
FileStore fs = bm.createFileStore("clob"); //$NON-NLS-1$
FileStoreInputStreamFactory fsisf = new FileStoreInputStreamFactory(fs, Streamable.ENCODING);
boolean remove = true;
try (Reader characterStream = str1.getCharacterStream(); Reader characterStream2 = str2.getCharacterStream();){
Writer writer = fsisf.getWriter();
int chars = ObjectConverterUtil.write(writer, characterStream, -1, false);
chars += ObjectConverterUtil.write(writer, characterStream2, -1, false);
writer.close();
if (fsisf.getStorageMode() == StorageMode.MEMORY) {
//detach if just in memory
byte[] bytes = fsisf.getMemoryBytes();
return new ClobType(new ClobImpl(new String(bytes, Streamable.ENCODING)));
}
remove = false;
context.addCreatedLob(fsisf);
return new ClobType(new ClobImpl(fsisf, chars));
} finally {
if (remove) {
fs.remove();
}
}
}
public static ClobType concat2(CommandContext context, ClobType str1, ClobType str2) throws IOException, SQLException {
if (str1 == null) {
if (str2 == null) {
return null;
}
return str2;
}
if (str2 == null) {
return str1;
}
return concat(context, str1, str2);
}
// ================== Function = substring =====================
public static Object substring(String string, Integer startVal, Integer lengthVal) {
if (startVal < 0) {
startVal = string.length() + startVal;
} else if (startVal > 0){
startVal--; // Adjust to 1-based
}
if(startVal < 0 || startVal >= string.length()) {
return null;
}
if(lengthVal < 0) {
return null;
}
int endVal = Math.min(startVal+lengthVal, string.length());
return new String(string.substring(startVal, endVal));
}
public static Object substring(String string, Integer start) {
int startVal = start.intValue();
return substring(string, startVal, string.length());
}
// ================== Function = left =====================
public static Object left(String string, Integer count)
throws FunctionExecutionException {
int countValue = count.intValue();
if(countValue < 0) {
throw new FunctionExecutionException(QueryPlugin.Event.TEIID30396, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30396, countValue));
}
if(string.length() < countValue) {
return string;
}
return new String(string.substring(0, countValue));
}
// ================== Function = right =====================
public static Object right(String string, Integer count)
throws FunctionExecutionException {
int countValue = count.intValue();
if(countValue < 0) {
throw new FunctionExecutionException(QueryPlugin.Event.TEIID30396, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30396, countValue));
} else if(string.length() < countValue) {
return string;
} else {
return new String(string.substring(string.length() - countValue));
}
}
// ================== Function = lowercase =====================
public static Object lowerCase(String str) {
return str.toLowerCase();
}
public static ClobType lowerCase(ClobType str) {
return new ClobType(new ClobImpl(new ClobInputStreamFactory(str) {
@Override
public Reader getReader(Reader reader) {
return new UpperLowerReader(reader, false);
}
}, str.getLength()));
}
// ================== Function = uppercase =====================
public static Object upperCase(String str) {
return str.toUpperCase();
}
public static ClobType upperCase(ClobType str) {
return new ClobType(new ClobImpl(new ClobInputStreamFactory(str) {
@Override
public Reader getReader(Reader reader) {
return new UpperLowerReader(reader, true);
}
}, str.getLength()));
}
// ================== Function = locate =====================
public static Object locate(String sub, String str) {
return locate(sub, str, 1);
}
// ================== Function = endsWith =====================
public static Object endsWith(String sub, String str) {
return str.endsWith(sub);
}
/**
* TODO: The treatment of negative start indexes is inconsistent here.
* We're treating the null value like Derby, but not throwing an
* exception if the value is less than 1 (less than 0 in DB2).