forked from microsoft/mssql-jdbc
/
SQLServerPreparedStatement.java
3201 lines (2772 loc) · 150 KB
/
SQLServerPreparedStatement.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 com.microsoft.sqlserver.jdbc.SQLServerConnection.getCachedParsedSQL;
import static com.microsoft.sqlserver.jdbc.SQLServerConnection.parseAndCacheSQL;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.sql.BatchUpdateException;
import java.sql.NClob;
import java.sql.ParameterMetaData;
import java.sql.ResultSet;
import java.sql.RowId;
import java.sql.SQLException;
import java.sql.SQLTimeoutException;
import java.sql.SQLType;
import java.sql.SQLXML;
import java.sql.Statement;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import java.util.logging.Level;
import com.microsoft.sqlserver.jdbc.SQLServerConnection.CityHash128Key;
import com.microsoft.sqlserver.jdbc.SQLServerConnection.PreparedStatementHandle;
/**
* Provides an implementation of java.sql.PreparedStatement interface that assists in preparing Statements for SQL
* Server.
* <p>
* SQLServerPreparedStatement prepares a statement using SQL Server's sp_prepexec and re-uses the returned statement
* handle for each subsequent execution of the statement (typically using different parameters provided by the user)
* <p>
* SQLServerPreparedStatement supports batching whereby a set of prepared statements are executed in a single database
* round trip to improve runtime performance.
* <p>
* The API javadoc for JDBC API methods that this class implements are not repeated here. Please see Sun's JDBC API
* interfaces javadoc for those details.
*/
public class SQLServerPreparedStatement extends SQLServerStatement implements ISQLServerPreparedStatement {
/**
* Always update serialVersionUID when prompted.
*/
private static final long serialVersionUID = -6292257029445685221L;
/** delimiter for multiple statements in a single batch */
@SuppressWarnings("unused")
private static final int BATCH_STATEMENT_DELIMITER_TDS_71 = 0x80;
private static final int BATCH_STATEMENT_DELIMITER_TDS_72 = 0xFF;
/** batch statement delimiter */
final int nBatchStatementDelimiter = BATCH_STATEMENT_DELIMITER_TDS_72;
/** The prepared type definitions */
private String preparedTypeDefinitions;
/** Processed SQL statement text, may not be same as what user initially passed. */
final String userSQL;
/** Parameter positions in processed SQL statement text. */
final int[] userSQLParamPositions;
/** SQL statement with expanded parameter tokens */
private String preparedSQL;
/** True if this execute has been called for this statement at least once */
private boolean isExecutedAtLeastOnce = false;
/** Reference to cache item for statement handle pooling. Only used to decrement ref count on statement close. */
private PreparedStatementHandle cachedPreparedStatementHandle;
/** Hash of user supplied SQL statement used for various cache lookups */
private CityHash128Key sqlTextCacheKey;
/**
* Array with parameter names generated in buildParamTypeDefinitions For mapping encryption information to
* parameters, as the second result set returned by sp_describe_parameter_encryption doesn't depend on order of
* input parameter
**/
private ArrayList<String> parameterNames;
/** Set to true if the statement is a stored procedure call that expects a return value */
final boolean bReturnValueSyntax;
/** user FMTOnly flag */
private boolean useFmtOnly = this.connection.getUseFmtOnly();
/**
* The number of OUT parameters to skip in the response to get to the first app-declared OUT parameter.
*
* When executing prepared and callable statements and/or statements that produce cursored results, the first OUT
* parameters returned by the server contain the internal values like the prepared statement handle and the cursor
* ID and row count. This value indicates how many of those internal OUT parameters were in the response.
*/
int outParamIndexAdjustment;
/** Set of parameter values in the current batch */
ArrayList<Parameter[]> batchParamValues;
/** The prepared statement handle returned by the server */
private int prepStmtHandle = 0;
/** Statement used for getMetadata(). Declared as a field to facilitate closing the statement. */
private SQLServerStatement internalStmt = null;
private void setPreparedStatementHandle(int handle) {
this.prepStmtHandle = handle;
}
/**
* boolean value for deciding if the driver should use bulk copy API for batch inserts
*/
private boolean useBulkCopyForBatchInsert;
/**
* Returns the prepared statement's useBulkCopyForBatchInsert value.
*
* @return Per the description.
* @throws SQLServerException
* when an error occurs
*/
@SuppressWarnings("unused")
private boolean getUseBulkCopyForBatchInsert() throws SQLServerException {
checkClosed();
return useBulkCopyForBatchInsert;
}
/**
* Sets the prepared statement's useBulkCopyForBatchInsert value.
*
* @param useBulkCopyForBatchInsert
* the boolean value
* @throws SQLServerException
* when an error occurs
*/
@SuppressWarnings("unused")
private void setUseBulkCopyForBatchInsert(boolean useBulkCopyForBatchInsert) throws SQLServerException {
checkClosed();
this.useBulkCopyForBatchInsert = useBulkCopyForBatchInsert;
}
@Override
public int getPreparedStatementHandle() throws SQLServerException {
checkClosed();
return prepStmtHandle;
}
/**
* Returns true if this statement has a server handle.
*
* @return Per the description.
*/
private boolean hasPreparedStatementHandle() {
return 0 < prepStmtHandle;
}
/**
* Resets the server handle for this prepared statement to no handle.
*/
private boolean resetPrepStmtHandle(boolean discardCurrentCacheItem) {
boolean statementPoolingUsed = null != cachedPreparedStatementHandle;
// Return to pool and decrement reference count
if (statementPoolingUsed) {
// Make sure the cached handle does not get re-used more.
if (discardCurrentCacheItem)
cachedPreparedStatementHandle.setIsExplicitlyDiscarded();
}
prepStmtHandle = 0;
return statementPoolingUsed;
}
/** Flag set to true when statement execution is expected to return the prepared statement handle */
private boolean expectPrepStmtHandle = false;
/**
* Flag set to true when all encryption metadata of inOutParam is retrieved
*/
private boolean encryptionMetadataIsRetrieved = false;
/**
* local user SQL
*/
private String localUserSQL;
/**
* crypto meta batch
*/
private Vector<CryptoMetadata> cryptoMetaBatch = new Vector<>();
// Internal function used in tracing
String getClassNameInternal() {
return "SQLServerPreparedStatement";
}
/**
* Constructs a SQLServerPreparedStatement.
*
* @param conn
* the connection
* @param sql
* the user's sql
* @param nRSType
* the result set type
* @param nRSConcur
* the result set concurrency
* @param stmtColEncSetting
* the statement column encryption setting
* @throws SQLServerException
* when an error occurs
*/
SQLServerPreparedStatement(SQLServerConnection conn, String sql, int nRSType, int nRSConcur,
SQLServerStatementColumnEncryptionSetting stmtColEncSetting) throws SQLServerException {
super(conn, nRSType, nRSConcur, stmtColEncSetting);
if (null == sql) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_NullValue"));
Object[] msgArgs1 = {"Statement SQL"};
throw new SQLServerException(form.format(msgArgs1), null);
}
stmtPoolable = true;
// Create a cache key for this statement.
sqlTextCacheKey = new CityHash128Key(sql);
// Parse or fetch SQL metadata from cache.
ParsedSQLCacheItem parsedSQL = getCachedParsedSQL(sqlTextCacheKey);
if (null != parsedSQL) {
if (null != connection && connection.isStatementPoolingEnabled()) {
isExecutedAtLeastOnce = true;
}
} else {
parsedSQL = parseAndCacheSQL(sqlTextCacheKey, sql);
}
// Retrieve meta data from cache item.
procedureName = parsedSQL.procedureName;
bReturnValueSyntax = parsedSQL.bReturnValueSyntax;
userSQL = parsedSQL.processedSQL;
userSQLParamPositions = parsedSQL.parameterPositions;
initParams(userSQLParamPositions.length);
useBulkCopyForBatchInsert = conn.getUseBulkCopyForBatchInsert();
}
/**
* Closes the prepared statement's prepared handle.
*/
private void closePreparedHandle() {
if (!hasPreparedStatementHandle())
return;
// If the connection is already closed, don't bother trying to close
// the prepared handle. We won't be able to, and it's already closed
// on the server anyway.
if (connection.isSessionUnAvailable()) {
if (loggerExternal.isLoggable(java.util.logging.Level.FINER))
loggerExternal.finer(
this + ": Not closing PreparedHandle:" + prepStmtHandle + "; connection is already closed.");
} else {
isExecutedAtLeastOnce = false;
final int handleToClose = prepStmtHandle;
// Handle unprepare actions through statement pooling.
if (resetPrepStmtHandle(false)) {
connection.returnCachedPreparedStatementHandle(cachedPreparedStatementHandle);
}
// If no reference to a statement pool cache item is found handle unprepare actions through batching @
// connection level.
else if (connection.isPreparedStatementUnprepareBatchingEnabled()) {
connection.enqueueUnprepareStatementHandle(
connection.new PreparedStatementHandle(null, handleToClose, executedSqlDirectly, true));
} else {
// Non batched behavior (same as pre batch clean-up implementation)
if (loggerExternal.isLoggable(java.util.logging.Level.FINER))
loggerExternal.finer(this + ": Closing PreparedHandle:" + handleToClose);
final class PreparedHandleClose extends UninterruptableTDSCommand {
/**
* Always update serialVersionUID when prompted.
*/
private static final long serialVersionUID = -8944096664249990764L;
PreparedHandleClose() {
super("closePreparedHandle");
}
final boolean doExecute() throws SQLServerException {
TDSWriter tdsWriter = startRequest(TDS.PKT_RPC);
tdsWriter.writeShort((short) 0xFFFF); // procedure name length -> use ProcIDs
tdsWriter.writeShort(
executedSqlDirectly ? TDS.PROCID_SP_UNPREPARE : TDS.PROCID_SP_CURSORUNPREPARE);
tdsWriter.writeByte((byte) 0); // RPC procedure option 1
tdsWriter.writeByte((byte) 0); // RPC procedure option 2
tdsWriter.sendEnclavePackage(null, null);
tdsWriter.writeRPCInt(null, handleToClose, false);
TDSParser.parse(startResponse(), getLogContext());
return true;
}
}
// Try to close the server cursor. Any failure is caught, logged, and ignored.
try {
executeCommand(new PreparedHandleClose());
} catch (SQLServerException e) {
if (loggerExternal.isLoggable(java.util.logging.Level.FINER))
loggerExternal.log(Level.FINER,
this + ": Error (ignored) closing PreparedHandle:" + handleToClose, e);
}
if (loggerExternal.isLoggable(java.util.logging.Level.FINER))
loggerExternal.finer(this + ": Closed PreparedHandle:" + handleToClose);
}
// Always run any outstanding discard actions as statement pooling always uses batched sp_unprepare.
connection.unprepareUnreferencedPreparedStatementHandles(false);
}
}
/**
* Closes this prepared statement.
*
* Note that the public Statement.close() method performs all of the cleanup work through this internal method which
* cannot throw any exceptions. This is done deliberately to ensure that ALL of the object's client-side and
* server-side state is cleaned up as best as possible, even under conditions which would normally result in
* exceptions being thrown.
*/
final void closeInternal() {
super.closeInternal();
// If we have a prepared statement handle, close it.
closePreparedHandle();
// Close the statement that was used to generate empty statement from getMetadata().
try {
if (null != internalStmt)
internalStmt.close();
} catch (SQLServerException e) {
if (loggerExternal.isLoggable(java.util.logging.Level.FINER))
loggerExternal
.finer("Ignored error closing internal statement: " + e.getErrorCode() + " " + e.getMessage());
} finally {
internalStmt = null;
}
// Clean up client-side state
batchParamValues = null;
}
/**
* Initializes the statement parameters.
*
* @param nParams
* Number of parameters to initialize.
*/
final void initParams(int nParams) {
inOutParam = new Parameter[nParams];
for (int i = 0; i < nParams; i++) {
inOutParam[i] = new Parameter(Util.shouldHonorAEForParameters(stmtColumnEncriptionSetting, connection));
}
}
@Override
public final void clearParameters() throws SQLServerException {
loggerExternal.entering(getClassNameLogging(), "clearParameters");
checkClosed();
encryptionMetadataIsRetrieved = false;
cryptoMetaBatch.clear();
int i;
if (inOutParam == null)
return;
for (i = 0; i < inOutParam.length; i++) {
inOutParam[i].clearInputValue();
}
loggerExternal.exiting(getClassNameLogging(), "clearParameters");
}
/**
* Determines whether the statement needs to be reprepared based on a change in any of the type definitions of any
* of the parameters due to changes in scale, length, etc., and, if so, sets the new type definition string.
*/
private boolean buildPreparedStrings(Parameter[] params, boolean renewDefinition) throws SQLServerException {
String newTypeDefinitions = buildParamTypeDefinitions(params, renewDefinition);
if (null != preparedTypeDefinitions && newTypeDefinitions.equalsIgnoreCase(preparedTypeDefinitions))
return false;
preparedTypeDefinitions = newTypeDefinitions;
/* Replace the parameter marker '?' with the param numbers @p1, @p2 etc */
preparedSQL = connection.replaceParameterMarkers(userSQL, userSQLParamPositions, params, bReturnValueSyntax);
if (bRequestedGeneratedKeys)
preparedSQL = preparedSQL + identityQuery;
return true;
}
/**
* Builds the parameter type definitons for a JDBC prepared statement that will be used to prepare the statement.
*
* @param params
* the statement parameters
* @param renewDefinition
* True if renewing parameter definition, False otherwise
* @throws SQLServerException
* when an error occurs.
* @return the required data type definitions.
*/
private String buildParamTypeDefinitions(Parameter[] params, boolean renewDefinition) throws SQLServerException {
StringBuilder sb = new StringBuilder();
int nCols = params.length;
char cParamName[] = new char[10];
parameterNames = new ArrayList<>();
for (int i = 0; i < nCols; i++) {
if (i > 0)
sb.append(',');
int l = SQLServerConnection.makeParamName(i, cParamName, 0);
for (int j = 0; j < l; j++)
sb.append(cParamName[j]);
sb.append(' ');
parameterNames.add(i, (new String(cParamName)).trim());
params[i].renewDefinition = renewDefinition;
String typeDefinition = params[i].getTypeDefinition(connection, resultsReader());
if (null == typeDefinition) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_valueNotSetForParameter"));
Object[] msgArgs = {i + 1};
SQLServerException.makeFromDriverError(connection, this, form.format(msgArgs), null, false);
}
sb.append(typeDefinition);
if (params[i].isOutput())
sb.append(" OUTPUT");
}
return sb.toString();
}
@Override
public java.sql.ResultSet executeQuery() throws SQLServerException, SQLTimeoutException {
loggerExternal.entering(getClassNameLogging(), "executeQuery");
if (loggerExternal.isLoggable(Level.FINER) && Util.isActivityTraceOn()) {
loggerExternal.finer(toString() + " ActivityId: " + ActivityCorrelator.getNext().toString());
}
checkClosed();
executeStatement(new PrepStmtExecCmd(this, EXECUTE_QUERY));
loggerExternal.exiting(getClassNameLogging(), "executeQuery");
return resultSet;
}
/**
* Executes a query without cursoring for metadata.
*
* @throws SQLServerException
* @return ResultSet
* @throws SQLTimeoutException
*/
final java.sql.ResultSet executeQueryInternal() throws SQLServerException, SQLTimeoutException {
checkClosed();
executeStatement(new PrepStmtExecCmd(this, EXECUTE_QUERY_INTERNAL));
return resultSet;
}
@Override
public int executeUpdate() throws SQLServerException, SQLTimeoutException {
loggerExternal.entering(getClassNameLogging(), "executeUpdate");
if (loggerExternal.isLoggable(Level.FINER) && Util.isActivityTraceOn()) {
loggerExternal.finer(toString() + " ActivityId: " + ActivityCorrelator.getNext().toString());
}
checkClosed();
executeStatement(new PrepStmtExecCmd(this, EXECUTE_UPDATE));
// this shouldn't happen, caller probably meant to call executeLargeUpdate
if (updateCount < Integer.MIN_VALUE || updateCount > Integer.MAX_VALUE)
SQLServerException.makeFromDriverError(connection, this,
SQLServerException.getErrString("R_updateCountOutofRange"), null, true);
loggerExternal.exiting(getClassNameLogging(), "executeUpdate", updateCount);
return (int) updateCount;
}
@Override
public long executeLargeUpdate() throws SQLServerException, SQLTimeoutException {
loggerExternal.entering(getClassNameLogging(), "executeLargeUpdate");
if (loggerExternal.isLoggable(Level.FINER) && Util.isActivityTraceOn()) {
loggerExternal.finer(toString() + " ActivityId: " + ActivityCorrelator.getNext().toString());
}
checkClosed();
executeStatement(new PrepStmtExecCmd(this, EXECUTE_UPDATE));
loggerExternal.exiting(getClassNameLogging(), "executeLargeUpdate", updateCount);
return updateCount;
}
@Override
public boolean execute() throws SQLServerException, SQLTimeoutException {
loggerExternal.entering(getClassNameLogging(), "execute");
if (loggerExternal.isLoggable(Level.FINER) && Util.isActivityTraceOn()) {
loggerExternal.finer(toString() + " ActivityId: " + ActivityCorrelator.getNext().toString());
}
checkClosed();
executeStatement(new PrepStmtExecCmd(this, EXECUTE));
loggerExternal.exiting(getClassNameLogging(), "execute", null != resultSet);
return null != resultSet;
}
/**
* Prepare statement exec command
*/
private final class PrepStmtExecCmd extends TDSCommand {
/**
* Always update serialVersionUID when prompted.
*/
private static final long serialVersionUID = 4098801171124750861L;
private final SQLServerPreparedStatement stmt;
PrepStmtExecCmd(SQLServerPreparedStatement stmt, int executeMethod) {
super(stmt.toString() + " executeXXX", queryTimeout, cancelQueryTimeoutSeconds);
this.stmt = stmt;
stmt.executeMethod = executeMethod;
}
final boolean doExecute() throws SQLServerException {
stmt.doExecutePreparedStatement(this);
return false;
}
final void processResponse(TDSReader tdsReader) throws SQLServerException {
ensureExecuteResultsReader(tdsReader);
processExecuteResults();
}
}
final void doExecutePreparedStatement(PrepStmtExecCmd command) throws SQLServerException {
resetForReexecute();
// If this request might be a query (as opposed to an update) then make
// sure we set the max number of rows and max field size for any ResultSet
// that may be returned.
//
// If the app uses Statement.execute to execute an UPDATE or DELETE statement
// and has called Statement.setMaxRows to limit the number of rows from an
// earlier query, then the number of rows updated/deleted will be limited as
// well.
//
// Note: similar logic in SQLServerStatement.doExecuteStatement
setMaxRowsAndMaxFieldSize();
if (loggerExternal.isLoggable(Level.FINER) && Util.isActivityTraceOn()) {
loggerExternal.finer(toString() + " ActivityId: " + ActivityCorrelator.getNext().toString());
}
boolean hasExistingTypeDefinitions = preparedTypeDefinitions != null;
boolean hasNewTypeDefinitions = true;
if (!encryptionMetadataIsRetrieved) {
hasNewTypeDefinitions = buildPreparedStrings(inOutParam, false);
}
if (connection.isAEv2() && !isInternalEncryptionQuery) {
this.enclaveCEKs = connection.initEnclaveParameters(preparedSQL, preparedTypeDefinitions, inOutParam,
parameterNames);
encryptionMetadataIsRetrieved = true;
setMaxRowsAndMaxFieldSize();
hasNewTypeDefinitions = buildPreparedStrings(inOutParam, true);
}
if ((Util.shouldHonorAEForParameters(stmtColumnEncriptionSetting, connection)) && (0 < inOutParam.length)
&& !isInternalEncryptionQuery) {
// retrieve parameter encryption metadata if they are not retrieved yet
if (!encryptionMetadataIsRetrieved) {
getParameterEncryptionMetadata(inOutParam);
encryptionMetadataIsRetrieved = true;
// maxRows is set to 0 when retrieving encryption metadata,
// need to set it back
setMaxRowsAndMaxFieldSize();
}
// fix an issue when inserting unicode into non-encrypted nchar column using setString() and AE is on on
// Connection
hasNewTypeDefinitions = buildPreparedStrings(inOutParam, true);
}
boolean needsPrepare = true;
// Retry execution if existing handle could not be re-used.
for (int attempt = 1; attempt <= 2; ++attempt) {
try {
// Re-use handle if available, requires parameter definitions which are not available until here.
if (reuseCachedHandle(hasNewTypeDefinitions, 1 < attempt)) {
hasNewTypeDefinitions = false;
}
// Start the request and detach the response reader so that we can
// continue using it after we return.
TDSWriter tdsWriter = command.startRequest(TDS.PKT_RPC);
needsPrepare = doPrepExec(tdsWriter, inOutParam, hasNewTypeDefinitions, hasExistingTypeDefinitions);
ensureExecuteResultsReader(command.startResponse(getIsResponseBufferingAdaptive()));
startResults();
getNextResult(true);
} catch (SQLException e) {
if (retryBasedOnFailedReuseOfCachedHandle(e, attempt, needsPrepare, false))
continue;
else
throw e;
}
break;
}
if (EXECUTE_QUERY == executeMethod && null == resultSet) {
SQLServerException.makeFromDriverError(connection, this, SQLServerException.getErrString("R_noResultset"),
null, true);
} else if (EXECUTE_UPDATE == executeMethod && null != resultSet) {
SQLServerException.makeFromDriverError(connection, this,
SQLServerException.getErrString("R_resultsetGeneratedForUpdate"), null, false);
}
}
/**
* Returns if the execution should be retried because the re-used cached handle could not be re-used due to server
* side state changes.
*/
private boolean retryBasedOnFailedReuseOfCachedHandle(SQLException e, int attempt, boolean needsPrepare,
boolean isBatch) {
// Only retry based on these error codes and if statementPooling is enabled:
// 586: The prepared statement handle %d is not valid in this context. Please verify that current database, user
// default schema, and
// ANSI_NULLS and QUOTED_IDENTIFIER set options are not changed since the handle is prepared.
// 8179: Could not find prepared statement with handle %d.
if (needsPrepare && !isBatch)
return false;
return 1 == attempt && (586 == e.getErrorCode() || 8179 == e.getErrorCode())
&& connection.isStatementPoolingEnabled();
}
/**
* Consumes the OUT parameter for the statement object itself.
*
* When a prepared statement handle is expected as the first OUT parameter from PreparedStatement or
* CallableStatement execution, then it gets consumed here.
*/
boolean consumeExecOutParam(TDSReader tdsReader) throws SQLServerException {
final class PrepStmtExecOutParamHandler extends StmtExecOutParamHandler {
boolean onRetValue(TDSReader tdsReader) throws SQLServerException {
// If no prepared statement handle is expected at this time
// then don't consume this OUT parameter as it does not contain
// a prepared statement handle.
if (!expectPrepStmtHandle)
return super.onRetValue(tdsReader);
// If a prepared statement handle is expected then consume it
// and continue processing.
expectPrepStmtHandle = false;
Parameter param = new Parameter(
Util.shouldHonorAEForParameters(stmtColumnEncriptionSetting, connection));
param.skipRetValStatus(tdsReader);
setPreparedStatementHandle(param.getInt(tdsReader));
// Cache the reference to the newly created handle, NOT for cursorable handles.
if (null == cachedPreparedStatementHandle && !isCursorable(executeMethod)) {
cachedPreparedStatementHandle = connection.registerCachedPreparedStatementHandle(
new CityHash128Key(preparedSQL, preparedTypeDefinitions), prepStmtHandle,
executedSqlDirectly);
}
param.skipValue(tdsReader, true);
if (getStatementLogger().isLoggable(java.util.logging.Level.FINER))
getStatementLogger().finer(toString() + ": Setting PreparedHandle:" + prepStmtHandle);
return true;
}
}
if (expectPrepStmtHandle || expectCursorOutParams) {
TDSParser.parse(tdsReader, new PrepStmtExecOutParamHandler());
return true;
}
return false;
}
/**
* Sends the statement parameters by RPC.
*/
void sendParamsByRPC(TDSWriter tdsWriter, Parameter[] params) throws SQLServerException {
char cParamName[];
for (int index = 0; index < params.length; index++) {
if (JDBCType.TVP == params[index].getJdbcType()) {
cParamName = new char[10];
int paramNameLen = SQLServerConnection.makeParamName(index, cParamName, 0);
tdsWriter.writeByte((byte) paramNameLen);
tdsWriter.writeString(new String(cParamName, 0, paramNameLen));
}
params[index].sendByRPC(tdsWriter, connection);
}
}
private void buildServerCursorPrepExecParams(TDSWriter tdsWriter) throws SQLServerException {
if (getStatementLogger().isLoggable(java.util.logging.Level.FINE))
getStatementLogger().fine(toString() + ": calling sp_cursorprepexec: PreparedHandle:"
+ getPreparedStatementHandle() + ", SQL:" + preparedSQL);
expectPrepStmtHandle = true;
executedSqlDirectly = false;
expectCursorOutParams = true;
outParamIndexAdjustment = 7;
tdsWriter.writeShort((short) 0xFFFF); // procedure name length -> use ProcIDs
tdsWriter.writeShort(TDS.PROCID_SP_CURSORPREPEXEC);
tdsWriter.writeByte((byte) 0); // RPC procedure option 1
tdsWriter.writeByte((byte) 0); // RPC procedure option 2
tdsWriter.sendEnclavePackage(preparedSQL, enclaveCEKs);
// <prepared handle>
// IN (reprepare): Old handle to unprepare before repreparing
// OUT: The newly prepared handle
tdsWriter.writeRPCInt(null, getPreparedStatementHandle(), true);
resetPrepStmtHandle(false);
// <cursor> OUT
tdsWriter.writeRPCInt(null, 0, true); // cursor ID (OUTPUT)
// <formal parameter defn> IN
tdsWriter.writeRPCStringUnicode((preparedTypeDefinitions.length() > 0) ? preparedTypeDefinitions : null);
// <stmt> IN
tdsWriter.writeRPCStringUnicode(preparedSQL);
// <scrollopt> IN
// Note: we must strip out SCROLLOPT_PARAMETERIZED_STMT if we don't
// actually have any parameters.
tdsWriter.writeRPCInt(null, getResultSetScrollOpt()
& ~((0 == preparedTypeDefinitions.length()) ? TDS.SCROLLOPT_PARAMETERIZED_STMT : 0), false);
// <ccopt> IN
tdsWriter.writeRPCInt(null, getResultSetCCOpt(), false);
// <rowcount> OUT
tdsWriter.writeRPCInt(null, 0, true);
}
private void buildPrepExecParams(TDSWriter tdsWriter) throws SQLServerException {
if (getStatementLogger().isLoggable(java.util.logging.Level.FINE))
getStatementLogger().fine(toString() + ": calling sp_prepexec: PreparedHandle:"
+ getPreparedStatementHandle() + ", SQL:" + preparedSQL);
expectPrepStmtHandle = true;
executedSqlDirectly = true;
expectCursorOutParams = false;
outParamIndexAdjustment = 3;
tdsWriter.writeShort((short) 0xFFFF); // procedure name length -> use ProcIDs
tdsWriter.writeShort(TDS.PROCID_SP_PREPEXEC);
tdsWriter.writeByte((byte) 0); // RPC procedure option 1
tdsWriter.writeByte((byte) 0); // RPC procedure option 2
tdsWriter.sendEnclavePackage(preparedSQL, enclaveCEKs);
// <prepared handle>
// IN (reprepare): Old handle to unprepare before repreparing
// OUT: The newly prepared handle
tdsWriter.writeRPCInt(null, getPreparedStatementHandle(), true);
resetPrepStmtHandle(false);
// <formal parameter defn> IN
tdsWriter.writeRPCStringUnicode((preparedTypeDefinitions.length() > 0) ? preparedTypeDefinitions : null);
// <stmt> IN
tdsWriter.writeRPCStringUnicode(preparedSQL);
}
private void buildExecSQLParams(TDSWriter tdsWriter) throws SQLServerException {
if (getStatementLogger().isLoggable(java.util.logging.Level.FINE))
getStatementLogger().fine(toString() + ": calling sp_executesql: SQL:" + preparedSQL);
expectPrepStmtHandle = false;
executedSqlDirectly = true;
expectCursorOutParams = false;
outParamIndexAdjustment = 2;
tdsWriter.writeShort((short) 0xFFFF); // procedure name length -> use ProcIDs
tdsWriter.writeShort(TDS.PROCID_SP_EXECUTESQL);
tdsWriter.writeByte((byte) 0); // RPC procedure option 1
tdsWriter.writeByte((byte) 0); // RPC procedure option 2
tdsWriter.sendEnclavePackage(preparedSQL, enclaveCEKs);
// No handle used.
resetPrepStmtHandle(false);
// <stmt> IN
tdsWriter.writeRPCStringUnicode(preparedSQL);
// <formal parameter defn> IN
if (preparedTypeDefinitions.length() > 0)
tdsWriter.writeRPCStringUnicode(preparedTypeDefinitions);
}
private void buildServerCursorExecParams(TDSWriter tdsWriter) throws SQLServerException {
if (getStatementLogger().isLoggable(java.util.logging.Level.FINE))
getStatementLogger().fine(toString() + ": calling sp_cursorexecute: PreparedHandle:"
+ getPreparedStatementHandle() + ", SQL:" + preparedSQL);
expectPrepStmtHandle = false;
executedSqlDirectly = false;
expectCursorOutParams = true;
outParamIndexAdjustment = 5;
tdsWriter.writeShort((short) 0xFFFF); // procedure name length -> use ProcIDs
tdsWriter.writeShort(TDS.PROCID_SP_CURSOREXECUTE);
tdsWriter.writeByte((byte) 0); // RPC procedure option 1
tdsWriter.writeByte((byte) 0); // RPC procedure option 2 */
tdsWriter.sendEnclavePackage(preparedSQL, enclaveCEKs);
// <handle> IN
assert hasPreparedStatementHandle();
tdsWriter.writeRPCInt(null, getPreparedStatementHandle(), false);
// <cursor> OUT
tdsWriter.writeRPCInt(null, 0, true);
// <scrollopt> IN
tdsWriter.writeRPCInt(null, getResultSetScrollOpt() & ~TDS.SCROLLOPT_PARAMETERIZED_STMT, false);
// <ccopt> IN
tdsWriter.writeRPCInt(null, getResultSetCCOpt(), false);
// <rowcount> OUT
tdsWriter.writeRPCInt(null, 0, true);
}
private void buildExecParams(TDSWriter tdsWriter) throws SQLServerException {
if (getStatementLogger().isLoggable(java.util.logging.Level.FINE))
getStatementLogger().fine(toString() + ": calling sp_execute: PreparedHandle:"
+ getPreparedStatementHandle() + ", SQL:" + preparedSQL);
expectPrepStmtHandle = false;
executedSqlDirectly = true;
expectCursorOutParams = false;
outParamIndexAdjustment = 1;
tdsWriter.writeShort((short) 0xFFFF); // procedure name length -> use ProcIDs
tdsWriter.writeShort(TDS.PROCID_SP_EXECUTE);
tdsWriter.writeByte((byte) 0); // RPC procedure option 1
tdsWriter.writeByte((byte) 0); // RPC procedure option 2 */
tdsWriter.sendEnclavePackage(preparedSQL, enclaveCEKs);
// <handle> IN
assert hasPreparedStatementHandle();
tdsWriter.writeRPCInt(null, getPreparedStatementHandle(), false);
}
private void getParameterEncryptionMetadata(Parameter[] params) throws SQLServerException {
/*
* The parameter list is created from the data types provided by the user for the parameters. the data types do
* not need to be the same as in the table definition. Also, when string is sent to an int field, the parameter
* is defined as nvarchar(<size of string>). Same for varchar datatypes, exact length is used.
*/
assert connection != null : "Connection should not be null";
try (Statement stmt = connection.prepareCall("exec sp_describe_parameter_encryption ?,?")) {
if (getStatementLogger().isLoggable(java.util.logging.Level.FINE)) {
getStatementLogger().fine(
"Calling stored procedure sp_describe_parameter_encryption to get parameter encryption information.");
}
((SQLServerCallableStatement) stmt).isInternalEncryptionQuery = true;
((SQLServerCallableStatement) stmt).setNString(1, preparedSQL);
((SQLServerCallableStatement) stmt).setNString(2, preparedTypeDefinitions);
try (ResultSet rs = ((SQLServerCallableStatement) stmt).executeQueryInternal()) {
if (null == rs) {
// No results. Meaning no parameter.
// Should never happen.
return;
}
Map<Integer, CekTableEntry> cekList = new HashMap<>();
CekTableEntry cekEntry = null;
while (rs.next()) {
int currentOrdinal = rs.getInt(DescribeParameterEncryptionResultSet1.KeyOrdinal.value());
if (!cekList.containsKey(currentOrdinal)) {
cekEntry = new CekTableEntry(currentOrdinal);
cekList.put(cekEntry.ordinal, cekEntry);
} else {
cekEntry = cekList.get(currentOrdinal);
}
cekEntry.add(rs.getBytes(DescribeParameterEncryptionResultSet1.EncryptedKey.value()),
rs.getInt(DescribeParameterEncryptionResultSet1.DbId.value()),
rs.getInt(DescribeParameterEncryptionResultSet1.KeyId.value()),
rs.getInt(DescribeParameterEncryptionResultSet1.KeyVersion.value()),
rs.getBytes(DescribeParameterEncryptionResultSet1.KeyMdVersion.value()),
rs.getString(DescribeParameterEncryptionResultSet1.KeyPath.value()),
rs.getString(DescribeParameterEncryptionResultSet1.ProviderName.value()),
rs.getString(DescribeParameterEncryptionResultSet1.KeyEncryptionAlgorithm.value()));
}
if (getStatementLogger().isLoggable(java.util.logging.Level.FINE)) {
getStatementLogger().fine("Matadata of CEKs is retrieved.");
}
// Process the second resultset.
if (!stmt.getMoreResults()) {
throw new SQLServerException(this,
SQLServerException.getErrString("R_UnexpectedDescribeParamFormat"), null, 0, false);
}
// Parameter count in the result set.
int paramCount = 0;
try (ResultSet secondRs = stmt.getResultSet()) {
while (secondRs.next()) {
paramCount++;
String paramName = secondRs
.getString(DescribeParameterEncryptionResultSet2.ParameterName.value());
int paramIndex = parameterNames.indexOf(paramName);
int cekOrdinal = secondRs
.getInt(DescribeParameterEncryptionResultSet2.ColumnEncryptionKeyOrdinal.value());
cekEntry = cekList.get(cekOrdinal);
// cekEntry will be null if none of the parameters are encrypted.
if ((null != cekEntry) && (cekList.size() < cekOrdinal)) {
MessageFormat form = new MessageFormat(
SQLServerException.getErrString("R_InvalidEncryptionKeyOrdinal"));
Object[] msgArgs = {cekOrdinal, cekEntry.getSize()};
throw new SQLServerException(this, form.format(msgArgs), null, 0, false);
}
SQLServerEncryptionType encType = SQLServerEncryptionType.of((byte) secondRs
.getInt(DescribeParameterEncryptionResultSet2.ColumnEncrytionType.value()));
if (SQLServerEncryptionType.PlainText != encType) {
params[paramIndex].cryptoMeta = new CryptoMetadata(cekEntry, (short) cekOrdinal,
(byte) secondRs.getInt(
DescribeParameterEncryptionResultSet2.ColumnEncryptionAlgorithm.value()),
null, encType.value, (byte) secondRs.getInt(
DescribeParameterEncryptionResultSet2.NormalizationRuleVersion.value()));
// Decrypt the symmetric key.(This will also validate and throw if needed).
SQLServerSecurityUtility.decryptSymmetricKey(params[paramIndex].cryptoMeta, connection);
} else {
if (params[paramIndex].getForceEncryption()) {
MessageFormat form = new MessageFormat(SQLServerException
.getErrString("R_ForceEncryptionTrue_HonorAETrue_UnencryptedColumn"));
Object[] msgArgs = {userSQL, paramIndex + 1};
SQLServerException.makeFromDriverError(connection, this, form.format(msgArgs), null,
true);
}
}
}
if (getStatementLogger().isLoggable(java.util.logging.Level.FINE)) {
getStatementLogger().fine("Parameter encryption metadata is set.");
}
}
if (paramCount != params.length) {
// Encryption metadata wasn't sent by the server.
// We expect the metadata to be sent for all the parameters in the original
// sp_describe_parameter_encryption.
// For parameters that don't need encryption, the encryption type is set to plaintext.
MessageFormat form = new MessageFormat(
SQLServerException.getErrString("R_MissingParamEncryptionMetadata"));
Object[] msgArgs = {userSQL};
throw new SQLServerException(this, form.format(msgArgs), null, 0, false);
}
}
} catch (SQLException e) {
if (e instanceof SQLServerException) {
throw (SQLServerException) e;
} else {
throw new SQLServerException(SQLServerException.getErrString("R_UnableRetrieveParameterMetadata"), null,
0, e);
}
}
connection.resetCurrentCommand();
}
/**
* Manages re-using cached handles.
*/
private boolean reuseCachedHandle(boolean hasNewTypeDefinitions, boolean discardCurrentCacheItem) {
// No re-use of caching for cursorable statements (statements that WILL use sp_cursor*)
if (isCursorable(executeMethod))
return false;
// If current cache items needs to be discarded or New type definitions found with existing cached handle
// reference then deregister cached
// handle.
if (discardCurrentCacheItem || hasNewTypeDefinitions) {
if (null != cachedPreparedStatementHandle && (discardCurrentCacheItem
|| (hasPreparedStatementHandle() && prepStmtHandle == cachedPreparedStatementHandle.getHandle()))) {
cachedPreparedStatementHandle.removeReference();