-
Notifications
You must be signed in to change notification settings - Fork 426
/
SQLServerStatement.java
2680 lines (2302 loc) · 114 KB
/
SQLServerStatement.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.sql.BatchUpdateException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLTimeoutException;
import java.sql.SQLWarning;
import java.sql.Statement;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.microsoft.sqlserver.jdbc.SQLServerConnection.CityHash128Key;
/**
* Provides an implementation of java.sql.Statement JDBC Interface to assist in creating Statements against SQL Server.
* It also provides a number of base class implementation methods for the JDBC prepared statement and callable
* Statements. SQLServerStatement's basic role is to execute SQL statements and return update counts and resultset rows
* to the user application.
*
* Documentation for specific public methods that are undocumented can be found under Sun's standard JDBC documentation
* for class java.sql.Statement. Those methods are part of Sun's standard JDBC documentation and therefore their
* documentation is not duplicated here.
* <p>
* Implementation Notes
* <p>
* Fetching Result sets
* <p>
* The queries first rowset is available immediately after the executeQuery. The first rs.next() does not make a server
* round trip. For non server side resultsets the entire result set is in the rowset. For server side result sets the
* number of rows in the rowset is set with nFetchSize
* <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 SQLServerStatement implements ISQLServerStatement {
/**
* Always update serialVersionUID when prompted.
*/
private static final long serialVersionUID = -4421134713913331507L;
final static char LEFT_CURLY_BRACKET = 123;
final static char RIGHT_CURLY_BRACKET = 125;
private boolean isResponseBufferingAdaptive = false;
final boolean getIsResponseBufferingAdaptive() {
return isResponseBufferingAdaptive;
}
private boolean wasResponseBufferingSet = false;
final boolean wasResponseBufferingSet() {
return wasResponseBufferingSet;
}
final static String identityQuery = " select SCOPE_IDENTITY() AS GENERATED_KEYS";
/** the stored procedure name to call (if there is one) */
String procedureName;
/** OUT parameters associated with this statement's execution */
private int serverCursorId;
final int getServerCursorId() {
return serverCursorId;
}
private int serverCursorRowCount;
final int getServerCursorRowCount() {
return serverCursorRowCount;
}
/** The value of the poolable state */
boolean stmtPoolable;
/** Streaming access to the response TDS data stream */
private TDSReader tdsReader;
final TDSReader resultsReader() {
return tdsReader;
}
final boolean wasExecuted() {
return null != tdsReader;
}
/**
* The input and out parameters for statement execution.
*/
Parameter[] inOutParam; // Parameters for prepared stmts and stored procedures
/**
* The statement's connection.
*/
final SQLServerConnection connection;
/**
* The user's specifed query timeout (in seconds).
*/
int queryTimeout;
/**
* timeout value for canceling the query timeout
*/
int cancelQueryTimeoutSeconds;
/**
* Is closeOnCompletion is enabled? If true statement will be closed when all of its dependent result sets are
* closed
*/
boolean isCloseOnCompletion = false;
/**
* Currently executing or most recently executed TDSCommand (statement cmd, server cursor cmd, ...) subject to
* cancellation through Statement.cancel.
*
* Note: currentCommand is declared volatile to ensure that the JVM always returns the most recently set value for
* currentCommand to the cancelling thread.
*/
private volatile TDSCommand currentCommand = null;
private TDSCommand lastStmtExecCmd = null;
final void discardLastExecutionResults() {
if (null != lastStmtExecCmd && !bIsClosed) {
lastStmtExecCmd.close();
lastStmtExecCmd = null;
}
clearLastResult();
}
static final java.util.logging.Logger loggerExternal = java.util.logging.Logger
.getLogger("com.microsoft.sqlserver.jdbc.Statement");
final private String loggingClassName;
final private String traceID;
String getClassNameLogging() {
return loggingClassName;
}
/*
* Column Encryption Override. Defaults to the connection setting, in which case it will be Enabled if
* columnEncryptionSetting = true in the connection setting, Disabled if false. This may also be used to set other
* behavior which overrides connection level setting.
*/
protected SQLServerStatementColumnEncryptionSetting stmtColumnEncriptionSetting = SQLServerStatementColumnEncryptionSetting.UseConnectionSetting;
protected SQLServerStatementColumnEncryptionSetting getStmtColumnEncriptionSetting() {
return stmtColumnEncriptionSetting;
}
/**
* Encapsulates a subset of statement property values as they were set at execution time.
*/
final class ExecuteProperties {
final private boolean wasResponseBufferingSet;
final boolean wasResponseBufferingSet() {
return wasResponseBufferingSet;
}
final private boolean isResponseBufferingAdaptive;
final boolean isResponseBufferingAdaptive() {
return isResponseBufferingAdaptive;
}
final private int holdability;
final int getHoldability() {
return holdability;
}
ExecuteProperties(SQLServerStatement stmt) {
wasResponseBufferingSet = stmt.wasResponseBufferingSet();
isResponseBufferingAdaptive = stmt.getIsResponseBufferingAdaptive();
holdability = stmt.connection.getHoldabilityInternal();
}
}
private ExecuteProperties execProps;
final ExecuteProperties getExecProps() {
return execProps;
}
/**
* Executes this Statement using TDSCommand newStmtCmd.
*
* The TDSCommand is assumed to be a statement execution command (StmtExecCmd, PrepStmtExecCmd,
* PrepStmtBatchExecCmd).
*/
final void executeStatement(TDSCommand newStmtCmd) throws SQLServerException, SQLTimeoutException {
// Ensure that any response left over from a previous execution has been
// completely processed. There may be ENVCHANGEs in that response that
// we must acknowledge before proceeding.
discardLastExecutionResults();
// make sure statement hasn't been closed due to closeOnCompletion
checkClosed();
execProps = new ExecuteProperties(this);
try {
// (Re)execute this Statement with the new command
executeCommand(newStmtCmd);
} catch (SQLServerException e) {
if (e.getDriverErrorCode() == SQLServerException.ERROR_QUERY_TIMEOUT)
throw new SQLTimeoutException(e.getMessage(), e.getSQLState(), e.getErrorCode(), e.getCause());
else
throw e;
} finally {
lastStmtExecCmd = newStmtCmd;
}
}
/**
* Executes TDSCommand newCommand through this Statement object, allowing it to be cancelled through
* Statement.cancel().
*
* The specified command is typically the one used to execute the statement. But it could also be a server cursor
* command (fetch, move, close) generated by a ResultSet that this statement produced.
*
* This method does not prevent applications from simultaneously executing commands from multiple threads. The
* assumption is that apps only call cancel() from another thread while the command is executing.
*/
final void executeCommand(TDSCommand newCommand) throws SQLServerException {
// Set the new command as the current command so that
// its execution can be cancelled from another thread
currentCommand = newCommand;
connection.executeCommand(newCommand);
}
/**
* Flag to indicate that are potentially more results (ResultSets, update counts, or errors) to be processed in the
* response.
*/
boolean moreResults = false;
/**
* The statement's current result set.
*/
SQLServerResultSet resultSet;
/**
* The number of opened result sets in the statement.
*/
int resultSetCount = 0;
/**
* Increment opened result set counter
*/
synchronized void incrResultSetCount() {
resultSetCount++;
}
/**
* Decrement opened result set counter.
*/
synchronized void decrResultSetCount() {
resultSetCount--;
assert resultSetCount >= 0;
// close statement if no more result sets opened
if (isCloseOnCompletion && !(EXECUTE_BATCH == executeMethod && moreResults) && resultSetCount == 0) {
closeInternal();
}
}
/**
* The statement execution method (executeQuery(), executeUpdate(), execute(), or executeBatch()) that was used to
* execute the statement.
*/
static final int EXECUTE_NOT_SET = 0;
static final int EXECUTE_QUERY = 1;
static final int EXECUTE_UPDATE = 2;
static final int EXECUTE = 3;
static final int EXECUTE_BATCH = 4;
static final int EXECUTE_QUERY_INTERNAL = 5;
int executeMethod = EXECUTE_NOT_SET;
/**
* The update count returned from an update.
*/
long updateCount = -1;
/**
* The status of escape processing.
*/
boolean escapeProcessing;
/** Limit for the maximum number of rows in a ResultSet */
int maxRows = 0; // default: 0 --> no limit
/** Limit for the size of data (in bytes) returned for any column value */
int maxFieldSize = 0; // default: 0 --> no limit
/**
* The user's specified result set concurrency.
*/
int resultSetConcurrency;
/**
* The app result set type. This is the value passed to the statement's constructor (or inferred by default) when
* the statement was created. ResultSet.getType() returns this value. It may differ from the SQL Server result set
* type (see below). Namely, an app result set type of TYPE_FORWARD_ONLY will have an SQL Server result set type of
* TYPE_SS_DIRECT_FORWARD_ONLY or TYPE_SS_SERVER_CURSOR_FORWARD_ONLY depending on the value of the selectMethod
* connection property.
*
* Possible values of the app result set type are:
*
* TYPE_FORWARD_ONLY TYPE_SCROLL_INSENSITIVE TYPE_SCROLL_SENSITIVE TYPE_SS_DIRECT_FORWARD_ONLY
* TYPE_SS_SERVER_CURSOR_FORWARD_ONLY TYPE_SS_SCROLL_DYNAMIC TYPE_SS_SCROLL_KEYSET TYPE_SS_SCROLL_STATIC
*/
int appResultSetType;
/**
* The SQL Server result set type. This is the value used everywhere EXCEPT ResultSet.getType(). This value may or
* may not be the same as the app result set type (above).
*
* Possible values of the SQL Server result set type are:
*
* TYPE_SS_DIRECT_FORWARD_ONLY TYPE_SS_SERVER_CURSOR_FORWARD_ONLY TYPE_SS_SCROLL_DYNAMIC TYPE_SS_SCROLL_KEYSET
* TYPE_SS_SCROLL_STATIC
*/
int resultSetType;
final int getSQLResultSetType() {
return resultSetType;
}
final int getCursorType() {
return getResultSetScrollOpt() & ~TDS.SCROLLOPT_PARAMETERIZED_STMT;
}
/**
* Returns whether to request a server cursor when executing this statement.
*
* Executing a statement with execute() or executeQuery() requests a server cursor in all scrollability and
* updatability combinations except direct forward-only, read-only.
*
* Note that when execution requests a server cursor (i.e. this method returns true), there is no guarantee that SQL
* Server returns one. The variable executedSqlDirectly indicates whether SQL Server executed the query with a
* cursor or not.
*
* @return true if statement execution requests a server cursor, false otherwise.
*/
final boolean isCursorable(int executeMethod) {
return resultSetType != SQLServerResultSet.TYPE_SS_DIRECT_FORWARD_ONLY
&& (EXECUTE == executeMethod || EXECUTE_QUERY == executeMethod);
}
/**
* Indicates whether SQL Server executed this statement with a cursor or not.
*
* When trying to execute a cursor-unfriendly statement with a server cursor, SQL Server may choose to execute the
* statement directly (i.e. as if no server cursor had been requested) rather than fail to execute the statement at
* all. We need to know when this happens so that if no rows are returned, we can tell whether the result is an
* empty result set or a cursored result set with rows to be fetched later.
*/
boolean executedSqlDirectly = false;
/**
* Indicates whether OUT parameters (cursor ID and row count) from cursorized execution of this statement are
* expected in the response.
*
* In most cases, except for severe errors, cursor OUT parameters are returned whenever a cursor is requested for
* statement execution. Even if SQL Server does not cursorize the statement as requested, these values are still
* present in the response and must be processed, even though their values are meaningless in that case.
*/
boolean expectCursorOutParams;
class StmtExecOutParamHandler extends TDSTokenHandler {
StmtExecOutParamHandler() {
super("StmtExecOutParamHandler");
}
boolean onRetStatus(TDSReader tdsReader) throws SQLServerException {
(new StreamRetStatus()).setFromTDS(tdsReader);
return true;
}
boolean onRetValue(TDSReader tdsReader) throws SQLServerException {
if (expectCursorOutParams) {
Parameter param = new Parameter(
Util.shouldHonorAEForParameters(stmtColumnEncriptionSetting, connection));
// Read the cursor ID
param.skipRetValStatus(tdsReader);
serverCursorId = param.getInt(tdsReader);
param.skipValue(tdsReader, true);
param = new Parameter(Util.shouldHonorAEForParameters(stmtColumnEncriptionSetting, connection));
// Read the row count (-1 means unknown)
param.skipRetValStatus(tdsReader);
if (-1 == (serverCursorRowCount = param.getInt(tdsReader)))
serverCursorRowCount = SQLServerResultSet.UNKNOWN_ROW_COUNT;
param.skipValue(tdsReader, true);
// We now have everything we need to build the result set.
expectCursorOutParams = false;
return true;
}
return false;
}
boolean onDone(TDSReader tdsReader) throws SQLServerException {
return false;
}
}
/**
* The cursor name.
*/
String cursorName;
/**
* The user's specified fetch size. Only used for server side result sets. Client side cursors read all rows.
*/
int nFetchSize;
int defaultFetchSize;
/**
* The users specified result set fetch direction
*/
int nFetchDirection;
/**
* True is the statement is closed
*/
boolean bIsClosed;
/**
* True if the user requested to driver to generate insert keys
*/
boolean bRequestedGeneratedKeys;
/**
* The result set if auto generated keys were requested.
*/
private ResultSet autoGeneratedKeys;
/**
* The array of objects in a batched call. Applicable to statements and prepared statements When the
* iterativeBatching property is turned on.
*/
/** The buffer that accumulates batchable statements */
private final ArrayList<String> batchStatementBuffer = new ArrayList<>();
/** logging init at the construction */
static final private java.util.logging.Logger stmtlogger = java.util.logging.Logger
.getLogger("com.microsoft.sqlserver.jdbc.internals.SQLServerStatement");
/** Returns the statement's id for logging info */
@Override
public String toString() {
return traceID;
}
// Internal function used in tracing
String getClassNameInternal() {
return "SQLServerStatement";
}
/** Generate the statement's logging ID */
private static final AtomicInteger lastStatementID = new AtomicInteger(0);
private static int nextStatementID() {
return lastStatementID.incrementAndGet();
}
/**
* Constructs a SQLServerStatement
*
* @param con
* The statements connections.
* @param nType
* The statement type.
* @param nConcur
* The statement concurrency.
* @param stmtColEncSetting
* The statement column encryption setting.
* @exception SQLServerException
* The statement could not be created.
*/
SQLServerStatement(SQLServerConnection con, int nType, int nConcur,
SQLServerStatementColumnEncryptionSetting stmtColEncSetting)
throws SQLServerException {
// Return a string representation of this statement's unqualified class name
// (e.g. "SQLServerStatement" or "SQLServerPreparedStatement"),
// its unique ID, and its parent connection.
int statementID = nextStatementID();
String classN = getClassNameInternal();
traceID = classN + ":" + statementID;
loggingClassName = "com.microsoft.sqlserver.jdbc." + classN + ":" + statementID;
stmtPoolable = false;
connection = con;
bIsClosed = false;
// Validate result set type ...
if (ResultSet.TYPE_FORWARD_ONLY != nType && ResultSet.TYPE_SCROLL_SENSITIVE != nType
&& ResultSet.TYPE_SCROLL_INSENSITIVE != nType && SQLServerResultSet.TYPE_SS_DIRECT_FORWARD_ONLY != nType
&& SQLServerResultSet.TYPE_SS_SERVER_CURSOR_FORWARD_ONLY != nType
&& SQLServerResultSet.TYPE_SS_SCROLL_DYNAMIC != nType
&& SQLServerResultSet.TYPE_SS_SCROLL_KEYSET != nType
&& SQLServerResultSet.TYPE_SS_SCROLL_STATIC != nType) {
SQLServerException.makeFromDriverError(connection, this,
SQLServerException.getErrString("R_unsupportedCursor"), null, true);
}
// ... and concurrency
if (ResultSet.CONCUR_READ_ONLY != nConcur && ResultSet.CONCUR_UPDATABLE != nConcur
&& SQLServerResultSet.CONCUR_SS_SCROLL_LOCKS != nConcur
&& SQLServerResultSet.CONCUR_SS_OPTIMISTIC_CC != nConcur
&& SQLServerResultSet.CONCUR_SS_OPTIMISTIC_CCVAL != nConcur) {
SQLServerException.makeFromDriverError(connection, this,
SQLServerException.getErrString("R_unsupportedConcurrency"), null, true);
}
if (null == stmtColEncSetting) {
SQLServerException.makeFromDriverError(connection, this,
SQLServerException.getErrString("R_unsupportedStmtColEncSetting"), null, true);
}
stmtColumnEncriptionSetting = stmtColEncSetting;
resultSetConcurrency = nConcur;
// App result set type is always whatever was used to create the statement.
// This value will be returned by ResultSet.getType() calls.
appResultSetType = nType;
// SQL Server result set type is used everwhere other than ResultSet.getType() and
// may need to be inferred based on the app result set type and the value of
// the selectMethod connection property.
if (ResultSet.TYPE_FORWARD_ONLY == nType) {
if (ResultSet.CONCUR_READ_ONLY == nConcur) {
// Check selectMethod and set to TYPE_SS_DIRECT_FORWARD_ONLY or
// TYPE_SS_SERVER_CURSOR_FORWARD_ONLY accordingly.
String selectMethod = con.getSelectMethod();
resultSetType = (null == selectMethod
|| !"cursor".equals(selectMethod)) ? SQLServerResultSet.TYPE_SS_DIRECT_FORWARD_ONLY : // Default
// forward-only,
// read-only
// cursor
// type
SQLServerResultSet.TYPE_SS_SERVER_CURSOR_FORWARD_ONLY;
} else {
resultSetType = SQLServerResultSet.TYPE_SS_SERVER_CURSOR_FORWARD_ONLY;
}
} else if (ResultSet.TYPE_SCROLL_INSENSITIVE == nType) {
resultSetType = SQLServerResultSet.TYPE_SS_SCROLL_STATIC;
} else if (ResultSet.TYPE_SCROLL_SENSITIVE == nType) {
resultSetType = SQLServerResultSet.TYPE_SS_SCROLL_KEYSET;
} else // App specified one of the SQL Server types
{
resultSetType = nType;
}
// Figure out default fetch direction
nFetchDirection = (SQLServerResultSet.TYPE_SS_DIRECT_FORWARD_ONLY == resultSetType
|| SQLServerResultSet.TYPE_SS_SERVER_CURSOR_FORWARD_ONLY == resultSetType) ? ResultSet.FETCH_FORWARD
: ResultSet.FETCH_UNKNOWN;
// Figure out fetch size:
//
// Too many scroll locks adversely impact concurrency on the server
// and thus system performance, so default to a low value when using
// scroll locks. Otherwise, use a larger fetch size.
nFetchSize = (SQLServerResultSet.CONCUR_SS_SCROLL_LOCKS == resultSetConcurrency) ? 8 : 128;
// Save off the default fetch size so it can be restored by setFetchSize(0).
defaultFetchSize = nFetchSize;
// Check compatibility between the result set type and concurrency.
// Against a Yukon server, certain scrollability values are incompatible
// with all but read only concurrency. Against a Shiloh server, such
// combinations cause the cursor to be silently "upgraded" to one that
// works. We enforce the more restrictive behavior of the two here.
if (ResultSet.CONCUR_READ_ONLY != nConcur && (SQLServerResultSet.TYPE_SS_DIRECT_FORWARD_ONLY == resultSetType
|| SQLServerResultSet.TYPE_SS_SCROLL_STATIC == resultSetType)) {
SQLServerException.makeFromDriverError(connection, this,
SQLServerException.getErrString("R_unsupportedCursorAndConcurrency"), null, true);
}
// All result set types other than firehose (SQL Server default) use server side cursors.
setResponseBuffering(connection.getResponseBuffering());
setDefaultQueryTimeout();
setDefaultQueryCancelTimeout();
if (stmtlogger.isLoggable(java.util.logging.Level.FINER)) {
stmtlogger.finer("Properties for " + toString() + ":" + " Result type:" + appResultSetType + " ("
+ resultSetType + ")" + " Concurrency:" + resultSetConcurrency + " Fetchsize:" + nFetchSize
+ " bIsClosed:" + bIsClosed + " useLastUpdateCount:" + connection.useLastUpdateCount());
}
if (stmtlogger.isLoggable(java.util.logging.Level.FINE)) {
stmtlogger.fine(toString() + " created by (" + connection.toString() + ")");
}
}
private void setDefaultQueryCancelTimeout() {
int cancelQueryTimeoutSeconds = this.connection.getCancelQueryTimeoutSeconds();
if (cancelQueryTimeoutSeconds > 0) {
this.cancelQueryTimeoutSeconds = cancelQueryTimeoutSeconds;
}
}
// add query timeout to statement
private void setDefaultQueryTimeout() {
int queryTimeoutSeconds = this.connection.getQueryTimeoutSeconds();
if (queryTimeoutSeconds > 0) {
this.queryTimeout = queryTimeoutSeconds;
}
}
final java.util.logging.Logger getStatementLogger() {
return stmtlogger;
}
/**
* Closes the statement.
*
* Note that the public 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.
*/
void closeInternal() {
// Regardless what happens when cleaning up,
// the statement is considered closed.
assert !bIsClosed;
discardLastExecutionResults();
bIsClosed = true;
autoGeneratedKeys = null;
sqlWarnings = null;
inOutParam = null;
connection.removeOpenStatement(this);
}
@Override
public void close() throws SQLServerException {
loggerExternal.entering(getClassNameLogging(), "close");
if (!bIsClosed)
closeInternal();
loggerExternal.exiting(getClassNameLogging(), "close");
}
@Override
public void closeOnCompletion() throws SQLException {
loggerExternal.entering(getClassNameLogging(), "closeOnCompletion");
checkClosed();
// enable closeOnCompletion feature
isCloseOnCompletion = true;
loggerExternal.exiting(getClassNameLogging(), "closeOnCompletion");
}
@Override
public java.sql.ResultSet executeQuery(String sql) throws SQLServerException, SQLTimeoutException {
loggerExternal.entering(getClassNameLogging(), "executeQuery", sql);
if (loggerExternal.isLoggable(Level.FINER) && Util.isActivityTraceOn()) {
loggerExternal.finer(toString() + " ActivityId: " + ActivityCorrelator.getNext().toString());
}
checkClosed();
executeStatement(new StmtExecCmd(this, sql, EXECUTE_QUERY, NO_GENERATED_KEYS));
loggerExternal.exiting(getClassNameLogging(), "executeQuery", resultSet);
return resultSet;
}
final SQLServerResultSet executeQueryInternal(String sql) throws SQLServerException, SQLTimeoutException {
checkClosed();
executeStatement(new StmtExecCmd(this, sql, EXECUTE_QUERY_INTERNAL, NO_GENERATED_KEYS));
return resultSet;
}
@Override
public int executeUpdate(String sql) throws SQLServerException, SQLTimeoutException {
loggerExternal.entering(getClassNameLogging(), "executeUpdate", sql);
if (loggerExternal.isLoggable(Level.FINER) && Util.isActivityTraceOn()) {
loggerExternal.finer(toString() + " ActivityId: " + ActivityCorrelator.getNext().toString());
}
checkClosed();
executeStatement(new StmtExecCmd(this, sql, EXECUTE_UPDATE, NO_GENERATED_KEYS));
// 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(String sql) throws SQLServerException, SQLTimeoutException {
loggerExternal.entering(getClassNameLogging(), "executeLargeUpdate", sql);
if (loggerExternal.isLoggable(Level.FINER) && Util.isActivityTraceOn()) {
loggerExternal.finer(toString() + " ActivityId: " + ActivityCorrelator.getNext().toString());
}
checkClosed();
executeStatement(new StmtExecCmd(this, sql, EXECUTE_UPDATE, NO_GENERATED_KEYS));
loggerExternal.exiting(getClassNameLogging(), "executeLargeUpdate", updateCount);
return updateCount;
}
@Override
public boolean execute(String sql) throws SQLServerException, SQLTimeoutException {
loggerExternal.entering(getClassNameLogging(), "execute", sql);
if (loggerExternal.isLoggable(Level.FINER) && Util.isActivityTraceOn()) {
loggerExternal.finer(toString() + " ActivityId: " + ActivityCorrelator.getNext().toString());
}
checkClosed();
executeStatement(new StmtExecCmd(this, sql, EXECUTE, NO_GENERATED_KEYS));
loggerExternal.exiting(getClassNameLogging(), "execute", null != resultSet);
return null != resultSet;
}
private final class StmtExecCmd extends TDSCommand {
/**
* Always update serialVersionUID when prompted.
*/
private static final long serialVersionUID = 4534132352812876292L;
final SQLServerStatement stmt;
final String sql;
final int executeMethod;
final int autoGeneratedKeys;
StmtExecCmd(SQLServerStatement stmt, String sql, int executeMethod, int autoGeneratedKeys) {
super(stmt.toString() + " executeXXX", stmt.queryTimeout, stmt.cancelQueryTimeoutSeconds);
this.stmt = stmt;
this.sql = sql;
this.executeMethod = executeMethod;
this.autoGeneratedKeys = autoGeneratedKeys;
}
final boolean doExecute() throws SQLServerException {
stmt.doExecuteStatement(this);
return false;
}
final void processResponse(TDSReader tdsReader) throws SQLServerException {
ensureExecuteResultsReader(tdsReader);
processExecuteResults();
}
}
private String ensureSQLSyntax(String sql) throws SQLServerException {
if (sql.indexOf(LEFT_CURLY_BRACKET) >= 0) {
CityHash128Key cacheKey = new CityHash128Key(sql);
// Check for cached SQL metadata.
ParsedSQLCacheItem cacheItem = getCachedParsedSQL(cacheKey);
if (null == cacheItem)
cacheItem = parseAndCacheSQL(cacheKey, sql);
// Retrieve from cache item.
procedureName = cacheItem.procedureName;
return cacheItem.processedSQL;
}
return sql;
}
void startResults() {
moreResults = true;
}
final void setMaxRowsAndMaxFieldSize() throws SQLServerException {
if (EXECUTE_QUERY == executeMethod || EXECUTE == executeMethod) {
connection.setMaxRows(maxRows);
connection.setMaxFieldSize(maxFieldSize);
} else {
assert EXECUTE_UPDATE == executeMethod || EXECUTE_BATCH == executeMethod
|| EXECUTE_QUERY_INTERNAL == executeMethod;
// If we are executing via any of the above methods then make sure any
// previous maxRows limitation on the connection is removed.
connection.setMaxRows(0);
}
}
final void doExecuteStatement(StmtExecCmd execCmd) throws SQLServerException {
resetForReexecute();
// Set this command as the current command
executeMethod = execCmd.executeMethod;
// Apps can use JDBC call syntax to call unparameterized stored procedures
// through regular Statement objects. We need to ensure that any such JDBC
// call syntax is rewritten here as SQL exec syntax.
String sql = ensureSQLSyntax(execCmd.sql);
if (!isInternalEncryptionQuery && connection.isAEv2()) {
execCmd.enclaveCEKs = connection.initEnclaveParameters(sql, null, null, null);
}
// 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 SQLServerPreparedStatement.doExecutePreparedStatement
setMaxRowsAndMaxFieldSize();
if (loggerExternal.isLoggable(Level.FINER) && Util.isActivityTraceOn()) {
loggerExternal.finer(toString() + " ActivityId: " + ActivityCorrelator.getNext().toString());
}
if (isCursorable(executeMethod) && isSelect(sql)) {
if (stmtlogger.isLoggable(java.util.logging.Level.FINE))
stmtlogger.fine(toString() + " Executing server side cursor " + sql);
doExecuteCursored(execCmd, sql);
} else // Non-cursored execution (includes EXECUTE_QUERY_INTERNAL)
{
executedSqlDirectly = true;
expectCursorOutParams = false;
TDSWriter tdsWriter = execCmd.startRequest(TDS.PKT_QUERY);
tdsWriter.sendEnclavePackage(sql, execCmd.enclaveCEKs);
tdsWriter.writeString(sql);
// If this is an INSERT statement and generated keys were requested
// then add on the query to return them.
if (RETURN_GENERATED_KEYS == execCmd.autoGeneratedKeys
&& (EXECUTE_UPDATE == executeMethod || EXECUTE == executeMethod)
&& sql.trim().toUpperCase().startsWith("INSERT")) {
tdsWriter.writeString(identityQuery);
}
if (stmtlogger.isLoggable(java.util.logging.Level.FINE))
stmtlogger.fine(toString() + " Executing (not server cursor) " + sql);
// Start the response
ensureExecuteResultsReader(execCmd.startResponse(isResponseBufferingAdaptive));
startResults();
getNextResult(true);
}
// If execution produced no result set, then throw an exception if executeQuery() was used.
if (null == resultSet) {
if (EXECUTE_QUERY == executeMethod) {
SQLServerException.makeFromDriverError(connection, this,
SQLServerException.getErrString("R_noResultset"), null, true);
}
}
// Otherwise, if execution produced a result set, then throw an exception
// if executeUpdate() or executeBatch() was used.
else {
if (EXECUTE_UPDATE == executeMethod || EXECUTE_BATCH == executeMethod) {
SQLServerException.makeFromDriverError(connection, this,
SQLServerException.getErrString("R_resultsetGeneratedForUpdate"), null, false);
}
}
}
private final class StmtBatchExecCmd extends TDSCommand {
/**
* Always update serialVersionUID when prompted.
*/
private static final long serialVersionUID = -4621631860790243331L;
final SQLServerStatement stmt;
StmtBatchExecCmd(SQLServerStatement stmt) {
super(stmt.toString() + " executeBatch", stmt.queryTimeout, stmt.cancelQueryTimeoutSeconds);
this.stmt = stmt;
}
final boolean doExecute() throws SQLServerException {
stmt.doExecuteStatementBatch(this);
return false;
}
final void processResponse(TDSReader tdsReader) throws SQLServerException {
ensureExecuteResultsReader(tdsReader);
processExecuteResults();
}
}
private void doExecuteStatementBatch(StmtBatchExecCmd execCmd) throws SQLServerException {
resetForReexecute();
// Make sure any previous maxRows limitation on the connection is removed.
connection.setMaxRows(0);
String batchStatementString = String.join(";", batchStatementBuffer);
if (connection.isAEv2()) {
execCmd.enclaveCEKs = connection.initEnclaveParameters(batchStatementString, null, null, null);
}
if (loggerExternal.isLoggable(Level.FINER) && Util.isActivityTraceOn()) {
loggerExternal.finer(toString() + " ActivityId: " + ActivityCorrelator.getNext().toString());
}
// Batch execution is always non-cursored
executeMethod = EXECUTE_BATCH;
executedSqlDirectly = true;
expectCursorOutParams = false;
TDSWriter tdsWriter = execCmd.startRequest(TDS.PKT_QUERY);
// Write the concatenated batch of statements, delimited by semicolons
tdsWriter.sendEnclavePackage(batchStatementString, execCmd.enclaveCEKs);
tdsWriter.writeString(batchStatementString);
// Start the response
ensureExecuteResultsReader(execCmd.startResponse(isResponseBufferingAdaptive));
startResults();
getNextResult(true);
// If execution produced a result set, then throw an exception
if (null != resultSet) {
SQLServerException.makeFromDriverError(connection, this,
SQLServerException.getErrString("R_resultsetGeneratedForUpdate"), null, false);
}
}
/**
* Resets the state to get the statement for reexecute callable statement overrides this.
*/
final void resetForReexecute() throws SQLServerException {
ensureExecuteResultsReader(null);
autoGeneratedKeys = null;
updateCount = -1;
sqlWarnings = null;
executedSqlDirectly = false;
startResults();
}
/**
* Determines if the SQL is a SELECT.
*
* @param sql
* The statement SQL.
* @return True if the statement is a select.
*/
final boolean isSelect(String sql) throws SQLServerException {
checkClosed();
// Used to check just the first letter which would cause
// "Set" commands to return true...
String temp = sql.trim();
if (null == sql || sql.length() < 6) {
return false;
}
return "select".equalsIgnoreCase(temp.substring(0, 6));
}
/**
* Determine if the SQL is a INSERT.
*
* @param sql
* The statement SQL.
* @return True if the statement is an insert.
*/
final boolean isInsert(String sql) throws SQLServerException {
checkClosed();
// Used to check just the first letter which would cause
// "Set" commands to return true...
String temp = sql.trim();
if (null == sql || sql.length() < 6) {
return false;
}
if ("/*".equalsIgnoreCase(temp.substring(0, 2))) {
int index = temp.indexOf("*/") + 2;
return isInsert(temp.substring(index));