forked from microsoft/mssql-jdbc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSQLServerResultSet.java
5743 lines (4662 loc) · 236 KB
/
SQLServerResultSet.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.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.NClob;
import java.sql.Ref;
import java.sql.ResultSet;
import java.sql.RowId;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLType;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.text.MessageFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import com.microsoft.sqlserver.jdbc.dataclassification.SensitivityClassification;
/**
* Indicates the type of the row received from the server.
*/
enum RowType {
ROW,
NBCROW,
UNKNOWN,
}
/**
* Defines the Top-level JDBC ResultSet implementation.
*/
public class SQLServerResultSet implements ISQLServerResultSet, java.io.Serializable {
/**
* Always refresh SerialVersionUID when prompted
*/
private static final long serialVersionUID = -1624082547992040463L;
/** Generate the statement's logging ID */
private static final AtomicInteger lastResultSetID = new AtomicInteger(0);
private final String traceID;
private static int nextResultSetID() {
return lastResultSetID.incrementAndGet();
}
final static java.util.logging.Logger logger = java.util.logging.Logger
.getLogger("com.microsoft.sqlserver.jdbc.internals.SQLServerResultSet");
@Override
public String toString() {
return traceID;
}
String logCursorState() {
return " currentRow:" + currentRow + " numFetchedRows:" + numFetchedRows + " rowCount:" + rowCount;
}
protected static final java.util.logging.Logger loggerExternal = java.util.logging.Logger
.getLogger("com.microsoft.sqlserver.jdbc.ResultSet");
final private String loggingClassName;
String getClassNameLogging() {
return loggingClassName;
}
/** the statement that generated this result set */
private final SQLServerStatement stmt;
/** max rows to return from this result set */
private final int maxRows;
/** the meta data for this result set */
private SQLServerResultSetMetaData metaData;
/** is the result set close */
private boolean isClosed = false;
private final int serverCursorId;
protected int getServerCursorId() {
return serverCursorId;
}
/** the intended fetch direction to optimize cursor performance */
private int fetchDirection;
/** the desired fetch size to optimize cursor performance */
private int fetchSize;
/** true if the cursor is positioned on the insert row */
private boolean isOnInsertRow = false;
/** true if the last value read was SQL NULL */
private boolean lastValueWasNull = false;
/** The index (1-based) of the last column in the current row that has been marked for reading */
private int lastColumnIndex;
// Indicates if the null bit map is loaded for the current row
// in the resultset
private boolean areNullCompressedColumnsInitialized = false;
// Indicates the type of the current row in the result set
private RowType resultSetCurrentRowType = RowType.UNKNOWN;
// getter for resultSetCurrentRowType
final RowType getCurrentRowType() {
return resultSetCurrentRowType;
}
// setter for resultSetCurrentRowType
final void setCurrentRowType(RowType rowType) {
resultSetCurrentRowType = rowType;
}
/**
* Currently active Stream Note only one stream can be active at a time, JDBC spec calls for the streams to be
* closed when a column or row move occurs
*/
private transient Closeable activeStream;
private SQLServerLob activeLOB;
/**
* A window of fetchSize quickly accessible rows for scrollable result sets
*/
private final ScrollWindow scrollWindow;
/**
* Current row, which is either the actual (1-based) value or one of the special values defined below.
*/
private static final int BEFORE_FIRST_ROW = 0;
private static final int AFTER_LAST_ROW = -1;
private static final int UNKNOWN_ROW = -2;
private int currentRow = BEFORE_FIRST_ROW;
/** Flag set to true if the current row was updated through this ResultSet object */
private boolean updatedCurrentRow = false;
// Column name hash map for caching.
private final Map<String, Integer> columnNames = new HashMap<>();
final boolean getUpdatedCurrentRow() {
return updatedCurrentRow;
}
final void setUpdatedCurrentRow(boolean rowUpdated) {
updatedCurrentRow = rowUpdated;
}
/** Flag set to true if the current row was deleted through this ResultSet object */
private boolean deletedCurrentRow = false;
final boolean getDeletedCurrentRow() {
return deletedCurrentRow;
}
final void setDeletedCurrentRow(boolean rowDeleted) {
deletedCurrentRow = rowDeleted;
}
/**
* Count of rows in this result set.
*
* The number of rows in the result set may be known when this ResultSet object is created, after the first full
* traversal of the result set, or possibly never (as is the case with DYNAMIC cursors).
*/
static final int UNKNOWN_ROW_COUNT = -3;
private int rowCount;
/** The current row's column values */
private final Column[] columns;
// The CekTable retrieved from the COLMETADATA token for this resultset.
private CekTable cekTable = null;
/* Returns the CekTable */
CekTable getCekTable() {
return cekTable;
}
final void setColumnName(int index, String name) {
columns[index - 1].setColumnName(name);
}
/**
* Skips columns between the last marked column and the target column, inclusive, optionally discarding their values
* as they are skipped.
*/
private void skipColumns(int columnsToSkip, boolean discardValues) throws SQLServerException {
assert lastColumnIndex >= 1;
assert 0 <= columnsToSkip && columnsToSkip <= columns.length;
for (int columnsSkipped = 0; columnsSkipped < columnsToSkip; ++columnsSkipped) {
Column column = getColumn(lastColumnIndex++);
column.skipValue(tdsReader, discardValues && isForwardOnly());
if (discardValues)
column.clear();
}
}
/** TDS reader from which row values are read */
private TDSReader tdsReader;
protected TDSReader getTDSReader() {
return tdsReader;
}
private final FetchBuffer fetchBuffer;
@Override
public SensitivityClassification getSensitivityClassification() {
return tdsReader.sensitivityClassification;
}
/**
* Constructs a SQLServerResultSet.
*
* @param stmtIn
* the generating statement
*/
SQLServerResultSet(SQLServerStatement stmtIn) throws SQLServerException {
int resultSetID = nextResultSetID();
loggingClassName = "com.microsoft.sqlserver.jdbc.SQLServerResultSet" + ":" + resultSetID;
traceID = "SQLServerResultSet:" + resultSetID;
// Common initializer class for server-cursored and client-cursored ResultSets.
// The common initializer builds columns from the column metadata and other table
// info when present. Specialized subclasses take care of behavior that is specific
// to either server-cursored or client-cursored ResultSets.
abstract class CursorInitializer extends TDSTokenHandler {
abstract int getRowCount();
abstract int getServerCursorId();
private StreamColumns columnMetaData = null;
private StreamColInfo colInfo = null;
private StreamTabName tabName = null;
final Column[] buildColumns() throws SQLServerException {
return columnMetaData.buildColumns(colInfo, tabName);
}
CursorInitializer(String name) {
super(name);
}
boolean onColInfo(TDSReader tdsReader) throws SQLServerException {
colInfo = new StreamColInfo();
colInfo.setFromTDS(tdsReader);
return true;
}
boolean onTabName(TDSReader tdsReader) throws SQLServerException {
tabName = new StreamTabName();
tabName.setFromTDS(tdsReader);
return true;
}
boolean onColMetaData(TDSReader tdsReader) throws SQLServerException {
columnMetaData = new StreamColumns(
Util.shouldHonorAEForRead(stmt.stmtColumnEncriptionSetting, stmt.connection));
columnMetaData.setFromTDS(tdsReader);
cekTable = columnMetaData.getCekTable();
return true;
}
}
// Server-cursor initializer expects a cursorID and row count to be
// returned in OUT parameters from the sp_cursor[prep]exec call.
// There should not be any rows present when initializing a server-cursored
// ResultSet (until/unless support for cursor auto-fetch is implemented).
final class ServerCursorInitializer extends CursorInitializer {
private final SQLServerStatement stmt;
final int getRowCount() {
return stmt.getServerCursorRowCount();
}
final int getServerCursorId() {
return stmt.getServerCursorId();
}
ServerCursorInitializer(SQLServerStatement stmt) {
super("ServerCursorInitializer");
this.stmt = stmt;
}
boolean onRetStatus(TDSReader tdsReader) throws SQLServerException {
// With server-cursored result sets, the column metadata is
// followed by a return status and cursor-related OUT parameters
// for the sp_cursor[prep]exec call. Two of those OUT parameters
// are the cursor ID and row count needed to construct this
// ResultSet.
stmt.consumeExecOutParam(tdsReader);
return true;
}
boolean onRetValue(TDSReader tdsReader) throws SQLServerException {
// The first OUT parameter after the sp_cursor[prep]exec OUT parameters
// is the start of the application OUT parameters. Leave parsing
// of them up to CallableStatement OUT param handlers.
return false;
}
}
// Client-cursor initializer expects 0 or more rows or a row-level error
// to follow the column metadata.
final class ClientCursorInitializer extends CursorInitializer {
private int rowCount = UNKNOWN_ROW_COUNT;
final int getRowCount() {
return rowCount;
}
final int getServerCursorId() {
return 0;
}
ClientCursorInitializer() {
super("ClientCursorInitializer");
}
boolean onRow(TDSReader tdsReader) throws SQLServerException {
// A ROW token indicates the start of the fetch buffer
return false;
}
boolean onNBCRow(TDSReader tdsReader) throws SQLServerException {
// A NBCROW token indicates the start of the fetch buffer
return false;
}
boolean onError(TDSReader tdsReader) throws SQLServerException {
// An ERROR token indicates a row error in lieu of a row.
// In this case, the row error is in lieu of the first row.
// Stop parsing and let the fetch buffer handle the error.
rowCount = 0;
return false;
}
boolean onDone(TDSReader tdsReader) throws SQLServerException {
// When initializing client-cursored ResultSets, a DONE token
// following the column metadata indicates an empty result set.
rowCount = 0;
// Continue to read the error message if DONE packet has error flag
int packetType = tdsReader.peekTokenType();
if (TDS.TDS_DONE == packetType) {
short status = tdsReader.peekStatusFlag();
// check if status flag has DONE_ERROR set i.e., 0x2
if ((status & 0x0002) != 0) {
// Consume the DONE packet if there is error
StreamDone doneToken = new StreamDone();
doneToken.setFromTDS(tdsReader);
return true;
}
}
return false;
}
}
this.stmt = stmtIn;
this.maxRows = stmtIn.maxRows;
this.fetchSize = stmtIn.nFetchSize;
this.fetchDirection = stmtIn.nFetchDirection;
CursorInitializer initializer = stmtIn.executedSqlDirectly ? (new ClientCursorInitializer())
: (new ServerCursorInitializer(stmtIn));
TDSParser.parse(stmtIn.resultsReader(), initializer);
this.columns = initializer.buildColumns();
this.rowCount = initializer.getRowCount();
this.serverCursorId = initializer.getServerCursorId();
// If this result set does not use a server cursor, then the result set rows
// (if any) are already present in the fetch buffer at which the statement's
// TDSReader now points.
//
// If this result set uses a server cursor, then without support for server
// cursor autofetch, there are initially no rows with which to populate the
// fetch buffer. The app will have to do a server cursor fetch first.
this.tdsReader = (0 == serverCursorId) ? stmtIn.resultsReader() : null;
this.fetchBuffer = new FetchBuffer();
this.scrollWindow = isForwardOnly() ? null : new ScrollWindow(fetchSize);
this.numFetchedRows = 0;
// increment opened resultset counter
stmtIn.incrResultSetCount();
if (logger.isLoggable(java.util.logging.Level.FINE)) {
logger.fine(toString() + " created by (" + stmt.toString() + ")");
}
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
loggerExternal.entering(getClassNameLogging(), "isWrapperFor");
boolean f = iface.isInstance(this);
loggerExternal.exiting(getClassNameLogging(), "isWrapperFor", f);
return f;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
loggerExternal.entering(getClassNameLogging(), "unwrap");
T t;
try {
t = iface.cast(this);
} catch (ClassCastException e) {
throw new SQLServerException(e.getMessage(), e);
}
loggerExternal.exiting(getClassNameLogging(), "unwrap", t);
return t;
}
private SQLServerException rowErrorException = null;
/**
* Checks if the result set is closed
*
* @throws SQLServerException
*/
void checkClosed() throws SQLServerException {
if (isClosed) {
SQLServerException.makeFromDriverError(null, null, SQLServerException.getErrString("R_resultsetClosed"),
null, false);
}
stmt.checkClosed();
// This ResultSet isn't closed, but also check whether it's effectively dead
// due to a row error. Once a ResultSet encounters a row error, nothing more
// can be done with it other than closing it.
if (null != rowErrorException)
throw rowErrorException;
}
@Override
public boolean isClosed() throws SQLException {
loggerExternal.entering(getClassNameLogging(), "isClosed");
boolean result = isClosed || stmt.isClosed();
loggerExternal.exiting(getClassNameLogging(), "isClosed", result);
return result;
}
/**
* Called by ResultSet API methods to disallow method use on forward only result sets.
*
* @throws SQLException
* if the result set is forward only.
* @throws SQLFeatureNotSupportedException
*/
private void throwNotScrollable() throws SQLException {
SQLServerException.makeFromDriverError(stmt.connection, this,
SQLServerException.getErrString("R_requestedOpNotSupportedOnForward"), null, true);
}
protected boolean isForwardOnly() {
return TYPE_SS_DIRECT_FORWARD_ONLY == stmt.getSQLResultSetType()
|| TYPE_SS_SERVER_CURSOR_FORWARD_ONLY == stmt.getSQLResultSetType();
}
private boolean isDynamic() {
return 0 != serverCursorId && TDS.SCROLLOPT_DYNAMIC == stmt.getCursorType();
}
private void verifyResultSetIsScrollable() throws SQLException {
if (isForwardOnly())
throwNotScrollable();
}
/**
* Called by ResultSet API methods to disallow method use on read only result sets.
*
* @throws SQLServerException
* if the result set is read only.
*/
private void throwNotUpdatable() throws SQLServerException {
SQLServerException.makeFromDriverError(stmt.connection, this,
SQLServerException.getErrString("R_resultsetNotUpdatable"), null, true);
}
private void verifyResultSetIsUpdatable() throws SQLServerException {
if (CONCUR_READ_ONLY == stmt.resultSetConcurrency || 0 == serverCursorId)
throwNotUpdatable();
}
/**
* Returns whether the result set has a current row.
*
* @return true if there is a current row
* @return false if the result set is positioned before the first row or after the last row.
*/
private boolean hasCurrentRow() {
return BEFORE_FIRST_ROW != currentRow && AFTER_LAST_ROW != currentRow;
}
/**
* Verifies whether this result set has a current row.
*
* This check DOES NOT consider whether the cursor is on the insert row. The result set may or may not have a
* current row regardless whether the cursor is on the insert row. Consider the following scenarios:
*
* beforeFirst(); moveToInsertRow(); relative(1); No current row to move relative to. Throw "no current row"
* exception.
*
* first(); moveToInsertRow(); relative(1); Call to relative moves off of the insert row one row past the current
* row. That is, the cursor ends up on the second row of the result set.
*
* @throws SQLServerException
* if the result set has no current row
*/
private void verifyResultSetHasCurrentRow() throws SQLServerException {
if (!hasCurrentRow()) {
SQLServerException.makeFromDriverError(stmt.connection, stmt,
SQLServerException.getErrString("R_resultsetNoCurrentRow"), null, true);
}
}
/**
* Called by ResultSet API methods to disallow method use when cursor is on a deleted row.
*
* @throws SQLServerException
* if the cursor is not on an updatable row.
*/
private void verifyCurrentRowIsNotDeleted(String errResource) throws SQLServerException {
if (currentRowDeleted()) {
SQLServerException.makeFromDriverError(stmt.connection, stmt, SQLServerException.getErrString(errResource),
null, true);
}
}
/**
* Called by ResultSet API methods to disallow method use when the column index is not in the range of columns
* returned in the results.
*
* @throws SQLServerException
* if the column index is out of bounds
*/
private void verifyValidColumnIndex(int index) throws SQLServerException {
int nCols = columns.length;
// Rows that come back from server side cursors tack on a "hidden" ROWSTAT column
// (used to detect deletes from a keyset) at the end of each row. Don't include
// that column in the list of valid columns.
if (0 != serverCursorId)
--nCols;
if (index < 1 || index > nCols) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_indexOutOfRange"));
Object[] msgArgs = {index};
SQLServerException.makeFromDriverError(stmt.connection, stmt, form.format(msgArgs), "07009", false);
}
}
/**
* Called by ResultSet API methods to disallow method use when cursor is on the insert row.
*
* @throws SQLServerException
* if the cursor is on the insert row.
*/
private void verifyResultSetIsNotOnInsertRow() throws SQLServerException {
if (isOnInsertRow) {
SQLServerException.makeFromDriverError(stmt.connection, stmt,
SQLServerException.getErrString("R_mustNotBeOnInsertRow"), null, true);
}
}
private void throwUnsupportedCursorOp() throws SQLServerException {
// Absolute positioning of dynamic cursors is unsupported.
SQLServerException.makeFromDriverError(stmt.connection, this,
SQLServerException.getErrString("R_unsupportedCursorOperation"), null, true);
}
/**
* Closes the result set.
*
* 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.
*/
private void closeInternal() {
// Calling close on a closed ResultSet is a no-op per JDBC spec
if (isClosed)
return;
// Mark this ResultSet as closed, then clean up.
isClosed = true;
// Discard the current fetch buffer contents.
discardFetchBuffer();
// Close the server cursor if there is one.
closeServerCursor();
// Clean up client-side state
metaData = null;
// decrement opened resultset counter
stmt.decrResultSetCount();
}
@Override
public void close() throws SQLServerException {
loggerExternal.entering(getClassNameLogging(), "close");
if (loggerExternal.isLoggable(Level.FINER) && Util.isActivityTraceOn()) {
loggerExternal.finer(toString() + " ActivityId: " + ActivityCorrelator.getNext().toString());
}
closeInternal();
loggerExternal.exiting(getClassNameLogging(), "close");
}
/**
* Finds a column index given a column name.
*
* @param userProvidedColumnName
* the name of the column
* @throws SQLServerException
* If any errors occur.
* @return the column index
*/
@Override
public int findColumn(String userProvidedColumnName) throws SQLServerException {
loggerExternal.entering(getClassNameLogging(), "findColumn", userProvidedColumnName);
checkClosed();
Integer value = columnNames.get(userProvidedColumnName);
if (null != value) {
return value;
}
// In order to be as accurate as possible when locating column name
// indexes, as well as be deterministic when running on various client
// locales, we search for column names using the following scheme:
// Per JDBC spec 27.1.5 "if there are multiple columns with the same name
// [findColumn] will return the value of the first matching name".
// 1. Search using case-sensitive non-locale specific (binary) compare first.
// 2. Search using case-insensitive, non-locale specific (binary) compare last.
// NOTE: Any attempt to use a locale aware comparison will fail because:
//
// 1. SQL allows any valid UNICODE characters in the column name.
// 2. SQL does not store any locale info associated with the column name.
// 3. We cannot second guess the developer and decide to use VM locale or
// database default locale when making comparisons, this would produce
// inconsistent results on different clients or different servers.
// Search using case-sensitive, non-locale specific (binary) compare.
// If the user supplies a true match for the column name, we will find it here.
for (int i = 0; i < columns.length; i++) {
if (columns[i].getColumnName().equals(userProvidedColumnName)) {
columnNames.put(userProvidedColumnName, i + 1);
loggerExternal.exiting(getClassNameLogging(), "findColumn", i + 1);
return i + 1;
}
}
// Check for case-insensitive match using a non-locale aware method.
// Per JDBC spec, 27.3 "The driver will do a case-insensitive search for
// columnName in it's attempt to map it to the column's index".
// Use VM supplied String.equalsIgnoreCase to do the "case-insensitive search".
for (int i = 0; i < columns.length; i++) {
if (columns[i].getColumnName().equalsIgnoreCase(userProvidedColumnName)) {
columnNames.put(userProvidedColumnName, i + 1);
loggerExternal.exiting(getClassNameLogging(), "findColumn", i + 1);
return i + 1;
}
}
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidColumnName"));
Object[] msgArgs = {userProvidedColumnName};
SQLServerException.makeFromDriverError(stmt.connection, stmt, form.format(msgArgs), "07009", false);
return 0;
}
final int getColumnCount() {
int nCols = columns.length;
if (0 != serverCursorId)
nCols--; // Do not include SQL Server's automatic rowstat column
return nCols;
}
final Column getColumn(int columnIndex) throws SQLServerException {
// Close any stream that might be open on the current column
// before moving to another one.
if (null != activeStream) {
try {
fillLOBs();
activeStream.close();
} catch (IOException e) {
SQLServerException.makeFromDriverError(null, null, e.getMessage(), null, true);
} finally {
activeStream = null;
}
}
return columns[columnIndex - 1];
}
/**
* Initializes null compressed columns only when the row type is NBCROW and if the
* areNullCompressedColumnsInitialized is false. In all other cases this will be a no-op.
*
* @throws SQLServerException
*/
private void initializeNullCompressedColumns() throws SQLServerException {
if (resultSetCurrentRowType.equals(RowType.NBCROW) && (!areNullCompressedColumnsInitialized)) {
int columnNo = 0;
// no of bytes to be read from the stream
int noOfBytes = ((this.columns.length - 1) >> 3) + 1;// equivalent of
// (int)Math.ceil(this.columns.length/8.0) and gives
// better perf
for (int byteNo = 0; byteNo < noOfBytes; byteNo++) {
int byteValue = tdsReader.readUnsignedByte();
// if this byte is 0, skip to the next byte
// and increment the column number by 8(no of bits)
if (byteValue == 0) {
columnNo = columnNo + 8;
continue;
}
for (int bitNo = 0; bitNo < 8 && columnNo < this.columns.length; bitNo++, columnNo++) {
if ((byteValue & (1 << bitNo)) != 0) {
this.columns[columnNo].initFromCompressedNull();
}
}
}
areNullCompressedColumnsInitialized = true;
}
}
private Column loadColumn(int index) throws SQLServerException {
assert 1 <= index && index <= columns.length;
initializeNullCompressedColumns();
// Skip any columns between the last indexed column and the target column,
// retaining their values so they can be retrieved later.
if (index > lastColumnIndex && (!this.columns[index - 1].isInitialized()))
skipColumns(index - lastColumnIndex, false);
// Then return the target column
return getColumn(index);
}
/**
* Clears result set warnings.
*
* @throws SQLServerException
* when an error occurs
*/
@Override
public void clearWarnings() throws SQLServerException {
loggerExternal.entering(getClassNameLogging(), "clearWarnings");
loggerExternal.exiting(getClassNameLogging(), "clearWarnings");
}
/* ----------------- JDBC API methods ------------------ */
private void moverInit() throws SQLServerException {
fillLOBs();
cancelInsert();
cancelUpdates();
}
@Override
public boolean relative(int rows) throws SQLException {
if (loggerExternal.isLoggable(java.util.logging.Level.FINER))
loggerExternal.entering(getClassNameLogging(), "relative", rows);
if (logger.isLoggable(java.util.logging.Level.FINER))
logger.finer(toString() + " rows:" + rows + logCursorState());
checkClosed();
// From JDBC spec:
// Throws SQLException if (1) there is no current row or (2)
// the type of this ResultSet object is TYPE_FORWARD_ONLY.
verifyResultSetIsScrollable();
verifyResultSetHasCurrentRow();
moverInit();
moveRelative(rows);
boolean value = hasCurrentRow();
loggerExternal.exiting(getClassNameLogging(), "relative", value);
return value;
}
private void moveRelative(int rowsToMove) throws SQLServerException {
// Relative moves must be from somewhere within the result set
assert hasCurrentRow();
// If rows is 0, the cursor's position does not change.
if (0 == rowsToMove)
return;
if (rowsToMove > 0)
moveForward(rowsToMove);
else
moveBackward(rowsToMove);
}
private void moveForward(int rowsToMove) throws SQLServerException {
assert hasCurrentRow();
assert rowsToMove > 0;
// If there's a chance that the move can happen just in the scroll window then try that first
if (scrollWindow.getRow() + rowsToMove <= scrollWindow.getMaxRows()) {
int rowsMoved = 0;
while (rowsToMove > 0 && scrollWindow.next(this)) {
++rowsMoved;
--rowsToMove;
}
// Update the current row
updateCurrentRow(rowsMoved);
// If the move happened entirely in the scroll window, then we're done.
if (0 == rowsToMove)
return;
}
// All or part of the move lies outside the scroll window.
assert rowsToMove > 0;
// For client-cursored result sets, where the fetch buffer contains all of the rows, moves outside of
// the scroll window are done via an absolute in the fetch buffer.
if (0 == serverCursorId) {
assert UNKNOWN_ROW != currentRow;
currentRow = clientMoveAbsolute(currentRow + rowsToMove);
return;
}
// For server-cursored result sets (where the fetch buffer and scroll window are the same size),
// moves outside the scroll window require fetching more rows from the server.
//
// A few words on fetching strategy with server cursors
// There is an assumption here that moving past the current position is an indication
// that the result set is being traversed in forward order, so it makes sense to grab a
// block of fetchSize rows from the server, starting at the desired location, to maximize
// the number of rows that can be consumed before the next server fetch. That assumption
// isn't necessarily true.
if (1 == rowsToMove)
doServerFetch(TDS.FETCH_NEXT, 0, fetchSize);
else
doServerFetch(TDS.FETCH_RELATIVE, rowsToMove + scrollWindow.getRow() - 1, fetchSize);
// If the new fetch buffer returned no rows, then the cursor has reached the end of the result set.
if (!scrollWindow.next(this)) {
currentRow = AFTER_LAST_ROW;
return;
}
// The move succeeded, so update the current row.
updateCurrentRow(rowsToMove);
}
private void moveBackward(int rowsToMove) throws SQLServerException {
assert hasCurrentRow();
assert rowsToMove < 0;
// If the move is contained in scroll window then handle it there.
if (scrollWindow.getRow() + rowsToMove >= 1) {
for (int rowsMoved = 0; rowsMoved > rowsToMove; --rowsMoved)
scrollWindow.previous(this);
updateCurrentRow(rowsToMove);
return;
}
// The move lies outside the scroll window.
// For client-cursored result sets, where the fetch buffer contains all of the rows, moves outside of
// the scroll window are done via an absolute move in the fetch buffer.
if (0 == serverCursorId) {
assert UNKNOWN_ROW != currentRow;
// Relative moves to before the first row must be handled here; a negative argument
// to clientMoveAbsolute is interpreted as relative to the last row, not the first.
if (currentRow + rowsToMove < 1) {
moveBeforeFirst();
} else {
currentRow = clientMoveAbsolute(currentRow + rowsToMove);
}
return;
}
// For server-cursored result sets (where the fetch buffer and scroll window are the same size),
// moves outside the scroll window require fetching more rows from the server.
//
// A few words on fetching strategy with server cursors
// There is an assumption here that moving to the previous row is an indication
// that the result set is being traversed in reverse order, so it makes sense to grab a
// block of fetchSize rows from the server, ending with the desired location, to maximize
// the number of rows that can be consumed before the next server fetch. That assumption
// isn't necessarily true.
//
// Also, when moving further back than the previous row, it is not generally feasible to
// try to fetch a block of rows ending with the target row, since a move far enough back
// that the start of the fetch buffer would be before the first row of the result set would
// position the cursor before the first row and return no rows, even though the target row
// may not be before the first row. Instead, such moves are done so that the target row
// is the first row in the returned block of rows rather than the last row.
if (-1 == rowsToMove) {
doServerFetch(TDS.FETCH_PREV_NOADJUST, 0, fetchSize);
// If the new fetch buffer returned no rows, then the cursor has reached the start of the result set.
if (!scrollWindow.next(this)) {
currentRow = BEFORE_FIRST_ROW;
return;
}
// Scroll past the last of the returned rows, and ...
while (scrollWindow.next(this));
// back up one row.
scrollWindow.previous(this);
} else {
doServerFetch(TDS.FETCH_RELATIVE, rowsToMove + scrollWindow.getRow() - 1, fetchSize);
// If the new fetch buffer returned no rows, then the cursor has reached the start of the result set.
if (!scrollWindow.next(this)) {
currentRow = BEFORE_FIRST_ROW;
return;
}
}
// The move succeeded, so update the current row.
updateCurrentRow(rowsToMove);
}
/**
* Updates the current row's position if known.
*
* If known, the current row is assumed to be at a valid position somewhere in the ResultSet. That is, the current
* row is not before the first row or after the last row.
*/
private void updateCurrentRow(int rowsToMove) {
if (UNKNOWN_ROW != currentRow) {
assert currentRow >= 1;
currentRow += rowsToMove;
assert currentRow >= 1;
}
}
/**
* Moves the cursor to the first row of this ResultSet object initially, then subsequent calls move the cursor to
* the second row, the third row, and so on.
*
* @return false when there are no more rows to read
*/
@Override
public boolean next() throws SQLServerException {
loggerExternal.entering(getClassNameLogging(), "next");
if (loggerExternal.isLoggable(Level.FINER) && Util.isActivityTraceOn()) {
loggerExternal.finer(toString() + " ActivityId: " + ActivityCorrelator.getNext().toString());
}
if (logger.isLoggable(java.util.logging.Level.FINER))
logger.finer(toString() + logCursorState());
checkClosed();
moverInit();
// If the cursor is already positioned after the last row in this result set
// then it can't move any farther forward.
if (AFTER_LAST_ROW == currentRow) {
loggerExternal.exiting(getClassNameLogging(), "next", false);
return false;
}