forked from microsoft/mssql-jdbc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParameter.java
1328 lines (1119 loc) · 59.4 KB
/
Parameter.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 java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.ResultSet;
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.Locale;
import java.util.UUID;
/**
* Parameter represents a JDBC parameter value that is supplied with a prepared or callable statement or an updatable
* result set. Parameter is JDBC type specific and is capable of representing any Java native type as well as a number
* of Java object types including binary and character streams.
*/
final class Parameter {
// Value type info for OUT parameters (excluding return status)
private TypeInfo typeInfo;
// For unencrypted parameters cryptometa will be null. For encrypted parameters it will hold encryption metadata.
CryptoMetadata cryptoMeta = null;
boolean isNonPLP = false;
TypeInfo getTypeInfo() {
return typeInfo;
}
final CryptoMetadata getCryptoMetadata() {
return cryptoMeta;
}
private boolean shouldHonorAEForParameter = false;
private boolean userProvidesPrecision = false;
private boolean userProvidesScale = false;
private boolean isReturnValue = false;
// The parameter type definition
private String typeDefinition = null;
boolean renewDefinition = false;
// updated if sendStringParametersAsUnicode=true for setNString, setNCharacterStream, and setNClob methods
private JDBCType jdbcTypeSetByUser = null;
// set length of value for variable length type (String)
private int valueLength = 0;
private boolean forceEncryption = false;
Parameter(boolean honorAE) {
shouldHonorAEForParameter = honorAE;
}
// Flag set to true if this is a registered OUTPUT parameter.
boolean isOutput() {
return null != registeredOutDTV;
}
/**
* Returns true/false if the parameter is of return type
*
* @return isReturnValue
*/
boolean isReturnValue() {
return isReturnValue;
}
/**
* Sets the parameter to be of return type
*
* @param isReturnValue
*/
void setReturnValue(boolean isReturnValue) {
this.isReturnValue = isReturnValue;
}
/**
* Sets the name of the parameter
*
* @param name
*/
void setName(String name) {
this.name = name;
}
/**
* Retrieve the name of the parameter
*
* @return
*/
String getName() {
return this.name;
}
/**
* Returns the `registeredOutDTV` instance of the parameter
*
* @return registeredOutDTV
*/
DTV getRegisteredOutDTV() {
return this.registeredOutDTV;
}
/**
* Returns the `inputDTV` instance of the parameter
*
* @return inputDTV
*/
DTV getInputDTV() {
return this.inputDTV;
}
// Since a parameter can have only one type definition for both sending its value to the server (IN)
// and getting its value from the server (OUT), we use the JDBC type of the IN parameter value if there
// is one; otherwise we use the registered OUT param JDBC type.
JDBCType getJdbcType() {
return (null != inputDTV) ? inputDTV.getJdbcType() : JDBCType.UNKNOWN;
}
/**
* Used when sendStringParametersAsUnicode=true to derive the appropriate National Character Set JDBC type
* corresponding to the specified JDBC type.
*/
private static JDBCType getSSPAUJDBCType(JDBCType jdbcType) {
switch (jdbcType) {
case CHAR:
return JDBCType.NCHAR;
case VARCHAR:
return JDBCType.NVARCHAR;
case LONGVARCHAR:
return JDBCType.LONGNVARCHAR;
case CLOB:
return JDBCType.NCLOB;
default:
return jdbcType;
}
}
// For parameters whose underlying type is not represented by a JDBC type
// the transport type reflects how the value is sent to the
// server (e.g. JDBCType.CHAR for GUID parameters).
void registerForOutput(JDBCType jdbcType, SQLServerConnection con) throws SQLServerException {
// DateTimeOffset is not supported with SQL Server versions earlier than Katmai
if (JDBCType.DATETIMEOFFSET == jdbcType && !con.isKatmaiOrLater()) {
throw new SQLServerException(SQLServerException.getErrString("R_notSupported"),
SQLState.DATA_EXCEPTION_NOT_SPECIFIC, DriverError.NOT_SET, null);
}
// sendStringParametersAsUnicode
// If set to true, this connection property tells the driver to send textual parameters
// to the server as Unicode rather than MBCS. This is accomplished here by re-tagging
// the value with the appropriate corresponding Unicode type.
if (con.sendStringParametersAsUnicode()) {
if (shouldHonorAEForParameter) {
setJdbcTypeSetByUser(jdbcType);
}
jdbcType = getSSPAUJDBCType(jdbcType);
}
registeredOutDTV = new DTV();
registeredOutDTV.setJdbcType(jdbcType);
if (null == setterDTV)
inputDTV = registeredOutDTV;
resetOutputValue();
}
int scale = 0;
// Scale requested for a DECIMAL and NUMERIC OUT parameter. If the OUT parameter
// is also non-null IN parameter, the scale will be the larger of this value and
// the value of the IN parameter's scale.
private int outScale = 4;
int getOutScale() {
return outScale;
}
void setOutScale(int outScale) {
this.outScale = outScale;
userProvidesScale = true;
}
// The parameter name
private String name;
private String schemaName;
/*
* The different DTVs representing the parameter's value: getterDTV - The OUT value, if set, of the parameter after
* execution. This is the value retrieved by CallableStatement getter methods. registeredOutDTV - The "IN" value
* corresponding to a SQL NULL with a JDBC type that was passed to the CallableStatement.registerOutParameter
* method. Since SQL Server does not directly support OUT-only parameters (just IN and IN/OUT), the driver sends a
* null IN value for an OUT parameter, unless the application set an input value (setterDTV) as well. setterDTV -
* The IN value, if set, of the parameter. This is the value set by PreparedStatement and CallableStatement setter
* methods. inputDTV - If set, refers to either setterDTV or registeredOutDTV depending on whether the parameter is
* IN, IN/OUT, or OUT-only. If cleared (i.e. set to null), it means that no value is set for the parameter and that
* execution of the PreparedStatement or CallableStatement should throw a "parameter not set" exception. Note that
* if the parameter value is a stream, the driver consumes its contents it at execution and clears inputDTV and
* setterDTV so that the application must reset the parameter prior to the next execution to avoid getting a
* "parameter not set" exception.
*/
private DTV getterDTV;
private DTV registeredOutDTV = null;
private DTV setterDTV = null;
private DTV inputDTV = null;
/**
* Clones this Parameter object for use in a batch.
*
* The clone method creates a shallow clone of the Parameter object. That is, the cloned instance references all of
* the same internal objects and state as the original.
*
* Note: this method is purposely NOT the Object.clone() method, as that method has specific requirements and
* semantics that we don't need here.
*/
final Parameter cloneForBatch() {
Parameter clonedParam = new Parameter(shouldHonorAEForParameter);
clonedParam.typeInfo = typeInfo;
clonedParam.typeDefinition = typeDefinition;
clonedParam.outScale = outScale;
clonedParam.name = name;
clonedParam.getterDTV = getterDTV;
clonedParam.registeredOutDTV = registeredOutDTV;
clonedParam.setterDTV = setterDTV;
clonedParam.inputDTV = inputDTV;
clonedParam.cryptoMeta = cryptoMeta;
clonedParam.jdbcTypeSetByUser = jdbcTypeSetByUser;
clonedParam.valueLength = valueLength;
clonedParam.userProvidesPrecision = userProvidesPrecision;
clonedParam.userProvidesScale = userProvidesScale;
return clonedParam;
}
/**
* Skip value.
*/
final void skipValue(TDSReader tdsReader, boolean isDiscard) throws SQLServerException {
if (null == getterDTV)
getterDTV = new DTV();
deriveTypeInfo(tdsReader);
getterDTV.skipValue(typeInfo, tdsReader, isDiscard);
}
/**
* Skip value.
*/
final void skipRetValStatus(TDSReader tdsReader) throws SQLServerException {
StreamRetValue srv = new StreamRetValue();
srv.setFromTDS(tdsReader);
}
// Clear an INPUT parameter value
void clearInputValue() {
setterDTV = null;
inputDTV = registeredOutDTV;
}
// reset output value for re -execution
// if there was old value reset it to a new DTV
void resetOutputValue() {
getterDTV = null;
typeInfo = null;
}
void deriveTypeInfo(TDSReader tdsReader) throws SQLServerException {
if (null == typeInfo) {
typeInfo = TypeInfo.getInstance(tdsReader, true);
if (shouldHonorAEForParameter && typeInfo.isEncrypted()) {
// In this case, method getCryptoMetadata(tdsReader) retrieves baseTypeInfo without cryptoMetadata,
// so save cryptoMetadata first.
CekTableEntry cekEntry = cryptoMeta.getCekTableEntry();
cryptoMeta = (new StreamRetValue()).getCryptoMetadata(tdsReader);
cryptoMeta.setCekTableEntry(cekEntry);
}
}
}
void setFromReturnStatus(int returnStatus, SQLServerConnection con) throws SQLServerException {
if (null == getterDTV)
getterDTV = new DTV();
getterDTV.setValue(null, this.getJdbcType(), returnStatus, JavaType.INTEGER, null, null, null, con,
getForceEncryption());
}
void setValue(JDBCType jdbcType, Object value, JavaType javaType, StreamSetterArgs streamSetterArgs,
Calendar calendar, Integer precision, Integer scale, SQLServerConnection con, boolean forceEncrypt,
SQLServerStatementColumnEncryptionSetting stmtColumnEncriptionSetting, int parameterIndex, String userSQL,
String tvpName) throws SQLServerException {
if (shouldHonorAEForParameter) {
userProvidesPrecision = false;
userProvidesScale = false;
if (null != precision) {
userProvidesPrecision = true;
}
if (null != scale) {
userProvidesScale = true;
}
// for encrypted tinyint, we need to convert short value to byte value,
// otherwise it would be sent as smallint
// Also, for setters, we are able to send tinyint to smallint
// However, for output parameter, it might cause error.
if (!isOutput() && ((JavaType.SHORT == javaType)
&& ((JDBCType.TINYINT == jdbcType) || (JDBCType.SMALLINT == jdbcType)))) {
// value falls in the TINYINT range
if (((Short) value) >= 0 && ((Short) value) <= 255) {
value = ((Short) value).byteValue();
javaType = JavaType.of(value);
jdbcType = javaType.getJDBCType(SSType.UNKNOWN, jdbcType);
}
// value falls outside tinyint range. Throw an error if the user intends to send as tinyint.
else {
// This is for cases like setObject(1, Short.valueOf("-1"), java.sql.Types.TINYINT);
if (JDBCType.TINYINT == jdbcType) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_InvalidDataForAE"));
Object[] msgArgs = {javaType.toString().toLowerCase(Locale.ENGLISH),
jdbcType.toString().toLowerCase(Locale.ENGLISH)};
throw new SQLServerException(form.format(msgArgs), null);
}
}
}
}
// forceEncryption is true, shouldhonorae is false
if (forceEncrypt && !Util.shouldHonorAEForParameters(stmtColumnEncriptionSetting, con)) {
MessageFormat form = new MessageFormat(
SQLServerException.getErrString("R_ForceEncryptionTrue_HonorAEFalse"));
Object[] msgArgs = {parameterIndex, userSQL};
SQLServerException.makeFromDriverError(con, this, form.format(msgArgs), null, true);
}
// DateTimeOffset is not supported with SQL Server versions earlier than Katmai
if ((JDBCType.DATETIMEOFFSET == jdbcType || JavaType.DATETIMEOFFSET == javaType) && !con.isKatmaiOrLater()) {
throw new SQLServerException(SQLServerException.getErrString("R_notSupported"),
SQLState.DATA_EXCEPTION_NOT_SPECIFIC, DriverError.NOT_SET, null);
}
if (JavaType.TVP == javaType) {
TVP tvpValue;
if (null == value) {
tvpValue = new TVP(tvpName);
} else if (value instanceof SQLServerDataTable) {
tvpValue = new TVP(tvpName, (SQLServerDataTable) value);
} else if (value instanceof ResultSet) {
tvpValue = new TVP(tvpName, (ResultSet) value);
} else if (value instanceof ISQLServerDataRecord) {
tvpValue = new TVP(tvpName, (ISQLServerDataRecord) value);
} else {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_TVPInvalidValue"));
Object[] msgArgs = {parameterIndex};
throw new SQLServerException(form.format(msgArgs), null);
}
if (!tvpValue.isNull() && (0 == tvpValue.getTVPColumnCount())) {
throw new SQLServerException(SQLServerException.getErrString("R_TVPEmptyMetadata"), null);
}
name = (tvpValue).getTVPName();
schemaName = tvpValue.getOwningSchemaNameTVP();
value = tvpValue;
}
// setting JDBCType and exact length needed for AE stored procedure
if (shouldHonorAEForParameter) {
setForceEncryption(forceEncrypt);
// set it if it is not output parameter or jdbcTypeSetByUser is null
if (!(this.isOutput() && this.jdbcTypeSetByUser != null)) {
setJdbcTypeSetByUser(jdbcType);
}
// skip it if is (character types or binary type) & is output parameter && value is already set,
if ((!(jdbcType.isTextual() || jdbcType.isBinary())) || !(this.isOutput()) || (this.valueLength == 0)) {
this.valueLength = Util.getValueLengthBaseOnJavaType(value, javaType, precision, scale, jdbcType);
}
if (null != scale) {
this.outScale = scale;
}
}
// sendStringParametersAsUnicode
// If set to true, this connection property tells the driver to send textual parameters
// to the server as Unicode rather than MBCS. This is accomplished here by re-tagging
// the value with the appropriate corresponding Unicode type.
// JavaType.OBJECT == javaType when calling setNull()
if (con.sendStringParametersAsUnicode() && (JavaType.STRING == javaType || JavaType.READER == javaType
|| JavaType.CLOB == javaType || JavaType.OBJECT == javaType)) {
jdbcType = getSSPAUJDBCType(jdbcType);
}
DTV newDTV = new DTV();
newDTV.setValue(con.getDatabaseCollation(), jdbcType, value, javaType, streamSetterArgs, calendar, scale, con,
forceEncrypt);
if (!con.sendStringParametersAsUnicode()) {
newDTV.sendStringParametersAsUnicode = false;
}
inputDTV = setterDTV = newDTV;
}
boolean isNull() {
if (null != getterDTV)
return getterDTV.isNull();
return false;
}
boolean isValueGotten() {
return null != getterDTV;
}
Object getValue(JDBCType jdbcType, InputStreamGetterArgs getterArgs, Calendar cal, TDSReader tdsReader,
SQLServerStatement statement) throws SQLServerException {
if (null == getterDTV) {
getterDTV = new DTV();
}
if (null != tdsReader) {
deriveTypeInfo(tdsReader);
}
// If the parameter is not encrypted or column encryption is turned off (either at connection or
// statement level), cryptoMeta would be null.
return getterDTV.getValue(jdbcType, outScale, getterArgs, cal, typeInfo, cryptoMeta, tdsReader, statement);
}
Object getSetterValue() {
return setterDTV.getSetterValue();
}
int getInt(TDSReader tdsReader, SQLServerStatement statement) throws SQLServerException {
Integer value = (Integer) getValue(JDBCType.INTEGER, null, null, tdsReader, statement);
return null != value ? value : 0;
}
/**
* DTV execute op to determine the parameter type definition.
*/
final class GetTypeDefinitionOp extends DTVExecuteOp {
private static final String NVARCHAR_MAX = "nvarchar(max)";
private static final String NVARCHAR_4K = "nvarchar(4000)";
private static final String NTEXT = "ntext";
private static final String VARCHAR_MAX = "varchar(max)";
private static final String VARCHAR_8K = "varchar(8000)";
private static final String TEXT = "text";
private static final String VARBINARY_MAX = "varbinary(max)";
private static final String VARBINARY_8K = "varbinary(8000)";
private static final String IMAGE = "image";
private final Parameter param;
private final SQLServerConnection con;
GetTypeDefinitionOp(Parameter param, SQLServerConnection con) {
this.param = param;
this.con = con;
}
private void setTypeDefinition(DTV dtv) {
switch (dtv.getJdbcType()) {
case TINYINT:
param.typeDefinition = SSType.TINYINT.toString();
break;
case SMALLINT:
param.typeDefinition = SSType.SMALLINT.toString();
break;
case INTEGER:
param.typeDefinition = SSType.INTEGER.toString();
break;
case BIGINT:
param.typeDefinition = SSType.BIGINT.toString();
break;
case REAL:
// sp_describe_parameter_encryption must be queried as real for AE
if (param.shouldHonorAEForParameter && (null != jdbcTypeSetByUser)
&& !(null == param.getCryptoMetadata() && param.renewDefinition)) {
/*
* This means AE is ON in the connection, and (1) this is either the first round to SQL Server
* to get encryption meta data, or (2) this is the second round of renewing meta data and
* parameter is encrypted In both of these cases we need to send specific type info, otherwise
* generic type info can be used as before.
*/
param.typeDefinition = SSType.REAL.toString();
} else {
// use FLOAT if column is not encrypted
param.typeDefinition = SSType.FLOAT.toString();
}
break;
case FLOAT:
case DOUBLE:
param.typeDefinition = SSType.FLOAT.toString();
break;
case DECIMAL:
case NUMERIC:
// First, bound the scale by the maximum allowed by SQL Server
if (scale > SQLServerConnection.MAX_DECIMAL_PRECISION) {
scale = SQLServerConnection.MAX_DECIMAL_PRECISION;
}
// Next, prepare with the largest of:
// - the value's scale (initial value, as limited above)
// - the specified input scale (if any)
// - the registered output scale
Integer inScale = dtv.getScale();
if (null != inScale && scale < inScale)
scale = inScale;
if (param.isOutput() && scale < param.getOutScale())
scale = param.getOutScale();
if (param.shouldHonorAEForParameter && (null != jdbcTypeSetByUser)
&& !(null == param.getCryptoMetadata() && param.renewDefinition)) {
/*
* This means AE is ON in the connection, and (1) this is either the first round to SQL Server
* to get encryption meta data, or (2) this is the second round of renewing meta data and
* parameter is encrypted In both of these cases we need to send specific type info, otherwise
* generic type info can be used as before.
*/
if (0 == valueLength) {
// for prepared statement and callable statement, There are only two cases where valueLength
// is 0:
// 1. when the parameter is output parameter
// 2. for input parameter, the value is null
// so, here, if the decimal parameter is encrypted and it is null and it is not outparameter
// then we set precision as the default precision instead of max precision
if (!isOutput()) {
param.typeDefinition = SSType.DECIMAL.toString() + "("
+ SQLServerConnection.DEFAULT_DECIMAL_PRECISION + "," + scale + ")";
}
} else {
if (SQLServerConnection.DEFAULT_DECIMAL_PRECISION >= valueLength) {
param.typeDefinition = SSType.DECIMAL.toString() + "("
+ SQLServerConnection.DEFAULT_DECIMAL_PRECISION + "," + scale + ")";
if (SQLServerConnection.DEFAULT_DECIMAL_PRECISION < (valueLength + scale)) {
param.typeDefinition = SSType.DECIMAL.toString() + "("
+ (SQLServerConnection.DEFAULT_DECIMAL_PRECISION + scale) + "," + scale
+ ")";
}
} else {
param.typeDefinition = SSType.DECIMAL.toString() + "("
+ SQLServerConnection.MAX_DECIMAL_PRECISION + "," + scale + ")";
}
}
if (isOutput()) {
param.typeDefinition = SSType.DECIMAL.toString() + "("
+ SQLServerConnection.MAX_DECIMAL_PRECISION + ", " + scale + ")";
}
if (userProvidesPrecision) {
param.typeDefinition = SSType.DECIMAL.toString() + "(" + valueLength + "," + scale + ")";
}
} else {
if (con.getCalcBigDecimalPrecision() && dtv.getJavaType() == JavaType.BIGDECIMAL
&& null != dtv.getSetterValue()) {
String[] plainValueArray = ((BigDecimal) dtv.getSetterValue()).abs().toPlainString()
.split("\\.");
// Precision is computed as opposed to using BigDecimal.precision(). This is because the
// BigDecimal method can lead to inaccurate results.
int calculatedPrecision;
// If the string array has two parts, e.g .the input was a decimal, check if the first
// part is a 0. For BigDecimals with leading zeroes, the leading zero does not count towards
// precision. For all other decimals, we include the integer portion as part of the precision
// When the string array has just one part, we only look at that part to compute precision.
if (plainValueArray.length == 2) {
if (plainValueArray[0].length() == 1 && (Integer.parseInt(plainValueArray[0]) == 0)) {
calculatedPrecision = plainValueArray[1].length();
} else {
calculatedPrecision = plainValueArray[0].length() + plainValueArray[1].length();
}
} else {
calculatedPrecision = plainValueArray[0].length();
}
param.typeDefinition = SSType.DECIMAL.toString() + "(" + calculatedPrecision + ","
+ (plainValueArray.length == 2 ? plainValueArray[1].length() : 0) + ")";
} else {
param.typeDefinition = SSType.DECIMAL.toString() + "("
+ SQLServerConnection.MAX_DECIMAL_PRECISION + "," + scale + ")";
}
}
break;
case MONEY:
param.typeDefinition = SSType.MONEY.toString();
break;
case SMALLMONEY:
param.typeDefinition = SSType.MONEY.toString();
if (param.shouldHonorAEForParameter
&& !(null == param.getCryptoMetadata() && param.renewDefinition)) {
param.typeDefinition = SSType.SMALLMONEY.toString();
}
break;
case BIT:
case BOOLEAN:
param.typeDefinition = SSType.BIT.toString();
break;
case LONGVARBINARY:
case BLOB:
param.typeDefinition = VARBINARY_MAX;
break;
case BINARY:
case VARBINARY:
// To avoid the server side cost of re-preparing, once a "long" type, always a "long" type...
if (VARBINARY_MAX.equals(param.typeDefinition) || IMAGE.equals(param.typeDefinition))
break;
if (param.shouldHonorAEForParameter && (null != jdbcTypeSetByUser)
&& !(null == param.getCryptoMetadata() && param.renewDefinition)) {
/*
* This means AE is ON in the connection, and (1) this is either the first round to SQL Server
* to get encryption meta data, or (2) this is the second round of renewing meta data and
* parameter is encrypted In both of these cases we need to send specific type info, otherwise
* generic type info can be used as before.
*/
if (0 == valueLength) {
// Workaround for the issue when inserting empty string and null into encrypted columns
param.typeDefinition = "varbinary(1)";
valueLength++;
} else {
param.typeDefinition = "varbinary(" + valueLength + ")";
}
if (JDBCType.LONGVARBINARY == jdbcTypeSetByUser) {
param.typeDefinition = VARBINARY_MAX;
}
} else
param.typeDefinition = VARBINARY_8K;
break;
case DATE:
// Bind DATE values to pre-Katmai servers as DATETIME (which has no DATE-only type).
param.typeDefinition = con.isKatmaiOrLater() ? SSType.DATE.toString() : SSType.DATETIME.toString();
break;
case TIME:
if (param.shouldHonorAEForParameter
&& !(null == param.getCryptoMetadata() && param.renewDefinition)) {
/*
* This means AE is ON in the connection, and (1) this is either the first round to SQL Server
* to get encryption meta data, or (2) this is the second round of renewing meta data and
* parameter is encrypted In both of these cases we need to send specific type info, otherwise
* generic type info can be used as before.
*/
if (userProvidesScale) {
param.typeDefinition = SSType.TIME.toString() + "(" + outScale + ")";
} else {
param.typeDefinition = SSType.TIME.toString() + "(" + valueLength + ")";
}
} else {
param.typeDefinition = con.getSendTimeAsDatetime() ? SSType.DATETIME.toString()
: SSType.TIME.toString();
}
break;
case TIMESTAMP:
// Bind TIMESTAMP values to pre-Katmai servers as DATETIME. Bind TIMESTAMP values to
// Katmai and later servers as DATETIME2 to take advantage of increased precision.
if (param.shouldHonorAEForParameter
&& !(null == param.getCryptoMetadata() && param.renewDefinition)) {
/*
* This means AE is ON in the connection, and (1) this is either the first round to SQL Server
* to get encryption meta data, or (2) this is the second round of renewing meta data and
* parameter is encrypted In both of these cases we need to send specific type info, otherwise
* generic type info can be used as before.
*/
if (userProvidesScale) {
param.typeDefinition = getDatetimeDataType(con, outScale);
} else {
param.typeDefinition = getDatetimeDataType(con, valueLength);
}
} else {
param.typeDefinition = getDatetimeDataType(con, null);
}
break;
case DATETIME:
// send as Datetime by default
param.typeDefinition = getDatetimeDataType(con, null);
if (param.shouldHonorAEForParameter
&& !(null == param.getCryptoMetadata() && param.renewDefinition)) {
param.typeDefinition = SSType.DATETIME.toString();
}
if (!param.shouldHonorAEForParameter) {
// if AE is off and it is output parameter of stored procedure, sent it as datetime2(3)
// otherwise it returns incorrect milliseconds.
if (param.isOutput()) {
param.typeDefinition = getDatetimeDataType(con, outScale);
}
} else {
// when AE is on, set it to Datetime by default,
// However, if column is not encrypted and it is output parameter of stored procedure,
// renew it to datetime2(3)
if (null == param.getCryptoMetadata() && param.renewDefinition) {
if (param.isOutput()) {
param.typeDefinition = getDatetimeDataType(con, outScale);
}
break;
}
}
break;
case SMALLDATETIME:
param.typeDefinition = getDatetimeDataType(con, null);
if (param.shouldHonorAEForParameter
&& !(null == param.getCryptoMetadata() && param.renewDefinition)) {
param.typeDefinition = SSType.SMALLDATETIME.toString();
}
break;
case TIME_WITH_TIMEZONE:
case TIMESTAMP_WITH_TIMEZONE:
case DATETIMEOFFSET:
if (param.shouldHonorAEForParameter
&& !(null == param.getCryptoMetadata() && param.renewDefinition)) {
/*
* This means AE is ON in the connection, and (1) this is either the first round to SQL Server
* to get encryption meta data, or (2) this is the second round of renewing meta data and
* parameter is encrypted In both of these cases we need to send specific type info, otherwise
* generic type info can be used as before.
*/
if (userProvidesScale) {
param.typeDefinition = SSType.DATETIMEOFFSET.toString() + "(" + outScale + ")";
} else {
param.typeDefinition = SSType.DATETIMEOFFSET.toString() + "(" + valueLength + ")";
}
} else {
param.typeDefinition = SSType.DATETIMEOFFSET.toString();
}
break;
case LONGVARCHAR:
case CLOB:
param.typeDefinition = VARCHAR_MAX;
break;
case CHAR:
case VARCHAR:
// To avoid the server side cost of re-preparing, once a "long" type, always a "long" type...
if (VARCHAR_MAX.equals(param.typeDefinition) || TEXT.equals(param.typeDefinition))
break;
// Adding for case useColumnEncryption=true & sendStringParametersAsUnicode=false
if (param.shouldHonorAEForParameter && (null != jdbcTypeSetByUser)
&& !(null == param.getCryptoMetadata() && param.renewDefinition)) {
/*
* This means AE is ON in the connection, and (1) this is either the first round to SQL Server
* to get encryption meta data, or (2) this is the second round of renewing meta data and
* parameter is encrypted In both of these cases we need to send specific type info, otherwise
* generic type info can be used as before.
*/
if (0 == valueLength) {
// Workaround for the issue when inserting empty string and null into encrypted columns
param.typeDefinition = SSType.VARCHAR.toString() + "(1)";
valueLength++;
} else {
param.typeDefinition = SSType.VARCHAR.toString() + "(" + valueLength + ")";
if (DataTypes.SHORT_VARTYPE_MAX_BYTES <= valueLength) {
param.typeDefinition = VARCHAR_MAX;
}
}
} else
param.typeDefinition = VARCHAR_8K;
break;
case LONGNVARCHAR:
if (param.shouldHonorAEForParameter
&& !(null == param.getCryptoMetadata() && param.renewDefinition)) {
/*
* This means AE is ON in the connection, and (1) this is either the first round to SQL Server
* to get encryption meta data, or (2) this is the second round of renewing meta data and
* parameter is encrypted In both of these cases we need to send specific type info, otherwise
* generic type info can be used as before.
*/
if ((null != jdbcTypeSetByUser)
&& ((jdbcTypeSetByUser == JDBCType.VARCHAR) || (jdbcTypeSetByUser == JDBCType.CHAR)
|| (jdbcTypeSetByUser == JDBCType.LONGVARCHAR))) {
if (0 == valueLength) {
// Workaround for the issue when inserting empty string and null into encrypted columns
param.typeDefinition = SSType.VARCHAR.toString() + "(1)";
valueLength++;
} else if (DataTypes.SHORT_VARTYPE_MAX_BYTES < valueLength) {
param.typeDefinition = VARCHAR_MAX;
} else {
param.typeDefinition = SSType.VARCHAR.toString() + "(" + valueLength + ")";
}
if (jdbcTypeSetByUser == JDBCType.LONGVARCHAR) {
param.typeDefinition = VARCHAR_MAX;
}
} else if ((null != jdbcTypeSetByUser) && (jdbcTypeSetByUser == JDBCType.NVARCHAR
|| jdbcTypeSetByUser == JDBCType.LONGNVARCHAR)) {
if (0 == valueLength) {
// Workaround for the issue when inserting empty string and null into encrypted columns
param.typeDefinition = SSType.NVARCHAR.toString() + "(1)";
valueLength++;
} else if (DataTypes.SHORT_VARTYPE_MAX_CHARS < valueLength) {
param.typeDefinition = NVARCHAR_MAX;
} else {
param.typeDefinition = SSType.NVARCHAR.toString() + "(" + valueLength + ")";
}
if (jdbcTypeSetByUser == JDBCType.LONGNVARCHAR) {
param.typeDefinition = NVARCHAR_MAX;
}
} else { // used if setNull() is called with java.sql.Types.NCHAR
if (0 == valueLength) {
// Workaround for the issue when inserting empty string and null into encrypted columns
param.typeDefinition = SSType.NVARCHAR.toString() + "(1)";
valueLength++;
} else {
param.typeDefinition = SSType.NVARCHAR.toString() + "(" + valueLength + ")";
if (DataTypes.SHORT_VARTYPE_MAX_BYTES <= valueLength) {
param.typeDefinition = NVARCHAR_MAX;
}
}
}
break;
} else
param.typeDefinition = NVARCHAR_MAX;
break;
case NCLOB:
// do not need to check if AE is enabled or not,
// because NCLOB does not work with it
param.typeDefinition = NVARCHAR_MAX;
break;
case NCHAR:
case NVARCHAR:
// To avoid the server side cost of re-preparing, once a "long" type, always a "long" type...
if (NVARCHAR_MAX.equals(param.typeDefinition) || NTEXT.equals(param.typeDefinition))
break;
if (param.shouldHonorAEForParameter
&& !(null == param.getCryptoMetadata() && param.renewDefinition)) {
/*
* This means AE is ON in the connection, and (1) this is either the first round to SQL Server
* to get encryption meta data, or (2) this is the second round of renewing meta data and
* parameter is encrypted In both of these cases we need to send specific type info, otherwise
* generic type info can be used as before.
*/
if ((null != jdbcTypeSetByUser)
&& ((jdbcTypeSetByUser == JDBCType.VARCHAR) || (jdbcTypeSetByUser == JDBCType.CHAR)
|| (JDBCType.LONGVARCHAR == jdbcTypeSetByUser))) {
if (0 == valueLength) {
// Workaround for the issue when inserting empty string and null into encrypted columns
param.typeDefinition = SSType.VARCHAR.toString() + "(1)";
valueLength++;
} else {
param.typeDefinition = SSType.VARCHAR.toString() + "(" + valueLength + ")";
if (DataTypes.SHORT_VARTYPE_MAX_BYTES < valueLength) {
param.typeDefinition = VARCHAR_MAX;
}
}
if (JDBCType.LONGVARCHAR == jdbcTypeSetByUser) {
param.typeDefinition = VARCHAR_MAX;
}
} else if ((null != jdbcTypeSetByUser)
&& ((jdbcTypeSetByUser == JDBCType.NVARCHAR) || (jdbcTypeSetByUser == JDBCType.NCHAR)
|| (JDBCType.LONGNVARCHAR == jdbcTypeSetByUser))) {
if (0 == valueLength) {
// Workaround for the issue when inserting empty string and null into encrypted columns
param.typeDefinition = SSType.NVARCHAR.toString() + "(1)";
valueLength++;
} else {
param.typeDefinition = SSType.NVARCHAR.toString() + "(" + valueLength + ")";
if (DataTypes.SHORT_VARTYPE_MAX_BYTES <= valueLength) {
param.typeDefinition = NVARCHAR_MAX;
}
}
if (JDBCType.LONGNVARCHAR == jdbcTypeSetByUser) {
param.typeDefinition = NVARCHAR_MAX;
}
} else { // used if setNull() is called with java.sql.Types.NCHAR
if (0 == valueLength) {
// Workaround for the issue when inserting empty string and null into encrypted columns
param.typeDefinition = SSType.NVARCHAR.toString() + "(1)";
valueLength++;
} else {
param.typeDefinition = SSType.NVARCHAR.toString() + "(" + valueLength + ")";
if (DataTypes.SHORT_VARTYPE_MAX_BYTES <= valueLength) {
param.typeDefinition = NVARCHAR_MAX;
}
}
}
break;
} else
param.typeDefinition = NVARCHAR_4K;
break;
case SQLXML:
param.typeDefinition = SSType.XML.toString();
break;
case TVP:
// definition should contain the TVP name and the keyword READONLY
String schema = param.schemaName;
if (null != schema) {
param.typeDefinition = "[" + schema + "].[" + param.name + "] READONLY";
} else {
param.typeDefinition = "[" + param.name + "] READONLY";
}
break;
case GUID:
param.typeDefinition = SSType.GUID.toString();
break;
case SQL_VARIANT:
param.typeDefinition = SSType.SQL_VARIANT.toString();
break;
case GEOMETRY:
param.typeDefinition = SSType.GEOMETRY.toString();
break;
case GEOGRAPHY:
param.typeDefinition = SSType.GEOGRAPHY.toString();
break;
default:
assert false : "Unexpected JDBC type " + dtv.getJdbcType();
break;
}
}
/**
* Generates the SQL datatype to use for Java date-based values. This
* setting can be controlled by setting the "datetimeParameterType" connection
* string. It defaults to "datetime2" for SQL Server 2008+ and always
* uses "datetime" for older SQL Server installations.
*/
String getDatetimeDataType(SQLServerConnection con, Integer scale) {
String datatype;
if (con.isKatmaiOrLater()) {
String paramType = con.getDatetimeParameterType();
if (paramType.equalsIgnoreCase(DatetimeType.DATETIME2.toString())) {
datatype = SSType.DATETIME2.toString();