-
Notifications
You must be signed in to change notification settings - Fork 227
Expand file tree
/
Copy pathDataHandler.java
More file actions
569 lines (483 loc) · 17.9 KB
/
DataHandler.java
File metadata and controls
569 lines (483 loc) · 17.9 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
/*
* Jython Database Specification API 2.0
*
*
* Copyright (c) 2001 brian zimmer <bzimmer@ziclix.com>
*
*/
package com.ziclix.python.sql;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.lang.reflect.Constructor;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import org.python.core.Py;
import org.python.core.PyFile;
import org.python.core.PyList;
import org.python.core.PyObject;
/**
* The DataHandler is responsible mapping the JDBC data type to
* a Jython object. Depending on the version of the JDBC
* implementation and the particulars of the driver, the type
* mapping can be significantly different.
*
* This interface can also be used to change the behaviour of
* the default mappings provided by the cursor. This might be
* useful in handling more complicated data types such as BLOBs,
* CLOBs and Arrays.
*
* @author brian zimmer
*/
public class DataHandler {
/** Default size for buffers. */
private static final int INITIAL_SIZE = 1024 * 4;
private static final String[] SYSTEM_DATAHANDLERS = {
"com.ziclix.python.sql.JDBC20DataHandler"
};
/**
* Handle most generic Java data types.
*/
public DataHandler() {}
/**
* Some database vendors are case sensitive on calls to DatabaseMetaData,
* most notably Oracle. This callback allows a DataHandler to affect the
* name.
*/
public String getMetaDataName(PyObject name) {
return ((name == Py.None) ? null : name.__str__().toString());
}
/**
* A factory method for determing the correct procedure class to use
* per the cursor type.
* @param cursor an open cursor
* @param name the name of the procedure to invoke
* @return an instance of a Procedure
* @throws SQLException
*/
public Procedure getProcedure(PyCursor cursor, PyObject name) throws SQLException {
return new Procedure(cursor, name);
}
/**
* Returns the row id of the last executed statement.
*
* @param stmt the current statement
* @return the row id of the last executed statement or None
* @throws SQLException thrown if an exception occurs
*
*/
public PyObject getRowId(Statement stmt) throws SQLException {
return Py.None;
}
/**
* A callback prior to each execution of the statement. If the statement is
* a PreparedStatement, all the parameters will have been set.
*/
public void preExecute(Statement stmt) throws SQLException {
return;
}
/**
* A callback after successfully executing the statement.
*/
public void postExecute(Statement stmt) throws SQLException {
return;
}
/**
* Any .execute() which uses prepared statements will receive a callback for deciding
* how to map the PyObject to the appropriate JDBC type.
*
* @param stmt the current PreparedStatement
* @param index the index for which this object is bound
* @param object the PyObject in question
* @throws SQLException
*/
public void setJDBCObject(PreparedStatement stmt, int index, PyObject object) throws SQLException {
try {
Object o = object.__tojava__(Object.class);
if (o instanceof BigInteger) {
//XXX: This is in here to specifically fix passing a PyLong into Postgresql.
stmt.setObject(index, o, Types.BIGINT);
} else {
stmt.setObject(index, o);
}
} catch (Exception e) {
SQLException cause = null, ex = new SQLException("error setting index [" + index + "]");
if (e instanceof SQLException) {
cause = (SQLException) e;
} else {
cause = new SQLException(e.getMessage());
}
ex.setNextException(cause);
throw ex;
}
}
/**
* Any .execute() which uses prepared statements will receive a callback for deciding
* how to map the PyObject to the appropriate JDBC type. The <i>type</i> is the JDBC
* type as obtained from <i>java.sql.Types</i>.
*
* @param stmt the current PreparedStatement
* @param index the index for which this object is bound
* @param object the PyObject in question
* @param type the <i>java.sql.Types</i> for which this PyObject should be bound
* @throws SQLException
*/
public void setJDBCObject(PreparedStatement stmt, int index, PyObject object, int type)
throws SQLException {
try {
if (checkNull(stmt, index, object, type)) {
return;
}
switch (type) {
case Types.DATE:
Date date = (Date) object.__tojava__(Date.class);
stmt.setDate(index, date);
break;
case Types.TIME:
Time time = (Time) object.__tojava__(Time.class);
stmt.setTime(index, time);
break;
case Types.TIMESTAMP:
Timestamp timestamp = (Timestamp) object.__tojava__(Timestamp.class);
stmt.setTimestamp(index, timestamp);
break;
case Types.LONGVARCHAR:
if (object instanceof PyFile) {
object = ((PyFile) object).read();
}
String varchar = (String) object.__tojava__(String.class);
Reader reader = new BufferedReader(new StringReader(varchar));
stmt.setCharacterStream(index, reader, varchar.length());
break;
case Types.BIT:
stmt.setBoolean(index, object.__nonzero__());
break;
default :
if (object instanceof PyFile) {
object = ((PyFile) object).read();
}
stmt.setObject(index, object.__tojava__(Object.class), type);
break;
}
} catch (Exception e) {
SQLException cause = null, ex = new SQLException("error setting index [" + index
+ "], type [" + type + "]");
if (e instanceof SQLException) {
cause = (SQLException) e;
} else {
cause = new SQLException(e.getMessage());
}
ex.setNextException(cause);
throw ex;
}
}
/**
* Given a ResultSet, column and type, return the appropriate
* Jython object.
*
* <p>Note: DO NOT iterate the ResultSet.
*
* @param set the current ResultSet set to the current row
* @param col the column number (adjusted properly for JDBC)
* @param type the column type
* @throws SQLException if the type is unmappable
*/
public PyObject getPyObject(ResultSet set, int col, int type) throws SQLException {
PyObject obj = Py.None;
switch (type) {
case Types.CHAR:
case Types.VARCHAR:
case Types.NCHAR:
case Types.NVARCHAR:
String string = set.getString(col);
obj = string == null ? Py.None : Py.newUnicode(string);
break;
case Types.LONGVARCHAR:
case Types.LONGNVARCHAR:
Reader reader = set.getCharacterStream(col);
obj = reader == null ? Py.None : Py.newUnicode(read(reader));
break;
case Types.NUMERIC:
case Types.DECIMAL:
BigDecimal bd = set.getBigDecimal(col);
obj = (bd == null) ? Py.None : Py.newFloat(bd.doubleValue());
break;
case Types.BIT:
case Types.BOOLEAN:
obj = set.getBoolean(col) ? Py.True : Py.False;
break;
case Types.INTEGER:
case Types.TINYINT:
case Types.SMALLINT:
obj = Py.newInteger(set.getInt(col));
break;
case Types.BIGINT:
obj = Py.newLong(set.getLong(col));
break;
case Types.FLOAT:
case Types.REAL:
obj = Py.newFloat(set.getFloat(col));
break;
case Types.DOUBLE:
obj = Py.newFloat(set.getDouble(col));
break;
case Types.TIME:
obj = Py.newTime(set.getTime(col));
break;
case Types.TIMESTAMP:
obj = Py.newDatetime(set.getTimestamp(col));
break;
case Types.DATE:
Object date = set.getObject(col);
// don't newDate mysql YEAR columns
obj = date instanceof Date ? Py.newDate((Date)date) : Py.java2py(date);
break;
case Types.NULL:
obj = Py.None;
break;
case Types.OTHER:
case Types.JAVA_OBJECT:
obj = Py.java2py(set.getObject(col));
break;
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
obj = Py.java2py(set.getBytes(col));
break;
case Types.BLOB:
Blob blob = set.getBlob(col);
obj = blob == null ? Py.None : Py.java2py(read(blob.getBinaryStream()));
break;
case Types.CLOB:
case Types.NCLOB:
case Types.SQLXML:
Clob clob = set.getClob(col);
obj = clob == null ? Py.None : Py.java2py(read(clob.getCharacterStream()));
break;
// TODO can we support these?
case Types.ARRAY:
throw createUnsupportedTypeSQLException("ARRAY", col);
case Types.DATALINK:
throw createUnsupportedTypeSQLException("DATALINK", col);
case Types.DISTINCT:
throw createUnsupportedTypeSQLException("DISTINCT", col);
case Types.REF:
throw createUnsupportedTypeSQLException("REF", col);
case Types.ROWID:
throw createUnsupportedTypeSQLException("STRUCT", col);
case Types.STRUCT:
throw createUnsupportedTypeSQLException("STRUCT", col);
default :
throw createUnsupportedTypeSQLException(Integer.valueOf(type), col);
}
return set.wasNull() || obj == null ? Py.None : obj;
}
protected final SQLException createUnsupportedTypeSQLException(Object type, int col) {
Object[] vals = {type, Integer.valueOf(col)};
String msg = zxJDBC.getString("unsupportedTypeForColumn", vals);
return new SQLException(msg);
}
/**
* Given a CallableStatement, column and type, return the appropriate
* Jython object.
*
* @param stmt the CallableStatement
* @param col the column number (adjusted properly for JDBC)
* @param type the column type
* @throws SQLException if the type is unmappable
*/
public PyObject getPyObject(CallableStatement stmt, int col, int type) throws SQLException {
PyObject obj = Py.None;
switch (type) {
case Types.CHAR:
case Types.VARCHAR:
case Types.LONGVARCHAR:
String string = stmt.getString(col);
obj = (string == null) ? Py.None : Py.newUnicode(string);
break;
case Types.NUMERIC:
case Types.DECIMAL:
BigDecimal bd = stmt.getBigDecimal(col);
obj = (bd == null) ? Py.None : Py.newFloat(bd.doubleValue());
break;
case Types.BIT:
obj = stmt.getBoolean(col) ? Py.True : Py.False;
break;
case Types.INTEGER:
case Types.TINYINT:
case Types.SMALLINT:
obj = Py.newInteger(stmt.getInt(col));
break;
case Types.BIGINT:
obj = Py.newLong(stmt.getLong(col));
break;
case Types.FLOAT:
case Types.REAL:
obj = Py.newFloat(stmt.getFloat(col));
break;
case Types.DOUBLE:
obj = Py.newFloat(stmt.getDouble(col));
break;
case Types.TIME:
obj = Py.newTime(stmt.getTime(col));
break;
case Types.TIMESTAMP:
obj = Py.newDatetime(stmt.getTimestamp(col));
break;
case Types.DATE:
obj = Py.newDate(stmt.getDate(col));
break;
case Types.NULL:
obj = Py.None;
break;
case Types.OTHER:
obj = Py.java2py(stmt.getObject(col));
break;
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
obj = Py.java2py(stmt.getBytes(col));
break;
default :
createUnsupportedTypeSQLException(type, col);
}
return stmt.wasNull() || obj == null ? Py.None : obj;
}
/**
* Called when a stored procedure or function is executed and OUT parameters
* need to be registered with the statement.
*
* @param statement
* @param index the JDBC offset column number
* @param colType the column as from DatabaseMetaData (eg, procedureColumnOut)
* @param dataType the JDBC datatype from Types
* @param dataTypeName the JDBC datatype name
*
* @throws SQLException
*
*/
public void registerOut(CallableStatement statement, int index, int colType, int dataType,
String dataTypeName) throws SQLException {
try {
statement.registerOutParameter(index, dataType);
} catch (Throwable t) {
SQLException cause = null;
SQLException ex = new SQLException("error setting index ["
+ index + "], coltype [" + colType + "], datatype [" + dataType
+ "], datatypename [" + dataTypeName + "]");
if (t instanceof SQLException) {
cause = (SQLException)t;
} else {
cause = new SQLException(t.getMessage());
}
ex.setNextException(cause);
throw ex;
}
}
/**
* Handles checking if the object is null or None and setting it on the statement.
*
* @return true if the object is null and was set on the statement, false otherwise
*/
public static final boolean checkNull(PreparedStatement stmt, int index, PyObject object,
int type) throws SQLException {
if ((object == null) || (Py.None == object)) {
stmt.setNull(index, type);
return true;
}
return false;
}
/**
* Consume the InputStream into an byte array and close the InputStream.
*
* @return the contents of the InputStream a byte[]
*/
public static final byte[] read(InputStream stream) {
int size = 0;
byte[] buffer = new byte[INITIAL_SIZE];
ByteArrayOutputStream baos = new ByteArrayOutputStream(INITIAL_SIZE);
try {
while ((size = stream.read(buffer)) != -1) {
baos.write(buffer, 0, size);
}
} catch (IOException ioe) {
throw zxJDBC.makeException(ioe);
} finally {
try {
stream.close();
} catch (IOException ioe) {
throw zxJDBC.makeException(ioe);
}
}
return baos.toByteArray();
}
/**
* Consume the Reader into a String and close the Reader.
*
* @return the contents of the Reader as a String
*/
public static String read(Reader reader) {
int size = 0;
char[] buffer = new char[INITIAL_SIZE];
StringBuilder builder = new StringBuilder(INITIAL_SIZE);
try {
while ((size = reader.read(buffer)) != -1) {
builder.append(buffer, 0, size);
}
} catch (IOException ioe) {
throw zxJDBC.makeException(ioe);
} finally {
try {
reader.close();
} catch (IOException ioe) {
throw zxJDBC.makeException(ioe);
}
}
return builder.toString();
}
/**
* Build the DataHandler chain depending on the VM. This guarentees a DataHandler
* but might additionally chain a JDBC2.0 or JDBC3.0 implementation.
* @return a DataHandler configured for the VM version
*/
public static final DataHandler getSystemDataHandler() {
DataHandler dh = new DataHandler();
for (String element : SYSTEM_DATAHANDLERS) {
try {
Class<?> c = Class.forName(element);
Constructor<?> cons = c.getConstructor(new Class<?>[]{DataHandler.class});
dh = (DataHandler) cons.newInstance(new Object[]{dh});
} catch (Throwable t) {}
}
return dh;
}
/**
* Returns a list of datahandlers chained together through the use of delegation.
*
* @return a list of datahandlers
*/
public PyObject __chain__() {
return new PyList(Py.javas2pys(this));
}
/**
* Returns the classname of this datahandler.
*/
@Override
public String toString() {
return getClass().getName();
}
}