-
Notifications
You must be signed in to change notification settings - Fork 227
Expand file tree
/
Copy pathPyCursor.java
More file actions
1103 lines (987 loc) · 35.4 KB
/
PyCursor.java
File metadata and controls
1103 lines (987 loc) · 35.4 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
996
997
998
999
1000
/*
* Jython Database Specification API 2.0
*
*
* Copyright (c) 2001 brian zimmer <bzimmer@ziclix.com>
*
*/
package com.ziclix.python.sql;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
import java.util.List;
import org.python.core.ClassDictInit;
import org.python.core.Py;
import org.python.core.PyBuiltinMethodSet;
import org.python.core.PyDictionary;
import org.python.core.PyException;
import org.python.core.PyList;
import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.core.PyTuple;
import org.python.core.PyUnicode;
import org.python.core.Traverseproc;
import org.python.core.Visitproc;
import com.ziclix.python.sql.util.PyArgParser;
import org.python.core.ContextManager;
import org.python.core.ThreadState;
/**
* These objects represent a database cursor, which is used to manage the
* context of a fetch operation.
*
* @author brian zimmer
*/
public class PyCursor extends PyObject implements ClassDictInit, WarningListener,
ContextManager, Traverseproc {
/** Field fetch */
protected Fetch fetch;
/** Field closed */
private boolean closed;
/** Field arraysize */
protected int arraysize;
/** Field softspace */
protected int softspace;
/** Field rsType */
protected PyObject rsType;
/** Field rsConcur */
protected PyObject rsConcur;
/** Field warnings */
protected PyObject warnings;
/** Field warnings */
protected PyObject lastrowid;
/** Field updatecount */
protected PyObject updatecount;
/** Field dynamicFetch */
protected boolean dynamicFetch;
/** Field connection */
protected PyConnection connection;
/** Field datahandler */
protected DataHandler datahandler;
/** Field statement */
protected PyStatement statement;
// they are stateless instances, so we only need to instantiate it once
private static final DataHandler DATAHANDLER = DataHandler.getSystemDataHandler();
/**
* Create the cursor with a static fetch.
*
* @param connection
*/
PyCursor(PyConnection connection) {
this(connection, false);
}
/**
* Create the cursor, optionally choosing the type of fetch (static or dynamic).
* If dynamicFetch is true, then use a dynamic fetch.
*
* @param connection
* @param dynamicFetch
*/
PyCursor(PyConnection connection, boolean dynamicFetch) {
this.arraysize = 1;
this.softspace = 0;
this.closed = false;
this.rsType = Py.None;
this.rsConcur = Py.None;
this.connection = connection;
this.datahandler = DATAHANDLER;
this.dynamicFetch = dynamicFetch;
// constructs the appropriate Fetch among other things
this.clear();
}
/**
* Create the cursor, optionally choosing the type of fetch (static or dynamic).
* If dynamicFetch is true, then use a dynamic fetch.
* rsType and rsConcur are used to create the Statement if both are non-None
*
* @param connection
* @param dynamicFetch
* @param rsType
* @param rsConcur
*/
PyCursor(PyConnection connection, boolean dynamicFetch, PyObject rsType, PyObject rsConcur) {
this(connection, dynamicFetch);
this.rsType = rsType;
this.rsConcur = rsConcur;
}
/** Field __methods__ */
protected static PyList __methods__;
/** Field __members__ */
protected static PyList __members__;
static {
PyObject[] m = new PyObject[9];
m[0] = new PyString("close");
m[1] = new PyString("execute");
m[2] = new PyString("executemany");
m[3] = new PyString("fetchone");
m[4] = new PyString("fetchall");
m[5] = new PyString("fetchmany");
m[6] = new PyString("callproc");
m[7] = new PyString("next");
m[8] = new PyString("write");
__methods__ = new PyList(m);
m = new PyObject[11];
m[0] = new PyString("arraysize");
m[1] = new PyString("rowcount");
m[2] = new PyString("rownumber");
m[3] = new PyString("description");
m[4] = new PyString("datahandler");
m[5] = new PyString("warnings");
m[6] = new PyString("lastrowid");
m[7] = new PyString("updatecount");
m[8] = new PyString("softspace");
m[9] = new PyString("closed");
m[10] = new PyString("connection");
__members__ = new PyList(m);
}
/**
* String representation of the object.
*
* @return a string representation of the object.
*/
@Override
public String toString() {
return String.format("<PyCursor object at %s>", Py.idstr(this));
}
/**
* Sets the attribute name to value.
*
* @param name
* @param value
*/
@Override
public void __setattr__(String name, PyObject value) {
if ("arraysize".equals(name)) {
this.arraysize = value.asInt();
} else if ("softspace".equals(name)) {
this.softspace = value.asInt();
} else if ("datahandler".equals(name)) {
this.datahandler = (DataHandler)value.__tojava__(DataHandler.class);
} else {
super.__setattr__(name, value);
}
}
/**
* Gets the value of the attribute name.
*
* @param name
* @return the attribute for the given name
*/
@Override
public PyObject __findattr_ex__(String name) {
if ("arraysize".equals(name)) {
return Py.newInteger(arraysize);
} else if ("softspace".equals(name)) {
return Py.newInteger(softspace);
} else if ("__methods__".equals(name)) {
return __methods__;
} else if ("__members__".equals(name)) {
return __members__;
} else if ("description".equals(name)) {
return this.fetch.description;
} else if ("rowcount".equals(name)) {
return Py.newInteger(this.fetch.rowcount);
} else if ("rownumber".equals(name)) {
int rn = this.fetch.rownumber;
return (rn < 0) ? Py.None : Py.newInteger(rn);
} else if ("warnings".equals(name)) {
return warnings;
} else if ("lastrowid".equals(name)) {
return lastrowid;
} else if ("updatecount".equals(name)) {
return updatecount;
} else if ("datahandler".equals(name)) {
return Py.java2py(this.datahandler);
} else if ("dynamic".equals(name)) {
return this.dynamicFetch ? Py.One : Py.Zero;
} else if ("connection".equals(name)) {
return this.connection;
} else if ("closed".equals(name)) {
return Py.newBoolean(closed);
} else if ("callproc".equals(name)) {
try {
// dynamically decide on the the attribute based on the driver
if (!getMetaData().supportsStoredProcedures()) {
return null;
}
} catch (Throwable t) {}
}
return super.__findattr_ex__(name);
}
/**
* Initializes the object's namespace.
*
* @param dict
*/
static public void classDictInit(PyObject dict) {
dict.__setitem__("fetchmany", new CursorFunc("fetchmany", 0, 0, 1, "fetch specified number of rows"));
dict.__setitem__("close", new CursorFunc("close", 1, 0, "close the cursor"));
dict.__setitem__("fetchall", new CursorFunc("fetchall", 2, 0, "fetch all results"));
dict.__setitem__("fetchone", new CursorFunc("fetchone", 3, 0, "fetch the next result"));
dict.__setitem__("nextset", new CursorFunc("nextset", 4, 0, "return next set or None"));
dict.__setitem__("execute", new CursorFunc("execute", 5, 1, 4, "execute the sql expression"));
dict.__setitem__("setinputsizes", new CursorFunc("setinputsizes", 6, 1, "not implemented"));
dict.__setitem__("setoutputsize", new CursorFunc("setoutputsize", 7, 1, 2, "not implemented"));
dict.__setitem__("callproc", new CursorFunc("callproc", 8, 1, 4, "executes a stored procedure"));
dict.__setitem__("executemany", new CursorFunc("executemany", 9, 1, 3, "execute sql with the parameter list"));
dict.__setitem__("scroll", new CursorFunc("scroll", 10, 1, 2, "scroll the cursor in the result set to a new position according to mode"));
dict.__setitem__("write", new CursorFunc("write", 11, 1, "execute the sql written to this file-like object"));
dict.__setitem__("prepare", new CursorFunc("prepare", 12, 1, "prepare the sql statement for later execution"));
dict.__setitem__("__enter__", new CursorFunc("__enter__", 13, 0, 0, "__enter__"));
dict.__setitem__("__exit__", new CursorFunc("__exit__", 14, 3, 3, "__exit__"));
// hide from python
dict.__setitem__("classDictInit", null);
dict.__setitem__("toString", null);
dict.__setitem__("getDataHandler", null);
dict.__setitem__("warning", null);
dict.__setitem__("fetch", null);
dict.__setitem__("statement", null);
dict.__setitem__("dynamicFetch", null);
dict.__setitem__("getPyClass", null);
dict.__setitem__("rsConcur", null);
dict.__setitem__("rsType", null);
}
/**
* Delete the cursor.
*
*/
public void __del__() {
close();
}
/**
* Close the cursor now (rather than whenever __del__ is called).
* The cursor will be unusable from this point forward; an Error
* (or subclass) exception will be raised if any operation is
* attempted with the cursor.
*
*/
public void close() {
try {
this.clear();
this.connection.remove(this);
} finally {
this.closed = true;
}
}
/**
* Returns an iteratable object.
*
* @return PyObject
*
* @since Jython 2.2, DB API 2.0+
*/
@Override
public PyObject __iter__() {
return this;
}
/**
* Returns the next row from the currently executing SQL statement
* using the same semantics as .fetchone(). A StopIteration
* exception is raised when the result set is exhausted for Python
* versions 2.2 and later.
*
* @return PyObject
*
* @since Jython 2.2, DB API 2.0+
*/
public PyObject next() {
PyObject row = __iternext__();
if (row == null) {
throw Py.StopIteration("");
}
return row;
}
/**
* Return the next element of the sequence that this is an iterator
* for. Returns null when the end of the sequence is reached.
*
* @since Jython 2.2
*
* @return PyObject
*/
@Override
public PyObject __iternext__() {
PyObject row = fetchone();
return row.__nonzero__() ? row : null;
}
/**
* Return ths DatabaseMetaData for the current connection.
*
* @return DatabaseMetaData
*
* @throws SQLException
*/
protected DatabaseMetaData getMetaData() throws SQLException {
return this.connection.connection.getMetaData();
}
/**
* Return the currently bound DataHandler.
*
* @return DataHandler
*/
public DataHandler getDataHandler() {
return this.datahandler;
}
/**
* Prepare a statement ready for executing.
*
* @param sql the sql to execute or a prepared statement
* @param maxRows max number of rows to be returned
* @param prepared if true, prepare the statement, otherwise create a normal statement
*
* @return PyStatement
*/
private PyStatement prepareStatement(PyObject sql, PyObject maxRows, boolean prepared) {
PyStatement stmt = null;
if (sql == Py.None) {
return null;
}
try {
if (sql instanceof PyStatement) {
stmt = (PyStatement)sql;
} else {
Statement sqlStatement = null;
String sqlString =
sql instanceof PyUnicode ? sql.toString() : sql.__str__().toString();
if (sqlString.trim().length() == 0) {
return null;
}
boolean normal = (this.rsType == Py.None && this.rsConcur == Py.None);
if (normal) {
if (prepared) {
sqlStatement = this.connection.connection.prepareStatement(sqlString);
} else {
sqlStatement = this.connection.connection.createStatement();
}
} else {
int t = this.rsType.asInt();
int c = this.rsConcur.asInt();
if (prepared) {
sqlStatement = this.connection.connection.prepareStatement(sqlString, t,
c);
} else {
sqlStatement = this.connection.connection.createStatement(t, c);
}
}
int style = prepared
? PyStatement.STATEMENT_PREPARED : PyStatement.STATEMENT_STATIC;
stmt = new PyStatement(sqlStatement, sqlString, style);
}
if (maxRows != Py.None) {
stmt.statement.setMaxRows(maxRows.asInt());
}
} catch (AbstractMethodError e) {
throw zxJDBC.makeException(zxJDBC.NotSupportedError,
zxJDBC.getString("nodynamiccursors"));
} catch (PyException e) {
throw e;
} catch (Throwable e) {
throw zxJDBC.makeException(e);
}
return stmt;
}
/**
* This method is optional since not all databases provide stored procedures.
*
* Call a stored database procedure with the given name. The sequence of parameters
* must contain one entry for each argument that the procedure expects. The result of
* the call is returned as modified copy of the input sequence. Input parameters are
* left untouched, output and input/output parameters replaced with possibly new values.
*
* The procedure may also provide a result set as output. This must then be made available
* through the standard fetchXXX() methods.
*
* @param name
* @param params
* @param bindings
* @param maxRows
*/
public void callproc(PyObject name, final PyObject params, PyObject bindings,
PyObject maxRows) {
this.clear();
try {
if (getMetaData().supportsStoredProcedures()) {
if (isSeqSeq(params)) {
throw zxJDBC.makeException(zxJDBC.NotSupportedError,
"sequence of sequences is not supported");
}
final Procedure procedure = datahandler.getProcedure(this, name);
Statement stmt = procedure.prepareCall(this.rsType, this.rsConcur);
if (maxRows != Py.None) {
stmt.setMaxRows(maxRows.asInt());
}
// get the bindings per the stored proc spec
PyDictionary callableBindings = new PyDictionary();
procedure.normalizeInput(params, callableBindings);
// overwrite with any user specific bindings
if (bindings instanceof PyDictionary) {
callableBindings.update(bindings);
}
this.statement = new PyStatement(stmt, procedure);
this.execute(params, callableBindings);
} else {
throw zxJDBC.makeException(zxJDBC.NotSupportedError,
zxJDBC.getString("noStoredProc"));
}
} catch (Throwable t) {
if (statement != null) {
statement.close();
}
throw zxJDBC.makeException(t);
}
}
/**
* Prepare a database operation (query or command) and then execute it against all
* parameter sequences or mappings found in the sequence seq_of_parameters.
* Modules are free to implement this method using multiple calls to the execute()
* method or by using array operations to have the database process the sequence as
* a whole in one call.
*
* The same comments as for execute() also apply accordingly to this method.
*
* Return values are not defined.
*
* @param sql
* @param params
* @param bindings
* @param maxRows
*/
public void executemany(PyObject sql, PyObject params, PyObject bindings, PyObject maxRows) {
if (isSeq(params) && params.__len__() == 0) {
//executemany with an empty params tuple is a no-op
return;
}
execute(sql, params, bindings, maxRows);
}
/**
* Prepare and execute a database operation (query or command).
* Parameters may be provided as sequence or mapping and will
* be bound to variables in the operation. Variables are specified
* in a database-specific notation (see the module's paramstyle
* attribute for details).
*
* A reference to the operation will be retained by the cursor.
* If the same operation object is passed in again, then the cursor
* can optimize its behavior. This is most effective for algorithms
* where the same operation is used, but different parameters are
* bound to it (many times).
*
* For maximum efficiency when reusing an operation, it is best to
* use the setinputsizes() method to specify the parameter types and
* sizes ahead of time. It is legal for a parameter to not match the
* predefined information; the implementation should compensate, possibly
* with a loss of efficiency.
*
* The parameters may also be specified as list of tuples to e.g. insert
* multiple rows in a single operation, but this kind of usage is
* deprecated: executemany() should be used instead.
*
* Return values are not defined.
*
* @param sql sql string or prepared statement
* @param params params for a prepared statement
* @param bindings dictionary of (param index : SQLType binding)
* @param maxRows integer value of max rows
*/
public void execute(final PyObject sql, PyObject params, PyObject bindings, PyObject maxRows) {
int rowIndex = -1;
this.clear();
boolean hasParams = hasParams(params);
PyStatement stmt = this.prepareStatement(sql, maxRows, hasParams);
if (stmt == null) {
return;
}
this.statement = stmt;
try {
synchronized (this.statement) {
if (hasParams) {
// if we have a sequence of sequences, let's run through them and finish
if (isSeqSeq(params)) {
// [(3, 4)] or [(3, 4), (5, 6)]
rowIndex = 0;
for (int i = 0, len = params.__len__(); i < len; i++) {
PyObject param = params.__getitem__(i);
this.execute(param, bindings);
rowIndex++;
}
} else {
this.execute(params, bindings);
}
} else {
// execute the sql string straight up
this.execute(Py.None, Py.None);
}
}
} catch (Throwable t) {
if (statement != null && !(sql instanceof PyStatement)) {
// only close static, single-use statements
statement.close();
}
throw zxJDBC.makeException(zxJDBC.Error, t, rowIndex);
}
}
/**
* Execute the current sql statement. Some generic functionality such
* as updating the lastrowid and updatecount occur as well.
*/
protected void execute(PyObject params, PyObject bindings) {
try {
Statement stmt = this.statement.statement;
this.datahandler.preExecute(stmt);
// this performs the SQL execution and fetch per the Statement type
this.statement.execute(this, params, bindings);
this.updateAttributes(stmt.getUpdateCount());
warning(new WarningEvent(this, stmt.getWarnings()));
this.datahandler.postExecute(stmt);
} catch (PyException e) {
throw e;
} catch (Throwable e) {
throw zxJDBC.makeException(e);
}
}
/**
* Update the cursor's lastrowid and updatecount.
*
* @param updateCount The int value of updatecount
* @throws SQLException
*/
private void updateAttributes(int updateCount) throws SQLException {
lastrowid = datahandler.getRowId(statement.statement);
updatecount = updateCount < 0 ? Py.None : Py.newInteger(updateCount);
}
/**
* Fetch the next row of a query result set, returning a single sequence,
* or None when no more data is available.
*
* 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() {
ensureOpen();
return this.fetch.fetchone();
}
/**
* 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.
*
* 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
*/
public PyObject fetchall() {
ensureOpen();
return this.fetch.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.
*
* 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.
*
* 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.
*
* 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.
*
* @param size
* @return a sequence of sequences from the result set, or an empty sequence when
* no more data is available
*/
public PyObject fetchmany(int size) {
ensureOpen();
return this.fetch.fetchmany(size);
}
/**
* Move the result pointer to the next set if available.
*
* @return true if more sets exist, else None
*/
public PyObject nextset() {
ensureOpen();
PyObject nextset = fetch.nextset();
// If the fetch is exhausted and multiple ResultSets are supported, try addding a
// next ResultSet. XXX: DynamicFetch currently isn't so tailored for this
if (!nextset.__nonzero__() && connection.supportsMultipleResultSets && !dynamicFetch) {
Statement stmt = statement.statement;
try {
boolean hasMoreResults;
int updateCount = -1;
if ((hasMoreResults = stmt.getMoreResults())
|| (updateCount = stmt.getUpdateCount()) != -1) {
// Only call getUpdateCount once, per its docs
updateAttributes(!hasMoreResults ? updateCount : stmt.getUpdateCount());
fetch.add(stmt.getResultSet());
nextset = Py.One;
}
} catch (SQLException sqle) {
throw zxJDBC.makeException(sqle);
}
}
return nextset;
}
/**
* Prepare a sql statement for later execution.
*
* @param sql The sql string to be prepared.
*
* @return A prepared statement usable with .executeXXX()
*/
public PyStatement prepare(PyObject sql) {
PyStatement s = this.prepareStatement(sql, Py.None, true);
// add to the set of statements which are leaving our control
this.connection.add(s);
return s;
}
/**
* Scroll the cursor in the result set to a new position according
* to mode.
*
* 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.
*
* 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).
*
* 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 void scroll(int value, String mode) {
ensureOpen();
this.fetch.scroll(value, mode);
}
/**
* Adds a warning to the tuple and will follow the chain as necessary.
*
* @param event
*/
public void warning(WarningEvent event) {
if (this.warnings == Py.None) {
this.warnings = new PyList();
}
SQLWarning warning = event.getWarning();
while (warning != null) {
// there are three parts: (reason, state, vendorCode)
PyObject[] warn =
Py.javas2pys(warning.getMessage(), warning.getSQLState(), warning.getErrorCode());
// add the warning to the list
((PyList)this.warnings).append(new PyTuple(warn));
warning = warning.getNextWarning();
}
}
/**
* Resets the cursor state. This includes flushing the warnings
* and any previous results.
*
*/
protected void clear() {
ensureOpen();
this.warnings = Py.None;
this.lastrowid = Py.None;
this.updatecount = Py.newInteger(-1);
try {
this.fetch.close();
} catch (Throwable e) {
// ok
} finally {
this.fetch = Fetch.newFetch(this.datahandler, this.dynamicFetch);
this.fetch.addWarningListener(this);
}
if (this.statement != null) {
// Finally done with the Statement: only close it if we created it
try {
if (!this.connection.contains(this.statement)) {
this.statement.close();
}
} finally {
this.statement = null;
}
}
}
/**
* Method isSeq
*
* @param object
*
* @return true for any PyList, PyTuple or java.util.List
*
*/
public static boolean isSeq(PyObject object) {
if (object == null || object == Py.None) {
return false;
}
if (object.__tojava__(List.class) != Py.NoConversion) {
return true;
}
// originally checked for __getitem__ and __len__, but this is true for PyString
// and we don't want to insert one character at a time
return object instanceof PyList || object instanceof PyTuple;
}
/**
* Method hasParams
*
* @param params
*
* @return boolean
*
*/
public static boolean hasParams(PyObject params) {
if (Py.None == params) {
return false;
}
boolean isSeq = isSeq(params);
// the optional argument better be a sequence
if (!isSeq) {
throw zxJDBC.makeException(zxJDBC.ProgrammingError,
zxJDBC.getString("optionalSecond"));
}
return params.__len__() > 0;
}
/**
* Method isSeqSeq
*
* @param object
*
* @return true is a sequence of sequences
*
*/
public static boolean isSeqSeq(PyObject object) {
if (isSeq(object) && (object.__len__() > 0)) {
for (int i = 0; i < object.__len__(); i++) {
if (!isSeq(object.__finditem__(i))) {
return false;
}
}
return true;
}
return false;
}
/**
* Throw a ProgrammingError if the cursor has been closed.
*/
private void ensureOpen() {
if (closed) {
throw zxJDBC.makeException(zxJDBC.ProgrammingError, "cursor is closed");
}
}
public PyObject __enter__(ThreadState ts) {
return this;
}
public PyObject __enter__() {
return this;
}
public boolean __exit__(ThreadState ts, PyException exception) {
close();
return false;
}
public boolean __exit__(PyObject type, PyObject value, PyObject traceback) {
close();
return false;
}
/* Traverseproc implementation */
@Override
public int traverse(Visitproc visit, Object arg) {
int retVal;
if (fetch != null) {
retVal = fetch.traverse(visit, arg);
if (retVal != 0) {
return retVal;
}
}
if (rsType != null) {
retVal = visit.visit(rsType, arg);
if (retVal != 0) {
return retVal;
}
}
if (rsConcur != null) {
retVal = visit.visit(rsConcur, arg);
if (retVal != 0) {
return retVal;
}
}
if (warnings != null) {
retVal = visit.visit(warnings, arg);
if (retVal != 0) {
return retVal;
}
}
if (lastrowid != null) {
retVal = visit.visit(lastrowid, arg);
if (retVal != 0) {
return retVal;
}
}
if (updatecount != null) {
retVal = visit.visit(updatecount, arg);
if (retVal != 0) {
return retVal;
}
}
if (connection != null) {
retVal = visit.visit(connection, arg);
if (retVal != 0) {
return retVal;
}
}
return statement != null ? visit.visit(statement, arg) : 0;
}
@Override
public boolean refersDirectlyTo(PyObject ob) {
if (ob == null) {
return false;
} else if (ob == rsType || ob == rsConcur || ob == warnings || ob == lastrowid
|| ob == updatecount || ob == connection || ob == statement) {
return true;
} else {
return fetch.refersDirectlyTo(ob);
}
}
}
class CursorFunc extends PyBuiltinMethodSet {
CursorFunc(String name, int index, int argcount, String doc) {
this(name, index, argcount, argcount, doc);
}
CursorFunc(String name, int index, int minargs, int maxargs, String doc) {
super(name, index, minargs, maxargs, doc, PyCursor.class);
}
@Override
public PyObject __call__() {
PyCursor cursor = (PyCursor)__self__;
switch (index) {
case 0 :
return cursor.fetchmany(cursor.arraysize);
case 1 :
cursor.close();
return Py.None;
case 2 :
return cursor.fetchall();
case 3 :
return cursor.fetchone();
case 4 :
return cursor.nextset();
case 13 :
return cursor.__enter__();
default :
throw info.unexpectedCall(0, false);
}
}