forked from microsoft/mssql-jdbc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDDC.java
1396 lines (1233 loc) · 57.5 KB
/
DDC.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
/*
* Microsoft JDBC Driver for SQL Server
*
* Copyright(c) Microsoft Corporation All rights reserved.
*
* This program is made available under the terms of the MIT License. See the LICENSE file in the project root for more information.
*/
package com.microsoft.sqlserver.jdbc;
import static java.nio.charset.StandardCharsets.US_ASCII;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.text.MessageFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;
/**
* Utility class for all Data Dependant Conversions (DDC).
*/
final class DDC {
/**
* Convert an Integer object to desired target user type.
*
* @param intvalue
* the value to convert.
* @param valueLength
* the value to convert.
* @param jdbcType
* the jdbc type required.
* @param streamType
* the type of stream required.
* @return the required object.
*/
static final Object convertIntegerToObject(int intValue,
int valueLength,
JDBCType jdbcType,
StreamType streamType) {
switch (jdbcType) {
case INTEGER:
return new Integer(intValue);
case SMALLINT: // 2.21 small and tinyint returned as short
case TINYINT:
return new Short((short) intValue);
case BIT:
case BOOLEAN:
return new Boolean(0 != intValue);
case BIGINT:
return new Long(intValue);
case DECIMAL:
case NUMERIC:
case MONEY:
case SMALLMONEY:
return new BigDecimal(Integer.toString(intValue));
case FLOAT:
case DOUBLE:
return new Double(intValue);
case REAL:
return new Float(intValue);
case BINARY:
return convertIntToBytes(intValue, valueLength);
default:
return Integer.toString(intValue);
}
}
/**
* Convert a Long object to desired target user type.
*
* @param longVal
* the value to convert.
* @param jdbcType
* the jdbc type required.
* @param baseSSType
* the base SQLServer type.
* @param streamType
* the stream type.
* @return the required object.
*/
static final Object convertLongToObject(long longVal,
JDBCType jdbcType,
SSType baseSSType,
StreamType streamType) {
switch (jdbcType) {
case BIGINT:
return new Long(longVal);
case INTEGER:
return new Integer((int) longVal);
case SMALLINT: // small and tinyint returned as short
case TINYINT:
return new Short((short) longVal);
case BIT:
case BOOLEAN:
return new Boolean(0 != longVal);
case DECIMAL:
case NUMERIC:
case MONEY:
case SMALLMONEY:
return new BigDecimal(Long.toString(longVal));
case FLOAT:
case DOUBLE:
return new Double(longVal);
case REAL:
return new Float(longVal);
case BINARY:
byte[] convertedBytes = convertLongToBytes(longVal);
int bytesToReturnLength = 0;
byte[] bytesToReturn;
switch (baseSSType) {
case BIT:
case TINYINT:
bytesToReturnLength = 1;
bytesToReturn = new byte[bytesToReturnLength];
System.arraycopy(convertedBytes, convertedBytes.length - bytesToReturnLength, bytesToReturn, 0, bytesToReturnLength);
return bytesToReturn;
case SMALLINT:
bytesToReturnLength = 2;
bytesToReturn = new byte[bytesToReturnLength];
System.arraycopy(convertedBytes, convertedBytes.length - bytesToReturnLength, bytesToReturn, 0, bytesToReturnLength);
return bytesToReturn;
case INTEGER:
bytesToReturnLength = 4;
bytesToReturn = new byte[bytesToReturnLength];
System.arraycopy(convertedBytes, convertedBytes.length - bytesToReturnLength, bytesToReturn, 0, bytesToReturnLength);
return bytesToReturn;
case BIGINT:
bytesToReturnLength = 8;
bytesToReturn = new byte[bytesToReturnLength];
System.arraycopy(convertedBytes, convertedBytes.length - bytesToReturnLength, bytesToReturn, 0, bytesToReturnLength);
return bytesToReturn;
default:
return convertedBytes;
}
case VARBINARY:
switch (baseSSType) {
case BIGINT:
return new Long(longVal);
case INTEGER:
return new Integer((int) longVal);
case SMALLINT: // small and tinyint returned as short
case TINYINT:
return new Short((short) longVal);
case BIT:
return new Boolean(0 != longVal);
case DECIMAL:
case NUMERIC:
case MONEY:
case SMALLMONEY:
return new BigDecimal(Long.toString(longVal));
case FLOAT:
return new Double(longVal);
case REAL:
return new Float(longVal);
case BINARY:
return convertLongToBytes(longVal);
default:
return Long.toString(longVal);
}
default:
return Long.toString(longVal);
}
}
/**
* Encodes an integer value to a byte array in big-endian order.
*
* @param intValue
* the integer value to encode.
* @param valueLength
* the number of bytes to encode.
* @return the byte array containing the big-endian encoded value.
*/
static final byte[] convertIntToBytes(int intValue,
int valueLength) {
byte bytes[] = new byte[valueLength];
for (int i = valueLength; i-- > 0;) {
bytes[i] = (byte) (intValue & 0xFF);
intValue >>= 8;
}
return bytes;
}
/**
* Convert a Float object to desired target user type.
*
* @param floatVal
* the value to convert.
* @param jdbcType
* the jdbc type required.
* @param streamType
* the stream type.
* @return the required object.
*/
static final Object convertFloatToObject(float floatVal,
JDBCType jdbcType,
StreamType streamType) {
switch (jdbcType) {
case REAL:
return new Float(floatVal);
case INTEGER:
return new Integer((int) floatVal);
case SMALLINT: // small and tinyint returned as short
case TINYINT:
return new Short((short) floatVal);
case BIT:
case BOOLEAN:
return new Boolean(0 != Float.compare(0.0f, floatVal));
case BIGINT:
return new Long((long) floatVal);
case DECIMAL:
case NUMERIC:
case MONEY:
case SMALLMONEY:
return new BigDecimal(Float.toString(floatVal));
case FLOAT:
case DOUBLE:
return new Double((new Float(floatVal)).doubleValue());
case BINARY:
return convertIntToBytes(Float.floatToRawIntBits(floatVal), 4);
default:
return Float.toString(floatVal);
}
}
/**
* Encodes a long value to a byte array in big-endian order.
*
* @param longValue
* the long value to encode.
* @return the byte array containing the big-endian encoded value.
*/
static final byte[] convertLongToBytes(long longValue) {
byte bytes[] = new byte[8];
for (int i = 8; i-- > 0;) {
bytes[i] = (byte) (longValue & 0xFF);
longValue >>= 8;
}
return bytes;
}
/**
* Convert a Double object to desired target user type.
*
* @param doubleVal
* the value to convert.
* @param jdbcType
* the jdbc type required.
* @param streamType
* the stream type.
* @return the required object.
*/
static final Object convertDoubleToObject(double doubleVal,
JDBCType jdbcType,
StreamType streamType) {
switch (jdbcType) {
case FLOAT:
case DOUBLE:
return new Double(doubleVal);
case REAL:
return new Float((new Double(doubleVal)).floatValue());
case INTEGER:
return new Integer((int) doubleVal);
case SMALLINT: // small and tinyint returned as short
case TINYINT:
return new Short((short) doubleVal);
case BIT:
case BOOLEAN:
return new Boolean(0 != Double.compare(0.0d, doubleVal));
case BIGINT:
return new Long((long) doubleVal);
case DECIMAL:
case NUMERIC:
case MONEY:
case SMALLMONEY:
return new BigDecimal(Double.toString(doubleVal));
case BINARY:
return convertLongToBytes(Double.doubleToRawLongBits(doubleVal));
default:
return Double.toString(doubleVal);
}
}
static final byte[] convertBigDecimalToBytes(BigDecimal bigDecimalVal,
int scale) {
byte[] valueBytes;
if (bigDecimalVal == null) {
valueBytes = new byte[2];
valueBytes[0] = (byte) scale;
valueBytes[1] = 0; // data length
}
else {
boolean isNegative = (bigDecimalVal.signum() < 0);
// NOTE: Handle negative scale as a special case for JDK 1.5 and later VMs.
if (bigDecimalVal.scale() < 0)
bigDecimalVal = bigDecimalVal.setScale(0);
BigInteger bi = bigDecimalVal.unscaledValue();
if (isNegative)
bi = bi.negate();
byte[] unscaledBytes = bi.toByteArray();
valueBytes = new byte[unscaledBytes.length + 3];
int j = 0;
valueBytes[j++] = (byte) bigDecimalVal.scale();
valueBytes[j++] = (byte) (unscaledBytes.length + 1); // data length + sign
valueBytes[j++] = (byte) (isNegative ? 0 : 1); // 1 = +ve, 0 = -ve
for (int i = unscaledBytes.length - 1; i >= 0; i--)
valueBytes[j++] = unscaledBytes[i];
}
return valueBytes;
}
/**
* Convert a BigDecimal object to desired target user type.
*
* @param bigDecimalVal
* the value to convert.
* @param jdbcType
* the jdbc type required.
* @param streamType
* the stream type.
* @return the required object.
*/
static final Object convertBigDecimalToObject(BigDecimal bigDecimalVal,
JDBCType jdbcType,
StreamType streamType) {
switch (jdbcType) {
case DECIMAL:
case NUMERIC:
case MONEY:
case SMALLMONEY:
return bigDecimalVal;
case FLOAT:
case DOUBLE:
return new Double(bigDecimalVal.doubleValue());
case REAL:
return new Float(bigDecimalVal.floatValue());
case INTEGER:
return new Integer(bigDecimalVal.intValue());
case SMALLINT: // small and tinyint returned as short
case TINYINT:
return new Short(bigDecimalVal.shortValue());
case BIT:
case BOOLEAN:
return new Boolean(0 != bigDecimalVal.compareTo(BigDecimal.valueOf(0)));
case BIGINT:
return new Long(bigDecimalVal.longValue());
case BINARY:
return convertBigDecimalToBytes(bigDecimalVal, bigDecimalVal.scale());
default:
return bigDecimalVal.toString();
}
}
/**
* Convert a Money object to desired target user type.
*
* @param bigDecimalVal
* the value to convert.
* @param jdbcType
* the jdbc type required.
* @param streamType
* the stream type.
* @param numberOfBytes
* the number of bytes to convert
* @return the required object.
*/
static final Object convertMoneyToObject(BigDecimal bigDecimalVal,
JDBCType jdbcType,
StreamType streamType,
int numberOfBytes) {
switch (jdbcType) {
case DECIMAL:
case NUMERIC:
case MONEY:
case SMALLMONEY:
return bigDecimalVal;
case FLOAT:
case DOUBLE:
return new Double(bigDecimalVal.doubleValue());
case REAL:
return new Float(bigDecimalVal.floatValue());
case INTEGER:
return new Integer(bigDecimalVal.intValue());
case SMALLINT: // small and tinyint returned as short
case TINYINT:
return new Short(bigDecimalVal.shortValue());
case BIT:
case BOOLEAN:
return new Boolean(0 != bigDecimalVal.compareTo(BigDecimal.valueOf(0)));
case BIGINT:
return new Long(bigDecimalVal.longValue());
case BINARY:
return convertToBytes(bigDecimalVal, bigDecimalVal.scale(), numberOfBytes);
default:
return bigDecimalVal.toString();
}
}
// converts big decimal to money and smallmoney
private static byte[] convertToBytes(BigDecimal value,
int scale,
int numBytes) {
boolean isNeg = value.signum() < 0;
value = value.setScale(scale);
BigInteger bigInt = value.unscaledValue();
byte[] unscaledBytes = bigInt.toByteArray();
byte[] ret = new byte[numBytes];
if (unscaledBytes.length < numBytes) {
for (int i = 0; i < numBytes - unscaledBytes.length; ++i) {
ret[i] = (byte) (isNeg ? -1 : 0);
}
}
int offset = numBytes - unscaledBytes.length;
for (int i = offset; i < numBytes; ++i) {
ret[i] = unscaledBytes[i - offset];
}
return ret;
}
/**
* Convert a byte array to desired target user type.
*
* @param bytesValue
* the value to convert.
* @param jdbcType
* the jdbc type required.
* @param baseTypeInfo
* the type information associated with bytesValue.
* @return the required object.
* @throws SQLServerException
* when an error occurs.
*/
static final Object convertBytesToObject(byte[] bytesValue,
JDBCType jdbcType,
TypeInfo baseTypeInfo) throws SQLServerException {
switch (jdbcType) {
case CHAR:
String str = Util.bytesToHexString(bytesValue, bytesValue.length);
if ((SSType.BINARY == baseTypeInfo.getSSType()) && (str.length() < (baseTypeInfo.getPrecision() * 2))) {
StringBuffer strbuf = new StringBuffer(str);
while (strbuf.length() < (baseTypeInfo.getPrecision() * 2)) {
strbuf.append('0');
}
return strbuf.toString();
}
return str;
case BINARY:
case VARBINARY:
case LONGVARBINARY:
if ((SSType.BINARY == baseTypeInfo.getSSType()) && (bytesValue.length < baseTypeInfo.getPrecision())) {
byte[] newBytes = new byte[baseTypeInfo.getPrecision()];
System.arraycopy(bytesValue, 0, newBytes, 0, bytesValue.length);
return newBytes;
}
return bytesValue;
default:
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_unsupportedConversionFromTo"));
throw new SQLServerException(form.format(new Object[] {baseTypeInfo.getSSType().name(), jdbcType}), null, 0, null);
}
}
/**
* Convert a String object to desired target user type.
*
* @param stringVal
* the value to convert.
* @param charset
* the character set.
* @param jdbcType
* the jdbc type required.
* @return the required object.
*/
static final Object convertStringToObject(String stringVal,
Charset charset,
JDBCType jdbcType,
StreamType streamType) throws UnsupportedEncodingException, IllegalArgumentException {
switch (jdbcType) {
// Convert String to Numeric types.
case DECIMAL:
case NUMERIC:
case MONEY:
case SMALLMONEY:
return new BigDecimal(stringVal.trim());
case FLOAT:
case DOUBLE:
return Double.valueOf(stringVal.trim());
case REAL:
return Float.valueOf(stringVal.trim());
case INTEGER:
return Integer.valueOf(stringVal.trim());
case SMALLINT: // small and tinyint returned as short
case TINYINT:
return Short.valueOf(stringVal.trim());
case BIT:
case BOOLEAN:
String trimmedString = stringVal.trim();
return (1 == trimmedString.length()) ? Boolean.valueOf('1' == trimmedString.charAt(0)) : Boolean.valueOf(trimmedString);
case BIGINT:
return Long.valueOf(stringVal.trim());
// Convert String to Temporal types.
case TIMESTAMP:
return java.sql.Timestamp.valueOf(stringVal.trim());
case DATE:
return java.sql.Date.valueOf(getDatePart(stringVal.trim()));
case TIME: {
// Accepted character formats for conversion to java.sql.Time are:
// hh:mm:ss[.nnnnnnnnn]
// YYYY-MM-DD hh:mm:ss[.nnnnnnnnn]
//
// To handle either of these formats:
// 1) Normalize and parse as a Timestamp
// 2) Round fractional seconds up to the nearest millisecond (max resolution of java.sql.Time)
// 3) Renormalize (as rounding may have changed the date) to a java.sql.Time
java.sql.Timestamp ts = java.sql.Timestamp.valueOf(TDS.BASE_DATE_1970 + " " + getTimePart(stringVal.trim()));
GregorianCalendar cal = new GregorianCalendar(Locale.US);
cal.clear();
cal.setTimeInMillis(ts.getTime());
if (ts.getNanos() % Nanos.PER_MILLISECOND >= Nanos.PER_MILLISECOND / 2)
cal.add(Calendar.MILLISECOND, 1);
cal.set(TDS.BASE_YEAR_1970, Calendar.JANUARY, 1);
return new java.sql.Time(cal.getTimeInMillis());
}
case BINARY:
return stringVal.getBytes(charset);
default:
// For everything else, just return either a string or appropriate stream.
switch (streamType) {
case CHARACTER:
return new StringReader(stringVal);
case ASCII:
return new ByteArrayInputStream(stringVal.getBytes(US_ASCII));
case BINARY:
return new ByteArrayInputStream(stringVal.getBytes());
default:
return stringVal;
}
}
}
static final Object convertStreamToObject(BaseInputStream stream,
TypeInfo typeInfo,
JDBCType jdbcType,
InputStreamGetterArgs getterArgs) throws SQLServerException {
// Need to handle the simple case of a null value here, as it is not done
// outside this function.
if (null == stream)
return null;
assert null != typeInfo;
assert null != getterArgs;
SSType ssType = typeInfo.getSSType();
try {
switch (jdbcType) {
case CHAR:
case VARCHAR:
case LONGVARCHAR:
case NCHAR:
case NVARCHAR:
case LONGNVARCHAR:
default:
// Binary streams to character types:
// - Direct conversion to ASCII stream
// - Convert as hexized value to other character types
if (SSType.BINARY == ssType || SSType.VARBINARY == ssType || SSType.VARBINARYMAX == ssType || SSType.TIMESTAMP == ssType
|| SSType.IMAGE == ssType || SSType.UDT == ssType) {
if (StreamType.ASCII == getterArgs.streamType) {
return stream;
}
else {
assert StreamType.CHARACTER == getterArgs.streamType || StreamType.NONE == getterArgs.streamType;
byte[] byteValue = stream.getBytes();
if (JDBCType.GUID == jdbcType) {
return Util.readGUID(byteValue);
}
else {
String hexString = Util.bytesToHexString(byteValue, byteValue.length);
if (StreamType.NONE == getterArgs.streamType)
return hexString;
return new StringReader(hexString);
}
}
}
// Handle streams converting to ASCII
if (StreamType.ASCII == getterArgs.streamType) {
// Fast path for SBCS data that converts directly/easily to ASCII
if (typeInfo.supportsFastAsciiConversion())
return new AsciiFilteredInputStream(stream);
// Slightly less fast path for MBCS data that converts directly/easily to ASCII
if (getterArgs.isAdaptive) {
return AsciiFilteredUnicodeInputStream.MakeAsciiFilteredUnicodeInputStream(stream,
new BufferedReader(new InputStreamReader(stream, typeInfo.getCharset())));
}
else {
return new ByteArrayInputStream((new String(stream.getBytes(), typeInfo.getCharset())).getBytes(US_ASCII));
}
}
else if (StreamType.CHARACTER == getterArgs.streamType || StreamType.NCHARACTER == getterArgs.streamType) {
if (getterArgs.isAdaptive)
return new BufferedReader(new InputStreamReader(stream, typeInfo.getCharset()));
else
return new StringReader(new String(stream.getBytes(), typeInfo.getCharset()));
}
// None of the special/fast textual conversion cases applied. Just go the normal route of converting via String.
return convertStringToObject(new String(stream.getBytes(), typeInfo.getCharset()), typeInfo.getCharset(), jdbcType,
getterArgs.streamType);
case CLOB:
return new SQLServerClob(stream, typeInfo);
case NCLOB:
return new SQLServerNClob(stream, typeInfo);
case SQLXML:
return new SQLServerSQLXML(stream, getterArgs, typeInfo);
case BINARY:
case VARBINARY:
case LONGVARBINARY:
case BLOB:
// Where allowed, streams convert directly to binary representation
if (StreamType.BINARY == getterArgs.streamType)
return stream;
if (JDBCType.BLOB == jdbcType)
return new SQLServerBlob(stream);
return stream.getBytes();
}
}
// Conversion can throw either of these exceptions:
//
// UnsupportedEncodingException (binary conversions)
// IllegalArgumentException (any conversion - note: numerics throw NumberFormatException subclass)
//
// Catch them and translate them to a SQLException so that we don't propagate an unexpected exception
// type all the way up to the app, which may not catch it either...
catch (IllegalArgumentException e) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_errorConvertingValue"));
throw new SQLServerException(form.format(new Object[] {typeInfo.getSSType(), jdbcType}), null, 0, e);
}
catch (UnsupportedEncodingException e) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_errorConvertingValue"));
throw new SQLServerException(form.format(new Object[] {typeInfo.getSSType(), jdbcType}), null, 0, e);
}
}
// Returns date portion of string.
// Expects one of "<date>" or "<date><space><time>".
private static String getDatePart(String s) {
int sp = s.indexOf(' ');
if (-1 == sp)
return s;
return s.substring(0, sp);
}
// Returns time portion of string.
// Expects one of "<time>" or "<date><space><time>".
private static String getTimePart(String s) {
int sp = s.indexOf(' ');
if (-1 == sp)
return s;
return s.substring(sp + 1);
}
// Formats nanoseconds as a String of the form ".nnnnnnn...." where the number
// of digits is equal to the scale. Returns the empty string for scale = 0;
private static String fractionalSecondsString(long subSecondNanos,
int scale) {
assert 0 <= subSecondNanos && subSecondNanos < Nanos.PER_SECOND;
assert 0 <= scale && scale <= TDS.MAX_FRACTIONAL_SECONDS_SCALE;
// Fast path for 0 scale (avoids creation of two BigDecimal objects and
// two Strings when the answer is going to be "" anyway...)
if (0 == scale)
return "";
return java.math.BigDecimal.valueOf(subSecondNanos % Nanos.PER_SECOND, 9).setScale(scale).toPlainString().substring(1);
}
/**
* Convert a SQL Server temporal value to the desired Java object type.
*
* Accepted SQL server data types:
*
* DATETIME SMALLDATETIME DATE TIME DATETIME2 DATETIMEOFFSET
*
* Converts to Java types (determined by JDBC type):
*
* java.sql.Date java.sql.Time java.sql.Timestamp java.lang.String
*
* @param jdbcType
* the JDBC type indicating the desired conversion
*
* @param ssType
* the SQL Server data type of the value being converted
*
* @param timeZoneCalendar
* (optional) a Calendar representing the time zone to associate with the resulting converted value. For DATETIMEOFFSET, this parameter
* represents the time zone associated with the value. Null means to use the default VM time zone.
*
* @param daysSinceBaseDate
* The date part of the value, expressed as a number of days since the base date for the specified SQL Server data type. For DATETIME
* and SMALLDATETIME, the base date is 1/1/1900. For other types, the base date is 1/1/0001. The number of days assumes Gregorian leap
* year behavior over the entire supported range of values. For TIME values, this parameter must be the number of days between 1/1/0001
* and 1/1/1900 when converting to java.sql.Timestamp.
*
* @param ticksSinceMidnight
* The time part of the value, expressed as a number of time units (ticks) since midnight. For DATETIME and SMALLDATETIME SQL Server
* data types, time units are in milliseconds. For other types, time units are in nanoseconds. For DATE values, this parameter must be
* 0.
*
* @param fractionalSecondsScale
* the desired fractional seconds scale to use when formatting the value as a String. Ignored for conversions to Java types other than
* String.
*
* @return a Java object of the desired type.
*/
static final Object convertTemporalToObject(JDBCType jdbcType,
SSType ssType,
Calendar timeZoneCalendar,
int daysSinceBaseDate,
long ticksSinceMidnight,
int fractionalSecondsScale) {
// Determine the local time zone to associate with the value. Use the default VM
// time zone if no time zone is otherwise specified.
TimeZone localTimeZone = (null != timeZoneCalendar) ? timeZoneCalendar.getTimeZone() : TimeZone.getDefault();
// Assumed time zone associated with the date and time parts of the value.
//
// For DATETIMEOFFSET, the date and time parts are assumed to be relative to UTC.
// For other data types, the date and time parts are assumed to be relative to the local time zone.
TimeZone componentTimeZone = (SSType.DATETIMEOFFSET == ssType) ? UTC.timeZone : localTimeZone;
int subSecondNanos = 0;
// The date and time parts assume a Gregorian calendar with Gregorian leap year behavior
// over the entire supported range of values. Create and initialize such a calendar to
// use to interpret the date and time parts in their associated time zone.
GregorianCalendar cal = new GregorianCalendar(componentTimeZone, Locale.US);
// Allow overflow in "smaller" fields (such as MILLISECOND and DAY_OF_YEAR) to update
// "larger" fields (such as HOUR, MINUTE, SECOND, and YEAR, MONTH, DATE).
cal.setLenient(true);
// Clear old state from the calendar. Newly created calendars are always initialized to the
// current date and time.
cal.clear();
// Set the calendar value according to the specified local time zone and constituent
// date (days since base date) and time (ticks since midnight) parts.
switch (ssType) {
case TIME: {
// Set the calendar to the specified value. Lenient calendar behavior will update
// individual fields according to standard Gregorian leap year rules, which are sufficient
// for all TIME values.
//
// When initializing the value, set the date component to 1/1/1900 to facilitate conversion
// to String and java.sql.Timestamp. Note that conversion to java.sql.Time, which is
// the expected majority conversion, resets the date to 1/1/1970. It is not measurably
// faster to conditionalize the date on the target data type to avoid resetting it.
//
// Ticks are in nanoseconds.
cal.set(TDS.BASE_YEAR_1900, Calendar.JANUARY, 1, 0, 0, 0);
cal.set(Calendar.MILLISECOND, (int) (ticksSinceMidnight / Nanos.PER_MILLISECOND));
subSecondNanos = (int) (ticksSinceMidnight % Nanos.PER_SECOND);
break;
}
case DATE:
case DATETIME2:
case DATETIMEOFFSET: {
// For dates after the standard Julian-Gregorian calendar change date,
// the calendar value can be accurately set using a straightforward
// (and measurably better performing) assignment.
//
// This optimized path is not functionally correct for dates earlier
// than the standard Gregorian change date.
if (daysSinceBaseDate >= GregorianChange.DAYS_SINCE_BASE_DATE_HINT) {
// Set the calendar to the specified value. Lenient calendar behavior will update
// individual fields according to pure Gregorian calendar rules.
//
// Ticks are in nanoseconds.
cal.set(1, Calendar.JANUARY, 1 + daysSinceBaseDate + GregorianChange.EXTRA_DAYS_TO_BE_ADDED, 0, 0, 0);
cal.set(Calendar.MILLISECOND, (int) (ticksSinceMidnight / Nanos.PER_MILLISECOND));
}
// For dates before the standard change date, it is necessary to rationalize
// the difference between SQL Server (pure Gregorian) calendar behavior and
// Java (standard Gregorian) calendar behavior. Rationalization ensures that
// the "wall calendar" representation of the value on both server and client
// are the same, taking into account the difference in the respective calendars'
// leap year rules.
//
// This code path is functionally correct, but less performant, than the
// optimized path above for dates after the standard Gregorian change date.
else {
cal.setGregorianChange(GregorianChange.PURE_CHANGE_DATE);
// Set the calendar to the specified value. Lenient calendar behavior will update
// individual fields according to pure Gregorian calendar rules.
//
// Ticks are in nanoseconds.
cal.set(1, Calendar.JANUARY, 1 + daysSinceBaseDate, 0, 0, 0);
cal.set(Calendar.MILLISECOND, (int) (ticksSinceMidnight / Nanos.PER_MILLISECOND));
// Recompute the calendar's internal UTC milliseconds value according to the historically
// standard Gregorian cutover date, which is needed for constructing java.sql.Time,
// java.sql.Date, and java.sql.Timestamp values from UTC milliseconds.
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int date = cal.get(Calendar.DATE);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
int millis = cal.get(Calendar.MILLISECOND);
cal.setGregorianChange(GregorianChange.STANDARD_CHANGE_DATE);
cal.set(year, month, date, hour, minute, second);
cal.set(Calendar.MILLISECOND, millis);
}
// For DATETIMEOFFSET values, recompute the calendar's UTC milliseconds value according
// to the specified local time zone (the time zone associated with the offset part
// of the DATETIMEOFFSET value).
//
// Optimization: Skip this step if there is no time zone difference
// (i.e. the time zone of the DATETIMEOFFSET value is UTC).
if (SSType.DATETIMEOFFSET == ssType && !componentTimeZone.hasSameRules(localTimeZone)) {
GregorianCalendar localCalendar = new GregorianCalendar(localTimeZone, Locale.US);
localCalendar.clear();
localCalendar.setTimeInMillis(cal.getTimeInMillis());
cal = localCalendar;
}
subSecondNanos = (int) (ticksSinceMidnight % Nanos.PER_SECOND);
break;
}
case DATETIME: // and SMALLDATETIME
{
// For Yukon (and earlier) data types DATETIME and SMALLDATETIME, there is no need to
// change the Gregorian cutover because the earliest representable value (1/1/1753)
// is after the historically standard cutover date (10/15/1582).
// Set the calendar to the specified value. Lenient calendar behavior will update
// individual fields according to standard Gregorian leap year rules, which are sufficient
// for all values in the supported DATETIME range.
//
// Ticks are in milliseconds.
cal.set(TDS.BASE_YEAR_1900, Calendar.JANUARY, 1 + daysSinceBaseDate, 0, 0, 0);
cal.set(Calendar.MILLISECOND, (int) ticksSinceMidnight);
subSecondNanos = (int) ((ticksSinceMidnight * Nanos.PER_MILLISECOND) % Nanos.PER_SECOND);
break;
}
default:
throw new AssertionError("Unexpected SSType: " + ssType);
}
int localMillisOffset = 0;
if (null == timeZoneCalendar) {
TimeZone tz = TimeZone.getDefault();
GregorianCalendar _cal = new GregorianCalendar(componentTimeZone, Locale.US);
_cal.setLenient(true);
_cal.clear();
localMillisOffset = tz.getOffset(_cal.getTimeInMillis());
}
else {
localMillisOffset = timeZoneCalendar.get(Calendar.ZONE_OFFSET);
}
// Convert the calendar value (in local time) to the desired Java object type.
switch (jdbcType.category) {
case BINARY: {
switch (ssType) {
case DATE: {
// Per JDBC spec, the time part of java.sql.Date values is initialized to midnight
// in the specified local time zone.
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return new java.sql.Date(cal.getTimeInMillis());
}
case DATETIME:
case DATETIME2: {
java.sql.Timestamp ts = new java.sql.Timestamp(cal.getTimeInMillis());
ts.setNanos(subSecondNanos);
return ts;
}
case DATETIMEOFFSET: {
// Per driver spec, conversion to DateTimeOffset is only supported from
// DATETIMEOFFSET SQL Server values.
assert SSType.DATETIMEOFFSET == ssType;
// For DATETIMEOFFSET SQL Server values, the time zone offset is in minutes.
// The offset from Java TimeZone objects is in milliseconds. Because we
// are only dealing with DATETIMEOFFSET SQL Server values here, we can assume
// that the offset is precise only to the minute and that rescaling from
// milliseconds precision results in no loss of precision.
assert 0 == localMillisOffset % (60 * 1000);
java.sql.Timestamp ts = new java.sql.Timestamp(cal.getTimeInMillis());
ts.setNanos(subSecondNanos);
return microsoft.sql.DateTimeOffset.valueOf(ts, localMillisOffset / (60 * 1000));
}
case TIME: {
// Per driver spec, values of sql server data types types (including TIME) which have greater
// than millisecond precision are rounded, not truncated, to the nearest millisecond when
// converting to java.sql.Time. Since the milliseconds value in the calendar is truncated,
// round it now.
if (subSecondNanos % Nanos.PER_MILLISECOND >= Nanos.PER_MILLISECOND / 2)
cal.add(Calendar.MILLISECOND, 1);
// Per JDBC spec, the date part of java.sql.Time values is initialized to 1/1/1970
// in the specified local time zone. This must be done after rounding (above) to
// prevent rounding values within nanoseconds of the next day from ending up normalized
// to 1/2/1970 instead...
cal.set(TDS.BASE_YEAR_1970, Calendar.JANUARY, 1);
return new java.sql.Time(cal.getTimeInMillis());
}
default:
throw new AssertionError("Unexpected SSType: " + ssType);
}
}
case DATE: {
// Per JDBC spec, the time part of java.sql.Date values is initialized to midnight
// in the specified local time zone.
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return new java.sql.Date(cal.getTimeInMillis());
}
case TIME: {
// Per driver spec, values of sql server data types types (including TIME) which have greater
// than millisecond precision are rounded, not truncated, to the nearest millisecond when
// converting to java.sql.Time. Since the milliseconds value in the calendar is truncated,
// round it now.
if (subSecondNanos % Nanos.PER_MILLISECOND >= Nanos.PER_MILLISECOND / 2)
cal.add(Calendar.MILLISECOND, 1);