-
Notifications
You must be signed in to change notification settings - Fork 435
/
Copy pathdtv.java
4156 lines (3545 loc) · 191 KB
/
dtv.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.UTF_16LE;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.math.RoundingMode;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
import java.util.Calendar;
import java.util.EnumMap;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.Map;
import java.util.SimpleTimeZone;
import java.util.TimeZone;
import java.util.UUID;
import com.microsoft.sqlserver.jdbc.JavaType.SetterConversionAE;
/**
* Defines an abstraction for execution of type-specific operations on DTV values.
*
* This abstract design keeps the logic of determining how to handle particular DTV value and jdbcType combinations in a
* single place (DTV.executeOp()) and forces new operations to be able to handle *all* the required combinations.
*
* Current operations and their locations are:
*
* Parameter.GetTypeDefinitionOp Determines the specific parameter type definition according to the current value.
*
* DTV.SendByRPCOp (below) Marshals the value onto the binary (RPC) buffer for sending to the server.
*/
abstract class DTVExecuteOp {
abstract void execute(DTV dtv, String strValue) throws SQLServerException;
abstract void execute(DTV dtv, Clob clobValue) throws SQLServerException;
abstract void execute(DTV dtv, Byte byteValue) throws SQLServerException;
abstract void execute(DTV dtv, Integer intValue) throws SQLServerException;
abstract void execute(DTV dtv, java.sql.Time timeValue) throws SQLServerException;
abstract void execute(DTV dtv, java.sql.Date dateValue) throws SQLServerException;
abstract void execute(DTV dtv, java.sql.Timestamp timestampValue) throws SQLServerException;
abstract void execute(DTV dtv, java.util.Date utilDateValue) throws SQLServerException;
abstract void execute(DTV dtv, java.util.Calendar calendarValue) throws SQLServerException;
abstract void execute(DTV dtv, LocalDate localDateValue) throws SQLServerException;
abstract void execute(DTV dtv, LocalTime localTimeValue) throws SQLServerException;
abstract void execute(DTV dtv, LocalDateTime localDateTimeValue) throws SQLServerException;
abstract void execute(DTV dtv, OffsetTime offsetTimeValue) throws SQLServerException;
abstract void execute(DTV dtv, OffsetDateTime offsetDateTimeValue) throws SQLServerException;
abstract void execute(DTV dtv, microsoft.sql.DateTimeOffset dtoValue) throws SQLServerException;
abstract void execute(DTV dtv, Float floatValue) throws SQLServerException;
abstract void execute(DTV dtv, Double doubleValue) throws SQLServerException;
abstract void execute(DTV dtv, BigDecimal bigDecimalValue) throws SQLServerException;
abstract void execute(DTV dtv, Long longValue) throws SQLServerException;
abstract void execute(DTV dtv, BigInteger bigIntegerValue) throws SQLServerException;
abstract void execute(DTV dtv, Short shortValue) throws SQLServerException;
abstract void execute(DTV dtv, Boolean booleanValue) throws SQLServerException;
abstract void execute(DTV dtv, byte[] byteArrayValue) throws SQLServerException;
abstract void execute(DTV dtv, Blob blobValue) throws SQLServerException;
abstract void execute(DTV dtv, InputStream inputStreamValue) throws SQLServerException;
abstract void execute(DTV dtv, Reader readerValue) throws SQLServerException;
abstract void execute(DTV dtv, SQLServerSQLXML xmlValue) throws SQLServerException;
abstract void execute(DTV dtv, TVP tvpValue) throws SQLServerException;
abstract void execute(DTV dtv, SqlVariant sqlVariantValue) throws SQLServerException;
}
/**
* Outer level DTV class.
*
* All DTV manipulation is done through this class.
*/
final class DTV {
static final private java.util.logging.Logger aeLogger = java.util.logging.Logger
.getLogger("com.microsoft.sqlserver.jdbc.DTV");
/** The source (app or server) providing the data for this value. */
private DTVImpl impl;
CryptoMetadata cryptoMeta = null;
JDBCType jdbcTypeSetByUser = null;
int valueLength = 0;
boolean sendStringParametersAsUnicode = true;
/**
* Sets a DTV value from a Java object.
*
* The new value replaces any value (column or parameter return value) that was previously set via the TDS response.
* Doing this may change the DTV's internal implementation to an AppDTVImpl.
*/
void setValue(SQLCollation collation, JDBCType jdbcType, Object value, JavaType javaType,
StreamSetterArgs streamSetterArgs, Calendar calendar, Integer scale, SQLServerConnection con,
boolean forceEncrypt) throws SQLServerException {
if (null == impl)
impl = new AppDTVImpl();
impl.setValue(this, collation, jdbcType, value, javaType, streamSetterArgs, calendar, scale, con, forceEncrypt);
}
final void setValue(Object value, JavaType javaType) {
impl.setValue(value, javaType);
}
final void clear() {
impl = null;
}
final void skipValue(TypeInfo type, TDSReader tdsReader, boolean isDiscard) throws SQLServerException {
if (null == impl)
impl = new ServerDTVImpl();
impl.skipValue(type, tdsReader, isDiscard);
}
final void initFromCompressedNull() {
if (null == impl)
impl = new ServerDTVImpl();
impl.initFromCompressedNull();
}
final void setStreamSetterArgs(StreamSetterArgs streamSetterArgs) {
impl.setStreamSetterArgs(streamSetterArgs);
}
final void setCalendar(Calendar calendar) {
impl.setCalendar(calendar);
}
final void setScale(Integer scale) {
impl.setScale(scale);
}
final void setForceEncrypt(boolean forceEncrypt) {
impl.setForceEncrypt(forceEncrypt);
}
StreamSetterArgs getStreamSetterArgs() {
return impl.getStreamSetterArgs();
}
Calendar getCalendar() {
return impl.getCalendar();
}
Integer getScale() {
return impl.getScale();
}
/**
* Returns whether the DTV's current value is null.
*/
boolean isNull() {
return null == impl || impl.isNull();
}
/**
* @return true if impl is not null
*/
final boolean isInitialized() {
return (null != impl);
}
final void setJdbcType(JDBCType jdbcType) {
if (null == impl)
impl = new AppDTVImpl();
impl.setJdbcType(jdbcType);
}
/**
* Returns the DTV's current JDBC type
*/
final JDBCType getJdbcType() {
assert null != impl;
return impl.getJdbcType();
}
/**
* Returns the DTV's current JDBC type
*/
final JavaType getJavaType() {
assert null != impl;
return impl.getJavaType();
}
/**
* Returns the DTV's current value as the specified type.
*
* This variant of getValue() takes an extra parameter to handle the few cases where extra arguments are needed to
* determine the value (e.g. a Calendar object for time-valued DTV values).
*/
Object getValue(JDBCType jdbcType, int scale, InputStreamGetterArgs streamGetterArgs, Calendar cal,
TypeInfo typeInfo, CryptoMetadata cryptoMetadata, TDSReader tdsReader) throws SQLServerException {
if (null == impl)
impl = new ServerDTVImpl();
return impl.getValue(this, jdbcType, scale, streamGetterArgs, cal, typeInfo, cryptoMetadata, tdsReader);
}
Object getSetterValue() {
return impl.getSetterValue();
}
SqlVariant getInternalVariant() {
return impl.getInternalVariant();
}
/**
* Called by DTV implementation instances to change to a different DTV implementation.
*/
void setImpl(DTVImpl impl) {
this.impl = impl;
}
final class SendByRPCOp extends DTVExecuteOp {
private final String name;
private final TypeInfo typeInfo;
private final SQLCollation collation;
private final int precision;
private final int outScale;
private final boolean isOutParam;
private final TDSWriter tdsWriter;
private final SQLServerConnection conn;
SendByRPCOp(String name, TypeInfo typeInfo, SQLCollation collation, int precision, int outScale,
boolean isOutParam, TDSWriter tdsWriter, SQLServerConnection conn) {
this.name = name;
this.typeInfo = typeInfo;
this.collation = collation;
this.precision = precision;
this.outScale = outScale;
this.isOutParam = isOutParam;
this.tdsWriter = tdsWriter;
this.conn = conn;
}
void execute(DTV dtv, String strValue) throws SQLServerException {
tdsWriter.writeRPCStringUnicode(name, strValue, isOutParam, collation);
}
void execute(DTV dtv, Clob clobValue) throws SQLServerException {
// executeOp should have handled null Clob as a String
assert null != clobValue;
long clobLength = 0;
Reader clobReader = null;
try {
clobLength = DataTypes.getCheckedLength(conn, dtv.getJdbcType(), clobValue.length(), false);
clobReader = clobValue.getCharacterStream();
} catch (SQLException e) {
SQLServerException.makeFromDriverError(conn, null, e.getMessage(), null, false);
}
// If the Clob value is to be sent as MBCS, then convert the value to an MBCS InputStream
JDBCType jdbcType = dtv.getJdbcType();
if (null != collation && (JDBCType.CHAR == jdbcType || JDBCType.VARCHAR == jdbcType
|| JDBCType.LONGVARCHAR == jdbcType || JDBCType.CLOB == jdbcType)) {
if (null == clobReader) {
tdsWriter.writeRPCByteArray(name, null, isOutParam, jdbcType, collation);
} else {
ReaderInputStream clobStream = new ReaderInputStream(clobReader, collation.getCharset(),
clobLength);
tdsWriter.writeRPCInputStream(name, clobStream, DataTypes.UNKNOWN_STREAM_LENGTH, isOutParam,
jdbcType, collation);
}
} else // Send CLOB value as Unicode
{
if (null == clobReader) {
tdsWriter.writeRPCStringUnicode(name, null, isOutParam, collation);
} else {
tdsWriter.writeRPCReaderUnicode(name, clobReader, clobLength, isOutParam, collation);
}
}
}
void execute(DTV dtv, Byte byteValue) throws SQLServerException {
tdsWriter.writeRPCByte(name, byteValue, isOutParam);
}
void execute(DTV dtv, Integer intValue) throws SQLServerException {
tdsWriter.writeRPCInt(name, intValue, isOutParam);
}
void execute(DTV dtv, java.sql.Time timeValue) throws SQLServerException {
sendTemporal(dtv, JavaType.TIME, timeValue);
}
void execute(DTV dtv, java.sql.Date dateValue) throws SQLServerException {
sendTemporal(dtv, JavaType.DATE, dateValue);
}
void execute(DTV dtv, java.sql.Timestamp timestampValue) throws SQLServerException {
sendTemporal(dtv, JavaType.TIMESTAMP, timestampValue);
}
void execute(DTV dtv, java.util.Date utilDateValue) throws SQLServerException {
sendTemporal(dtv, JavaType.UTILDATE, utilDateValue);
}
void execute(DTV dtv, java.util.Calendar calendarValue) throws SQLServerException {
sendTemporal(dtv, JavaType.CALENDAR, calendarValue);
}
void execute(DTV dtv, LocalDate localDateValue) throws SQLServerException {
sendTemporal(dtv, JavaType.LOCALDATE, localDateValue);
}
void execute(DTV dtv, LocalTime localTimeValue) throws SQLServerException {
sendTemporal(dtv, JavaType.LOCALTIME, localTimeValue);
}
void execute(DTV dtv, LocalDateTime localDateTimeValue) throws SQLServerException {
sendTemporal(dtv, JavaType.LOCALDATETIME, localDateTimeValue);
}
void execute(DTV dtv, OffsetTime offsetTimeValue) throws SQLServerException {
sendTemporal(dtv, JavaType.OFFSETTIME, offsetTimeValue);
}
void execute(DTV dtv, OffsetDateTime offsetDateTimeValue) throws SQLServerException {
sendTemporal(dtv, JavaType.OFFSETDATETIME, offsetDateTimeValue);
}
void execute(DTV dtv, microsoft.sql.DateTimeOffset dtoValue) throws SQLServerException {
sendTemporal(dtv, JavaType.DATETIMEOFFSET, dtoValue);
}
void execute(DTV dtv, TVP tvpValue) throws SQLServerException {
// shouldn't be an output parameter
tdsWriter.writeTVP(tvpValue);
}
/**
* Clears the calendar and then sets only the fields passed in. Rest of the fields will have default values.
*/
private void clearSetCalendar(Calendar cal, boolean lenient, Integer year, Integer month, Integer day_of_month,
Integer hour_of_day, Integer minute, Integer second) {
cal.clear();
cal.setLenient(lenient);
if (null != year) {
cal.set(Calendar.YEAR, year);
}
if (null != month) {
cal.set(Calendar.MONTH, month);
}
if (null != day_of_month) {
cal.set(Calendar.DAY_OF_MONTH, day_of_month);
}
if (null != hour_of_day) {
cal.set(Calendar.HOUR_OF_DAY, hour_of_day);
}
if (null != minute) {
cal.set(Calendar.MINUTE, minute);
}
if (null != second) {
cal.set(Calendar.SECOND, second);
}
}
/**
* Sends the specified temporal type value to the server as the appropriate SQL Server type.
*
* To send the value to the server, this method does the following: 1) Converts its given temporal value
* argument into a common form encapsulated by a pure, lenient GregorianCalendar instance. 2) Normalizes that
* common form according to the target data type. 3) Sends the value to the server using the appropriate target
* data type method.
*
* @param dtv
* DTV with type info, etc.
* @param javaType
* the Java type of the Object that follows
* @param value
* the temporal value to send to the server. May be null.
*/
private void sendTemporal(DTV dtv, JavaType javaType, Object value) throws SQLServerException {
JDBCType jdbcType = dtv.getJdbcType();
GregorianCalendar calendar = null;
int subSecondNanos = 0;
int minutesOffset = 0;
/*
* Some precisions to consider: java.sql.Time is millisecond precision java.sql.Timestamp is nanosecond
* precision java.util.Date is millisecond precision java.util.Calendar is millisecond precision
* java.time.LocalTime is nanosecond precision java.time.LocalDateTime is nanosecond precision
* java.time.OffsetTime is nanosecond precision, with a zone offset java.time.OffsetDateTime is nanosecond
* precision, with a zone offset SQL Server Types: datetime2 is 7 digit precision, i.e 100 ns (default and
* max) datetime is 3 digit precision, i.e ms precision (default and max) time is 7 digit precision, i.e 100
* ns (default and max) Note: sendTimeAsDatetime is true by default and it actually sends the time value as
* datetime, not datetime2 which looses precision values as datetime is only MS precision (1/300 of a second
* to be precise). Null values pass right on through to the typed writers below. For non-null values, load
* the value from its original Java object (java.sql.Time, java.sql.Date, java.sql.Timestamp,
* java.util.Date, java.time.LocalDate, java.time.LocalTime, java.time.LocalDateTime or
* microsoft.sql.DateTimeOffset) into a Gregorian calendar. Don't use the DTV's calendar directly, as it may
* not be Gregorian...
*/
if (null != value) {
TimeZone timeZone = TimeZone.getDefault(); // Time zone to associate with the value in the Gregorian
// calendar
long utcMillis = 0; // Value to which the calendar is to be set (in milliseconds 1/1/1970 00:00:00 GMT)
// Figure out the value components according to the type of the Java object passed in...
switch (javaType) {
case TIME: {
// Set the time zone from the calendar supplied by the app or use the JVM default
timeZone = (null != dtv.getCalendar()) ? dtv.getCalendar().getTimeZone()
: TimeZone.getDefault();
utcMillis = ((java.sql.Time) value).getTime();
subSecondNanos = Nanos.PER_MILLISECOND * (int) (utcMillis % 1000);
// The utcMillis value may be negative for morning times in time zones east of GMT.
// Since the date part of the java.sql.Time object is normalized to 1/1/1970
// in the local time zone, the date may still be 12/31/1969 UTC.
//
// If that is the case then adjust the sub-second nanos to the correct non-negative
// "wall clock" value. For example: -1 nanos (one nanosecond before midnight) becomes
// 999999999 nanos (999,999,999 nanoseconds after 11:59:59).
if (subSecondNanos < 0)
subSecondNanos += Nanos.PER_SECOND;
break;
}
case DATE: {
// Set the time zone from the calendar supplied by the app or use the JVM default
timeZone = (null != dtv.getCalendar()) ? dtv.getCalendar().getTimeZone()
: TimeZone.getDefault();
utcMillis = ((java.sql.Date) value).getTime();
break;
}
case TIMESTAMP: {
// Set the time zone from the calendar supplied by the app or use the JVM default
timeZone = (null != dtv.getCalendar()) ? dtv.getCalendar().getTimeZone()
: TimeZone.getDefault();
java.sql.Timestamp timestampValue = (java.sql.Timestamp) value;
utcMillis = timestampValue.getTime();
subSecondNanos = timestampValue.getNanos();
break;
}
case UTILDATE: {
// java.util.Date is mapped to JDBC type TIMESTAMP
// java.util.Date and java.sql.Date are both millisecond precision
// Set the time zone from the calendar supplied by the app or use the JVM default
timeZone = (null != dtv.getCalendar()) ? dtv.getCalendar().getTimeZone()
: TimeZone.getDefault();
utcMillis = ((java.util.Date) value).getTime();
// Need to use the subsecondnanoes part in UTILDATE besause it is mapped to JDBC TIMESTAMP. This
// is not
// needed in DATE because DATE is mapped to JDBC DATE (with time part normalized to midnight)
subSecondNanos = Nanos.PER_MILLISECOND * (int) (utcMillis % 1000);
// The utcMillis value may be negative for morning times in time zones east of GMT.
// Since the date part of the java.sql.Time object is normalized to 1/1/1970
// in the local time zone, the date may still be 12/31/1969 UTC.
//
// If that is the case then adjust the sub-second nanos to the correct non-negative
// "wall clock" value. For example: -1 nanos (one nanosecond before midnight) becomes
// 999999999 nanos (999,999,999 nanoseconds after 11:59:59).
if (subSecondNanos < 0)
subSecondNanos += Nanos.PER_SECOND;
break;
}
case CALENDAR: {
// java.util.Calendar is mapped to JDBC type TIMESTAMP
// java.util.Calendar is millisecond precision
// Set the time zone from the calendar supplied by the app or use the JVM default
timeZone = (null != dtv.getCalendar()) ? dtv.getCalendar().getTimeZone()
: TimeZone.getDefault();
utcMillis = ((java.util.Calendar) value).getTimeInMillis();
// Need to use the subsecondnanoes part in CALENDAR besause it is mapped to JDBC TIMESTAMP. This
// is not
// needed in DATE because DATE is mapped to JDBC DATE (with time part normalized to midnight)
subSecondNanos = Nanos.PER_MILLISECOND * (int) (utcMillis % 1000);
// The utcMillis value may be negative for morning times in time zones east of GMT.
// Since the date part of the java.sql.Time object is normalized to 1/1/1970
// in the local time zone, the date may still be 12/31/1969 UTC.
//
// If that is the case then adjust the sub-second nanos to the correct non-negative
// "wall clock" value. For example: -1 nanos (one nanosecond before midnight) becomes
// 999999999 nanos (999,999,999 nanoseconds after 11:59:59).
if (subSecondNanos < 0)
subSecondNanos += Nanos.PER_SECOND;
break;
}
case LOCALDATE:
// Mapped to JDBC type DATE
calendar = new GregorianCalendar(UTC.timeZone, Locale.US);
// All time fields are set to default
clearSetCalendar(calendar, true, ((LocalDate) value).getYear(),
((LocalDate) value).getMonthValue() - 1, // Calendar 'month'
// is 0-based, but
// LocalDate 'month'
// is 1-based
((LocalDate) value).getDayOfMonth(), null, null, null);
break;
case LOCALTIME:
// Nanoseconds precision, mapped to JDBC type TIME
calendar = new GregorianCalendar(UTC.timeZone, Locale.US);
// All date fields are set to default
LocalTime LocalTimeValue = ((LocalTime) value);
clearSetCalendar(calendar, true, conn.baseYear(), 1, 1, LocalTimeValue.getHour(), // Gets
// hour_of_day
// field
LocalTimeValue.getMinute(), LocalTimeValue.getSecond());
subSecondNanos = LocalTimeValue.getNano();
// Do not need to adjust subSecondNanos as in the case for TIME
// because LOCALTIME does not have time zone and is not using utcMillis
break;
case LOCALDATETIME:
// Nanoseconds precision, mapped to JDBC type TIMESTAMP
calendar = new GregorianCalendar(UTC.timeZone, Locale.US);
// Calendar 'month' is 0-based, but LocalDateTime 'month' is 1-based
LocalDateTime localDateTimeValue = (LocalDateTime) value;
clearSetCalendar(calendar, true, localDateTimeValue.getYear(),
localDateTimeValue.getMonthValue() - 1, localDateTimeValue.getDayOfMonth(),
localDateTimeValue.getHour(), // Gets hour_of_day field
localDateTimeValue.getMinute(), localDateTimeValue.getSecond());
subSecondNanos = localDateTimeValue.getNano();
// Do not need to adjust subSecondNanos as in the case for TIME
// because LOCALDATETIME does not have time zone and is not using utcMillis
break;
case OFFSETTIME:
OffsetTime offsetTimeValue = (OffsetTime) value;
try {
// offsetTimeValue.getOffset() returns a ZoneOffset object which has only hours and minutes
// components. So the result of the division will be an integer always. SQL Server also
// supports
// offsets in minutes precision.
minutesOffset = offsetTimeValue.getOffset().getTotalSeconds() / 60;
} catch (Exception e) {
throw new SQLServerException(SQLServerException.getErrString("R_zoneOffsetError"), null, // SQLState
// is
// null
// as
// this
// error
// is
// generated
// in
// the
// driver
0, // Use 0 instead of DriverError.NOT_SET to use the correct constructor
e);
}
subSecondNanos = offsetTimeValue.getNano();
// If the target data type is TIME_WITH_TIMEZONE, then use UTC for the calendar that
// will hold the value, since writeRPCDateTimeOffset expects a UTC calendar.
// Otherwise, when converting from DATETIMEOFFSET to other temporal data types,
// use a local time zone determined by the minutes offset of the value, since
// the writers for those types expect local calendars.
timeZone = (JDBCType.TIME_WITH_TIMEZONE == jdbcType
&& (null == typeInfo || SSType.DATETIMEOFFSET == typeInfo.getSSType())) ?
UTC.timeZone
: new SimpleTimeZone(
minutesOffset
* 60
* 1000,
"");
LocalDate baseDate = LocalDate.of(conn.baseYear(), 1, 1);
utcMillis = offsetTimeValue.atDate(baseDate).toEpochSecond() * 1000;
break;
case OFFSETDATETIME:
OffsetDateTime offsetDateTimeValue = (OffsetDateTime) value;
try {
// offsetTimeValue.getOffset() returns a ZoneOffset object which has only hours and minutes
// components. So the result of the division will be an integer always. SQL Server also
// supports
// offsets in minutes precision.
minutesOffset = offsetDateTimeValue.getOffset().getTotalSeconds() / 60;
} catch (Exception e) {
throw new SQLServerException(SQLServerException.getErrString("R_zoneOffsetError"), null, // SQLState
// is
// null
// as
// this
// error
// is
// generated
// in
// the
// driver
0, // Use 0 instead of DriverError.NOT_SET to use the correct constructor
e);
}
subSecondNanos = offsetDateTimeValue.getNano();
// If the target data type is TIME_WITH_TIMEZONE or TIMESTAMP_WITH_TIMEZONE, then use UTC for
// the calendar that
// will hold the value, since writeRPCDateTimeOffset expects a UTC calendar.
// Otherwise, when converting from DATETIMEOFFSET to other temporal data types,
// use a local time zone determined by the minutes offset of the value, since
// the writers for those types expect local calendars.
timeZone = ((JDBCType.TIMESTAMP_WITH_TIMEZONE == jdbcType
|| JDBCType.TIME_WITH_TIMEZONE == jdbcType)
&& (null == typeInfo || SSType.DATETIMEOFFSET == typeInfo.getSSType()))
? UTC.timeZone
: new SimpleTimeZone(
minutesOffset
* 60
* 1000,
"");
utcMillis = offsetDateTimeValue.toEpochSecond() * 1000;
break;
case DATETIMEOFFSET: {
microsoft.sql.DateTimeOffset dtoValue = (microsoft.sql.DateTimeOffset) value;
utcMillis = dtoValue.getTimestamp().getTime();
subSecondNanos = dtoValue.getTimestamp().getNanos();
minutesOffset = dtoValue.getMinutesOffset();
// microsoft.sql.DateTimeOffset values have a time zone offset that is internal
// to the value, so there should not be any DTV calendar for DateTimeOffset values.
assert null == dtv.getCalendar();
// If the target data type is DATETIMEOFFSET, then use UTC for the calendar that
// will hold the value, since writeRPCDateTimeOffset expects a UTC calendar.
// Otherwise, when converting from DATETIMEOFFSET to other temporal data types,
// use a local time zone determined by the minutes offset of the value, since
// the writers for those types expect local calendars.
timeZone = (JDBCType.DATETIMEOFFSET == jdbcType
&& (null == typeInfo || SSType.DATETIMEOFFSET == typeInfo.getSSType()
|| SSType.VARBINARY == typeInfo.getSSType()
|| SSType.VARBINARYMAX == typeInfo.getSSType())) ?
UTC.timeZone
: new SimpleTimeZone(
minutesOffset * 60
* 1000,
"");
break;
}
default:
throw new AssertionError("Unexpected JavaType: " + javaType);
}
// For the LocalDate, LocalTime and LocalDateTime values, calendar should be set by now.
if (null == calendar) {
// Create the calendar that will hold the value. For DateTimeOffset values, the calendar's
// time zone is UTC. For other values, the calendar's time zone is a local time zone.
calendar = new GregorianCalendar(timeZone, Locale.US);
// Set the calendar lenient to allow setting the DAY_OF_YEAR and MILLISECOND fields
// to roll other fields to their correct values.
calendar.setLenient(true);
// Clear the calendar of any existing state. The state of a new Calendar object always
// reflects the current date, time, DST offset, etc.
calendar.clear();
// Load the calendar with the desired value
calendar.setTimeInMillis(utcMillis);
}
}
// With the value now stored in a Calendar object, determine the backend data type and
// write out the value to the server, after any necessarily normalization.
// typeInfo is null when called from PreparedStatement->Parameter->SendByRPC
if (null != typeInfo) // updater
{
switch (typeInfo.getSSType()) {
case DATETIME:
case DATETIME2:
/*
* Default and max fractional precision is 7 digits (100ns) Send DateTime2 to DateTime columns
* to let the server handle nanosecond rounding. Also adjust scale accordingly to avoid rounding
* on driver's end.
*/
int scale = (typeInfo.getSSType() == SSType.DATETIME) ? typeInfo.getScale() + 4
: typeInfo.getScale();
tdsWriter.writeRPCDateTime2(name,
timestampNormalizedCalendar(calendar, javaType, conn.baseYear()), subSecondNanos, scale,
isOutParam);
break;
case DATE:
tdsWriter.writeRPCDate(name, calendar, isOutParam);
break;
case TIME:
// Default and max fractional precision is 7 digits (100ns)
tdsWriter.writeRPCTime(name, calendar, subSecondNanos, typeInfo.getScale(), isOutParam);
break;
case DATETIMEOFFSET:
// When converting from any other temporal Java type to DATETIMEOFFSET,
// deliberately interpret the "wall calendar" representation as expressing
// a date/time in UTC rather than the local time zone.
if (JavaType.DATETIMEOFFSET != javaType) {
calendar = timestampNormalizedCalendar(localCalendarAsUTC(calendar), javaType,
conn.baseYear());
minutesOffset = 0; // UTC
}
tdsWriter.writeRPCDateTimeOffset(name, calendar, minutesOffset, subSecondNanos,
typeInfo.getScale(), isOutParam);
break;
case SMALLDATETIME:
tdsWriter.writeRPCDateTime(name,
timestampNormalizedCalendar(calendar, javaType, conn.baseYear()), subSecondNanos,
isOutParam);
break;
case VARBINARY:
case VARBINARYMAX:
switch (jdbcType) {
case DATETIME:
case SMALLDATETIME:
tdsWriter.writeEncryptedRPCDateTime(name,
timestampNormalizedCalendar(calendar, javaType, conn.baseYear()),
subSecondNanos, isOutParam, jdbcType);
break;
case TIMESTAMP:
assert null != cryptoMeta;
tdsWriter.writeEncryptedRPCDateTime2(name,
timestampNormalizedCalendar(calendar, javaType, conn.baseYear()),
subSecondNanos, valueLength, isOutParam);
break;
case TIME:
// when colum is encrypted, always send time as time, ignore sendTimeAsDatetime setting
assert null != cryptoMeta;
tdsWriter.writeEncryptedRPCTime(name, calendar, subSecondNanos, valueLength,
isOutParam);
break;
case DATE:
assert null != cryptoMeta;
tdsWriter.writeEncryptedRPCDate(name, calendar, isOutParam);
break;
case TIMESTAMP_WITH_TIMEZONE:
case DATETIMEOFFSET:
// When converting from any other temporal Java type to
// DATETIMEOFFSET/TIMESTAMP_WITH_TIMEZONE,
// deliberately reinterpret the value as local to UTC. This is to match
// SQL Server behavior for such conversions.
if ((JavaType.DATETIMEOFFSET != javaType) && (JavaType.OFFSETDATETIME != javaType)) {
calendar = timestampNormalizedCalendar(localCalendarAsUTC(calendar), javaType,
conn.baseYear());
minutesOffset = 0; // UTC
}
assert null != cryptoMeta;
tdsWriter.writeEncryptedRPCDateTimeOffset(name, calendar, minutesOffset, subSecondNanos,
valueLength, isOutParam);
break;
default:
assert false : "Unexpected JDBCType: " + jdbcType;
}
break;
default:
assert false : "Unexpected SSType: " + typeInfo.getSSType();
}
} else // setter
{
// Katmai and later
// ----------------
//
// When sending as...
// - java.sql.Types.TIMESTAMP, use DATETIME2 SQL Server data type
// - java.sql.Types.TIME, use TIME or DATETIME SQL Server data type
// as determined by sendTimeAsDatetime setting
// - java.sql.Types.DATE, use DATE SQL Server data type
// - microsoft.sql.Types.DATETIMEOFFSET, use DATETIMEOFFSET SQL Server data type
if (conn.isKatmaiOrLater()) {
if (aeLogger.isLoggable(java.util.logging.Level.FINE) && (null != cryptoMeta)) {
aeLogger.fine("Encrypting temporal data type.");
}
switch (jdbcType) {
case DATETIME:
case SMALLDATETIME:
case TIMESTAMP:
if (null != cryptoMeta) {
if ((JDBCType.DATETIME == jdbcType) || (JDBCType.SMALLDATETIME == jdbcType)) {
tdsWriter.writeEncryptedRPCDateTime(name,
timestampNormalizedCalendar(calendar, javaType, conn.baseYear()),
subSecondNanos, isOutParam, jdbcType);
} else if (0 == valueLength) {
tdsWriter.writeEncryptedRPCDateTime2(name,
timestampNormalizedCalendar(calendar, javaType, conn.baseYear()),
subSecondNanos, outScale, isOutParam);
} else {
tdsWriter.writeEncryptedRPCDateTime2(name,
timestampNormalizedCalendar(calendar, javaType, conn.baseYear()),
subSecondNanos, (valueLength), isOutParam);
}
} else
tdsWriter.writeRPCDateTime2(name,
timestampNormalizedCalendar(calendar, javaType, conn.baseYear()),
subSecondNanos, TDS.MAX_FRACTIONAL_SECONDS_SCALE, isOutParam);
break;
case TIME:
// if column is encrypted, always send as TIME
if (null != cryptoMeta) {
if (0 == valueLength) {
tdsWriter.writeEncryptedRPCTime(name, calendar, subSecondNanos, outScale,
isOutParam);
} else {
tdsWriter.writeEncryptedRPCTime(name, calendar, subSecondNanos, valueLength,
isOutParam);
}
} else {
// Send the java.sql.Types.TIME value as TIME or DATETIME SQL Server
// data type, based on sendTimeAsDatetime setting.
if (conn.getSendTimeAsDatetime()) {
tdsWriter.writeRPCDateTime(name,
timestampNormalizedCalendar(calendar, JavaType.TIME, TDS.BASE_YEAR_1970),
subSecondNanos, isOutParam);
} else {
tdsWriter.writeRPCTime(name, calendar, subSecondNanos,
TDS.MAX_FRACTIONAL_SECONDS_SCALE, isOutParam);
}
}
break;
case DATE:
if (null != cryptoMeta)
tdsWriter.writeEncryptedRPCDate(name, calendar, isOutParam);
else
tdsWriter.writeRPCDate(name, calendar, isOutParam);
break;
case TIME_WITH_TIMEZONE:
// When converting from any other temporal Java type to TIME_WITH_TIMEZONE,
// deliberately reinterpret the value as local to UTC. This is to match
// SQL Server behavior for such conversions.
if ((JavaType.OFFSETDATETIME != javaType) && (JavaType.OFFSETTIME != javaType)) {
calendar = timestampNormalizedCalendar(localCalendarAsUTC(calendar), javaType,
conn.baseYear());
minutesOffset = 0; // UTC
}
tdsWriter.writeRPCDateTimeOffset(name, calendar, minutesOffset, subSecondNanos,
TDS.MAX_FRACTIONAL_SECONDS_SCALE, isOutParam);
break;
case TIMESTAMP_WITH_TIMEZONE:
case DATETIMEOFFSET:
// When converting from any other temporal Java type to
// DATETIMEOFFSET/TIMESTAMP_WITH_TIMEZONE,
// deliberately reinterpret the value as local to UTC. This is to match
// SQL Server behavior for such conversions.
if ((JavaType.DATETIMEOFFSET != javaType) && (JavaType.OFFSETDATETIME != javaType)) {
calendar = timestampNormalizedCalendar(localCalendarAsUTC(calendar), javaType,
conn.baseYear());
minutesOffset = 0; // UTC
}
if (null != cryptoMeta) {
if (0 == valueLength) {
tdsWriter.writeEncryptedRPCDateTimeOffset(name, calendar, minutesOffset,
subSecondNanos, outScale, isOutParam);
} else {
tdsWriter.writeEncryptedRPCDateTimeOffset(name, calendar, minutesOffset,
subSecondNanos,
(0 == valueLength ? TDS.MAX_FRACTIONAL_SECONDS_SCALE : valueLength),
isOutParam);
}
} else
tdsWriter.writeRPCDateTimeOffset(name, calendar, minutesOffset, subSecondNanos,
TDS.MAX_FRACTIONAL_SECONDS_SCALE, isOutParam);
break;
default:
assert false : "Unexpected JDBCType: " + jdbcType;
}
}
// Yukon and earlier
// -----------------
//
// When sending as...
// - java.sql.Types.TIMESTAMP, use DATETIME SQL Server data type (all components)
// - java.sql.Types.TIME, use DATETIME SQL Server data type (with date = 1/1/1970)
// - java.sql.Types.DATE, use DATETIME SQL Server data type (with time = midnight)
// - microsoft.sql.Types.DATETIMEOFFSET (not supported - exception should have been thrown earlier)
else {
assert JDBCType.TIME == jdbcType || JDBCType.DATE == jdbcType
|| JDBCType.TIMESTAMP == jdbcType : "Unexpected JDBCType: " + jdbcType;
tdsWriter.writeRPCDateTime(name,
timestampNormalizedCalendar(calendar, javaType, TDS.BASE_YEAR_1970), subSecondNanos,
isOutParam);
}
} // setters
}
/**
* Normalizes a GregorianCalendar value appropriately for a DATETIME, SMALLDATETIME, DATETIME2, or
* DATETIMEOFFSET SQL Server data type.
*
* For DATE values, the time must be normalized to midnight. For TIME values, the date must be normalized to
* January of the specified base year (1970 or 1900) For other temporal types (DATETIME, SMALLDATETIME,
* DATETIME2, DATETIMEOFFSET), no normalization is needed - both date and time contribute to the final value.
*
* @param calendar
* the value to normalize. May be null.
* @param javaType
* the Java type that the calendar value represents.
* @param baseYear