-
Notifications
You must be signed in to change notification settings - Fork 227
Expand file tree
/
Copy pathFetch.java
More file actions
995 lines (873 loc) · 31.6 KB
/
Fetch.java
File metadata and controls
995 lines (873 loc) · 31.6 KB
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
/*
* Jython Database Specification API 2.0
*
*
* Copyright (c) 2001 brian zimmer <bzimmer@ziclix.com>
*
*/
package com.ziclix.python.sql;
import org.python.core.Py;
import org.python.core.PyException;
import org.python.core.PyInteger;
import org.python.core.PyList;
import org.python.core.PyObject;
import org.python.core.PyTuple;
import org.python.core.Traverseproc;
import org.python.core.Visitproc;
import java.sql.CallableStatement;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Types;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
/**
* <p>The responsibility of a Fetch instance is to manage the iteration of a
* ResultSet. Two different alogorithms are available: static or dynamic.</p>
*
* <p><b>Static</b> The static variety iterates the entire set immediately,
* creating the necessary Jython objects and storing them. It is able to
* immediately close the ResultSet so a call to close() is essentially a no-op
* from a database resource perspective (it does clear the results list however).
* This approach also allows for the correct rowcount to be determined since
* the entire result set has been iterated.</p>
*
* <p><b>Dynamic</b> The dynamic variety iterates the result set only as requested.
* This holds a bit truer to the intent of the API as the fetch*() methods actually
* fetch when instructed. This is especially useful for managing exeedingly large
* results, but is unable to determine the rowcount without having worked through
* the entire result set. The other disadvantage is the ResultSet remains open
* throughout the entire iteration. So the tradeoff is in open database resources
* versus JVM resources since the application can keep constant space if it doesn't
* require the entire result set be presented as one.</p>
*
* @author brian zimmer
*/
abstract public class Fetch implements Traverseproc {
/**
* The total number of rows in the result set.
* <p>
* Note: since JDBC provides no means to get this information without iterating
* the entire result set, only those fetches which build the result statically
* will have an accurate row count.
*/
protected int rowcount;
/**
* The current row of the cursor (-1 if off either end).
*/
protected int rownumber;
/**
* Field cursor
*/
private DataHandler datahandler;
/**
* Field description
*/
protected PyObject description;
/**
* A list of warning listeners.
*/
private List<WarningListener> listeners;
/**
* Constructor Fetch
*
* @param datahandler
*/
protected Fetch(DataHandler datahandler) {
this.rowcount = -1;
this.rownumber = -1;
this.description = Py.None;
this.datahandler = datahandler;
this.listeners = new ArrayList<WarningListener>(3);
}
/**
* Method newFetch
*
* @param datahandler
* @param dynamic
* @return Fetch
*/
public static Fetch newFetch(DataHandler datahandler, boolean dynamic) {
if (dynamic) {
return new DynamicFetch(datahandler);
} else {
return new StaticFetch(datahandler);
}
}
/**
* The number of rows in the current result set.
*/
public int getRowCount() {
return this.rowcount;
}
/**
* The description of each column, in order, for the data in the result
* set.
*/
public PyObject getDescription() {
return this.description;
}
/**
* Create the results after a successful execution and manages the result set.
*
* @param resultSet
*/
abstract public void add(ResultSet resultSet);
/**
* Create the results after a successful execution and manages the result set.
* Optionally takes a set of JDBC-indexed columns to automatically set to None
* primarily to support getTypeInfo() which sets a column type of a number but
* doesn't use the value so a driver is free to put anything it wants there.
*
* @param resultSet
* @param skipCols JDBC-indexed set of columns to be skipped
*/
abstract public void add(ResultSet resultSet, Set<Integer> skipCols);
/**
* Method add
*
* @param callableStatement
* @param procedure
* @param params
*/
abstract public void add(CallableStatement callableStatement, Procedure procedure,
PyObject params);
/**
* Fetch the next row of a query result set, returning a single sequence,
* or None when no more data is available.
* <p>
* An Error (or subclass) exception is raised if the previous call to
* executeXXX() did not produce any result set or no call was issued yet.
*
* @return a single sequence from the result set, or None when no more data is available
*/
public PyObject fetchone() {
PyObject sequence = fetchmany(1);
if (sequence.__len__() == 1) {
return sequence.__getitem__(0);
} else {
return Py.None;
}
}
/**
* Fetch all (remaining) rows of a query result, returning them as a sequence
* of sequences (e.g. a list of tuples). Note that the cursor's arraysize attribute
* can affect the performance of this operation.
* <p>
* An Error (or subclass) exception is raised if the previous call to executeXXX()
* did not produce any result set or no call was issued yet.
*
* @return a sequence of sequences from the result set, or None when no more data is available
*/
public abstract PyObject fetchall();
/**
* Fetch the next set of rows of a query result, returning a sequence of
* sequences (e.g. a list of tuples). An empty sequence is returned when
* no more rows are available.
* <p>
* The number of rows to fetch per call is specified by the parameter. If
* it is not given, the cursor's arraysize determines the number of rows
* to be fetched. The method should try to fetch as many rows as indicated
* by the size parameter. If this is not possible due to the specified number
* of rows not being available, fewer rows may be returned.
* <p>
* An Error (or subclass) exception is raised if the previous call to executeXXX()
* did not produce any result set or no call was issued yet.
* <p>
* Note there are performance considerations involved with the size parameter.
* For optimal performance, it is usually best to use the arraysize attribute.
* If the size parameter is used, then it is best for it to retain the same value
* from one fetchmany() call to the next.
*
* @return a sequence of sequences from the result set, or None when no more data is available
*/
public abstract PyObject fetchmany(int size);
/**
* Move the result pointer to the next set if available.
*
* @return true if more sets exist, else None
*/
public abstract PyObject nextset();
/**
* Scroll the cursor in the result set to a new position according
* to mode.
* <p>
* If mode is 'relative' (default), value is taken as offset to
* the current position in the result set, if set to 'absolute',
* value states an absolute target position.
* <p>
* An IndexError should be raised in case a scroll operation would
* leave the result set. In this case, the cursor position is left
* undefined (ideal would be to not move the cursor at all).
* <p>
* Note: This method should use native scrollable cursors, if
* available, or revert to an emulation for forward-only
* scrollable cursors. The method may raise NotSupportedErrors to
* signal that a specific operation is not supported by the
* database (e.g. backward scrolling).
*
* @param value
* @param mode
*/
public abstract void scroll(int value, String mode);
/**
* Cleanup any resources.
*/
public void close() throws SQLException {
this.listeners.clear();
}
/**
* Builds a tuple containing the meta-information about each column.
* <p>
* (name, type_code, display_size, internal_size, precision, scale, null_ok)
* <p>
* precision and scale are only available for numeric types
*/
protected PyObject createDescription(ResultSetMetaData meta) throws SQLException {
PyObject metadata = new PyList();
for (int i = 1; i <= meta.getColumnCount(); i++) {
PyObject[] a = new PyObject[7];
a[0] = Py.newUnicode(meta.getColumnLabel(i));
a[1] = Py.newInteger(meta.getColumnType(i));
a[2] = Py.newInteger(meta.getColumnDisplaySize(i));
a[3] = Py.None;
switch (meta.getColumnType(i)) {
case Types.BIGINT:
case Types.BIT:
case Types.DECIMAL:
case Types.NUMERIC:
case Types.DOUBLE:
case Types.FLOAT:
case Types.INTEGER:
case Types.SMALLINT:
case Types.TINYINT:
a[4] = Py.newInteger(meta.getPrecision(i));
a[5] = Py.newInteger(meta.getScale(i));
break;
default :
a[4] = Py.None;
a[5] = Py.None;
break;
}
a[6] = Py.newInteger(meta.isNullable(i));
((PyList) metadata).append(new PyTuple(a));
}
return metadata;
}
/**
* Builds a tuple containing the meta-information about each column.
* <p>
* (name, type_code, display_size, internal_size, precision, scale, null_ok)
* <p>
* precision and scale are only available for numeric types
*/
protected PyObject createDescription(Procedure procedure) throws SQLException {
PyObject metadata = new PyList();
for (int i = 0, len = procedure.columns.__len__(); i < len; i++) {
PyObject column = procedure.columns.__getitem__(i);
int colType = column.__getitem__(Procedure.COLUMN_TYPE).asInt();
switch (colType) {
case DatabaseMetaData.procedureColumnReturn:
PyObject[] a = new PyObject[7];
a[0] = column.__getitem__(Procedure.NAME);
a[1] = column.__getitem__(Procedure.DATA_TYPE);
a[2] = Py.newInteger(-1);
a[3] = column.__getitem__(Procedure.LENGTH);
switch (a[1].asInt()) {
case Types.BIGINT:
case Types.BIT:
case Types.DECIMAL:
case Types.DOUBLE:
case Types.FLOAT:
case Types.INTEGER:
case Types.SMALLINT:
a[4] = column.__getitem__(Procedure.PRECISION);
a[5] = column.__getitem__(Procedure.SCALE);
break;
default :
a[4] = Py.None;
a[5] = Py.None;
break;
}
int nullable = column.__getitem__(Procedure.NULLABLE).asInt();
a[6] = (nullable == DatabaseMetaData.procedureNullable) ? Py.One : Py.Zero;
((PyList) metadata).append(new PyTuple(a));
break;
}
}
return metadata;
}
/**
* Method createResults
*
* @param callableStatement
* @param procedure
* @param params
* @return PyObject
* @throws SQLException
*/
protected PyObject createResults(CallableStatement callableStatement, Procedure procedure,
PyObject params) throws SQLException {
PyList results = new PyList();
for (int i = 0, j = 0, len = procedure.columns.__len__(); i < len; i++) {
PyObject obj = Py.None;
PyObject column = procedure.columns.__getitem__(i);
int colType = column.__getitem__(Procedure.COLUMN_TYPE).asInt();
int dataType = column.__getitem__(Procedure.DATA_TYPE).asInt();
switch (colType) {
case DatabaseMetaData.procedureColumnIn:
j++;
break;
case DatabaseMetaData.procedureColumnOut:
case DatabaseMetaData.procedureColumnInOut:
obj = datahandler.getPyObject(callableStatement, i + 1, dataType);
params.__setitem__(j++, obj);
break;
case DatabaseMetaData.procedureColumnReturn:
obj = datahandler.getPyObject(callableStatement, i + 1, dataType);
// Oracle sends ResultSets as a return value
Object rs = obj.__tojava__(ResultSet.class);
if (rs == Py.NoConversion) {
results.append(obj);
} else {
add((ResultSet) rs);
}
break;
}
}
if (results.__len__() == 0) {
return results;
}
PyList ret = new PyList();
ret.append(PyTuple.fromIterable(results));
return ret;
}
/**
* Creates the results of a query. Iterates through the list and builds the tuple.
*
* @param set result set
* @param skipCols set of JDBC-indexed columns to automatically set to None
* @return a list of tuples of the results
* @throws SQLException
*/
protected PyList createResults(ResultSet set, Set<Integer> skipCols, PyObject metaData)
throws SQLException {
PyList res = new PyList();
while (set.next()) {
PyObject tuple = createResult(set, skipCols, metaData);
res.append(tuple);
}
return res;
}
/**
* Creates the individual result row from the current ResultSet row.
*
* @param set result set
* @param skipCols set of JDBC-indexed columns to automatically set to None
* @return a tuple of the results
* @throws SQLException
*/
protected PyTuple createResult(ResultSet set, Set<Integer> skipCols, PyObject metaData)
throws SQLException {
int descriptionLength = metaData.__len__();
PyObject[] row = new PyObject[descriptionLength];
for (int i = 0; i < descriptionLength; i++) {
if (skipCols != null && skipCols.contains(i + 1)) {
row[i] = Py.None;
} else {
int type = ((PyInteger) metaData.__getitem__(i).__getitem__(1)).getValue();
row[i] = datahandler.getPyObject(set, i + 1, type);
}
}
SQLWarning warning = set.getWarnings();
if (warning != null) {
fireWarning(warning);
}
return new PyTuple(row);
}
protected void fireWarning(SQLWarning warning) {
WarningEvent event = new WarningEvent(this, warning);
for (WarningListener listener : listeners) {
try {
listener.warning(event);
} catch (Throwable t) {
// ok
}
}
}
public void addWarningListener(WarningListener listener) {
this.listeners.add(listener);
}
public boolean removeWarningListener(WarningListener listener) {
return this.listeners.remove(listener);
}
/* Traverseproc support for Fetch */
public int traverse(Visitproc visit, Object arg) {
int retVal = visit.visit(description, arg);
if (retVal != 0) {
return retVal;
}
if (listeners != null) {
for (WarningListener obj: listeners) {
if (obj != null) {
if (obj instanceof PyObject) {
retVal = visit.visit((PyObject) obj, arg);
if (retVal != 0) {
return retVal;
}
} else if (obj instanceof Traverseproc) {
retVal = ((Traverseproc) obj).traverse(visit, arg);
if (retVal != 0) {
return retVal;
}
}
}
}
}
return 0;
}
public boolean refersDirectlyTo(PyObject ob) throws UnsupportedOperationException {
if (ob == null) {
return false;
} else if (ob == description) {
return true;
} else {
throw new UnsupportedOperationException();
}
}
}
/**
* This version of fetch builds the results statically. This consumes more resources but
* allows for efficient closing of database resources because the contents of the result
* set are immediately consumed. It also allows for an accurate rowcount attribute, whereas
* a dynamic query is unable to provide this information until all the results have been
* consumed.
*/
class StaticFetch extends Fetch {
/**
* Field results
*/
protected List<PyObject> results;
/**
* Field descriptions
*/
protected List<PyObject> descriptions;
/**
* Construct a static fetch. The entire result set is iterated as it
* is added and the result set is immediately closed.
*/
public StaticFetch(DataHandler datahandler) {
super(datahandler);
this.results = new LinkedList<PyObject>();
this.descriptions = new LinkedList<PyObject>();
}
/**
* Method add
*
* @param resultSet
*/
@Override
public void add(ResultSet resultSet) {
this.add(resultSet, null);
}
/**
* Method add
*
* @param resultSet
* @param skipCols
*/
@Override
public void add(ResultSet resultSet, Set<Integer> skipCols) {
try {
if (resultSet != null && resultSet.getMetaData() != null) {
PyObject metadata = this.createDescription(resultSet.getMetaData());
PyObject result = this.createResults(resultSet, skipCols, metadata);
this.results.add(result);
this.descriptions.add(metadata);
// we want the rowcount of the first result set
this.rowcount = this.results.get(0).__len__();
// we want the description of the first result set
this.description = this.descriptions.get(0);
// set the current rownumber
this.rownumber = 0;
}
} catch (PyException e) {
throw e;
} catch (Throwable e) {
throw zxJDBC.makeException(e);
} finally {
try {
resultSet.close();
} catch (Throwable e) {
}
}
}
/**
* Method add
*
* @param callableStatement
* @param procedure
* @param params
*/
@Override
public void add(CallableStatement callableStatement, Procedure procedure, PyObject params) {
try {
PyObject result = this.createResults(callableStatement, procedure, params);
if (result.__len__() > 0) {
this.results.add(result);
this.descriptions.add(this.createDescription(procedure));
// we want the rowcount of the first result set
this.rowcount = this.results.get(0).__len__();
// we want the description of the first result set
this.description = this.descriptions.get(0);
// set the current rownumber
this.rownumber = 0;
}
} catch (PyException e) {
throw e;
} catch (Throwable e) {
throw zxJDBC.makeException(e);
}
}
/**
* Fetch all (remaining) rows of a query result, returning them as a sequence
* of sequences (e.g. a list of tuples). Note that the cursor's arraysize attribute
* can affect the performance of this operation.
* <p>
* An Error (or subclass) exception is raised if the previous call to executeXXX()
* did not produce any result set or no call was issued yet.
*
* @return a sequence of sequences from the result set, or an empty sequence when
* no more data is available
*/
@Override
public PyObject fetchall() {
return fetchmany(this.rowcount);
}
/**
* Fetch the next set of rows of a query result, returning a sequence of
* sequences (e.g. a list of tuples). An empty sequence is returned when
* no more rows are available.
* <p>
* The number of rows to fetch per call is specified by the parameter. If
* it is not given, the cursor's arraysize determines the number of rows
* to be fetched. The method should try to fetch as many rows as indicated
* by the size parameter. If this is not possible due to the specified number
* of rows not being available, fewer rows may be returned.
* <p>
* An Error (or subclass) exception is raised if the previous call to executeXXX()
* did not produce any result set or no call was issued yet.
* <p>
* Note there are performance considerations involved with the size parameter.
* For optimal performance, it is usually best to use the arraysize attribute.
* If the size parameter is used, then it is best for it to retain the same value
* from one fetchmany() call to the next.
*
* @return a sequence of sequences from the result set, or an empty sequence when
* no more data is available
*/
@Override
public PyObject fetchmany(int size) {
if (results == null || results.size() == 0) {
throw zxJDBC.makeException(zxJDBC.DatabaseError, "no results");
}
PyObject res = new PyList();
PyObject current = results.get(0);
if (size <= 0) {
size = this.rowcount;
}
if (this.rownumber < this.rowcount) {
res = current.__getslice__(Py.newInteger(this.rownumber),
Py.newInteger(this.rownumber + size), Py.One);
this.rownumber += size;
}
return res;
}
/**
* Method scroll
*
* @param value
* @param mode 'relative' or 'absolute'
*/
@Override
public void scroll(int value, String mode) {
int pos;
if ("relative".equals(mode)) {
pos = this.rownumber + value;
} else if ("absolute".equals(mode)) {
pos = value;
} else {
throw zxJDBC.makeException(zxJDBC.ProgrammingError, "invalid cursor scroll mode ["
+ mode + "]");
}
if (pos >= 0 && pos < this.rowcount) {
this.rownumber = pos;
} else {
throw zxJDBC.makeException(Py.IndexError, "cursor index [" + pos + "] out of range");
}
}
/**
* Move the result pointer to the next set if available.
*
* @return true if more sets exist, else None
*/
@Override
public PyObject nextset() {
PyObject next = Py.None;
if (results != null && results.size() > 1) {
this.results.remove(0);
this.descriptions.remove(0);
next = this.results.get(0);
this.description = this.descriptions.get(0);
this.rowcount = next.__len__();
this.rownumber = 0;
}
return next == Py.None ? Py.None : Py.One;
}
/**
* Remove the results.
*/
@Override
public void close() throws SQLException {
super.close();
this.rownumber = -1;
this.results.clear();
}
/* Traverseproc support for StaticFetch */
public int traverse(Visitproc visit, Object arg) {
int retVal = super.traverse(visit, arg);
if (retVal != 0) {
return retVal;
}
if (results != null) {
for (PyObject obj: results) {
if (obj != null) {
retVal = visit.visit((PyObject) obj, arg);
if (retVal != 0) {
return retVal;
}
}
}
}
if (descriptions != null) {
for (PyObject obj: descriptions) {
if (obj != null) {
retVal = visit.visit((PyObject) obj, arg);
if (retVal != 0) {
return retVal;
}
}
}
}
return 0;
}
public boolean refersDirectlyTo(PyObject ob) throws UnsupportedOperationException {
if (ob == null) {
return false;
}
if (results != null && results.contains(ob)) {
return true;
}
if (descriptions != null && descriptions.contains(ob)) {
return true;
}
return super.refersDirectlyTo(ob);
}
}
/**
* Dynamically construct the results from an execute*(). The static version builds the entire
* result set immediately upon completion of the query, however in some circumstances, this
* requires far too many resources to be efficient. In this version of the fetch the resources
* remain constant. The dis-advantage to this approach from an API perspective is its impossible
* to generate an accurate rowcount since not all the rows have been consumed.
*/
class DynamicFetch extends Fetch {
/**
* Field skipCols
*/
protected Set<Integer> skipCols;
/**
* Field resultSet
*/
protected ResultSet resultSet;
/**
* Construct a dynamic fetch.
*/
public DynamicFetch(DataHandler datahandler) {
super(datahandler);
}
/**
* Add the result set to the results. If more than one result
* set is attempted to be added, an Error is raised since JDBC
* requires that only one ResultSet be iterated for one Statement
* at any one time. Since this is a dynamic iteration, it precludes
* the addition of more than one result set.
*/
@Override
public void add(ResultSet resultSet) {
add(resultSet, null);
}
/**
* Add the result set to the results. If more than one result
* set is attempted to be added, an Error is raised since JDBC
* requires that only one ResultSet be iterated for one Statement
* at any one time. Since this is a dynamic iteration, it precludes
* the addition of more than one result set.
*/
@Override
public void add(ResultSet resultSet, Set<Integer> skipCols) {
if (this.resultSet != null) {
throw zxJDBC.makeException(zxJDBC.getString("onlyOneResultSet"));
}
try {
if (resultSet != null && resultSet.getMetaData() != null) {
if (this.description == Py.None) {
this.description = this.createDescription(resultSet.getMetaData());
}
this.resultSet = resultSet;
this.skipCols = skipCols;
// it would be more compliant if we knew the resultSet actually
// contained some rows, but since we don't make a stab at it so
// everything else looks better
this.rowcount = 0;
this.rownumber = 0;
}
} catch (PyException e) {
throw e;
} catch (Throwable e) {
throw zxJDBC.makeException(e);
}
}
/**
* Method add
*
* @param callableStatement
* @param procedure
* @param params
*/
@Override
public void add(CallableStatement callableStatement, Procedure procedure, PyObject params) {
throw zxJDBC.makeException(zxJDBC.NotSupportedError,
zxJDBC.getString("nocallprocsupport"));
}
/**
* Iterate the remaining contents of the ResultSet and return.
*/
@Override
public PyObject fetchall() {
return fetch(0, true);
}
/**
* Iterate up to size rows remaining in the ResultSet and return.
*/
@Override
public PyObject fetchmany(int size) {
return fetch(size, false);
}
/**
* Internal use only. If <i>all</i> is true, return everything
* that's left in the result set, otherwise return up to size. Fewer
* than size may be returned if fewer than size results are left in
* the set.
*/
private PyObject fetch(int size, boolean all) {
PyList res = new PyList();
if (this.resultSet == null) {
throw zxJDBC.makeException(zxJDBC.DatabaseError, "no results");
}
try {
all = (size < 0) ? true : all;
while ((size-- > 0 || all) && this.resultSet.next()) {
PyTuple tuple = createResult(this.resultSet, this.skipCols, this.description);
res.append(tuple);
this.rowcount++;
this.rownumber = this.resultSet.getRow();
}
} catch (AbstractMethodError e) {
throw zxJDBC.makeException(zxJDBC.NotSupportedError,
zxJDBC.getString("nodynamiccursors"));
} catch (PyException e) {
throw e;
} catch (Throwable e) {
throw zxJDBC.makeException(e);
}
return res;
}
/**
* Always returns None.
*/
@Override
public PyObject nextset() {
return Py.None;
}
/**
* Method scroll
*
* @param value
* @param mode
*/
@Override
public void scroll(int value, String mode) {
try {
int type = this.resultSet.getType();
if (type != ResultSet.TYPE_FORWARD_ONLY || value > 0) {
if ("relative".equals(mode)) {
if (value < 0) {
value = Math.abs(this.rownumber + value);
} else if (value > 0) {
value = this.rownumber + value + 1;
}
} else if ("absolute".equals(mode)) {
if (value < 0) {
throw zxJDBC.makeException(Py.IndexError, "cursor index [" + value
+ "] out of range");
}
} else {
throw zxJDBC.makeException(zxJDBC.ProgrammingError,
"invalid cursor scroll mode [" + mode + "]");
}
if (value == 0) {
this.resultSet.beforeFirst();
} else {
if (!this.resultSet.absolute(value)) {
throw zxJDBC.makeException(Py.IndexError, "cursor index [" + value
+ "] out of range");
}
}
// since .rownumber is the *next* row, then the JDBC value suits us fine
this.rownumber = this.resultSet.getRow();
} else {
String msg = "dynamic result set of type [" + type
+ "] does not support scrolling";
throw zxJDBC.makeException(zxJDBC.NotSupportedError, msg);
}
} catch (AbstractMethodError e) {
throw zxJDBC.makeException(zxJDBC.NotSupportedError,
zxJDBC.getString("nodynamiccursors"));
} catch (SQLException e) {
throw zxJDBC.makeException(e);
} catch (Throwable t) {
throw zxJDBC.makeException(t);
}
}
/**
* Close the underlying ResultSet.
*/
@Override
public void close() throws SQLException {
super.close();
if (this.resultSet == null) {
return;
}
this.rownumber = -1;
try {
this.resultSet.close();
} finally {
this.resultSet = null;
}
}
}