Index: src/java/pljava/org/postgresql/pljava/jdbc/SPIParameterMetaData.java =================================================================== RCS file: /cvsroot/pljava/org.postgresql.pljava/src/java/pljava/org/postgresql/pljava/jdbc/SPIParameterMetaData.java,v retrieving revision 1.3 diff -u -r1.3 SPIParameterMetaData.java --- src/java/pljava/org/postgresql/pljava/jdbc/SPIParameterMetaData.java 11 Feb 2006 13:57:50 -0000 1.3 +++ src/java/pljava/org/postgresql/pljava/jdbc/SPIParameterMetaData.java 17 May 2010 19:50:50 -0000 @@ -10,84 +10,92 @@ import java.sql.SQLException; /** - * + * * @author Thomas Hallgren */ public class SPIParameterMetaData implements ParameterMetaData { - private final int[] m_sqlTypes; - + private final int[] m_sqlTypes; + SPIParameterMetaData(int[] sqlTypes) { - m_sqlTypes = sqlTypes; - } + m_sqlTypes = sqlTypes; + } public int getParameterCount() throws SQLException { - return m_sqlTypes == null ? 0 : m_sqlTypes.length; - } + return m_sqlTypes == null ? 0 : m_sqlTypes.length; + } public int isNullable(int arg0) throws SQLException { - return parameterNullableUnknown; - } + return parameterNullableUnknown; + } public boolean isSigned(int arg0) throws SQLException { - return true; - } + return true; + } public int getPrecision(int arg0) throws SQLException { - return 0; - } + return 0; + } public int getScale(int arg0) throws SQLException { - return 0; - } + return 0; + } public int getParameterType(int paramIndex) throws SQLException { - if(paramIndex < 1 || paramIndex > this.getParameterCount()) - throw new SQLException("Parameter index out of range"); - return m_sqlTypes[paramIndex-1]; - } + if (paramIndex < 1 || paramIndex > this.getParameterCount()) + throw new SQLException("Parameter index out of range"); + return m_sqlTypes[paramIndex - 1]; + } - /** - * This feature is not yet supported. + /** + * This feature is not yet supported. * @throws SQLException indicating that this feature is not supported. - */ + */ public String getParameterTypeName(int arg0) throws SQLException { - throw new UnsupportedFeatureException("Parameter type name support not yet implemented"); - } + throw new UnsupportedFeatureException("Parameter type name support not yet implemented"); + } - /** - * This feature is not yet supported. + /** + * This feature is not yet supported. * @throws SQLException indicating that this feature is not supported. - */ + */ public String getParameterClassName(int arg0) throws SQLException { - throw new UnsupportedFeatureException("Parameter class name support not yet implemented"); - } + throw new UnsupportedFeatureException("Parameter class name support not yet implemented"); + } - /** + /** * Returns {@link ParameterMetaData#parameterModeIn} always since this * is the only supported type at this time. - */ - public int getParameterMode(int paramIndex) throws SQLException + */ + public int getParameterMode(int paramIndex) throws SQLException { - if(paramIndex < 1 || paramIndex > this.getParameterCount()) - throw new SQLException("Parameter index out of range"); - return parameterModeIn; - } + if (paramIndex < 1 || paramIndex > this.getParameterCount()) + throw new SQLException("Parameter index out of range"); + return parameterModeIn; + } + + public boolean isWrapperFor(Class iface) throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } + + public T unwrap(Class iface) throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } } \ No newline at end of file Index: src/java/pljava/org/postgresql/pljava/jdbc/AbstractResultSet.java =================================================================== RCS file: /cvsroot/pljava/org.postgresql.pljava/src/java/pljava/org/postgresql/pljava/jdbc/AbstractResultSet.java,v retrieving revision 1.4 diff -u -r1.4 AbstractResultSet.java --- src/java/pljava/org/postgresql/pljava/jdbc/AbstractResultSet.java 11 Feb 2006 13:57:50 -0000 1.4 +++ src/java/pljava/org/postgresql/pljava/jdbc/AbstractResultSet.java 17 May 2010 19:50:49 -0000 @@ -8,19 +8,21 @@ import java.io.InputStream; import java.io.Reader; - +import java.math.BigDecimal; +import java.net.URL; import java.sql.Array; import java.sql.Blob; import java.sql.Clob; import java.sql.Date; +import java.sql.NClob; import java.sql.Ref; import java.sql.ResultSet; +import java.sql.RowId; import java.sql.SQLException; +import java.sql.SQLXML; import java.sql.Statement; import java.sql.Time; import java.sql.Timestamp; -import java.math.BigDecimal; -import java.net.URL; import java.util.Calendar; import java.util.Map; @@ -29,7 +31,7 @@ * of the{@link java.sql.ResultSet} interface. All calls using columnNames are * translated into the corresponding call with index position computed using * a call to {@link java.sql.ResultSet#findColumn(String) findColumn}. - * + * * @author Thomas Hallgren */ public abstract class AbstractResultSet implements ResultSet @@ -55,8 +57,9 @@ /** * @deprecated */ + @Deprecated public BigDecimal getBigDecimal(String columnName, int scale) - throws SQLException + throws SQLException { return this.getBigDecimal(this.findColumn(columnName), scale); } @@ -151,10 +154,10 @@ return this.getObject(this.findColumn(columnName)); } - public Object getObject(String columnName, Map map) - throws SQLException + public Object getObject(String columnLabel, Map> map) + throws SQLException { - return this.getObject(this.findColumn(columnName), map); + return this.getObject(this.findColumn(columnLabel), map); } public Ref getRef(String columnName) @@ -169,11 +172,11 @@ return this.getShort(this.findColumn(columnName)); } - public Statement getStatement() - throws SQLException - { - return null; - } + public Statement getStatement() + throws SQLException + { + return null; + } public String getString(String columnName) throws SQLException @@ -200,7 +203,7 @@ } public Timestamp getTimestamp(String columnName, Calendar cal) - throws SQLException + throws SQLException { return this.getTimestamp(this.findColumn(columnName), cal); } @@ -227,19 +230,19 @@ } public void updateAsciiStream(String columnName, InputStream x, int length) - throws SQLException + throws SQLException { this.updateAsciiStream(this.findColumn(columnName), x, length); } public void updateBigDecimal(String columnName, BigDecimal x) - throws SQLException + throws SQLException { this.updateBigDecimal(this.findColumn(columnName), x); } public void updateBinaryStream(String columnName, InputStream x, int length) - throws SQLException + throws SQLException { this.updateBinaryStream(this.findColumn(columnName), x, length); } @@ -269,7 +272,7 @@ } public void updateCharacterStream(String columnName, Reader x, int length) - throws SQLException + throws SQLException { this.updateCharacterStream(this.findColumn(columnName), x, length); } @@ -323,7 +326,7 @@ } public void updateObject(String columnName, Object x, int scale) - throws SQLException + throws SQLException { this.updateObject(this.findColumn(columnName), x, scale); } @@ -357,4 +360,336 @@ { this.updateTimestamp(this.findColumn(columnName), x); } + + public int getHoldability() throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public Reader getNCharacterStream(int columnIndex) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public Reader getNCharacterStream(String columnLabel) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public NClob getNClob(int columnIndex) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public NClob getNClob(String columnLabel) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public String getNString(int columnIndex) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public String getNString(String columnLabel) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public Object getObject(int columnIndex, Map> map) + throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public RowId getRowId(int columnIndex) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public RowId getRowId(String columnLabel) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public SQLXML getSQLXML(int columnIndex) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public SQLXML getSQLXML(String columnLabel) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public boolean isClosed() throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateAsciiStream(int columnIndex, InputStream x) + throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateAsciiStream(String columnLabel, InputStream x) + throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateAsciiStream(int columnIndex, InputStream x, long length) + throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateAsciiStream(String columnLabel, InputStream x, long length) + throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateBinaryStream(int columnIndex, InputStream x) + throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateBinaryStream(String columnLabel, InputStream x) + throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateBinaryStream(int columnIndex, InputStream x, long length) + throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateBinaryStream(String columnLabel, InputStream x, long length) + throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateBlob(int columnIndex, InputStream inputStream) + throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateBlob(String columnLabel, InputStream inputStream) + throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateBlob(int columnIndex, InputStream inputStream, long length) + throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateBlob(String columnLabel, InputStream inputStream, long length) + throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateCharacterStream(int columnIndex, Reader x) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateCharacterStream(String columnLabel, Reader reader) + throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateCharacterStream(int columnIndex, Reader x, long length) + throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateCharacterStream(String columnLabel, Reader reader, long length) + throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateClob(int columnIndex, Reader reader) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateClob(String columnLabel, Reader reader) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateClob(int columnIndex, Reader reader, long length) + throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateClob(String columnLabel, Reader reader, long length) + throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateNCharacterStream(int columnIndex, Reader x) + throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateNCharacterStream(String columnLabel, Reader reader) + throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateNCharacterStream(int columnIndex, Reader x, long length) + throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateNCharacterStream(String columnLabel, Reader reader, long length) + throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateNClob(int columnIndex, NClob nClob) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateNClob(String columnLabel, NClob nClob) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateNClob(int columnIndex, Reader reader) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateNClob(String columnLabel, Reader reader) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateNClob(int columnIndex, Reader reader, long length) + throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateNClob(String columnLabel, Reader reader, long length) + throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateNString(int columnIndex, String nString) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateNString(String columnLabel, String nString) + throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateRowId(int columnIndex, RowId x) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateRowId(String columnLabel, RowId x) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateSQLXML(int columnIndex, SQLXML xmlObject) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void updateSQLXML(String columnLabel, SQLXML xmlObject) + throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public boolean isWrapperFor(Class iface) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public T unwrap(Class iface) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } } Index: src/java/pljava/org/postgresql/pljava/jdbc/BlobValue.java =================================================================== RCS file: /cvsroot/pljava/org.postgresql.pljava/src/java/pljava/org/postgresql/pljava/jdbc/BlobValue.java,v retrieving revision 1.6 diff -u -r1.6 BlobValue.java --- src/java/pljava/org/postgresql/pljava/jdbc/BlobValue.java 6 May 2006 11:41:13 -0000 1.6 +++ src/java/pljava/org/postgresql/pljava/jdbc/BlobValue.java 17 May 2010 19:50:49 -0000 @@ -7,8 +7,8 @@ package org.postgresql.pljava.jdbc; import java.io.ByteArrayInputStream; -import java.io.InputStream; import java.io.IOException; +import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.sql.Blob; @@ -25,10 +25,10 @@ { value.mark(Integer.MAX_VALUE); long length = value.skip(Long.MAX_VALUE); - if(length > Integer.MAX_VALUE) + if (length > Integer.MAX_VALUE) throw new SQLException("stream content too large"); value.reset(); - return (int)length; + return (int) length; } catch(IOException e) { @@ -46,20 +46,20 @@ { this(new ByteArrayInputStream(bytes), bytes.length); } + public BlobValue(InputStream stream, long nBytes) { - m_stream = stream; - m_nBytes = nBytes; + m_stream = stream; + m_nBytes = nBytes; m_streamPos = 0L; - m_markPos = 0L; + m_markPos = 0L; } - - //*************************************** + // *************************************** // Implementation of java.io.InputStream - //*************************************** - public int available() - throws IOException + // *************************************** + @Override + public int available() throws IOException { return m_stream.available(); } @@ -69,24 +69,23 @@ return this; } - public byte[] getBytes(long pos, int length) - throws SQLException + public byte[] getBytes(long pos, int length) throws SQLException { - if(pos < 0L || length < 0) + if (pos < 0L || length < 0) throw new IllegalArgumentException(); - if(length == 0) + if (length == 0) return new byte[0]; - if(pos + length > m_nBytes) + if (pos + length > m_nBytes) throw new SQLException("Attempt to read beyond end of Blob data"); long skip = pos - m_streamPos; - if(skip < 0) + if (skip < 0) throw new SQLException("Cannot position Blob stream backwards"); try { - if(skip > 0) + if (skip > 0) this.skip(skip); byte[] buf = new byte[length]; @@ -110,7 +109,7 @@ throws IOException { int rs = 0; - if(buf.hasArray()) + if (buf.hasArray()) { byte[] bytes = buf.array(); rs = m_stream.read(bytes); @@ -119,31 +118,33 @@ { byte[] trBuf = new byte[1024]; int br; - while((br = m_stream.read(trBuf)) > 0) + while ((br = m_stream.read(trBuf)) > 0) { buf.put(trBuf, 0, br); rs += br; } } - if(rs != m_nBytes) + if (rs != m_nBytes) throw new IOException("Not all bytes could be read"); m_streamPos += rs; } - //*************************************** + // *************************************** // Implementation of java.sql.Blob - //*************************************** + // *************************************** public long length() { return m_nBytes; } + @Override public synchronized void mark(int readLimit) { m_stream.mark(readLimit); m_markPos = m_streamPos; } + @Override public boolean markSupported() { return m_stream.markSupported(); @@ -165,45 +166,45 @@ throw new UnsupportedOperationException(); } - public synchronized int read() - throws IOException + @Override + public synchronized int read() throws IOException { int rs = m_stream.read(); m_streamPos++; return rs; } - public synchronized int read(byte[] b) - throws IOException + @Override + public synchronized int read(byte[] b) throws IOException { int rs = m_stream.read(b); m_streamPos += rs; return rs; } - public synchronized int read(byte[] b, int off, int len) - throws IOException + @Override + public synchronized int read(byte[] b, int off, int len) throws IOException { int rs = m_stream.read(b, off, len); m_streamPos += rs; return rs; } - public synchronized void reset() - throws IOException + @Override + public synchronized void reset() throws IOException { m_stream.reset(); m_streamPos = m_markPos; } - //************************************************************************* + // ************************************************************************* // Implementation of java.sql.Blob JDK 1.4 methods // // Those method are intended to provide a channel to the underlying data // storage as an alternatvie to the setBinaryStream // on the preparedStatement and are not implemented by the BlobValue. // - //************************************************************************* + // ************************************************************************* /** * In this method is not supported by BlobValue */ @@ -228,8 +229,8 @@ throw new UnsupportedOperationException(); } - public synchronized long skip(long nBytes) - throws IOException + @Override + public synchronized long skip(long nBytes) throws IOException { long skipped = m_stream.skip(nBytes); m_streamPos += skipped; @@ -243,4 +244,16 @@ { throw new UnsupportedOperationException(); } + + public void free() throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public InputStream getBinaryStream(long pos, long length) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } } Index: src/java/pljava/org/postgresql/pljava/jdbc/Invocation.java =================================================================== RCS file: /cvsroot/pljava/org.postgresql.pljava/src/java/pljava/org/postgresql/pljava/jdbc/Invocation.java,v retrieving revision 1.8 diff -u -r1.8 Invocation.java --- src/java/pljava/org/postgresql/pljava/jdbc/Invocation.java 11 Feb 2006 13:57:50 -0000 1.8 +++ src/java/pljava/org/postgresql/pljava/jdbc/Invocation.java 17 May 2010 19:50:49 -0000 @@ -19,172 +19,172 @@ */ public class Invocation { - /** - * The current "stack" of invocations. - */ - private static Invocation[] s_levels = new Invocation[10]; - - /** - * Nesting level for this invocation - */ - private final int m_nestingLevel; - - /** - * Top level savepoint relative to this invocation. - */ - private PgSavepoint m_savepoint; + /** + * The current "stack" of invocations. + */ + private static Invocation[] s_levels = new Invocation[10]; + + /** + * Nesting level for this invocation + */ + private final int m_nestingLevel; + + /** + * Top level savepoint relative to this invocation. + */ + private PgSavepoint m_savepoint; private Invocation(int level) { - m_nestingLevel = level; - } + m_nestingLevel = level; + } - /** - * @return The nesting level of this invocation - */ + /** + * @return The nesting level of this invocation + */ public int getNestingLevel() { - return m_nestingLevel; - } + return m_nestingLevel; + } - /** - * @return Returns the savePoint. - */ + /** + * @return Returns the savePoint. + */ final PgSavepoint getSavepoint() { - return m_savepoint; - } + return m_savepoint; + } - private ArrayList m_preparedStatements; + private ArrayList m_preparedStatements; final void manageStatement(PreparedStatement statement) { - if(m_preparedStatements == null) - m_preparedStatements = new ArrayList(); - m_preparedStatements.add(statement); - } + if (m_preparedStatements == null) + m_preparedStatements = new ArrayList(); + m_preparedStatements.add(statement); + } final void forgetStatement(PreparedStatement statement) { - if(m_preparedStatements == null) - return; + if (m_preparedStatements == null) + return; - int idx = m_preparedStatements.size(); - while(--idx >= 0) + int idx = m_preparedStatements.size(); + while (--idx >= 0) if(m_preparedStatements.get(idx) == statement) { - m_preparedStatements.remove(idx); - return; - } - } + m_preparedStatements.remove(idx); + return; + } + } - /** + /** * @param savepoint The savepoint to set. - */ + */ final void setSavepoint(PgSavepoint savepoint) { - m_savepoint = savepoint; - } + m_savepoint = savepoint; + } - /** + /** * Called from the backend when the invokation exits. Should * not be invoked any other way. - */ + */ public void onExit() throws SQLException { try { - if(m_savepoint != null) - m_savepoint.onInvocationExit(SPIDriver.getDefault()); + if (m_savepoint != null) + m_savepoint.onInvocationExit(SPIDriver.getDefault()); if(m_preparedStatements != null) { - int idx = m_preparedStatements.size(); + int idx = m_preparedStatements.size(); if(idx > 0) { - Logger w = Logger.getAnonymousLogger(); + Logger w = Logger.getAnonymousLogger(); w.warning( "Closing " + idx + " \"forgotten\" statement" + ((idx > 1) ? "s" : "")); while(--idx >= 0) { - PreparedStatement stmt = (PreparedStatement)m_preparedStatements.get(idx); - w.fine("Closed: " + stmt); - stmt.close(); - } - } - } + PreparedStatement stmt = (PreparedStatement) m_preparedStatements.get(idx); + w.fine("Closed: " + stmt); + stmt.close(); + } + } + } } finally { - s_levels[m_nestingLevel] = null; - } - } - - /** - * @return The current invocation - */ + s_levels[m_nestingLevel] = null; + } + } + + /** + * @return The current invocation + */ public static Invocation current() { synchronized(Backend.THREADLOCK) { - Invocation curr = _getCurrent(); - if(curr != null) - return curr; + Invocation curr = _getCurrent(); + if (curr != null) + return curr; - int level = _getNestingLevel(); - int top = s_levels.length; + int level = _getNestingLevel(); + int top = s_levels.length; if(level < top) { - curr = s_levels[level]; + curr = s_levels[level]; if(curr != null) { - curr._register(); - return curr; - } + curr._register(); + return curr; + } } else { - int newSize = top; + int newSize = top; do { newSize <<= 2; } while(newSize <= level); - Invocation[] levels = new Invocation[newSize]; - System.arraycopy(s_levels, 0, levels, 0, top); - s_levels = levels; - } - curr = new Invocation(level); - s_levels[level] = curr; - curr._register(); - return curr; - } - } + Invocation[] levels = new Invocation[newSize]; + System.arraycopy(s_levels, 0, levels, 0, top); + s_levels = levels; + } + curr = new Invocation(level); + s_levels[level] = curr; + curr._register(); + return curr; + } + } static void clearErrorCondition() { synchronized(Backend.THREADLOCK) { - _clearErrorCondition(); - } - } + _clearErrorCondition(); + } + } + + /** + * Register this Invocation so that it receives the onExit callback + */ + private native void _register(); - /** - * Register this Invocation so that it receives the onExit callback - */ - private native void _register(); - - /** + /** * Returns the current invocation or null if no invocation has been * registered yet. - */ - private native static Invocation _getCurrent(); + */ + private native static Invocation _getCurrent(); - /** - * Returns the current nesting level - */ - private native static int _getNestingLevel(); - - /** - * Clears the error condition set by elog(ERROR) - */ - private native static void _clearErrorCondition(); + /** + * Returns the current nesting level + */ + private native static int _getNestingLevel(); + + /** + * Clears the error condition set by elog(ERROR) + */ + private native static void _clearErrorCondition(); } Index: src/java/pljava/org/postgresql/pljava/jdbc/SPIDatabaseMetaData.java =================================================================== RCS file: /cvsroot/pljava/org.postgresql.pljava/src/java/pljava/org/postgresql/pljava/jdbc/SPIDatabaseMetaData.java,v retrieving revision 1.10 diff -u -r1.10 SPIDatabaseMetaData.java --- src/java/pljava/org/postgresql/pljava/jdbc/SPIDatabaseMetaData.java 25 Sep 2006 06:28:31 -0000 1.10 +++ src/java/pljava/org/postgresql/pljava/jdbc/SPIDatabaseMetaData.java 17 May 2010 19:50:50 -0000 @@ -7,6 +7,7 @@ import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; +import java.sql.RowIdLifetime; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; @@ -24,13 +25,13 @@ } private static final String KEYWORDS = "abort,acl,add,aggregate,append,archive," - + "arch_store,backward,binary,boolean,change,cluster," - + "copy,database,delimiter,delimiters,do,extend," - + "explain,forward,heavy,index,inherits,isnull," - + "light,listen,load,merge,nothing,notify," - + "notnull,oids,purge,rename,replace,retrieve," - + "returns,rule,recipe,setof,stdin,stdout,store," - + "vacuum,verbose,version"; + + "arch_store,backward,binary,boolean,change,cluster," + + "copy,database,delimiter,delimiters,do,extend," + + "explain,forward,heavy,index,inherits,isnull," + + "light,listen,load,merge,nothing,notify," + + "notnull,oids,purge,rename,replace,retrieve," + + "returns,rule,recipe,setof,stdin,stdout,store," + + "vacuum,verbose,version"; private final SPIConnection m_connection; // The connection association @@ -42,14 +43,14 @@ protected int getMaxIndexKeys() throws SQLException { - if(INDEX_MAX_KEYS == 0) + if (INDEX_MAX_KEYS == 0) INDEX_MAX_KEYS = Integer.parseInt(Backend.getConfigOption("max_index_keys")); return INDEX_MAX_KEYS; } protected int getMaxNameLength() throws SQLException { - if(NAMEDATALEN == 0) + if (NAMEDATALEN == 0) { String sql = "SELECT t.typlen FROM pg_catalog.pg_type t, pg_catalog.pg_namespace n" + " WHERE t.typnamespace=n.oid" + @@ -338,17 +339,17 @@ public String getNumericFunctions() throws SQLException { return BuiltinFunctions.ABS + ',' + BuiltinFunctions.ACOS + ',' - + BuiltinFunctions.ASIN + ',' + BuiltinFunctions.ATAN + ',' - + BuiltinFunctions.ATAN2 + ',' + BuiltinFunctions.CEILING + ',' - + BuiltinFunctions.COS + ',' + BuiltinFunctions.COT + ',' - + BuiltinFunctions.DEGREES + ',' + BuiltinFunctions.EXP + ',' - + BuiltinFunctions.FLOOR + ',' + BuiltinFunctions.LOG + ',' - + BuiltinFunctions.LOG10 + ',' + BuiltinFunctions.MOD + ',' - + BuiltinFunctions.PI + ',' + BuiltinFunctions.POWER + ',' - + BuiltinFunctions.RADIANS + ',' + BuiltinFunctions.RAND + ',' - + BuiltinFunctions.ROUND + ',' + BuiltinFunctions.SIGN + ',' - + BuiltinFunctions.SIN + ',' + BuiltinFunctions.SQRT + ',' - + BuiltinFunctions.TAN + ',' + BuiltinFunctions.TRUNCATE; + + BuiltinFunctions.ASIN + ',' + BuiltinFunctions.ATAN + ',' + + BuiltinFunctions.ATAN2 + ',' + BuiltinFunctions.CEILING + ',' + + BuiltinFunctions.COS + ',' + BuiltinFunctions.COT + ',' + + BuiltinFunctions.DEGREES + ',' + BuiltinFunctions.EXP + ',' + + BuiltinFunctions.FLOOR + ',' + BuiltinFunctions.LOG + ',' + + BuiltinFunctions.LOG10 + ',' + BuiltinFunctions.MOD + ',' + + BuiltinFunctions.PI + ',' + BuiltinFunctions.POWER + ',' + + BuiltinFunctions.RADIANS + ',' + BuiltinFunctions.RAND + ',' + + BuiltinFunctions.ROUND + ',' + BuiltinFunctions.SIGN + ',' + + BuiltinFunctions.SIN + ',' + BuiltinFunctions.SQRT + ',' + + BuiltinFunctions.TAN + ',' + BuiltinFunctions.TRUNCATE; } @@ -357,10 +358,10 @@ String funcs = BuiltinFunctions.ASCII + ',' + BuiltinFunctions.CHAR + ',' + BuiltinFunctions.CONCAT + ',' + BuiltinFunctions.LCASE + ',' + BuiltinFunctions.LEFT + ',' + BuiltinFunctions.LENGTH + ',' - + BuiltinFunctions.LTRIM + ',' + BuiltinFunctions.REPEAT + ',' - + BuiltinFunctions.RTRIM + ',' + BuiltinFunctions.SPACE + ',' - + BuiltinFunctions.SUBSTRING + ',' + BuiltinFunctions.UCASE + ',' - + BuiltinFunctions.REPLACE; + + BuiltinFunctions.LTRIM + ',' + BuiltinFunctions.REPEAT + ',' + + BuiltinFunctions.RTRIM + ',' + BuiltinFunctions.SPACE + ',' + + BuiltinFunctions.SUBSTRING + ',' + BuiltinFunctions.UCASE + ',' + + BuiltinFunctions.REPLACE; // Currently these don't work correctly with parameterized // arguments, so leave them out. They reorder the arguments @@ -621,12 +622,14 @@ } /* - * Does this driver support the ANSI-92 entry level SQL grammar? All JDBC - * Compliant drivers must return true. We currently report false until - * 'schema' support is added. Then this should be changed to return true, - * since we will be mostly compliant (probably more compliant than many - * other databases) And since this is a requirement for all JDBC drivers we - * need to get to the point where we can return true. @return true if so + * Does this driver support the ANSI-92 entry level SQL grammar? All + * JDBC Compliant drivers must return true. We currently report false + * until 'schema' support is added. Then this should be changed to + * return true, since we will be mostly compliant (probably more + * compliant than many other databases) And since this is a requirement + * for all JDBC drivers we need to get to the point where we can return + * true. @return true if so + * * @exception SQLException if a database access error occurs */ public boolean supportsANSI92EntryLevelSQL() throws SQLException @@ -1221,12 +1224,12 @@ public boolean supportsTransactionIsolationLevel(int level) throws SQLException { - if(level == Connection.TRANSACTION_SERIALIZABLE - || level == Connection.TRANSACTION_READ_COMMITTED) + if (level == Connection.TRANSACTION_SERIALIZABLE + || level == Connection.TRANSACTION_READ_COMMITTED) return true; - if(this.getDatabaseMajorVersion() >= 8 - && (level == Connection.TRANSACTION_READ_UNCOMMITTED || level == Connection.TRANSACTION_REPEATABLE_READ)) + if (this.getDatabaseMajorVersion() >= 8 + && (level == Connection.TRANSACTION_READ_UNCOMMITTED || level == Connection.TRANSACTION_REPEATABLE_READ)) return true; return false; @@ -1238,7 +1241,7 @@ * occurs */ public boolean supportsDataDefinitionAndDataManipulationTransactions() - throws SQLException + throws SQLException { return true; } @@ -1281,21 +1284,21 @@ */ private static String escapeQuotes(String s) { - if (s == null) - { - return null; - } + if (s == null) + { + return null; + } StringBuffer sb = new StringBuffer(); int length = s.length(); char prevChar = ' '; char prevPrevChar = ' '; - for(int i = 0; i < length; i++) + for (int i = 0; i < length; i++) { char c = s.charAt(i); sb.append(c); - if(c == '\'' - && (prevChar != '\\' || (prevChar == '\\' && prevPrevChar == '\\'))) + if (c == '\'' + && (prevChar != '\\' || (prevChar == '\\' && prevPrevChar == '\\'))) { sb.append("'"); } @@ -1308,63 +1311,63 @@ /** * Creates a condition with the specified operator * based on schema specification:
- *
    - *
  • schema is specified => search in this schema only
  • - *
  • schema is equal to "" => search in the 'public' schema
  • - *
  • schema is null => search in all schemas
  • + *
      + *
    • schema is specified => search in this schema only
    • + *
    • schema is equal to "" => search in the 'public' schema
    • + *
    • schema is null => search in all schemas
    • *
    */ private static String resolveSchemaConditionWithOperator( String expr, String schema, String operator) { - //schema is null => search in current_schemas(true) - if (schema == null) - { - //This means that only "visible" schemas are searched. - //It was approved to change to *all* schemas. + // schema is null => search in current_schemas(true) + if (schema == null) + { + // This means that only "visible" schemas are searched. + // It was approved to change to *all* schemas. //return expr + " " + operator + " ANY (current_schemas(true))"; return "1=1"; - } - //schema is specified => search in this schema - else if(!"".equals(schema)) + } + // schema is specified => search in this schema + else if (!"".equals(schema)) { return expr + " " + operator + " '" + escapeQuotes(schema) + "' "; } - //schema is "" => search in the 'public' schema - else - { - return expr + " " + operator + " 'public' "; - } - } + // schema is "" => search in the 'public' schema + else + { + return expr + " " + operator + " 'public' "; + } + } /** * Creates an equality condition based on schema specification:
    - *
      - *
    • schema is specified => search in this schema only
    • - *
    • schema is equal to "" => search in the 'public' schema
    • - *
    • schema is null => search in all schemas
    • + *
        + *
      • schema is specified => search in this schema only
      • + *
      • schema is equal to "" => search in the 'public' schema
      • + *
      • schema is null => search in all schemas
      • *
      */ private static String resolveSchemaCondition(String expr, String schema) { - return resolveSchemaConditionWithOperator(expr, schema, "="); - } + return resolveSchemaConditionWithOperator(expr, schema, "="); + } /** * Creates a pattern condition based on schema specification:
      - *
        - *
      • schema is specified => search in this schema only
      • - *
      • schema is equal to "" => search in the 'public' schema
      • - *
      • schema is null => search in all schemas
      • + *
          + *
        • schema is specified => search in this schema only
        • + *
        • schema is equal to "" => search in the 'public' schema
        • + *
        • schema is null => search in all schemas
        • *
        */ private static String resolveSchemaPatternCondition( String expr, String schema) { - return resolveSchemaConditionWithOperator(expr, schema, "LIKE"); - } + return resolveSchemaConditionWithOperator(expr, schema, "LIKE"); + } - /* + /* * Get a description of stored procedures available in a catalog

        Only * procedure descriptions matching the schema and procedure name criteria * are returned. They are ordered by PROCEDURE_SCHEM and PROCEDURE_NAME

        Each @@ -1397,7 +1400,7 @@ + " WHERE p.pronamespace=n.oid " + " AND " + resolveSchemaPatternCondition( "n.nspname", schemaPattern); - if(procedureNamePattern != null) + if (procedureNamePattern != null) { sql += " AND p.proname LIKE '" + escapeQuotes(procedureNamePattern) + "' "; @@ -1440,18 +1443,19 @@ */ // Implementation note: This is required for Borland's JBuilder to work public java.sql.ResultSet getProcedureColumns(String catalog, - String schemaPattern, String procedureNamePattern, - String columnNamePattern) throws SQLException + String schemaPattern, String procedureNamePattern, + String columnNamePattern) throws SQLException { ResultSetField f[] = new ResultSetField[13]; - ArrayList v = new ArrayList(); // The new ResultSet tuple stuff + ArrayList v = new ArrayList(); // The new ResultSet + // tuple stuff f[0] = new ResultSetField("PROCEDURE_CAT", TypeOid.VARCHAR, - getMaxNameLength()); + getMaxNameLength()); f[1] = new ResultSetField("PROCEDURE_SCHEM", TypeOid.VARCHAR, - getMaxNameLength()); + getMaxNameLength()); f[2] = new ResultSetField("PROCEDURE_NAME", TypeOid.VARCHAR, - getMaxNameLength()); + getMaxNameLength()); f[3] = new ResultSetField("COLUMN_NAME", TypeOid.VARCHAR, getMaxNameLength()); f[4] = new ResultSetField("COLUMN_TYPE", TypeOid.INT2, 2); @@ -1471,7 +1475,7 @@ + " WHERE p.pronamespace=n.oid AND p.prorettype=t.oid " + " AND " + resolveSchemaPatternCondition( "n.nspname", schemaPattern); - if(procedureNamePattern != null) + if (procedureNamePattern != null) { sql += " AND p.proname LIKE '" + escapeQuotes(procedureNamePattern) + "' "; @@ -1486,17 +1490,17 @@ Oid returnTypeRelid = null; Oid[] argTypes = null; - while(rs.next()) + while (rs.next()) { schema = rs.getString("nspname"); procedureName = rs.getString("proname"); - returnType = (Oid)rs.getObject("prorettype"); + returnType = (Oid) rs.getObject("prorettype"); returnTypeType = rs.getString("typtype"); - returnTypeRelid = (Oid)rs.getObject("typrelid"); - argTypes = (Oid[])rs.getObject("proargtypes"); + returnTypeRelid = (Oid) rs.getObject("typrelid"); + argTypes = (Oid[]) rs.getObject("proargtypes"); // decide if we are returning a single column result. - if(!returnTypeType.equals("c")) + if (!returnTypeType.equals("c")) { Object[] tuple = new Object[13]; tuple[0] = null; @@ -1504,7 +1508,7 @@ tuple[2] = procedureName; tuple[3] = "returnValue"; tuple[4] = new Short((short)java.sql.DatabaseMetaData.procedureColumnReturn); - tuple[5] = new Short((short)m_connection.getSQLType(returnType)); + tuple[5] = new Short((short) m_connection.getSQLType(returnType)); tuple[6] = m_connection.getPGType(returnType); tuple[7] = null; tuple[8] = null; @@ -1516,7 +1520,7 @@ } // Add a row for each argument. - for(int i = 0; i < argTypes.length; i++) + for (int i = 0; i < argTypes.length; i++) { Oid argOid = argTypes[i]; Object[] tuple = new Object[13]; @@ -1525,7 +1529,7 @@ tuple[2] = procedureName; tuple[3] = "$" + (i + 1); tuple[4] = new Short((short)java.sql.DatabaseMetaData.procedureColumnIn); - tuple[5] = new Short((short)m_connection.getSQLType(argOid)); + tuple[5] = new Short((short) m_connection.getSQLType(argOid)); tuple[6] = m_connection.getPGType(argOid); tuple[7] = null; tuple[8] = null; @@ -1537,16 +1541,16 @@ } // if we are returning a multi-column result. - if(returnTypeType.equals("c")) + if (returnTypeType.equals("c")) { String columnsql = "SELECT a.attname,a.atttypid FROM pg_catalog.pg_attribute a WHERE a.attrelid = ? ORDER BY a.attnum "; PreparedStatement stmt = m_connection.prepareStatement(columnsql); stmt.setObject(1, returnTypeRelid); ResultSet columnrs = stmt.executeQuery(columnsql); - while(columnrs.next()) + while (columnrs.next()) { - Oid columnTypeOid = (Oid)columnrs.getObject("atttypid"); + Oid columnTypeOid = (Oid) columnrs.getObject("atttypid"); Object[] tuple = new Object[13]; tuple[0] = null; tuple[1] = schema; @@ -1593,7 +1597,7 @@ * if a database-access error occurs. */ public java.sql.ResultSet getTables(String catalog, String schemaPattern, - String tableNamePattern, String types[]) throws SQLException + String tableNamePattern, String types[]) throws SQLException { String useSchemas = "SCHEMAS"; String select = "SELECT NULL AS TABLE_CAT, n.nspname AS TABLE_SCHEM, c.relname AS TABLE_NAME, " @@ -1635,23 +1639,23 @@ "n.nspname", schemaPattern); String orderby = " ORDER BY TABLE_TYPE,TABLE_SCHEM,TABLE_NAME "; - if(types == null) + if (types == null) { types = s_defaultTableTypes; } - if(tableNamePattern != null) + if (tableNamePattern != null) { select += " AND c.relname LIKE '" + escapeQuotes(tableNamePattern) - + "' "; + + "' "; } String sql = select; sql += " AND (false "; - for(int i = 0; i < types.length; i++) + for (int i = 0; i < types.length; i++) { - HashMap clauses = (HashMap)s_tableTypeClauses.get(types[i]); - if(clauses != null) + HashMap clauses = (HashMap) s_tableTypeClauses.get(types[i]); + if (clauses != null) { - String clause = (String)clauses.get(useSchemas); + String clause = (String) clauses.get(useSchemas); sql += " OR ( " + clause + " ) "; } } @@ -1661,71 +1665,71 @@ return createMetaDataStatement().executeQuery(sql); } - private static final HashMap s_tableTypeClauses; + private static final HashMap s_tableTypeClauses; static { - s_tableTypeClauses = new HashMap(); - HashMap ht = new HashMap(); + s_tableTypeClauses = new HashMap(); + HashMap ht = new HashMap(); s_tableTypeClauses.put("TABLE", ht); ht.put("SCHEMAS", - "c.relkind = 'r' AND n.nspname NOT LIKE 'pg!_%' ESCAPE '!' AND n.nspname <> 'information_schema'"); + "c.relkind = 'r' AND n.nspname NOT LIKE 'pg!_%' ESCAPE '!' AND n.nspname <> 'information_schema'"); ht.put("NOSCHEMAS", - "c.relkind = 'r' AND c.relname NOT LIKE 'pg!_%' ESCAPE '!'"); - ht = new HashMap(); + "c.relkind = 'r' AND c.relname NOT LIKE 'pg!_%' ESCAPE '!'"); + ht = new HashMap(); s_tableTypeClauses.put("VIEW", ht); ht.put("SCHEMAS", - "c.relkind = 'v' AND n.nspname <> 'pg_catalog' AND n.nspname <> 'information_schema'"); + "c.relkind = 'v' AND n.nspname <> 'pg_catalog' AND n.nspname <> 'information_schema'"); ht.put("NOSCHEMAS", - "c.relkind = 'v' AND c.relname NOT LIKE 'pg!_%' ESCAPE '!'"); - ht = new HashMap(); + "c.relkind = 'v' AND c.relname NOT LIKE 'pg!_%' ESCAPE '!'"); + ht = new HashMap(); s_tableTypeClauses.put("INDEX", ht); ht.put("SCHEMAS", - "c.relkind = 'i' AND n.nspname NOT LIKE 'pg!_%' ESCAPE '!' AND n.nspname <> 'information_schema'"); + "c.relkind = 'i' AND n.nspname NOT LIKE 'pg!_%' ESCAPE '!' AND n.nspname <> 'information_schema'"); ht.put("NOSCHEMAS", - "c.relkind = 'i' AND c.relname NOT LIKE 'pg!_%' ESCAPE '!'"); - ht = new HashMap(); + "c.relkind = 'i' AND c.relname NOT LIKE 'pg!_%' ESCAPE '!'"); + ht = new HashMap(); s_tableTypeClauses.put("SEQUENCE", ht); ht.put("SCHEMAS", "c.relkind = 'S'"); ht.put("NOSCHEMAS", "c.relkind = 'S'"); - ht = new HashMap(); + ht = new HashMap(); s_tableTypeClauses.put("SYSTEM TABLE", ht); ht.put("SCHEMAS", - "c.relkind = 'r' AND (n.nspname = 'pg_catalog' OR n.nspname = 'information_schema')"); + "c.relkind = 'r' AND (n.nspname = 'pg_catalog' OR n.nspname = 'information_schema')"); ht.put("NOSCHEMAS", - "c.relkind = 'r' AND c.relname LIKE 'pg!_%' ESCAPE '!' AND c.relname NOT LIKE 'pgLIKE 'pg!_toast!_%' ESCAPE '!'toast!_%' ESCAPE '!' AND c.relname NOT LIKE 'pg!_temp!_%' ESCAPE '!'"); - ht = new HashMap(); + "c.relkind = 'r' AND c.relname LIKE 'pg!_%' ESCAPE '!' AND c.relname NOT LIKE 'pgLIKE 'pg!_toast!_%' ESCAPE '!'toast!_%' ESCAPE '!' AND c.relname NOT LIKE 'pg!_temp!_%' ESCAPE '!'"); + ht = new HashMap(); s_tableTypeClauses.put("SYSTEM TOAST TABLE", ht); ht.put("SCHEMAS", "c.relkind = 'r' AND n.nspname = 'pg_toast'"); ht.put("NOSCHEMAS", - "c.relkind = 'r' AND c.relname LIKE 'pg!_toast!_%' ESCAPE '!'"); - ht = new HashMap(); + "c.relkind = 'r' AND c.relname LIKE 'pg!_toast!_%' ESCAPE '!'"); + ht = new HashMap(); s_tableTypeClauses.put("SYSTEM TOAST INDEX", ht); ht.put("SCHEMAS", "c.relkind = 'i' AND n.nspname = 'pg_toast'"); ht.put("NOSCHEMAS", - "c.relkind = 'i' AND c.relname LIKE 'pg!_toast!_%' ESCAPE '!'"); - ht = new HashMap(); + "c.relkind = 'i' AND c.relname LIKE 'pg!_toast!_%' ESCAPE '!'"); + ht = new HashMap(); s_tableTypeClauses.put("SYSTEM VIEW", ht); ht.put("SCHEMAS", - "c.relkind = 'v' AND (n.nspname = 'pg_catalog' OR n.nspname = 'information_schema') "); + "c.relkind = 'v' AND (n.nspname = 'pg_catalog' OR n.nspname = 'information_schema') "); ht.put("NOSCHEMAS", "c.relkind = 'v' AND c.relname LIKE 'pg!_%' ESCAPE '!'"); - ht = new HashMap(); + ht = new HashMap(); s_tableTypeClauses.put("SYSTEM INDEX", ht); ht.put("SCHEMAS", - "c.relkind = 'i' AND (n.nspname = 'pg_catalog' OR n.nspname = 'information_schema') "); + "c.relkind = 'i' AND (n.nspname = 'pg_catalog' OR n.nspname = 'information_schema') "); ht.put("NOSCHEMAS", - "c.relkind = 'v' AND c.relname LIKE 'pg!_%' ESCAPE '!' AND c.relname NOT LIKE 'pg!_toast!_%' ESCAPE '!' AND c.relname NOT LIKE 'pg!_temp!_%' ESCAPE '!'"); - ht = new HashMap(); + "c.relkind = 'v' AND c.relname LIKE 'pg!_%' ESCAPE '!' AND c.relname NOT LIKE 'pg!_toast!_%' ESCAPE '!' AND c.relname NOT LIKE 'pg!_temp!_%' ESCAPE '!'"); + ht = new HashMap(); s_tableTypeClauses.put("TEMPORARY TABLE", ht); ht.put("SCHEMAS", - "c.relkind = 'r' AND n.nspname LIKE 'pg!_temp!_%' ESCAPE '!' "); + "c.relkind = 'r' AND n.nspname LIKE 'pg!_temp!_%' ESCAPE '!' "); ht.put("NOSCHEMAS", - "c.relkind = 'r' AND c.relname LIKE 'pg!_temp!_%' ESCAPE '!' "); - ht = new HashMap(); + "c.relkind = 'r' AND c.relname LIKE 'pg!_temp!_%' ESCAPE '!' "); + ht = new HashMap(); s_tableTypeClauses.put("TEMPORARY INDEX", ht); ht.put("SCHEMAS", - "c.relkind = 'i' AND n.nspname LIKE 'pg!_temp!_%' ESCAPE '!' "); + "c.relkind = 'i' AND n.nspname LIKE 'pg!_temp!_%' ESCAPE '!' "); ht.put("NOSCHEMAS", - "c.relkind = 'i' AND c.relname LIKE 'pg!_temp!_%' ESCAPE '!' "); + "c.relkind = 'i' AND c.relname LIKE 'pg!_temp!_%' ESCAPE '!' "); } // These are the default tables, used when NULL is passed to getTables @@ -1770,10 +1774,10 @@ sortStringArray(types); ResultSetField f[] = new ResultSetField[1]; - ArrayList v = new ArrayList(); + ArrayList v = new ArrayList(); f[0] = new ResultSetField(new String("TABLE_TYPE"), TypeOid.VARCHAR, - getMaxNameLength()); - for(int i = 0; i < types.length; i++) + getMaxNameLength()); + for (int i = 0; i < types.length; i++) { Object[] tuple = new Object[1]; tuple[0] = types[i]; @@ -1816,11 +1820,13 @@ * @see #getSearchStringEscape */ public java.sql.ResultSet getColumns(String catalog, String schemaPattern, - String tableNamePattern, String columnNamePattern) throws SQLException + String tableNamePattern, String columnNamePattern) throws SQLException { - ArrayList v = new ArrayList(); // The new ResultSet tuple stuff - ResultSetField f[] = new ResultSetField[18]; // The field descriptors - // for the new ResultSet + ArrayList v = new ArrayList(); // The new ResultSet + // tuple stuff + ResultSetField f[] = new ResultSetField[18]; // The field + // descriptors + // for the new ResultSet f[0] = new ResultSetField("TABLE_CAT", TypeOid.VARCHAR, getMaxNameLength()); @@ -1835,7 +1841,7 @@ getMaxNameLength()); f[6] = new ResultSetField("COLUMN_SIZE", TypeOid.INT4, 4); f[7] = new ResultSetField("BUFFER_LENGTH", TypeOid.VARCHAR, - getMaxNameLength()); + getMaxNameLength()); f[8] = new ResultSetField("DECIMAL_DIGITS", TypeOid.INT4, 4); f[9] = new ResultSetField("NUM_PREC_RADIX", TypeOid.INT4, 4); f[10] = new ResultSetField("NULLABLE", TypeOid.INT4, 4); @@ -1848,7 +1854,7 @@ f[15] = new ResultSetField("CHAR_OCTET_LENGTH", TypeOid.INT4, 4); f[16] = new ResultSetField("ORDINAL_POSITION", TypeOid.INT4, 4); f[17] = new ResultSetField("IS_NULLABLE", TypeOid.VARCHAR, - getMaxNameLength()); + getMaxNameLength()); String sql = "SELECT n.nspname,c.relname,a.attname," + " a.atttypid as atttypid,a.attnotnull,a.atttypmod," @@ -1864,12 +1870,12 @@ + " AND " + resolveSchemaPatternCondition( "n.nspname", schemaPattern); - if(tableNamePattern != null && !"".equals(tableNamePattern)) + if (tableNamePattern != null && !"".equals(tableNamePattern)) { sql += " AND c.relname LIKE '" + escapeQuotes(tableNamePattern) + "' "; } - if(columnNamePattern != null && !"".equals(columnNamePattern)) + if (columnNamePattern != null && !"".equals(columnNamePattern)) { sql += " AND a.attname LIKE '" + escapeQuotes(columnNamePattern) + "' "; @@ -1877,34 +1883,34 @@ sql += " ORDER BY nspname,relname,attnum "; ResultSet rs = m_connection.createStatement().executeQuery(sql); - while(rs.next()) + while (rs.next()) { Object[] tuple = new Object[18]; - Oid typeOid = (Oid)rs.getObject("atttypid"); + Oid typeOid = (Oid) rs.getObject("atttypid"); tuple[0] = null; // Catalog name, not supported tuple[1] = rs.getString("nspname"); // Schema tuple[2] = rs.getString("relname"); // Table name tuple[3] = rs.getString("attname"); // Column name - tuple[4] = new Short((short)m_connection.getSQLType(typeOid)); + tuple[4] = new Short((short) m_connection.getSQLType(typeOid)); String pgType = m_connection.getPGType(typeOid); tuple[5] = m_connection.getPGType(typeOid); // Type name String defval = rs.getString("adsrc"); - if(defval != null) + if (defval != null) { - if(pgType.equals("int4")) + if (pgType.equals("int4")) { - if(defval.indexOf("nextval(") != -1) + if (defval.indexOf("nextval(") != -1) tuple[5] = "serial"; // Type name == - // serial + // serial } else if(pgType.equals("int8")) { - if(defval.indexOf("nextval(") != -1) + if (defval.indexOf("nextval(") != -1) tuple[5] = "bigserial"; // Type name == - // bigserial + // bigserial } } @@ -1913,7 +1919,7 @@ // overwrite later. tuple[8] = new Integer(0); - if(pgType.equals("bpchar") || pgType.equals("varchar")) + if (pgType.equals("bpchar") || pgType.equals("varchar")) { int atttypmod = rs.getInt("atttypmod"); tuple[6] = new Integer(atttypmod != -1 @@ -1923,8 +1929,8 @@ else if(pgType.equals("numeric") || pgType.equals("decimal")) { int attypmod = rs.getInt("atttypmod") - VARHDRSZ; - tuple[6] = new Integer ((attypmod >> 16) & 0xffff); - tuple[8] = new Integer (attypmod & 0xffff); + tuple[6] = new Integer((attypmod >> 16) & 0xffff); + tuple[8] = new Integer(attypmod & 0xffff); tuple[9] = new Integer(10); } else if(pgType.equals("bit") || pgType.equals("varbit")) @@ -1951,7 +1957,7 @@ tuple[15] = tuple[6]; // char octet length tuple[16] = new Integer(rs.getInt("attnum")); // ordinal position tuple[17] = rs.getBoolean("attnotnull") ? "NO" : "YES"; // Is - // nullable + // nullable v.add(tuple); } rs.close(); @@ -1982,12 +1988,12 @@ throws SQLException { ResultSetField f[] = new ResultSetField[8]; - ArrayList v = new ArrayList(); + ArrayList v = new ArrayList(); - if(table == null) + if (table == null) table = "%"; - if(columnNamePattern == null) + if (columnNamePattern == null) columnNamePattern = "%"; f[0] = new ResultSetField("TABLE_CAT", TypeOid.VARCHAR, @@ -2005,7 +2011,7 @@ f[6] = new ResultSetField("PRIVILEGE", TypeOid.VARCHAR, getMaxNameLength()); f[7] = new ResultSetField("IS_GRANTABLE", TypeOid.VARCHAR, - getMaxNameLength()); + getMaxNameLength()); String sql = "SELECT n.nspname,c.relname,u.usename,c.relacl,a.attname " + " FROM pg_catalog.pg_namespace n, pg_catalog.pg_class c, pg_catalog.pg_user u, pg_catalog.pg_attribute a " @@ -2017,7 +2023,7 @@ "n.nspname", schema); sql += " AND c.relname = '" + escapeQuotes(table) + "' "; - if(columnNamePattern != null && !"".equals(columnNamePattern)) + if (columnNamePattern != null && !"".equals(columnNamePattern)) { sql += " AND a.attname LIKE '" + escapeQuotes(columnNamePattern) + "' "; @@ -2030,25 +2036,25 @@ String column = null; String owner = null; String[] acls = null; - HashMap permissions = null; + HashMap> permissions = null; String permNames[] = null; - while(rs.next()) + while (rs.next()) { schemaName = rs.getString("nspname"); tableName = rs.getString("relname"); column = rs.getString("attname"); owner = rs.getString("usename"); - acls = (String[])rs.getObject("relacl"); + acls = (String[]) rs.getObject("relacl"); permissions = parseACL(acls, owner); permNames = (String[])permissions.keySet().toArray(new String[permissions.size()]); sortStringArray(permNames); - for(int i = 0; i < permNames.length; i++) + for (int i = 0; i < permNames.length; i++) { - ArrayList grantees = (ArrayList)permissions.get(permNames[i]); - for(int j = 0; j < grantees.size(); j++) + ArrayList grantees = permissions.get(permNames[i]); + for (int j = 0; j < grantees.size(); j++) { - String grantee = (String)grantees.get(j); + String grantee = grantees.get(j); String grantable = owner.equals(grantee) ? "YES" : "NO"; Object[] tuple = new Object[8]; tuple[0] = null; @@ -2088,10 +2094,10 @@ * @see #getSearchStringEscape */ public java.sql.ResultSet getTablePrivileges(String catalog, - String schemaPattern, String tableNamePattern) throws SQLException + String schemaPattern, String tableNamePattern) throws SQLException { ResultSetField f[] = new ResultSetField[7]; - ArrayList v = new ArrayList(); + ArrayList v = new ArrayList(); f[0] = new ResultSetField("TABLE_CAT", TypeOid.VARCHAR, getMaxNameLength()); @@ -2106,7 +2112,7 @@ f[5] = new ResultSetField("PRIVILEGE", TypeOid.VARCHAR, getMaxNameLength()); f[6] = new ResultSetField("IS_GRANTABLE", TypeOid.VARCHAR, - getMaxNameLength()); + getMaxNameLength()); String sql = "SELECT n.nspname,c.relname,u.usename,c.relacl " + " FROM pg_catalog.pg_namespace n, pg_catalog.pg_class c, pg_catalog.pg_user u " @@ -2115,7 +2121,7 @@ + " AND " + resolveSchemaPatternCondition( "n.nspname", schemaPattern); - if(tableNamePattern != null && !"".equals(tableNamePattern)) + if (tableNamePattern != null && !"".equals(tableNamePattern)) { sql += " AND c.relname LIKE '" + escapeQuotes(tableNamePattern) + "' "; @@ -2127,24 +2133,25 @@ String table = null; String owner = null; String[] acls = null; - HashMap permissions = null; + HashMap> permissions = null; String permNames[] = null; - while(rs.next()) + while (rs.next()) { schema = rs.getString("nspname"); table = rs.getString("relname"); owner = rs.getString("usename"); - acls = (String[])rs.getObject("relacl"); + acls = (String[]) rs.getObject("relacl"); permissions = parseACL(acls, owner); - permNames = (String[])permissions.keySet().toArray(new String[permissions.size()]); + permNames = (String[]) permissions.keySet().toArray( + new String[permissions.size()]); sortStringArray(permNames); - for(int i = 0; i < permNames.length; i++) + for (int i = 0; i < permNames.length; i++) { - ArrayList grantees = (ArrayList)permissions.get(permNames[i]); - for(int j = 0; j < grantees.size(); j++) + ArrayList grantees = permissions.get(permNames[i]); + for (int j = 0; j < grantees.size(); j++) { - String grantee = (String)grantees.get(j); + String grantee = grantees.get(j); String grantable = owner.equals(grantee) ? "YES" : "NO"; Object[] tuple = new Object[7]; tuple[0] = null; @@ -2165,11 +2172,11 @@ private static void sortStringArray(String s[]) { - for(int i = 0; i < s.length - 1; i++) + for (int i = 0; i < s.length - 1; i++) { - for(int j = i + 1; j < s.length; j++) + for (int j = i + 1; j < s.length; j++) { - if(s[i].compareTo(s[j]) > 0) + if (s[i].compareTo(s[j]) > 0) { String tmp = s[i]; s[i] = s[j]; @@ -2183,63 +2190,64 @@ * Add the user described by the given acl to the ArrayLists of users with the * privileges described by the acl. */ - private void addACLPrivileges(String acl, HashMap privileges) + private void addACLPrivileges(String acl, + HashMap> privileges) { int equalIndex = acl.lastIndexOf("="); String name = acl.substring(0, equalIndex); - if(name.length() == 0) + if (name.length() == 0) { name = "PUBLIC"; } String privs = acl.substring(equalIndex + 1); - for(int i = 0; i < privs.length(); i++) + for (int i = 0; i < privs.length(); i++) { char c = privs.charAt(i); String sqlpriv; - switch(c) + switch (c) { - case 'a': - sqlpriv = "INSERT"; - break; - case 'r': - sqlpriv = "SELECT"; - break; - case 'w': - sqlpriv = "UPDATE"; - break; - case 'd': - sqlpriv = "DELETE"; - break; - case 'R': - sqlpriv = "RULE"; - break; - case 'x': - sqlpriv = "REFERENCES"; - break; - case 't': - sqlpriv = "TRIGGER"; - break; - // the folloowing can't be granted to a table, but - // we'll keep them for completeness. - case 'X': - sqlpriv = "EXECUTE"; - break; - case 'U': - sqlpriv = "USAGE"; - break; - case 'C': - sqlpriv = "CREATE"; - break; - case 'T': - sqlpriv = "CREATE TEMP"; - break; - default: - sqlpriv = "UNKNOWN"; + case 'a': + sqlpriv = "INSERT"; + break; + case 'r': + sqlpriv = "SELECT"; + break; + case 'w': + sqlpriv = "UPDATE"; + break; + case 'd': + sqlpriv = "DELETE"; + break; + case 'R': + sqlpriv = "RULE"; + break; + case 'x': + sqlpriv = "REFERENCES"; + break; + case 't': + sqlpriv = "TRIGGER"; + break; + // the folloowing can't be granted to a table, but + // we'll keep them for completeness. + case 'X': + sqlpriv = "EXECUTE"; + break; + case 'U': + sqlpriv = "USAGE"; + break; + case 'C': + sqlpriv = "CREATE"; + break; + case 'T': + sqlpriv = "CREATE TEMP"; + break; + default: + sqlpriv = "UNKNOWN"; } - ArrayList usersWithPermission = (ArrayList)privileges.get(sqlpriv); - if(usersWithPermission == null) + ArrayList usersWithPermission = privileges.get(sqlpriv); + if (usersWithPermission == null) { - usersWithPermission = new ArrayList(); + usersWithPermission = new ArrayList(); privileges.put(sqlpriv, usersWithPermission); } usersWithPermission.add(name); @@ -2251,15 +2259,16 @@ * mapping the SQL permission name to a ArrayList of usernames who have that * permission. */ - protected HashMap parseACL(String[] aclArray, String owner) + protected HashMap> parseACL(String[] aclArray, + String owner) { - if(aclArray == null || aclArray.length == 0) + if (aclArray == null || aclArray.length == 0) { // null acl is a shortcut for owner having full privs aclArray = new String[] { owner + "=arwdRxt" }; } - HashMap privileges = new HashMap(); - for(int i = 0; i < aclArray.length; i++) + HashMap> privileges = new HashMap>(); + for (int i = 0; i < aclArray.length; i++) { String acl = aclArray[i]; addACLPrivileges(acl, privileges); @@ -2293,7 +2302,8 @@ throws SQLException { ResultSetField f[] = new ResultSetField[8]; - ArrayList v = new ArrayList(); // The new ResultSet tuple stuff + ArrayList v = new ArrayList(); // The new ResultSet + // tuple stuff f[0] = new ResultSetField("SCOPE", TypeOid.INT2, 2); f[1] = new ResultSetField("COLUMN_NAME", TypeOid.VARCHAR, @@ -2318,24 +2328,24 @@ + " AND " + resolveSchemaCondition( "n.nspname", schema); String sql = "SELECT a.attname, a.atttypid as atttypid " + from - + " WHERE ct.oid=i.indrelid AND ci.oid=i.indexrelid " - + " AND a.attrelid=ci.oid AND i.indisprimary " - + " AND ct.relname = '" + escapeQuotes(table) + "' " + where - + " ORDER BY a.attnum "; + + " WHERE ct.oid=i.indrelid AND ci.oid=i.indexrelid " + + " AND a.attrelid=ci.oid AND i.indisprimary " + + " AND ct.relname = '" + escapeQuotes(table) + "' " + where + + " ORDER BY a.attnum "; ResultSet rs = m_connection.createStatement().executeQuery(sql); - while(rs.next()) + while (rs.next()) { Object[] tuple = new Object[8]; - Oid columnTypeOid = (Oid)rs.getObject("atttypid"); - tuple[0] = new Short((short)scope); + Oid columnTypeOid = (Oid) rs.getObject("atttypid"); + tuple[0] = new Short((short) scope); tuple[1] = rs.getString("attname"); - tuple[2] = new Short((short)m_connection.getSQLType(columnTypeOid)); + tuple[2] = new Short((short) m_connection.getSQLType(columnTypeOid)); tuple[3] = m_connection.getPGType(columnTypeOid); tuple[4] = null; tuple[5] = null; tuple[6] = null; - tuple[7] = new Short((short)java.sql.DatabaseMetaData.bestRowNotPseudo); + tuple[7] = new Short((short) java.sql.DatabaseMetaData.bestRowNotPseudo); v.add(tuple); } @@ -2359,10 +2369,11 @@ * name @return ResultSet each row is a column description */ public java.sql.ResultSet getVersionColumns(String catalog, String schema, - String table) throws SQLException + String table) throws SQLException { ResultSetField f[] = new ResultSetField[8]; - ArrayList v = new ArrayList(); // The new ResultSet tuple stuff + ArrayList v = new ArrayList(); // The new ResultSet + // tuple stuff f[0] = new ResultSetField("SCOPE", TypeOid.INT2, 2); f[1] = new ResultSetField("COLUMN_NAME", TypeOid.VARCHAR, @@ -2389,12 +2400,12 @@ tuple[0] = null; tuple[1] = "ctid"; - tuple[2] = new Short((short)m_connection.getSQLType("tid")); + tuple[2] = new Short((short) m_connection.getSQLType("tid")); tuple[3] = "tid"; tuple[4] = null; tuple[5] = null; tuple[6] = null; - tuple[7] = new Short((short)java.sql.DatabaseMetaData.versionColumnPseudo); + tuple[7] = new Short((short) java.sql.DatabaseMetaData.versionColumnPseudo); v.add(tuple); /* @@ -2417,27 +2428,27 @@ * ResultSet each row is a primary key column description */ public java.sql.ResultSet getPrimaryKeys(String catalog, String schema, - String table) throws SQLException + String table) throws SQLException { String from; String where = ""; String select = "SELECT NULL AS TABLE_CAT, n.nspname AS TABLE_SCHEM, "; - from = " FROM pg_catalog.pg_namespace n, pg_catalog.pg_class ct, pg_catalog.pg_class ci, pg_catalog.pg_attribute a, pg_catalog.pg_index i "; + from = " FROM pg_catalog.pg_namespace n, pg_catalog.pg_class ct, pg_catalog.pg_class ci, pg_catalog.pg_attribute a, pg_catalog.pg_index i "; where = " AND ct.relnamespace = n.oid AND " + resolveSchemaCondition("n.nspname", schema); String sql = select + " ct.relname AS TABLE_NAME, " - + " a.attname AS COLUMN_NAME, " + " a.attnum::int2 AS KEY_SEQ, " - + " ci.relname AS PK_NAME " + from - + " WHERE ct.oid=i.indrelid AND ci.oid=i.indexrelid " - + " AND a.attrelid=ci.oid AND i.indisprimary "; - if(table != null && !"".equals(table)) + + " a.attname AS COLUMN_NAME, " + " a.attnum::int2 AS KEY_SEQ, " + + " ci.relname AS PK_NAME " + from + + " WHERE ct.oid=i.indrelid AND ci.oid=i.indexrelid " + + " AND a.attrelid=ci.oid AND i.indisprimary "; + if (table != null && !"".equals(table)) { sql += " AND ct.relname = '" + escapeQuotes(table) + "' "; } sql += where + " ORDER BY table_name, pk_name, key_seq"; - return createMetaDataStatement().executeQuery(sql); + return createMetaDataStatement().executeQuery(sql); } /** @@ -2450,27 +2461,27 @@ */ protected java.sql.ResultSet getImportedExportedKeys(String primaryCatalog, - String primarySchema, String primaryTable, String foreignCatalog, - String foreignSchema, String foreignTable) throws SQLException + String primarySchema, String primaryTable, String foreignCatalog, + String foreignSchema, String foreignTable) throws SQLException { ResultSetField f[] = new ResultSetField[14]; f[0] = new ResultSetField("PKTABLE_CAT", TypeOid.VARCHAR, getMaxNameLength()); f[1] = new ResultSetField("PKTABLE_SCHEM", TypeOid.VARCHAR, - getMaxNameLength()); + getMaxNameLength()); f[2] = new ResultSetField("PKTABLE_NAME", TypeOid.VARCHAR, - getMaxNameLength()); + getMaxNameLength()); f[3] = new ResultSetField("PKCOLUMN_NAME", TypeOid.VARCHAR, - getMaxNameLength()); + getMaxNameLength()); f[4] = new ResultSetField("FKTABLE_CAT", TypeOid.VARCHAR, getMaxNameLength()); f[5] = new ResultSetField("FKTABLE_SCHEM", TypeOid.VARCHAR, - getMaxNameLength()); + getMaxNameLength()); f[6] = new ResultSetField("FKTABLE_NAME", TypeOid.VARCHAR, - getMaxNameLength()); + getMaxNameLength()); f[7] = new ResultSetField("FKCOLUMN_NAME", TypeOid.VARCHAR, - getMaxNameLength()); + getMaxNameLength()); f[8] = new ResultSetField("KEY_SEQ", TypeOid.INT2, 2); f[9] = new ResultSetField("UPDATE_RULE", TypeOid.INT2, 2); f[10] = new ResultSetField("DELETE_RULE", TypeOid.INT2, 2); @@ -2490,65 +2501,65 @@ * make it difficult to determine the PK_NAME field. */ String sql = "SELECT NULL::text AS PKTABLE_CAT, pkn.nspname AS PKTABLE_SCHEM, pkc.relname AS PKTABLE_NAME, pka.attname AS PKCOLUMN_NAME, " - + "NULL::text AS FKTABLE_CAT, fkn.nspname AS FKTABLE_SCHEM, fkc.relname AS FKTABLE_NAME, fka.attname AS FKCOLUMN_NAME, " - + "pos.n::int2 AS KEY_SEQ, " - + "CASE con.confupdtype " - + " WHEN 'c' THEN " - + DatabaseMetaData.importedKeyCascade - + " WHEN 'n' THEN " - + DatabaseMetaData.importedKeySetNull - + " WHEN 'd' THEN " - + DatabaseMetaData.importedKeySetDefault - + " WHEN 'r' THEN " - + DatabaseMetaData.importedKeyRestrict - + " WHEN 'a' THEN " - + DatabaseMetaData.importedKeyNoAction - + " ELSE NULL END::int2 AS UPDATE_RULE, " - + "CASE con.confdeltype " - + " WHEN 'c' THEN " - + DatabaseMetaData.importedKeyCascade - + " WHEN 'n' THEN " - + DatabaseMetaData.importedKeySetNull - + " WHEN 'd' THEN " - + DatabaseMetaData.importedKeySetDefault - + " WHEN 'r' THEN " - + DatabaseMetaData.importedKeyRestrict - + " WHEN 'a' THEN " - + DatabaseMetaData.importedKeyNoAction - + " ELSE NULL END::int2 AS DELETE_RULE, " - + "con.conname AS FK_NAME, pkic.relname AS PK_NAME, " - + "CASE " - + " WHEN con.condeferrable AND con.condeferred THEN " - + DatabaseMetaData.importedKeyInitiallyDeferred - + " WHEN con.condeferrable THEN " - + DatabaseMetaData.importedKeyInitiallyImmediate - + " ELSE " - + DatabaseMetaData.importedKeyNotDeferrable - + " END::int2 AS DEFERRABILITY " - + " FROM " - + " pg_catalog.pg_namespace pkn, pg_catalog.pg_class pkc, pg_catalog.pg_attribute pka, " - + " pg_catalog.pg_namespace fkn, pg_catalog.pg_class fkc, pg_catalog.pg_attribute fka, " - + " pg_catalog.pg_constraint con, " + + "NULL::text AS FKTABLE_CAT, fkn.nspname AS FKTABLE_SCHEM, fkc.relname AS FKTABLE_NAME, fka.attname AS FKCOLUMN_NAME, " + + "pos.n::int2 AS KEY_SEQ, " + + "CASE con.confupdtype " + + " WHEN 'c' THEN " + + DatabaseMetaData.importedKeyCascade + + " WHEN 'n' THEN " + + DatabaseMetaData.importedKeySetNull + + " WHEN 'd' THEN " + + DatabaseMetaData.importedKeySetDefault + + " WHEN 'r' THEN " + + DatabaseMetaData.importedKeyRestrict + + " WHEN 'a' THEN " + + DatabaseMetaData.importedKeyNoAction + + " ELSE NULL END::int2 AS UPDATE_RULE, " + + "CASE con.confdeltype " + + " WHEN 'c' THEN " + + DatabaseMetaData.importedKeyCascade + + " WHEN 'n' THEN " + + DatabaseMetaData.importedKeySetNull + + " WHEN 'd' THEN " + + DatabaseMetaData.importedKeySetDefault + + " WHEN 'r' THEN " + + DatabaseMetaData.importedKeyRestrict + + " WHEN 'a' THEN " + + DatabaseMetaData.importedKeyNoAction + + " ELSE NULL END::int2 AS DELETE_RULE, " + + "con.conname AS FK_NAME, pkic.relname AS PK_NAME, " + + "CASE " + + " WHEN con.condeferrable AND con.condeferred THEN " + + DatabaseMetaData.importedKeyInitiallyDeferred + + " WHEN con.condeferrable THEN " + + DatabaseMetaData.importedKeyInitiallyImmediate + + " ELSE " + + DatabaseMetaData.importedKeyNotDeferrable + + " END::int2 AS DEFERRABILITY " + + " FROM " + + " pg_catalog.pg_namespace pkn, pg_catalog.pg_class pkc, pg_catalog.pg_attribute pka, " + + " pg_catalog.pg_namespace fkn, pg_catalog.pg_class fkc, pg_catalog.pg_attribute fka, " + + " pg_catalog.pg_constraint con, " + " pg_catalog.generate_series(1, " + getMaxIndexKeys() + ") pos(n), " - + " pg_catalog.pg_depend dep, pg_catalog.pg_class pkic " - + " WHERE pkn.oid = pkc.relnamespace AND pkc.oid = pka.attrelid AND pka.attnum = con.confkey[pos.n] AND con.confrelid = pkc.oid " - + " AND fkn.oid = fkc.relnamespace AND fkc.oid = fka.attrelid AND fka.attnum = con.conkey[pos.n] AND con.conrelid = fkc.oid " + + " pg_catalog.pg_depend dep, pg_catalog.pg_class pkic " + + " WHERE pkn.oid = pkc.relnamespace AND pkc.oid = pka.attrelid AND pka.attnum = con.confkey[pos.n] AND con.confrelid = pkc.oid " + + " AND fkn.oid = fkc.relnamespace AND fkc.oid = fka.attrelid AND fka.attnum = con.conkey[pos.n] AND con.conrelid = fkc.oid " + " AND con.contype = 'f' AND con.oid = dep.objid AND pkic.oid = dep.refobjid AND pkic.relkind = 'i' AND dep.classid = 'pg_constraint'::regclass::oid AND dep.refclassid = 'pg_class'::regclass::oid " + " AND " + resolveSchemaCondition("pkn.nspname", primarySchema) + " AND " + resolveSchemaCondition("fkn.nspname", foreignSchema); - if(primaryTable != null && !"".equals(primaryTable)) + if (primaryTable != null && !"".equals(primaryTable)) { sql += " AND pkc.relname = '" + escapeQuotes(primaryTable) + "' "; } - if(foreignTable != null && !"".equals(foreignTable)) + if (foreignTable != null && !"".equals(foreignTable)) { sql += " AND fkc.relname = '" + escapeQuotes(foreignTable) + "' "; } - if(primaryTable != null) + if (primaryTable != null) { sql += " ORDER BY fkn.nspname,fkc.relname,pos.n"; } @@ -2593,7 +2604,7 @@ * @see #getExportedKeys */ public java.sql.ResultSet getImportedKeys(String catalog, String schema, - String table) throws SQLException + String table) throws SQLException { return getImportedExportedKeys(null, null, null, catalog, schema, table); } @@ -2633,7 +2644,7 @@ * @see #getImportedKeys */ public java.sql.ResultSet getExportedKeys(String catalog, String schema, - String table) throws SQLException + String table) throws SQLException { return getImportedExportedKeys(catalog, schema, table, null, null, null); } @@ -2675,8 +2686,8 @@ * @see #getImportedKeys */ public java.sql.ResultSet getCrossReference(String primaryCatalog, - String primarySchema, String primaryTable, String foreignCatalog, - String foreignSchema, String foreignTable) throws SQLException + String primarySchema, String primaryTable, String foreignCatalog, + String foreignSchema, String foreignTable) throws SQLException { return getImportedExportedKeys(primaryCatalog, primarySchema, primaryTable, foreignCatalog, foreignSchema, foreignTable); @@ -2713,18 +2724,19 @@ { ResultSetField f[] = new ResultSetField[18]; - ArrayList v = new ArrayList(); // The new ResultSet tuple stuff + ArrayList v = new ArrayList(); // The new ResultSet + // tuple stuff f[0] = new ResultSetField("TYPE_NAME", TypeOid.VARCHAR, getMaxNameLength()); f[1] = new ResultSetField("DATA_TYPE", TypeOid.INT2, 2); f[2] = new ResultSetField("PRECISION", TypeOid.INT4, 4); f[3] = new ResultSetField("LITERAL_PREFIX", TypeOid.VARCHAR, - getMaxNameLength()); + getMaxNameLength()); f[4] = new ResultSetField("LITERAL_SUFFIX", TypeOid.VARCHAR, - getMaxNameLength()); + getMaxNameLength()); f[5] = new ResultSetField("CREATE_PARAMS", TypeOid.VARCHAR, - getMaxNameLength()); + getMaxNameLength()); f[6] = new ResultSetField("NULLABLE", TypeOid.INT2, 2); f[7] = new ResultSetField("CASE_SENSITIVE", TypeOid.BOOL, 1); f[8] = new ResultSetField("SEARCHABLE", TypeOid.INT2, 2); @@ -2732,7 +2744,7 @@ f[10] = new ResultSetField("FIXED_PREC_SCALE", TypeOid.BOOL, 1); f[11] = new ResultSetField("AUTO_INCREMENT", TypeOid.BOOL, 1); f[12] = new ResultSetField("LOCAL_TYPE_NAME", TypeOid.VARCHAR, - getMaxNameLength()); + getMaxNameLength()); f[13] = new ResultSetField("MINIMUM_SCALE", TypeOid.INT2, 2); f[14] = new ResultSetField("MAXIMUM_SCALE", TypeOid.INT2, 2); f[15] = new ResultSetField("SQL_DATA_TYPE", TypeOid.INT4, 4); @@ -2746,17 +2758,17 @@ // things up a little. Integer i9 = new Integer(9); Integer i10 = new Integer(10); - Short nn = new Short((short)java.sql.DatabaseMetaData.typeNoNulls); - Short ts = new Short((short)java.sql.DatabaseMetaData.typeSearchable); + Short nn = new Short((short) java.sql.DatabaseMetaData.typeNoNulls); + Short ts = new Short((short) java.sql.DatabaseMetaData.typeSearchable); String typname = null; - while(rs.next()) + while (rs.next()) { Object[] tuple = new Object[18]; typname = rs.getString(1); tuple[0] = typname; - tuple[1] = new Short((short)m_connection.getSQLType(typname)); + tuple[1] = new Short((short) m_connection.getSQLType(typname)); tuple[2] = i9; // for now tuple[6] = nn; // for now tuple[7] = Boolean.FALSE; // false for now - not case sensitive @@ -2772,9 +2784,9 @@ v.add(tuple); // add pseudo-type serial, bigserial - if(typname.equals("int4")) + if (typname.equals("int4")) { - Object[] tuple1 = (Object[])tuple.clone(); + Object[] tuple1 = (Object[]) tuple.clone(); tuple1[0] = "serial"; tuple1[11] = Boolean.TRUE; @@ -2782,7 +2794,7 @@ } else if(typname.equals("int8")) { - Object[] tuple1 = (Object[])tuple.clone(); + Object[] tuple1 = (Object[]) tuple.clone(); tuple1[0] = "bigserial"; tuple1[11] = Boolean.TRUE; @@ -2831,8 +2843,8 @@ */ // Implementation note: This is required for Borland's JBuilder to work public java.sql.ResultSet getIndexInfo(String catalog, String schema, - String tableName, boolean unique, boolean approximate) - throws SQLException + String tableName, boolean unique, boolean approximate) + throws SQLException { String select = "SELECT NULL AS TABLE_CAT, n.nspname AS TABLE_SCHEM, "; String from = " FROM pg_catalog.pg_namespace n, pg_catalog.pg_class ct, pg_catalog.pg_class ci, pg_catalog.pg_index i, pg_catalog.pg_attribute a, pg_catalog.pg_am am "; @@ -2841,28 +2853,28 @@ " AND " + resolveSchemaCondition("n.nspname", schema); String sql = select - + " ct.relname AS TABLE_NAME, NOT i.indisunique AS NON_UNIQUE, NULL AS INDEX_QUALIFIER, ci.relname AS INDEX_NAME, " - + " CASE i.indisclustered " - + " WHEN true THEN " - + java.sql.DatabaseMetaData.tableIndexClustered - + " ELSE CASE am.amname " - + " WHEN 'hash' THEN " - + java.sql.DatabaseMetaData.tableIndexHashed - + " ELSE " - + java.sql.DatabaseMetaData.tableIndexOther - + " END " - + " END::int2 AS TYPE, " - + " a.attnum::int2 AS ORDINAL_POSITION, " - + " a.attname AS COLUMN_NAME, " - + " NULL AS ASC_OR_DESC, " - + " ci.reltuples AS CARDINALITY, " - + " ci.relpages AS PAGES, " - + " NULL AS FILTER_CONDITION " - + from - + " WHERE ct.oid=i.indrelid AND ci.oid=i.indexrelid AND a.attrelid=ci.oid AND ci.relam=am.oid " - + where + " AND ct.relname = '" + escapeQuotes(tableName) + "' "; + + " ct.relname AS TABLE_NAME, NOT i.indisunique AS NON_UNIQUE, NULL AS INDEX_QUALIFIER, ci.relname AS INDEX_NAME, " + + " CASE i.indisclustered " + + " WHEN true THEN " + + java.sql.DatabaseMetaData.tableIndexClustered + + " ELSE CASE am.amname " + + " WHEN 'hash' THEN " + + java.sql.DatabaseMetaData.tableIndexHashed + + " ELSE " + + java.sql.DatabaseMetaData.tableIndexOther + + " END " + + " END::int2 AS TYPE, " + + " a.attnum::int2 AS ORDINAL_POSITION, " + + " a.attname AS COLUMN_NAME, " + + " NULL AS ASC_OR_DESC, " + + " ci.reltuples AS CARDINALITY, " + + " ci.relpages AS PAGES, " + + " NULL AS FILTER_CONDITION " + + from + + " WHERE ct.oid=i.indrelid AND ci.oid=i.indexrelid AND a.attrelid=ci.oid AND ci.relam=am.oid " + + where + " AND ct.relname = '" + escapeQuotes(tableName) + "' "; - if(unique) + if (unique) { sql += " AND i.indisunique "; } @@ -2891,14 +2903,14 @@ * occurs */ public boolean supportsResultSetConcurrency(int type, int concurrency) - throws SQLException + throws SQLException { // These combinations are not supported! - if(type != java.sql.ResultSet.TYPE_FORWARD_ONLY) + if (type != java.sql.ResultSet.TYPE_FORWARD_ONLY) return false; // We support only Concur Read Only - if(concurrency != java.sql.ResultSet.CONCUR_READ_ONLY) + if (concurrency != java.sql.ResultSet.CONCUR_READ_ONLY) return false; // Everything else we do @@ -2969,43 +2981,43 @@ * @return ResultSet */ public java.sql.ResultSet getUDTs(String catalog, String schemaPattern, - String typeNamePattern, int[] types) throws SQLException + String typeNamePattern, int[] types) throws SQLException { String sql = "select " - + "null as type_cat, n.nspname as type_schem, t.typname as type_name, null as class_name, " - + "CASE WHEN t.typtype='c' then " - + java.sql.Types.STRUCT - + " else " - + java.sql.Types.DISTINCT - + " end as data_type, pg_catalog.obj_description(t.oid, 'pg_type') " - + "as remarks, CASE WHEN t.typtype = 'd' then (select CASE"; + + "null as type_cat, n.nspname as type_schem, t.typname as type_name, null as class_name, " + + "CASE WHEN t.typtype='c' then " + + java.sql.Types.STRUCT + + " else " + + java.sql.Types.DISTINCT + + " end as data_type, pg_catalog.obj_description(t.oid, 'pg_type') " + + "as remarks, CASE WHEN t.typtype = 'd' then (select CASE"; - for(int i = 0; i < SPIConnection.JDBC3_TYPE_NAMES.length; i++) + for (int i = 0; i < SPIConnection.JDBC3_TYPE_NAMES.length; i++) { sql += " when typname = '" + SPIConnection.JDBC_TYPE_NUMBERS[i] - + "' then " + SPIConnection.JDBC_TYPE_NUMBERS[i]; + + "' then " + SPIConnection.JDBC_TYPE_NUMBERS[i]; } sql += " else " - + java.sql.Types.OTHER - + " end from pg_type where oid=t.typbasetype) " - + "else null end as base_type " - + "from pg_catalog.pg_type t, pg_catalog.pg_namespace n where t.typnamespace = n.oid and n.nspname != 'pg_catalog' and n.nspname != 'pg_toast'"; + + java.sql.Types.OTHER + + " end from pg_type where oid=t.typbasetype) " + + "else null end as base_type " + + "from pg_catalog.pg_type t, pg_catalog.pg_namespace n where t.typnamespace = n.oid and n.nspname != 'pg_catalog' and n.nspname != 'pg_toast'"; String toAdd = ""; - if(types != null) + if (types != null) { toAdd += " and (false "; - for(int i = 0; i < types.length; i++) + for (int i = 0; i < types.length; i++) { - switch(types[i]) + switch (types[i]) { - case java.sql.Types.STRUCT: - toAdd += " or t.typtype = 'c'"; - break; - case java.sql.Types.DISTINCT: - toAdd += " or t.typtype = 'd'"; - break; + case java.sql.Types.STRUCT: + toAdd += " or t.typtype = 'c'"; + break; + case java.sql.Types.DISTINCT: + toAdd += " or t.typtype = 'd'"; + break; } } toAdd += " ) "; @@ -3017,16 +3029,16 @@ // spec says that if typeNamePattern is a fully qualified name // then the schema and catalog are ignored - if(typeNamePattern != null) + if (typeNamePattern != null) { // search for qualifier int firstQualifier = typeNamePattern.indexOf('.'); int secondQualifier = typeNamePattern.lastIndexOf('.'); if(firstQualifier != -1) // if one of them is -1 they both will - // be + // be { - if(firstQualifier != secondQualifier) + if (firstQualifier != secondQualifier) { // we have a catalog.schema.typename, ignore catalog schemaPattern = typeNamePattern.substring( @@ -3047,7 +3059,7 @@ } // schemaPattern may have been modified above - if(schemaPattern != null) + if (schemaPattern != null) { toAdd += " and n.nspname like '" + escapeQuotes(schemaPattern) + "'"; @@ -3083,7 +3095,7 @@ private Statement createMetaDataStatement() throws SQLException { return m_connection.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY, - java.sql.ResultSet.CONCUR_READ_ONLY); + java.sql.ResultSet.CONCUR_READ_ONLY); } /** @@ -3184,7 +3196,7 @@ * @since 1.4 */ public ResultSet getSuperTypes(String catalog, String schemaPattern, - String typeNamePattern) throws SQLException + String typeNamePattern) throws SQLException { throw new UnsupportedFeatureException("DatabaseMetaData.getSuperTypes"); } @@ -3227,7 +3239,7 @@ * @since 1.4 */ public ResultSet getSuperTables(String catalog, String schemaPattern, - String tableNamePattern) throws SQLException + String tableNamePattern) throws SQLException { throw new UnsupportedFeatureException("DatabaseMetaData.getSuperTables"); } @@ -3261,9 +3273,9 @@ *
      • NUM_PREC_RADIX int => Radix (typically either 10 or 2) *
      • NULLABLE int => whether NULL is allowed *
          - *
        • attributeNoNulls - might not allow NULL values - *
        • attributeNullable - definitely allows NULL values - *
        • attributeNullableUnknown - nullability unknown + *
        • attributeNoNulls - might not allow NULL values + *
        • attributeNullable - definitely allows NULL values + *
        • attributeNullableUnknown - nullability unknown *
        *
      • REMARKS String => comment describing column (may be * null) @@ -3444,8 +3456,66 @@ * statement. */ private ResultSet createSyntheticResultSet(ResultSetField[] f, ArrayList tuples) - throws SQLException + throws SQLException { return new SyntheticResultSet(f, tuples); } + + public boolean autoCommitFailureClosesAllResultSets() throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public ResultSet getClientInfoProperties() throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public ResultSet getFunctionColumns(String catalog, String schemaPattern, + String functionNamePattern, String columnNamePattern) + throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public ResultSet getFunctions(String catalog, String schemaPattern, + String functionNamePattern) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public RowIdLifetime getRowIdLifetime() throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public ResultSet getSchemas(String catalog, String schemaPattern) + throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public boolean supportsStoredFunctionsUsingCallSyntax() throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public boolean isWrapperFor(Class iface) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public T unwrap(Class iface) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } } Index: src/java/pljava/org/postgresql/pljava/jdbc/ClobValue.java =================================================================== RCS file: /cvsroot/pljava/org.postgresql.pljava/src/java/pljava/org/postgresql/pljava/jdbc/ClobValue.java,v retrieving revision 1.4 diff -u -r1.4 ClobValue.java --- src/java/pljava/org/postgresql/pljava/jdbc/ClobValue.java 6 May 2006 11:41:13 -0000 1.4 +++ src/java/pljava/org/postgresql/pljava/jdbc/ClobValue.java 17 May 2010 19:50:49 -0000 @@ -8,8 +8,8 @@ import java.io.BufferedInputStream; import java.io.CharConversionException; -import java.io.InputStream; import java.io.IOException; +import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.StringReader; @@ -28,10 +28,10 @@ { value.mark(Integer.MAX_VALUE); long length = value.skip(Long.MAX_VALUE); - if(length > Integer.MAX_VALUE) + if (length > Integer.MAX_VALUE) throw new SQLException("stream content too large"); value.reset(); - return (int)length; + return (int) length; } catch(IOException e) { @@ -60,6 +60,7 @@ this(new StringReader(value), value.length()); } + @Override public void close() throws IOException { m_reader.close(); @@ -71,12 +72,13 @@ { return new BufferedInputStream(new InputStream() { + @Override public int read() throws IOException { int nextChar = ClobValue.this.read(); - if(nextChar > 127) + if (nextChar > 127) throw new CharConversionException( - "Non ascii character in Clob data"); + "Non ascii character in Clob data"); return nextChar; } }); @@ -89,26 +91,26 @@ public String getSubString(long pos, int length) throws SQLException { - if(pos < 0L || length < 0) + if (pos < 0L || length < 0) throw new IllegalArgumentException(); - if(length == 0) + if (length == 0) return ""; - if(pos + length > m_nChars) + if (pos + length > m_nChars) throw new SQLException("Attempt to read beyond end of Clob data"); long skip = pos - m_readerPos; - if(skip < 0) + if (skip < 0) throw new SQLException("Cannot position Clob stream backwards"); try { - if(skip > 0) + if (skip > 0) this.skip(skip); char[] buf = new char[length]; int nr = this.read(buf); - if(nr < length) + if (nr < length) throw new SQLException("Clob data read not fulfilled"); return new String(buf); } @@ -123,12 +125,14 @@ return m_nChars; } + @Override public synchronized void mark(int readLimit) throws IOException { m_reader.mark(readLimit); m_markPos = m_readerPos; } + @Override public boolean markSupported() { return m_reader.markSupported(); @@ -150,6 +154,7 @@ throw new UnsupportedOperationException(); } + @Override public synchronized int read() throws IOException { int rs = m_reader.read(); @@ -157,6 +162,7 @@ return rs; } + @Override public synchronized int read(char[] b) throws IOException { int rs = m_reader.read(b); @@ -164,6 +170,7 @@ return rs; } + @Override public synchronized int read(char[] b, int off, int len) throws IOException { int rs = m_reader.read(b, off, len); @@ -171,11 +178,13 @@ return rs; } + @Override public synchronized boolean ready() throws IOException { return m_reader.ready(); } + @Override public synchronized void reset() throws IOException { m_reader.reset(); @@ -214,6 +223,7 @@ throw new UnsupportedOperationException(); } + @Override public synchronized long skip(long nBytes) throws IOException { long skipped = m_reader.skip(nBytes); @@ -228,4 +238,17 @@ { throw new UnsupportedOperationException(); } + + public void free() throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + + } + + public Reader getCharacterStream(long pos, long length) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } } Index: src/java/pljava/org/postgresql/pljava/jdbc/SQLInputFromTuple.java =================================================================== RCS file: /cvsroot/pljava/org.postgresql.pljava/src/java/pljava/org/postgresql/pljava/jdbc/SQLInputFromTuple.java,v retrieving revision 1.1 diff -u -r1.1 SQLInputFromTuple.java --- src/java/pljava/org/postgresql/pljava/jdbc/SQLInputFromTuple.java 6 May 2006 11:41:13 -0000 1.1 +++ src/java/pljava/org/postgresql/pljava/jdbc/SQLInputFromTuple.java 17 May 2010 19:50:50 -0000 @@ -14,9 +14,12 @@ import java.sql.Blob; import java.sql.Clob; import java.sql.Date; +import java.sql.NClob; import java.sql.Ref; +import java.sql.RowId; import java.sql.SQLException; import java.sql.SQLInput; +import java.sql.SQLXML; import java.sql.Time; import java.sql.Timestamp; @@ -28,7 +31,7 @@ * A single row, updateable ResultSet specially made for triggers. The * changes made to this ResultSet are remembered and converted to a * SPI_modify_tuple call prior to function return. - * + * * @author Thomas Hallgren */ public class SQLInputFromTuple extends JavaWrapper implements SQLInput @@ -38,17 +41,17 @@ private boolean m_wasNull; public SQLInputFromTuple(long heapTupleHeaderPointer, TupleDesc tupleDesc) - throws SQLException + throws SQLException { super(heapTupleHeaderPointer); m_tupleDesc = tupleDesc; - m_index = 0; + m_index = 0; m_wasNull = false; } public Array readArray() throws SQLException { - return (Array)this.readValue(Array.class); + return (Array) this.readValue(Array.class); } public InputStream readAsciiStream() throws SQLException @@ -59,7 +62,7 @@ public BigDecimal readBigDecimal() throws SQLException { - return (BigDecimal)this.readValue(BigDecimal.class); + return (BigDecimal) this.readValue(BigDecimal.class); } public InputStream readBinaryStream() throws SQLException @@ -71,12 +74,12 @@ public Blob readBlob() throws SQLException { byte[] bytes = this.readBytes(); - return (bytes == null) ? null : new BlobValue(bytes); + return (bytes == null) ? null : new BlobValue(bytes); } public boolean readBoolean() throws SQLException { - Boolean b = (Boolean)this.readValue(Boolean.class); + Boolean b = (Boolean) this.readValue(Boolean.class); return (b == null) ? false : b.booleanValue(); } @@ -88,7 +91,7 @@ public byte[] readBytes() throws SQLException { - return (byte[])this.readValue(byte[].class); + return (byte[]) this.readValue(byte[].class); } public Reader readCharacterStream() throws SQLException @@ -100,12 +103,12 @@ public Clob readClob() throws SQLException { String str = this.readString(); - return (str == null) ? null : new ClobValue(str); + return (str == null) ? null : new ClobValue(str); } public Date readDate() throws SQLException { - return (Date)this.readValue(Date.class); + return (Date) this.readValue(Date.class); } public double readDouble() throws SQLException @@ -134,10 +137,10 @@ public Object readObject() throws SQLException { - if(m_index < m_tupleDesc.size()) + if (m_index < m_tupleDesc.size()) { Object v; - synchronized(Backend.THREADLOCK) + synchronized (Backend.THREADLOCK) { v = _getObject(this.getNativePointer(), m_tupleDesc.getNativePointer(), ++m_index); } @@ -149,7 +152,7 @@ public Ref readRef() throws SQLException { - return (Ref)this.readValue(Ref.class); + return (Ref) this.readValue(Ref.class); } public short readShort() throws SQLException @@ -160,22 +163,22 @@ public String readString() throws SQLException { - return (String)this.readValue(String.class); + return (String) this.readValue(String.class); } public Time readTime() throws SQLException { - return (Time)this.readValue(Time.class); + return (Time) this.readValue(Time.class); } public Timestamp readTimestamp() throws SQLException { - return (Timestamp)this.readValue(Timestamp.class); + return (Timestamp) this.readValue(Timestamp.class); } public URL readURL() throws SQLException { - return (URL)this.readValue(URL.class); + return (URL) this.readValue(URL.class); } public boolean wasNull() throws SQLException @@ -193,8 +196,33 @@ return SPIConnection.basicCoersion(valueClass, this.readObject()); } + @Override protected native void _free(long pointer); - private static native Object _getObject(long pointer, long tupleDescPointer, int index) + private static native Object _getObject(long pointer, long tupleDescPointer, int index) throws SQLException; + + public NClob readNClob() throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public String readNString() throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public RowId readRowId() throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public SQLXML readSQLXML() throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } } Index: src/java/pljava/org/postgresql/pljava/jdbc/SQLOutputToTuple.java =================================================================== RCS file: /cvsroot/pljava/org.postgresql.pljava/src/java/pljava/org/postgresql/pljava/jdbc/SQLOutputToTuple.java,v retrieving revision 1.2 diff -u -r1.2 SQLOutputToTuple.java --- src/java/pljava/org/postgresql/pljava/jdbc/SQLOutputToTuple.java 6 May 2006 12:52:42 -0000 1.2 +++ src/java/pljava/org/postgresql/pljava/jdbc/SQLOutputToTuple.java 17 May 2010 19:50:50 -0000 @@ -18,10 +18,13 @@ import java.sql.Blob; import java.sql.Clob; import java.sql.Date; +import java.sql.NClob; import java.sql.Ref; +import java.sql.RowId; import java.sql.SQLData; import java.sql.SQLException; import java.sql.SQLOutput; +import java.sql.SQLXML; import java.sql.Struct; import java.sql.Time; import java.sql.Timestamp; @@ -34,170 +37,186 @@ */ public class SQLOutputToTuple implements SQLOutput { - private final Object[] m_values; - private final TupleDesc m_tupleDesc; - private int m_index; - private Tuple m_tuple; + private final Object[] m_values; + private final TupleDesc m_tupleDesc; + private int m_index; + private Tuple m_tuple; public SQLOutputToTuple(TupleDesc tupleDesc) { - m_tupleDesc = tupleDesc; - m_values = new Object[tupleDesc.size()]; - m_index = 0; - } + m_tupleDesc = tupleDesc; + m_values = new Object[tupleDesc.size()]; + m_index = 0; + } - /** + /** * Creates a tuple from the written values and returns its native pointer. * All values must have been written. This method is called automatically by * the trigger handler and should not be called in any other way. - * - * @return The Tuple reflecting the current row values. - * @throws SQLException - */ + * + * @return The Tuple reflecting the current row values. + * @throws SQLException + */ public long getTuple() throws SQLException { - if(m_tuple != null) - return m_tuple.getNativePointer(); + if (m_tuple != null) + return m_tuple.getNativePointer(); - if(m_index < m_values.length) - throw new SQLException("Too few values have been written"); + if (m_index < m_values.length) + throw new SQLException("Too few values have been written"); - m_tuple = m_tupleDesc.formTuple(m_values); - return m_tuple.getNativePointer(); - } + m_tuple = m_tupleDesc.formTuple(m_values); + return m_tuple.getNativePointer(); + } public void writeArray(Array value) throws SQLException { - this.writeValue(value); - } + this.writeValue(value); + } public void writeAsciiStream(InputStream value) throws SQLException { try { - Reader rdr = new BufferedReader(new InputStreamReader(value, "US-ASCII")); - this.writeClob(new ClobValue(rdr, ClobValue.getReaderLength(rdr))); + Reader rdr = new BufferedReader(new InputStreamReader(value, "US-ASCII")); + this.writeClob(new ClobValue(rdr, ClobValue.getReaderLength(rdr))); } catch(UnsupportedEncodingException e) { - throw new SQLException(e.toString()); - } - } + throw new SQLException(e.toString()); + } + } public void writeBigDecimal(BigDecimal value) throws SQLException { - this.writeValue(value); - } + this.writeValue(value); + } public void writeBinaryStream(InputStream value) throws SQLException { - if(!value.markSupported()) - value = new BufferedInputStream(value); - this.writeBlob(new BlobValue(value, BlobValue.getStreamLength(value))); - } + if (!value.markSupported()) + value = new BufferedInputStream(value); + this.writeBlob(new BlobValue(value, BlobValue.getStreamLength(value))); + } public void writeBlob(Blob value) throws SQLException { - this.writeValue(value); - } + this.writeValue(value); + } public void writeBoolean(boolean value) throws SQLException { - this.writeValue(value ? Boolean.TRUE : Boolean.FALSE); - } + this.writeValue(value ? Boolean.TRUE : Boolean.FALSE); + } public void writeByte(byte value) throws SQLException { - this.writeValue(new Byte(value)); - } + this.writeValue(new Byte(value)); + } public void writeBytes(byte[] value) throws SQLException { - this.writeValue(value); - } + this.writeValue(value); + } public void writeCharacterStream(Reader value) throws SQLException { - if(!value.markSupported()) - value = new BufferedReader(value); - this.writeClob(new ClobValue(value, ClobValue.getReaderLength(value))); - } + if (!value.markSupported()) + value = new BufferedReader(value); + this.writeClob(new ClobValue(value, ClobValue.getReaderLength(value))); + } public void writeClob(Clob value) throws SQLException { - this.writeValue(value); - } + this.writeValue(value); + } public void writeDate(Date value) throws SQLException { - this.writeValue(value); - } + this.writeValue(value); + } public void writeDouble(double value) throws SQLException { - this.writeValue(new Double(value)); - } + this.writeValue(new Double(value)); + } public void writeFloat(float value) throws SQLException { - this.writeValue(new Float(value)); - } + this.writeValue(new Float(value)); + } public void writeInt(int value) throws SQLException { - this.writeValue(new Integer(value)); - } + this.writeValue(new Integer(value)); + } public void writeLong(long value) throws SQLException { - this.writeValue(new Long(value)); - } + this.writeValue(new Long(value)); + } public void writeObject(SQLData value) throws SQLException { - this.writeValue(value); - } + this.writeValue(value); + } public void writeRef(Ref value) throws SQLException { - this.writeValue(value); - } + this.writeValue(value); + } public void writeShort(short value) throws SQLException { - this.writeValue(new Short(value)); - } + this.writeValue(new Short(value)); + } public void writeString(String value) throws SQLException { - this.writeValue(value); - } + this.writeValue(value); + } public void writeStruct(Struct value) throws SQLException { - this.writeValue(value); - } + this.writeValue(value); + } public void writeTime(Time value) throws SQLException { - this.writeValue(value); - } + this.writeValue(value); + } public void writeTimestamp(Timestamp value) throws SQLException { - this.writeValue(value); - } + this.writeValue(value); + } public void writeURL(URL value) throws SQLException { - this.writeValue(value.toString()); - } + this.writeValue(value.toString()); + } private void writeValue(Object value) throws SQLException { - if(m_index >= m_values.length) - throw new SQLException("Tuple cannot take more values"); - m_values[m_index++] = value; - } + if (m_index >= m_values.length) + throw new SQLException("Tuple cannot take more values"); + m_values[m_index++] = value; + } + + public void writeNClob(NClob x) throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } + + public void writeNString(String x) throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } + + public void writeRowId(RowId x) throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } + + public void writeSQLXML(SQLXML x) throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } } Index: src/java/pljava/org/postgresql/pljava/jdbc/TriggerResultSet.java =================================================================== RCS file: /cvsroot/pljava/org.postgresql.pljava/src/java/pljava/org/postgresql/pljava/jdbc/TriggerResultSet.java,v retrieving revision 1.6 diff -u -r1.6 TriggerResultSet.java --- src/java/pljava/org/postgresql/pljava/jdbc/TriggerResultSet.java 22 Mar 2006 20:52:30 -0000 1.6 +++ src/java/pljava/org/postgresql/pljava/jdbc/TriggerResultSet.java 17 May 2010 19:50:50 -0000 @@ -16,125 +16,123 @@ * A single row, updateable ResultSet specially made for triggers. The * changes made to this ResultSet are remembered and converted to a * SPI_modify_tuple call prior to function return. - * + * * @author Thomas Hallgren */ public class TriggerResultSet extends SingleRowResultSet { private ArrayList m_tupleChanges; - private final TupleDesc m_tupleDesc; - private final Tuple m_tuple; - private final boolean m_readOnly; + private final TupleDesc m_tupleDesc; + private final Tuple m_tuple; + private final boolean m_readOnly; public TriggerResultSet(TupleDesc tupleDesc, Tuple tuple, boolean readOnly) throws SQLException { - m_tupleDesc = tupleDesc; - m_tuple = tuple; - m_readOnly = readOnly; - } - - /** - * Cancel all changes made to the Tuple. - */ + m_tupleDesc = tupleDesc; + m_tuple = tuple; + m_readOnly = readOnly; + } + + /** + * Cancel all changes made to the Tuple. + */ public void cancelRowUpdates() throws SQLException { - m_tupleChanges = null; - } + m_tupleChanges = null; + } - /** - * Cancels all changes but doesn't really close the set. - */ + /** + * Cancels all changes but doesn't really close the set. + */ public void close() throws SQLException { - m_tupleChanges = null; - } + m_tupleChanges = null; + } - /** - * Returns the concurrency for this ResultSet. - * @see java.sql.ResultSet#getConcurrency - */ + /** + * Returns the concurrency for this ResultSet. + * @see java.sql.ResultSet#getConcurrency + */ public int getConcurrency() throws SQLException { - return m_readOnly ? CONCUR_READ_ONLY : CONCUR_UPDATABLE; - } + return m_readOnly ? CONCUR_READ_ONLY : CONCUR_UPDATABLE; + } - /** - * Returns true if this row has been updated. - */ + /** + * Returns true if this row has been updated. + */ public boolean rowUpdated() throws SQLException { - return m_tupleChanges != null; - } + return m_tupleChanges != null; + } - /** - * Store this change for later use - */ + /** + * Store this change for later use + */ public void updateObject(int columnIndex, Object x) throws SQLException { - if(m_readOnly) - throw new UnsupportedFeatureException("ResultSet is read-only"); + if (m_readOnly) + throw new UnsupportedFeatureException("ResultSet is read-only"); - if(m_tupleChanges == null) - m_tupleChanges = new ArrayList(); + if (m_tupleChanges == null) + m_tupleChanges = new ArrayList(); - m_tupleChanges.add(new Integer(columnIndex)); - m_tupleChanges.add(x); - } + m_tupleChanges.add(new Integer(columnIndex)); + m_tupleChanges.add(x); + } - - /** + /** * Return a 2 element array describing the changes that has been made to * the contained Tuple. The first element is an int[] containing * the index of each changed value. The second element is an Object[] * with containing the corresponding values. - * - * @return The 2 element array or null if no change has been made. - */ + * + * @return The 2 element array or null if no change has been made. + */ public Object[] getChangeIndexesAndValues() { - ArrayList changes = m_tupleChanges; - if(changes == null) - return null; - - int top = changes.size(); - if(changes.size() == 0) - return null; - - top /= 2; - int[] indexes = new int[top]; - Object[] values = new Object[top]; - int vIdx = 0; + ArrayList changes = m_tupleChanges; + if (changes == null) + return null; + + int top = changes.size(); + if (changes.size() == 0) + return null; + + top /= 2; + int[] indexes = new int[top]; + Object[] values = new Object[top]; + int vIdx = 0; for(int idx = 0; idx < top; ++idx) { - indexes[idx] = ((Integer)changes.get(vIdx++)).intValue(); - values[idx] = changes.get(vIdx++); - } - return new Object[] { m_tuple, indexes, values }; - } - - protected Object getObjectValue(int columnIndex) - throws SQLException - { - // Check if this value has been changed. - // - ArrayList changes = m_tupleChanges; + indexes[idx] = ((Integer) changes.get(vIdx++)).intValue(); + values[idx] = changes.get(vIdx++); + } + return new Object[] { m_tuple, indexes, values }; + } + + @Override + protected Object getObjectValue(int columnIndex) throws SQLException { + // Check if this value has been changed. + // + ArrayList changes = m_tupleChanges; if(changes != null) { - int top = changes.size(); - for(int idx = 0; idx < top; idx += 2) - if(columnIndex == ((Integer)changes.get(idx)).intValue()) - return changes.get(idx + 1); - } - return m_tuple.getObject(this.getTupleDesc(), columnIndex); - } - - protected final TupleDesc getTupleDesc() - { - return m_tupleDesc; - } + int top = changes.size(); + for (int idx = 0; idx < top; idx += 2) + if (columnIndex == ((Integer) changes.get(idx)).intValue()) + return changes.get(idx + 1); + } + return m_tuple.getObject(this.getTupleDesc(), columnIndex); + } + + @Override + protected final TupleDesc getTupleDesc() { + return m_tupleDesc; + } } Index: src/java/pljava/org/postgresql/pljava/jdbc/SPIConnection.java =================================================================== RCS file: /cvsroot/pljava/org.postgresql.pljava/src/java/pljava/org/postgresql/pljava/jdbc/SPIConnection.java,v retrieving revision 1.14 diff -u -r1.14 SPIConnection.java --- src/java/pljava/org/postgresql/pljava/jdbc/SPIConnection.java 18 Jun 2009 00:01:03 -0000 1.14 +++ src/java/pljava/org/postgresql/pljava/jdbc/SPIConnection.java 17 May 2010 19:50:49 -0000 @@ -10,18 +10,23 @@ import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URL; +import java.sql.Array; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.Clob; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.Date; +import java.sql.NClob; import java.sql.PreparedStatement; import java.sql.ResultSet; +import java.sql.SQLClientInfoException; import java.sql.SQLException; import java.sql.SQLWarning; +import java.sql.SQLXML; import java.sql.Savepoint; import java.sql.Statement; +import java.sql.Struct; import java.sql.Time; import java.sql.Timestamp; import java.sql.Types; @@ -29,6 +34,7 @@ import java.util.Calendar; import java.util.HashMap; import java.util.Map; +import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; @@ -41,8 +47,9 @@ */ public class SPIConnection implements Connection { - private static final HashMap s_sqlType2Class = new HashMap(30); - private int[] VERSION_NUMBER = null; //version number + private static final HashMap s_sqlType2Class = new HashMap( + 30); + private int[] VERSION_NUMBER = null; // version number static { @@ -198,7 +205,7 @@ /** * It is assumed that an inserts and updates can be performed using and - * SPIConnection. Changing that is not supported. + * SPIConnection. Changing that is not supported. * @throws SQLException indicating that this feature is not supported. */ public void setReadOnly(boolean readOnly) @@ -212,7 +219,7 @@ */ public String getCatalog() throws SQLException - { + { ResultSet rs = createStatement().executeQuery("SELECT pg_catalog.current_database()"); try { rs.next(); @@ -254,20 +261,20 @@ public void releaseSavepoint(Savepoint savepoint) throws SQLException { - if(!(savepoint instanceof PgSavepoint)) + if (!(savepoint instanceof PgSavepoint)) throw new IllegalArgumentException("Not a PL/Java Savepoint"); - PgSavepoint sp = (PgSavepoint)savepoint; + PgSavepoint sp = (PgSavepoint) savepoint; sp.release(); forgetSavepoint(sp); } public void rollback(Savepoint savepoint) throws SQLException { - if(!(savepoint instanceof PgSavepoint)) + if (!(savepoint instanceof PgSavepoint)) throw new IllegalArgumentException("Not a PL/Java Savepoint"); - PgSavepoint sp = (PgSavepoint)savepoint; + PgSavepoint sp = (PgSavepoint) savepoint; Invocation.clearErrorCondition(); sp.rollback(); forgetSavepoint(sp); @@ -279,7 +286,7 @@ public Statement createStatement() throws SQLException { - if(this.isClosed()) + if (this.isClosed()) throw new SQLException("Connection is closed"); return new SPIStatement(this); } @@ -295,12 +302,12 @@ public Statement createStatement( int resultSetType, int resultSetConcurrency) - throws SQLException + throws SQLException { - if(resultSetType != ResultSet.TYPE_FORWARD_ONLY) + if (resultSetType != ResultSet.TYPE_FORWARD_ONLY) throw new UnsupportedOperationException("TYPE_FORWARD_ONLY supported ResultSet type"); - if(resultSetConcurrency != ResultSet.CONCUR_READ_ONLY) + if (resultSetConcurrency != ResultSet.CONCUR_READ_ONLY) throw new UnsupportedOperationException("CONCUR_READ_ONLY is the supported ResultSet concurrency"); return this.createStatement(); } @@ -320,7 +327,7 @@ int resultSetHoldability) throws SQLException { - if(resultSetHoldability != ResultSet.CLOSE_CURSORS_AT_COMMIT) + if (resultSetHoldability != ResultSet.CLOSE_CURSORS_AT_COMMIT) throw new UnsupportedOperationException( "CLOSE_CURSORS_AT_COMMIT is the only supported ResultSet holdability"); return this.createStatement(resultSetType, resultSetConcurrency); @@ -353,24 +360,24 @@ { return this.nativeSQL(sql, null); } - + public String nativeSQL(String sql, int[] paramCountRet) { StringBuffer buf = new StringBuffer(); int len = sql.length(); char inQuote = 0; int paramIndex = 1; - for(int idx = 0; idx < len; ++idx) + for (int idx = 0; idx < len; ++idx) { char c = sql.charAt(idx); - switch(c) + switch (c) { case '\\': // Next character is escaped. Keep both // escape and the character. // buf.append(c); - if(++idx == len) + if (++idx == len) break; c = sql.charAt(idx); break; @@ -380,29 +387,29 @@ // Strings within quotes should not be subject // to '?' -> '$n' substitution. // - if(inQuote == c) + if (inQuote == c) inQuote = 0; else inQuote = c; break; - + case '?': - if(inQuote == 0) + if (inQuote == 0) { buf.append('$'); buf.append(paramIndex++); continue; } break; - + default: - if(inQuote == 0 && Character.isWhitespace(c)) + if (inQuote == 0 && Character.isWhitespace(c)) { // Strip of multiple whitespace outside of // strings. // ++idx; - while(idx < len && Character.isWhitespace(sql.charAt(idx))) + while (idx < len && Character.isWhitespace(sql.charAt(idx))) ++idx; --idx; c = ' '; @@ -410,7 +417,7 @@ } buf.append(c); } - if(paramCountRet != null) + if (paramCountRet != null) paramCountRet[0] = paramIndex - 1; return buf.toString(); } @@ -457,7 +464,7 @@ public PreparedStatement prepareStatement(String sql) throws SQLException { - if(this.isClosed()) + if (this.isClosed()) throw new SQLException("Connection is closed"); int[] pcount = new int[] { 0 }; @@ -472,7 +479,7 @@ * @throws SQLException indicating that this feature is not supported. */ public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) - throws SQLException + throws SQLException { throw new UnsupportedFeatureException("Auto generated key support not yet implemented"); } @@ -491,10 +498,10 @@ int resultSetConcurrency) throws SQLException { - if(resultSetType != ResultSet.TYPE_FORWARD_ONLY) + if (resultSetType != ResultSet.TYPE_FORWARD_ONLY) throw new UnsupportedOperationException("TYPE_FORWARD_ONLY supported ResultSet type"); - if(resultSetConcurrency != ResultSet.CONCUR_READ_ONLY) + if (resultSetConcurrency != ResultSet.CONCUR_READ_ONLY) throw new UnsupportedOperationException("CONCUR_READ_ONLY is the supported ResultSet concurrency"); return prepareStatement(sql); } @@ -515,9 +522,9 @@ int resultSetHoldability) throws SQLException { - if(resultSetHoldability != ResultSet.CLOSE_CURSORS_AT_COMMIT) + if (resultSetHoldability != ResultSet.CLOSE_CURSORS_AT_COMMIT) throw new UnsupportedOperationException( - "CLOSE_CURSORS_AT_COMMIT is the only supported ResultSet holdability"); + "CLOSE_CURSORS_AT_COMMIT is the only supported ResultSet holdability"); return this.prepareStatement(sql, resultSetType, resultSetConcurrency); } @@ -526,7 +533,7 @@ * @throws SQLException indicating that this feature is not supported. */ public PreparedStatement prepareStatement(String sql, int[] columnIndexes) - throws SQLException + throws SQLException { throw new UnsupportedFeatureException("Auto generated key support not yet implemented"); } @@ -536,7 +543,7 @@ * @throws SQLException indicating that this feature is not supported. */ public PreparedStatement prepareStatement(String sql, String[] columnNames) - throws SQLException + throws SQLException { throw new UnsupportedFeatureException("Auto generated key support not yet implemented"); } @@ -555,11 +562,11 @@ static int getTypeForClass(Class c) { - if(c.isArray() && !c.equals(byte[].class)) + if (c.isArray() && !c.equals(byte[].class)) return Types.ARRAY; - Integer sqt = (Integer)s_sqlType2Class.get(c); - if(sqt != null) + Integer sqt = (Integer) s_sqlType2Class.get(c); + if (sqt != null) return sqt.intValue(); /* @@ -577,7 +584,7 @@ // Invocation invocation = Invocation.current(); Savepoint old = invocation.getSavepoint(); - if(old == null) + if (old == null) invocation.setSavepoint(sp); return sp; } @@ -586,135 +593,135 @@ throws SQLException { Invocation invocation = Invocation.current(); - if(invocation.getSavepoint() == sp) + if (invocation.getSavepoint() == sp) invocation.setSavepoint(null); } - public int[] getVersionNumber() throws SQLException - { - if (VERSION_NUMBER != null) - return VERSION_NUMBER; + public int[] getVersionNumber() throws SQLException + { + if (VERSION_NUMBER != null) + return VERSION_NUMBER; ResultSet rs = createStatement().executeQuery( "SELECT version()"); - try - { - if (!rs.next()) + try + { + if (!rs.next()) throw new SQLException( "Cannot retrieve product version number"); - String ver = rs.getString(1); + String ver = rs.getString(1); Pattern p = Pattern.compile( "^PostgreSQL\\s+(\\d+)\\.(\\d+)(.\\d+)?.*"); - Matcher m = p.matcher(ver); - if(m.matches()) - { - VERSION_NUMBER = new int[3]; - VERSION_NUMBER[0] = Integer.parseInt(m.group(1)); - VERSION_NUMBER[1] = Integer.parseInt(m.group(2)); - String bugfix = m.group(3); - if(bugfix != null && bugfix.length() > 1) - VERSION_NUMBER[2] = Integer.parseInt(bugfix.substring(1)); - return VERSION_NUMBER; - } + Matcher m = p.matcher(ver); + if (m.matches()) + { + VERSION_NUMBER = new int[3]; + VERSION_NUMBER[0] = Integer.parseInt(m.group(1)); + VERSION_NUMBER[1] = Integer.parseInt(m.group(2)); + String bugfix = m.group(3); + if (bugfix != null && bugfix.length() > 1) + VERSION_NUMBER[2] = Integer.parseInt(bugfix.substring(1)); + return VERSION_NUMBER; + } throw new SQLException( "Unexpected product version string format: " + ver); } catch (PatternSyntaxException e) - { + { throw new SQLException( "Error in product version string parsing: " + e.getMessage()); } finally - { - rs.close(); - } - } + { + rs.close(); + } + } - /* - * This implemetation uses the jdbc3Types array to support the jdbc3 + /* + * This implemetation uses the jdbc3Types array to support the jdbc3 * datatypes. Basically jdbc2 and jdbc3 are the same, except that * jdbc3 adds some - */ - public int getSQLType(String pgTypeName) - { - if (pgTypeName == null) - return Types.OTHER; - - for (int i = 0;i < JDBC3_TYPE_NAMES.length;i++) - if (pgTypeName.equals(JDBC3_TYPE_NAMES[i])) - return JDBC_TYPE_NUMBERS[i]; - - return Types.OTHER; - } - - /* - * This returns the java.sql.Types type for a PG type oid - * - * @param oid PostgreSQL type oid - * @return the java.sql.Types type - * @exception SQLException if a database access error occurs - */ - public int getSQLType(Oid oid) throws SQLException - { - return getSQLType(getPGType(oid)); - } - - public String getPGType(Oid oid) throws SQLException - { - String typeName = null; - PreparedStatement query = null; - ResultSet rs = null; - - try - { - query = prepareStatement("SELECT typname FROM pg_catalog.pg_type WHERE oid=?"); - query.setObject(1, oid); - rs = query.executeQuery(); - - if (rs.next()) - { - typeName = rs.getString(1); + */ + public int getSQLType(String pgTypeName) + { + if (pgTypeName == null) + return Types.OTHER; + + for (int i = 0; i < JDBC3_TYPE_NAMES.length; i++) + if (pgTypeName.equals(JDBC3_TYPE_NAMES[i])) + return JDBC_TYPE_NUMBERS[i]; + + return Types.OTHER; + } + + /* + * This returns the java.sql.Types type for a PG type oid + * + * @param oid PostgreSQL type oid + * @return the java.sql.Types type + * @exception SQLException if a database access error occurs + */ + public int getSQLType(Oid oid) throws SQLException + { + return getSQLType(getPGType(oid)); + } + + public String getPGType(Oid oid) throws SQLException + { + String typeName = null; + PreparedStatement query = null; + ResultSet rs = null; + + try + { + query = prepareStatement("SELECT typname FROM pg_catalog.pg_type WHERE oid=?"); + query.setObject(1, oid); + rs = query.executeQuery(); + + if (rs.next()) + { + typeName = rs.getString(1); } else - { - throw new SQLException("Cannot find PG type with oid=" + oid); - } + { + throw new SQLException("Cannot find PG type with oid=" + oid); + } } finally - { - if (query != null) - { - query.close(); - } - } + { + if (query != null) + { + query.close(); + } + } - return typeName; - } + return typeName; + } static Object basicCoersion(Class cls, Object value) throws SQLException { - if(value == null || cls.isInstance(value)) + if (value == null || cls.isInstance(value)) return value; - if(cls == String.class) + if (cls == String.class) { if(value instanceof Number || value instanceof Boolean || value instanceof Timestamp || value instanceof Date - || value instanceof Time) + || value instanceof Time) return value.toString(); } else if(cls == URL.class && value instanceof String) { try { - return new URL((String)value); + return new URL((String) value); } catch(MalformedURLException e) { @@ -728,50 +735,50 @@ static Number basicNumericCoersion(Class cls, Object value) throws SQLException { - if(value == null || value instanceof Number) - return (Number)value; + if (value == null || value instanceof Number) + return (Number) value; if(cls == int.class || cls == long.class || cls == short.class || cls == byte.class) { - if(value instanceof String) - return Long.valueOf((String)value); + if (value instanceof String) + return Long.valueOf((String) value); - if(value instanceof Boolean) - return new Long(((Boolean)value).booleanValue() ? 1 : 0); + if (value instanceof Boolean) + return new Long(((Boolean) value).booleanValue() ? 1 : 0); } else if(cls == BigDecimal.class) { - if(value instanceof String) - return new BigDecimal((String)value); + if (value instanceof String) + return new BigDecimal((String) value); - if(value instanceof Boolean) - return new BigDecimal(((Boolean)value).booleanValue() ? 1 : 0); + if (value instanceof Boolean) + return new BigDecimal(((Boolean) value).booleanValue() ? 1 : 0); } - if(cls == double.class || cls == float.class) + if (cls == double.class || cls == float.class) { - if(value instanceof String) - return Double.valueOf((String)value); + if (value instanceof String) + return Double.valueOf((String) value); - if(value instanceof Boolean) - return new Double(((Boolean)value).booleanValue() ? 1 : 0); + if (value instanceof Boolean) + return new Double(((Boolean) value).booleanValue() ? 1 : 0); } throw new SQLException("Cannot derive a Number from an object of class " + value.getClass().getName()); } static Object basicCalendricalCoersion(Class cls, Object value, Calendar cal) - throws SQLException + throws SQLException { - if(value == null) + if (value == null) return value; - if(cls.isInstance(value)) + if (cls.isInstance(value)) return value; - if(cls == Timestamp.class) + if (cls == Timestamp.class) { - if(value instanceof Date) + if (value instanceof Date) { - cal.setTime((Date)value); + cal.setTime((Date) value); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); @@ -780,20 +787,20 @@ } else if(value instanceof Time) { - cal.setTime((Date)value); + cal.setTime((Date) value); cal.set(1970, 0, 1); return new Timestamp(cal.getTimeInMillis()); } else if(value instanceof String) { - return Timestamp.valueOf((String)value); + return Timestamp.valueOf((String) value); } } else if(cls == Date.class) { - if(value instanceof Timestamp) + if (value instanceof Timestamp) { - Timestamp ts = (Timestamp)value; + Timestamp ts = (Timestamp) value; cal.setTime(ts); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); @@ -803,36 +810,36 @@ } else if(value instanceof String) { - return Date.valueOf((String)value); + return Date.valueOf((String) value); } } else if(cls == Time.class) { - if(value instanceof Timestamp) + if (value instanceof Timestamp) { - Timestamp ts = (Timestamp)value; + Timestamp ts = (Timestamp) value; cal.setTime(ts); cal.set(1970, 0, 1); return new Time(cal.getTimeInMillis()); } else if(value instanceof String) { - return Time.valueOf((String)value); + return Time.valueOf((String) value); } } throw new SQLException("Cannot derive a value of class " + cls.getName() + " from an object of class " + value.getClass().getName()); } - /* - * This table holds the org.postgresql names for the types supported. + /* + * This table holds the org.postgresql names for the types supported. * Any types that map to Types.OTHER (eg POINT) don't go into this table. * They default automatically to Types.OTHER - * - * Note: This must be in the same order as below. - * - * Tip: keep these grouped together by the Types. value - */ + * + * Note: This must be in the same order as below. + * + * Tip: keep these grouped together by the Types. value + */ public static final String JDBC3_TYPE_NAMES[] = { "int2", "int4", "oid", @@ -855,13 +862,13 @@ "_bytea" }; - /* - * This table holds the JDBC type for each entry above. - * - * Note: This must be in the same order as above - * - * Tip: keep these grouped together by the Types. value - */ + /* + * This table holds the JDBC type for each entry above. + * + * Note: This must be in the same order as above + * + * Tip: keep these grouped together by the Types. value + */ public static final int JDBC_TYPE_NUMBERS[] = { Types.SMALLINT, @@ -884,4 +891,86 @@ Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY }; - } + + + public Array createArrayOf(String typeName, Object[] elements) + throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public Blob createBlob() throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public Clob createClob() throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public NClob createNClob() throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public SQLXML createSQLXML() throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public Struct createStruct(String typeName, Object[] attributes) + throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public Properties getClientInfo() throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public String getClientInfo(String name) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public boolean isValid(int timeout) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void setClientInfo(Properties properties) throws SQLClientInfoException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public void setClientInfo(String name, String value) + throws SQLClientInfoException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public boolean isWrapperFor(Class iface) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public T unwrap(Class iface) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } +} Index: src/java/pljava/org/postgresql/pljava/jdbc/ObjectResultSet.java =================================================================== RCS file: /cvsroot/pljava/org.postgresql.pljava/src/java/pljava/org/postgresql/pljava/jdbc/ObjectResultSet.java,v retrieving revision 1.5 diff -u -r1.5 ObjectResultSet.java --- src/java/pljava/org/postgresql/pljava/jdbc/ObjectResultSet.java 11 Feb 2006 13:57:50 -0000 1.5 +++ src/java/pljava/org/postgresql/pljava/jdbc/ObjectResultSet.java 17 May 2010 19:50:49 -0000 @@ -6,6 +6,12 @@ */ package org.postgresql.pljava.jdbc; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.UnsupportedEncodingException; +import java.math.BigDecimal; +import java.net.URL; import java.sql.Array; import java.sql.Blob; import java.sql.Clob; @@ -16,17 +22,9 @@ import java.sql.SQLWarning; import java.sql.Time; import java.sql.Timestamp; -import java.math.BigDecimal; -import java.net.URL; import java.util.Calendar; import java.util.Map; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.UnsupportedEncodingException; - - /** * @author Thomas Hallgren */ @@ -34,7 +32,6 @@ { private boolean m_wasNull = false; - /** * This is a noop since warnings are not supported. */ @@ -46,7 +43,7 @@ public Array getArray(int columnIndex) throws SQLException { - return (Array)this.getValue(columnIndex, Array.class); + return (Array) this.getValue(columnIndex, Array.class); } public InputStream getAsciiStream(int columnIndex) @@ -59,14 +56,14 @@ public BigDecimal getBigDecimal(int columnIndex) throws SQLException { - return (BigDecimal)this.getValue(columnIndex, BigDecimal.class); + return (BigDecimal) this.getValue(columnIndex, BigDecimal.class); } /** * @deprecated */ - public BigDecimal getBigDecimal(int columnIndex, int scale) - throws SQLException + @Deprecated + public BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException { throw new UnsupportedFeatureException("getBigDecimal(int, int)"); } @@ -83,13 +80,13 @@ throws SQLException { byte[] bytes = this.getBytes(columnIndex); - return (bytes == null) ? null : new BlobValue(bytes); + return (bytes == null) ? null : new BlobValue(bytes); } public boolean getBoolean(int columnIndex) throws SQLException { - Boolean b = (Boolean)this.getValue(columnIndex, Boolean.class); + Boolean b = (Boolean) this.getValue(columnIndex, Boolean.class); return (b == null) ? false : b.booleanValue(); } @@ -103,7 +100,7 @@ public byte[] getBytes(int columnIndex) throws SQLException { - return (byte[])this.getValue(columnIndex, byte[].class); + return (byte[]) this.getValue(columnIndex, byte[].class); } public Reader getCharacterStream(int columnIndex) @@ -117,19 +114,19 @@ throws SQLException { String str = this.getString(columnIndex); - return (str == null) ? null : new ClobValue(str); + return (str == null) ? null : new ClobValue(str); } - + public Date getDate(int columnIndex) throws SQLException { - return (Date)this.getValue(columnIndex, Date.class); + return (Date) this.getValue(columnIndex, Date.class); } public Date getDate(int columnIndex, Calendar cal) throws SQLException { - return (Date)this.getValue(columnIndex, Date.class, cal); + return (Date) this.getValue(columnIndex, Date.class, cal); } public double getDouble(int columnIndex) @@ -189,7 +186,7 @@ public Ref getRef(int columnIndex) throws SQLException { - return (Ref)this.getValue(columnIndex, Ref.class); + return (Ref) this.getValue(columnIndex, Ref.class); } public short getShort(int columnIndex) @@ -202,31 +199,31 @@ public String getString(int columnIndex) throws SQLException { - return (String)this.getValue(columnIndex, String.class); + return (String) this.getValue(columnIndex, String.class); } public Time getTime(int columnIndex) throws SQLException { - return (Time)this.getValue(columnIndex, Time.class); + return (Time) this.getValue(columnIndex, Time.class); } public Time getTime(int columnIndex, Calendar cal) throws SQLException { - return (Time)this.getValue(columnIndex, Time.class, cal); + return (Time) this.getValue(columnIndex, Time.class, cal); } public Timestamp getTimestamp(int columnIndex) throws SQLException { - return (Timestamp)this.getValue(columnIndex, Timestamp.class); + return (Timestamp) this.getValue(columnIndex, Timestamp.class); } public Timestamp getTimestamp(int columnIndex, Calendar cal) throws SQLException { - return (Timestamp)this.getValue(columnIndex, Timestamp.class, cal); + return (Timestamp) this.getValue(columnIndex, Timestamp.class, cal); } /** @@ -240,7 +237,7 @@ public URL getURL(int columnIndex) throws SQLException { - return (URL)this.getValue(columnIndex, URL.class); + return (URL) this.getValue(columnIndex, URL.class); } public SQLWarning getWarnings() @@ -265,7 +262,7 @@ } public void updateAsciiStream(int columnIndex, InputStream x, int length) - throws SQLException + throws SQLException { try { @@ -285,9 +282,9 @@ } public void updateBinaryStream(int columnIndex, InputStream x, int length) - throws SQLException + throws SQLException { - this.updateBlob(columnIndex, new BlobValue(x, length)); + this.updateBlob(columnIndex, (Blob) new BlobValue(x, length)); } public void updateBlob(int columnIndex, Blob x) @@ -315,9 +312,9 @@ } public void updateCharacterStream(int columnIndex, Reader x, int length) - throws SQLException + throws SQLException { - this.updateClob(columnIndex, new ClobValue(x, length)); + this.updateClob(columnIndex, (Clob) new ClobValue(x, length)); } public void updateClob(int columnIndex, Clob x) @@ -412,15 +409,15 @@ } protected Object getValue(int columnIndex, Class cls, Calendar cal) - throws SQLException + throws SQLException { return SPIConnection.basicCalendricalCoersion(cls, this.getObject(columnIndex), cal); } protected Object getObjectValue(int columnIndex, Map typeMap) - throws SQLException + throws SQLException { - if(typeMap == null) + if (typeMap == null) return this.getObjectValue(columnIndex); throw new UnsupportedFeatureException("Obtaining values using explicit Map"); } Index: src/java/pljava/org/postgresql/pljava/jdbc/SQLInputFromChunk.java =================================================================== RCS file: /cvsroot/pljava/org.postgresql.pljava/src/java/pljava/org/postgresql/pljava/jdbc/SQLInputFromChunk.java,v retrieving revision 1.2 diff -u -r1.2 SQLInputFromChunk.java --- src/java/pljava/org/postgresql/pljava/jdbc/SQLInputFromChunk.java 28 Feb 2006 08:16:57 -0000 1.2 +++ src/java/pljava/org/postgresql/pljava/jdbc/SQLInputFromChunk.java 17 May 2010 19:50:50 -0000 @@ -18,9 +18,12 @@ import java.sql.Blob; import java.sql.Clob; import java.sql.Date; +import java.sql.NClob; import java.sql.Ref; +import java.sql.RowId; import java.sql.SQLException; import java.sql.SQLInput; +import java.sql.SQLXML; import java.sql.Time; import java.sql.Timestamp; @@ -39,133 +42,133 @@ */ public class SQLInputFromChunk implements SQLInput { - private static final byte[] s_byteBuffer = new byte[8]; + private static final byte[] s_byteBuffer = new byte[8]; - private final int m_chunkSize; + private final int m_chunkSize; - private int m_position; + private int m_position; - private long m_handle; + private long m_handle; public SQLInputFromChunk(long handle, int chunkSize) { - m_handle = handle; - m_chunkSize = chunkSize; - m_position = 0; - } + m_handle = handle; + m_chunkSize = chunkSize; + m_position = 0; + } public Array readArray() throws SQLException { - throw new UnsupportedOperationException("readArray"); - } + throw new UnsupportedOperationException("readArray"); + } public InputStream readAsciiStream() throws SQLException { - throw new UnsupportedOperationException("readAsciiStream"); - } + throw new UnsupportedOperationException("readAsciiStream"); + } public BigDecimal readBigDecimal() throws SQLException { - return new BigDecimal(this.readString()); - } + return new BigDecimal(this.readString()); + } public InputStream readBinaryStream() throws SQLException { - return new ByteArrayInputStream(this.readBytes()); - } + return new ByteArrayInputStream(this.readBytes()); + } public Blob readBlob() throws SQLException { - throw new UnsupportedOperationException("readBlob"); - } + throw new UnsupportedOperationException("readBlob"); + } public boolean readBoolean() throws SQLException { - int c = this.read(); - if(c < 0) - throw new SQLException("Unexpected EOF on data input"); - return c != 0; - } + int c = this.read(); + if (c < 0) + throw new SQLException("Unexpected EOF on data input"); + return c != 0; + } public byte readByte() throws SQLException { - int c = this.read(); - if(c < 0) - throw new SQLException("Unexpected EOF on data input"); - return (byte)c; - } + int c = this.read(); + if (c < 0) + throw new SQLException("Unexpected EOF on data input"); + return (byte) c; + } public byte[] readBytes() throws SQLException { synchronized(Backend.THREADLOCK) { - if(m_handle == 0) - throw new SQLException("Stream is closed"); + if (m_handle == 0) + throw new SQLException("Stream is closed"); - if(m_chunkSize - m_position < 2) - throw new SQLException("Unexpected EOF on data input"); - _readBytes(m_handle, m_position, s_byteBuffer, 2); - m_position += 2; + if (m_chunkSize - m_position < 2) + throw new SQLException("Unexpected EOF on data input"); + _readBytes(m_handle, m_position, s_byteBuffer, 2); + m_position += 2; - int len = ((s_byteBuffer[0] & 0xff) << 8) | (s_byteBuffer[1] & 0xff); - byte[] buffer = new byte[len]; + int len = ((s_byteBuffer[0] & 0xff) << 8) | (s_byteBuffer[1] & 0xff); + byte[] buffer = new byte[len]; if(len > 0) { - _readBytes(m_handle, m_position, buffer, len); - m_position += len; - } - return buffer; - } - } + _readBytes(m_handle, m_position, buffer, len); + m_position += len; + } + return buffer; + } + } public Reader readCharacterStream() throws SQLException { - return new StringReader(this.readString()); - } + return new StringReader(this.readString()); + } public Clob readClob() throws SQLException { - throw new UnsupportedOperationException("readClob"); - } + throw new UnsupportedOperationException("readClob"); + } public Date readDate() throws SQLException { - return new Date(this.readLong()); - } + return new Date(this.readLong()); + } public double readDouble() throws SQLException { - return Double.longBitsToDouble(this.readLong()); - } + return Double.longBitsToDouble(this.readLong()); + } public float readFloat() throws SQLException { - return Float.intBitsToFloat(readInt()); - } + return Float.intBitsToFloat(readInt()); + } public int readInt() throws SQLException { synchronized(Backend.THREADLOCK) { - if(m_chunkSize - m_position < 4) - throw new SQLException("Unexpected EOF on data input"); - _readBytes(m_handle, m_position, s_byteBuffer, 4); - m_position += 4; + if (m_chunkSize - m_position < 4) + throw new SQLException("Unexpected EOF on data input"); + _readBytes(m_handle, m_position, s_byteBuffer, 4); + m_position += 4; return ((s_byteBuffer[0] & 0xff) << 24) | ((s_byteBuffer[1] & 0xff) << 16) | ((s_byteBuffer[2] & 0xff) << 8) | (s_byteBuffer[3] & 0xff); - } - } + } + } public long readLong() throws SQLException { synchronized(Backend.THREADLOCK) { - if(m_chunkSize - m_position < 8) - throw new SQLException("Unexpected EOF on data input"); - _readBytes(m_handle, m_position, s_byteBuffer, 8); - m_position += 8; + if (m_chunkSize - m_position < 8) + throw new SQLException("Unexpected EOF on data input"); + _readBytes(m_handle, m_position, s_byteBuffer, 8); + m_position += 8; return ((long)(s_byteBuffer[0] & 0xff) << 56) | ((long)(s_byteBuffer[1] & 0xff) << 48) | ((long)(s_byteBuffer[2] & 0xff) << 40) | @@ -174,74 +177,74 @@ ((s_byteBuffer[5] & 0xff) << 16) | ((s_byteBuffer[6] & 0xff) << 8) | (s_byteBuffer[7] & 0xff); - } - } + } + } public Object readObject() throws SQLException { - throw new UnsupportedOperationException("readObject"); - } + throw new UnsupportedOperationException("readObject"); + } public Ref readRef() throws SQLException { - throw new UnsupportedOperationException("readRef"); - } + throw new UnsupportedOperationException("readRef"); + } public short readShort() throws SQLException { synchronized(Backend.THREADLOCK) { - if(m_chunkSize - m_position < 2) - throw new SQLException("Unexpected EOF on data input"); - _readBytes(m_handle, m_position, s_byteBuffer, 2); - m_position += 2; - return (short)(((s_byteBuffer[0] & 0xff) << 8) | (s_byteBuffer[1] & 0xff)); - } - } + if (m_chunkSize - m_position < 2) + throw new SQLException("Unexpected EOF on data input"); + _readBytes(m_handle, m_position, s_byteBuffer, 2); + m_position += 2; + return (short) (((s_byteBuffer[0] & 0xff) << 8) | (s_byteBuffer[1] & 0xff)); + } + } public String readString() throws SQLException { try { - return new String(this.readBytes(), "UTF8"); + return new String(this.readBytes(), "UTF8"); } catch(UnsupportedEncodingException e) { - throw new SQLException("UTF8 encoding not supported by JVM"); - } - } + throw new SQLException("UTF8 encoding not supported by JVM"); + } + } public Time readTime() throws SQLException { - return new Time(this.readLong()); - } + return new Time(this.readLong()); + } public Timestamp readTimestamp() throws SQLException { - return new Timestamp(this.readLong()); - } + return new Timestamp(this.readLong()); + } public URL readURL() throws SQLException { try { - return new URL(this.readString()); + return new URL(this.readString()); } catch(MalformedURLException e) { - throw new SQLException(e.getMessage()); - } - } + throw new SQLException(e.getMessage()); + } + } public boolean wasNull() throws SQLException { - return false; - } + return false; + } void close() { - m_handle = 0; - } + m_handle = 0; + } private int read() throws SQLException { @@ -249,15 +252,31 @@ { synchronized(Backend.THREADLOCK) { - if(m_handle == 0) - throw new SQLException("Stream is closed"); - return _readByte(m_handle, m_position++); - } - } - return -1; - } - - private static native int _readByte(long handle, int position); - - private static native void _readBytes(long handle, int position, byte[] dest, int len); + if (m_handle == 0) + throw new SQLException("Stream is closed"); + return _readByte(m_handle, m_position++); + } + } + return -1; + } + + private static native int _readByte(long handle, int position); + + private static native void _readBytes(long handle, int position, byte[] dest, int len); + + public NClob readNClob() throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } + + public String readNString() throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } + + public RowId readRowId() throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } + + public SQLXML readSQLXML() throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } } Index: src/java/pljava/org/postgresql/pljava/jdbc/SPIPreparedStatement.java =================================================================== RCS file: /cvsroot/pljava/org.postgresql.pljava/src/java/pljava/org/postgresql/pljava/jdbc/SPIPreparedStatement.java,v retrieving revision 1.10 diff -u -r1.10 SPIPreparedStatement.java --- src/java/pljava/org/postgresql/pljava/jdbc/SPIPreparedStatement.java 16 Nov 2007 07:49:37 -0000 1.10 +++ src/java/pljava/org/postgresql/pljava/jdbc/SPIPreparedStatement.java 17 May 2010 19:50:50 -0000 @@ -16,12 +16,15 @@ import java.sql.Blob; import java.sql.Clob; import java.sql.Date; +import java.sql.NClob; import java.sql.ParameterMetaData; import java.sql.PreparedStatement; import java.sql.Ref; import java.sql.ResultSet; import java.sql.ResultSetMetaData; +import java.sql.RowId; import java.sql.SQLException; +import java.sql.SQLXML; import java.sql.Time; import java.sql.Timestamp; import java.sql.Types; @@ -32,124 +35,124 @@ import org.postgresql.pljava.internal.Oid; /** - * + * * @author Thomas Hallgren */ public class SPIPreparedStatement extends SPIStatement implements PreparedStatement { - private final Oid[] m_typeIds; - private final Object[] m_values; - private final int[] m_sqlTypes; - private final String m_statement; - private ExecutionPlan m_plan; + private final Oid[] m_typeIds; + private final Object[] m_values; + private final int[] m_sqlTypes; + private final String m_statement; + private ExecutionPlan m_plan; public SPIPreparedStatement(SPIConnection conn, String statement, int paramCount) { - super(conn); - m_statement = statement; - m_typeIds = new Oid[paramCount]; - m_values = new Object[paramCount]; - m_sqlTypes = new int[paramCount]; - Arrays.fill(m_sqlTypes, Types.NULL); - } + super(conn); + m_statement = statement; + m_typeIds = new Oid[paramCount]; + m_values = new Object[paramCount]; + m_sqlTypes = new int[paramCount]; + Arrays.fill(m_sqlTypes, Types.NULL); + } public void close() throws SQLException { if(m_plan != null) { - m_plan.close(); - m_plan = null; - } - this.clearParameters(); - super.close(); - Invocation.current().forgetStatement(this); - } + m_plan.close(); + m_plan = null; + } + this.clearParameters(); + super.close(); + Invocation.current().forgetStatement(this); + } public ResultSet executeQuery() throws SQLException { - this.execute(); - return this.getResultSet(); - } + this.execute(); + return this.getResultSet(); + } public int executeUpdate() throws SQLException { - this.execute(); - return this.getUpdateCount(); - } + this.execute(); + return this.getUpdateCount(); + } public void setNull(int columnIndex, int sqlType) throws SQLException { - this.setObject(columnIndex, null, sqlType); - } + this.setObject(columnIndex, null, sqlType); + } public void setBoolean(int columnIndex, boolean value) throws SQLException { - this.setObject(columnIndex, value ? Boolean.TRUE : Boolean.FALSE, Types.BOOLEAN); - } + this.setObject(columnIndex, value ? Boolean.TRUE : Boolean.FALSE, Types.BOOLEAN); + } public void setByte(int columnIndex, byte value) throws SQLException { - this.setObject(columnIndex, new Byte(value), Types.TINYINT); - } + this.setObject(columnIndex, new Byte(value), Types.TINYINT); + } public void setShort(int columnIndex, short value) throws SQLException { - this.setObject(columnIndex, new Short(value), Types.SMALLINT); - } + this.setObject(columnIndex, new Short(value), Types.SMALLINT); + } public void setInt(int columnIndex, int value) throws SQLException { - this.setObject(columnIndex, new Integer(value), Types.INTEGER); - } + this.setObject(columnIndex, new Integer(value), Types.INTEGER); + } public void setLong(int columnIndex, long value) throws SQLException { - this.setObject(columnIndex, new Long(value), Types.BIGINT); - } + this.setObject(columnIndex, new Long(value), Types.BIGINT); + } public void setFloat(int columnIndex, float value) throws SQLException { - this.setObject(columnIndex, new Float(value), Types.FLOAT); - } + this.setObject(columnIndex, new Float(value), Types.FLOAT); + } public void setDouble(int columnIndex, double value) throws SQLException { - this.setObject(columnIndex, new Double(value), Types.DOUBLE); - } + this.setObject(columnIndex, new Double(value), Types.DOUBLE); + } public void setBigDecimal(int columnIndex, BigDecimal value) throws SQLException { - this.setObject(columnIndex, value, Types.DECIMAL); - } + this.setObject(columnIndex, value, Types.DECIMAL); + } public void setString(int columnIndex, String value) throws SQLException { - this.setObject(columnIndex, value, Types.VARCHAR); - } + this.setObject(columnIndex, value, Types.VARCHAR); + } public void setBytes(int columnIndex, byte[] value) throws SQLException { - this.setObject(columnIndex, value, Types.VARBINARY); - } + this.setObject(columnIndex, value, Types.VARBINARY); + } public void setDate(int columnIndex, Date value) throws SQLException { - this.setObject(columnIndex, value, Types.DATE); - } + this.setObject(columnIndex, value, Types.DATE); + } public void setTime(int columnIndex, Time value) throws SQLException { - this.setObject(columnIndex, value, Types.TIME); - } + this.setObject(columnIndex, value, Types.TIME); + } public void setTimestamp(int columnIndex, Timestamp value) throws SQLException { - this.setObject(columnIndex, value, Types.TIMESTAMP); - } + this.setObject(columnIndex, value, Types.TIMESTAMP); + } public void setAsciiStream(int columnIndex, InputStream value, int length) throws SQLException { @@ -161,265 +164,335 @@ } catch(UnsupportedEncodingException e) { - throw new SQLException("US-ASCII encoding is not supported by this JVM"); - } - } - - /** - * @deprecated - */ - public void setUnicodeStream(int columnIndex, InputStream value, int arg2) throws SQLException - { - throw new UnsupportedFeatureException("PreparedStatement.setUnicodeStream"); - } + throw new SQLException("US-ASCII encoding is not supported by this JVM"); + } + } + + /** + * @deprecated + */ + @Deprecated + public void setUnicodeStream(int columnIndex, InputStream value, int arg2) throws SQLException { + throw new UnsupportedFeatureException("PreparedStatement.setUnicodeStream"); + } public void setBinaryStream(int columnIndex, InputStream value, int length) throws SQLException { - this.setObject(columnIndex, new BlobValue(value, length), Types.BLOB); - } + this.setObject(columnIndex, new BlobValue(value, length), Types.BLOB); + } public void clearParameters() throws SQLException { - Arrays.fill(m_values, null); - Arrays.fill(m_sqlTypes, Types.NULL); - } + Arrays.fill(m_values, null); + Arrays.fill(m_sqlTypes, Types.NULL); + } public void setObject(int columnIndex, Object value, int sqlType, int scale) throws SQLException { - this.setObject(columnIndex, value, sqlType); - } + this.setObject(columnIndex, value, sqlType); + } public void setObject(int columnIndex, Object value, int sqlType) throws SQLException { - if(columnIndex < 1 || columnIndex > m_sqlTypes.length) - throw new SQLException("Illegal parameter index"); + if (columnIndex < 1 || columnIndex > m_sqlTypes.length) + throw new SQLException("Illegal parameter index"); Oid id = (sqlType == Types.OTHER) ? Oid.forJavaClass(value.getClass()) : Oid.forSqlType(sqlType); - // Default to String. - // - if(id == null) - id = Oid.forSqlType(Types.VARCHAR); - - Oid op = m_typeIds[--columnIndex]; - if(op == null) - m_typeIds[columnIndex] = id; + // Default to String. + // + if (id == null) + id = Oid.forSqlType(Types.VARCHAR); + + Oid op = m_typeIds[--columnIndex]; + if (op == null) + m_typeIds[columnIndex] = id; else if(!op.equals(id)) { - m_typeIds[columnIndex] = id; - - // We must re-prepare - // - if(m_plan != null) - m_plan.close(); - m_plan = null; - } - m_sqlTypes[columnIndex] = sqlType; - m_values[columnIndex] = value; - } + m_typeIds[columnIndex] = id; + + // We must re-prepare + // + if (m_plan != null) + m_plan.close(); + m_plan = null; + } + m_sqlTypes[columnIndex] = sqlType; + m_values[columnIndex] = value; + } public void setObject(int columnIndex, Object value) throws SQLException { - if(value == null) - throw new SQLException("Can't assign null unless the SQL type is known"); + if (value == null) + throw new SQLException("Can't assign null unless the SQL type is known"); - this.setObject(columnIndex, value, SPIConnection.getTypeForClass(value.getClass())); - } + this.setObject(columnIndex, value, SPIConnection.getTypeForClass(value.getClass())); + } - /** - * Obtains the XOPEN SQL types for the parameters. - * @return The array of types. - */ + /** + * Obtains the XOPEN SQL types for the parameters. + * @return The array of types. + */ private int[] getSqlTypes() { - int idx = m_sqlTypes.length; - int[] types = (int[])m_sqlTypes.clone(); + int idx = m_sqlTypes.length; + int[] types = (int[]) m_sqlTypes.clone(); while(--idx >= 0) { - if(types[idx] == Types.NULL) - types[idx] = Types.VARCHAR; // Default. - } - return types; - } + if (types[idx] == Types.NULL) + types[idx] = Types.VARCHAR; // Default. + } + return types; + } public boolean execute() throws SQLException { - int[] sqlTypes = m_sqlTypes; - int idx = sqlTypes.length; - while(--idx >= 0) - if(sqlTypes[idx] == Types.NULL) - throw new SQLException("Not all parameters have been set"); - - if(m_plan == null) - m_plan = ExecutionPlan.prepare(m_statement, m_typeIds); + int[] sqlTypes = m_sqlTypes; + int idx = sqlTypes.length; + while (--idx >= 0) + if (sqlTypes[idx] == Types.NULL) + throw new SQLException("Not all parameters have been set"); + + if (m_plan == null) + m_plan = ExecutionPlan.prepare(m_statement, m_typeIds); + + boolean result = this.executePlan(m_plan, m_values); + this.clearParameters(); // Parameters are cleared upon successful completion. + return result; + } - boolean result = this.executePlan(m_plan, m_values); - this.clearParameters(); // Parameters are cleared upon successful completion. - return result; - } - - /** - * The prepared statement cannot be used for executing oter statements. + /** + * The prepared statement cannot be used for executing oter statements. * @throws SQLException indicating that this feature is not supported. - */ - public boolean execute(String statement) - throws SQLException - { - throw new UnsupportedFeatureException("Can't execute other statements using a prepared statement"); - } + */ + @Override + public boolean execute(String statement) throws SQLException { + throw new UnsupportedFeatureException("Can't execute other statements using a prepared statement"); + } public void addBatch() throws SQLException { - this.internalAddBatch(new Object[]{m_values.clone(), m_sqlTypes.clone(), m_typeIds.clone()}); - this.clearParameters(); // Parameters are cleared upon successful completion. - } + this.internalAddBatch(new Object[] { m_values.clone(), m_sqlTypes.clone(), m_typeIds.clone() }); + this.clearParameters(); // Parameters are cleared upon successful completion. + } - /** - * The prepared statement cannot have other statements added too it. + /** + * The prepared statement cannot have other statements added too it. * @throws SQLException indicating that this feature is not supported. - */ - public void addBatch(String statement) - throws SQLException - { - throw new UnsupportedFeatureException("Can't add batch statements to a prepared statement"); - } + */ + @Override + public void addBatch(String statement) throws SQLException { + throw new UnsupportedFeatureException("Can't add batch statements to a prepared statement"); + } public void setCharacterStream(int columnIndex, Reader value, int length) throws SQLException { - this.setObject(columnIndex, new ClobValue(value, length), Types.CLOB); - } + this.setObject(columnIndex, new ClobValue(value, length), Types.CLOB); + } public void setRef(int columnIndex, Ref value) throws SQLException { - this.setObject(columnIndex, value, Types.REF); - } + this.setObject(columnIndex, value, Types.REF); + } public void setBlob(int columnIndex, Blob value) throws SQLException { - this.setObject(columnIndex, value, Types.BLOB); - } + this.setObject(columnIndex, value, Types.BLOB); + } public void setClob(int columnIndex, Clob value) throws SQLException { - this.setObject(columnIndex, value, Types.CLOB); - } + this.setObject(columnIndex, value, Types.CLOB); + } public void setArray(int columnIndex, Array value) throws SQLException { - this.setObject(columnIndex, value, Types.ARRAY); - } + this.setObject(columnIndex, value, Types.ARRAY); + } - /** - * ResultSetMetaData is not yet supported. + /** + * ResultSetMetaData is not yet supported. * @throws SQLException indicating that this feature is not supported. - */ + */ public ResultSetMetaData getMetaData() throws SQLException { - throw new UnsupportedFeatureException("ResultSet meta data is not yet implemented"); - } + throw new UnsupportedFeatureException("ResultSet meta data is not yet implemented"); + } public void setDate(int columnIndex, Date value, Calendar cal) throws SQLException { - if(cal == null || cal == Calendar.getInstance()) - this.setObject(columnIndex, value, Types.DATE); - throw new UnsupportedFeatureException("Setting date using explicit Calendar"); - } + if (cal == null || cal == Calendar.getInstance()) + this.setObject(columnIndex, value, Types.DATE); + throw new UnsupportedFeatureException("Setting date using explicit Calendar"); + } public void setTime(int columnIndex, Time value, Calendar cal) throws SQLException { - if(cal == null || cal == Calendar.getInstance()) - this.setObject(columnIndex, value, Types.TIME); - throw new UnsupportedFeatureException("Setting time using explicit Calendar"); - } + if (cal == null || cal == Calendar.getInstance()) + this.setObject(columnIndex, value, Types.TIME); + throw new UnsupportedFeatureException("Setting time using explicit Calendar"); + } public void setTimestamp(int columnIndex, Timestamp value, Calendar cal) throws SQLException { - if(cal == null || cal == Calendar.getInstance()) - this.setObject(columnIndex, value, Types.TIMESTAMP); - throw new UnsupportedFeatureException("Setting time using explicit Calendar"); - } + if (cal == null || cal == Calendar.getInstance()) + this.setObject(columnIndex, value, Types.TIMESTAMP); + throw new UnsupportedFeatureException("Setting time using explicit Calendar"); + } public void setNull(int columnIndex, int sqlType, String typeName) throws SQLException { - this.setNull(columnIndex, sqlType); - } + this.setNull(columnIndex, sqlType); + } public void setURL(int columnIndex, URL value) throws SQLException { - this.setObject(columnIndex, value, Types.DATALINK); - } + this.setObject(columnIndex, value, Types.DATALINK); + } - public String toString() - { - return m_statement; - } + @Override + public String toString() { + return m_statement; + } - /** + /** * Due to the design of the SPI_prepare, it is currently impossible to * obtain the correct parameter meta data before all the parameters have been * set, hence a ParameterMetaData obtained prior to setting the paramteres * will have all parameters set to the default type {@link Types#VARCHAR}. * Once the parameters have been set, a fair attempt is made to generate this * object based on the supplied values. - * @return The meta data for parameter values. - */ + * @return The meta data for parameter values. + */ public ParameterMetaData getParameterMetaData() throws SQLException { - return new SPIParameterMetaData(this.getSqlTypes()); - } + return new SPIParameterMetaData(this.getSqlTypes()); + } protected int executeBatchEntry(Object batchEntry) throws SQLException { - int ret = SUCCESS_NO_INFO; - Object batchParams[] = (Object[])batchEntry; - Object batchValues = batchParams[0]; - Object batchSqlTypes = batchParams[1]; - Object batchTypeIds[] = (Object[])batchParams[2]; - - System.arraycopy(batchValues, 0, m_values, 0, m_values.length); - System.arraycopy(batchSqlTypes, 0, m_sqlTypes, 0, m_sqlTypes.length); - - // Determine if we need to replan the query because the - // types have changed from the last execution. - // - for (int i=0; i= 0) - ret = updCount; - } - return ret; - } + int updCount = this.getUpdateCount(); + if (updCount >= 0) + ret = updCount; + } + return ret; + } + + public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } + + public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } + + public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } + + public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } + + public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } + + public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } + + public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } + + public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } + + public void setClob(int parameterIndex, Reader reader) throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } + + public void setClob(int parameterIndex, Reader reader, long length) throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } + + public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } + + public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } + + public void setNClob(int parameterIndex, NClob value) throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } + + public void setNClob(int parameterIndex, Reader reader) throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } + + public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } + + public void setNString(int parameterIndex, String value) throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } + + public void setRowId(int parameterIndex, RowId x) throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } + + public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } } Index: src/java/pljava/org/postgresql/pljava/jdbc/SPIStatement.java =================================================================== RCS file: /cvsroot/pljava/org.postgresql.pljava/src/java/pljava/org/postgresql/pljava/jdbc/SPIStatement.java,v retrieving revision 1.16 diff -u -r1.16 SPIStatement.java --- src/java/pljava/org/postgresql/pljava/jdbc/SPIStatement.java 4 Jun 2008 15:31:39 -0000 1.16 +++ src/java/pljava/org/postgresql/pljava/jdbc/SPIStatement.java 17 May 2010 19:50:50 -0000 @@ -8,9 +8,9 @@ import java.sql.Connection; import java.sql.ResultSet; -import java.sql.Statement; import java.sql.SQLException; import java.sql.SQLWarning; +import java.sql.Statement; import java.util.ArrayList; import org.postgresql.pljava.internal.ExecutionPlan; @@ -19,382 +19,399 @@ import org.postgresql.pljava.internal.SPIException; /** - * + * * @author Thomas Hallgren */ public class SPIStatement implements Statement { - private final SPIConnection m_connection; - - // Default settings. - // - private String m_cursorName = null; - private int m_fetchSize = 1000; - private int m_maxRows = 0; - private ResultSet m_resultSet = null; - private int m_updateCount = 0; - private ArrayList m_batch = null; - private boolean m_closed = false; + private final SPIConnection m_connection; + + // Default settings. + // + private String m_cursorName = null; + private int m_fetchSize = 1000; + private int m_maxRows = 0; + private ResultSet m_resultSet = null; + private int m_updateCount = 0; + private ArrayList m_batch = null; + private boolean m_closed = false; public SPIStatement(SPIConnection conn) { - m_connection = conn; - } + m_connection = conn; + } public void addBatch(String statement) throws SQLException { - // Statements are converted to native SQL once they - // are executed. - // - this.internalAddBatch(statement); - } + // Statements are converted to native SQL once they + // are executed. + // + this.internalAddBatch(statement); + } public void cancel() throws SQLException { - } + } public void clearBatch() throws SQLException { - m_batch = null; - } + m_batch = null; + } public void clearWarnings() throws SQLException { - } + } private void clear() throws SQLException { - if(m_resultSet != null) - // - // The close will call back to the resultSetClosed method - // and set the m_resultSet to null. - // - m_resultSet.close(); - - m_updateCount = -1; - m_cursorName = null; - m_batch = null; - } + if (m_resultSet != null) + // + // The close will call back to the resultSetClosed method + // and set the m_resultSet to null. + // + m_resultSet.close(); + + m_updateCount = -1; + m_cursorName = null; + m_batch = null; + } public void close() throws SQLException { - clear(); - m_closed = true; - } + clear(); + m_closed = true; + } public boolean execute(String statement) throws SQLException { - // Ensure that the last statement is cleaned up - // before we re-execute - // - this.clear(); + // Ensure that the last statement is cleaned up + // before we re-execute + // + this.clear(); ExecutionPlan plan = ExecutionPlan.prepare( m_connection.nativeSQL(statement), null); - int result = SPI.getResult(); - if(plan == null) - throw new SPIException(result); + int result = SPI.getResult(); + if (plan == null) + throw new SPIException(result); try { - return this.executePlan(plan, null); - } + return this.executePlan(plan, null); + } finally { try { plan.close(); } catch(Exception e) {} - } - } + } + } protected boolean executePlan(ExecutionPlan plan, Object[] paramValues) throws SQLException { - m_updateCount = -1; - m_resultSet = null; + m_updateCount = -1; + m_resultSet = null; - boolean isResultSet = plan.isCursorPlan(); + boolean isResultSet = plan.isCursorPlan(); if(isResultSet) { - Portal portal = plan.cursorOpen(m_cursorName, paramValues); - m_resultSet = new SPIResultSet(this, portal, m_maxRows); + Portal portal = plan.cursorOpen(m_cursorName, paramValues); + m_resultSet = new SPIResultSet(this, portal, m_maxRows); } else { try { - plan.execute(paramValues, m_maxRows); - m_updateCount = SPI.getProcessed(); + plan.execute(paramValues, m_maxRows); + m_updateCount = SPI.getProcessed(); } finally { - SPI.freeTupTable(); - } - } - return isResultSet; - } + SPI.freeTupTable(); + } + } + return isResultSet; + } - /** - * Return of auto generated keys is not yet supported. + /** + * Return of auto generated keys is not yet supported. * @throws SQLException indicating that this feature is not supported. - */ + */ public boolean execute(String statement, int autoGeneratedKeys) throws SQLException { - throw new UnsupportedFeatureException("Statement.execute(String,int)"); - } + throw new UnsupportedFeatureException("Statement.execute(String,int)"); + } - /** - * Return of auto generated keys is not yet supported. + /** + * Return of auto generated keys is not yet supported. * @throws SQLException indicating that this feature is not supported. - */ + */ public boolean execute(String statement, int[] columnIndexes) throws SQLException { - throw new UnsupportedFeatureException("Statement.execute(String,int[])"); - } + throw new UnsupportedFeatureException("Statement.execute(String,int[])"); + } - /** - * Return of auto generated keys is not yet supported. + /** + * Return of auto generated keys is not yet supported. * @throws SQLException indicating that this feature is not supported. - */ + */ public boolean execute(String statement, String[] columnNames) throws SQLException { - throw new UnsupportedFeatureException("Statement.execute(String,String[])"); - } + throw new UnsupportedFeatureException("Statement.execute(String,String[])"); + } public int[] executeBatch() throws SQLException { - int numBatches = (m_batch == null) ? 0 : m_batch.size(); - int[] result = new int[numBatches]; - for(int idx = 0; idx < numBatches; ++idx) - result[idx] = this.executeBatchEntry(m_batch.get(idx)); - return result; - } + int numBatches = (m_batch == null) ? 0 : m_batch.size(); + int[] result = new int[numBatches]; + for (int idx = 0; idx < numBatches; ++idx) + result[idx] = this.executeBatchEntry(m_batch.get(idx)); + return result; + } public ResultSet executeQuery(String statement) throws SQLException { - this.execute(statement); - return this.getResultSet(); - } + this.execute(statement); + return this.getResultSet(); + } public int executeUpdate(String statement) throws SQLException { - this.execute(statement); - return this.getUpdateCount(); - } + this.execute(statement); + return this.getUpdateCount(); + } - /** - * Return of auto generated keys is not yet supported. + /** + * Return of auto generated keys is not yet supported. * @throws SQLException indicating that this feature is not supported. - */ + */ public int executeUpdate(String statement, int autoGeneratedKeys) throws SQLException { - throw new UnsupportedFeatureException("Auto generated key support not yet implemented"); - } - + throw new UnsupportedFeatureException("Auto generated key support not yet implemented"); + } - /** - * Return of auto generated keys is not yet supported. + /** + * Return of auto generated keys is not yet supported. * @throws SQLException indicating that this feature is not supported. - */ + */ public int executeUpdate(String statement, int[] columnIndexes) throws SQLException { - throw new UnsupportedFeatureException("Auto generated key support not yet implemented"); - } + throw new UnsupportedFeatureException("Auto generated key support not yet implemented"); + } - - /** - * Return of auto generated keys is not yet supported. + /** + * Return of auto generated keys is not yet supported. * @throws SQLException indicating that this feature is not supported. - */ + */ public int executeUpdate(String statement, String[] columnNames) throws SQLException { - throw new UnsupportedFeatureException("Auto generated key support not yet implemented"); - } + throw new UnsupportedFeatureException("Auto generated key support not yet implemented"); + } - /** - * Returns the Connection from that created this statement. + /** + * Returns the Connection from that created this statement. * @throws SQLException if the statement is closed. - */ + */ public Connection getConnection() throws SQLException { - if(m_connection == null) - throw new StatementClosedException(); - return m_connection; - } + if (m_connection == null) + throw new StatementClosedException(); + return m_connection; + } public int getFetchDirection() throws SQLException { - return ResultSet.FETCH_FORWARD; - } - + return ResultSet.FETCH_FORWARD; + } + public int getFetchSize() throws SQLException { - return m_fetchSize; - } - + return m_fetchSize; + } + public ResultSet getGeneratedKeys() throws SQLException { - throw new SQLException("JDK 1.4 functionality not yet implemented"); - } - + throw new SQLException("JDK 1.4 functionality not yet implemented"); + } + public int getMaxFieldSize() throws SQLException { - return Integer.MAX_VALUE; - } - + return Integer.MAX_VALUE; + } + public int getMaxRows() throws SQLException { - return m_maxRows; - } - + return m_maxRows; + } + public boolean getMoreResults() throws SQLException { - return false; - } - + return false; + } + public boolean getMoreResults(int current) throws SQLException { - return false; - } - + return false; + } + public int getQueryTimeout() throws SQLException { - return 0; - } - + return 0; + } + public ResultSet getResultSet() throws SQLException { - return m_resultSet; - } + return m_resultSet; + } public int getResultSetConcurrency() { - return ResultSet.CONCUR_READ_ONLY; - } + return ResultSet.CONCUR_READ_ONLY; + } public int getResultSetHoldability() throws SQLException { - throw new SQLException("JDK 1.4 functionality not yet implemented"); - } + throw new SQLException("JDK 1.4 functionality not yet implemented"); + } public int getResultSetType() { - return ResultSet.TYPE_FORWARD_ONLY; - } + return ResultSet.TYPE_FORWARD_ONLY; + } public int getUpdateCount() throws SQLException { - return m_updateCount; - } + return m_updateCount; + } public SQLWarning getWarnings() throws SQLException { - if (m_closed) { - throw new SQLException("getWarnings: Statement is closed"); - } + if (m_closed) { + throw new SQLException("getWarnings: Statement is closed"); + } - return null; - } + return null; + } public void setCursorName(String cursorName) throws SQLException { - m_cursorName = cursorName; - } + m_cursorName = cursorName; + } public void setEscapeProcessing(boolean enable) throws SQLException { - throw new UnsupportedFeatureException("Statement.setEscapeProcessing"); - } - + throw new UnsupportedFeatureException("Statement.setEscapeProcessing"); + } - /** - * Only {@link ResultSet#FETCH_FORWARD} is supported. + /** + * Only {@link ResultSet#FETCH_FORWARD} is supported. * @throws SQLException indicating that this feature is not supported * for other values on direction. - */ + */ public void setFetchDirection(int direction) throws SQLException { - if(direction != ResultSet.FETCH_FORWARD) - throw new UnsupportedFeatureException("Non forward fetch direction"); - } + if (direction != ResultSet.FETCH_FORWARD) + throw new UnsupportedFeatureException("Non forward fetch direction"); + } public void setFetchSize(int size) throws SQLException { - m_fetchSize = size; - } + m_fetchSize = size; + } public void setMaxFieldSize(int size) throws SQLException { - throw new UnsupportedFeatureException("Statement.setMaxFieldSize"); - } + throw new UnsupportedFeatureException("Statement.setMaxFieldSize"); + } public void setMaxRows(int rows) throws SQLException { - m_maxRows = rows; - } + m_maxRows = rows; + } public void setQueryTimeout(int seconds) throws SQLException { - throw new UnsupportedFeatureException("Statement.setQueryTimeout"); - } + throw new UnsupportedFeatureException("Statement.setQueryTimeout"); + } protected void internalAddBatch(Object batch) throws SQLException { - if(m_batch == null) - m_batch = new ArrayList(); - m_batch.add(batch); - } + if (m_batch == null) + m_batch = new ArrayList(); + m_batch.add(batch); + } protected int executeBatchEntry(Object batchEntry) throws SQLException { - int ret = SUCCESS_NO_INFO; - if(this.execute(m_connection.nativeSQL((String)batchEntry))) - this.getResultSet().close(); - else if(m_updateCount >= 0) - ret = m_updateCount; - return ret; - } + int ret = SUCCESS_NO_INFO; + if (this.execute(m_connection.nativeSQL((String) batchEntry))) + this.getResultSet().close(); + else if (m_updateCount >= 0) + ret = m_updateCount; + return ret; + } void resultSetClosed(ResultSet rs) { - if(rs == m_resultSet) - m_resultSet = null; - } + if (rs == m_resultSet) + m_resultSet = null; + } + + public boolean isClosed() throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } + + public boolean isPoolable() throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } + + public void setPoolable(boolean poolable) throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } + + public boolean isWrapperFor(Class iface) throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } + + public T unwrap(Class iface) throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } } Index: src/java/pljava/org/postgresql/pljava/jdbc/SQLOutputToChunk.java =================================================================== RCS file: /cvsroot/pljava/org.postgresql.pljava/src/java/pljava/org/postgresql/pljava/jdbc/SQLOutputToChunk.java,v retrieving revision 1.2 diff -u -r1.2 SQLOutputToChunk.java --- src/java/pljava/org/postgresql/pljava/jdbc/SQLOutputToChunk.java 28 Feb 2006 08:16:57 -0000 1.2 +++ src/java/pljava/org/postgresql/pljava/jdbc/SQLOutputToChunk.java 17 May 2010 19:50:50 -0000 @@ -18,10 +18,13 @@ import java.sql.Blob; import java.sql.Clob; import java.sql.Date; +import java.sql.NClob; import java.sql.Ref; +import java.sql.RowId; import java.sql.SQLData; import java.sql.SQLException; import java.sql.SQLOutput; +import java.sql.SQLXML; import java.sql.Struct; import java.sql.Time; import java.sql.Timestamp; @@ -36,220 +39,237 @@ * during that single call. The handle of the instance will be invalidated when * the call returns and subsequent use of the instance will yield a * SQLException with the message "Stream is closed". - * + * * @author Thomas Hallgren */ public class SQLOutputToChunk implements SQLOutput { - private static final byte[] s_byteBuffer = new byte[8]; + private static final byte[] s_byteBuffer = new byte[8]; - private long m_handle; + private long m_handle; public SQLOutputToChunk(long handle) { - m_handle = handle; - } + m_handle = handle; + } public void writeArray(Array value) throws SQLException { - throw new UnsupportedOperationException("writeArray"); - } + throw new UnsupportedOperationException("writeArray"); + } public void writeAsciiStream(InputStream value) throws SQLException { - throw new UnsupportedOperationException("writeAsciiStream"); - } + throw new UnsupportedOperationException("writeAsciiStream"); + } public void writeBigDecimal(BigDecimal value) throws SQLException { - this.writeString(value.toString()); - } + this.writeString(value.toString()); + } public void writeBinaryStream(InputStream value) throws SQLException { - byte[] buf = new byte[1024]; - ByteArrayOutputStream bld = new ByteArrayOutputStream(); - int count; + byte[] buf = new byte[1024]; + ByteArrayOutputStream bld = new ByteArrayOutputStream(); + int count; try { - while((count = value.read(buf)) > 0) - bld.write(buf, 0, count); - this.writeBytes(bld.toByteArray()); + while ((count = value.read(buf)) > 0) + bld.write(buf, 0, count); + this.writeBytes(bld.toByteArray()); } catch(IOException e) { - throw new SQLException(e.getMessage()); - } - } + throw new SQLException(e.getMessage()); + } + } public void writeBlob(Blob value) throws SQLException { - throw new UnsupportedOperationException("writeBlob"); - } + throw new UnsupportedOperationException("writeBlob"); + } public void writeBoolean(boolean value) throws SQLException { - this.write(value ? 1 : 0); - } + this.write(value ? 1 : 0); + } public void writeByte(byte value) throws SQLException { - this.write(value); - } + this.write(value); + } public void writeBytes(byte[] buffer) throws SQLException { - int len = buffer.length; + int len = buffer.length; if(len > 0) { - if(len > 65535) - throw new SQLException("Byte buffer exceeds maximum size of 65535 bytes"); + if (len > 65535) + throw new SQLException("Byte buffer exceeds maximum size of 65535 bytes"); synchronized(Backend.THREADLOCK) { - if(m_handle == 0) - throw new SQLException("Stream is closed"); + if (m_handle == 0) + throw new SQLException("Stream is closed"); - s_byteBuffer[0] = (byte)((len >> 8) & 0xff); - s_byteBuffer[1] = (byte)(len & 0xff); - _writeBytes(m_handle, s_byteBuffer, 2); - _writeBytes(m_handle, buffer, len); - } - } - } + s_byteBuffer[0] = (byte) ((len >> 8) & 0xff); + s_byteBuffer[1] = (byte) (len & 0xff); + _writeBytes(m_handle, s_byteBuffer, 2); + _writeBytes(m_handle, buffer, len); + } + } + } public void writeCharacterStream(Reader value) throws SQLException { - char[] buf = new char[1024]; - StringWriter bld = new StringWriter(); - int count; + char[] buf = new char[1024]; + StringWriter bld = new StringWriter(); + int count; try { - while((count = value.read(buf)) > 0) - bld.write(buf, 0, count); - this.writeString(bld.toString()); + while ((count = value.read(buf)) > 0) + bld.write(buf, 0, count); + this.writeString(bld.toString()); } catch(IOException e) { - throw new SQLException(e.getMessage()); - } - } + throw new SQLException(e.getMessage()); + } + } public void writeClob(Clob value) throws SQLException { - throw new UnsupportedOperationException("writeClob"); - } + throw new UnsupportedOperationException("writeClob"); + } public void writeDate(Date value) throws SQLException { - this.writeLong(value.getTime()); - } + this.writeLong(value.getTime()); + } public void writeDouble(double value) throws SQLException { - this.writeLong(Double.doubleToLongBits(value)); - } + this.writeLong(Double.doubleToLongBits(value)); + } public void writeFloat(float value) throws SQLException { - this.writeInt(Float.floatToIntBits(value)); - } + this.writeInt(Float.floatToIntBits(value)); + } public void writeInt(int value) throws SQLException { synchronized(Backend.THREADLOCK) { - s_byteBuffer[0] = (byte)(value >>> 24); - s_byteBuffer[1] = (byte)(value >>> 16); - s_byteBuffer[2] = (byte)(value >>> 8); - s_byteBuffer[3] = (byte)(value >>> 0); - _writeBytes(m_handle, s_byteBuffer, 4); - } - } + s_byteBuffer[0] = (byte) (value >>> 24); + s_byteBuffer[1] = (byte) (value >>> 16); + s_byteBuffer[2] = (byte) (value >>> 8); + s_byteBuffer[3] = (byte) (value >>> 0); + _writeBytes(m_handle, s_byteBuffer, 4); + } + } public void writeLong(long value) throws SQLException { synchronized(Backend.THREADLOCK) { - s_byteBuffer[0] = (byte)(value >>> 56); - s_byteBuffer[1] = (byte)(value >>> 48); - s_byteBuffer[2] = (byte)(value >>> 40); - s_byteBuffer[3] = (byte)(value >>> 32); - s_byteBuffer[4] = (byte)(value >>> 24); - s_byteBuffer[5] = (byte)(value >>> 16); - s_byteBuffer[6] = (byte)(value >>> 8); - s_byteBuffer[7] = (byte)(value >>> 0); - _writeBytes(m_handle, s_byteBuffer, 8); - } - } + s_byteBuffer[0] = (byte) (value >>> 56); + s_byteBuffer[1] = (byte) (value >>> 48); + s_byteBuffer[2] = (byte) (value >>> 40); + s_byteBuffer[3] = (byte) (value >>> 32); + s_byteBuffer[4] = (byte) (value >>> 24); + s_byteBuffer[5] = (byte) (value >>> 16); + s_byteBuffer[6] = (byte) (value >>> 8); + s_byteBuffer[7] = (byte) (value >>> 0); + _writeBytes(m_handle, s_byteBuffer, 8); + } + } public void writeObject(SQLData value) throws SQLException { - throw new UnsupportedOperationException("writeObject"); - } + throw new UnsupportedOperationException("writeObject"); + } public void writeRef(Ref value) throws SQLException { - throw new UnsupportedOperationException("writeRef"); - } + throw new UnsupportedOperationException("writeRef"); + } public void writeShort(short value) throws SQLException { synchronized(Backend.THREADLOCK) { - s_byteBuffer[0] = (byte)(value >>> 8); - s_byteBuffer[1] = (byte)(value >>> 0); - _writeBytes(m_handle, s_byteBuffer, 2); - } - } + s_byteBuffer[0] = (byte) (value >>> 8); + s_byteBuffer[1] = (byte) (value >>> 0); + _writeBytes(m_handle, s_byteBuffer, 2); + } + } public void writeString(String value) throws SQLException { try { - this.writeBytes(value.getBytes("UTF8")); + this.writeBytes(value.getBytes("UTF8")); } catch(UnsupportedEncodingException e) { - throw new SQLException("UTF8 encoding not supported by JVM"); - } - } + throw new SQLException("UTF8 encoding not supported by JVM"); + } + } public void writeStruct(Struct value) throws SQLException { - throw new UnsupportedOperationException("writeStruct"); - } + throw new UnsupportedOperationException("writeStruct"); + } public void writeTime(Time value) throws SQLException { - this.writeLong(value.getTime()); - } + this.writeLong(value.getTime()); + } public void writeTimestamp(Timestamp value) throws SQLException { - this.writeLong(value.getTime()); - } + this.writeLong(value.getTime()); + } public void writeURL(URL value) throws SQLException { - this.writeString(value.toString()); - } + this.writeString(value.toString()); + } void close() { - m_handle = 0; - } + m_handle = 0; + } private void write(int b) throws SQLException { synchronized(Backend.THREADLOCK) { - if(m_handle == 0) - throw new SQLException("Stream is closed"); - _writeByte(m_handle, b); - } - } - - private static native void _writeByte(long handle, int theByte); - private static native void _writeBytes(long handle, byte[] src, int len); + if (m_handle == 0) + throw new SQLException("Stream is closed"); + _writeByte(m_handle, b); + } + } + + private static native void _writeByte(long handle, int theByte); + + private static native void _writeBytes(long handle, byte[] src, int len); + + public void writeNClob(NClob x) throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } + + public void writeNString(String x) throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } + + public void writeRowId(RowId x) throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } + + public void writeSQLXML(SQLXML x) throws SQLException { + throw new UnsupportedOperationException("This method is not implemented yet!"); + } } Index: src/java/pljava/org/postgresql/pljava/jdbc/SyntheticResultSet.java =================================================================== RCS file: /cvsroot/pljava/org.postgresql.pljava/src/java/pljava/org/postgresql/pljava/jdbc/SyntheticResultSet.java,v retrieving revision 1.8 diff -u -r1.8 SyntheticResultSet.java --- src/java/pljava/org/postgresql/pljava/jdbc/SyntheticResultSet.java 11 Feb 2006 13:57:50 -0000 1.8 +++ src/java/pljava/org/postgresql/pljava/jdbc/SyntheticResultSet.java 17 May 2010 19:50:50 -0000 @@ -6,8 +6,8 @@ */ package org.postgresql.pljava.jdbc; -import java.sql.SQLException; import java.sql.ResultSetMetaData; +import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; @@ -15,34 +15,33 @@ * A Synthetic ResultSet that provides direct access to data stored * in a {@link java.util.ArrayList}. This kind of ResultSet has nothing * common with any statement. - * + * * @author Filip Hrbek */ -public class SyntheticResultSet extends ResultSetBase -{ - private final ResultSetField[] m_fields; - private final ArrayList m_tuples; - private final HashMap m_fieldIndexes; +public class SyntheticResultSet extends ResultSetBase { + private final ResultSetField[] m_fields; + private final ArrayList m_tuples; + private final HashMap m_fieldIndexes; SyntheticResultSet(ResultSetField[] fields, ArrayList tuples) throws SQLException { - super(tuples.size()); - m_fields = fields; - m_tuples = tuples; - m_fieldIndexes = new HashMap(); + super(tuples.size()); + m_fields = fields; + m_tuples = tuples; + m_fieldIndexes = new HashMap(); int i = m_fields.length; - while(--i >= 0) - m_fieldIndexes.put(m_fields[i].getColumnLabel(), new Integer(i+1)); + while (--i >= 0) + m_fieldIndexes.put(m_fields[i].getColumnLabel(), new Integer(i + 1)); - Object[][] tupleTest = (Object[][]) m_tuples.toArray(new Object[0][]); - Object value; + Object[][] tupleTest = (Object[][]) m_tuples.toArray(new Object[0][]); + Object value; for (i=0; i < tupleTest.length; i++) { - int j = m_fields.length; + int j = m_fields.length; while(--j >= 0) { - value = tupleTest[i][j]; + value = tupleTest[i][j]; if (value != null && !m_fields[j].canContain(value.getClass())) { throw new SQLException( @@ -50,63 +49,60 @@ " in ResultSetField '" + m_fields[j].getColumnLabel() + "'" + " with OID " + m_fields[j].getOID() + " (expected class: " + m_fields[j].getJavaClass() + ")"); - } - } - } - } + } + } + } + } - public void close() - throws SQLException - { - m_tuples.clear(); - super.close(); - } + @Override + public void close() throws SQLException { + m_tuples.clear(); + super.close(); + } public int findColumn(String columnName) throws SQLException { - Integer idx = (Integer)m_fieldIndexes.get(columnName.toUpperCase()); + Integer idx = (Integer) m_fieldIndexes.get(columnName.toUpperCase()); if(idx != null) { return idx.intValue(); } throw new SQLException("No such field: '" + columnName + "'"); - } + } - protected Object getObjectValue(int columnIndex) - throws SQLException - { - return getCurrentRow()[columnIndex-1]; - } + @Override + protected Object getObjectValue(int columnIndex) throws SQLException { + return getCurrentRow()[columnIndex - 1]; + } protected final Object[] getCurrentRow() throws SQLException { - int row = this.getRow(); - if(row < 1 || row > m_tuples.size()) - throw new SQLException("ResultSet is not positioned on a valid row"); - return (Object[])m_tuples.get(row-1); - } + int row = this.getRow(); + if (row < 1 || row > m_tuples.size()) + throw new SQLException("ResultSet is not positioned on a valid row"); + return (Object[]) m_tuples.get(row - 1); + } public boolean isLast() throws SQLException { - return this.getRow() == m_tuples.size(); - } + return this.getRow() == m_tuples.size(); + } public boolean next() throws SQLException { - int row = this.getRow(); + int row = this.getRow(); if(row < m_tuples.size()) { - this.setRow(row+1); - return true; - } - return false; - } + this.setRow(row + 1); + return true; + } + return false; + } - public ResultSetMetaData getMetaData() - throws SQLException - { - return new SyntheticResultSetMetaData(m_fields); - } + @Override + public ResultSetMetaData getMetaData() throws SQLException { + return new SyntheticResultSetMetaData(m_fields); + } } Index: src/java/pljava/org/postgresql/pljava/jdbc/AbstractResultSetMetaData.java =================================================================== RCS file: /cvsroot/pljava/org.postgresql.pljava/src/java/pljava/org/postgresql/pljava/jdbc/AbstractResultSetMetaData.java,v retrieving revision 1.4 diff -u -r1.4 AbstractResultSetMetaData.java --- src/java/pljava/org/postgresql/pljava/jdbc/AbstractResultSetMetaData.java 6 May 2006 11:41:13 -0000 1.4 +++ src/java/pljava/org/postgresql/pljava/jdbc/AbstractResultSetMetaData.java 17 May 2010 19:50:49 -0000 @@ -7,16 +7,16 @@ package org.postgresql.pljava.jdbc; -import java.sql.ResultSetMetaData; -import java.sql.SQLException; import java.sql.Connection; import java.sql.DriverManager; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; import org.postgresql.pljava.internal.Oid; /** * Implementation of ResultSetMetaData for SyntheticResultSet - * + * * @author Filip Hrbek */ public abstract class AbstractResultSetMetaData implements ResultSetMetaData @@ -32,31 +32,31 @@ m_conn = null; } - /** - * Returns the number of columns in this ResultSet object. - * - * @return the number of columns + /** + * Returns the number of columns in this ResultSet object. + * + * @return the number of columns * @exception SQLException if a database access error occurs - */ - public abstract int getColumnCount() throws SQLException; + */ + public abstract int getColumnCount() throws SQLException; - /** + /** * Indicates whether the designated column is automatically numbered, thus read-only. - * + * * @param column the first column is 1, the second is 2, ... - * @return true if so; false otherwise + * @return true if so; false otherwise * @exception SQLException if a database access error occurs - */ - public abstract boolean isAutoIncrement(int column) throws SQLException; + */ + public abstract boolean isAutoIncrement(int column) throws SQLException; /** - * Indicates whether a column's case matters. - * + * Indicates whether a column's case matters. + * * @param column the first column is 1, the second is 2, ... - * @return true if so; false otherwise + * @return true if so; false otherwise * @exception SQLException if a database access error occurs - */ - public final boolean isCaseSensitive(int column) throws SQLException + */ + public final boolean isCaseSensitive(int column) throws SQLException { checkColumnIndex(column); Oid oid = this.getOid(column); @@ -66,56 +66,56 @@ || oid.equals(TypeOid.BPCHAR)); } - /** + /** * Indicates whether the designated column can be used in a where clause. - * + * * @param column the first column is 1, the second is 2, ... - * @return true if so; false otherwise + * @return true if so; false otherwise * @exception SQLException if a database access error occurs - */ - public final boolean isSearchable(int column) throws SQLException + */ + public final boolean isSearchable(int column) throws SQLException { checkColumnIndex(column); return true; } - /** - * Indicates whether the designated column is a cash value. - * + /** + * Indicates whether the designated column is a cash value. + * * @param column the first column is 1, the second is 2, ... - * @return true if so; false otherwise + * @return true if so; false otherwise * @exception SQLException if a database access error occurs - */ - public final boolean isCurrency(int column) throws SQLException + */ + public final boolean isCurrency(int column) throws SQLException { checkColumnIndex(column); - //For now it is false; it can be changed when TypeOid.java - //contains currency data types. + // For now it is false; it can be changed when TypeOid.java + // contains currency data types. return false; } - - /** - * Indicates the nullability of values in the designated column. - * + + /** + * Indicates the nullability of values in the designated column. + * * @param column the first column is 1, the second is 2, ... * @return the nullability status of the given column; one of columnNoNulls, * columnNullable or columnNullableUnknown * @exception SQLException if a database access error occurs - */ - public final int isNullable(int column) throws SQLException + */ + public final int isNullable(int column) throws SQLException { checkColumnIndex(column); return columnNullableUnknown; } - /** + /** * Indicates whether values in the designated column are signed numbers. - * + * * @param column the first column is 1, the second is 2, ... - * @return true if so; false otherwise + * @return true if so; false otherwise * @exception SQLException if a database access error occurs - */ - public final boolean isSigned(int column) throws SQLException + */ + public final boolean isSigned(int column) throws SQLException { checkColumnIndex(column); Oid oid = this.getOid(column); @@ -126,20 +126,20 @@ || oid.equals(TypeOid.FLOAT8)); } - /** + /** * Indicates the designated column's normal maximum width in characters. - * + * * @param column the first column is 1, the second is 2, ... - * @return the normal maximum number of characters allowed as the width - * of the designated column + * @return the normal maximum number of characters allowed as the width + * of the designated column * @exception SQLException if a database access error occurs - */ - public final int getColumnDisplaySize(int column) throws SQLException + */ + public final int getColumnDisplaySize(int column) throws SQLException { checkColumnIndex(column); Oid oid = this.getOid(column); - if(oid.equals(TypeOid.INT2)) + if (oid.equals(TypeOid.INT2)) return 6; if(oid.equals(TypeOid.INT4) @@ -152,13 +152,13 @@ || oid.equals(TypeOid.OID)) return 20; - if(oid.equals(TypeOid.BOOL)) + if (oid.equals(TypeOid.BOOL)) return 3; - if(oid.equals(TypeOid.DATE)) + if (oid.equals(TypeOid.DATE)) return 13; - if(oid.equals(TypeOid.TIME)) + if (oid.equals(TypeOid.TIME)) return 10; if(oid.equals(TypeOid.TIMESTAMP) @@ -168,74 +168,74 @@ return getFieldLength(column); } - /** + /** * Gets the designated column's suggested title for use in printouts and * displays. - * + * * @param column the first column is 1, the second is 2, ... - * @return the suggested column title + * @return the suggested column title * @exception SQLException if a database access error occurs - */ - public abstract String getColumnLabel(int column) throws SQLException; + */ + public abstract String getColumnLabel(int column) throws SQLException; - /** - * Get the designated column's name. - * + /** + * Get the designated column's name. + * * @param column the first column is 1, the second is 2, ... - * @return column name + * @return column name * @exception SQLException if a database access error occurs - */ - public String getColumnName(int column) throws SQLException + */ + public String getColumnName(int column) throws SQLException { checkColumnIndex(column); return getColumnLabel(column); } - /** - * Get the designated column's table's schema. - * + /** + * Get the designated column's table's schema. + * * @param column the first column is 1, the second is 2, ... - * @return schema name or "" if not applicable + * @return schema name or "" if not applicable * @exception SQLException if a database access error occurs - */ - public final String getSchemaName(int column) throws SQLException + */ + public final String getSchemaName(int column) throws SQLException { checkColumnIndex(column); return ""; } - /** - * Get the designated column's number of decimal digits. - * + /** + * Get the designated column's number of decimal digits. + * * @param column the first column is 1, the second is 2, ... - * @return precision + * @return precision * @exception SQLException if a database access error occurs - */ - public final int getPrecision(int column) throws SQLException + */ + public final int getPrecision(int column) throws SQLException { checkColumnIndex(column); Oid oid = this.getOid(column); - if(oid.equals(TypeOid.INT2)) + if (oid.equals(TypeOid.INT2)) return 5; - if(oid.equals(TypeOid.INT4)) + if (oid.equals(TypeOid.INT4)) return 10; if(oid.equals(TypeOid.INT8) || oid.equals(TypeOid.OID)) return 20; - if(oid.equals(TypeOid.FLOAT4)) + if (oid.equals(TypeOid.FLOAT4)) return 8; - if(oid.equals(TypeOid.FLOAT8)) + if (oid.equals(TypeOid.FLOAT8)) return 16; - if(oid.equals(TypeOid.BOOL)) + if (oid.equals(TypeOid.BOOL)) return 1; - if(oid.equals(TypeOid.NUMERIC)) + if (oid.equals(TypeOid.NUMERIC)) return -1; return 0; @@ -243,117 +243,117 @@ /** * Gets the designated column's number of digits to right of the decimal point. - * + * * @param column the first column is 1, the second is 2, ... - * @return scale + * @return scale * @exception SQLException if a database access error occurs - */ - public final int getScale(int column) throws SQLException + */ + public final int getScale(int column) throws SQLException { checkColumnIndex(column); Oid oid = this.getOid(column); - if(oid.equals(TypeOid.FLOAT4)) + if (oid.equals(TypeOid.FLOAT4)) return 8; - - if(oid.equals(TypeOid.FLOAT8)) + + if (oid.equals(TypeOid.FLOAT8)) return 16; - - if(oid.equals(TypeOid.NUMERIC)) + + if (oid.equals(TypeOid.NUMERIC)) return -1; return 0; } - /** - * Gets the designated column's table name. - * + /** + * Gets the designated column's table name. + * * @param column the first column is 1, the second is 2, ... - * @return table name or "" if not applicable + * @return table name or "" if not applicable * @exception SQLException if a database access error occurs - */ - public final String getTableName(int column) throws SQLException + */ + public final String getTableName(int column) throws SQLException { checkColumnIndex(column); return ""; } - /** - * Gets the designated column's table's catalog name. - * + /** + * Gets the designated column's table's catalog name. + * * @param column the first column is 1, the second is 2, ... * @return the name of the catalog for the table in which the given column * appears or "" if not applicable * @exception SQLException if a database access error occurs - */ - public final String getCatalogName(int column) throws SQLException + */ + public final String getCatalogName(int column) throws SQLException { checkColumnIndex(column); return ""; } - /** - * Retrieves the designated column's SQL type. - * + /** + * Retrieves the designated column's SQL type. + * * @param column the first column is 1, the second is 2, ... - * @return SQL type from {@link java.sql.Types} + * @return SQL type from {@link java.sql.Types} * @exception SQLException if a database access error occurs - * @see java.sql.Types - */ - public final int getColumnType(int column) throws SQLException + * @see java.sql.Types + */ + public final int getColumnType(int column) throws SQLException { checkColumnIndex(column); - return ((SPIConnection)getDefaultConnection()).getSQLType(getOid(column)); + return ((SPIConnection) getDefaultConnection()).getSQLType(getOid(column)); } - /** - * Retrieves the designated column's database-specific type name. - * + /** + * Retrieves the designated column's database-specific type name. + * * @param column the first column is 1, the second is 2, ... * @return type name used by the database. If the column type is * a user-defined type, then a fully-qualified type name is returned. * @exception SQLException if a database access error occurs - */ - public final String getColumnTypeName(int column) throws SQLException + */ + public final String getColumnTypeName(int column) throws SQLException { checkColumnIndex(column); - return ((SPIConnection)getDefaultConnection()).getPGType(getOid(column)); + return ((SPIConnection) getDefaultConnection()).getPGType(getOid(column)); } - /** - * Indicates whether the designated column is definitely not writable. - * + /** + * Indicates whether the designated column is definitely not writable. + * * @param column the first column is 1, the second is 2, ... - * @return true if so; false otherwise + * @return true if so; false otherwise * @exception SQLException if a database access error occurs - */ - public final boolean isReadOnly(int column) throws SQLException + */ + public final boolean isReadOnly(int column) throws SQLException { checkColumnIndex(column); return true; } - /** + /** * Indicates whether it is possible for a write on the designated column to succeed. - * + * * @param column the first column is 1, the second is 2, ... - * @return true if so; false otherwise + * @return true if so; false otherwise * @exception SQLException if a database access error occurs - */ - public final boolean isWritable(int column) throws SQLException + */ + public final boolean isWritable(int column) throws SQLException { checkColumnIndex(column); return false; } - /** + /** * Indicates whether a write on the designated column will definitely succeed. - * + * * @param column the first column is 1, the second is 2, ... - * @return true if so; false otherwise + * @return true if so; false otherwise * @exception SQLException if a database access error occurs - */ - public final boolean isDefinitelyWritable(int column) throws SQLException + */ + public final boolean isDefinitelyWritable(int column) throws SQLException { checkColumnIndex(column); return false; @@ -361,30 +361,30 @@ //--------------------------JDBC 2.0----------------------------------- - /** + /** *

        Returns the fully-qualified name of the Java class whose instances * are manufactured if the method ResultSet.getObject * is called to retrieve a value * from the column. ResultSet.getObject may return a subclass of the * class returned by this method. - * + * * @param column the first column is 1, the second is 2, ... * @return the fully-qualified name of the class in the Java programming * language that would be used by the method * ResultSet.getObject to retrieve the value in the specified * column. This is the class name used for custom mapping. * @exception SQLException if a database access error occurs - * @since 1.2 - */ - public abstract String getColumnClassName(int column) throws SQLException; - - /** - * Checks if the column index is valid. - * + * @since 1.2 + */ + public abstract String getColumnClassName(int column) throws SQLException; + + /** + * Checks if the column index is valid. + * * @param column the first column is 1, the second is 2, ... * @exception SQLException if the column is out of index bounds - */ - protected abstract void checkColumnIndex(int column) throws SQLException; + */ + protected abstract void checkColumnIndex(int column) throws SQLException; /** * Gets column OID @@ -401,6 +401,7 @@ * @throws SQLException if an error occurs */ protected abstract int getFieldLength(int column) throws SQLException; + /** * Obtains connection to the database if needed. * Once called, it stores the connection reference to a private variable. @@ -416,4 +417,15 @@ return m_conn; } + public boolean isWrapperFor(Class iface) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } + + public T unwrap(Class iface) throws SQLException + { + throw new UnsupportedOperationException( + "This method is not implemented yet!"); + } } Index: src/java/pljava/org/postgresql/pljava/internal/ExecutionPlan.java =================================================================== RCS file: /cvsroot/pljava/org.postgresql.pljava/src/java/pljava/org/postgresql/pljava/internal/ExecutionPlan.java,v retrieving revision 1.17 diff -u -r1.17 ExecutionPlan.java --- src/java/pljava/org/postgresql/pljava/internal/ExecutionPlan.java 26 Mar 2006 14:10:45 -0000 1.17 +++ src/java/pljava/org/postgresql/pljava/internal/ExecutionPlan.java 17 May 2010 19:50:49 -0000 @@ -8,8 +8,8 @@ import java.sql.SQLException; import java.util.Collections; -import java.util.Map; import java.util.LinkedHashMap; +import java.util.Map; /** * The ExecutionPlan correspons to the execution plan obtained @@ -28,7 +28,7 @@ /** * MRU cache for prepared plans. */ - static final class PlanCache extends LinkedHashMap + static final class PlanCache extends LinkedHashMap { private final int m_cacheSize; @@ -38,15 +38,16 @@ m_cacheSize = cacheSize; } + @Override protected boolean removeEldestEntry(Map.Entry eldest) { - if(this.size() <= m_cacheSize) + if (this.size() <= m_cacheSize) return false; - ExecutionPlan evicted = (ExecutionPlan)eldest.getValue(); - synchronized(Backend.THREADLOCK) + ExecutionPlan evicted = (ExecutionPlan) eldest.getValue(); + synchronized (Backend.THREADLOCK) { - if(evicted.m_pointer != 0) + if (evicted.m_pointer != 0) { _invalidate(evicted.m_pointer); evicted.m_pointer = 0; @@ -71,35 +72,37 @@ m_argTypes = argTypes; } + @Override public boolean equals(Object o) { - if(!(o instanceof PlanKey)) + if (!(o instanceof PlanKey)) return false; - PlanKey pk = (PlanKey)o; - if(!pk.m_stmt.equals(m_stmt)) + PlanKey pk = (PlanKey) o; + if (!pk.m_stmt.equals(m_stmt)) return false; Oid[] pat = pk.m_argTypes; Oid[] mat = m_argTypes; int idx = pat.length; - if(mat.length != idx) + if (mat.length != idx) return false; - while(--idx >= 0) - if(!pat[idx].equals(mat[idx])) + while (--idx >= 0) + if (!pat[idx].equals(mat[idx])) return false; return true; } + @Override public int hashCode() { return m_hashCode; } } - private static final Map s_planCache; + private static final Map s_planCache; private final Object m_key; @@ -108,7 +111,7 @@ int cacheSize = Backend.getStatementCacheSize(); s_planCache = Collections.synchronizedMap(new PlanCache(cacheSize < 11 ? 11 - : cacheSize)); + : cacheSize)); } private ExecutionPlan(Object key, long pointer) @@ -122,10 +125,10 @@ */ public void close() { - ExecutionPlan old = (ExecutionPlan)s_planCache.put(m_key, this); - if(old != null && old.m_pointer != 0) + ExecutionPlan old = s_planCache.put(m_key, this); + if (old != null && old.m_pointer != 0) { - synchronized(Backend.THREADLOCK) + synchronized (Backend.THREADLOCK) { _invalidate(old.m_pointer); old.m_pointer = 0; @@ -144,12 +147,12 @@ * @throws SQLException If the underlying native structure has gone stale. */ public Portal cursorOpen(String cursorName, Object[] parameters) - throws SQLException + throws SQLException { - synchronized(Backend.THREADLOCK) + synchronized (Backend.THREADLOCK) { return _cursorOpen(m_pointer, System.identityHashCode(Thread - .currentThread()), cursorName, parameters); + .currentThread()), cursorName, parameters); } } @@ -164,7 +167,7 @@ */ public boolean isCursorPlan() throws SQLException { - synchronized(Backend.THREADLOCK) + synchronized (Backend.THREADLOCK) { return _isCursorPlan(m_pointer); } @@ -182,10 +185,10 @@ */ public int execute(Object[] parameters, int rowCount) throws SQLException { - synchronized(Backend.THREADLOCK) + synchronized (Backend.THREADLOCK) { return _execute(m_pointer, System.identityHashCode(Thread - .currentThread()), parameters, rowCount); + .currentThread()), parameters, rowCount); } } @@ -200,16 +203,16 @@ * @see java.sql.Types */ public static ExecutionPlan prepare(String statement, Oid[] argTypes) - throws SQLException + throws SQLException { Object key = (argTypes == null) ? (Object)statement : (Object)new PlanKey(statement, argTypes); - ExecutionPlan plan = (ExecutionPlan)s_planCache.remove(key); - if(plan == null) + ExecutionPlan plan = (ExecutionPlan) s_planCache.remove(key); + if (plan == null) { - synchronized(Backend.THREADLOCK) + synchronized (Backend.THREADLOCK) { plan = new ExecutionPlan(key, _prepare( System.identityHashCode(Thread.currentThread()), statement, argTypes)); @@ -219,13 +222,13 @@ } private static native Portal _cursorOpen(long pointer, long threadId, - String cursorName, Object[] parameters) throws SQLException; + String cursorName, Object[] parameters) throws SQLException; private static native boolean _isCursorPlan(long pointer) throws SQLException; private static native int _execute(long pointer, long threadId, - Object[] parameters, int rowCount) throws SQLException; + Object[] parameters, int rowCount) throws SQLException; private static native long _prepare(long threadId, String statement, Oid[] argTypes) throws SQLException; Index: src/java/pljava/org/postgresql/pljava/internal/ObjectPoolImpl.java =================================================================== RCS file: /cvsroot/pljava/org.postgresql.pljava/src/java/pljava/org/postgresql/pljava/internal/ObjectPoolImpl.java,v retrieving revision 1.2 diff -u -r1.2 ObjectPoolImpl.java --- src/java/pljava/org/postgresql/pljava/internal/ObjectPoolImpl.java 11 Feb 2006 13:57:51 -0000 1.2 +++ src/java/pljava/org/postgresql/pljava/internal/ObjectPoolImpl.java 17 May 2010 19:50:49 -0000 @@ -28,14 +28,14 @@ private static Class[] s_ctorSignature = { ObjectPool.class }; private static PooledObjectHandle s_handlePool; - private static final IdentityHashMap s_poolCache = new IdentityHashMap(); + private static final IdentityHashMap s_poolCache = new IdentityHashMap(); private final Constructor m_ctor; private PooledObjectHandle m_providerPool; - private ObjectPoolImpl(Class c) + private ObjectPoolImpl(Class c) { - if(!PooledObject.class.isAssignableFrom(c)) + if (!PooledObject.class.isAssignableFrom(c)) throw new IllegalArgumentException("Class " + c + " does not implement the " + PooledObject.class + " interface"); @@ -61,8 +61,8 @@ */ public static ObjectPoolImpl getObjectPool(Class cls) { - ObjectPoolImpl pool = (ObjectPoolImpl)s_poolCache.get(cls); - if(pool == null) + ObjectPoolImpl pool = s_poolCache.get(cls); + if (pool == null) { pool = new ObjectPoolImpl(cls); s_poolCache.put(cls, pool); @@ -75,7 +75,7 @@ { PooledObject instance; PooledObjectHandle handle = m_providerPool; - if(handle != null) + if (handle != null) { m_providerPool = handle.m_next; instance = handle.m_instance; @@ -95,12 +95,12 @@ catch(InvocationTargetException e) { Throwable t = e.getTargetException(); - if(t instanceof SQLException) - throw (SQLException)t; - if(t instanceof RuntimeException) - throw (RuntimeException)t; - if(t instanceof Error) - throw (Error)t; + if (t instanceof SQLException) + throw (SQLException) t; + if (t instanceof RuntimeException) + throw (RuntimeException) t; + if (t instanceof Error) + throw (Error) t; throw new SQLException(e.getMessage()); } catch(RuntimeException e) @@ -142,7 +142,7 @@ // we have something to wrap the instance in. // PooledObjectHandle handle = s_handlePool; - if(handle != null) + if (handle != null) s_handlePool = handle.m_next; else handle = new PooledObjectHandle(); @@ -155,11 +155,11 @@ public void removeInstance(PooledObject instance) throws SQLException { PooledObjectHandle prev = null; - for(PooledObjectHandle handle = m_providerPool; handle != null; handle = handle.m_next) + for (PooledObjectHandle handle = m_providerPool; handle != null; handle = handle.m_next) { - if(handle.m_instance == instance) + if (handle.m_instance == instance) { - if(prev == null) + if (prev == null) m_providerPool = handle.m_next; else prev.m_next = handle.m_next; Index: src/java/pljava/org/postgresql/pljava/internal/SubXactListener.java =================================================================== RCS file: /cvsroot/pljava/org.postgresql.pljava/src/java/pljava/org/postgresql/pljava/internal/SubXactListener.java,v retrieving revision 1.2 diff -u -r1.2 SubXactListener.java --- src/java/pljava/org/postgresql/pljava/internal/SubXactListener.java 11 Feb 2006 13:57:51 -0000 1.2 +++ src/java/pljava/org/postgresql/pljava/internal/SubXactListener.java 17 May 2010 19:50:49 -0000 @@ -11,59 +11,57 @@ import org.postgresql.pljava.SavepointListener; - /** * Class that enables registrations using the PostgreSQL RegisterSubXactCallback * function. - * + * * @author Thomas Hallgren */ -class SubXactListener -{ - private static final HashMap s_listeners = new HashMap(); +class SubXactListener { + private static final HashMap s_listeners = new HashMap(); static void onAbort(long listenerId, int spId, int parentSpId) throws SQLException { - SavepointListener listener = (SavepointListener)s_listeners.get(new Long(listenerId)); - if(listener != null) - listener.onAbort(Backend.getSession(), PgSavepoint.forId(spId), PgSavepoint.forId(parentSpId)); - } + SavepointListener listener = (SavepointListener) s_listeners.get(new Long(listenerId)); + if (listener != null) + listener.onAbort(Backend.getSession(), PgSavepoint.forId(spId), PgSavepoint.forId(parentSpId)); + } static void onCommit(long listenerId, int spId, int parentSpId) throws SQLException { - SavepointListener listener = (SavepointListener)s_listeners.get(new Long(listenerId)); - if(listener != null) - listener.onCommit(Backend.getSession(), PgSavepoint.forId(spId), PgSavepoint.forId(parentSpId)); - } + SavepointListener listener = (SavepointListener) s_listeners.get(new Long(listenerId)); + if (listener != null) + listener.onCommit(Backend.getSession(), PgSavepoint.forId(spId), PgSavepoint.forId(parentSpId)); + } static void onStart(long listenerId, long spPointer, int parentSpId) throws SQLException { - SavepointListener listener = (SavepointListener)s_listeners.get(new Long(listenerId)); - if(listener != null) - listener.onStart(Backend.getSession(), new PgSavepoint(spPointer), PgSavepoint.forId(parentSpId)); - } + SavepointListener listener = (SavepointListener) s_listeners.get(new Long(listenerId)); + if (listener != null) + listener.onStart(Backend.getSession(), new PgSavepoint(spPointer), PgSavepoint.forId(parentSpId)); + } static void addListener(SavepointListener listener) { synchronized(Backend.THREADLOCK) { - long key = System.identityHashCode(listener); - if(s_listeners.put(new Long(key), listener) != listener) - _register(key); - } - } + long key = System.identityHashCode(listener); + if (s_listeners.put(new Long(key), listener) != listener) + _register(key); + } + } static void removeListener(SavepointListener listener) { synchronized(Backend.THREADLOCK) { - long key = System.identityHashCode(listener); - if(s_listeners.remove(new Long(key)) == listener) - _unregister(key); - } - } + long key = System.identityHashCode(listener); + if (s_listeners.remove(new Long(key)) == listener) + _unregister(key); + } + } - private static native void _register(long listenerId); + private static native void _register(long listenerId); - private static native void _unregister(long listenerId); + private static native void _unregister(long listenerId); } Index: src/java/pljava/org/postgresql/pljava/internal/XactListener.java =================================================================== RCS file: /cvsroot/pljava/org.postgresql.pljava/src/java/pljava/org/postgresql/pljava/internal/XactListener.java,v retrieving revision 1.2 diff -u -r1.2 XactListener.java --- src/java/pljava/org/postgresql/pljava/internal/XactListener.java 11 Feb 2006 13:57:51 -0000 1.2 +++ src/java/pljava/org/postgresql/pljava/internal/XactListener.java 17 May 2010 19:50:49 -0000 @@ -11,59 +11,57 @@ import org.postgresql.pljava.TransactionListener; - /** * Class that enables registrations using the PostgreSQL RegisterXactCallback * function. - * + * * @author Thomas Hallgren */ -class XactListener -{ - private static final HashMap s_listeners = new HashMap(); +class XactListener { + private static final HashMap s_listeners = new HashMap(); static void onAbort(long listenerId) throws SQLException { - TransactionListener listener = (TransactionListener)s_listeners.get(new Long(listenerId)); - if(listener != null) - listener.onAbort(Backend.getSession()); - } + TransactionListener listener = (TransactionListener) s_listeners.get(new Long(listenerId)); + if (listener != null) + listener.onAbort(Backend.getSession()); + } static void onCommit(long listenerId) throws SQLException { - TransactionListener listener = (TransactionListener)s_listeners.get(new Long(listenerId)); - if(listener != null) - listener.onCommit(Backend.getSession()); - } + TransactionListener listener = (TransactionListener) s_listeners.get(new Long(listenerId)); + if (listener != null) + listener.onCommit(Backend.getSession()); + } static void onPrepare(long listenerId) throws SQLException { - TransactionListener listener = (TransactionListener)s_listeners.get(new Long(listenerId)); - if(listener != null) - listener.onPrepare(Backend.getSession()); - } - + TransactionListener listener = (TransactionListener) s_listeners.get(new Long(listenerId)); + if (listener != null) + listener.onPrepare(Backend.getSession()); + } + static void addListener(TransactionListener listener) { synchronized(Backend.THREADLOCK) { - long key = System.identityHashCode(listener); - if(s_listeners.put(new Long(key), listener) != listener) - _register(key); - } - } - + long key = System.identityHashCode(listener); + if (s_listeners.put(new Long(key), listener) != listener) + _register(key); + } + } + static void removeListener(TransactionListener listener) { synchronized(Backend.THREADLOCK) { - long key = System.identityHashCode(listener); - if(s_listeners.remove(new Long(key)) == listener) - _unregister(key); - } - } + long key = System.identityHashCode(listener); + if (s_listeners.remove(new Long(key)) == listener) + _unregister(key); + } + } - private static native void _register(long listenerId); + private static native void _register(long listenerId); - private static native void _unregister(long listenerId); + private static native void _unregister(long listenerId); } Index: src/java/pljava/org/postgresql/pljava/internal/PgSavepoint.java =================================================================== RCS file: /cvsroot/pljava/org.postgresql.pljava/src/java/pljava/org/postgresql/pljava/internal/PgSavepoint.java,v retrieving revision 1.2 diff -u -r1.2 PgSavepoint.java --- src/java/pljava/org/postgresql/pljava/internal/PgSavepoint.java 11 Feb 2006 13:57:51 -0000 1.2 +++ src/java/pljava/org/postgresql/pljava/internal/PgSavepoint.java 17 May 2010 19:50:49 -0000 @@ -17,7 +17,7 @@ */ public class PgSavepoint implements java.sql.Savepoint { - private static final WeakHashMap s_knownSavepoints = new WeakHashMap(); + private static final WeakHashMap s_knownSavepoints = new WeakHashMap(); private long m_pointer; @@ -29,7 +29,7 @@ public static PgSavepoint set(String name) throws SQLException { - synchronized(Backend.THREADLOCK) + synchronized (Backend.THREADLOCK) { PgSavepoint sp = new PgSavepoint(_set(name)); s_knownSavepoints.put(sp, Boolean.TRUE); @@ -39,15 +39,15 @@ static PgSavepoint forId(int savepointId) { - if(savepointId != 0) + if (savepointId != 0) { - synchronized(Backend.THREADLOCK) + synchronized (Backend.THREADLOCK) { Iterator itor = s_knownSavepoints.keySet().iterator(); - while(itor.hasNext()) + while (itor.hasNext()) { - PgSavepoint sp = (PgSavepoint)itor.next(); - if(savepointId == _getId(sp.m_pointer)) + PgSavepoint sp = (PgSavepoint) itor.next(); + if (savepointId == _getId(sp.m_pointer)) return sp; } } @@ -55,11 +55,13 @@ return null; } + @Override public int hashCode() { return this.getSavepointId(); } + @Override public boolean equals(Object o) { return (this == o); @@ -68,7 +70,7 @@ public void release() throws SQLException { - synchronized(Backend.THREADLOCK) + synchronized (Backend.THREADLOCK) { _release(m_pointer); s_knownSavepoints.remove(this); @@ -79,7 +81,7 @@ public void rollback() throws SQLException { - synchronized(Backend.THREADLOCK) + synchronized (Backend.THREADLOCK) { _rollback(m_pointer); s_knownSavepoints.remove(this); @@ -89,7 +91,7 @@ public String getSavepointName() throws SQLException { - synchronized(Backend.THREADLOCK) + synchronized (Backend.THREADLOCK) { return _getName(m_pointer); } @@ -97,7 +99,7 @@ public int getSavepointId() { - synchronized(Backend.THREADLOCK) + synchronized (Backend.THREADLOCK) { return _getId(m_pointer); } @@ -106,11 +108,11 @@ public void onInvocationExit(Connection conn) throws SQLException { - if(m_pointer == 0) + if (m_pointer == 0) return; Logger logger = Logger.getAnonymousLogger(); - if(Backend.isReleaseLingeringSavepoints()) + if (Backend.isReleaseLingeringSavepoints()) { logger.warning("Releasing savepoint '" + _getId(m_pointer) + "' since its lifespan exceeds that of the function where it was set"); Index: src/java/pljava/org/postgresql/pljava/internal/TransactionalMap.java =================================================================== RCS file: /cvsroot/pljava/org.postgresql.pljava/src/java/pljava/org/postgresql/pljava/internal/TransactionalMap.java,v retrieving revision 1.4 diff -u -r1.4 TransactionalMap.java --- src/java/pljava/org/postgresql/pljava/internal/TransactionalMap.java 11 Feb 2006 13:57:51 -0000 1.4 +++ src/java/pljava/org/postgresql/pljava/internal/TransactionalMap.java 17 May 2010 19:50:49 -0000 @@ -6,14 +6,14 @@ */ package org.postgresql.pljava.internal; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; +import java.util.AbstractCollection; +import java.util.AbstractSet; import java.util.Collection; +import java.util.HashMap; import java.util.Iterator; -import java.util.AbstractSet; -import java.util.AbstractCollection; +import java.util.Map; import java.util.NoSuchElementException; +import java.util.Set; /** * A TransactionalMap acts as a modifiable front for a backing map. All @@ -22,10 +22,10 @@ * * The map is not synchronized so care should be taken if multiple threads * will access the map. - * + * * @author Thomas Hallgren */ -public class TransactionalMap extends HashMap +public class TransactionalMap extends HashMap { private static final long serialVersionUID = 5337569423915578121L; @@ -35,15 +35,15 @@ // Cache of backed collections. // - private Set m_entrySet; - private Set m_keySet; - private Collection m_valueColl; + private Set> m_entrySet; + private Set m_keySet; + private Collection m_valueColl; // Commited data // - private final Map m_base; + private final Map m_base; - protected TransactionalMap(Map base) + protected TransactionalMap(Map base) { m_base = base; } @@ -61,6 +61,7 @@ * Clear this map (an anti-object is inserted for each entry * present in the backed map). */ + @Override public void clear() { super.clear(); @@ -69,7 +70,7 @@ // parent scope. // Iterator itor = m_base.keySet().iterator(); - while(itor.hasNext()) + while (itor.hasNext()) super.put(itor.next(), s_noObject); } @@ -81,12 +82,12 @@ public void commit() { Iterator itor = super.entrySet().iterator(); - while(itor.hasNext()) + while (itor.hasNext()) { - Map.Entry e = (Map.Entry)itor.next(); + Map.Entry e = (Map.Entry) itor.next(); Object key = e.getKey(); Object val = e.getValue(); - if(val == s_noObject) + if (val == s_noObject) m_base.remove(key); else m_base.put(key, val); @@ -94,107 +95,115 @@ super.clear(); } + @Override public boolean containsKey(Object key) { Object v = super.get(key); - if(v != null) + if (v != null) return (v != s_noObject); return super.containsKey(key) || m_base.containsKey(key); } + @Override public Object get(Object key) { Object val = super.get(key); - if(val == s_noObject) + if (val == s_noObject) val = null; - else - if(val == null && !super.containsKey(key)) + else if (val == null && !super.containsKey(key)) val = m_base.get(key); return val; } + @Override public Object remove(Object key) { Object val = super.get(key); - if(val == s_noObject) + if (val == s_noObject) // // Already removed // return null; Object bval = m_base.get(key); - if(bval == null && !m_base.containsKey(key)) + if (bval == null && !m_base.containsKey(key)) { // Not present in base // - if(val != null || super.containsKey(key)) + if (val != null || super.containsKey(key)) super.remove(key); return val; } - if(val == null && !super.containsKey(key)) + if (val == null && !super.containsKey(key)) val = bval; super.put(key, s_noObject); return val; } + @Override public int size() { - int sz = m_base.size(); + int sz = m_base.size(); int psz = super.size(); - if(sz == 0) + if (sz == 0) return psz; - if(psz == 0) + if (psz == 0) return sz; Iterator itor = super.entrySet().iterator(); // Decrease counter for entries present in both maps. // - while(itor.hasNext()) + while (itor.hasNext()) { - Map.Entry me = (Map.Entry)itor.next(); + Map.Entry me = (Map.Entry) itor.next(); Object val = me.getValue(); - if(val == s_noObject) + if (val == s_noObject) --sz; - else if(!m_base.containsKey(me.getKey())) + else if (!m_base.containsKey(me.getKey())) ++sz; } return sz; } + @Override public boolean containsValue(Object val) { Iterator itor = this.getValueIterator(); - while(itor.hasNext()) + while (itor.hasNext()) { Object v = itor.next(); - if(v == val || (v != null && v.equals(val))) + if (v == val || (v != null && v.equals(val))) return true; } return false; } - public Set entrySet() + @Override + public Set> entrySet() { - if(m_entrySet == null) + if (m_entrySet == null) { - m_entrySet = new AbstractSet() + m_entrySet = new AbstractSet>() { - public Iterator iterator() + @Override + public Iterator> iterator() { return TransactionalMap.this.getEntryIterator(); } + @Override public int size() { return TransactionalMap.this.size(); } + @Override public boolean contains(Object k) { return TransactionalMap.this.containsKey(k); @@ -204,27 +213,32 @@ return m_entrySet; } + @Override public boolean isEmpty() { return (this.size() == 0); } - public Set keySet() + @Override + public Set keySet() { - if(m_keySet == null) + if (m_keySet == null) { - m_keySet = new AbstractSet() + m_keySet = new AbstractSet() { - public Iterator iterator() + @Override + public Iterator iterator() { return TransactionalMap.this.getKeyIterator(); } + @Override public int size() { return TransactionalMap.this.size(); } + @Override public boolean contains(Object k) { return TransactionalMap.this.containsKey(k); @@ -234,6 +248,7 @@ return m_keySet; } + @Override public Object put(Object key, Object value) { Object old = this.get(key); @@ -241,27 +256,32 @@ return old; } - public void putAll(Map t) + @Override + public void putAll(Map t) { super.putAll(t); } - public Collection values() + @Override + public Collection values() { - if(m_valueColl == null) + if (m_valueColl == null) { - m_valueColl = new AbstractCollection() + m_valueColl = new AbstractCollection() { - public Iterator iterator() + @Override + public Iterator iterator() { return TransactionalMap.this.getValueIterator(); } + @Override public int size() { return TransactionalMap.this.size(); } + @Override public boolean contains(Object v) { return TransactionalMap.this.containsValue(v); @@ -281,19 +301,19 @@ return new EntryIterator(); } - protected Iterator getKeyIterator() + protected Iterator getKeyIterator() { return new KeyIterator(); } - protected Iterator getValueIterator() + protected Iterator getValueIterator() { return new ValueIterator(); } protected class BackedEntry implements Map.Entry { - private Object m_key; + private final Object m_key; public BackedEntry(Object key) { @@ -316,11 +336,12 @@ } } - protected class KeyIterator implements Iterator + protected class KeyIterator implements Iterator { private boolean m_phaseA = true; - private Iterator m_currentItor = TransactionalMap.this.superKeySet().iterator(); + private Iterator m_currentItor = TransactionalMap.this.superKeySet() + .iterator(); private Object m_currentKey = null; @@ -333,7 +354,7 @@ public Object next() { Object key = this.getValidKey(m_currentKey); - if(key == null) + if (key == null) throw new NoSuchElementException(); m_currentKey = null; // Force retrieval of next key @@ -347,21 +368,21 @@ protected Object getValidKey(Object key) { - if(key != null && TransactionalMap.this.containsKey(key)) + if (key != null && TransactionalMap.this.containsKey(key)) return key; // Entry is not valid. Get next entry. // - for(;;) + for (;;) { - while(m_currentItor.hasNext()) + while (m_currentItor.hasNext()) { key = m_currentItor.next(); - if(TransactionalMap.this.containsKey(key)) + if (TransactionalMap.this.containsKey(key)) return key; } - if(!m_phaseA) + if (!m_phaseA) break; m_currentItor = m_base.keySet().iterator(); @@ -373,6 +394,7 @@ protected class EntryIterator extends KeyIterator { + @Override public Object next() { return new BackedEntry(super.next()); @@ -381,6 +403,7 @@ protected class ValueIterator extends KeyIterator { + @Override public Object next() { return TransactionalMap.this.get(super.next()); Index: src/java/pljava/org/postgresql/pljava/internal/Oid.java =================================================================== RCS file: /cvsroot/pljava/org.postgresql.pljava/src/java/pljava/org/postgresql/pljava/internal/Oid.java,v retrieving revision 1.8 diff -u -r1.8 Oid.java --- src/java/pljava/org/postgresql/pljava/internal/Oid.java 6 May 2006 11:41:13 -0000 1.8 +++ src/java/pljava/org/postgresql/pljava/internal/Oid.java 17 May 2010 19:50:49 -0000 @@ -13,14 +13,14 @@ * The Oid correspons to the internal PostgreSQL Oid. * Should the size of that change from 32 bit, this class must change too. * In Java, the InvalidOid is represented as null. - * + * * @author Thomas Hallgren */ public class Oid extends Number { - private static final HashMap s_class2typeId = new HashMap(); + private static final HashMap s_class2typeId = new HashMap(); - private static final HashMap s_typeId2class = new HashMap(); + private static final HashMap s_typeId2class = new HashMap(); static { try @@ -43,7 +43,7 @@ */ public static Oid forJavaClass(Class clazz) { - return (Oid)s_class2typeId.get(clazz); + return (Oid) s_class2typeId.get(clazz); } /** @@ -54,7 +54,7 @@ */ public static Oid forTypeName(String typeString) { - synchronized(Backend.THREADLOCK) + synchronized (Backend.THREADLOCK) { return new Oid(_forTypeName(typeString)); } @@ -67,7 +67,7 @@ */ public static Oid forSqlType(int sqlType) { - synchronized(Backend.THREADLOCK) + synchronized (Backend.THREADLOCK) { return new Oid(_forSqlType(sqlType)); } @@ -78,7 +78,7 @@ */ public static Oid getTypeId() { - synchronized(Backend.THREADLOCK) + synchronized (Backend.THREADLOCK) { return _getTypeId(); } @@ -94,7 +94,7 @@ public static void registerType(Class clazz, Oid typeId) { s_class2typeId.put(clazz, typeId); - if(!s_typeId2class.containsKey(typeId)) + if (!s_typeId2class.containsKey(typeId)) s_typeId2class.put(typeId, clazz); } @@ -110,6 +110,7 @@ m_native = value; } + @Override public double doubleValue() { return m_native; @@ -121,11 +122,13 @@ * of this Oid. * @return true if the objects are equal. */ + @Override public boolean equals(Object o) { - return (o == this) || ((o instanceof Oid) && ((Oid)o).m_native == m_native); + return (o == this) || ((o instanceof Oid) && ((Oid) o).m_native == m_native); } + @Override public float floatValue() { return m_native; @@ -134,11 +137,11 @@ public Class getJavaClass() throws SQLException { - Class c = (Class)s_typeId2class.get(this); - if(c == null) + Class c = (Class) s_typeId2class.get(this); + if (c == null) { String className; - synchronized(Backend.THREADLOCK) + synchronized (Backend.THREADLOCK) { className = _getJavaClassName(m_native); } @@ -160,16 +163,19 @@ * The native value is used as the hash code. * @return The hashCode for this Oid. */ + @Override public int hashCode() { return m_native; } + @Override public int intValue() { return m_native; } + @Override public long longValue() { return m_native; @@ -178,6 +184,7 @@ /** * Returns a string representation of this OID. */ + @Override public String toString() { return "OID(" + m_native + ')'; @@ -185,35 +192,35 @@ private static String getCanonicalClassName(String name, int nDims) { - if(name.endsWith("[]")) + if (name.endsWith("[]")) return getCanonicalClassName(name.substring(0, name.length() - 2), nDims + 1); boolean primitive = true; - if(name.equals("boolean")) + if (name.equals("boolean")) name = "Z"; - else if(name.equals("byte")) + else if (name.equals("byte")) name = "B"; - else if(name.equals("char")) + else if (name.equals("char")) name = "C"; - else if(name.equals("double")) + else if (name.equals("double")) name = "D"; - else if(name.equals("float")) + else if (name.equals("float")) name = "F"; - else if(name.equals("int")) + else if (name.equals("int")) name = "I"; - else if(name.equals("long")) + else if (name.equals("long")) name = "J"; - else if(name.equals("short")) + else if (name.equals("short")) name = "S"; else primitive = false; - - if(nDims > 0) + + if (nDims > 0) { StringBuffer bld = new StringBuffer(); - while(--nDims >= 0) + while (--nDims >= 0) bld.append('['); - if(primitive) + if (primitive) bld.append(name); else { @@ -233,5 +240,5 @@ private native static Oid _getTypeId(); private native static String _getJavaClassName(int nativeOid) - throws SQLException; + throws SQLException; } Index: src/java/pljava/org/postgresql/pljava/internal/Session.java =================================================================== RCS file: /cvsroot/pljava/org.postgresql.pljava/src/java/pljava/org/postgresql/pljava/internal/Session.java,v retrieving revision 1.9 diff -u -r1.9 Session.java --- src/java/pljava/org/postgresql/pljava/internal/Session.java 6 May 2006 11:41:13 -0000 1.9 +++ src/java/pljava/org/postgresql/pljava/internal/Session.java 17 May 2010 19:50:49 -0000 @@ -17,16 +17,16 @@ import org.postgresql.pljava.TransactionListener; import org.postgresql.pljava.jdbc.SQLUtils; - /** * An instance of this interface reflects the current session. The attribute * store is transactional. - * + * * @author Thomas Hallgren */ public class Session implements org.postgresql.pljava.Session { - private final TransactionalMap m_attributes = new TransactionalMap(new HashMap()); + private final TransactionalMap m_attributes = new TransactionalMap( + new HashMap()); /** * Adds the specified listener to the list of listeners that will @@ -72,7 +72,6 @@ return AclId.getSessionUser().getName(); } - public void removeAttribute(String attributeName) { m_attributes.remove(attributeName); @@ -102,10 +101,10 @@ } public void executeAsSessionUser(Connection conn, String statement) - throws SQLException + throws SQLException { Statement stmt = conn.createStatement(); - synchronized(Backend.THREADLOCK) + synchronized (Backend.THREADLOCK) { ResultSet rs = null; AclId sessionUser = AclId.getSessionUser(); @@ -113,7 +112,7 @@ try { _setUser(sessionUser); - if(stmt.execute(statement)) + if (stmt.execute(statement)) { rs = stmt.getResultSet(); rs.next(); @@ -135,7 +134,7 @@ throws SQLException { ELogHandler.init(); - + // Should be replace with a Thread.getId() once we abandon // Java 1.4 // Index: src/java/test/org/postgresql/pljava/test/Tester.java =================================================================== RCS file: /cvsroot/pljava/org.postgresql.pljava/src/java/test/org/postgresql/pljava/test/Tester.java,v retrieving revision 1.24 diff -u -r1.24 Tester.java --- src/java/test/org/postgresql/pljava/test/Tester.java 14 May 2006 13:34:02 -0000 1.24 +++ src/java/test/org/postgresql/pljava/test/Tester.java 17 May 2010 19:50:51 -0000 @@ -6,16 +6,16 @@ */ package org.postgresql.pljava.test; -import java.sql.Timestamp; +import java.io.PrintStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; -import java.sql.Statement; import java.sql.SQLException; +import java.sql.Statement; +import java.sql.Timestamp; import java.util.ArrayList; import java.util.Arrays; import java.util.regex.Pattern; -import java.io.PrintStream; /** * Some fairly crude tests. All tests are confided to the schema @@ -45,7 +45,7 @@ private final Connection m_connection; - private static final ArrayList s_commands = new ArrayList(); + private static final ArrayList s_commands = new ArrayList(); static { @@ -62,11 +62,11 @@ { int top = s_commands.size(); int candidateCmd = CMD_UNKNOWN; - for(int idx = 0; idx < top; ++idx) + for (int idx = 0; idx < top; ++idx) { - if(((String)s_commands.get(idx)).startsWith(arg)) + if (((String) s_commands.get(idx)).startsWith(arg)) { - if(candidateCmd != CMD_UNKNOWN) + if (candidateCmd != CMD_UNKNOWN) return CMD_AMBIGUOUS; candidateCmd = idx; } @@ -81,12 +81,12 @@ out.println(" [ -host ] # default is localhost"); out.println(" [ -port ] # default is blank"); out - .println(" [ -database ] # default is name of current user"); + .println(" [ -database ] # default is name of current user"); out - .println(" [ -user ] # default is name of current user"); + .println(" [ -user ] # default is name of current user"); out.println(" [ -password ] # default is no password"); out - .println(" [ -exclude excludePattern ] # exclude tests matching pattern"); + .println(" [ -exclude excludePattern ] # exclude tests matching pattern"); out .println(" [ -debug ] # wait for debugger to attach to backend"); } @@ -104,92 +104,92 @@ boolean debug = false; int top = argv.length; - for(int idx = 0; idx < top; ++idx) + for (int idx = 0; idx < top; ++idx) { String arg = argv[idx]; - if(arg.length() < 2) + if (arg.length() < 2) { printUsage(); return; } - if(arg.charAt(0) == '-') + if (arg.charAt(0) == '-') { int optCmd = getCommand(arg.substring(1)); - switch(optCmd) + switch (optCmd) { - case CMD_DEBUG: - debug = true; - break; - - case CMD_USER: - if(++idx < top) - { - userName = argv[idx]; + case CMD_DEBUG: + debug = true; + break; + + case CMD_USER: + if (++idx < top) + { + userName = argv[idx]; if(userName.length() > 0 && userName.charAt(0) != '-') - break; - } - printUsage(); - return; - - case CMD_PASSWORD: - if(++idx < top) - { - password = argv[idx]; + break; + } + printUsage(); + return; + + case CMD_PASSWORD: + if (++idx < top) + { + password = argv[idx]; if(password.length() > 0 && password.charAt(0) != '-') - break; - } - printUsage(); - return; - - case CMD_DATABASE: - if(++idx < top) - { - database = argv[idx]; + break; + } + printUsage(); + return; + + case CMD_DATABASE: + if (++idx < top) + { + database = argv[idx]; if(database.length() > 0 && database.charAt(0) != '-') - break; - } - printUsage(); - return; - - case CMD_HOSTNAME: - if(++idx < top) - { - hostName = argv[idx]; + break; + } + printUsage(); + return; + + case CMD_HOSTNAME: + if (++idx < top) + { + hostName = argv[idx]; if(hostName.length() > 0 && hostName.charAt(0) != '-') - break; - } - printUsage(); - return; - - case CMD_EXCLUDE: - if(++idx < top) - { - exclude = argv[idx]; - if(exclude.length() > 0 && exclude.charAt(0) != '-') - break; - } - printUsage(); - return; - - case CMD_PORT: - if(++idx < top) - { - portNumber = argv[idx]; + break; + } + printUsage(); + return; + + case CMD_EXCLUDE: + if (++idx < top) + { + exclude = argv[idx]; + if (exclude.length() > 0 && exclude.charAt(0) != '-') + break; + } + printUsage(); + return; + + case CMD_PORT: + if (++idx < top) + { + portNumber = argv[idx]; if(portNumber.length() > 0 && portNumber.charAt(0) != '-') - break; - } - printUsage(); - return; - - default: - printUsage(); - return; + break; + } + printUsage(); + return; + + default: + printUsage(); + return; } } } @@ -202,7 +202,7 @@ cc.append(subsystem); cc.append("://"); cc.append(hostName); - if(portNumber != null) + if (portNumber != null) { cc.append(':'); cc.append(portNumber); @@ -210,56 +210,56 @@ cc.append('/'); cc.append(database); Connection c = DriverManager.getConnection(cc.toString(), userName, - password); + password); Tester t = new Tester(c); - if(debug) + if (debug) { System.out.println("Attach debugger to backend"); Thread.sleep(30000); System.out.println("continuing"); } - for(int idx = 0; idx < 10; ++idx) + for (int idx = 0; idx < 10; ++idx) { Pattern p = (exclude == null) ? null : Pattern.compile(exclude, Pattern.CASE_INSENSITIVE); - if(p == null || !p.matcher("parameters").matches()) + if (p == null || !p.matcher("parameters").matches()) t.testParameters(); - if(p == null || !p.matcher("usernametrigger").matches()) + if (p == null || !p.matcher("usernametrigger").matches()) t.testInsertUsernameTrigger(); - if(p == null || !p.matcher("moddatetimetrigger").matches()) + if (p == null || !p.matcher("moddatetimetrigger").matches()) t.testModdatetimeTrigger(); - if(p == null || !p.matcher("spiactions").matches()) + if (p == null || !p.matcher("spiactions").matches()) t.testSPIActions(); - if(p == null || !p.matcher("tuplereturn").matches()) + if (p == null || !p.matcher("tuplereturn").matches()) t.testTupleReturn(); - if(p == null || !p.matcher("setreturn").matches()) + if (p == null || !p.matcher("setreturn").matches()) t.testSetReturn(); - if(p == null || !p.matcher("callincall").matches()) + if (p == null || !p.matcher("callincall").matches()) t.testCallInCall(); - if(p == null || !p.matcher("currentdir").matches()) + if (p == null || !p.matcher("currentdir").matches()) t.testCurrentDir(); - if(p == null || !p.matcher("usingproperties").matches()) + if (p == null || !p.matcher("usingproperties").matches()) t.testUsingProperties(); - if(p == null || !p.matcher("usingscalarproperties").matches()) + if (p == null || !p.matcher("usingscalarproperties").matches()) t.testUsingScalarProperties(); - if(p == null || !p.matcher("usingresultsetproperties").matches()) + if (p == null || !p.matcher("usingresultsetproperties").matches()) t.testUsingResultSetProperties(); - if(p == null || !p.matcher("savepointsanity").matches()) + if (p == null || !p.matcher("savepointsanity").matches()) t.testSavepointSanity(); - if(p == null || !p.matcher("transactionrecovery").matches()) + if (p == null || !p.matcher("transactionrecovery").matches()) t.testTransactionRecovery(); - if(p == null || !p.matcher("trustedsecurity").matches()) + if (p == null || !p.matcher("trustedsecurity").matches()) t.testTrustedSecurity(); - if(p == null || !p.matcher("binarycolumns").matches()) + if (p == null || !p.matcher("binarycolumns").matches()) t.testBinaryColumns(); - if(p == null || !p.matcher("databasemetadata").matches()) + if (p == null || !p.matcher("databasemetadata").matches()) t.testDatabaseMetaData(); - if(p == null || !p.matcher("resultset").matches()) + if (p == null || !p.matcher("resultset").matches()) t.testResultSet(); - if(p == null || !p.matcher("complexscalar").matches()) + if (p == null || !p.matcher("complexscalar").matches()) t.testComplexScalar(); - if(p == null || !p.matcher("complextuple").matches()) + if (p == null || !p.matcher("complextuple").matches()) t.testComplexTuple(); } t.close(); @@ -297,24 +297,24 @@ stmt.execute("DELETE FROM employees1"); stmt.execute("DELETE FROM employees2"); stmt.execute("INSERT INTO employees1 VALUES(" - + "1, 'Calvin Forrester', 10000)"); + + "1, 'Calvin Forrester', 10000)"); stmt.execute("INSERT INTO employees1 VALUES(" + "2, 'Edwin Archer', 20000)"); stmt.execute("INSERT INTO employees1 VALUES(" - + "3, 'Rebecka Shawn', 30000)"); + + "3, 'Rebecka Shawn', 30000)"); stmt.execute("INSERT INTO employees1 VALUES(" - + "4, 'Priscilla Johnson', 25000)"); + + "4, 'Priscilla Johnson', 25000)"); stmt.execute("SELECT transferPeople(20000)"); ResultSet rs = stmt.executeQuery("SELECT * FROM employees2"); - while(rs.next()) + while (rs.next()) { int id = rs.getInt(1); String name = rs.getString(2); int salary = rs.getInt(3); System.out.println("Id = \"" + id + "\", name = \"" + name - + "\", salary = \"" + salary + "\""); + + "\", salary = \"" + salary + "\""); } rs.close(); } @@ -324,7 +324,7 @@ System.out.println("*** testTupleReturn()"); Statement stmt = m_connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT tupleReturnToString(tupleReturnExample(1, 5))"); - while(rs.next()) + while (rs.next()) { String str = rs.getString(1); System.out.println(str); @@ -332,7 +332,7 @@ rs.close(); rs = stmt.executeQuery("SELECT tupleReturnToString(tupleReturnExample2(1, NULL))"); - while(rs.next()) + while (rs.next()) { String str = rs.getString(1); System.out.println(str); @@ -345,8 +345,8 @@ System.out.println("*** testSetReturn()"); Statement stmt = m_connection.createStatement(); ResultSet rs = stmt - .executeQuery("SELECT base, incbase, ctime FROM setReturnExample(1, 5)"); - while(rs.next()) + .executeQuery("SELECT base, incbase, ctime FROM setReturnExample(1, 5)"); + while (rs.next()) { int base = rs.getInt(1); int incbase = rs.getInt(2); @@ -362,8 +362,8 @@ System.out.println("*** testUsingProperties()"); Statement stmt = m_connection.createStatement(); ResultSet rs = stmt - .executeQuery("SELECT name, value FROM propertyExample()"); - while(rs.next()) + .executeQuery("SELECT name, value FROM propertyExample()"); + while (rs.next()) { String name = rs.getString(1); String value = rs.getString(2); @@ -378,8 +378,8 @@ System.out.println("*** testUsingResultSetProperties()"); Statement stmt = m_connection.createStatement(); ResultSet rs = stmt - .executeQuery("SELECT name, value FROM resultSetPropertyExample()"); - while(rs.next()) + .executeQuery("SELECT name, value FROM resultSetPropertyExample()"); + while (rs.next()) { String name = rs.getString(1); String value = rs.getString(2); @@ -394,7 +394,7 @@ System.out.println("*** testUsingScalarProperties()"); Statement stmt = m_connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT scalarPropertyExample()"); - while(rs.next()) + while (rs.next()) System.out.println(rs.getString(1)); rs.close(); } @@ -405,11 +405,11 @@ Statement stmt = m_connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM binaryColumnTest()"); - while(rs.next()) + while (rs.next()) { byte[] b1 = rs.getBytes(1); byte[] b2 = rs.getBytes(2); - if(!Arrays.equals(b1, b2)) + if (!Arrays.equals(b1, b2)) throw new SQLException("binary columns differ"); } rs.close(); @@ -421,7 +421,7 @@ Statement stmt = m_connection.createStatement(); ResultSet rs = stmt .executeQuery("SELECT maxFromSetReturnExample(10, 8)"); - while(rs.next()) + while (rs.next()) { int max = rs.getInt(1); System.out.println("Max = \"" + max + "\""); @@ -438,13 +438,13 @@ stmt.execute("INSERT INTO mdt VALUES (3, 'third')"); ResultSet rs = stmt.executeQuery("SELECT * FROM mdt"); - while(rs.next()) + while (rs.next()) { int id = rs.getInt(1); String idesc = rs.getString(2); Timestamp moddate = rs.getTimestamp(3); System.out.println("Id = \"" + id + "\", idesc = \"" + idesc - + "\", moddate = \"" + moddate + "\""); + + "\", moddate = \"" + moddate + "\""); } rs.close(); @@ -453,13 +453,13 @@ stmt.execute("UPDATE mdt SET id = 6 WHERE id = 3"); rs = stmt.executeQuery("SELECT * FROM mdt"); - while(rs.next()) + while (rs.next()) { int id = rs.getInt(1); String idesc = rs.getString(2); Timestamp moddate = rs.getTimestamp(3); System.out.println("Id = \"" + id + "\", idesc = \"" + idesc - + "\", moddate = \"" + moddate + "\""); + + "\", moddate = \"" + moddate + "\""); } rs.close(); stmt.close(); @@ -478,7 +478,7 @@ stmt.execute("INSERT INTO username_test VALUES ('name', 'name')"); ResultSet rs = stmt.executeQuery("SELECT * FROM username_test"); - while(rs.next()) + while (rs.next()) { String name = rs.getString(1); String username = rs.getString(2); @@ -512,13 +512,13 @@ System.out.println("*** testTimestamp()"); Statement stmt = m_connection.createStatement(); ResultSet rs = stmt - .executeQuery("SELECT java_getTimestamp(), java_getTimestamptz()"); + .executeQuery("SELECT java_getTimestamp(), java_getTimestamptz()"); - if(!rs.next()) + if (!rs.next()) System.out.println("Unable to position ResultSet"); else System.out.println("Timestamp = " + rs.getTimestamp(1) - + ", Timestamptz = " + rs.getTimestamp(2)); + + ", Timestamptz = " + rs.getTimestamp(2)); rs.close(); // Test parameter overloading. Set log_min_messages (in posgresql.conf) @@ -543,18 +543,18 @@ */ Statement stmt = m_connection.createStatement(); ResultSet rs = stmt - .executeQuery("SELECT java_addOne(java_addOne(54)), nullOnEven(1), nullOnEven(2)"); - if(!rs.next()) + .executeQuery("SELECT java_addOne(java_addOne(54)), nullOnEven(1), nullOnEven(2)"); + if (!rs.next()) System.out.println("Unable to position ResultSet"); else { System.out.println("54 + 2 = " + rs.getInt(1)); int n = rs.getInt(2); System.out.println("nullOnEven(1) = " - + (rs.wasNull() ? "null" : Integer.toString(n))); + + (rs.wasNull() ? "null" : Integer.toString(n))); n = rs.getInt(3); System.out.println("nullOnEven(2) = " - + (rs.wasNull() ? "null" : Integer.toString(n))); + + (rs.wasNull() ? "null" : Integer.toString(n))); } rs.close(); stmt.close(); @@ -565,8 +565,8 @@ System.out.println("*** testComplexScalar()"); Statement stmt = m_connection.createStatement(); ResultSet rs = stmt - .executeQuery("SELECT logcomplex('(34.56,12.78)'::complex)"); - if(!rs.next()) + .executeQuery("SELECT logcomplex('(34.56,12.78)'::complex)"); + if (!rs.next()) System.out.println("Unable to position ResultSet"); else System.out.println(rs.getString(1)); @@ -579,8 +579,8 @@ System.out.println("*** testComplexTuple()"); Statement stmt = m_connection.createStatement(); ResultSet rs = stmt - .executeQuery("SELECT logcomplex((34.56,12.78)::complextuple)"); - if(!rs.next()) + .executeQuery("SELECT logcomplex((34.56,12.78)::complextuple)"); + if (!rs.next()) System.out.println("Unable to position ResultSet"); else System.out.println(rs.getString(1)); @@ -593,9 +593,9 @@ System.out.println("*** testCurrentDir()"); Statement stmt = m_connection.createStatement(); ResultSet rs = stmt - .executeQuery("SELECT java_getSystemProperty('user.dir')"); + .executeQuery("SELECT java_getSystemProperty('user.dir')"); - if(!rs.next()) + if (!rs.next()) System.out.println("Unable to position ResultSet"); else System.out.println("Server directory = " + rs.getString(1)); @@ -609,7 +609,7 @@ Statement stmt = m_connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT testSavepointSanity()"); - if(!rs.next()) + if (!rs.next()) System.out.println("Unable to position ResultSet"); else System.out.println("Savepoint sanity = " + rs.getInt(1)); @@ -623,7 +623,7 @@ Statement stmt = m_connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT testTransactionRecovery()"); - if(!rs.next()) + if (!rs.next()) System.out.println("Unable to position ResultSet"); else System.out.println("Transaction recovery = " + rs.getInt(1)); @@ -643,10 +643,10 @@ try { rs = stmt.executeQuery("SHOW IS_SUPERUSER"); - if(!(rs.next() && rs.getString(1).equals("on"))) + if (!(rs.next() && rs.getString(1).equals("on"))) { System.out - .println("Tester is not superuser so tests on untrusted language cannot be performed"); + .println("Tester is not superuser so tests on untrusted language cannot be performed"); return; } @@ -654,16 +654,16 @@ // System.out.println("*** testUntrustedSecurity()"); stmt - .execute("CREATE OR REPLACE FUNCTION javatest.create_temp_file_untrusted()" - + " RETURNS varchar" - + " AS 'org.postgresql.pljava.example.Security.createTempFile'" - + " LANGUAGE javaU"); + .execute("CREATE OR REPLACE FUNCTION javatest.create_temp_file_untrusted()" + + " RETURNS varchar" + + " AS 'org.postgresql.pljava.example.Security.createTempFile'" + + " LANGUAGE javaU"); tryCreateTempFile(false); } finally { - if(rs != null) + if (rs != null) { try { @@ -674,7 +674,7 @@ } rs = null; } - if(funcCreated) + if (funcCreated) stmt .execute("DROP FUNCTION javatest.create_temp_file_untrusted()"); stmt.close(); @@ -688,31 +688,31 @@ try { - if(trusted) + if (trusted) rs = stmt.executeQuery("SELECT create_temp_file_trusted()"); else rs = stmt.executeQuery("SELECT create_temp_file_untrusted()"); - if(!rs.next()) + if (!rs.next()) System.out.println("Unable to position ResultSet"); else System.out.println("Name of created temp file = " + rs.getString(1)); - if(trusted) + if (trusted) throw new RuntimeException( - "ERROR: Tempfile creation succeded although language is trusted!"); + "ERROR: Tempfile creation succeded although language is trusted!"); } catch(SQLException e) { - if(!trusted) + if (!trusted) throw e; System.out - .println("OK, creation of temp file was *unsuccessful* as it should be"); + .println("OK, creation of temp file was *unsuccessful* as it should be"); } finally { - if(rs != null) + if (rs != null) { try { @@ -737,7 +737,7 @@ System.out.println("*** DatabaseMetaData 'String' functions:"); rs = stmt .executeQuery("SELECT * FROM javatest.getMetaDataStrings()"); - while(rs.next()) + while (rs.next()) { String methodName = rs.getString(1); String methodResult = rs.getString(2); @@ -749,7 +749,7 @@ System.out.println("*** DatabaseMetaData 'boolean' functions:"); rs = stmt .executeQuery("SELECT * FROM javatest.getMetaDataBooleans()"); - while(rs.next()) + while (rs.next()) { String methodName = rs.getString(1); boolean methodResult = rs.getBoolean(2); @@ -760,7 +760,7 @@ System.out.println("*** DatabaseMetaData 'int' functions:"); rs = stmt.executeQuery("SELECT * FROM javatest.getMetaDataInts()"); - while(rs.next()) + while (rs.next()) { String methodName = rs.getString(1); int methodResult = rs.getInt(2); @@ -770,48 +770,48 @@ rs.close(); executeMetaDataFunction(stmt, - "getAttributes((String)null,\"javatest\",\"%\",\"%\")"); + "getAttributes((String)null,\"javatest\",\"%\",\"%\")"); executeMetaDataFunction(stmt, - "getBestRowIdentifier((String)null,\"sqlj\",\"jar_repository\",0,FALSE)"); + "getBestRowIdentifier((String)null,\"sqlj\",\"jar_repository\",0,FALSE)"); executeMetaDataFunction(stmt, "getCatalogs()"); executeMetaDataFunction(stmt, - "getColumnPrivileges((String)null,\"sqlj\",\"jar_repository\",\"jarid\")"); + "getColumnPrivileges((String)null,\"sqlj\",\"jar_repository\",\"jarid\")"); executeMetaDataFunction(stmt, - "getColumns((String)null,\"sqlj\",\"jar_repository\",\"%\")"); + "getColumns((String)null,\"sqlj\",\"jar_repository\",\"%\")"); executeMetaDataFunction( - stmt, - "getCrossReference((String)null,\"sqlj\",\"jar_repository\",(String)null,\"sqlj\",\"jar_entry\")"); + stmt, + "getCrossReference((String)null,\"sqlj\",\"jar_repository\",(String)null,\"sqlj\",\"jar_entry\")"); executeMetaDataFunction(stmt, - "getExportedKeys((String)null,\"sqlj\",\"jar_repository\")"); + "getExportedKeys((String)null,\"sqlj\",\"jar_repository\")"); executeMetaDataFunction(stmt, - "getImportedKeys((String)null,\"sqlj\",\"jar_repository\")"); + "getImportedKeys((String)null,\"sqlj\",\"jar_repository\")"); executeMetaDataFunction(stmt, - "getIndexInfo((String)null,\"sqlj\",\"jar_repository\",TRUE,FALSE)"); + "getIndexInfo((String)null,\"sqlj\",\"jar_repository\",TRUE,FALSE)"); executeMetaDataFunction(stmt, - "getPrimaryKeys((String)null,\"sqlj\",\"jar_repository\")"); + "getPrimaryKeys((String)null,\"sqlj\",\"jar_repository\")"); executeMetaDataFunction(stmt, - "getProcedureColumns((String)null,\"sqlj\",\"install_jar\",(String)null)"); + "getProcedureColumns((String)null,\"sqlj\",\"install_jar\",(String)null)"); executeMetaDataFunction(stmt, - "getProcedures((String)null,\"sqlj\",\"%\")"); + "getProcedures((String)null,\"sqlj\",\"%\")"); executeMetaDataFunction(stmt, "getSchemas()"); executeMetaDataFunction(stmt, - "getSuperTables((String)null,\"sqlj\",\"jar_repository\")"); + "getSuperTables((String)null,\"sqlj\",\"jar_repository\")"); executeMetaDataFunction(stmt, - "getSuperTypes((String)null,\"sqlj\",\"%\")"); + "getSuperTypes((String)null,\"sqlj\",\"%\")"); executeMetaDataFunction(stmt, - "getTablePrivileges((String)null,\"sqlj\",\"jar_repository\")"); + "getTablePrivileges((String)null,\"sqlj\",\"jar_repository\")"); executeMetaDataFunction(stmt, - "getTables((String)null,\"sqlj\",\"jar%\",{\"TABLE\"})"); + "getTables((String)null,\"sqlj\",\"jar%\",{\"TABLE\"})"); executeMetaDataFunction(stmt, "getTableTypes()"); executeMetaDataFunction(stmt, "getTypeInfo()"); executeMetaDataFunction(stmt, - "getUDTs((String)null,\"sqlj\",\"%\",(int[])null)"); + "getUDTs((String)null,\"sqlj\",\"%\",(int[])null)"); executeMetaDataFunction(stmt, - "getVersionColumns((String)null,\"sqlj\",\"jar_repository\")"); + "getVersionColumns((String)null,\"sqlj\",\"jar_repository\")"); } finally { - if(rs != null) + if (rs != null) { try { @@ -826,7 +826,7 @@ } private void executeMetaDataFunction(Statement stmt, String functionCall) - throws SQLException + throws SQLException { ResultSet rs = null; try @@ -835,7 +835,7 @@ rs = stmt .executeQuery("SELECT * FROM javatest.callMetaDataMethod('" + functionCall + "')"); - while(rs.next()) + while (rs.next()) { System.out.println(rs.getString(1)); } @@ -848,7 +848,7 @@ } finally { - if(rs != null) + if (rs != null) { try { @@ -872,15 +872,15 @@ { System.out.println("*** ResultSet test:"); sql = "SELECT * FROM javatest.executeSelect(" - + "'select ''Foo'' as t_varchar, 1::integer as t_integer, " - + "1.5::float as t_float, 23.67::decimal(8,2) as t_decimal, " - + "''2005-06-01''::date as t_date, ''20:56''::time as t_time, " - + "''2006-02-04 23:55:10''::timestamp as t_timestamp')"; + + "'select ''Foo'' as t_varchar, 1::integer as t_integer, " + + "1.5::float as t_float, 23.67::decimal(8,2) as t_decimal, " + + "''2005-06-01''::date as t_date, ''20:56''::time as t_time, " + + "''2006-02-04 23:55:10''::timestamp as t_timestamp')"; rs = stmt.executeQuery(sql); System.out.println("SQL = " + sql); System.out.println("results:"); - while(rs.next()) + while (rs.next()) { System.out.println(rs.getString(1)); } @@ -888,7 +888,7 @@ } finally { - if(rs != null) + if (rs != null) { try { Index: src/java/test/org/postgresql/pljava/test/TestPLJava.java =================================================================== RCS file: /cvsroot/pljava/org.postgresql.pljava/src/java/test/org/postgresql/pljava/test/TestPLJava.java,v retrieving revision 1.6 diff -u -r1.6 TestPLJava.java --- src/java/test/org/postgresql/pljava/test/TestPLJava.java 26 Feb 2006 15:22:48 -0000 1.6 +++ src/java/test/org/postgresql/pljava/test/TestPLJava.java 17 May 2010 19:50:51 -0000 @@ -14,35 +14,34 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; - /** * PL/Java Test harness - * + * * @author Thomas Hallgren */ public class TestPLJava { -// private static final int CMD_AMBIGUOUS = -2; -// private static final int CMD_UNKNOWN = -1; - private static final int CMD_PGSQLHOME = 0; - private static final int CMD_TESTDIR = 1; - private static final int CMD_PORT = 2; - - private static final ArrayList s_commands = new ArrayList(); - - private final File m_pgsqlHome; - private final File m_pljavaHome; - private final File m_pljavaBin; - private final File m_testHome; - private final int m_majorVer; - private final int m_minorVer; + // private static final int CMD_AMBIGUOUS = -2; + // private static final int CMD_UNKNOWN = -1; + private static final int CMD_PGSQLHOME = 0; + private static final int CMD_TESTDIR = 1; + private static final int CMD_PORT = 2; + + private static final ArrayList s_commands = new ArrayList(); + + private final File m_pgsqlHome; + private final File m_pljavaHome; + private final File m_pljavaBin; + private final File m_testHome; + private final int m_majorVer; + private final int m_minorVer; static { - s_commands.add(CMD_PGSQLHOME, "pgsqlhome"); - s_commands.add(CMD_TESTDIR, "testdir"); - s_commands.add(CMD_PORT, "port"); - } + s_commands.add(CMD_PGSQLHOME, "pgsqlhome"); + s_commands.add(CMD_TESTDIR, "testdir"); + s_commands.add(CMD_PORT, "port"); + } /* private static final int getCommand(String arg) { @@ -61,149 +60,149 @@ } */ public static void printUsage() { - PrintStream out = System.err; - out.println("usage: java org.postgresql.pljava.test.TestPLJava"); - out.println(" [ -port ] # default is 5432"); - out.println(" [ -pgsqlhome ] # default is /usr/local/pgsql"); - out.println(" [ -testdir ] # default is current directory"); - out.println(" [ -printenv ] # print the env for the postmaster"); - out.println(" [ -windows ] # If the server is on a Windows machine"); - } + PrintStream out = System.err; + out.println("usage: java org.postgresql.pljava.test.TestPLJava"); + out.println(" [ -port ] # default is 5432"); + out.println(" [ -pgsqlhome ] # default is /usr/local/pgsql"); + out.println(" [ -testdir ] # default is current directory"); + out.println(" [ -printenv ] # print the env for the postmaster"); + out.println(" [ -windows ] # If the server is on a Windows machine"); + } class KillPostmaster extends Thread { - - } + + } private int[] getPostgreSQLVersion() throws IOException { - // Get the PostgreSQL version using pg_ctl - // + // Get the PostgreSQL version using pg_ctl + // CommandReader pg_ctl = CommandReader.create( new String[] { "pg_ctl", "--version" }, this.getPostgresEnvironment().asArray()); - String verLine = pg_ctl.readLine(); - pg_ctl.close(); - int exitVal = pg_ctl.getExitValue(); - if(exitVal != 0) - throw new IOException("pg_ctl exit value " + exitVal); - - Pattern verPattern = Pattern.compile("\\D+(\\d+)\\.(\\d+)\\D"); - Matcher verMatcher = verPattern.matcher(verLine); - if(!verMatcher.lookingAt()) - throw new IOException("Unable to determine PostgreSQL version from " + verLine); + String verLine = pg_ctl.readLine(); + pg_ctl.close(); + int exitVal = pg_ctl.getExitValue(); + if (exitVal != 0) + throw new IOException("pg_ctl exit value " + exitVal); + + Pattern verPattern = Pattern.compile("\\D+(\\d+)\\.(\\d+)\\D"); + Matcher verMatcher = verPattern.matcher(verLine); + if (!verMatcher.lookingAt()) + throw new IOException("Unable to determine PostgreSQL version from " + verLine); return new int[] { Integer.parseInt(verMatcher.group(1)), Integer.parseInt(verMatcher.group(2)) }; - } + } public TestPLJava(String pgsqlHome, String pljavaHome) throws IOException { - m_pgsqlHome = new File(pgsqlHome); - m_pljavaHome = new File(pljavaHome); - m_testHome = new File(m_pljavaHome, "test"); - m_pljavaBin = new File(new File(new File(m_pljavaHome, "bin"), "build"), "pljava"); - - int[] ver = this.getPostgreSQLVersion(); - m_majorVer = ver[0]; - m_minorVer = ver[1]; - } + m_pgsqlHome = new File(pgsqlHome); + m_pljavaHome = new File(pljavaHome); + m_testHome = new File(m_pljavaHome, "test"); + m_pljavaBin = new File(new File(new File(m_pljavaHome, "bin"), "build"), "pljava"); + + int[] ver = this.getPostgreSQLVersion(); + m_majorVer = ver[0]; + m_minorVer = ver[1]; + } class Postmaster extends Thread { Postmaster() { - } + } - public void run() - { - List args = new ArrayList(); - args.add("postmaster"); - args.add("-D"); - args.add(new File(m_testHome, "db").getAbsolutePath()); + @Override + public void run() { + List args = new ArrayList(); + args.add("postmaster"); + args.add("-D"); + args.add(new File(m_testHome, "db").getAbsolutePath()); if(m_minorVer < 5) { - args.add("-c"); - args.add("tcpip_socket=true"); + args.add("-c"); + args.add("tcpip_socket=true"); } else { - args.add("-c"); - args.add("custom_variable_classes=pljava"); - } - args.add("-c"); - args.add("log_min_messages=debug1"); - args.add("-c"); - args.add("dynamic_library_path=" + m_pljavaBin.getAbsolutePath()); - - Runtime rt = Runtime.getRuntime(); - KillPostmaster killer = new KillPostmaster(); - rt.addShutdownHook(killer); + args.add("-c"); + args.add("custom_variable_classes=pljava"); + } + args.add("-c"); + args.add("log_min_messages=debug1"); + args.add("-c"); + args.add("dynamic_library_path=" + m_pljavaBin.getAbsolutePath()); + + Runtime rt = Runtime.getRuntime(); + KillPostmaster killer = new KillPostmaster(); + rt.addShutdownHook(killer); try { - rt.exec((String[])args.toArray(new String[args.size()])); + rt.exec((String[]) args.toArray(new String[args.size()])); } catch(IOException e) { - - } - rt.removeShutdownHook(killer); - } - } + } + rt.removeShutdownHook(killer); + + } + } public Environment getPostgresEnvironment() throws IOException { - Environment env = new Environment(); - Path path = new Path(env.get("PATH")); - File pgsqlBin = new File(m_pgsqlHome, "bin"); - File pgsqlLib = new File(m_pgsqlHome, "lib"); + Environment env = new Environment(); + Path path = new Path(env.get("PATH")); + File pgsqlBin = new File(m_pgsqlHome, "bin"); + File pgsqlLib = new File(m_pgsqlHome, "lib"); - if(Environment.isWindows()) - path.addFirst(pgsqlLib); + if (Environment.isWindows()) + path.addFirst(pgsqlLib); else { - Path ldPath = new Path(env.get("LD_LIBRARY_PATH")); - ldPath.addFirst(pgsqlLib); - env.put("LD_LIBRARY_PATH", ldPath.toString()); - } - - path.addFirst(pgsqlBin); - env.put("PATH", path.toString()); - return env; - } + Path ldPath = new Path(env.get("LD_LIBRARY_PATH")); + ldPath.addFirst(pgsqlLib); + env.put("LD_LIBRARY_PATH", ldPath.toString()); + } + + path.addFirst(pgsqlBin); + env.put("PATH", path.toString()); + return env; + } public static void main(String[] args) { try { - TestPLJava tpj = new TestPLJava("c:\\msys\\local\\pgsql", "c:\\"); - System.out.println(tpj.getPostgresEnvironment()); + TestPLJava tpj = new TestPLJava("c:\\msys\\local\\pgsql", "c:\\"); + System.out.println(tpj.getPostgresEnvironment()); } catch(Exception e) { - e.printStackTrace(); - } - } - + e.printStackTrace(); + } + } + public void initdb() { - - } + + } public final int getMajorVer() { - return m_majorVer; - } - + return m_majorVer; + } + public final int getMinorVer() { - return m_minorVer; - } - + return m_minorVer; + } + } Index: src/java/test/org/postgresql/pljava/test/Environment.java =================================================================== RCS file: /cvsroot/pljava/org.postgresql.pljava/src/java/test/org/postgresql/pljava/test/Environment.java,v retrieving revision 1.3 diff -u -r1.3 Environment.java --- src/java/test/org/postgresql/pljava/test/Environment.java 23 Jan 2005 13:56:16 -0000 1.3 +++ src/java/test/org/postgresql/pljava/test/Environment.java 17 May 2010 19:50:51 -0000 @@ -24,12 +24,12 @@ private static final Pattern s_envPattern = Pattern.compile("^(\\w+)=(.*)$"); private static final boolean s_isWindows; - private final TreeMap m_env; + private final TreeMap m_env; static { - Pattern osPattern = Pattern.compile("^windows\\W", Pattern.CASE_INSENSITIVE); - s_isWindows = osPattern.matcher(System.getProperty("os.name")).lookingAt(); + Pattern osPattern = Pattern.compile("^windows\\W", Pattern.CASE_INSENSITIVE); + s_isWindows = osPattern.matcher(System.getProperty("os.name")).lookingAt(); } private static String getEnvCommand() @@ -45,21 +45,21 @@ public Environment() throws IOException { - String line; - TreeMap env = new TreeMap(); + String line; + TreeMap env = new TreeMap(); m_env = env; - Process proc = Runtime.getRuntime().exec(getEnvCommand()); + Process proc = Runtime.getRuntime().exec(getEnvCommand()); BufferedReader lr = new BufferedReader(new InputStreamReader(proc.getInputStream())); - while((line = lr.readLine()) != null) + while ((line = lr.readLine()) != null) { Matcher matcher = s_envPattern.matcher(line); - if(matcher.matches()) + if (matcher.matches()) { String key = matcher.group(1); String val = matcher.group(2); - if(s_isWindows) + if (s_isWindows) env.put(key.toLowerCase(), new String[] { key, val } ); else env.put(key, val); @@ -69,21 +69,21 @@ public String get(String key) { - if(s_isWindows) + if (s_isWindows) { - String[] entry = (String[])m_env.get(key.toLowerCase()); + String[] entry = (String[]) m_env.get(key.toLowerCase()); return (entry == null) ? null : entry[1]; } - return (String)m_env.get(key); + return (String) m_env.get(key); } public void put(String key, String val) { - if(s_isWindows) + if (s_isWindows) { String lowKey = key.toLowerCase(); - String[] entry = (String[])m_env.get(lowKey); - if(entry == null) + String[] entry = (String[]) m_env.get(lowKey); + if (entry == null) m_env.put(lowKey, new String[] { key, val }); else entry[1] = val; @@ -95,14 +95,14 @@ public String[] asArray() { StringBuffer bld = new StringBuffer(); - ArrayList envArr = new ArrayList(); + ArrayList envArr = new ArrayList(); Iterator itor = m_env.entrySet().iterator(); - while(itor.hasNext()) + while (itor.hasNext()) { - Map.Entry entry = (Map.Entry)itor.next(); - if(s_isWindows) + Map.Entry entry = (Map.Entry) itor.next(); + if (s_isWindows) { - String[] kv = (String[])entry.getValue(); + String[] kv = (String[]) entry.getValue(); bld.append(kv[0]); bld.append('='); bld.append(kv[1]); @@ -116,20 +116,21 @@ envArr.add(bld.toString()); bld.setLength(0); } - return (String[])envArr.toArray(new String[envArr.size()]); + return (String[]) envArr.toArray(new String[envArr.size()]); } - + + @Override public String toString() { StringBuffer bld = new StringBuffer(); String newLine = System.getProperty("line.separator"); Iterator itor = m_env.entrySet().iterator(); - while(itor.hasNext()) + while (itor.hasNext()) { - Map.Entry entry = (Map.Entry)itor.next(); - if(s_isWindows) + Map.Entry entry = (Map.Entry) itor.next(); + if (s_isWindows) { - String[] kv = (String[])entry.getValue(); + String[] kv = (String[]) entry.getValue(); bld.append(kv[0]); bld.append(" = "); bld.append(kv[1]); Index: src/java/test/org/postgresql/pljava/test/Path.java =================================================================== RCS file: /cvsroot/pljava/org.postgresql.pljava/src/java/test/org/postgresql/pljava/test/Path.java,v retrieving revision 1.2 diff -u -r1.2 Path.java --- src/java/test/org/postgresql/pljava/test/Path.java 23 Jan 2005 13:56:16 -0000 1.2 +++ src/java/test/org/postgresql/pljava/test/Path.java 17 May 2010 19:50:51 -0000 @@ -11,12 +11,12 @@ /** * PL/Java Test harness - * + * * @author Thomas Hallgren */ -public class Path +public class Path { - public final ArrayList m_path; + public final ArrayList m_path; public Path(String path) { @@ -24,62 +24,62 @@ if(path != null) { - char pathSep = File.pathSeparatorChar; - int sep = path.indexOf(pathSep); + char pathSep = File.pathSeparatorChar; + int sep = path.indexOf(pathSep); while(sep >= 0) { - if(sep > 0) - this.addLast(new File(path.substring(0, sep))); - path = path.substring(sep + 1); - sep = path.indexOf(pathSep); - } - if(path.length() > 0) - this.addLast(new File(path)); - } - } + if (sep > 0) + this.addLast(new File(path.substring(0, sep))); + path = path.substring(sep + 1); + sep = path.indexOf(pathSep); + } + if (path.length() > 0) + this.addLast(new File(path)); + } + } public void addFirst(File dir) { - int pos = m_path.indexOf(dir); + int pos = m_path.indexOf(dir); if(pos >= 0) { - if(pos == 0) - return; - m_path.remove(pos); - } - m_path.add(0, dir); - } + if (pos == 0) + return; + m_path.remove(pos); + } + m_path.add(0, dir); + } public void addLast(File dir) { - int pos = m_path.indexOf(dir); + int pos = m_path.indexOf(dir); if(pos >= 0) { - if(pos == m_path.size() - 1) - return; - m_path.remove(pos); - } - m_path.add(dir); - } - - public String toString() - { - int top = m_path.size(); - if(top == 0) - return ""; - - String first = m_path.get(0).toString(); - if(top == 1) - return first; - - StringBuffer bld = new StringBuffer(); - char pathSep = File.pathSeparatorChar; - bld.append(first); + if (pos == m_path.size() - 1) + return; + m_path.remove(pos); + } + m_path.add(dir); + } + + @Override + public String toString() { + int top = m_path.size(); + if (top == 0) + return ""; + + String first = m_path.get(0).toString(); + if (top == 1) + return first; + + StringBuffer bld = new StringBuffer(); + char pathSep = File.pathSeparatorChar; + bld.append(first); for(int idx = 1; idx < top; ++idx) { - bld.append(pathSep); - bld.append(m_path.get(idx)); - } - return bld.toString(); - } + bld.append(pathSep); + bld.append(m_path.get(idx)); + } + return bld.toString(); + } } Index: src/java/Makefile.global =================================================================== RCS file: /cvsroot/pljava/org.postgresql.pljava/src/java/Makefile.global,v retrieving revision 1.9 diff -u -r1.9 Makefile.global --- src/java/Makefile.global 11 Feb 2006 13:57:51 -0000 1.9 +++ src/java/Makefile.global 17 May 2010 19:50:48 -0000 @@ -14,7 +14,8 @@ GCJ := gcj JAVAC := $(GCJ) -C else - JAVAC := javac -source 1.4 -target 1.4 + JAVAC := javac +#-source 1.6 -target 1.6 endif JARFILE := $(TARGETDIR)/$(NAME).jar Index: src/java/pljava/org/postgresql/pljava/management/Commands.java =================================================================== RCS file: /cvsroot/pljava/org.postgresql.pljava/src/java/pljava/org/postgresql/pljava/management/Commands.java,v retrieving revision 1.18 diff -u -r1.18 Commands.java --- src/java/pljava/org/postgresql/pljava/management/Commands.java 15 Nov 2007 20:08:08 -0000 1.18 +++ src/java/pljava/org/postgresql/pljava/management/Commands.java 17 May 2010 19:50:51 -0000 @@ -45,7 +45,7 @@ *
        * * - * + * * * * @@ -91,7 +91,7 @@ *
        jar_urlThe URL that denotes the location of the jar that should be loaded The URL that denotes the location of the jar that should be loaded
        jar_name
        * * - * + * * * * @@ -232,7 +232,7 @@ * @throws SQLException */ public static void addClassImages(int jarId, InputStream urlStream) - throws SQLException + throws SQLException { PreparedStatement stmt = null; PreparedStatement descIdStmt = null; @@ -244,27 +244,27 @@ byte[] buf = new byte[1024]; ByteArrayOutputStream img = new ByteArrayOutputStream(); stmt = SQLUtils - .getDefaultConnection() - .prepareStatement( - "INSERT INTO sqlj.jar_entry(entryName, jarId, entryImage) VALUES(?, ?, ?)"); + .getDefaultConnection() + .prepareStatement( + "INSERT INTO sqlj.jar_entry(entryName, jarId, entryImage) VALUES(?, ?, ?)"); JarInputStream jis = new JarInputStream(urlStream); Manifest manifest = jis.getManifest(); - if(manifest != null) + if (manifest != null) { ByteArrayOutputStream out = new ByteArrayOutputStream(); manifest.write(out); PreparedStatement us = SQLUtils - .getDefaultConnection() - .prepareStatement( - "UPDATE sqlj.jar_repository SET jarManifest = ? WHERE jarId = ?"); + .getDefaultConnection() + .prepareStatement( + "UPDATE sqlj.jar_repository SET jarManifest = ? WHERE jarId = ?"); try { us.setString(1, new String(out.toByteArray(), "UTF8")); us.setInt(2, jarId); - if(us.executeUpdate() != 1) + if (us.executeUpdate() != 1) throw new SQLException( - "Jar repository update did not update 1 row"); + "Jar repository update did not update 1 row"); } catch(UnsupportedEncodingException e) { @@ -277,76 +277,76 @@ SQLUtils.close(us); } } - for(;;) + for (;;) { JarEntry je = jis.getNextJarEntry(); - if(je == null) + if (je == null) break; - if(je.isDirectory()) + if (je.isDirectory()) continue; String entryName = je.getName(); Attributes attrs = je.getAttributes(); boolean isDepDescr = false; - if(attrs != null) + if (attrs != null) { isDepDescr = "true".equalsIgnoreCase(attrs - .getValue("SQLJDeploymentDescriptor")); + .getValue("SQLJDeploymentDescriptor")); - if(isDepDescr && deployImageId >= 0) + if (isDepDescr && deployImageId >= 0) throw new SQLException( - "Only one SQLJDeploymentDescriptor allowed"); + "Only one SQLJDeploymentDescriptor allowed"); } int nBytes; img.reset(); - while((nBytes = jis.read(buf)) > 0) + while ((nBytes = jis.read(buf)) > 0) img.write(buf, 0, nBytes); jis.closeEntry(); stmt.setString(1, entryName); stmt.setInt(2, jarId); stmt.setBytes(3, img.toByteArray()); - if(stmt.executeUpdate() != 1) + if (stmt.executeUpdate() != 1) throw new SQLException( "Jar entry insert did not insert 1 row"); - if(isDepDescr) + if (isDepDescr) { descIdStmt = SQLUtils.getDefaultConnection() .prepareStatement( "SELECT entryId FROM sqlj.jar_entry" - + " WHERE jarId = ? AND entryName = ?"); + + " WHERE jarId = ? AND entryName = ?"); descIdStmt.setInt(1, jarId); descIdStmt.setString(2, entryName); rs = descIdStmt.executeQuery(); - if(!rs.next()) + if (!rs.next()) throw new SQLException( - "Failed to refecth row in sqlj.jar_entry"); + "Failed to refecth row in sqlj.jar_entry"); deployImageId = rs.getInt(1); } } - if(deployImageId >= 0) + if (deployImageId >= 0) { stmt.close(); stmt = SQLUtils - .getDefaultConnection() - .prepareStatement( - "UPDATE sqlj.jar_repository SET deploymentDesc = ? WHERE jarId = ?"); + .getDefaultConnection() + .prepareStatement( + "UPDATE sqlj.jar_repository SET deploymentDesc = ? WHERE jarId = ?"); stmt.setInt(1, deployImageId); stmt.setInt(2, jarId); - if(stmt.executeUpdate() != 1) + if (stmt.executeUpdate() != 1) throw new SQLException( - "Jar repository update did not insert 1 row"); + "Jar repository update did not insert 1 row"); } } catch(IOException e) { throw new SQLException("I/O exception reading jar file: " - + e.getMessage()); + + e.getMessage()); } finally { @@ -368,16 +368,16 @@ * @throws SQLException */ public static void addTypeMapping(String sqlTypeName, String javaClassName) - throws SQLException + throws SQLException { PreparedStatement stmt = null; try { ClassLoader loader = Loader.getCurrentLoader(); Class cls = loader.loadClass(javaClassName); - if(!SQLData.class.isAssignableFrom(cls)) + if (!SQLData.class.isAssignableFrom(cls)) throw new SQLException("Class " + javaClassName - + " does not implement java.sql.SQLData"); + + " does not implement java.sql.SQLData"); sqlTypeName = getFullSqlName(sqlTypeName); stmt = SQLUtils @@ -415,7 +415,7 @@ { sqlTypeName = getFullSqlName(sqlTypeName); stmt = SQLUtils.getDefaultConnection().prepareStatement( - "DELETE FROM sqlj.typemap_entry WHERE sqlName = ?"); + "DELETE FROM sqlj.typemap_entry WHERE sqlName = ?"); stmt.setString(1, sqlTypeName); stmt.executeUpdate(); } @@ -442,24 +442,24 @@ PreparedStatement stmt = null; try { - if(schemaName == null || schemaName.length() == 0) + if (schemaName == null || schemaName.length() == 0) schemaName = "public"; else schemaName = schemaName.toLowerCase(); stmt = SQLUtils - .getDefaultConnection() - .prepareStatement( - "SELECT r.jarName" - + " FROM sqlj.jar_repository r INNER JOIN sqlj.classpath_entry c ON r.jarId = c.jarId" - + " WHERE c.schemaName = ? ORDER BY c.ordinal"); + .getDefaultConnection() + .prepareStatement( + "SELECT r.jarName" + + " FROM sqlj.jar_repository r INNER JOIN sqlj.classpath_entry c ON r.jarId = c.jarId" + + " WHERE c.schemaName = ? ORDER BY c.ordinal"); stmt.setString(1, schemaName); rs = stmt.executeQuery(); StringBuffer buf = null; - while(rs.next()) + while (rs.next()) { - if(buf == null) + if (buf == null) buf = new StringBuffer(); else buf.append(':'); @@ -481,7 +481,7 @@ try { rs = stmt.executeQuery("SELECT current_schema()"); - if(!rs.next()) + if (!rs.next()) throw new SQLException("Unable to obtain current schema"); return rs.getString(1); } @@ -508,7 +508,7 @@ * @see #setClassPath */ public static void installJar(byte[] image, String jarName, boolean deploy) - throws SQLException + throws SQLException { installJar("streamed byte image", jarName, deploy, image); } @@ -546,21 +546,21 @@ * @throws SQLException if the named jar cannot be found in the repository. */ public static void removeJar(String jarName, boolean undeploy) - throws SQLException + throws SQLException { assertJarName(jarName); AclId[] ownerRet = new AclId[1]; int jarId = getJarId(jarName, ownerRet); - if(jarId < 0) + if (jarId < 0) throw new SQLException("No Jar named '" + jarName - + "' is known to the system"); + + "' is known to the system"); AclId user = AclId.getSessionUser(); - if(!(user.isSuperuser() || user.equals(ownerRet[0]))) + if (!(user.isSuperuser() || user.equals(ownerRet[0]))) throw new SecurityException( "Only super user or owner can remove a jar"); - if(undeploy) + if (undeploy) deployRemove(jarId, jarName); PreparedStatement stmt = SQLUtils @@ -569,7 +569,7 @@ try { stmt.setInt(1, jarId); - if(stmt.executeUpdate() != 1) + if (stmt.executeUpdate() != 1) throw new SQLException( "Jar repository update did not update 1 row"); } @@ -630,45 +630,45 @@ * file. */ public static void setClassPath(String schemaName, String path) - throws SQLException + throws SQLException { - if(schemaName == null || schemaName.length() == 0) + if (schemaName == null || schemaName.length() == 0) schemaName = "public"; - if("public".equals(schemaName)) + if ("public".equals(schemaName)) { - if(!AclId.getSessionUser().isSuperuser()) + if (!AclId.getSessionUser().isSuperuser()) throw new SQLException( - "Permission denied. Only a super user can set the classpath of the public schema"); + "Permission denied. Only a super user can set the classpath of the public schema"); } else { schemaName = schemaName.toLowerCase(); Oid schemaId = getSchemaId(schemaName); - if(schemaId == null) + if (schemaId == null) throw new SQLException("No such schema: " + schemaName); - if(!AclId.getSessionUser().hasSchemaCreatePermission(schemaId)) + if (!AclId.getSessionUser().hasSchemaCreatePermission(schemaId)) throw new SQLException( - "Permission denied. User must have create permission on the target schema in order to set the classpath"); + "Permission denied. User must have create permission on the target schema in order to set the classpath"); } PreparedStatement stmt; - ArrayList entries = null; - if(path != null && path.length() > 0) + ArrayList entries = null; + if (path != null && path.length() > 0) { // Collect and verify that all entries in the path represents a // valid jar // - entries = new ArrayList(); + entries = new ArrayList(); stmt = SQLUtils.getDefaultConnection().prepareStatement( - "SELECT jarId FROM sqlj.jar_repository WHERE jarName = ?"); + "SELECT jarId FROM sqlj.jar_repository WHERE jarName = ?"); try { - for(;;) + for (;;) { int colon = path.indexOf(':'); String jarName; - if(colon >= 0) + if (colon >= 0) { jarName = path.substring(0, colon); path = path.substring(colon + 1); @@ -677,11 +677,11 @@ jarName = path; int jarId = getJarId(stmt, jarName, null); - if(jarId < 0) + if (jarId < 0) throw new SQLException("No such jar: " + jarName); entries.add(new Integer(jarId)); - if(colon < 0) + if (colon < 0) break; } } @@ -694,7 +694,7 @@ // Delete the old classpath // stmt = SQLUtils.getDefaultConnection().prepareStatement( - "DELETE FROM sqlj.classpath_entry WHERE schemaName = ?"); + "DELETE FROM sqlj.classpath_entry WHERE schemaName = ?"); try { stmt.setString(1, schemaName); @@ -705,20 +705,20 @@ SQLUtils.close(stmt); } - if(entries != null) + if (entries != null) { // Insert the new path. // stmt = SQLUtils - .getDefaultConnection() - .prepareStatement( - "INSERT INTO sqlj.classpath_entry(schemaName, ordinal, jarId) VALUES(?, ?, ?)"); + .getDefaultConnection() + .prepareStatement( + "INSERT INTO sqlj.classpath_entry(schemaName, ordinal, jarId) VALUES(?, ?, ?)"); try { int top = entries.size(); - for(int idx = 0; idx < top; ++idx) + for (int idx = 0; idx < top; ++idx) { - int jarId = ((Integer)entries.get(idx)).intValue(); + int jarId = ((Integer) entries.get(idx)).intValue(); stmt.setString(1, schemaName); stmt.setInt(2, idx + 1); stmt.setInt(3, jarId); @@ -734,13 +734,13 @@ } private static boolean assertInPath(String jarName, - String[] originalSchemaAndPath) throws SQLException + String[] originalSchemaAndPath) throws SQLException { String currentSchema = getCurrentSchema(); String currentClasspath = getClassPath(currentSchema); originalSchemaAndPath[0] = currentSchema; originalSchemaAndPath[1] = currentClasspath; - if(currentClasspath == null) + if (currentClasspath == null) { setClassPath(currentSchema, jarName); return true; @@ -749,14 +749,14 @@ String[] elems = currentClasspath.split(":"); int idx = elems.length; boolean found = false; - while(--idx >= 0) - if(elems[idx].equals(jarName)) + while (--idx >= 0) + if (elems[idx].equals(jarName)) { found = true; break; } - if(found) + if (found) return false; setClassPath(currentSchema, jarName + ':' + currentClasspath); @@ -772,17 +772,17 @@ */ private static void assertJarName(String jarName) throws SQLException { - if(jarName != null) + if (jarName != null) { int len = jarName.length(); - if(len > 0 && Character.isJavaIdentifierStart(jarName.charAt(0))) + if (len > 0 && Character.isJavaIdentifierStart(jarName.charAt(0))) { int idx = 1; - for(; idx < len; ++idx) - if(!Character.isJavaIdentifierPart(jarName.charAt(idx))) + for (; idx < len; ++idx) + if (!Character.isJavaIdentifierPart(jarName.charAt(idx))) break; - if(idx == len) + if (idx == len) return; } } @@ -794,13 +794,13 @@ throws SQLException { SQLDeploymentDescriptor depDesc = getDeploymentDescriptor(jarId); - if(depDesc == null) + if (depDesc == null) return; String[] originalSchemaAndPath = new String[2]; boolean classpathChanged = assertInPath(jarName, originalSchemaAndPath); depDesc.install(SQLUtils.getDefaultConnection()); - if(classpathChanged) + if (classpathChanged) setClassPath(originalSchemaAndPath[0], originalSchemaAndPath[1]); } @@ -808,42 +808,42 @@ throws SQLException { SQLDeploymentDescriptor depDesc = getDeploymentDescriptor(jarId); - if(depDesc == null) + if (depDesc == null) return; String[] originalSchemaAndPath = new String[2]; boolean classpathChanged = assertInPath(jarName, originalSchemaAndPath); depDesc.remove(SQLUtils.getDefaultConnection()); - if(classpathChanged) + if (classpathChanged) setClassPath(originalSchemaAndPath[0], originalSchemaAndPath[1]); } private static SQLDeploymentDescriptor getDeploymentDescriptor(int jarId) - throws SQLException + throws SQLException { ResultSet rs = null; PreparedStatement stmt = SQLUtils.getDefaultConnection() .prepareStatement( "SELECT e.entryImage" - + " FROM sqlj.jar_repository r INNER JOIN sqlj.jar_entry e" - + " ON r.deploymentDesc = e.entryId" - + " WHERE r.jarId = ?"); + + " FROM sqlj.jar_repository r INNER JOIN sqlj.jar_entry e" + + " ON r.deploymentDesc = e.entryId" + + " WHERE r.jarId = ?"); try { stmt.setInt(1, jarId); rs = stmt.executeQuery(); - if(!rs.next()) + if (!rs.next()) return null; byte[] bytes = rs.getBytes(1); - if(bytes.length == 0) + if (bytes.length == 0) return null; // Accodring to the SQLJ standard, this entry must be // UTF8 encoded. // return new SQLDeploymentDescriptor(new String(bytes, "UTF8"), - "postgresql"); + "postgresql"); } catch(UnsupportedEncodingException e) { @@ -872,13 +872,13 @@ PreparedStatement stmt = SQLUtils.getDefaultConnection() .prepareStatement( "SELECT n.nspname, t.typname FROM pg_type t, pg_namespace n" - + " WHERE t.oid = ? AND n.oid = t.typnamespace"); + + " WHERE t.oid = ? AND n.oid = t.typnamespace"); try { stmt.setObject(1, typeId); rs = stmt.executeQuery(); - if(!rs.next()) + if (!rs.next()) throw new SQLException("Unable to obtain type info for " + typeId); @@ -892,16 +892,16 @@ } private static int getJarId(PreparedStatement stmt, String jarName, - AclId[] ownerRet) throws SQLException + AclId[] ownerRet) throws SQLException { stmt.setString(1, jarName); ResultSet rs = stmt.executeQuery(); try { - if(!rs.next()) + if (!rs.next()) return -1; int id = rs.getInt(1); - if(ownerRet != null) + if (ownerRet != null) { String ownerName = rs.getString(2); ownerRet[0] = AclId.fromName(ownerName); @@ -924,7 +924,7 @@ * @throws SQLException */ private static int getJarId(String jarName, AclId[] ownerRet) - throws SQLException + throws SQLException { PreparedStatement stmt = SQLUtils .getDefaultConnection() @@ -958,9 +958,9 @@ { stmt.setString(1, schemaName); rs = stmt.executeQuery(); - if(!rs.next()) + if (!rs.next()) return null; - return (Oid)rs.getObject(1); + return (Oid) rs.getObject(1); } finally { @@ -974,20 +974,20 @@ { assertJarName(jarName); - if(getJarId(jarName, null) >= 0) + if (getJarId(jarName, null) >= 0) throw new SQLException("A jar named '" + jarName + "' already exists"); PreparedStatement stmt = SQLUtils - .getDefaultConnection() - .prepareStatement( - "INSERT INTO sqlj.jar_repository(jarName, jarOrigin, jarOwner) VALUES(?, ?, ?)"); + .getDefaultConnection() + .prepareStatement( + "INSERT INTO sqlj.jar_repository(jarName, jarOrigin, jarOwner) VALUES(?, ?, ?)"); try { stmt.setString(1, jarName); stmt.setString(2, urlString); stmt.setString(3, AclId.getSessionUser().getName()); - if(stmt.executeUpdate() != 1) + if (stmt.executeUpdate() != 1) throw new SQLException( "Jar repository insert did not insert 1 row"); } @@ -998,10 +998,10 @@ AclId[] ownerRet = new AclId[1]; int jarId = getJarId(jarName, ownerRet); - if(jarId < 0) + if (jarId < 0) throw new SQLException("Unable to obtain id of '" + jarName + "'"); - if(image == null) + if (image == null) Backend.addClassImages(jarId, urlString); else { @@ -1009,37 +1009,37 @@ addClassImages(jarId, imageStream); } Loader.clearSchemaLoaders(); - if(deploy) + if (deploy) deployInstall(jarId, jarName); } private static void replaceJar(String urlString, String jarName, - boolean redeploy, byte[] image) throws SQLException + boolean redeploy, byte[] image) throws SQLException { AclId[] ownerRet = new AclId[1]; int jarId = getJarId(jarName, ownerRet); - if(jarId < 0) + if (jarId < 0) throw new SQLException("No Jar named '" + jarName - + "' is known to the system"); + + "' is known to the system"); AclId user = AclId.getSessionUser(); - if(!(user.isSuperuser() || user.equals(ownerRet[0]))) + if (!(user.isSuperuser() || user.equals(ownerRet[0]))) throw new SecurityException( "Only super user or owner can replace a jar"); - if(redeploy) + if (redeploy) deployRemove(jarId, jarName); PreparedStatement stmt = SQLUtils - .getDefaultConnection() - .prepareStatement( - "UPDATE sqlj.jar_repository SET jarOrigin = ?, jarOwner = ?, jarManifest = NULL, deploymentDesc = NULL WHERE jarId = ?"); + .getDefaultConnection() + .prepareStatement( + "UPDATE sqlj.jar_repository SET jarOrigin = ?, jarOwner = ?, jarManifest = NULL, deploymentDesc = NULL WHERE jarId = ?"); try { stmt.setString(1, urlString); stmt.setString(2, user.getName()); stmt.setInt(3, jarId); - if(stmt.executeUpdate() != 1) + if (stmt.executeUpdate() != 1) throw new SQLException( "Jar repository update did not update 1 row"); } @@ -1049,7 +1049,7 @@ } stmt = SQLUtils.getDefaultConnection().prepareStatement( - "DELETE FROM sqlj.jar_entry WHERE jarId = ?"); + "DELETE FROM sqlj.jar_entry WHERE jarId = ?"); try { stmt.setInt(1, jarId); @@ -1059,7 +1059,7 @@ { SQLUtils.close(stmt); } - if(image == null) + if (image == null) Backend.addClassImages(jarId, urlString); else { @@ -1067,7 +1067,7 @@ addClassImages(jarId, imageStream); } Loader.clearSchemaLoaders(); - if(redeploy) + if (redeploy) deployInstall(jarId, jarName); } } Index: src/java/pljava/org/postgresql/pljava/management/SQLDeploymentDescriptor.java =================================================================== RCS file: /cvsroot/pljava/org.postgresql.pljava/src/java/pljava/org/postgresql/pljava/management/SQLDeploymentDescriptor.java,v retrieving revision 1.6 diff -u -r1.6 SQLDeploymentDescriptor.java --- src/java/pljava/org/postgresql/pljava/management/SQLDeploymentDescriptor.java 13 May 2006 09:18:38 -0000 1.6 +++ src/java/pljava/org/postgresql/pljava/management/SQLDeploymentDescriptor.java 17 May 2010 19:50:51 -0000 @@ -22,46 +22,45 @@ * SQLActions <left bracket> <right bracket> <equal sign> * { [ <double quote> <action group> <double quote> * [ <comma> <double quote> <action group> <double quote> ] ] } - * + * * <action group> ::= * <install actions> * | <remove actions> * * <install actions> ::= * BEGIN INSTALL [ <command> <semicolon> ]... END INSTALL - * + * * <remove actions> ::= * BEGIN REMOVE [ <command> <semicolon> ]... END REMOVE - * + * * <command> ::= * <SQL statement> * | <implementor block> - * + * * <SQL statement> ::= <SQL token>... * * <implementor block> ::= * BEGIN <implementor name> <SQL token>... END <implementor name> - * + * * <implementor name> ::= <identifier> - * + * * <SQL token> ::= an SQL lexical unit specified by the term "<token>" in * Subclause 5.2, "<token>" and "<separator>", in ISO/IEC 9075-2. - * + * * @author Thomas Hallgren */ -public class SQLDeploymentDescriptor -{ - private final ArrayList m_installCommands = new ArrayList(); - private final ArrayList m_removeCommands = new ArrayList(); - - private final StringBuffer m_buffer = new StringBuffer(); - private final char[] m_image; - private final String m_implementorName; - private final Logger m_logger; +public class SQLDeploymentDescriptor { + private final ArrayList m_installCommands = new ArrayList(); + private final ArrayList m_removeCommands = new ArrayList(); + + private final StringBuffer m_buffer = new StringBuffer(); + private final char[] m_image; + private final String m_implementorName; + private final Logger m_logger; - private int m_position = 0; + private int m_position = 0; - /** + /** * Parses the deployment descriptor descImage using * implementorName as discriminator for implementor specific * blocks. The install and remove blocks are remembered for later execution @@ -69,397 +68,397 @@ * @param descImage The image to parse * @param implementorName The discriminator to use for implementor blocks * @throws ParseException If a parse error is encountered - */ + */ public SQLDeploymentDescriptor(String descImage, String implementorName) throws ParseException { - m_image = descImage.toCharArray(); - m_implementorName = implementorName; - m_logger = Logger.getAnonymousLogger(); - this.readDescriptor(); - } + m_image = descImage.toCharArray(); + m_implementorName = implementorName; + m_logger = Logger.getAnonymousLogger(); + this.readDescriptor(); + } - /** - * Executes the INSTALL actions. + /** + * Executes the INSTALL actions. * @param conn The connection to use for the execution. - * @throws SQLException - */ + * @throws SQLException + */ public void install(Connection conn) throws SQLException { - this.executeArray(m_installCommands, conn); - } + this.executeArray(m_installCommands, conn); + } - /** - * Executes the REMOVE actions. + /** + * Executes the REMOVE actions. * @param conn The connection to use for the execution. - * @throws SQLException - */ + * @throws SQLException + */ public void remove(Connection conn) throws SQLException { - this.executeArray(m_removeCommands, conn); - } + this.executeArray(m_removeCommands, conn); + } - /** - * Returns the original image. - */ - public String toString() - { - return new String(m_image); - } + /** + * Returns the original image. + */ + @Override + public String toString() { + return new String(m_image); + } private void executeArray(ArrayList array, Connection conn) throws SQLException { - m_logger.entering("org.postgresql.pljava.management.SQLDeploymentDescriptor", "executeArray"); - Session session = SessionManager.current(); - int top = array.size(); + m_logger.entering("org.postgresql.pljava.management.SQLDeploymentDescriptor", "executeArray"); + Session session = SessionManager.current(); + int top = array.size(); for(int idx = 0; idx < top; ++idx) { - String cmd = (String)array.get(idx); - m_logger.finer(cmd); - session.executeAsSessionUser(conn, cmd); - } - m_logger.exiting("org.postgresql.pljava.management.SQLDeploymentDescriptor", "executeArray"); - } + String cmd = (String) array.get(idx); + m_logger.finer(cmd); + session.executeAsSessionUser(conn, cmd); + } + m_logger.exiting("org.postgresql.pljava.management.SQLDeploymentDescriptor", "executeArray"); + } private ParseException parseError(String msg) { - return new ParseException(msg, m_position); - } + return new ParseException(msg, m_position); + } private void readDescriptor() throws ParseException { - m_logger.entering("org.postgresql.pljava.management.SQLDeploymentDescriptor", "readDescriptor"); - if(!"SQLACTIONS".equals(this.readIdentifier())) - throw this.parseError("Excpected keyword 'SQLActions'"); - - this.readToken('['); - this.readToken(']'); - this.readToken('='); - this.readToken('{'); + m_logger.entering("org.postgresql.pljava.management.SQLDeploymentDescriptor", "readDescriptor"); + if (!"SQLACTIONS".equals(this.readIdentifier())) + throw this.parseError("Excpected keyword 'SQLActions'"); + + this.readToken('['); + this.readToken(']'); + this.readToken('='); + this.readToken('{'); for(;;) { - readActionGroup(); + readActionGroup(); if(readToken("},") == '}') { - // Only whitespace allowed now - // - int c = this.skipWhite(); - if(c >= 0) + // Only whitespace allowed now + // + int c = this.skipWhite(); + if (c >= 0) throw this.parseError( "Extraneous characters at end of descriptor"); - m_logger.exiting("org.postgresql.pljava.management.SQLDeploymentDescriptor", "readDescriptor"); - return; - } - } - } + m_logger.exiting("org.postgresql.pljava.management.SQLDeploymentDescriptor", "readDescriptor"); + return; + } + } + } private void readActionGroup() throws ParseException { - m_logger.entering("org.postgresql.pljava.management.SQLDeploymentDescriptor", "readActionGroup"); - this.readToken('"'); - if(!"BEGIN".equals(this.readIdentifier())) - throw this.parseError("Excpected keyword 'BEGIN'"); - - ArrayList commands; - String actionType = this.readIdentifier(); - if("INSTALL".equals(actionType)) - commands = m_installCommands; - else if("REMOVE".equals(actionType)) - commands = m_removeCommands; - else - throw this.parseError("Excpected keyword 'INSTALL' or 'REMOVE'"); + m_logger.entering("org.postgresql.pljava.management.SQLDeploymentDescriptor", "readActionGroup"); + this.readToken('"'); + if (!"BEGIN".equals(this.readIdentifier())) + throw this.parseError("Excpected keyword 'BEGIN'"); + + ArrayList commands; + String actionType = this.readIdentifier(); + if ("INSTALL".equals(actionType)) + commands = m_installCommands; + else if ("REMOVE".equals(actionType)) + commands = m_removeCommands; + else + throw this.parseError("Excpected keyword 'INSTALL' or 'REMOVE'"); for(;;) { - String cmd = this.readCommand(); + String cmd = this.readCommand(); - // Check if the cmd is in the form: - // - // ::= - // BEGIN ... END - // - // If it is, and if the implementor name corresponds to the one - // defined for this deployment, then extract the SQL token stream. - // - int top = cmd.length(); + // Check if the cmd is in the form: + // + // ::= + // BEGIN ... END + // + // If it is, and if the implementor name corresponds to the one + // defined for this deployment, then extract the SQL token stream. + // + int top = cmd.length(); if(top >= 15 && "BEGIN ".equalsIgnoreCase(cmd.substring(0, 6)) && Character.isJavaIdentifierStart(cmd.charAt(6))) { - int pos; - for(pos = 7; pos < top; ++pos) - if(!Character.isJavaIdentifierPart(cmd.charAt(pos))) - break; + int pos; + for (pos = 7; pos < top; ++pos) + if (!Character.isJavaIdentifierPart(cmd.charAt(pos))) + break; - if(cmd.charAt(pos) != ' ') + if (cmd.charAt(pos) != ' ') throw this.parseError( "Expected whitespace after "); - String implementorName = cmd.substring(6, pos); - int iLen = implementorName.length(); + String implementorName = cmd.substring(6, pos); + int iLen = implementorName.length(); - int endNamePos = top - iLen; - int endPos = endNamePos - 4; + int endNamePos = top - iLen; + int endPos = endNamePos - 4; if(!implementorName.equalsIgnoreCase(cmd.substring(endNamePos)) || !"END ".equalsIgnoreCase(cmd.substring(endPos, endNamePos))) throw this.parseError( "Implementor block must end with END "); - if(implementorName.equalsIgnoreCase(m_implementorName)) - cmd = cmd.substring(pos+1, endPos); - else - // Block is not intended for this implementor. - // - cmd = null; - } - - if(cmd != null) - commands.add(cmd.trim()); - - // Check if we have END INSTALL or END REMOVE - // - int savePos = m_position; + if (implementorName.equalsIgnoreCase(m_implementorName)) + cmd = cmd.substring(pos + 1, endPos); + else + // Block is not intended for this implementor. + // + cmd = null; + } + + if (cmd != null) + commands.add(cmd.trim()); + + // Check if we have END INSTALL or END REMOVE + // + int savePos = m_position; try { - String tmp = this.readIdentifier(); + String tmp = this.readIdentifier(); if("END".equals(tmp)) { - tmp = this.readIdentifier(); - if(actionType.equals(tmp)) - break; - } - m_position = savePos; + tmp = this.readIdentifier(); + if (actionType.equals(tmp)) + break; + } + m_position = savePos; } catch(ParseException e) { - m_position = savePos; - } - } - this.readToken('"'); - m_logger.exiting("org.postgresql.pljava.management.SQLDeploymentDescriptor", "readActionGroup"); - } + m_position = savePos; + } + } + this.readToken('"'); + m_logger.exiting("org.postgresql.pljava.management.SQLDeploymentDescriptor", "readActionGroup"); + } private String readCommand() throws ParseException { - m_logger.entering("org.postgresql.pljava.management.SQLDeploymentDescriptor", "readCommand"); - int startQuotePos = -1; - int inQuote = 0; - int c = this.skipWhite(); - m_buffer.setLength(0); + m_logger.entering("org.postgresql.pljava.management.SQLDeploymentDescriptor", "readCommand"); + int startQuotePos = -1; + int inQuote = 0; + int c = this.skipWhite(); + m_buffer.setLength(0); while(c != -1) { switch(c) { - case '\\': - m_buffer.append((char)c); - c = this.read(); + case '\\': + m_buffer.append((char) c); + c = this.read(); if(c != -1) { - m_buffer.append((char)c); - c = this.read(); - } - break; + m_buffer.append((char) c); + c = this.read(); + } + break; - case '"': - case '\'': + case '"': + case '\'': if(inQuote == 0) { - startQuotePos = m_position; - inQuote = c; + startQuotePos = m_position; + inQuote = c; } else if(inQuote == c) { - startQuotePos = -1; - inQuote = 0; - } - m_buffer.append((char)c); - c = this.read(); - break; + startQuotePos = -1; + inQuote = 0; + } + m_buffer.append((char) c); + c = this.read(); + break; - case ';': + case ';': if(inQuote == 0) { - String cmd = m_buffer.toString(); - m_logger.exiting("org.postgresql.pljava.management.SQLDeploymentDescriptor", "readCommand", cmd); - return cmd; - } - - m_buffer.append((char)c); - c = this.read(); - break; + String cmd = m_buffer.toString(); + m_logger.exiting("org.postgresql.pljava.management.SQLDeploymentDescriptor", "readCommand", cmd); + return cmd; + } + + m_buffer.append((char) c); + c = this.read(); + break; - default: + default: if(inQuote == 0 && Character.isWhitespace((char)c)) { - // Change multiple whitespace into one singe space. - // - m_buffer.append(' '); - c = this.skipWhite(); + // Change multiple whitespace into one singe space. + // + m_buffer.append(' '); + c = this.skipWhite(); } else { - m_buffer.append((char)c); - c = this.read(); - } - } - } - if(inQuote != 0) + m_buffer.append((char) c); + c = this.read(); + } + } + } + if (inQuote != 0) throw this.parseError("Untermintated " + (char)inQuote + " starting at position " + startQuotePos); - throw this.parseError("Unexpected EOF. Expecting ';' to end command"); - } + throw this.parseError("Unexpected EOF. Expecting ';' to end command"); + } private int skipWhite() throws ParseException { - int c; + int c; for(;;) { - c = this.read(); - if(c >= 0 && Character.isWhitespace((char)c)) - continue; - + c = this.read(); + if (c >= 0 && Character.isWhitespace((char) c)) + continue; + if(c == '/') { switch(this.peek()) { - // "//" starts a line comment. Skip until end of line. - // - case '/': - this.skip(); + // "//" starts a line comment. Skip until end of line. + // + case '/': + this.skip(); for(;;) { - c = this.read(); + c = this.read(); switch(c) { - case '\n': - case '\r': - case -1: - break; - default: - continue; - } - break; - } - continue; - - // "/*" starts a line comment. Skip until "*/" - // - case '*': - this.skip(); + case '\n': + case '\r': + case -1: + break; + default: + continue; + } + break; + } + continue; + + // "/*" starts a line comment. Skip until "*/" + // + case '*': + this.skip(); for(;;) { - c = this.read(); + c = this.read(); switch(c) { - case -1: + case -1: throw this.parseError( "Unexpected EOF when expecting end of multi line comment"); - - case '*': + + case '*': if(this.peek() == '/') { - this.skip(); - break; - } - continue; - - default: - continue; - } - break; - } - continue; - } - } - break; - } - return c; - } + this.skip(); + break; + } + continue; + + default: + continue; + } + break; + } + continue; + } + } + break; + } + return c; + } private String readIdentifier() throws ParseException { - int c = this.skipWhite(); - if(c < 0) - throw this.parseError("Unexpected EOF when expecting start of identifier"); + int c = this.skipWhite(); + if (c < 0) + throw this.parseError("Unexpected EOF when expecting start of identifier"); - char ch = (char)c; - if(!Character.isJavaIdentifierStart(ch)) + char ch = (char) c; + if (!Character.isJavaIdentifierStart(ch)) throw this.parseError( "Syntax error at '" + ch + "', expected identifier"); - m_buffer.setLength(0); - m_buffer.append(ch); + m_buffer.setLength(0); + m_buffer.append(ch); for(;;) { - c = this.peek(); - if(c < 0) - break; + c = this.peek(); + if (c < 0) + break; - ch = (char)c; + ch = (char) c; if(Character.isJavaIdentifierPart(ch)) { - m_buffer.append(ch); - this.skip(); - continue; - } - break; - } - return m_buffer.toString().toUpperCase(); - } + m_buffer.append(ch); + this.skip(); + continue; + } + break; + } + return m_buffer.toString().toUpperCase(); + } private char readToken(String tokens) throws ParseException { - int c = this.skipWhite(); - if(c < 0) - throw this.parseError("Unexpected EOF when expecting one of \"" + tokens + '"'); + int c = this.skipWhite(); + if (c < 0) + throw this.parseError("Unexpected EOF when expecting one of \"" + tokens + '"'); - char ch = (char)c; - if(tokens.indexOf(ch) < 0) + char ch = (char) c; + if (tokens.indexOf(ch) < 0) throw this.parseError( "Syntax error at '" + ch + "', expected one of '" + tokens + "'"); - return ch; - } + return ch; + } private char readToken(char token) throws ParseException { - int c = this.skipWhite(); - if(c < 0) - throw this.parseError("Unexpected EOF when expecting token '" + token + '\''); + int c = this.skipWhite(); + if (c < 0) + throw this.parseError("Unexpected EOF when expecting token '" + token + '\''); - char ch = (char)c; - if(ch != token) + char ch = (char) c; + if (ch != token) throw this.parseError( "Syntax error at '" + ch + "', expected '" + token + "'"); - return ch; - } + return ch; + } private int peek() { - return (m_position >= m_image.length) ? -1 : m_image[m_position]; - } + return (m_position >= m_image.length) ? -1 : m_image[m_position]; + } private void skip() { - m_position++; - } + m_position++; + } private int read() { - int pos = m_position++; - return (pos >= m_image.length) ? -1 : m_image[pos]; - } + int pos = m_position++; + return (pos >= m_image.length) ? -1 : m_image[pos]; + } } \ No newline at end of file Index: src/java/pljava/org/postgresql/pljava/sqlj/Loader.java =================================================================== RCS file: /cvsroot/pljava/org.postgresql.pljava/src/java/pljava/org/postgresql/pljava/sqlj/Loader.java,v retrieving revision 1.8 diff -u -r1.8 Loader.java --- src/java/pljava/org/postgresql/pljava/sqlj/Loader.java 6 May 2006 11:41:13 -0000 1.8 +++ src/java/pljava/org/postgresql/pljava/sqlj/Loader.java 17 May 2010 19:50:51 -0000 @@ -34,7 +34,7 @@ { private final static Logger s_logger = Logger.getLogger(Loader.class.getName()); - static class EntryEnumeration implements Enumeration + static class EntryEnumeration implements Enumeration { private final int[] m_entryIds; private int m_top = 0; @@ -48,8 +48,8 @@ { return (m_top < m_entryIds.length); } - - public Object nextElement() + + public URL nextElement() throws NoSuchElementException { if (m_top >= m_entryIds.length) @@ -57,11 +57,12 @@ return entryURL(m_entryIds[m_top++]); } } + private static final String PUBLIC_SCHEMA = "public"; - private static final Map s_schemaLoaders = new HashMap(); + private static final Map s_schemaLoaders = new HashMap(); - private static final Map s_typeMap = new HashMap(); + private static final Map> s_typeMap = new HashMap>(); /** * Removes all cached schema loaders, functions, and type maps. This @@ -91,7 +92,7 @@ try { rs = stmt.executeQuery("SELECT current_schema()"); - if(!rs.next()) + if (!rs.next()) throw new SQLException("Unable to determine current schema"); schema = rs.getString(1); } @@ -113,16 +114,16 @@ public static ClassLoader getSchemaLoader(String schemaName) throws SQLException { - if(schemaName == null || schemaName.length() == 0) + if (schemaName == null || schemaName.length() == 0) schemaName = PUBLIC_SCHEMA; else schemaName = schemaName.toLowerCase(); - ClassLoader loader = (ClassLoader)s_schemaLoaders.get(schemaName); - if(loader != null) + ClassLoader loader = (ClassLoader) s_schemaLoaders.get(schemaName); + if (loader != null) return loader; - Map classImages = new HashMap(); + Map classImages = new HashMap(); Connection conn = SQLUtils.getDefaultConnection(); PreparedStatement outer = null; PreparedStatement inner = null; @@ -142,18 +143,18 @@ ResultSet rs = outer.executeQuery(); try { - while(rs.next()) + while (rs.next()) { inner.setInt(1, rs.getInt(1)); ResultSet rs2 = inner.executeQuery(); try { - while(rs2.next()) + while (rs2.next()) { int entryId = rs2.getInt(1); String entryName = rs2.getString(2); - int[] oldEntry = (int[])classImages.get(entryName); - if(oldEntry == null) + int[] oldEntry = (int[]) classImages.get(entryName); + if (oldEntry == null) classImages.put(entryName, new int[] { entryId }); else { @@ -183,7 +184,7 @@ } ClassLoader parent = ClassLoader.getSystemClassLoader(); - if(classImages.size() == 0) + if (classImages.size() == 0) // // No classpath defined for the schema. Default to // classpath of public schema or to the system classloader if the @@ -202,20 +203,21 @@ * Java UDT mappings for the given schema. * This method is called by the function mapping mechanisms. Application code * should never call this method. - * + * * @param schema The schema * @return The Map, possibly empty but never null. */ public static Map getTypeMap(final String schema) throws SQLException { - Map typesForSchema = (Map)s_typeMap.get(schema); - if(typesForSchema != null) + Map typesForSchema = s_typeMap.get(schema); + if (typesForSchema != null) return typesForSchema; s_logger.fine("Creating typeMappings for schema " + schema); - typesForSchema = new HashMap() + typesForSchema = new HashMap() { - public Object get(Object key) + @Override + public Class get(Object key) { s_logger.fine("Obtaining type mapping for OID " + key + " for schema " + schema); return super.get(key); @@ -227,16 +229,16 @@ try { rs = stmt.executeQuery("SELECT javaName, sqlName FROM sqlj.typemap_entry"); - while(rs.next()) + while (rs.next()) { try { String javaClassName = rs.getString(1); String sqlName = rs.getString(2); Class cls = loader.loadClass(javaClassName); - if(!SQLData.class.isAssignableFrom(cls)) + if (!SQLData.class.isAssignableFrom(cls)) throw new SQLException("Class " + javaClassName + " does not implement java.sql.SQLData"); - + Oid typeOid = Oid.forTypeName(sqlName); typesForSchema.put(typeOid, cls); s_logger.fine("Adding type mapping for OID " + typeOid + " -> class " + cls.getName() + " for schema " + schema); @@ -246,7 +248,7 @@ // Ignore, type is not know to this schema and that is ok } } - if(typesForSchema.isEmpty()) + if (typesForSchema.isEmpty()) typesForSchema = Collections.EMPTY_MAP; s_typeMap.put(schema, typesForSchema); return typesForSchema; @@ -288,12 +290,13 @@ m_entries = entries; } + @Override protected Class findClass(final String name) throws ClassNotFoundException { String path = name.replace('.', '/').concat(".class"); - int[] entryId = (int[])m_entries.get(path); - if(entryId != null) + int[] entryId = (int[]) m_entries.get(path); + if (entryId != null) { PreparedStatement stmt = null; ResultSet rs = null; @@ -304,11 +307,11 @@ // for the duration of the loader. // stmt = SQLUtils.getDefaultConnection().prepareStatement( - "SELECT entryImage FROM sqlj.jar_entry WHERE entryId = ?"); + "SELECT entryImage FROM sqlj.jar_entry WHERE entryId = ?"); stmt.setInt(1, entryId[0]); rs = stmt.executeQuery(); - if(rs.next()) + if (rs.next()) { byte[] img = rs.getBytes(1); rs.close(); @@ -327,23 +330,24 @@ SQLUtils.close(stmt); } } - throw new ClassNotFoundException(name); + throw new ClassNotFoundException(name); } + @Override protected URL findResource(String name) { - int[] entryIds = (int[])m_entries.get(name); - if(entryIds == null) + int[] entryIds = (int[]) m_entries.get(name); + if (entryIds == null) return null; - + return entryURL(entryIds[0]); } - protected Enumeration findResources(String name) - throws IOException + @Override + protected Enumeration findResources(String name) throws IOException { - int[] entryIds = (int[])m_entries.get(name); - if(entryIds == null) + int[] entryIds = (int[]) m_entries.get(name); + if (entryIds == null) entryIds = new int[0]; return new EntryEnumeration(entryIds); }
        jar_urlThe URL that denotes the location of the jar that should be loaded The URL that denotes the location of the jar that should be loaded
        jar_name