From: <pj...@us...> - 2009-05-07 04:15:21
|
Revision: 6314 http://jython.svn.sourceforge.net/jython/?rev=6314&view=rev Author: pjenvey Date: 2009-05-07 04:15:11 +0000 (Thu, 07 May 2009) Log Message: ----------- o revert the deprecated getBigDecimal postgresql driver workaround, this problem was resolved long ago o suppress warnings in the old, preserved Jython22DataHandler Modified Paths: -------------- trunk/jython/src/com/ziclix/python/sql/Jython22DataHandler.java trunk/jython/src/com/ziclix/python/sql/handler/PostgresqlDataHandler.java Modified: trunk/jython/src/com/ziclix/python/sql/Jython22DataHandler.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/Jython22DataHandler.java 2009-05-07 03:48:51 UTC (rev 6313) +++ trunk/jython/src/com/ziclix/python/sql/Jython22DataHandler.java 2009-05-07 04:15:11 UTC (rev 6314) @@ -210,6 +210,7 @@ * @param type the column type * @throws SQLException if the type is unmappable */ + @SuppressWarnings("deprecation") public PyObject getPyObject(ResultSet set, int col, int type) throws SQLException { PyObject obj = Py.None; @@ -326,6 +327,7 @@ * @param type the column type * @throws SQLException if the type is unmappable */ + @SuppressWarnings("deprecation") public PyObject getPyObject(CallableStatement stmt, int col, int type) throws SQLException { PyObject obj = Py.None; Modified: trunk/jython/src/com/ziclix/python/sql/handler/PostgresqlDataHandler.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/handler/PostgresqlDataHandler.java 2009-05-07 03:48:51 UTC (rev 6313) +++ trunk/jython/src/com/ziclix/python/sql/handler/PostgresqlDataHandler.java 2009-05-07 04:15:11 UTC (rev 6314) @@ -60,14 +60,7 @@ case Types.NUMERIC: case Types.DECIMAL: - // in JDBC 2.0, use of a scale is deprecated - // The big fix here is a problem with numeric types. It seems the ResultSet - // tries to fix a JBuilder bug (as commented in the source) by including a - // scale of 0. Well this blows up BigDecimal if the number is, say, 4.22. - // It appears the workaround is to call the deprecated method with a scale of - // -1 which forces the return of the BD without setting the scale. - BigDecimal bd = set.getBigDecimal(col, -1); - + BigDecimal bd = set.getBigDecimal(col); obj = (bd == null) ? Py.None : Py.newFloat(bd.doubleValue()); break; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-07-21 02:48:54
|
Revision: 6554 http://jython.svn.sourceforge.net/jython/?rev=6554&view=rev Author: pjenvey Date: 2009-07-21 02:48:53 +0000 (Tue, 21 Jul 2009) Log Message: ----------- accept unicode statements and return unicode for cursor description's name Modified Paths: -------------- trunk/jython/src/com/ziclix/python/sql/Fetch.java trunk/jython/src/com/ziclix/python/sql/PyConnection.java trunk/jython/src/com/ziclix/python/sql/PyCursor.java Modified: trunk/jython/src/com/ziclix/python/sql/Fetch.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/Fetch.java 2009-07-21 01:00:16 UTC (rev 6553) +++ trunk/jython/src/com/ziclix/python/sql/Fetch.java 2009-07-21 02:48:53 UTC (rev 6554) @@ -259,7 +259,7 @@ for (int i = 1; i <= meta.getColumnCount(); i++) { PyObject[] a = new PyObject[7]; - a[0] = Py.newString(meta.getColumnLabel(i)); + 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; Modified: trunk/jython/src/com/ziclix/python/sql/PyConnection.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/PyConnection.java 2009-07-21 01:00:16 UTC (rev 6553) +++ trunk/jython/src/com/ziclix/python/sql/PyConnection.java 2009-07-21 02:48:53 UTC (rev 6554) @@ -14,6 +14,7 @@ import java.util.HashSet; import java.util.Iterator; import java.util.Set; + import org.python.core.ClassDictInit; import org.python.core.Py; import org.python.core.PyBuiltinMethodSet; @@ -22,6 +23,8 @@ import org.python.core.PyList; import org.python.core.PyObject; import org.python.core.PyString; +import org.python.core.PyUnicode; + import com.ziclix.python.sql.util.PyArgParser; /** @@ -339,7 +342,6 @@ * @return the native form of this statement */ public PyObject nativesql(PyObject nativeSQL) { - if (closed) { throw zxJDBC.makeException(zxJDBC.ProgrammingError, "connection is closed"); } @@ -349,6 +351,9 @@ } try { + if (nativeSQL instanceof PyUnicode) { + return Py.newUnicode(this.connection.nativeSQL(nativeSQL.toString())); + } return Py.newString(this.connection.nativeSQL(nativeSQL.__str__().toString())); } catch (SQLException e) { throw zxJDBC.makeException(e); Modified: trunk/jython/src/com/ziclix/python/sql/PyCursor.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/PyCursor.java 2009-07-21 01:00:16 UTC (rev 6553) +++ trunk/jython/src/com/ziclix/python/sql/PyCursor.java 2009-07-21 02:48:53 UTC (rev 6554) @@ -23,6 +23,7 @@ import org.python.core.PyObject; import org.python.core.PyString; import org.python.core.PyTuple; +import org.python.core.PyUnicode; import com.ziclix.python.sql.util.PyArgParser; @@ -382,7 +383,8 @@ stmt = (PyStatement)sql; } else { Statement sqlStatement = null; - String sqlString = sql.__str__().toString(); + String sqlString = + sql instanceof PyUnicode ? sql.toString() : sql.__str__().toString(); if (sqlString.trim().length() == 0) { return null; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-07-22 02:18:45
|
Revision: 6558 http://jython.svn.sourceforge.net/jython/?rev=6558&view=rev Author: pjenvey Date: 2009-07-22 02:18:24 +0000 (Wed, 22 Jul 2009) Log Message: ----------- better repr Modified Paths: -------------- trunk/jython/src/com/ziclix/python/sql/PyConnection.java trunk/jython/src/com/ziclix/python/sql/PyCursor.java trunk/jython/src/com/ziclix/python/sql/PyStatement.java Modified: trunk/jython/src/com/ziclix/python/sql/PyConnection.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/PyConnection.java 2009-07-21 23:06:14 UTC (rev 6557) +++ trunk/jython/src/com/ziclix/python/sql/PyConnection.java 2009-07-22 02:18:24 UTC (rev 6558) @@ -118,12 +118,15 @@ * * @return string representation of the object. */ + @Override public String toString() { try { - return "<PyConnection user='" + this.connection.getMetaData().getUserName() + "', url='" + this.connection.getMetaData().getURL() + "'>"; + return String.format("<PyConnection object at %s user='%s', url='%s'>", Py.idstr(this), + connection.getMetaData().getUserName(), + connection.getMetaData().getURL()); } catch (SQLException e) { - return "<PyConnection at " + hashCode() + ">"; + return String.format("<PyConnection object at %s", Py.idstr(this)); } } Modified: trunk/jython/src/com/ziclix/python/sql/PyCursor.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/PyCursor.java 2009-07-21 23:06:14 UTC (rev 6557) +++ trunk/jython/src/com/ziclix/python/sql/PyCursor.java 2009-07-22 02:18:24 UTC (rev 6558) @@ -166,7 +166,7 @@ */ @Override public String toString() { - return "<PyCursor object instance at " + Py.id(this) + ">"; + return String.format("<PyCursor object at %s>", Py.idstr(this)); } /** Modified: trunk/jython/src/com/ziclix/python/sql/PyStatement.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/PyStatement.java 2009-07-21 23:06:14 UTC (rev 6557) +++ trunk/jython/src/com/ziclix/python/sql/PyStatement.java 2009-07-22 02:18:24 UTC (rev 6558) @@ -130,20 +130,10 @@ return super.__str__(); } - /** - * Method __repr__ - * - * @return PyString - */ + @Override public PyString __repr__() { - - // care is taken not to display a rounded second value - StringBuffer buf = new StringBuffer("<PyStatement object for ["); - - buf.append(__str__().toString()); - buf.append("] at ").append(Py.id(this)).append(">"); - - return Py.newString(buf.toString()); + return Py.newString(String.format("<PyStatement object at %s for [%s]", Py.idstr(this), + __str__())); } /** This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-07-31 04:52:42
|
Revision: 6610 http://jython.svn.sourceforge.net/jython/?rev=6610&view=rev Author: pjenvey Date: 2009-07-31 04:52:17 +0000 (Fri, 31 Jul 2009) Log Message: ----------- o read CLOBs into unicode instead of str o cleanup the DataHandler.read and have them close their input Modified Paths: -------------- trunk/jython/src/com/ziclix/python/sql/DataHandler.java trunk/jython/src/com/ziclix/python/sql/JDBC20DataHandler.java trunk/jython/src/com/ziclix/python/sql/handler/InformixDataHandler.java trunk/jython/src/com/ziclix/python/sql/handler/OracleDataHandler.java Modified: trunk/jython/src/com/ziclix/python/sql/DataHandler.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/DataHandler.java 2009-07-30 15:11:03 UTC (rev 6609) +++ trunk/jython/src/com/ziclix/python/sql/DataHandler.java 2009-07-31 04:52:17 UTC (rev 6610) @@ -14,6 +14,7 @@ import org.python.core.PyList; import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.Reader; @@ -48,7 +49,7 @@ */ public class DataHandler { - // default size for buffers + /** Default size for buffers. */ private static final int INITIAL_SIZE = 1024 * 4; private static final String[] SYSTEM_DATAHANDLERS = { @@ -153,7 +154,8 @@ * @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 { + public void setJDBCObject(PreparedStatement stmt, int index, PyObject object, int type) + throws SQLException { try { if (checkNull(stmt, index, object, type)) { return; @@ -163,19 +165,16 @@ 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; @@ -203,7 +202,8 @@ break; } } catch (Exception e) { - SQLException cause = null, ex = new SQLException("error setting index [" + index + "], type [" + type + "]"); + SQLException cause = null, ex = new SQLException("error setting index [" + index + + "], type [" + type + "]"); if (e instanceof SQLException) { cause = (SQLException) e; @@ -212,7 +212,6 @@ } ex.setNextException(cause); - throw ex; } } @@ -229,7 +228,6 @@ * @throws SQLException if the type is unmappable */ public PyObject getPyObject(ResultSet set, int col, int type) throws SQLException { - PyObject obj = Py.None; switch (type) { @@ -309,7 +307,7 @@ throw new SQLException(msg); } - return (set.wasNull() || (obj == null)) ? Py.None : obj; + return set.wasNull() || obj == null ? Py.None : obj; } /** @@ -322,7 +320,6 @@ * @throws SQLException if the type is unmappable */ public PyObject getPyObject(CallableStatement stmt, int col, int type) throws SQLException { - PyObject obj = Py.None; switch (type) { @@ -331,14 +328,12 @@ 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; @@ -398,7 +393,7 @@ throw new SQLException(msg); } - return (stmt.wasNull() || (obj == null)) ? Py.None : obj; + return stmt.wasNull() || obj == null ? Py.None : obj; } /** @@ -414,7 +409,8 @@ * @throws SQLException * */ - public void registerOut(CallableStatement statement, int index, int colType, int dataType, String dataTypeName) throws SQLException { + public void registerOut(CallableStatement statement, int index, int colType, int dataType, + String dataTypeName) throws SQLException { try { statement.registerOutParameter(index, dataType); @@ -439,7 +435,8 @@ * * @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 { + 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); @@ -449,54 +446,57 @@ } /** - * Since the driver needs to the know the length of all streams, - * read it into a byte[] array. + * Consume the InputStream into an byte array and close the InputStream. * - * @return the stream as a byte[] + * @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); - int b = -1, read = 0; - byte[] results = new byte[INITIAL_SIZE]; - try { - while ((b = stream.read()) != -1) { - if (results.length < (read + 1)) { - byte[] tmp = results; - results = new byte[results.length * 2]; - System.arraycopy(tmp, 0, results, 0, tmp.length); - } - results[read++] = (byte) b; + while ((size = stream.read(buffer)) != -1) { + baos.write(buffer, 0, size); } - } catch (IOException e) { - throw zxJDBC.makeException(e); + } catch (IOException ioe) { + throw zxJDBC.makeException(ioe); + } finally { + try { + stream.close(); + } catch (IOException ioe) { + throw zxJDBC.makeException(ioe); + } } - byte[] tmp = results; - results = new byte[read]; - System.arraycopy(tmp, 0, results, 0, read); - return results; + return baos.toByteArray(); } /** - * Read all the chars from the Reader into the String. + * Consume the Reader into a String and close the Reader. * - * @return the contents of the Reader in a String + * @return the contents of the Reader as a String */ - public static final String read(Reader reader) { + public static String read(Reader reader) { + int size = 0; + char[] buffer = new char[INITIAL_SIZE]; + StringBuilder builder = new StringBuilder(INITIAL_SIZE); - int c = 0; - StringBuffer buffer = new StringBuffer(INITIAL_SIZE); - try { - while ((c = reader.read()) != -1) { - buffer.append((char) c); + while ((size = reader.read(buffer)) != -1) { + builder.append(buffer, 0, size); } - } catch (IOException e) { - throw zxJDBC.makeException(e); + } catch (IOException ioe) { + throw zxJDBC.makeException(ioe); + } finally { + try { + reader.close(); + } catch (IOException ioe) { + throw zxJDBC.makeException(ioe); + } } - return buffer.toString(); + return builder.toString(); } /** @@ -509,8 +509,8 @@ for (String element : SYSTEM_DATAHANDLERS) { try { - Class c = Class.forName(element); - Constructor cons = c.getConstructor(new Class[]{DataHandler.class}); + Class<?> c = Class.forName(element); + Constructor<?> cons = c.getConstructor(new Class<?>[]{DataHandler.class}); dh = (DataHandler) cons.newInstance(new Object[]{dh}); } catch (Throwable t) {} } @@ -530,6 +530,7 @@ /** * Returns the classname of this datahandler. */ + @Override public String toString() { return getClass().getName(); } Modified: trunk/jython/src/com/ziclix/python/sql/JDBC20DataHandler.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/JDBC20DataHandler.java 2009-07-30 15:11:03 UTC (rev 6609) +++ trunk/jython/src/com/ziclix/python/sql/JDBC20DataHandler.java 2009-07-31 04:52:17 UTC (rev 6610) @@ -9,10 +9,8 @@ package com.ziclix.python.sql; import java.io.BufferedInputStream; -import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.InputStream; -import java.io.InputStreamReader; import java.io.Reader; import java.math.BigDecimal; import java.sql.Array; @@ -92,7 +90,7 @@ // it really is unfortunate that I need to send the length of the stream if (jobject instanceof InputStream) { - lob = DataHandler.read(new BufferedInputStream((InputStream) jobject)); + lob = read((InputStream) jobject); } else if (jobject instanceof byte[]) { lob = (byte[]) jobject; } @@ -135,60 +133,13 @@ break; case Types.CLOB: - - /* - * It seems some drivers (well at least Informix) don't clean up after themselves - * if the Clob is requested. The engine keeps a handle to an open table for each - * row requested and cleans up fully only when the ResultSet or Connection is closed. - * While this generally will never be noticed because the number of CLOBs or BLOBs - * queried will likely be small in the event a large number are queried, it is a huge - * problem. So, handle it as low as possible by managing the stream directly. I've - * decided to leave this in the generic JDBC20 handler because it works for all engines - * I've tested and seems to perform quite well to boot. - */ - Reader reader = null; - - try { - InputStream stream = set.getBinaryStream(col); - - if (stream == null) { - obj = Py.None; - } else { - reader = new InputStreamReader(stream); - reader = new BufferedReader(reader); - obj = Py.newString(DataHandler.read(reader)); - } - } finally { - if (reader != null) { - try { - reader.close(); - } catch (Exception e) { - } - } - } + Reader reader = set.getCharacterStream(col); + obj = reader == null ? Py.None : Py.newUnicode(read(reader)); break; case Types.BLOB: Blob blob = set.getBlob(col); - - if (blob == null) { - obj = Py.None; - } else { - InputStream stream = null; - - try { - stream = blob.getBinaryStream(); - stream = new BufferedInputStream(stream); - obj = Py.java2py(DataHandler.read(stream)); - } finally { - if (stream != null) { - try { - stream.close(); - } catch (Exception e) { - } - } - } - } + obj = blob == null ? Py.None : Py.java2py(read(blob.getBinaryStream())); break; case Types.ARRAY: Modified: trunk/jython/src/com/ziclix/python/sql/handler/InformixDataHandler.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/handler/InformixDataHandler.java 2009-07-30 15:11:03 UTC (rev 6609) +++ trunk/jython/src/com/ziclix/python/sql/handler/InformixDataHandler.java 2009-07-31 04:52:17 UTC (rev 6610) @@ -8,12 +8,10 @@ */ package com.ziclix.python.sql.handler; +import com.informix.jdbc.IfmxStatement; + import com.ziclix.python.sql.DataHandler; import com.ziclix.python.sql.FilterDataHandler; -import org.python.core.Py; -import org.python.core.PyFile; -import org.python.core.PyObject; -import org.python.core.PyString; import java.io.InputStream; import java.sql.Blob; @@ -23,6 +21,11 @@ import java.sql.Statement; import java.sql.Types; +import org.python.core.Py; +import org.python.core.PyFile; +import org.python.core.PyObject; +import org.python.core.PyString; + /** * Informix specific data handling. * @@ -48,12 +51,11 @@ * @return PyObject * @throws SQLException */ + @Override public PyObject getRowId(Statement stmt) throws SQLException { - - if (stmt instanceof com.informix.jdbc.IfmxStatement) { - return Py.newInteger(((com.informix.jdbc.IfmxStatement) stmt).getSerial()); + if (stmt instanceof IfmxStatement) { + return Py.newInteger(((IfmxStatement) stmt).getSerial()); } - return super.getRowId(stmt); } @@ -66,8 +68,9 @@ * @param type * @throws SQLException */ - public void setJDBCObject(PreparedStatement stmt, int index, PyObject object, int type) throws SQLException { - + @Override + public void setJDBCObject(PreparedStatement stmt, int index, PyObject object, int type) + throws SQLException { if (DataHandler.checkNull(stmt, index, object, type)) { return; } @@ -105,9 +108,11 @@ * @param object * @throws SQLException */ - public void setJDBCObject(PreparedStatement stmt, int index, PyObject object) throws SQLException { - - // there is a bug in the Ifx driver when using setObject() with a String for a prepared statement + @Override + public void setJDBCObject(PreparedStatement stmt, int index, PyObject object) + throws SQLException { + // there is a bug in the Ifx driver when using setObject() with a String for a + // prepared statement if (object instanceof PyString) { super.setJDBCObject(stmt, index, object, Types.VARCHAR); } else { @@ -125,6 +130,7 @@ * @throws SQLException thrown for a sql exception */ @SuppressWarnings("fallthrough") + @Override public PyObject getPyObject(ResultSet set, int col, int type) throws SQLException { PyObject obj = Py.None; @@ -133,7 +139,6 @@ case Types.OTHER: try { - // informix returns boolean as OTHERs, so let's give that a try obj = set.getBoolean(col) ? Py.One : Py.Zero; } catch (SQLException e) { @@ -145,33 +150,15 @@ int major = set.getStatement().getConnection().getMetaData().getDriverMajorVersion(); int minor = set.getStatement().getConnection().getMetaData().getDriverMinorVersion(); - if ((major <= 2) && (minor <= 11)) { + if (major <= 2 && minor <= 11) { Blob blob = set.getBlob(col); - - if (blob == null) { - obj = Py.None; - } else { - InputStream is = null; - - try { - - // the available() bug means we CANNOT buffer this stream - is = blob.getBinaryStream(); - obj = Py.java2py(DataHandler.read(is)); - } finally { - try { - is.close(); - } catch (Exception e) { - } - } - } - + obj = blob == null ? Py.None : Py.java2py(read(blob.getBinaryStream())); break; } default : obj = super.getPyObject(set, col, type); } - return (set.wasNull() || (obj == null)) ? Py.None : obj; + return set.wasNull() || obj == null ? Py.None : obj; } } Modified: trunk/jython/src/com/ziclix/python/sql/handler/OracleDataHandler.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/handler/OracleDataHandler.java 2009-07-30 15:11:03 UTC (rev 6609) +++ trunk/jython/src/com/ziclix/python/sql/handler/OracleDataHandler.java 2009-07-31 04:52:17 UTC (rev 6610) @@ -48,18 +48,18 @@ * @param name * @return String */ + @Override public String getMetaDataName(PyObject name) { - String metaName = super.getMetaDataName(name); - return (metaName == null) ? null : metaName.toUpperCase(); } /** * Provide functionality for Oracle specific types, such as ROWID. */ - public void setJDBCObject(PreparedStatement stmt, int index, PyObject object, int type) throws SQLException { - + @Override + public void setJDBCObject(PreparedStatement stmt, int index, PyObject object, int type) + throws SQLException { if (DataHandler.checkNull(stmt, index, object, type)) { return; } @@ -102,22 +102,15 @@ /** * Provide functionality for Oracle specific types, such as ROWID. */ + @Override public PyObject getPyObject(ResultSet set, int col, int type) throws SQLException { - PyObject obj = Py.None; switch (type) { case Types.BLOB: BLOB blob = ((OracleResultSet) set).getBLOB(col); - - if (blob == null) { - return Py.None; - } - - InputStream stream = new BufferedInputStream(blob.getBinaryStream()); - - obj = Py.java2py(DataHandler.read(stream)); + obj = blob == null ? Py.None : Py.java2py(read(blob.getBinaryStream())); break; case OracleTypes.ROWID: @@ -132,7 +125,7 @@ obj = super.getPyObject(set, col, type); } - return (set.wasNull() ? Py.None : obj); + return set.wasNull() ? Py.None : obj; } /** @@ -146,7 +139,9 @@ * @param dataTypeName the JDBC datatype name * @throws SQLException */ - public void registerOut(CallableStatement statement, int index, int colType, int dataType, String dataTypeName) throws SQLException { + @Override + public void registerOut(CallableStatement statement, int index, int colType, int dataType, + String dataTypeName) throws SQLException { if (dataType == Types.OTHER) { if ("REF CURSOR".equals(dataTypeName)) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-07-31 05:02:13
|
Revision: 6611 http://jython.svn.sourceforge.net/jython/?rev=6611&view=rev Author: pjenvey Date: 2009-07-31 05:01:54 +0000 (Fri, 31 Jul 2009) Log Message: ----------- quiet warnings, some coding standards Modified Paths: -------------- trunk/jython/src/com/ziclix/python/sql/Fetch.java trunk/jython/src/com/ziclix/python/sql/PyExtendedCursor.java trunk/jython/src/com/ziclix/python/sql/util/PyArgParser.java trunk/jython/src/com/ziclix/python/sql/util/Queue.java Modified: trunk/jython/src/com/ziclix/python/sql/Fetch.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/Fetch.java 2009-07-31 04:52:17 UTC (rev 6610) +++ trunk/jython/src/com/ziclix/python/sql/Fetch.java 2009-07-31 05:01:54 UTC (rev 6611) @@ -79,7 +79,7 @@ /** * A list of warning listeners. */ - private List listeners; + private List<WarningListener> listeners; /** * Constructor Fetch @@ -92,7 +92,7 @@ this.rownumber = -1; this.description = Py.None; this.datahandler = datahandler; - this.listeners = new ArrayList(3); + this.listeners = new ArrayList<WarningListener>(3); } /** @@ -142,7 +142,7 @@ * @param resultSet * @param skipCols JDBC-indexed set of columns to be skipped */ - abstract public void add(ResultSet resultSet, Set skipCols); + abstract public void add(ResultSet resultSet, Set<Integer> skipCols); /** * Method add @@ -151,7 +151,8 @@ * @param procedure * @param params */ - abstract public void add(CallableStatement callableStatement, Procedure procedure, PyObject params); + abstract public void add(CallableStatement callableStatement, Procedure procedure, + PyObject params); /** * Fetch the next row of a query result set, returning a single sequence, @@ -253,7 +254,6 @@ * 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++) { @@ -265,7 +265,6 @@ a[3] = Py.None; switch (meta.getColumnType(i)) { - case Types.BIGINT: case Types.BIT: case Types.DECIMAL: @@ -284,7 +283,6 @@ } a[6] = Py.newInteger(meta.isNullable(i)); - ((PyList) metadata).append(new PyTuple(a)); } @@ -299,7 +297,6 @@ * 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++) { @@ -307,7 +304,6 @@ int colType = column.__getitem__(Procedure.COLUMN_TYPE).asInt(); switch (colType) { - case DatabaseMetaData.procedureColumnReturn: PyObject[] a = new PyObject[7]; @@ -317,7 +313,6 @@ a[3] = column.__getitem__(Procedure.LENGTH); switch (a[1].asInt()) { - case Types.BIGINT: case Types.BIT: case Types.DECIMAL: @@ -336,9 +331,7 @@ } int nullable = column.__getitem__(Procedure.NULLABLE).asInt(); - a[6] = (nullable == DatabaseMetaData.procedureNullable) ? Py.One : Py.Zero; - ((PyList) metadata).append(new PyTuple(a)); break; } @@ -356,8 +349,8 @@ * @return PyObject * @throws SQLException */ - protected PyObject createResults(CallableStatement callableStatement, Procedure procedure, PyObject params) 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++) { @@ -367,7 +360,6 @@ int dataType = column.__getitem__(Procedure.DATA_TYPE).asInt(); switch (colType) { - case DatabaseMetaData.procedureColumnIn: j++; break; @@ -399,9 +391,7 @@ } PyList ret = new PyList(); - ret.append(PyTuple.fromIterable(results)); - return ret; } @@ -413,13 +403,12 @@ * @return a list of tuples of the results * @throws SQLException */ - protected PyList createResults(ResultSet set, Set skipCols, PyObject metaData) 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); } @@ -434,40 +423,36 @@ * @return a tuple of the results * @throws SQLException */ - protected PyTuple createResult(ResultSet set, Set skipCols, PyObject metaData) 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(new Integer(i + 1))) { + 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); } - PyTuple tuple = new PyTuple(row); - - return tuple; + return new PyTuple(row); } protected void fireWarning(SQLWarning warning) { - WarningEvent event = new WarningEvent(this, warning); - for (int i = listeners.size() - 1; i >= 0; i--) { + for (WarningListener listener : listeners) { try { - ((WarningListener) listeners.get(i)).warning(event); + listener.warning(event); } catch (Throwable t) { + // ok } } } @@ -493,23 +478,21 @@ /** * Field results */ - protected List results; + protected List<PyObject> results; /** * Field descriptions */ - protected List 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(); - this.descriptions = new LinkedList(); + this.results = new LinkedList<PyObject>(); + this.descriptions = new LinkedList<PyObject>(); } /** @@ -517,6 +500,7 @@ * * @param resultSet */ + @Override public void add(ResultSet resultSet) { this.add(resultSet, null); } @@ -527,10 +511,10 @@ * @param resultSet * @param skipCols */ - public void add(ResultSet resultSet, Set skipCols) { - + @Override + public void add(ResultSet resultSet, Set<Integer> skipCols) { try { - if ((resultSet != null) && (resultSet.getMetaData() != null)) { + if (resultSet != null && resultSet.getMetaData() != null) { PyObject metadata = this.createDescription(resultSet.getMetaData()); PyObject result = this.createResults(resultSet, skipCols, metadata); @@ -538,10 +522,10 @@ this.descriptions.add(metadata); // we want the rowcount of the first result set - this.rowcount = ((PyObject) this.results.get(0)).__len__(); + this.rowcount = this.results.get(0).__len__(); // we want the description of the first result set - this.description = ((PyObject) this.descriptions.get(0)); + this.description = this.descriptions.get(0); // set the current rownumber this.rownumber = 0; @@ -565,8 +549,8 @@ * @param procedure * @param params */ + @Override public void add(CallableStatement callableStatement, Procedure procedure, PyObject params) { - try { PyObject result = this.createResults(callableStatement, procedure, params); @@ -575,10 +559,10 @@ this.descriptions.add(this.createDescription(procedure)); // we want the rowcount of the first result set - this.rowcount = ((PyObject) this.results.get(0)).__len__(); + this.rowcount = this.results.get(0).__len__(); // we want the description of the first result set - this.description = ((PyObject) this.descriptions.get(0)); + this.description = this.descriptions.get(0); // set the current rownumber this.rownumber = 0; @@ -601,6 +585,7 @@ * @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); } @@ -627,21 +612,22 @@ * @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)) { + if (results == null || results.size() == 0) { throw zxJDBC.makeException(zxJDBC.DatabaseError, "no results"); } PyObject res = new PyList(); - PyObject current = (PyObject) results.get(0); + 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); + res = current.__getslice__(Py.newInteger(this.rownumber), + Py.newInteger(this.rownumber + size), Py.One); this.rownumber += size; } @@ -654,8 +640,8 @@ * @param value * @param mode 'relative' or 'absolute' */ + @Override public void scroll(int value, String mode) { - int pos; if ("relative".equals(mode)) { @@ -663,10 +649,11 @@ } else if ("absolute".equals(mode)) { pos = value; } else { - throw zxJDBC.makeException(zxJDBC.ProgrammingError, "invalid cursor scroll mode [" + mode + "]"); + throw zxJDBC.makeException(zxJDBC.ProgrammingError, "invalid cursor scroll mode [" + + mode + "]"); } - if ((pos >= 0) && (pos < this.rowcount)) { + if (pos >= 0 && pos < this.rowcount) { this.rownumber = pos; } else { throw zxJDBC.makeException(Py.IndexError, "cursor index [" + pos + "] out of range"); @@ -678,32 +665,30 @@ * * @return true if more sets exist, else None */ + @Override public PyObject nextset() { - PyObject next = Py.None; - if ((results != null) && (results.size() > 1)) { + if (results != null && results.size() > 1) { this.results.remove(0); this.descriptions.remove(0); - next = (PyObject) this.results.get(0); - this.description = (PyObject) this.descriptions.get(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; + 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(); } } @@ -720,7 +705,7 @@ /** * Field skipCols */ - protected Set skipCols; + protected Set<Integer> skipCols; /** * Field resultSet @@ -741,6 +726,7 @@ * 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); } @@ -752,14 +738,14 @@ * at any one time. Since this is a dynamic iteration, it precludes * the addition of more than one result set. */ - public void add(ResultSet resultSet, Set skipCols) { - + @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 (resultSet != null && resultSet.getMetaData() != null) { if (this.description == Py.None) { this.description = this.createDescription(resultSet.getMetaData()); } @@ -787,13 +773,16 @@ * @param procedure * @param params */ + @Override public void add(CallableStatement callableStatement, Procedure procedure, PyObject params) { - throw zxJDBC.makeException(zxJDBC.NotSupportedError, zxJDBC.getString("nocallprocsupport")); + 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); } @@ -801,6 +790,7 @@ /** * Iterate up to size rows remaining in the ResultSet and return. */ + @Override public PyObject fetchmany(int size) { return fetch(size, false); } @@ -812,7 +802,6 @@ * the set. */ private PyObject fetch(int size, boolean all) { - PyList res = new PyList(); if (this.resultSet == null) { @@ -822,14 +811,15 @@ try { all = (size < 0) ? true : all; - while (((size-- > 0) || all) && this.resultSet.next()) { + 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")); + throw zxJDBC.makeException(zxJDBC.NotSupportedError, + zxJDBC.getString("nodynamiccursors")); } catch (PyException e) { throw e; } catch (Throwable e) { @@ -842,6 +832,7 @@ /** * Always returns None. */ + @Override public PyObject nextset() { return Py.None; } @@ -852,12 +843,12 @@ * @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 (type != ResultSet.TYPE_FORWARD_ONLY || value > 0) { if ("relative".equals(mode)) { if (value < 0) { value = Math.abs(this.rownumber + value); @@ -866,29 +857,33 @@ } } else if ("absolute".equals(mode)) { if (value < 0) { - throw zxJDBC.makeException(Py.IndexError, "cursor index [" + value + "] out of range"); + throw zxJDBC.makeException(Py.IndexError, "cursor index [" + value + + "] out of range"); } } else { - throw zxJDBC.makeException(zxJDBC.ProgrammingError, "invalid cursor scroll mode [" + mode + "]"); + 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"); + 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"; - + 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")); + throw zxJDBC.makeException(zxJDBC.NotSupportedError, + zxJDBC.getString("nodynamiccursors")); } catch (SQLException e) { throw zxJDBC.makeException(e); } catch (Throwable t) { @@ -899,8 +894,8 @@ /** * Close the underlying ResultSet. */ + @Override public void close() throws SQLException { - super.close(); if (this.resultSet == null) { Modified: trunk/jython/src/com/ziclix/python/sql/PyExtendedCursor.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/PyExtendedCursor.java 2009-07-31 04:52:17 UTC (rev 6610) +++ trunk/jython/src/com/ziclix/python/sql/PyExtendedCursor.java 2009-07-31 05:01:54 UTC (rev 6611) @@ -14,7 +14,6 @@ import java.util.Set; import org.python.core.Py; import org.python.core.PyBuiltinMethodSet; -import org.python.core.PyClass; import org.python.core.PyList; import org.python.core.PyObject; import org.python.core.PyString; @@ -86,7 +85,8 @@ * @param rsType * @param rsConcur */ - PyExtendedCursor(PyConnection connection, boolean dynamicFetch, PyObject rsType, PyObject rsConcur) { + PyExtendedCursor(PyConnection connection, boolean dynamicFetch, PyObject rsType, + PyObject rsConcur) { super(connection, dynamicFetch, rsType, rsConcur); } @@ -95,6 +95,7 @@ * * @return a string representation of the object. */ + @Override public String toString() { return "<PyExtendedCursor object instance at " + Py.id(this) + ">"; } @@ -105,7 +106,6 @@ * @param dict */ static public void classDictInit(PyObject dict) { - PyCursor.classDictInit(dict); dict.__setitem__("__version__", Py.newString("$Revision$").__getslice__(Py.newInteger(11), Py.newInteger(-2), null)); dict.__setitem__("tables", new ExtendedCursorFunc("tables", 100, 4, 4, "query for table information")); @@ -131,8 +131,8 @@ * @param name the name of the attribute of interest * @return the value for the attribute of the specified name */ + @Override public PyObject __findattr_ex__(String name) { - if ("__methods__".equals(name)) { return __methods__; } else if ("__members__".equals(name)) { @@ -153,7 +153,6 @@ * @param type */ protected void tables(PyObject qualifier, PyObject owner, PyObject table, PyObject type) { - clear(); String q = getMetaDataName(qualifier); @@ -197,7 +196,6 @@ * @param column */ protected void columns(PyObject qualifier, PyObject owner, PyObject table, PyObject column) { - clear(); String q = getMetaDataName(qualifier); @@ -220,7 +218,6 @@ * @param procedure */ protected void procedures(PyObject qualifier, PyObject owner, PyObject procedure) { - clear(); String q = getMetaDataName(qualifier); @@ -242,8 +239,8 @@ * @param procedure * @param column */ - protected void procedurecolumns(PyObject qualifier, PyObject owner, PyObject procedure, PyObject column) { - + protected void procedurecolumns(PyObject qualifier, PyObject owner, PyObject procedure, + PyObject column) { clear(); String q = getMetaDataName(qualifier); @@ -296,8 +293,9 @@ * @param foreignOwner * @param foreignTable */ - protected void foreignkeys(PyObject primaryQualifier, PyObject primaryOwner, PyObject primaryTable, PyObject foreignQualifier, PyObject foreignOwner, PyObject foreignTable) { - + protected void foreignkeys(PyObject primaryQualifier, PyObject primaryOwner, + PyObject primaryTable, PyObject foreignQualifier, + PyObject foreignOwner, PyObject foreignTable) { clear(); String pq = getMetaDataName(primaryQualifier); @@ -324,14 +322,13 @@ * @param unique * @param accuracy */ - protected void statistics(PyObject qualifier, PyObject owner, PyObject table, PyObject unique, PyObject accuracy) { - + protected void statistics(PyObject qualifier, PyObject owner, PyObject table, PyObject unique, + PyObject accuracy) { clear(); - Set skipCols = new HashSet(); + Set<Integer> skipCols = new HashSet<Integer>(); + skipCols.add(12); - skipCols.add(new Integer(12)); - String q = getMetaDataName(qualifier); String o = getMetaDataName(owner); String t = getMetaDataName(table); @@ -351,14 +348,12 @@ * @param type data type for which to provide information */ protected void typeinfo(PyObject type) { - clear(); - Set skipCols = new HashSet(); + Set<Integer> skipCols = new HashSet<Integer>(); + skipCols.add(16); + skipCols.add(17); - skipCols.add(new Integer(16)); - skipCols.add(new Integer(17)); - try { this.fetch.add(getMetaData().getTypeInfo(), skipCols); } catch (SQLException e) { @@ -384,7 +379,6 @@ * Gets a description of possible table types. */ protected void tabletypeinfo() { - clear(); try { @@ -403,7 +397,6 @@ * @param table */ protected void bestrow(PyObject qualifier, PyObject owner, PyObject table) { - clear(); String c = getMetaDataName(qualifier); @@ -428,7 +421,6 @@ * @param table a table name */ protected void versioncolumns(PyObject qualifier, PyObject owner, PyObject table) { - clear(); String q = getMetaDataName(qualifier); @@ -449,7 +441,6 @@ * @return String */ protected String getMetaDataName(PyObject name) { - if (name == Py.None) { return null; } @@ -481,20 +472,17 @@ super(name, index, minargs, maxargs, doc, PyExtendedCursor.class); } + @Override public PyObject __call__() { - PyExtendedCursor cursor = (PyExtendedCursor) __self__; switch (index) { - case 107: cursor.typeinfo(Py.None); - return Py.None; case 108: cursor.tabletypeinfo(); - return Py.None; default : @@ -502,15 +490,13 @@ } } + @Override public PyObject __call__(PyObject arga) { - PyExtendedCursor cursor = (PyExtendedCursor) __self__; switch (index) { - case 107: cursor.typeinfo(arga); - return Py.None; default : @@ -518,80 +504,68 @@ } } + @Override public PyObject __call__(PyObject arga, PyObject argb, PyObject argc) { - PyExtendedCursor cursor = (PyExtendedCursor) __self__; switch (index) { - case 102: cursor.primarykeys(arga, argb, argc); - return Py.None; case 104: cursor.procedures(arga, argb, argc); - return Py.None; case 109: cursor.bestrow(arga, argb, argc); - return Py.None; case 110: cursor.versioncolumns(arga, argb, argc); - return Py.None; - default : + default: throw info.unexpectedCall(3, false); } } + @Override public PyObject fancyCall(PyObject[] args) { - PyExtendedCursor cursor = (PyExtendedCursor) __self__; switch (index) { - case 103: cursor.foreignkeys(args[0], args[1], args[2], args[3], args[4], args[5]); - return Py.None; case 106: cursor.statistics(args[0], args[1], args[2], args[3], args[4]); - return Py.None; - default : + default: throw info.unexpectedCall(args.length, true); } } + @Override public PyObject __call__(PyObject arg1, PyObject arg2, PyObject arg3, PyObject arg4) { - PyExtendedCursor cursor = (PyExtendedCursor) __self__; switch (index) { - case 100: cursor.tables(arg1, arg2, arg3, arg4); - return Py.None; case 101: cursor.columns(arg1, arg2, arg3, arg4); - return Py.None; case 105: cursor.procedurecolumns(arg1, arg2, arg3, arg4); - return Py.None; - default : + default: throw info.unexpectedCall(4, false); } } Modified: trunk/jython/src/com/ziclix/python/sql/util/PyArgParser.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/util/PyArgParser.java 2009-07-31 04:52:17 UTC (rev 6610) +++ trunk/jython/src/com/ziclix/python/sql/util/PyArgParser.java 2009-07-31 05:01:54 UTC (rev 6611) @@ -22,24 +22,18 @@ */ public class PyArgParser extends Object { - /** - * Field keywords - */ - protected Map keywords; + /** Field keywords. */ + protected Map<String, PyObject> keywords; - /** - * Field arguments - */ + /** Field arguments. */ protected PyObject[] arguments; /** * Construct a parser with the arguments and keywords. */ public PyArgParser(PyObject[] args, String[] kws) { - - this.keywords = new HashMap(); - this.arguments = null; - + keywords = new HashMap<String, PyObject>(); + arguments = null; parse(args, kws); } @@ -50,33 +44,31 @@ * @param kws */ protected void parse(PyObject[] args, String[] kws) { - // walk backwards through the kws and build the map int largs = args.length; if (kws != null) { - for (int i = kws.length - 1; i >= 0; i--) { - keywords.put(kws[i], args[--largs]); + for (String kw: kws) { + keywords.put(kw, args[--largs]); } } - this.arguments = new PyObject[largs]; - - System.arraycopy(args, 0, this.arguments, 0, largs); + arguments = new PyObject[largs]; + System.arraycopy(args, 0, arguments, 0, largs); } /** * How many keywords? */ public int numKw() { - return this.keywords.keySet().size(); + return keywords.keySet().size(); } /** * Does the keyword exist? */ public boolean hasKw(String kw) { - return this.keywords.containsKey(kw); + return keywords.containsKey(kw); } /** @@ -84,12 +76,11 @@ * not exist. */ public PyObject kw(String kw) { - if (!hasKw(kw)) { throw Py.KeyError(kw); } - return (PyObject) this.keywords.get(kw); + return keywords.get(kw); } /** @@ -97,35 +88,33 @@ * not exist. */ public PyObject kw(String kw, PyObject def) { - if (!hasKw(kw)) { return def; } - return (PyObject) this.keywords.get(kw); + return keywords.get(kw); } /** * Get the array of keywords. */ public String[] kws() { - return (String[]) this.keywords.keySet().toArray(new String[0]); + return keywords.keySet().toArray(new String[0]); } /** * Get the number of arguments. */ public int numArg() { - return this.arguments.length; + return arguments.length; } /** * Return the argument at the given index, raise an IndexError if out of range. */ public PyObject arg(int index) { - - if ((index >= 0) && (index <= this.arguments.length - 1)) { - return this.arguments[index]; + if (index >= 0 && index <= arguments.length - 1) { + return arguments[index]; } throw Py.IndexError("index out of range"); @@ -135,9 +124,8 @@ * Return the argument at the given index, or the default if the index is out of range. */ public PyObject arg(int index, PyObject def) { - - if ((index >= 0) && (index <= this.arguments.length - 1)) { - return this.arguments[index]; + if (index >= 0 && index <= arguments.length - 1) { + return arguments[index]; } return def; Modified: trunk/jython/src/com/ziclix/python/sql/util/Queue.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/util/Queue.java 2009-07-31 04:52:17 UTC (rev 6610) +++ trunk/jython/src/com/ziclix/python/sql/util/Queue.java 2009-07-31 05:01:54 UTC (rev 6611) @@ -28,7 +28,7 @@ /** * Field queue */ - protected LinkedList queue; + protected LinkedList<Object> queue; /** * Field capacity, threshold @@ -49,7 +49,7 @@ this.closed = false; this.capacity = capacity; - this.queue = new LinkedList(); + this.queue = new LinkedList<Object>(); this.threshold = (int) (this.capacity * 0.75f); } @@ -57,7 +57,6 @@ * Enqueue an object and notify all waiting Threads. */ public synchronized void enqueue(Object element) throws InterruptedException { - if (closed) { throw new QueueClosedException(); } @@ -81,7 +80,6 @@ * Blocks until an object is dequeued or the queue is closed. */ public synchronized Object dequeue() throws InterruptedException { - while (this.queue.size() <= 0) { this.wait(); @@ -104,9 +102,7 @@ * Close the queue and notify all waiting Threads. */ public synchronized void close() { - this.closed = true; - this.notifyAll(); } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-08-12 03:12:32
|
Revision: 6663 http://jython.svn.sourceforge.net/jython/?rev=6663&view=rev Author: pjenvey Date: 2009-08-12 03:12:07 +0000 (Wed, 12 Aug 2009) Log Message: ----------- cleanup/quiet warnings Modified Paths: -------------- trunk/jython/src/com/ziclix/python/sql/PyConnection.java trunk/jython/src/com/ziclix/python/sql/connect/Connectx.java trunk/jython/src/com/ziclix/python/sql/connect/Lookup.java Modified: trunk/jython/src/com/ziclix/python/sql/PyConnection.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/PyConnection.java 2009-08-11 06:45:00 UTC (rev 6662) +++ trunk/jython/src/com/ziclix/python/sql/PyConnection.java 2009-08-12 03:12:07 UTC (rev 6663) @@ -12,13 +12,11 @@ import java.sql.SQLException; import java.util.Collections; import java.util.HashSet; -import java.util.Iterator; import java.util.Set; import org.python.core.ClassDictInit; import org.python.core.Py; import org.python.core.PyBuiltinMethodSet; -import org.python.core.PyClass; import org.python.core.PyInteger; import org.python.core.PyList; import org.python.core.PyObject; @@ -36,39 +34,25 @@ */ public class PyConnection extends PyObject implements ClassDictInit { - /** - * Field closed - */ + /** True if closed. */ protected boolean closed; - /** - * Field connection - */ - protected Connection connection; - - /** - * Field supportsTransactions - */ + /** Whether transactions are supported. */ protected boolean supportsTransactions; - /** - * Field cursors - */ - private Set cursors; + /** The underlying java.sql.Connection. */ + protected Connection connection; - /** - * Field statements - */ - private Set statements; + /** Underlying cursors. */ + private Set<PyCursor> cursors; - /** - * Field __members__ - */ + /** Underlying statements. */ + private Set<PyStatement> statements; + + /** Field __members__ */ protected static PyList __members__; - /** - * Field __methods__ - */ + /** Field __methods__ */ protected static PyList __methods__; static { @@ -101,11 +85,10 @@ * @throws SQLException */ public PyConnection(Connection connection) throws SQLException { - this.closed = false; - this.cursors = new HashSet(); + this.cursors = new HashSet<PyCursor>(); this.connection = connection; - this.statements = new HashSet(); + this.statements = new HashSet<PyStatement>(); this.supportsTransactions = this.connection.getMetaData().supportsTransactions(); if (this.supportsTransactions) { @@ -120,7 +103,6 @@ */ @Override public String toString() { - try { return String.format("<PyConnection object at %s user='%s', url='%s'>", Py.idstr(this), connection.getMetaData().getUserName(), @@ -136,14 +118,20 @@ * @param dict */ static public void classDictInit(PyObject dict) { - + PyObject version = + Py.newString("$Revision$").__getslice__(Py.newInteger(11), + Py.newInteger(-2)); + dict.__setitem__("__version__", version); dict.__setitem__("autocommit", new PyInteger(0)); - dict.__setitem__("__version__", Py.newString("$Revision$").__getslice__(Py.newInteger(11), Py.newInteger(-2), null)); dict.__setitem__("close", new ConnectionFunc("close", 0, 0, 0, zxJDBC.getString("close"))); - dict.__setitem__("commit", new ConnectionFunc("commit", 1, 0, 0, zxJDBC.getString("commit"))); - dict.__setitem__("cursor", new ConnectionFunc("cursor", 2, 0, 4, zxJDBC.getString("cursor"))); - dict.__setitem__("rollback", new ConnectionFunc("rollback", 3, 0, 0, zxJDBC.getString("rollback"))); - dict.__setitem__("nativesql", new ConnectionFunc("nativesql", 4, 1, 1, zxJDBC.getString("nativesql"))); + dict.__setitem__("commit", new ConnectionFunc("commit", 1, 0, 0, + zxJDBC.getString("commit"))); + dict.__setitem__("cursor", new ConnectionFunc("cursor", 2, 0, 4, + zxJDBC.getString("cursor"))); + dict.__setitem__("rollback", new ConnectionFunc("rollback", 3, 0, 0, + zxJDBC.getString("rollback"))); + dict.__setitem__("nativesql", new ConnectionFunc("nativesql", 4, 1, 1, + zxJDBC.getString("nativesql"))); // hide from python dict.__setitem__("initModule", null); @@ -161,8 +149,8 @@ * @param name * @param value */ + @Override public void __setattr__(String name, PyObject value) { - if ("autocommit".equals(name)) { try { if (this.supportsTransactions) { @@ -171,7 +159,6 @@ } catch (SQLException e) { throw zxJDBC.makeException(zxJDBC.DatabaseError, e); } - return; } @@ -184,8 +171,8 @@ * @param name the name of the attribute of interest * @return the value for the attribute of the specified name */ + @Override public PyObject __findattr_ex__(String name) { - if ("autocommit".equals(name)) { try { return connection.getAutoCommit() ? Py.One : Py.Zero; @@ -240,40 +227,31 @@ } /** - * Close the connection now (rather than whenever __del__ is called). - * The connection will be unusable from this point forward; an Error - * (or subclass) exception will be raised if any operation is attempted - * with the connection. The same applies to all cursor objects trying - * to use the connection. + * Close the connection now (rather than whenever __del__ is called). The connection + * will be unusable from this point forward; an Error (or subclass) exception will be + * raised if any operation is attempted with the connection. The same applies to all + * cursor objects trying to use the connection. */ public void close() { - if (closed) { throw zxJDBC.makeException(zxJDBC.ProgrammingError, "connection is closed"); } - // mark ourselves closed now so that any callbacks we - // get from closing down cursors and statements to not - // try and modify our internal sets + // mark ourselves closed now so that any callbacks we get from closing down + // cursors and statements to not try and modify our internal sets this.closed = true; synchronized (this.cursors) { - - // close the cursors - for (Iterator i = this.cursors.iterator(); i.hasNext();) { - ((PyCursor) i.next()).close(); + for (PyCursor cursor: cursors) { + cursor.close(); } - this.cursors.clear(); } synchronized (this.statements) { - - // close the cursors - for (Iterator i = this.statements.iterator(); i.hasNext();) { - ((PyStatement) i.next()).close(); + for (PyStatement statement : statements) { + statement.close(); } - this.statements.clear(); } @@ -285,15 +263,14 @@ } /** - * Commit any pending transaction to the database. Note that if the - * database supports an auto-commit feature, this must be initially - * off. An interface method may be provided to turn it back on. + * Commit any pending transaction to the database. Note that if the database supports + * an auto-commit feature, this must be initially off. An interface method may be + * provided to turn it back on. * <p/> - * Database modules that do not support transactions should implement - * this method with void functionality. + * Database modules that do not support transactions should implement this method with + * void functionality. */ public void commit() { - if (closed) { throw zxJDBC.makeException(zxJDBC.ProgrammingError, "connection is closed"); } @@ -310,16 +287,13 @@ } /** - * <i>This method is optional since not all databases provide transaction - * support.</i> + * <i>This method is optional since not all databases provide transaction support.</i> * <p/> - * In case a database does provide transactions this method causes the database - * to roll back to the start of any pending transaction. Closing a connection - * without committing the changes first will cause an implicit rollback to be - * performed. + * In case a database does provide transactions this method causes the database to + * roll back to the start of any pending transaction. Closing a connection without + * committing the changes first will cause an implicit rollback to be performed. */ public void rollback() { - if (closed) { throw zxJDBC.makeException(zxJDBC.ProgrammingError, "connection is closed"); } @@ -336,10 +310,10 @@ } /** - * Converts the given SQL statement into the system's native SQL grammar. A - * driver may convert the JDBC sql grammar into its system's native SQL grammar - * prior to sending it; this method returns the native form of the statement - * that the driver would have sent. + * Converts the given SQL statement into the system's native SQL grammar. A driver may + * convert the JDBC sql grammar into its system's native SQL grammar prior to sending + * it; this method returns the native form of the statement that the driver would have + * sent. * * @param nativeSQL * @return the native form of this statement @@ -364,9 +338,9 @@ } /** - * Return a new Cursor Object using the connection. If the database does not - * provide a direct cursor concept, the module will have to emulate cursors - * using other means to the extent needed by this specification. + * Return a new Cursor Object using the connection. If the database does not provide a + * direct cursor concept, the module will have to emulate cursors using other means to + * the extent needed by this specification. * * @return a new cursor using this connection */ @@ -375,9 +349,9 @@ } /** - * Return a new Cursor Object using the connection. If the database does not - * provide a direct cursor concept, the module will have to emulate cursors - * using other means to the extent needed by this specification. + * Return a new Cursor Object using the connection. If the database does not provide a + * direct cursor concept, the module will have to emulate cursors using other means to + * the extent needed by this specification. * * @param dynamicFetch if true, dynamically iterate the result * @return a new cursor using this connection @@ -387,9 +361,9 @@ } /** - * Return a new Cursor Object using the connection. If the database does not - * provide a direct cursor concept, the module will have to emulate cursors - * using other means to the extent needed by this specification. + * Return a new Cursor Object using the connection. If the database does not provide a + * direct cursor concept, the module will have to emulate cursors using other means to + * the extent needed by this specification. * * @param dynamicFetch if true, dynamically iterate the result * @param rsType the type of the underlying ResultSet @@ -397,15 +371,12 @@ * @return a new cursor using this connection */ public PyCursor cursor(boolean dynamicFetch, PyObject rsType, PyObject rsConcur) { - if (closed) { throw zxJDBC.makeException(zxJDBC.ProgrammingError, "connection is closed"); } PyCursor cursor = new PyExtendedCursor(this, dynamicFetch, rsType, rsConcur); - this.cursors.add(cursor); - return cursor; } @@ -415,11 +386,9 @@ * @param cursor */ void remove(PyCursor cursor) { - if (closed) { return; } - this.cursors.remove(cursor); } @@ -429,11 +398,9 @@ * @param statement statement */ void add(PyStatement statement) { - if (closed) { return; } - this.statements.add(statement); } @@ -444,20 +411,20 @@ * @return boolean */ boolean contains(PyStatement statement) { - if (closed) { return false; } - return this.statements.contains(statement); } } class ConnectionFunc extends PyBuiltinMethodSet { + ConnectionFunc(String name, int index, int minargs, int maxargs, String doc) { super(name, index, minargs, maxargs, doc, PyConnection.class); } + @Override public PyObject __call__() { PyConnection c = (PyConnection) __self__; switch (index) { @@ -472,11 +439,12 @@ case 3: c.rollback(); return Py.None; - default : + default: throw info.unexpectedCall(0, false); } } + @Override public PyObject __call__(PyObject arg) { PyConnection c = (PyConnection) __self__; switch (index) { @@ -484,21 +452,23 @@ return c.cursor(arg.__nonzero__()); case 4: return c.nativesql(arg); - default : + default: throw info.unexpectedCall(1, false); } } + @Override public PyObject __call__(PyObject arg1, PyObject arg2, PyObject arg3) { PyConnection c = (PyConnection) __self__; switch (index) { case 2: return c.cursor(arg1.__nonzero__(), arg2, arg3); - default : + default: throw info.unexpectedCall(3, false); } } + @Override public PyObject __call__(PyObject[] args, String[] keywords) { PyConnection c = (PyConnection) __self__; PyArgParser parser = new PyArgParser(args, keywords); @@ -514,7 +484,7 @@ return c.cursor(dynamic.__nonzero__(), rstype, rsconcur); - default : + default: throw info.unexpectedCall(args.length, true); } } Modified: trunk/jython/src/com/ziclix/python/sql/connect/Connectx.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/connect/Connectx.java 2009-08-11 06:45:00 UTC (rev 6662) +++ trunk/jython/src/com/ziclix/python/sql/connect/Connectx.java 2009-08-12 03:12:07 UTC (rev 6663) @@ -35,14 +35,11 @@ public class Connectx extends PyObject { private final String SET = "set"; - private final PyString doc = new PyString("establish a connection through a javax.sql.DataSource or javax.sql.ConnectionPooledDataSource"); + private final PyString doc = + new PyString("establish a connection through a javax.sql.DataSource or " + + "javax.sql.ConnectionPooledDataSource"); - /** - * Constructor Connectx - */ - public Connectx() { - } - + @Override public PyObject __findattr_ex__(String name) { if ("__doc__".equals(name)) { return doc; @@ -53,23 +50,21 @@ /** * Construct a javax.sql.DataSource or javax.sql.ConnectionPooledDataSource */ + @Override public PyObject __call__(PyObject[] args, String[] keywords) { - Connection c = null; PyConnection pc = null; Object datasource = null; PyArgParser parser = new PyArgParser(args, keywords); try { - String _class = (String) parser.arg(0).__tojava__(String.class); - - datasource = Class.forName(_class).newInstance(); + String klass = (String) parser.arg(0).__tojava__(String.class); + datasource = Class.forName(klass).newInstance(); } catch (Exception e) { throw zxJDBC.makeException(zxJDBC.DatabaseError, "unable to instantiate datasource"); } String[] kws = parser.kws(); - for (int i = 0; i < kws.length; i++) { String methodName = kws[i]; @@ -78,21 +73,21 @@ } Object value = parser.kw(kws[i]).__tojava__(Object.class); - if (methodName.length() > SET.length()) { if (!SET.equals(methodName.substring(0, SET.length()))) { - // prepend "set" - invoke(datasource, SET + methodName.substring(0, 1).toUpperCase() + methodName.substring(1), value); + invoke(datasource, SET + methodName.substring(0, 1).toUpperCase() + + methodName.substring(1), value); } else { - // starts with "set" so just pass it on invoke(datasource, methodName, value); } } else { // shorter than "set" so it can't be a full method name - invoke(datasource, SET + methodName.substring(0, 1).toUpperCase() + methodName.substring(1), value); + invoke(datasource, + SET + methodName.substring(0, 1).toUpperCase() + methodName.substring(1), + value); } } @@ -107,7 +102,7 @@ } try { - if ((c == null) || c.isClosed()) { + if (c == null || c.isClosed()) { throw zxJDBC.makeException(zxJDBC.DatabaseError, "unable to establish connection"); } @@ -124,8 +119,9 @@ * * @return String */ + @Override public String toString() { - return "<connectx object instance at " + Py.id(this) + ">"; + return String.format("<connectx object at %s>", Py.id(this)); } /** @@ -136,19 +132,17 @@ * @param Object value */ protected void invoke(Object src, String methodName, Object value) { - Method method = null; - StringBuffer exceptionMsg = new StringBuffer("method [").append(methodName).append("] using arg type ["); + StringBuffer exceptionMsg = new StringBuffer("method ["); + exceptionMsg.append(methodName).append("] using arg type ["); + exceptionMsg.append(value.getClass()).append("], value ["); + exceptionMsg.append(value.toString()).append("]"); - exceptionMsg.append(value.getClass()).append("], value [").append(value.toString()).append("]"); - try { method = getMethod(src.getClass(), methodName, value.getClass()); - if (method == null) { throw zxJDBC.makeException("no such " + exceptionMsg); } - method.invoke(src, new Object[]{value}); } catch (IllegalAccessException e) { throw zxJDBC.makeException("illegal access for " + exceptionMsg); @@ -164,25 +158,23 @@ * is perhaps a primitive and attempt to recurse using the primitive type. Failing * that return null. */ - protected Method getMethod(Class srcClass, String methodName, Class valueClass) { - + protected Method getMethod(Class<?> srcClass, String methodName, Class<?> valueClass) { Method method = null; try { method = srcClass.getMethod(methodName, new Class[]{valueClass}); } catch (NoSuchMethodException e) { - Class primitive = null; + Class<?> primitive = null; try { Field f = valueClass.getField("TYPE"); - - primitive = (Class) f.get(valueClass); + primitive = (Class<?>) f.get(valueClass); } catch (NoSuchFieldException ex) { } catch (IllegalAccessException ex) { } catch (ClassCastException ex) { } - if ((primitive != null) && primitive.isPrimitive()) { + if (primitive != null && primitive.isPrimitive()) { return getMethod(srcClass, methodName, primitive); } } Modified: trunk/jython/src/com/ziclix/python/sql/connect/Lookup.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/connect/Lookup.java 2009-08-11 06:45:00 UTC (rev 6662) +++ trunk/jython/src/com/ziclix/python/sql/connect/Lookup.java 2009-08-12 03:12:07 UTC (rev 6663) @@ -8,20 +8,31 @@ */ package com.ziclix.python.sql.connect; -import java.sql.*; -import java.util.*; import java.lang.reflect.Field; -import javax.sql.*; -import javax.naming.*; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.Hashtable; -import org.python.core.*; -import com.ziclix.python.sql.*; -import com.ziclix.python.sql.util.*; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.sql.ConnectionPoolDataSource; +import javax.sql.DataSource; +import org.python.core.Py; +import org.python.core.PyObject; +import org.python.core.PyString; + +import com.ziclix.python.sql.PyConnection; +import com.ziclix.python.sql.zxJDBC; +import com.ziclix.python.sql.util.PyArgParser; + /** - * Establish a connection through a JNDI lookup. The bound object can be either a <code>DataSource</code>, - * <code>ConnectionPooledDataSource</code>, <code>Connection</code> or a <code>String</code>. If it's a - * <code>String</code> the value is passed to the DriverManager to obtain a connection, otherwise the + * Establish a connection through a JNDI lookup. The bound object can be either a + * <code>DataSource</code>, <code>ConnectionPooledDataSource</code>, + * <code>Connection</code> or a <code>String</code>. If it's a <code>String</code> the + * value is passed to the DriverManager to obtain a connection, otherwise the * <code>Connection</code> is established using the object. * * @author brian zimmer @@ -30,22 +41,17 @@ */ public class Lookup extends PyObject { - private static final PyString _doc = new PyString("establish a connection through a JNDI lookup"); + private static final PyString _doc = + new PyString("establish a connection through a JNDI lookup"); /** - * Constructor Lookup - */ - public Lookup() { - } - - /** * Method __findattr__ * * @param name * @return PyObject */ + @Override public PyObject __findattr_ex__(String name) { - if ("__doc__".equals(name)) { return _doc; } @@ -54,17 +60,18 @@ } /** - * Expects a single PyString argument which is the JNDI name of the bound Connection or DataSource. - * If any keywords are passed, an attempt is made to match the keyword to a static final Field on - * javax.naming.Context. If the Field is found, the value of the Field is substituted as the key - * and the value of the keyword is the value put in the Hashtable environment. If the Field is not - * found, the key is the keyword with no substitutions. + * Expects a single PyString argument which is the JNDI name of the bound Connection + * or DataSource. If any keywords are passed, an attempt is made to match the keyword + * to a static final Field on javax.naming.Context. If the Field is found, the value + * of the Field is substituted as the key and the value of the keyword is the value + * put in the Hashtable environment. If the Field is not found, the key is the + * keyword with no substitutions. */ + @Override public PyObject __call__(PyObject[] args, String[] keywords) { - Object ref = null; Connection connection = null; - Hashtable env = new Hashtable(); + Hashtable<String, Object> env = new Hashtable<String, Object>(); // figure out the correct params PyArgParser parser = new PyArgParser(args, keywords); @@ -95,7 +102,6 @@ } InitialContext context = null; - try { context = new InitialContext(env); ref = context.lookup((String) jndiName); @@ -106,12 +112,14 @@ try { context.close(); } catch (NamingException e) { + // ok } } } if (ref == null) { - throw zxJDBC.makeException(zxJDBC.ProgrammingError, "object [" + jndiName + "] not found in JNDI"); + throw zxJDBC.makeException(zxJDBC.ProgrammingError, + "object [" + jndiName + "] not found in JNDI"); } try { @@ -122,14 +130,15 @@ } else if (ref instanceof DataSource) { connection = ((DataSource) ref).getConnection(); } else if (ref instanceof ConnectionPoolDataSource) { - connection = ((ConnectionPoolDataSource) ref).getPooledConnection().getConnection(); + connection = + ((ConnectionPoolDataSource) ref).getPooledConnection().getConnection(); } } catch (SQLException e) { throw zxJDBC.makeException(zxJDBC.DatabaseError, e); } try { - if ((connection == null) || connection.isClosed()) { + if (connection == null || connection.isClosed()) { throw zxJDBC.makeException(zxJDBC.DatabaseError, "unable to establish connection"); } @@ -144,7 +153,8 @@ * * @return String */ + @Override public String toString() { - return "<lookup object instance at " + Py.id(this) + ">"; + return String.format("<lookup object at %s>", Py.idstr(this)); } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-09-11 03:35:56
|
Revision: 6780 http://jython.svn.sourceforge.net/jython/?rev=6780&view=rev Author: pjenvey Date: 2009-09-11 03:35:35 +0000 (Fri, 11 Sep 2009) Log Message: ----------- support multiple ResultSets via cursor.nextset. to accommodate this staticFetch Statements are no longer immediately closed after execute (unless an exception was thrown), like dynamicFetch Modified Paths: -------------- trunk/jython/src/com/ziclix/python/sql/PyConnection.java trunk/jython/src/com/ziclix/python/sql/PyCursor.java Modified: trunk/jython/src/com/ziclix/python/sql/PyConnection.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/PyConnection.java 2009-09-09 17:59:05 UTC (rev 6779) +++ trunk/jython/src/com/ziclix/python/sql/PyConnection.java 2009-09-11 03:35:35 UTC (rev 6780) @@ -40,6 +40,9 @@ /** Whether transactions are supported. */ protected boolean supportsTransactions; + /** Whether multiple ResultSets are supported. */ + protected boolean supportsMultipleResultSets; + /** The underlying java.sql.Connection. */ protected Connection connection; @@ -90,6 +93,8 @@ this.connection = connection; this.statements = new HashSet<PyStatement>(); this.supportsTransactions = this.connection.getMetaData().supportsTransactions(); + this.supportsMultipleResultSets = + this.connection.getMetaData().supportsMultipleResultSets(); if (this.supportsTransactions) { this.connection.setAutoCommit(false); Modified: trunk/jython/src/com/ziclix/python/sql/PyCursor.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/PyCursor.java 2009-09-09 17:59:05 UTC (rev 6779) +++ trunk/jython/src/com/ziclix/python/sql/PyCursor.java 2009-09-11 03:35:35 UTC (rev 6780) @@ -482,15 +482,11 @@ throw zxJDBC.makeException(zxJDBC.NotSupportedError, zxJDBC.getString("noStoredProc")); } - } catch (PyException e) { - throw e; - } catch (Throwable e) { - throw zxJDBC.makeException(e); - } finally { - if (this.statement != null) { - // close what we opened - this.statement.close(); + } catch (Throwable t) { + if (statement != null) { + statement.close(); } + throw zxJDBC.makeException(t); } } @@ -584,17 +580,12 @@ this.execute(Py.None, Py.None); } } - } catch (PyException e) { - throw e; - } catch (Throwable e) { - throw zxJDBC.makeException(zxJDBC.Error, e, rowIndex); - } finally { - if (this.statement != null) { + } catch (Throwable t) { + if (statement != null && !(sql instanceof PyStatement)) { // only close static, single-use statements - if (!(sql instanceof PyStatement) && !this.dynamicFetch) { - this.statement.close(); - } + statement.close(); } + throw zxJDBC.makeException(zxJDBC.Error, t, rowIndex); } } @@ -605,18 +596,12 @@ 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.lastrowid = this.datahandler.getRowId(stmt); - - int uc = stmt.getUpdateCount(); - - this.updatecount = uc < 0 ? Py.None : Py.newInteger(uc); - + this.updateAttributes(stmt.getUpdateCount()); warning(new WarningEvent(this, stmt.getWarnings())); this.datahandler.postExecute(stmt); } catch (PyException e) { @@ -627,6 +612,17 @@ } /** + * 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. * @@ -691,7 +687,28 @@ */ public PyObject nextset() { ensureOpen(); - return this.fetch.nextset(); + 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; } /** @@ -784,12 +801,9 @@ } if (this.statement != null) { - // we can't close a dynamic fetch statement until everything has been - // consumed so the only time we can clean up is now - // but if this is a previously prepared statement we don't want to close - // it underneath someone; we can check this by looking in the set + // Finally done with the Statement: only close it if we created it try { - if (this.dynamicFetch && !this.connection.contains(this.statement)) { + if (!this.connection.contains(this.statement)) { this.statement.close(); } } finally { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2009-09-11 06:44:28
|
Revision: 6784 http://jython.svn.sourceforge.net/jython/?rev=6784&view=rev Author: zyasoft Date: 2009-09-11 06:44:19 +0000 (Fri, 11 Sep 2009) Log Message: ----------- Added with-statement support to zxJDBC: * PyConnection - commit if no exception, otherwise rollback * PyCursor - always close this resource Modified Paths: -------------- trunk/jython/src/com/ziclix/python/sql/PyConnection.java trunk/jython/src/com/ziclix/python/sql/PyCursor.java Modified: trunk/jython/src/com/ziclix/python/sql/PyConnection.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/PyConnection.java 2009-09-11 05:52:44 UTC (rev 6783) +++ trunk/jython/src/com/ziclix/python/sql/PyConnection.java 2009-09-11 06:44:19 UTC (rev 6784) @@ -17,6 +17,7 @@ import org.python.core.ClassDictInit; import org.python.core.Py; import org.python.core.PyBuiltinMethodSet; +import org.python.core.PyException; import org.python.core.PyInteger; import org.python.core.PyList; import org.python.core.PyObject; @@ -24,7 +25,10 @@ import org.python.core.PyUnicode; import com.ziclix.python.sql.util.PyArgParser; +import org.python.core.ContextManager; +import org.python.core.ThreadState; + /** * A connection to the database. * @@ -32,7 +36,7 @@ * @author last revised by $Author$ * @version $Revision$ */ -public class PyConnection extends PyObject implements ClassDictInit { +public class PyConnection extends PyObject implements ClassDictInit, ContextManager { /** True if closed. */ protected boolean closed; @@ -137,6 +141,8 @@ zxJDBC.getString("rollback"))); dict.__setitem__("nativesql", new ConnectionFunc("nativesql", 4, 1, 1, zxJDBC.getString("nativesql"))); + dict.__setitem__("__enter__", new ConnectionFunc("__enter__", 5, 0, 0, "__enter__")); + dict.__setitem__("__exit__", new ConnectionFunc("__exit__", 6, 3, 3, "__exit__")); // hide from python dict.__setitem__("initModule", null); @@ -421,6 +427,33 @@ } return this.statements.contains(statement); } + + public PyObject __enter__(ThreadState ts) { + return this; + } + + public PyObject __enter__() { + return this; + } + + public boolean __exit__(ThreadState ts, PyException exception) { + if (exception == null) { + commit(); + } else { + rollback(); + } + return false; + } + + public boolean __exit__(PyObject type, PyObject value, PyObject traceback) { + if (type == null || type == Py.None) { + commit(); + } else { + rollback(); + } + return false; + } + } class ConnectionFunc extends PyBuiltinMethodSet { @@ -444,6 +477,8 @@ case 3: c.rollback(); return Py.None; + case 5: + return c.__enter__(); default: throw info.unexpectedCall(0, false); } @@ -468,6 +503,8 @@ switch (index) { case 2: return c.cursor(arg1.__nonzero__(), arg2, arg3); + case 6: + return Py.newBoolean(c.__exit__(arg1, arg2, arg3)); default: throw info.unexpectedCall(3, false); } Modified: trunk/jython/src/com/ziclix/python/sql/PyCursor.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/PyCursor.java 2009-09-11 05:52:44 UTC (rev 6783) +++ trunk/jython/src/com/ziclix/python/sql/PyCursor.java 2009-09-11 06:44:19 UTC (rev 6784) @@ -26,7 +26,10 @@ import org.python.core.PyUnicode; 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. @@ -35,7 +38,7 @@ * @author last revised by $Author$ * @version $Revision$ */ -public class PyCursor extends PyObject implements ClassDictInit, WarningListener { +public class PyCursor extends PyObject implements ClassDictInit, WarningListener, ContextManager { /** Field fetch */ protected Fetch fetch; @@ -260,6 +263,8 @@ 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); @@ -884,6 +889,24 @@ 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; + } } class CursorFunc extends PyBuiltinMethodSet { @@ -911,6 +934,8 @@ return cursor.fetchone(); case 4 : return cursor.nextset(); + case 13 : + return cursor.__enter__(); default : throw info.unexpectedCall(0, false); } @@ -983,6 +1008,8 @@ case 9 : cursor.executemany(arga, argb, argc, Py.None); return Py.None; + case 14 : + return Py.newBoolean(cursor.__exit__(arga, argc, argc)); default : throw info.unexpectedCall(3, false); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |