- // we'll keep them for completeness.
- * usernames who have that permission.
+++ /dev/null
-/*-------------------------------------------------------------------------
- *
- * AbstractJdbc1ResultSet.java
- * This class defines methods of the jdbc1 specification. This class is
- * extended by org.postgresql.jdbc2.AbstractJdbc2ResultSet which adds the
- * jdbc2 methods. The real ResultSet class (for jdbc1) is
- * org.postgresql.jdbc1.Jdbc1ResultSet
- *
- * Copyright (c) 2003, PostgreSQL Global Development Group
- *
- * IDENTIFICATION
- * $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/jdbc1/AbstractJdbc1ResultSet.java,v 1.25 2003/12/12 17:58:34 davec Exp $
- *
- *-------------------------------------------------------------------------
- */
-package org.postgresql.jdbc1;
-
-import java.math.BigDecimal;
-import java.io.*;
-import java.sql.*;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.Vector;
-import org.postgresql.Driver;
-import org.postgresql.core.BaseConnection;
-import org.postgresql.core.BaseResultSet;
-import org.postgresql.core.BaseStatement;
-import org.postgresql.core.Field;
-import org.postgresql.core.Encoding;
-import org.postgresql.core.QueryExecutor;
-import org.postgresql.largeobject.*;
-import org.postgresql.util.PGbytea;
-import org.postgresql.util.PGtokenizer;
-import org.postgresql.util.PSQLException;
-import org.postgresql.util.PSQLState;
-
-public abstract class AbstractJdbc1ResultSet implements BaseResultSet
-{
-
- protected Vector rows; // The results
- protected BaseStatement statement;
- protected Field fields[]; // The field descriptions
- protected String status; // Status of the result
- protected boolean binaryCursor = false; // is the data binary or Strings
- protected int updateCount; // How many rows did we get back?
- protected long insertOID; // The oid of an inserted row
- protected int current_row; // Our pointer to where we are at
- protected byte[][] this_row; // the current row result
- protected BaseConnection connection; // the connection which we returned from
- protected SQLWarning warnings = null; // The warning chain
- protected boolean wasNullFlag = false; // the flag for wasNull()
-
- // We can chain multiple resultSets together - this points to
- // next resultSet in the chain.
- protected BaseResultSet next = null;
-
- private StringBuffer sbuf = null;
- public byte[][] rowBuffer = null;
-
- private SimpleDateFormat m_tsFormat = null;
- private SimpleDateFormat m_tstzFormat = null;
- private SimpleDateFormat m_dateFormat = null;
-
- private int fetchSize; // Fetch size for next read (might be 0).
- private int lastFetchSize; // Fetch size of last read (might be 0).
-
- public abstract ResultSetMetaData getMetaData() throws SQLException;
-
- public AbstractJdbc1ResultSet(BaseStatement statement,
- Field[] fields,
- Vector tuples,
- String status,
- int updateCount,
- long insertOID,
- boolean binaryCursor)
- {
- this.connection = statement.getPGConnection();
- this.statement = statement;
- this.fields = fields;
- this.rows = tuples;
- this.status = status;
- this.updateCount = updateCount;
-
- this.insertOID = insertOID;
- this.this_row = null;
- this.current_row = -1;
- this.binaryCursor = binaryCursor;
-
- this.lastFetchSize = this.fetchSize = (statement == null ? 0 : statement.getFetchSize());
- }
-
- public BaseStatement getPGStatement() {
- return statement;
- }
-
- public StringBuffer getStringBuffer() {
- return sbuf;
- }
-
- //This is implemented in jdbc2
- public void setStatement(BaseStatement statement) {
- }
-
- //method to reinitialize a result set with more data
- public void reInit (Field[] fields, Vector tuples, String status,
- int updateCount, long insertOID, boolean binaryCursor)
- {
- this.fields = fields;
- // on a reinit the size of this indicates how many we pulled
- // back. If it's 0 then the res set has ended.
- this.rows = tuples;
- this.status = status;
- this.updateCount = updateCount;
- this.insertOID = insertOID;
- this.this_row = null;
- this.current_row = -1;
- this.binaryCursor = binaryCursor;
- }
-
- //
- // Part of the JDBC2 support, but convenient to implement here.
- //
-
- public void setFetchSize(int rows) throws SQLException
- {
- fetchSize = rows;
- }
-
-
- public int getFetchSize() throws SQLException
- {
- return fetchSize;
- }
-
- public boolean next() throws SQLException
- {
- if (rows == null)
- throw new PSQLException("postgresql.con.closed", PSQLState.CONNECTION_DOES_NOT_EXIST);
-
- if (++current_row >= rows.size())
- {
- String cursorName = statement.getFetchingCursorName();
- if (cursorName == null || lastFetchSize == 0 || rows.size() < lastFetchSize)
- return false; // Not doing a cursor-based fetch or the last fetch was the end of the query
-
- // Use the ref to the statement to get
- // the details we need to do another cursor
- // query - it will use reinit() to repopulate this
- // with the right data.
-
- // NB: We can reach this point with fetchSize == 0
- // if the fetch size is changed halfway through reading results.
- // Use "FETCH FORWARD ALL" in that case to complete the query.
- String[] sql = new String[] {
- fetchSize == 0 ? ("FETCH FORWARD ALL FROM " + cursorName) :
- ("FETCH FORWARD " + fetchSize + " FROM " + cursorName)
- };
-
- QueryExecutor.execute(sql,
- new String[0],
- this);
-
- // Test the new rows array.
- lastFetchSize = fetchSize;
- if (rows.size() == 0)
- return false;
-
- // Otherwise reset the counter and let it go on...
- current_row = 0;
- }
-
- this_row = (byte [][])rows.elementAt(current_row);
-
- rowBuffer = new byte[this_row.length][];
- System.arraycopy(this_row, 0, rowBuffer, 0, this_row.length);
- return true;
- }
-
- public void close() throws SQLException
- {
- //release resources held (memory for tuples)
- if (rows != null)
- {
- rows = null;
- }
- }
-
- public boolean wasNull() throws SQLException
- {
- return wasNullFlag;
- }
-
- public String getString(int columnIndex) throws SQLException
- {
- checkResultSet( columnIndex );
- wasNullFlag = (this_row[columnIndex - 1] == null);
- if (wasNullFlag)
- return null;
-
- Encoding encoding = connection.getEncoding();
- return trimString(columnIndex, encoding.decode(this_row[columnIndex-1]));
- }
-
- public boolean getBoolean(int columnIndex) throws SQLException
- {
- return toBoolean( getString(columnIndex) );
- }
-
-
- public byte getByte(int columnIndex) throws SQLException
- {
- String s = getString(columnIndex);
-
- if (s != null )
- {
- try
- {
- switch(fields[columnIndex-1].getSQLType())
- {
- case Types.NUMERIC:
- case Types.REAL:
- case Types.DOUBLE:
- case Types.FLOAT:
- case Types.DECIMAL:
- int loc = s.indexOf(".");
- if (loc!=-1 && Integer.parseInt(s.substring(loc+1,s.length()))==0)
- {
- s = s.substring(0,loc);
- }
- break;
- case Types.CHAR:
- s = s.trim();
- break;
- }
- if ( s.length() == 0 ) return 0;
- return Byte.parseByte(s);
- }
- catch (NumberFormatException e)
- {
- throw new PSQLException("postgresql.res.badbyte", PSQLState.NUMERIC_VALUE_OUT_OF_RANGE, s);
- }
- }
- return 0; // SQL NULL
- }
-
- public short getShort(int columnIndex) throws SQLException
- {
- String s = getFixedString(columnIndex);
-
- if (s != null)
- {
- try
- {
- switch(fields[columnIndex-1].getSQLType())
- {
- case Types.NUMERIC:
- case Types.REAL:
- case Types.DOUBLE:
- case Types.FLOAT:
- case Types.DECIMAL:
- int loc = s.indexOf(".");
- if (loc!=-1 && Integer.parseInt(s.substring(loc+1,s.length()))==0)
- {
- s = s.substring(0,loc);
- }
- break;
- case Types.CHAR:
- s = s.trim();
- break;
- }
- return Short.parseShort(s);
- }
- catch (NumberFormatException e)
- {
- throw new PSQLException("postgresql.res.badshort", PSQLState.NUMERIC_VALUE_OUT_OF_RANGE, s);
- }
- }
- return 0; // SQL NULL
- }
-
- public int getInt(int columnIndex) throws SQLException
- {
- return toInt( getFixedString(columnIndex) );
- }
-
- public long getLong(int columnIndex) throws SQLException
- {
- return toLong( getFixedString(columnIndex) );
- }
-
- public float getFloat(int columnIndex) throws SQLException
- {
- return toFloat( getFixedString(columnIndex) );
- }
-
- public double getDouble(int columnIndex) throws SQLException
- {
- return toDouble( getFixedString(columnIndex) );
- }
-
- public BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException
- {
- return toBigDecimal( getFixedString(columnIndex), scale );
- }
-
- /*
- * Get the value of a column in the current row as a Java byte array.
- *
- *
In normal use, the bytes represent the raw values returned by the
- * backend. However, if the column is an OID, then it is assumed to
- * refer to a Large Object, and that object is returned as a byte array.
- *
- *
Be warned If the large object is huge, then you may run out
- * of memory.
- *
- * @param columnIndex the first column is 1, the second is 2, ...
- * @return the column value; if the value is SQL NULL, the result
- * is null
- * @exception SQLException if a database access error occurs
- */
- public byte[] getBytes(int columnIndex) throws SQLException
- {
- checkResultSet( columnIndex );
- wasNullFlag = (this_row[columnIndex - 1] == null);
- if (!wasNullFlag)
- {
- if (binaryCursor)
- {
- //If the data is already binary then just return it
- return this_row[columnIndex - 1];
- }
- else if (connection.haveMinimumCompatibleVersion("7.2"))
- {
- //Version 7.2 supports the bytea datatype for byte arrays
- if (fields[columnIndex - 1].getPGType().equals("bytea"))
- {
- return trimBytes(columnIndex, PGbytea.toBytes(this_row[columnIndex - 1]));
- }
- else
- {
- return trimBytes(columnIndex, this_row[columnIndex - 1]);
- }
- }
- else
- {
- //Version 7.1 and earlier supports LargeObjects for byte arrays
- // Handle OID's as BLOBS
- if ( fields[columnIndex - 1].getOID() == 26)
- {
- LargeObjectManager lom = connection.getLargeObjectAPI();
- LargeObject lob = lom.open(getInt(columnIndex));
- byte buf[] = lob.read(lob.size());
- lob.close();
- return trimBytes(columnIndex, buf);
- }
- else
- {
- return trimBytes(columnIndex, this_row[columnIndex - 1]);
- }
- }
- }
- return null;
- }
-
- public java.sql.Date getDate(int columnIndex) throws SQLException
- {
- return toDate( getString(columnIndex) );
- }
-
- public Time getTime(int columnIndex) throws SQLException
- {
- return toTime( getString(columnIndex), this, fields[columnIndex - 1].getPGType() );
- }
-
- public Timestamp getTimestamp(int columnIndex) throws SQLException
- {
- return toTimestamp( getString(columnIndex), this, fields[columnIndex - 1].getPGType() );
- }
-
- public InputStream getAsciiStream(int columnIndex) throws SQLException
- {
- checkResultSet( columnIndex );
- wasNullFlag = (this_row[columnIndex - 1] == null);
- if (wasNullFlag)
- return null;
-
- if (connection.haveMinimumCompatibleVersion("7.2"))
- {
- //Version 7.2 supports AsciiStream for all the PG text types
- //As the spec/javadoc for this method indicate this is to be used for
- //large text values (i.e. LONGVARCHAR) PG doesn't have a separate
- //long string datatype, but with toast the text datatype is capable of
- //handling very large values. Thus the implementation ends up calling
- //getString() since there is no current way to stream the value from the server
- try
- {
- return new ByteArrayInputStream(getString(columnIndex).getBytes("ASCII"));
- }
- catch (UnsupportedEncodingException l_uee)
- {
- throw new PSQLException("postgresql.unusual", PSQLState.UNEXPECTED_ERROR, l_uee);
- }
- }
- else
- {
- // In 7.1 Handle as BLOBS so return the LargeObject input stream
- return getBinaryStream(columnIndex);
- }
- }
-
- public InputStream getUnicodeStream(int columnIndex) throws SQLException
- {
- checkResultSet( columnIndex );
- wasNullFlag = (this_row[columnIndex - 1] == null);
- if (wasNullFlag)
- return null;
-
- if (connection.haveMinimumCompatibleVersion("7.2"))
- {
- //Version 7.2 supports AsciiStream for all the PG text types
- //As the spec/javadoc for this method indicate this is to be used for
- //large text values (i.e. LONGVARCHAR) PG doesn't have a separate
- //long string datatype, but with toast the text datatype is capable of
- //handling very large values. Thus the implementation ends up calling
- //getString() since there is no current way to stream the value from the server
- try
- {
- return new ByteArrayInputStream(getString(columnIndex).getBytes("UTF-8"));
- }
- catch (UnsupportedEncodingException l_uee)
- {
- throw new PSQLException("postgresql.unusual", PSQLState.UNEXPECTED_ERROR, l_uee);
- }
- }
- else
- {
- // In 7.1 Handle as BLOBS so return the LargeObject input stream
- return getBinaryStream(columnIndex);
- }
- }
-
- public InputStream getBinaryStream(int columnIndex) throws SQLException
- {
- checkResultSet( columnIndex );
- wasNullFlag = (this_row[columnIndex - 1] == null);
- if (wasNullFlag)
- return null;
-
- if (connection.haveMinimumCompatibleVersion("7.2"))
- {
- //Version 7.2 supports BinaryStream for all PG bytea type
- //As the spec/javadoc for this method indicate this is to be used for
- //large binary values (i.e. LONGVARBINARY) PG doesn't have a separate
- //long binary datatype, but with toast the bytea datatype is capable of
- //handling very large values. Thus the implementation ends up calling
- //getBytes() since there is no current way to stream the value from the server
- byte b[] = getBytes(columnIndex);
- if (b != null)
- return new ByteArrayInputStream(b);
- }
- else
- {
- // In 7.1 Handle as BLOBS so return the LargeObject input stream
- if ( fields[columnIndex - 1].getOID() == 26)
- {
- LargeObjectManager lom = connection.getLargeObjectAPI();
- LargeObject lob = lom.open(getInt(columnIndex));
- return lob.getInputStream();
- }
- }
- return null;
- }
-
- public String getString(String columnName) throws SQLException
- {
- return getString(findColumn(columnName));
- }
-
- public boolean getBoolean(String columnName) throws SQLException
- {
- return getBoolean(findColumn(columnName));
- }
-
- public byte getByte(String columnName) throws SQLException
- {
-
- return getByte(findColumn(columnName));
- }
-
- public short getShort(String columnName) throws SQLException
- {
- return getShort(findColumn(columnName));
- }
-
- public int getInt(String columnName) throws SQLException
- {
- return getInt(findColumn(columnName));
- }
-
- public long getLong(String columnName) throws SQLException
- {
- return getLong(findColumn(columnName));
- }
-
- public float getFloat(String columnName) throws SQLException
- {
- return getFloat(findColumn(columnName));
- }
-
- public double getDouble(String columnName) throws SQLException
- {
- return getDouble(findColumn(columnName));
- }
-
- public BigDecimal getBigDecimal(String columnName, int scale) throws SQLException
- {
- return getBigDecimal(findColumn(columnName), scale);
- }
-
- public byte[] getBytes(String columnName) throws SQLException
- {
- return getBytes(findColumn(columnName));
- }
-
- public java.sql.Date getDate(String columnName) throws SQLException
- {
- return getDate(findColumn(columnName));
- }
-
- public Time getTime(String columnName) throws SQLException
- {
- return getTime(findColumn(columnName));
- }
-
- public Timestamp getTimestamp(String columnName) throws SQLException
- {
- return getTimestamp(findColumn(columnName));
- }
-
- public InputStream getAsciiStream(String columnName) throws SQLException
- {
- return getAsciiStream(findColumn(columnName));
- }
-
- public InputStream getUnicodeStream(String columnName) throws SQLException
- {
- return getUnicodeStream(findColumn(columnName));
- }
-
- public InputStream getBinaryStream(String columnName) throws SQLException
- {
- return getBinaryStream(findColumn(columnName));
- }
-
- public SQLWarning getWarnings() throws SQLException
- {
- return warnings;
- }
-
- public void clearWarnings() throws SQLException
- {
- warnings = null;
- }
-
- public void addWarnings(SQLWarning warnings)
- {
- if ( this.warnings != null )
- this.warnings.setNextWarning(warnings);
- else
- this.warnings = warnings;
- }
-
- public String getCursorName() throws SQLException
- {
- return (connection.getCursorName());
- }
-
- /*
- * Get the value of a column in the current row as a Java object
- *
- *
This method will return the value of the given column as a
- * Java object. The type of the Java object will be the default
- * Java Object type corresponding to the column's SQL type, following
- * the mapping specified in the JDBC specification.
- *
- *
This method may also be used to read database specific abstract
- * data types.
- *
- * @param columnIndex the first column is 1, the second is 2...
- * @return a Object holding the column value
- * @exception SQLException if a database access error occurs
- */
- public Object getObject(int columnIndex) throws SQLException
- {
- Field field;
-
- if (columnIndex < 1 || columnIndex > fields.length)
- throw new PSQLException("postgresql.res.colrange", PSQLState.INVALID_PARAMETER_VALUE);
- field = fields[columnIndex - 1];
-
- // some fields can be null, mainly from those returned by MetaData methods
- if (field == null)
- {
- wasNullFlag = true;
- return null;
- }
-
- switch (field.getSQLType())
- {
- case Types.BIT:
- return getBoolean(columnIndex) ? Boolean.TRUE : Boolean.FALSE;
- case Types.SMALLINT:
- return new Short(getShort(columnIndex));
- case Types.INTEGER:
- return new Integer(getInt(columnIndex));
- case Types.BIGINT:
- return new Long(getLong(columnIndex));
- case Types.NUMERIC:
- return getBigDecimal
- (columnIndex, (field.getMod() == -1) ? -1 : ((field.getMod() - 4) & 0xffff));
- case Types.REAL:
- return new Float(getFloat(columnIndex));
- case Types.DOUBLE:
- return new Double(getDouble(columnIndex));
- case Types.CHAR:
- case Types.VARCHAR:
- return getString(columnIndex);
- case Types.DATE:
- return getDate(columnIndex);
- case Types.TIME:
- return getTime(columnIndex);
- case Types.TIMESTAMP:
- return getTimestamp(columnIndex);
- case Types.BINARY:
- case Types.VARBINARY:
- return getBytes(columnIndex);
- default:
- String type = field.getPGType();
-
- // if the backend doesn't know the type then coerce to String
- if (type.equals("unknown"))
- {
- return getString(columnIndex);
- }
- // Specialized support for ref cursors is neater.
- else if (type.equals("refcursor"))
- {
- String cursorName = getString(columnIndex);
- return statement.createRefCursorResultSet(cursorName);
- }
- else
- {
- return connection.getObject(field.getPGType(), getString(columnIndex));
- }
- }
- }
-
- public Object getObject(String columnName) throws SQLException
- {
- return getObject(findColumn(columnName));
- }
-
- /*
- * Map a ResultSet column name to a ResultSet column index
- */
- public int findColumn(String columnName) throws SQLException
- {
- int i;
-
- final int flen = fields.length;
- for (i = 0 ; i < flen; ++i)
- if (fields[i].getName().equalsIgnoreCase(columnName))
- return (i + 1);
- throw new PSQLException ("postgresql.res.colname", columnName);
- }
-
-
- /*
- * We at times need to know if the resultSet we are working
- * with is the result of an UPDATE, DELETE or INSERT (in which
- * case, we only have a row count), or of a SELECT operation
- * (in which case, we have multiple fields) - this routine
- * tells us.
- */
- public boolean reallyResultSet()
- {
- return (fields != null);
- }
-
- /*
- * Since ResultSets can be chained, we need some method of
- * finding the next one in the chain. The method getNext()
- * returns the next one in the chain.
- *
- * @return the next ResultSet, or null if there are none
- */
- public ResultSet getNext()
- {
- return (ResultSet)next;
- }
-
- /*
- * This following method allows us to add a ResultSet object
- * to the end of the current chain.
- */
- public void append(BaseResultSet r)
- {
- if (next == null)
- next = r;
- else
- next.append(r);
- }
-
- /*
- * If we are just a place holder for results, we still need
- * to get an updateCount. This method returns it.
- */
- public int getResultCount()
- {
- return updateCount;
- }
-
- /*
- * We also need to provide a couple of auxiliary functions for
- * the implementation of the ResultMetaData functions. In
- * particular, we need to know the number of rows and the
- * number of columns. Rows are also known as Tuples
- */
- public int getTupleCount()
- {
- return rows.size();
- }
-
- /*
- * getColumnCount returns the number of columns
- */
- public int getColumnCount()
- {
- return fields.length;
- }
-
- /*
- * Returns the status message from the backend.
- * It is used internally by the driver.
- */
- public String getStatusString()
- {
- return status;
- }
-
- /*
- * returns the OID of a field.
- * It is used internally by the driver.
- */
- public int getColumnOID(int field)
- {
- return fields[field -1].getOID();
- }
-
- /*
- * returns the OID of the last inserted row. Deprecated in 7.2 because
- * range for OID values is greater than java signed int.
- * @deprecated Replaced by getLastOID() in 7.2
- */
- public int getInsertedOID()
- {
- return (int) getLastOID();
- }
-
-
- /*
- * returns the OID of the last inserted row
- * @since 7.2
- */
- public long getLastOID()
- {
- return insertOID;
- }
-
- /*
- * This is used to fix get*() methods on Money fields. It should only be
- * used by those methods!
- *
- * It converts ($##.##) to -##.## and $##.## to ##.##
- */
- public String getFixedString(int col) throws SQLException
- {
- String s = getString(col);
-
- // Handle SQL Null
- wasNullFlag = (this_row[col - 1] == null);
- if (wasNullFlag)
- return null;
-
- // if we don't have at least 2 characters it can't be money.
- if (s.length() < 2)
- return s;
-
- // Handle Money
- if (s.charAt(0) == '(')
- {
- s = "-" + PGtokenizer.removePara(s).substring(1);
- }
- if (s.charAt(0) == '$')
- {
- s = s.substring(1);
- }
- else if (s.charAt(0) == '-' && s.charAt(1) == '$')
- {
- s = "-" + s.substring(2);
- }
-
- return s;
- }
-
- protected void checkResultSet( int column ) throws SQLException
- {
- if ( this_row == null )
- throw new PSQLException("postgresql.res.nextrequired");
- if ( column < 1 || column > fields.length )
- throw new PSQLException("postgresql.res.colrange", PSQLState.INVALID_PARAMETER_VALUE );
- }
-
- //----------------- Formatting Methods -------------------
-
- public static boolean toBoolean(String s)
- {
- if (s != null)
- {
- s = s.trim();
-
- if (s.equalsIgnoreCase("true") || s.equalsIgnoreCase("t"))
- return true;
-
- try
- {
- if (Double.valueOf(s).doubleValue()==1)
- return true;
- }
- catch (NumberFormatException e)
- {
- }
- }
- return false; // SQL NULL
- }
-
- public static int toInt(String s) throws SQLException
- {
- if (s != null)
- {
- try
- {
- s = s.trim();
- return Integer.parseInt(s);
- }
- catch (NumberFormatException e)
- {
- throw new PSQLException ("postgresql.res.badint", PSQLState.NUMERIC_VALUE_OUT_OF_RANGE, s);
- }
- }
- return 0; // SQL NULL
- }
-
- public static long toLong(String s) throws SQLException
- {
- if (s != null)
- {
- try
- {
- s = s.trim();
- return Long.parseLong(s);
- }
- catch (NumberFormatException e)
- {
- throw new PSQLException ("postgresql.res.badlong", PSQLState.NUMERIC_VALUE_OUT_OF_RANGE, s);
- }
- }
- return 0; // SQL NULL
- }
-
- public static BigDecimal toBigDecimal(String s, int scale) throws SQLException
- {
- BigDecimal val;
- if (s != null)
- {
- try
- {
- s = s.trim();
- val = new BigDecimal(s);
- }
- catch (NumberFormatException e)
- {
- throw new PSQLException ("postgresql.res.badbigdec", PSQLState.NUMERIC_VALUE_OUT_OF_RANGE, s);
- }
- if (scale == -1)
- return val;
- try
- {
- return val.setScale(scale);
- }
- catch (ArithmeticException e)
- {
- throw new PSQLException ("postgresql.res.badbigdec", PSQLState.NUMERIC_VALUE_OUT_OF_RANGE, s);
- }
- }
- return null; // SQL NULL
- }
-
- public static float toFloat(String s) throws SQLException
- {
- if (s != null)
- {
- try
- {
- s = s.trim();
- return Float.valueOf(s).floatValue();
- }
- catch (NumberFormatException e)
- {
- throw new PSQLException ("postgresql.res.badfloat", PSQLState.NUMERIC_VALUE_OUT_OF_RANGE, s);
- }
- }
- return 0; // SQL NULL
- }
-
- public static double toDouble(String s) throws SQLException
- {
- if (s != null)
- {
- try
- {
- s = s.trim();
- return Double.valueOf(s).doubleValue();
- }
- catch (NumberFormatException e)
- {
- throw new PSQLException ("postgresql.res.baddouble", PSQLState.NUMERIC_VALUE_OUT_OF_RANGE, s);
- }
- }
- return 0; // SQL NULL
- }
-
- public static java.sql.Date toDate(String s) throws SQLException
- {
- if (s == null)
- return null;
- // length == 10: SQL Date
- // length > 10: SQL Timestamp, assumes PGDATESTYLE=ISO
- try
- {
- s = s.trim();
- return java.sql.Date.valueOf((s.length() == 10) ? s : s.substring(0, 10));
- }
- catch (NumberFormatException e)
- {
- throw new PSQLException("postgresql.res.baddate",PSQLState.BAD_DATETIME_FORMAT, s);
- }
- }
-
- public static Time toTime(String s, BaseResultSet resultSet, String pgDataType) throws SQLException
- {
- if (s == null)
- return null; // SQL NULL
- try
- {
- s = s.trim();
- if (s.length() == 8)
- {
- //value is a time value
- return java.sql.Time.valueOf(s);
- }
- else if (s.indexOf(".") == 8)
- {
- //value is a time value with fractional seconds
- java.sql.Time l_time = java.sql.Time.valueOf(s.substring(0, 8));
- String l_strMillis = s.substring(9);
- if (l_strMillis.length() > 3)
- l_strMillis = l_strMillis.substring(0, 3);
- int l_millis = Integer.parseInt(l_strMillis);
- if (l_millis < 10)
- {
- l_millis = l_millis * 100;
- }
- else if (l_millis < 100)
- {
- l_millis = l_millis * 10;
- }
- return new java.sql.Time(l_time.getTime() + l_millis);
- }
- else
- {
- //value is a timestamp
- return new java.sql.Time(toTimestamp(s, resultSet, pgDataType).getTime());
- }
- }
- catch (NumberFormatException e)
- {
- throw new PSQLException("postgresql.res.badtime", PSQLState.BAD_DATETIME_FORMAT, s);
- }
- }
-
- /**
- * Parse a string and return a timestamp representing its value.
- *
- * The driver is set to return ISO date formated strings. We modify this
- * string from the ISO format to a format that Java can understand. Java
- * expects timezone info as 'GMT+09:00' where as ISO gives '+09'.
- * Java also expects fractional seconds to 3 places where postgres
- * will give, none, 2 or 6 depending on the time and postgres version.
- * From version 7.2 postgres returns fractional seconds to 6 places.
- *
- * According to the Timestamp documentation, fractional digits are kept
- * in the nanos field of Timestamp and not in the milliseconds of Date.
- * Thus, parsing for fractional digits is entirely separated from the
- * rest.
- *
- * The method assumes that there are no more than 9 fractional
- * digits given. Undefined behavior if this is not the case.
- *
- * @param s The ISO formated date string to parse.
- * @param resultSet The ResultSet this date is part of.
- *
- * @return null if s is null or a timestamp of the parsed string s.
- *
- * @throws SQLException if there is a problem parsing s.
- **/
- public static Timestamp toTimestamp(String s, BaseResultSet resultSet, String pgDataType)
- throws SQLException
- {
- BaseResultSet rs = resultSet;
- if (s == null)
- return null;
-
- s = s.trim();
- // We must be synchronized here incase more theads access the ResultSet
- // bad practice but possible. Anyhow this is to protect sbuf and
- // SimpleDateFormat objects
- synchronized (rs)
- {
- StringBuffer l_sbuf = rs.getStringBuffer();
- SimpleDateFormat df = null;
- if ( Driver.logDebug )
- Driver.debug("the data from the DB is " + s);
-
- // If first time, create the buffer, otherwise clear it.
- if (l_sbuf == null)
- l_sbuf = new StringBuffer(32);
- else
- {
- l_sbuf.setLength(0);
- }
-
- // Copy s into sbuf for parsing.
- l_sbuf.append(s);
- int slen = s.length();
-
- // For a Timestamp, the fractional seconds are stored in the
- // nanos field. As a DateFormat is used for parsing which can
- // only parse to millisecond precision and which returns a
- // Date object, the fractional second parsing is completely
- // separate.
- int nanos = 0;
-
- if (slen > 19)
- {
- // The len of the ISO string to the second value is 19 chars. If
- // greater then 19, there may be tz info and perhaps fractional
- // second info which we need to change to java to read it.
-
- // cut the copy to second value "2001-12-07 16:29:22"
- int i = 19;
- l_sbuf.setLength(i);
-
- char c = s.charAt(i++);
- if (c == '.')
- {
- // Found a fractional value.
- final int start = i;
- while (true)
- {
- c = s.charAt(i++);
- if (!Character.isDigit(c))
- break;
- if (i == slen)
- {
- i++;
- break;
- }
- }
-
- // The range [start, i - 1) contains all fractional digits.
- final int end = i - 1;
- try
- {
- nanos = Integer.parseInt(s.substring(start, end));
- }
- catch (NumberFormatException e)
- {
- throw new PSQLException("postgresql.unusual", PSQLState.UNEXPECTED_ERROR, e);
- }
-
- // The nanos field stores nanoseconds. Adjust the parsed
- // value to the correct magnitude.
- for (int digitsToNano = 9 - (end - start);
- digitsToNano > 0; --digitsToNano)
- nanos *= 10;
- }
-
- if (i < slen)
- {
- // prepend the GMT part and then add the remaining bit of
- // the string.
- l_sbuf.append(" GMT");
- l_sbuf.append(c);
- l_sbuf.append(s.substring(i, slen));
-
- // Lastly, if the tz part doesn't specify the :MM part then
- // we add ":00" for java.
- if (slen - i < 5)
- l_sbuf.append(":00");
-
- // we'll use this dateformat string to parse the result.
- df = rs.getTimestampTZFormat();
- }
- else
- {
- // Just found fractional seconds but no timezone.
- //If timestamptz then we use GMT, else local timezone
- if (pgDataType.equals("timestamptz"))
- {
- l_sbuf.append(" GMT");
- df = rs.getTimestampTZFormat();
- }
- else
- {
- df = rs.getTimestampFormat();
- }
- }
- }
- else if (slen == 19)
- {
- // No tz or fractional second info.
- //If timestamptz then we use GMT, else local timezone
- if (pgDataType.equals("timestamptz"))
- {
- l_sbuf.append(" GMT");
- df = rs.getTimestampTZFormat();
- }
- else
- {
- df = rs.getTimestampFormat();
- }
- }
- else
- {
- if (slen == 8 && s.equals("infinity"))
- //java doesn't have a concept of postgres's infinity
- //so set to an arbitrary future date
- s = "9999-01-01";
- if (slen == 9 && s.equals("-infinity"))
- //java doesn't have a concept of postgres's infinity
- //so set to an arbitrary old date
- s = "0001-01-01";
-
- // We must just have a date. This case is
- // needed if this method is called on a date
- // column
- df = rs.getDateFormat();
- }
-
- try
- {
- // All that's left is to parse the string and return the ts.
- if ( Driver.logDebug )
- Driver.debug("the data after parsing is "
- + l_sbuf.toString() + " with " + nanos + " nanos");
-
- Timestamp result = new Timestamp(df.parse(l_sbuf.toString()).getTime());
- result.setNanos(nanos);
- return result;
- }
- catch (ParseException e)
- {
- throw new PSQLException("postgresql.res.badtimestamp", PSQLState.BAD_DATETIME_FORMAT, new Integer(e.getErrorOffset()), s);
- }
- }
- }
-
- private boolean isColumnTrimmable(int columnIndex) throws SQLException
- {
- switch (fields[columnIndex-1].getSQLType())
- {
- case Types.CHAR:
- case Types.VARCHAR:
- case Types.LONGVARCHAR:
- case Types.BINARY:
- case Types.VARBINARY:
- case Types.LONGVARBINARY:
- return true;
- }
- return false;
- }
-
- private byte[] trimBytes(int p_columnIndex, byte[] p_bytes) throws SQLException
- {
- int l_maxSize = statement.getMaxFieldSize();
- //we need to trim if maxsize is set and the length is greater than maxsize and the
- //type of this column is a candidate for trimming
- if (l_maxSize > 0 && p_bytes.length > l_maxSize && isColumnTrimmable(p_columnIndex))
- {
- byte[] l_bytes = new byte[l_maxSize];
- System.arraycopy (p_bytes, 0, l_bytes, 0, l_maxSize);
- return l_bytes;
- }
- else
- {
- return p_bytes;
- }
- }
-
- private String trimString(int p_columnIndex, String p_string) throws SQLException
- {
- int l_maxSize = statement.getMaxFieldSize();
- //we need to trim if maxsize is set and the length is greater than maxsize and the
- //type of this column is a candidate for trimming
- if (l_maxSize > 0 && p_string.length() > l_maxSize && isColumnTrimmable(p_columnIndex))
- {
- return p_string.substring(0,l_maxSize);
- }
- else
- {
- return p_string;
- }
- }
-
- public SimpleDateFormat getTimestampTZFormat() {
- if (m_tstzFormat == null) {
- m_tstzFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
- }
- return m_tstzFormat;
- }
- public SimpleDateFormat getTimestampFormat() {
- if (m_tsFormat == null) {
- m_tsFormat = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
- }
- return m_tsFormat;
- }
- public SimpleDateFormat getDateFormat() {
- if (m_dateFormat == null) {
- m_dateFormat = new SimpleDateFormat("yyyy-MM-dd");
- }
- return m_dateFormat;
- }
-}
-
+++ /dev/null
-package org.postgresql.jdbc1;
-
-import org.postgresql.core.BaseConnection;
-import org.postgresql.core.BaseResultSet;
-import org.postgresql.core.BaseStatement;
-import org.postgresql.core.Field;
-import org.postgresql.core.QueryExecutor;
-import org.postgresql.largeobject.LargeObject;
-import org.postgresql.largeobject.LargeObjectManager;
-import org.postgresql.util.PGbytea;
-import org.postgresql.util.PGobject;
-import org.postgresql.util.PSQLException;
-import org.postgresql.util.PSQLState;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.UnsupportedEncodingException;
-import java.math.BigDecimal;
-import java.sql.CallableStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.SQLWarning;
-import java.sql.Time;
-import java.sql.Timestamp;
-import java.sql.Types;
-import java.util.Vector;
-
-/* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/jdbc1/AbstractJdbc1Statement.java,v 1.44 2003/12/12 18:36:19 davec Exp $
- * This class defines methods of the jdbc1 specification. This class is
- * extended by org.postgresql.jdbc2.AbstractJdbc2Statement which adds the jdbc2
- * methods. The real Statement class (for jdbc1) is org.postgresql.jdbc1.Jdbc1Statement
- */
-public abstract class AbstractJdbc1Statement implements BaseStatement
-{
- // The connection who created us
- protected BaseConnection connection;
-
- /** The warnings chain. */
- protected SQLWarning warnings = null;
-
- /** Maximum number of rows to return, 0 = unlimited */
- protected int maxrows = 0;
-
- /** Number of rows to get in a batch. */
- protected int fetchSize = 0;
-
- /** Timeout (in seconds) for a query (not used) */
- protected int timeout = 0;
-
- protected boolean replaceProcessingEnabled = true;
-
- /** The current results */
- protected BaseResultSet result = null;
-
- // Static variables for parsing SQL when replaceProcessing is true.
- private static final short IN_SQLCODE = 0;
- private static final short IN_STRING = 1;
- private static final short BACKSLASH = 2;
- private static final short ESC_TIMEDATE = 3;
-
- // Some performance caches
- private StringBuffer sbuf = new StringBuffer(32);
-
- protected String[] m_sqlFragments; // Query fragments.
- private String[] m_executeSqlFragments; // EXECUTE(...) if useServerPrepare
- protected Object[] m_binds = new Object[0]; // Parameter values
-
- protected String[] m_bindTypes = new String[0]; // Parameter types, for PREPARE(...)
- protected String m_statementName = null; // Allocated PREPARE statement name for server-prepared statements
- protected String m_cursorName = null; // Allocated DECLARE cursor name for cursor-based fetch
-
- // Constants for allowXXX and m_isSingleStatement vars, below.
- // The idea is to defer the cost of examining the query until we really need to know,
- // but don't reexamine it every time thereafter.
-
- private static final short UNKNOWN = 0; // Don't know yet, examine the query.
- private static final short NO = 1; // Don't use feature
- private static final short YES = 2; // Do use feature
-
- private short m_isSingleDML = UNKNOWN; // Is the query a single SELECT/UPDATE/INSERT/DELETE?
- private short m_isSingleSelect = UNKNOWN; // Is the query a single SELECT?
- private short m_isSingleStatement = UNKNOWN; // Is the query a single statement?
-
- private boolean m_useServerPrepare = false;
-
- // m_preparedCount is used for naming of auto-cursors and must
- // be synchronized so that multiple threads using the same
- // connection don't stomp over each others cursors.
- private static int m_preparedCount = 1;
- private synchronized static int next_preparedCount()
- {
- return m_preparedCount++;
- }
-
- //Used by the callablestatement style methods
- private static final String JDBC_SYNTAX = "{[? =] call ([? [,?]*]) }";
- private static final String RESULT_ALIAS = "result";
- private String originalSql = "";
- private boolean isFunction;
- // functionReturnType contains the user supplied value to check
- // testReturn contains a modified version to make it easier to
- // check the getXXX methods..
- private int functionReturnType;
- private int testReturn;
- // returnTypeSet is true when a proper call to registerOutParameter has been made
- private boolean returnTypeSet;
- protected Object callResult;
- protected int maxfieldSize = 0;
-
- public abstract BaseResultSet createResultSet(Field[] fields, Vector tuples, String status, int updateCount, long insertOID, boolean binaryCursor) throws SQLException;
-
- public AbstractJdbc1Statement (BaseConnection connection)
- {
- this.connection = connection;
- }
-
- public AbstractJdbc1Statement (BaseConnection connection, String p_sql) throws SQLException
- {
- this.connection = connection;
- parseSqlStmt(p_sql); // this allows Callable stmt to override
- }
-
- public BaseConnection getPGConnection() {
- return connection;
- }
-
- public String getFetchingCursorName() {
- return m_cursorName;
- }
-
- public int getFetchSize() {
- return fetchSize;
- }
-
- protected void parseSqlStmt (String p_sql) throws SQLException
- {
- String l_sql = p_sql;
-
- l_sql = replaceProcessing(l_sql);
-
- if (this instanceof CallableStatement)
- {
- l_sql = modifyJdbcCall(l_sql);
- }
-
- Vector v = new Vector();
- boolean inQuotes = false;
- int lastParmEnd = 0, i;
-
- m_isSingleSelect = m_isSingleDML = UNKNOWN;
- m_isSingleStatement = YES;
-
- for (i = 0; i < l_sql.length(); ++i)
- {
- int c = l_sql.charAt(i);
-
- if (c == '\'')
- inQuotes = !inQuotes;
- if (c == '?' && !inQuotes)
- {
- v.addElement(l_sql.substring (lastParmEnd, i));
- lastParmEnd = i + 1;
- }
- if (c == ';' && !inQuotes)
- m_isSingleStatement = m_isSingleSelect = m_isSingleDML = NO;
- }
- v.addElement(l_sql.substring (lastParmEnd, l_sql.length()));
-
- m_sqlFragments = new String[v.size()];
- m_binds = new Object[v.size() - 1];
- m_bindTypes = new String[v.size() - 1];
-
- for (i = 0 ; i < m_sqlFragments.length; ++i)
- m_sqlFragments[i] = (String)v.elementAt(i);
-
- }
-
- /*
- * Deallocate resources allocated for the current query
- * in preparation for replacing it with a new query.
- */
- private void deallocateQuery()
- {
- //If we have already created a server prepared statement, we need
- //to deallocate the existing one
- if (m_statementName != null)
- {
- try
- {
- connection.execSQL("DEALLOCATE " + m_statementName);
- }
- catch (Exception e)
- {
- }
- }
-
- m_statementName = null;
- m_cursorName = null; // automatically closed at end of txn anyway
- m_executeSqlFragments = null;
- m_isSingleStatement = m_isSingleSelect = m_isSingleDML = UNKNOWN;
- }
-
- /*
- * Execute a SQL statement that retruns a single ResultSet
- *
- * @param sql typically a static SQL SELECT statement
- * @return a ResulSet that contains the data produced by the query
- * @exception SQLException if a database access error occurs
- */
- public java.sql.ResultSet executeQuery(String p_sql) throws SQLException
- {
- deallocateQuery();
-
- String l_sql = replaceProcessing(p_sql);
- m_sqlFragments = new String[] {l_sql};
- m_binds = new Object[0];
-
- return executeQuery();
- }
-
- /*
- * A Prepared SQL query is executed and its ResultSet is returned
- *
- * @return a ResultSet that contains the data produced by the
- * * query - never null
- * @exception SQLException if a database access error occurs
- */
- public java.sql.ResultSet executeQuery() throws SQLException
- {
- this.execute();
-
- while (result != null && !result.reallyResultSet())
- result = (BaseResultSet) result.getNext();
- if (result == null)
- throw new PSQLException("postgresql.stat.noresult", PSQLState.NO_DATA);
- return (ResultSet) result;
- }
-
- /*
- * Execute a SQL INSERT, UPDATE or DELETE statement. In addition
- * SQL statements that return nothing such as SQL DDL statements
- * can be executed
- *
- * @param sql a SQL statement
- * @return either a row count, or 0 for SQL commands
- * @exception SQLException if a database access error occurs
- */
- public int executeUpdate(String p_sql) throws SQLException
- {
- deallocateQuery();
-
- String l_sql = replaceProcessing(p_sql);
- m_sqlFragments = new String[] {l_sql};
- m_binds = new Object[0];
-
- return executeUpdate();
- }
-
- /*
- * Execute a SQL INSERT, UPDATE or DELETE statement. In addition,
- * SQL statements that return nothing such as SQL DDL statements can
- * be executed.
- *
- * @return either the row count for INSERT, UPDATE or DELETE; or
- * * 0 for SQL statements that return nothing.
- * @exception SQLException if a database access error occurs
- */
- public int executeUpdate() throws SQLException
- {
- this.execute();
- if (result.reallyResultSet())
- throw new PSQLException("postgresql.stat.result");
- return this.getUpdateCount();
- }
-
- /*
- * Execute a SQL statement that may return multiple results. We
- * don't have to worry about this since we do not support multiple
- * ResultSets. You can use getResultSet or getUpdateCount to
- * retrieve the result.
- *
- * @param sql any SQL statement
- * @return true if the next result is a ResulSet, false if it is
- * an update count or there are no more results
- * @exception SQLException if a database access error occurs
- */
- public boolean execute(String p_sql) throws SQLException
- {
- deallocateQuery();
-
- String l_sql = replaceProcessing(p_sql);
- m_sqlFragments = new String[] {l_sql};
- m_binds = new Object[0];
-
- return execute();
- }
-
- /*
- * Check if the current query is a single statement.
- */
- private boolean isSingleStatement()
- {
- if (m_isSingleStatement != UNKNOWN)
- return m_isSingleStatement == YES;
-
- // Crude detection of multiple statements. This could be
- // improved by parsing the whole query for quotes, but is
- // it worth it given that the only queries that get here are
- // unparameterized queries?
-
- for (int i = 0; i < m_sqlFragments.length; ++i) { // a bit redundant, but ..
- if (m_sqlFragments[i].indexOf(';') != -1) {
- m_isSingleStatement = NO;
- return false;
- }
- }
-
- m_isSingleStatement = YES;
- return true;
- }
-
- /*
- * Helper for isSingleSelect() and isSingleDML(): computes values
- * of m_isSingleDML and m_isSingleSelect.
- */
- private void analyzeStatementType()
- {
- if (!isSingleStatement()) {
- m_isSingleSelect = m_isSingleDML = NO;
- return;
- }
-
- String compare = m_sqlFragments[0].trim().toLowerCase();
- if (compare.startsWith("select")) {
- m_isSingleSelect = m_isSingleDML = YES;
- return;
- }
-
- m_isSingleSelect = NO;
-
- if (!compare.startsWith("update") &&
- !compare.startsWith("delete") &&
- !compare.startsWith("insert")) {
- m_isSingleDML = NO;
- return;
- }
-
- m_isSingleDML = YES;
- }
-
- /*
- * Check if the current query is a single SELECT.
- */
- private boolean isSingleSelect()
- {
- if (m_isSingleSelect == UNKNOWN)
- analyzeStatementType();
-
- return m_isSingleSelect == YES;
- }
-
- /*
- * Check if the current query is a single SELECT/UPDATE/INSERT/DELETE.
- */
- private boolean isSingleDML()
- {
- if (m_isSingleDML == UNKNOWN)
- analyzeStatementType();
-
- return m_isSingleDML == YES;
- }
-
- /*
- * Return the query fragments to use for a server-prepared statement.
- * The first query executed will include a PREPARE and EXECUTE;
- * subsequent queries will just be an EXECUTE.
- */
- private String[] transformToServerPrepare() {
- if (m_statementName != null)
- return m_executeSqlFragments;
-
- // First time through.
- m_statementName = "JDBC_STATEMENT_" + m_preparedCount++;
-
- // Set up m_executeSqlFragments
- m_executeSqlFragments = new String[m_sqlFragments.length];
- m_executeSqlFragments[0] = "EXECUTE " + m_statementName;
- if (m_sqlFragments.length > 1) {
- m_executeSqlFragments[0] += "(";
- for (int i = 1; i < m_bindTypes.length; i++)
- m_executeSqlFragments[i] = ", ";
- m_executeSqlFragments[m_bindTypes.length] = ")";
- }
-
- // Set up the PREPARE.
- String[] prepareSqlFragments = new String[m_sqlFragments.length];
- System.arraycopy(m_sqlFragments, 0, prepareSqlFragments, 0, m_sqlFragments.length);
-
- synchronized (sbuf) {
- sbuf.setLength(0);
- sbuf.append("PREPARE ");
- sbuf.append(m_statementName);
- if (m_sqlFragments.length > 1) {
- sbuf.append("(");
- for (int i = 0; i < m_bindTypes.length; i++) {
- if (i != 0) sbuf.append(", ");
- sbuf.append(m_bindTypes[i]);
- }
- sbuf.append(")");
- }
- sbuf.append(" AS ");
- sbuf.append(m_sqlFragments[0]);
- for (int i = 1; i < m_sqlFragments.length; i++) {
- sbuf.append(" $");
- sbuf.append(i);
- sbuf.append(" ");
- sbuf.append(m_sqlFragments[i]);
- }
- sbuf.append("; ");
- sbuf.append(m_executeSqlFragments[0]);
-
- prepareSqlFragments[0] = sbuf.toString();
- }
-
- System.arraycopy(m_executeSqlFragments, 1, prepareSqlFragments, 1, prepareSqlFragments.length - 1);
- return prepareSqlFragments;
- }
-
- /*
- * Return the current query transformed into a cursor-based statement.
- * This uses a new cursor on each query.
- */
- private String[] transformToCursorFetch()
- {
-
- // Pinch the prepared count for our own nefarious purposes.
- m_cursorName = "JDBC_CURS_" + m_preparedCount++;
-
- // Create a cursor declaration and initial fetch statement from the original query.
- int len = m_sqlFragments.length;
- String[] cursorBasedSql = new String[len];
- System.arraycopy(m_sqlFragments, 0, cursorBasedSql, 0, len);
- cursorBasedSql[0] = "DECLARE " + m_cursorName + " CURSOR FOR " + cursorBasedSql[0];
- cursorBasedSql[len-1] += "; FETCH FORWARD " + fetchSize + " FROM " + m_cursorName;
-
- // Make the cursor based query the one that will be used.
- if (org.postgresql.Driver.logDebug)
- org.postgresql.Driver.debug("using cursor based sql with cursor name " + m_cursorName);
-
- return cursorBasedSql;
- }
-
- /**
- * Do transformations to a query for server-side prepare or setFetchSize() cursor
- * work.
- * @return the query fragments to execute
- */
- private String[] getQueryFragments()
- {
- // nb: isSingleXXX() are relatively expensive, avoid calling them unless we must.
-
- // We check the "mutable" bits of these conditions (which may change without
- // a new query being created) here; isSingleXXX() only concern themselves with
- // the query structure itself.
-
- // We prefer cursor-based-fetch over server-side-prepare here.
- // Eventually a v3 implementation should let us do both at once.
- if (fetchSize > 0 && !connection.getAutoCommit() && isSingleSelect())
- return transformToCursorFetch();
-
- if (isUseServerPrepare() && isSingleDML())
- return transformToServerPrepare();
-
- // Not server-prepare or cursor-fetch, just return a plain query.
- return m_sqlFragments;
- }
-
- /*
- * Some prepared statements return multiple results; the execute method
- * handles these complex statements as well as the simpler form of
- * statements handled by executeQuery and executeUpdate
- *
- * @return true if the next result is a ResultSet; false if it is an
- * update count or there are no more results
- * @exception SQLException if a database access error occurs
- */
- public boolean execute() throws SQLException
- {
- if (isFunction && !returnTypeSet)
- throw new PSQLException("postgresql.call.noreturntype", PSQLState.STATEMENT_NOT_ALLOWED_IN_FUNCTION_CALL);
- if (isFunction)
- { // set entry 1 to dummy entry..
- m_binds[0] = ""; // dummy entry which ensured that no one overrode
- m_bindTypes[0] = PG_TEXT;
- // and calls to setXXX (2,..) really went to first arg in a function call..
- }
-
- // New in 7.1, if we have a previous resultset then force it to close
- // This brings us nearer to compliance, and helps memory management.
- // Internal stuff will call ExecSQL directly, bypassing this.
-
- if (result != null)
- {
- java.sql.ResultSet rs = getResultSet();
- if (rs != null)
- rs.close();
- }
-
- // Get the actual query fragments to run (might be a transformed version of
- // the original fragments)
- String[] fragments = getQueryFragments();
-
- // New in 7.1, pass Statement so that ExecSQL can customise to it
- result = QueryExecutor.execute(fragments,
- m_binds,
- this);
-
- //If we are executing a callable statement function set the return data
- if (isFunction)
- {
- if (!result.reallyResultSet())
- throw new PSQLException("postgresql.call.noreturnval", PSQLState.NO_DATA);
- if (!result.next ())
- throw new PSQLException ("postgresql.call.noreturnval", PSQLState.NO_DATA);
- callResult = result.getObject(1);
- int columnType = result.getMetaData().getColumnType(1);
- if (columnType != functionReturnType)
- throw new PSQLException ("postgresql.call.wrongrtntype", PSQLState.DATA_TYPE_MISMATCH,
- new Object[]{
- "java.sql.Types=" + columnType, "java.sql.Types=" + functionReturnType });
- result.close ();
- return true;
- }
- else
- {
- return (result != null && result.reallyResultSet());
- }
- }
-
- /*
- * setCursorName defines the SQL cursor name that will be used by
- * subsequent execute methods. This name can then be used in SQL
- * positioned update/delete statements to identify the current row
- * in the ResultSet generated by this statement. If a database
- * doesn't support positioned update/delete, this method is a
- * no-op.
- *
- *
Note: By definition, positioned update/delete execution
- * must be done by a different Statement than the one which
- * generated the ResultSet being used for positioning. Also, cursor
- * names must be unique within a Connection.
- *
- *
We throw an additional constriction. There can only be one
- * cursor active at any one time.
- *
- * @param name the new cursor name
- * @exception SQLException if a database access error occurs
- */
- public void setCursorName(String name) throws SQLException
- {
- connection.setCursorName(name);
- }
-
-
- /*
- * getUpdateCount returns the current result as an update count,
- * if the result is a ResultSet or there are no more results, -1
- * is returned. It should only be called once per result.
- *
- * @return the current result as an update count.
- * @exception SQLException if a database access error occurs
- */
- public int getUpdateCount() throws SQLException
- {
- if (result == null)
- return -1;
- if (isFunction)
- return 1;
- if (result.reallyResultSet())
- return -1;
- return result.getResultCount();
- }
-
- /*
- * getMoreResults moves to a Statement's next result. If it returns
- * true, this result is a ResulSet.
- *
- * @return true if the next ResultSet is valid
- * @exception SQLException if a database access error occurs
- */
- public boolean getMoreResults() throws SQLException
- {
- result = (BaseResultSet) result.getNext();
- return (result != null && result.reallyResultSet());
- }
-
-
-
- /*
- * Returns the status message from the current Result.
- * This is used internally by the driver.
- *
- * @return status message from backend
- */
- public String getResultStatusString()
- {
- if (result == null)
- return null;
- return result.getStatusString();
- }
-
- /*
- * The maxRows limit is set to limit the number of rows that
- * any ResultSet can contain. If the limit is exceeded, the
- * excess rows are silently dropped.
- *
- * @return the current maximum row limit; zero means unlimited
- * @exception SQLException if a database access error occurs
- */
- public int getMaxRows() throws SQLException
- {
- return maxrows;
- }
-
- /*
- * Set the maximum number of rows
- *
- * @param max the new max rows limit; zero means unlimited
- * @exception SQLException if a database access error occurs
- * @see getMaxRows
- */
- public void setMaxRows(int max) throws SQLException
- {
- if (max<0) throw new PSQLException("postgresql.input.rows.gt0");
- maxrows = max;
- }
-
- /*
- * If escape scanning is on (the default), the driver will do escape
- * substitution before sending the SQL to the database.
- *
- * @param enable true to enable; false to disable
- * @exception SQLException if a database access error occurs
- */
- public void setEscapeProcessing(boolean enable) throws SQLException
- {
- replaceProcessingEnabled = enable;
- }
-
- /*
- * The queryTimeout limit is the number of seconds the driver
- * will wait for a Statement to execute. If the limit is
- * exceeded, a SQLException is thrown.
- *
- * @return the current query timeout limit in seconds; 0 = unlimited
- * @exception SQLException if a database access error occurs
- */
- public int getQueryTimeout() throws SQLException
- {
- return timeout;
- }
-
- /*
- * Sets the queryTimeout limit
- *
- * @param seconds - the new query timeout limit in seconds
- * @exception SQLException if a database access error occurs
- */
- public void setQueryTimeout(int seconds) throws SQLException
- {
- if (seconds<0) throw new PSQLException("postgresql.input.query.gt0");
- timeout = seconds;
- }
-
- /**
- * This adds a warning to the warning chain.
- * @param msg message to add
- */
- public void addWarning(String msg)
- {
- if (warnings != null)
- warnings.setNextWarning(new SQLWarning(msg));
- else
- warnings = new SQLWarning(msg);
- }
-
- /*
- * The first warning reported by calls on this Statement is
- * returned. A Statement's execute methods clear its SQLWarning
- * chain. Subsequent Statement warnings will be chained to this
- * SQLWarning.
- *
- *
The Warning chain is automatically cleared each time a statement
- * is (re)executed.
- *
- *
Note: If you are processing a ResultSet then any warnings
- * associated with ResultSet reads will be chained on the ResultSet
- * object.
- *
- * @return the first SQLWarning on null
- * @exception SQLException if a database access error occurs
- */
- public SQLWarning getWarnings() throws SQLException
- {
- return warnings;
- }
-
- /*
- * The maxFieldSize limit (in bytes) is the maximum amount of
- * data returned for any column value; it only applies to
- * BINARY, VARBINARY, LONGVARBINARY, CHAR, VARCHAR and LONGVARCHAR
- * columns. If the limit is exceeded, the excess data is silently
- * discarded.
- *
- * @return the current max column size limit; zero means unlimited
- * @exception SQLException if a database access error occurs
- */
- public int getMaxFieldSize() throws SQLException
- {
- return maxfieldSize;
- }
-
- /*
- * Sets the maxFieldSize
- *
- * @param max the new max column size limit; zero means unlimited
- * @exception SQLException if a database access error occurs
- */
- public void setMaxFieldSize(int max) throws SQLException
- {
- if (max < 0) throw new PSQLException("postgresql.input.field.gt0");
- maxfieldSize = max;
- }
-
- /*
- * After this call, getWarnings returns null until a new warning
- * is reported for this Statement.
- *
- * @exception SQLException if a database access error occurs
- */
- public void clearWarnings() throws SQLException
- {
- warnings = null;
- }
-
- /*
- * Cancel can be used by one thread to cancel a statement that
- * is being executed by another thread.
- * Not implemented, this method is a no-op.
- *
- * @exception SQLException only because thats the spec.
- */
- public void cancel() throws SQLException
- {
- throw new PSQLException("postgresql.unimplemented", PSQLState.NOT_IMPLEMENTED);
- }
-
- /*
- * getResultSet returns the current result as a ResultSet. It
- * should only be called once per result.
- *
- * @return the current result set; null if there are no more
- * @exception SQLException if a database access error occurs (why?)
- */
- public java.sql.ResultSet getResultSet() throws SQLException
- {
- if (result != null && result.reallyResultSet())
- return (ResultSet) result;
- return null;
- }
-
- /*
- * In many cases, it is desirable to immediately release a
- * Statement's database and JDBC resources instead of waiting
- * for this to happen when it is automatically closed. The
- * close method provides this immediate release.
- *
- *
Note: A Statement is automatically closed when it is
- * garbage collected. When a Statement is closed, its current
- * ResultSet, if one exists, is also closed.
- *
- * @exception SQLException if a database access error occurs (why?)
- */
- public void close() throws SQLException
- {
- // Force the ResultSet to close
- java.sql.ResultSet rs = getResultSet();
- if (rs != null)
- rs.close();
-
- deallocateQuery();
-
- // Disasociate it from us (For Garbage Collection)
- result = null;
- }
-
- /**
- * This finalizer ensures that statements that have allocated server-side
- * resources free them when they become unreferenced.
- */
- protected void finalize() {
- try { close(); }
- catch (SQLException e) {}
- }
-
- /*
- * Filter the SQL string of Java SQL Escape clauses.
- *
- * Currently implemented Escape clauses are those mentioned in 11.3
- * in the specification. Basically we look through the sql string for
- * {d xxx}, {t xxx} or {ts xxx} in non-string sql code. When we find
- * them, we just strip the escape part leaving only the xxx part.
- * So, something like "select * from x where d={d '2001-10-09'}" would
- * return "select * from x where d= '2001-10-09'".
- */
- protected String replaceProcessing(String p_sql)
- {
- if (replaceProcessingEnabled)
- {
- // Since escape codes can only appear in SQL CODE, we keep track
- // of if we enter a string or not.
- StringBuffer newsql = new StringBuffer(p_sql.length());
- short state = IN_SQLCODE;
-
- int i = -1;
- int len = p_sql.length();
- while (++i < len)
- {
- char c = p_sql.charAt(i);
- switch (state)
- {
- case IN_SQLCODE:
- if (c == '\'') // start of a string?
- state = IN_STRING;
- else if (c == '{') // start of an escape code?
- if (i + 1 < len)
- {
- char next = p_sql.charAt(i + 1);
- if (next == 'd')
- {
- state = ESC_TIMEDATE;
- i++;
- break;
- }
- else if (next == 't')
- {
- state = ESC_TIMEDATE;
- i += (i + 2 < len && p_sql.charAt(i + 2) == 's') ? 2 : 1;
- break;
- }
- }
- newsql.append(c);
- break;
-
- case IN_STRING:
- if (c == '\'') // end of string?
- state = IN_SQLCODE;
- else if (c == '\\') // a backslash?
- state = BACKSLASH;
-
- newsql.append(c);
- break;
-
- case BACKSLASH:
- state = IN_STRING;
-
- newsql.append(c);
- break;
-
- case ESC_TIMEDATE:
- if (c == '}')
- state = IN_SQLCODE; // end of escape code.
- else
- newsql.append(c);
- break;
- } // end switch
- }
-
- return newsql.toString();
- }
- else
- {
- return p_sql;
- }
- }
-
- /*
- *
- * The following methods are postgres extensions and are defined
- * in the interface BaseStatement
- *
- */
-
- /*
- * Returns the Last inserted/updated oid. Deprecated in 7.2 because
- * range of OID values is greater than a java signed int.
- * @deprecated Replaced by getLastOID in 7.2
- */
- public int getInsertedOID() throws SQLException
- {
- if (result == null)
- return 0;
- return (int) result.getLastOID();
- }
-
- /*
- * Returns the Last inserted/updated oid.
- * @return OID of last insert
- * @since 7.2
- */
- public long getLastOID() throws SQLException
- {
- if (result == null)
- return 0;
- return result.getLastOID();
- }
-
- /*
- * Set a parameter to SQL NULL
- *
- *
Note: You must specify the parameters SQL type (although
- * PostgreSQL ignores it)
- *
- * @param parameterIndex the first parameter is 1, etc...
- * @param sqlType the SQL type code defined in java.sql.Types
- * @exception SQLException if a database access error occurs
- */
- public void setNull(int parameterIndex, int sqlType) throws SQLException
- {
- String l_pgType;
- switch (sqlType)
- {
- case Types.INTEGER:
- l_pgType = PG_INTEGER;
- break;
- case Types.TINYINT:
- case Types.SMALLINT:
- l_pgType = PG_INT2;
- break;
- case Types.BIGINT:
- l_pgType = PG_INT8;
- break;
- case Types.REAL:
- case Types.FLOAT:
- l_pgType = PG_FLOAT;
- break;
- case Types.DOUBLE:
- l_pgType = PG_DOUBLE;
- break;
- case Types.DECIMAL:
- case Types.NUMERIC:
- l_pgType = PG_NUMERIC;
- break;
- case Types.CHAR:
- case Types.VARCHAR:
- case Types.LONGVARCHAR:
- l_pgType = PG_TEXT;
- break;
- case Types.DATE:
- l_pgType = PG_DATE;
- break;
- case Types.TIME:
- l_pgType = PG_TIME;
- break;
- case Types.TIMESTAMP:
- l_pgType = PG_TIMESTAMPTZ;
- break;
- case Types.BIT:
- l_pgType = PG_BOOLEAN;
- break;
- case Types.BINARY:
- case Types.VARBINARY:
- case Types.LONGVARBINARY:
- l_pgType = PG_BYTEA;
- break;
- case Types.OTHER:
- l_pgType = PG_TEXT;
- break;
- default:
- l_pgType = PG_TEXT;
- }
- bind(parameterIndex, "null", l_pgType);
- }
-
- /*
- * Set a parameter to a Java boolean value. The driver converts this
- * to a SQL BIT value when it sends it to the database.
- *
- * @param parameterIndex the first parameter is 1...
- * @param x the parameter value
- * @exception SQLException if a database access error occurs
- */
- public void setBoolean(int parameterIndex, boolean x) throws SQLException
- {
- bind(parameterIndex, x ? "'1'" : "'0'", PG_BOOLEAN);
- }
-
- /*
- * Set a parameter to a Java byte value. The driver converts this to
- * a SQL TINYINT value when it sends it to the database.
- *
- * @param parameterIndex the first parameter is 1...
- * @param x the parameter value
- * @exception SQLException if a database access error occurs
- */
- public void setByte(int parameterIndex, byte x) throws SQLException
- {
- bind(parameterIndex, Integer.toString(x), PG_INT2);
- }
-
- /*
- * Set a parameter to a Java short value. The driver converts this
- * to a SQL SMALLINT value when it sends it to the database.
- *
- * @param parameterIndex the first parameter is 1...
- * @param x the parameter value
- * @exception SQLException if a database access error occurs
- */
- public void setShort(int parameterIndex, short x) throws SQLException
- {
- bind(parameterIndex, Integer.toString(x), PG_INT2);
- }
-
- /*
- * Set a parameter to a Java int value. The driver converts this to
- * a SQL INTEGER value when it sends it to the database.
- *
- * @param parameterIndex the first parameter is 1...
- * @param x the parameter value
- * @exception SQLException if a database access error occurs
- */
- public void setInt(int parameterIndex, int x) throws SQLException
- {
- bind(parameterIndex, Integer.toString(x), PG_INTEGER);
- }
-
- /*
- * Set a parameter to a Java long value. The driver converts this to
- * a SQL BIGINT value when it sends it to the database.
- *
- * @param parameterIndex the first parameter is 1...
- * @param x the parameter value
- * @exception SQLException if a database access error occurs
- */
- public void setLong(int parameterIndex, long x) throws SQLException
- {
- bind(parameterIndex, Long.toString(x), PG_INT8);
- }
-
- /*
- * Set a parameter to a Java float value. The driver converts this
- * to a SQL FLOAT value when it sends it to the database.
- *
- * @param parameterIndex the first parameter is 1...
- * @param x the parameter value
- * @exception SQLException if a database access error occurs
- */
- public void setFloat(int parameterIndex, float x) throws SQLException
- {
- bind(parameterIndex, Float.toString(x), PG_FLOAT);
- }
-
- /*
- * Set a parameter to a Java double value. The driver converts this
- * to a SQL DOUBLE value when it sends it to the database
- *
- * @param parameterIndex the first parameter is 1...
- * @param x the parameter value
- * @exception SQLException if a database access error occurs
- */
- public void setDouble(int parameterIndex, double x) throws SQLException
- {
- bind(parameterIndex, Double.toString(x), PG_DOUBLE);
- }
-
- /*
- * Set a parameter to a java.lang.BigDecimal value. The driver
- * converts this to a SQL NUMERIC value when it sends it to the
- * database.
- *
- * @param parameterIndex the first parameter is 1...
- * @param x the parameter value
- * @exception SQLException if a database access error occurs
- */
- public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException
- {
- if (x == null)
- setNull(parameterIndex, Types.DECIMAL);
- else
- {
- bind(parameterIndex, x.toString(), PG_NUMERIC);
- }
- }
-
- /*
- * Set a parameter to a Java String value. The driver converts this
- * to a SQL VARCHAR or LONGVARCHAR value (depending on the arguments
- * size relative to the driver's limits on VARCHARs) when it sends it
- * to the database.
- *
- * @param parameterIndex the first parameter is 1...
- * @param x the parameter value
- * @exception SQLException if a database access error occurs
- */
- public void setString(int parameterIndex, String x) throws SQLException
- {
- setString(parameterIndex, x, PG_TEXT);
- }
-
- public void setString(int parameterIndex, String x, String type) throws SQLException
- {
- // if the passed string is null, then set this column to null
- if (x == null)
- setNull(parameterIndex, Types.VARCHAR);
- else
- {
- // use the shared buffer object. Should never clash but this makes
- // us thread safe!
- synchronized (sbuf)
- {
- sbuf.setLength(0);
- sbuf.ensureCapacity(2 + x.length() + (int)(x.length() / 10));
- sbuf.append('\'');
- escapeString(x, sbuf);
- sbuf.append('\'');
- bind(parameterIndex, sbuf.toString(), type);
- }
- }
- }
-
- private void escapeString(String p_input, StringBuffer p_output) {
- for (int i = 0 ; i < p_input.length() ; ++i)
- {
- char c = p_input.charAt(i);
- switch (c)
- {
- case '\\':
- case '\'':
- p_output.append('\\');
- p_output.append(c);
- break;
- case '\0':
- throw new IllegalArgumentException("\\0 not allowed");
- default:
- p_output.append(c);
- }
- }
- }
-
-
- /*
- * Set a parameter to a Java array of bytes. The driver converts this
- * to a SQL VARBINARY or LONGVARBINARY (depending on the argument's
- * size relative to the driver's limits on VARBINARYs) when it sends
- * it to the database.
- *
- *
With org.postgresql, this creates a large object, and stores the
- * objects oid in this column.
- *
- * @param parameterIndex the first parameter is 1...
- * @param x the parameter value
- * @exception SQLException if a database access error occurs
- */
- public void setBytes(int parameterIndex, byte x[]) throws SQLException
- {
- if (connection.haveMinimumCompatibleVersion("7.2"))
- {
- //Version 7.2 supports the bytea datatype for byte arrays
- if (null == x)
- {
- setNull(parameterIndex, Types.VARBINARY);
- }
- else
- {
- setString(parameterIndex, PGbytea.toPGString(x), PG_BYTEA);
- }
- }
- else
- {
- //Version 7.1 and earlier support done as LargeObjects
- LargeObjectManager lom = connection.getLargeObjectAPI();
- int oid = lom.create();
- LargeObject lob = lom.open(oid);
- lob.write(x);
- lob.close();
- setInt(parameterIndex, oid);
- }
- }
-
- /*
- * Set a parameter to a java.sql.Date value. The driver converts this
- * to a SQL DATE value when it sends it to the database.
- *
- * @param parameterIndex the first parameter is 1...
- * @param x the parameter value
- * @exception SQLException if a database access error occurs
- */
- public void setDate(int parameterIndex, java.sql.Date x) throws SQLException
- {
- if (null == x)
- {
- setNull(parameterIndex, Types.DATE);
- }
- else
- {
- bind(parameterIndex, "'" + x.toString() + "'", PG_DATE);
- }
- }
-
- /*
- * Set a parameter to a java.sql.Time value. The driver converts
- * this to a SQL TIME value when it sends it to the database.
- *
- * @param parameterIndex the first parameter is 1...));
- * @param x the parameter value
- * @exception SQLException if a database access error occurs
- */
- public void setTime(int parameterIndex, Time x) throws SQLException
- {
- if (null == x)
- {
- setNull(parameterIndex, Types.TIME);
- }
- else
- {
- bind(parameterIndex, "'" + x.toString() + "'", PG_TIME);
- }
- }
-
- /*
- * Set a parameter to a java.sql.Timestamp value. The driver converts
- * this to a SQL TIMESTAMP value when it sends it to the database.
- *
- * @param parameterIndex the first parameter is 1...
- * @param x the parameter value
- * @exception SQLException if a database access error occurs
- */
- public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException
- {
- if (null == x)
- {
- setNull(parameterIndex, Types.TIMESTAMP);
- }
- else
- {
- // Use the shared StringBuffer
- synchronized (sbuf)
- {
- sbuf.setLength(0);
- sbuf.ensureCapacity(32);
- sbuf.append("'");
- //format the timestamp
- //we do our own formating so that we can get a format
- //that works with both timestamp with time zone and
- //timestamp without time zone datatypes.
- //The format is '2002-01-01 23:59:59.123456-0130'
- //we need to include the local time and timezone offset
- //so that timestamp without time zone works correctly
- int l_year = x.getYear() + 1900;
- sbuf.append(l_year);
- sbuf.append('-');
- int l_month = x.getMonth() + 1;
- if (l_month < 10)
- sbuf.append('0');
- sbuf.append(l_month);
- sbuf.append('-');
- int l_day = x.getDate();
- if (l_day < 10)
- sbuf.append('0');
- sbuf.append(l_day);
- sbuf.append(' ');
- int l_hours = x.getHours();
- if (l_hours < 10)
- sbuf.append('0');
- sbuf.append(l_hours);
- sbuf.append(':');
- int l_minutes = x.getMinutes();
- if (l_minutes < 10)
- sbuf.append('0');
- sbuf.append(l_minutes);
- sbuf.append(':');
- int l_seconds = x.getSeconds();
- if (l_seconds < 10)
- sbuf.append('0');
- sbuf.append(l_seconds);
- // Make decimal from nanos.
- char[] l_decimal = {'0', '0', '0', '0', '0', '0', '0', '0', '0'};
- char[] l_nanos = Integer.toString(x.getNanos()).toCharArray();
- System.arraycopy(l_nanos, 0, l_decimal, l_decimal.length - l_nanos.length, l_nanos.length);
- sbuf.append('.');
- if (connection.haveMinimumServerVersion("7.2"))
- {
- sbuf.append(l_decimal, 0, 6);
- }
- else
- {
- // Because 7.1 include bug that "hh:mm:59.999" becomes "hh:mm:60.00".
- sbuf.append(l_decimal, 0, 2);
- }
- //add timezone offset
- int l_offset = -(x.getTimezoneOffset());
- int l_houros = l_offset / 60;
- if (l_houros >= 0)
- {
- sbuf.append('+');
- }
- else
- {
- sbuf.append('-');
- }
- if (l_houros > -10 && l_houros < 10)
- sbuf.append('0');
- if (l_houros >= 0)
- {
- sbuf.append(l_houros);
- }
- else
- {
- sbuf.append(-l_houros);
- }
- int l_minos = l_offset - (l_houros * 60);
- if (l_minos != 0)
- {
- if (l_minos > -10 && l_minos < 10)
- sbuf.append('0');
- if (l_minos >= 0)
- {
- sbuf.append(l_minos);
- }
- else
- {
- sbuf.append(-l_minos);
- }
- }
- sbuf.append("'");
- bind(parameterIndex, sbuf.toString(), PG_TIMESTAMPTZ);
- }
-
- }
- }
-
- /*
- * When a very large ASCII value is input to a LONGVARCHAR parameter,
- * it may be more practical to send it via a java.io.InputStream.
- * JDBC will read the data from the stream as needed, until it reaches
- * end-of-file. The JDBC driver will do any necessary conversion from
- * ASCII to the database char format.
- *
- *
Note: This stream object can either be a standard Java
- * stream object or your own subclass that implements the standard
- * interface.
- *
- * @param parameterIndex the first parameter is 1...
- * @param x the parameter value
- * @param length the number of bytes in the stream
- * @exception SQLException if a database access error occurs
- */
- public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException
- {
- if (connection.haveMinimumCompatibleVersion("7.2"))
- {
- //Version 7.2 supports AsciiStream for all PG text types (char, varchar, text)
- //As the spec/javadoc for this method indicate this is to be used for
- //large String values (i.e. LONGVARCHAR) PG doesn't have a separate
- //long varchar datatype, but with toast all text datatypes are capable of
- //handling very large values. Thus the implementation ends up calling
- //setString() since there is no current way to stream the value to the server
- try
- {
- InputStreamReader l_inStream = new InputStreamReader(x, "ASCII");
- char[] l_chars = new char[length];
- int l_charsRead = l_inStream.read(l_chars, 0, length);
- setString(parameterIndex, new String(l_chars, 0, l_charsRead), PG_TEXT);
- }
- catch (UnsupportedEncodingException l_uee)
- {
- throw new PSQLException("postgresql.unusual", PSQLState.UNEXPECTED_ERROR, l_uee);
- }
- catch (IOException l_ioe)
- {
- throw new PSQLException("postgresql.unusual", PSQLState.UNEXPECTED_ERROR, l_ioe);
- }
- }
- else
- {
- //Version 7.1 supported only LargeObjects by treating everything
- //as binary data
- setBinaryStream(parameterIndex, x, length);
- }
- }
-
- /*
- * When a very large Unicode value is input to a LONGVARCHAR parameter,
- * it may be more practical to send it via a java.io.InputStream.
- * JDBC will read the data from the stream as needed, until it reaches
- * end-of-file. The JDBC driver will do any necessary conversion from
- * UNICODE to the database char format.
- *
- *
Note: This stream object can either be a standard Java
- * stream object or your own subclass that implements the standard
- * interface.
- *
- * @param parameterIndex the first parameter is 1...
- * @param x the parameter value
- * @exception SQLException if a database access error occurs
- */
- public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException
- {
- if (connection.haveMinimumCompatibleVersion("7.2"))
- {
- //Version 7.2 supports AsciiStream for all PG text types (char, varchar, text)
- //As the spec/javadoc for this method indicate this is to be used for
- //large String values (i.e. LONGVARCHAR) PG doesn't have a separate
- //long varchar datatype, but with toast all text datatypes are capable of
- //handling very large values. Thus the implementation ends up calling
- //setString() since there is no current way to stream the value to the server
- try
- {
- InputStreamReader l_inStream = new InputStreamReader(x, "UTF-8");
- char[] l_chars = new char[length];
- int l_charsRead = l_inStream.read(l_chars, 0, length);
- setString(parameterIndex, new String(l_chars, 0, l_charsRead), PG_TEXT);
- }
- catch (UnsupportedEncodingException l_uee)
- {
- throw new PSQLException("postgresql.unusual", PSQLState.UNEXPECTED_ERROR, l_uee);
- }
- catch (IOException l_ioe)
- {
- throw new PSQLException("postgresql.unusual", PSQLState.UNEXPECTED_ERROR, l_ioe);
- }
- }
- else
- {
- //Version 7.1 supported only LargeObjects by treating everything
- //as binary data
- setBinaryStream(parameterIndex, x, length);
- }
- }
-
- /*
- * When a very large binary value is input to a LONGVARBINARY parameter,
- * it may be more practical to send it via a java.io.InputStream.
- * JDBC will read the data from the stream as needed, until it reaches
- * end-of-file.
- *
- *
Note: This stream object can either be a standard Java
- * stream object or your own subclass that implements the standard
- * interface.
- *
- * @param parameterIndex the first parameter is 1...
- * @param x the parameter value
- * @exception SQLException if a database access error occurs
- */
- public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException
- {
- if (connection.haveMinimumCompatibleVersion("7.2"))
- {
- //Version 7.2 supports BinaryStream for for the PG bytea type
- //As the spec/javadoc for this method indicate this is to be used for
- //large binary values (i.e. LONGVARBINARY) PG doesn't have a separate
- //long binary datatype, but with toast the bytea datatype is capable of
- //handling very large values. Thus the implementation ends up calling
- //setBytes() since there is no current way to stream the value to the server
- byte[] l_bytes = new byte[length];
- int l_bytesRead;
- try
- {
- l_bytesRead = x.read(l_bytes, 0, length);
- }
- catch (IOException l_ioe)
- {
- throw new PSQLException("postgresql.unusual", PSQLState.UNEXPECTED_ERROR, l_ioe);
- }
- if (l_bytesRead == length)
- {
- setBytes(parameterIndex, l_bytes);
- }
- // x.read will return -1 not 0 on an empty InputStream
- else if (l_bytesRead == -1)
- {
- setBytes(parameterIndex, new byte[0]);
- }
- else
- {
- //the stream contained less data than they said
- byte[] l_bytes2 = new byte[l_bytesRead];
- System.arraycopy(l_bytes, 0, l_bytes2, 0, l_bytesRead);
- setBytes(parameterIndex, l_bytes2);
- }
- }
- else
- {
- //Version 7.1 only supported streams for LargeObjects
- //but the jdbc spec indicates that streams should be
- //available for LONGVARBINARY instead
- LargeObjectManager lom = connection.getLargeObjectAPI();
- int oid = lom.create();
- LargeObject lob = lom.open(oid);
- OutputStream los = lob.getOutputStream();
- try
- {
- // could be buffered, but then the OutputStream returned by LargeObject
- // is buffered internally anyhow, so there would be no performance
- // boost gained, if anything it would be worse!
- int c = x.read();
- int p = 0;
- while (c > -1 && p < length)
- {
- los.write(c);
- c = x.read();
- p++;
- }
- los.close();
- }
- catch (IOException se)
- {
- throw new PSQLException("postgresql.unusual", PSQLState.UNEXPECTED_ERROR, se);
- }
- // lob is closed by the stream so don't call lob.close()
- setInt(parameterIndex, oid);
- }
- }
-
-
- /*
- * In general, parameter values remain in force for repeated used of a
- * Statement. Setting a parameter value automatically clears its
- * previous value. However, in coms cases, it is useful to immediately
- * release the resources used by the current parameter values; this
- * can be done by calling clearParameters
- *
- * @exception SQLException if a database access error occurs
- */
- public void clearParameters() throws SQLException
- {
- int i;
-
- for (i = 0 ; i < m_binds.length ; i++)
- {
- m_binds[i] = null;
- m_bindTypes[i] = null;
- }
- }
-
- // Helper method that extracts numeric values from an arbitary Object.
- private String numericValueOf(Object x)
- {
- if (x instanceof Boolean)
- return ((Boolean)x).booleanValue() ? "1" :"0";
- else if (x instanceof Integer || x instanceof Long ||
- x instanceof Double || x instanceof Short ||
- x instanceof Number || x instanceof Float)
- return x.toString();
- else
- //ensure the value is a valid numeric value to avoid
- //sql injection attacks
- return new BigDecimal(x.toString()).toString();
- }
-
- /*
- * Set the value of a parameter using an object; use the java.lang
- * equivalent objects for integral values.
- *
- *
The given Java object will be converted to the targetSqlType before
- * being sent to the database.
- *
- *
note that this method may be used to pass database-specific
- * abstract data types. This is done by using a Driver-specific
- * Java type and using a targetSqlType of java.sql.Types.OTHER
- *
- * @param parameterIndex the first parameter is 1...
- * @param x the object containing the input parameter value
- * @param targetSqlType The SQL type to be send to the database
- * @param scale For java.sql.Types.DECIMAL or java.sql.Types.NUMERIC
- * * types this is the number of digits after the decimal. For
- * * all other types this value will be ignored.
- * @exception SQLException if a database access error occurs
- */
- public void setObject(int parameterIndex, Object x, int targetSqlType, int scale) throws SQLException
- {
- if (x == null)
- {
- setNull(parameterIndex, targetSqlType);
- return ;
- }
- switch (targetSqlType)
- {
- case Types.INTEGER:
- bind(parameterIndex, numericValueOf(x), PG_INTEGER);
- break;
- case Types.TINYINT:
- case Types.SMALLINT:
- bind(parameterIndex, numericValueOf(x), PG_INT2);
- break;
- case Types.BIGINT:
- bind(parameterIndex, numericValueOf(x), PG_INT8);
- break;
- case Types.REAL:
- case Types.FLOAT:
- bind(parameterIndex, numericValueOf(x), PG_FLOAT);
- break;
- case Types.DOUBLE:
- bind(parameterIndex, numericValueOf(x), PG_DOUBLE);
- break;
- case Types.DECIMAL:
- case Types.NUMERIC:
- bind(parameterIndex, numericValueOf(x), PG_NUMERIC);
- break;
- case Types.CHAR:
- case Types.VARCHAR:
- case Types.LONGVARCHAR:
- setString(parameterIndex, x.toString());
- break;
- case Types.DATE:
- if (x instanceof java.sql.Date)
- setDate(parameterIndex, (java.sql.Date)x);
- else
- {
- java.sql.Date tmpd = (x instanceof java.util.Date) ? new java.sql.Date(((java.util.Date)x).getTime()) : dateFromString(x.toString());
- setDate(parameterIndex, tmpd);
- }
- break;
- case Types.TIME:
- if (x instanceof java.sql.Time)
- setTime(parameterIndex, (java.sql.Time)x);
- else
- {
- java.sql.Time tmpt = (x instanceof java.util.Date) ? new java.sql.Time(((java.util.Date)x).getTime()) : timeFromString(x.toString());
- setTime(parameterIndex, tmpt);
- }
- break;
- case Types.TIMESTAMP:
- if (x instanceof java.sql.Timestamp)
- setTimestamp(parameterIndex ,(java.sql.Timestamp)x);
- else
- {
- java.sql.Timestamp tmpts = (x instanceof java.util.Date) ? new java.sql.Timestamp(((java.util.Date)x).getTime()) : timestampFromString(x.toString());
- setTimestamp(parameterIndex, tmpts);
- }
- break;
- case Types.BIT:
- if (x instanceof Boolean)
- {
- bind(parameterIndex, ((Boolean)x).booleanValue() ? "'1'" : "'0'", PG_BOOLEAN);
- }
- else if (x instanceof String)
- {
- bind(parameterIndex, Boolean.valueOf(x.toString()).booleanValue() ? "'1'" : "'0'", PG_BOOLEAN);
- }
- else if (x instanceof Number)
- {
- bind(parameterIndex, ((Number)x).intValue()!=0 ? "'1'" : "'0'", PG_BOOLEAN);
- }
- else
- {
- throw new PSQLException("postgresql.prep.type", PSQLState.INVALID_PARAMETER_TYPE);
- }
- break;
- case Types.BINARY:
- case Types.VARBINARY:
- case Types.LONGVARBINARY:
- setObject(parameterIndex, x);
- break;
- case Types.OTHER:
- if (x instanceof PGobject)
- setString(parameterIndex, ((PGobject)x).getValue(), ((PGobject)x).getType());
- else
- throw new PSQLException("postgresql.prep.type", PSQLState.INVALID_PARAMETER_TYPE);
- break;
- default:
- throw new PSQLException("postgresql.prep.type", PSQLState.INVALID_PARAMETER_TYPE);
- }
- }
-
- public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException
- {
- setObject(parameterIndex, x, targetSqlType, 0);
- }
-
- /*
- * This stores an Object into a parameter.
- */
- public void setObject(int parameterIndex, Object x) throws SQLException
- {
- if (x == null)
- {
- setNull(parameterIndex, Types.OTHER);
- return ;
- }
- if (x instanceof String)
- setString(parameterIndex, (String)x);
- else if (x instanceof BigDecimal)
- setBigDecimal(parameterIndex, (BigDecimal)x);
- else if (x instanceof Short)
- setShort(parameterIndex, ((Short)x).shortValue());
- else if (x instanceof Integer)
- setInt(parameterIndex, ((Integer)x).intValue());
- else if (x instanceof Long)
- setLong(parameterIndex, ((Long)x).longValue());
- else if (x instanceof Float)
- setFloat(parameterIndex, ((Float)x).floatValue());
- else if (x instanceof Double)
- setDouble(parameterIndex, ((Double)x).doubleValue());
- else if (x instanceof byte[])
- setBytes(parameterIndex, (byte[])x);
- else if (x instanceof java.sql.Date)
- setDate(parameterIndex, (java.sql.Date)x);
- else if (x instanceof Time)
- setTime(parameterIndex, (Time)x);
- else if (x instanceof Timestamp)
- setTimestamp(parameterIndex, (Timestamp)x);
- else if (x instanceof Boolean)
- setBoolean(parameterIndex, ((Boolean)x).booleanValue());
- else if (x instanceof PGobject)
- setString(parameterIndex, ((PGobject)x).getValue(), PG_TEXT);
- else
- // Try to store as a string in database
- setString(parameterIndex, x.toString(), PG_TEXT);
- }
-
- /*
- * Before executing a stored procedure call you must explicitly
- * call registerOutParameter to register the java.sql.Type of each
- * out parameter.
- *
- *
Note: When reading the value of an out parameter, you must use
- * the getXXX method whose Java type XXX corresponds to the
- * parameter's registered SQL type.
- *
- * ONLY 1 RETURN PARAMETER if {?= call ..} syntax is used
- *
- * @param parameterIndex the first parameter is 1, the second is 2,...
- * @param sqlType SQL type code defined by java.sql.Types; for
- * parameters of type Numeric or Decimal use the version of
- * registerOutParameter that accepts a scale value
- * @exception SQLException if a database-access error occurs.
- */
- public void registerOutParameter(int parameterIndex, int sqlType) throws SQLException
- {
- if (parameterIndex != 1)
- throw new PSQLException ("postgresql.call.noinout", PSQLState.STATEMENT_NOT_ALLOWED_IN_FUNCTION_CALL);
- if (!isFunction)
- throw new PSQLException ("postgresql.call.procasfunc", PSQLState.STATEMENT_NOT_ALLOWED_IN_FUNCTION_CALL,originalSql);
-
- // functionReturnType contains the user supplied value to check
- // testReturn contains a modified version to make it easier to
- // check the getXXX methods..
- functionReturnType = sqlType;
- testReturn = sqlType;
- if (functionReturnType == Types.CHAR ||
- functionReturnType == Types.LONGVARCHAR)
- testReturn = Types.VARCHAR;
- else if (functionReturnType == Types.FLOAT)
- testReturn = Types.REAL; // changes to streamline later error checking
- returnTypeSet = true;
- }
-
- /*
- * You must also specify the scale for numeric/decimal types:
- *
- *
Note: When reading the value of an out parameter, you must use
- * the getXXX method whose Java type XXX corresponds to the
- * parameter's registered SQL type.
- *
- * @param parameterIndex the first parameter is 1, the second is 2,...
- * @param sqlType use either java.sql.Type.NUMERIC or java.sql.Type.DECIMAL
- * @param scale a value greater than or equal to zero representing the
- * desired number of digits to the right of the decimal point
- * @exception SQLException if a database-access error occurs.
- */
- public void registerOutParameter(int parameterIndex, int sqlType,
- int scale) throws SQLException
- {
- registerOutParameter (parameterIndex, sqlType); // ignore for now..
- }
-
- /*
- * An OUT parameter may have the value of SQL NULL; wasNull
- * reports whether the last value read has this special value.
- *
- *
Note: You must first call getXXX on a parameter to read its
- * value and then call wasNull() to see if the value was SQL NULL.
- * @return true if the last parameter read was SQL NULL
- * @exception SQLException if a database-access error occurs.
- */
- public boolean wasNull() throws SQLException
- {
- // check to see if the last access threw an exception
- return (callResult == null);
- }
-
- /*
- * Get the value of a CHAR, VARCHAR, or LONGVARCHAR parameter as a
- * Java String.
- *
- * @param parameterIndex the first parameter is 1, the second is 2,...
- * @return the parameter value; if the value is SQL NULL, the result is null
- * @exception SQLException if a database-access error occurs.
- */
- public String getString(int parameterIndex) throws SQLException
- {
- checkIndex (parameterIndex, Types.VARCHAR, "String");
- return (String)callResult;
- }
-
-
- /*
- * Get the value of a BIT parameter as a Java boolean.
- *
- * @param parameterIndex the first parameter is 1, the second is 2,...
- * @return the parameter value; if the value is SQL NULL, the result is false
- * @exception SQLException if a database-access error occurs.
- */
- public boolean getBoolean(int parameterIndex) throws SQLException
- {
- checkIndex (parameterIndex, Types.BIT, "Boolean");
- if (callResult == null)
- return false;
- return ((Boolean)callResult).booleanValue ();
- }
-
- /*
- * Get the value of a TINYINT parameter as a Java byte.
- *
- * @param parameterIndex the first parameter is 1, the second is 2,...
- * @return the parameter value; if the value is SQL NULL, the result is 0
- * @exception SQLException if a database-access error occurs.
- */
- public byte getByte(int parameterIndex) throws SQLException
- {
- checkIndex (parameterIndex, Types.TINYINT, "Byte");
- if (callResult == null)
- return 0;
- return (byte)((Integer)callResult).intValue ();
- }
-
- /*
- * Get the value of a SMALLINT parameter as a Java short.
- *
- * @param parameterIndex the first parameter is 1, the second is 2,...
- * @return the parameter value; if the value is SQL NULL, the result is 0
- * @exception SQLException if a database-access error occurs.
- */
- public short getShort(int parameterIndex) throws SQLException
- {
- checkIndex (parameterIndex, Types.SMALLINT, "Short");
- if (callResult == null)
- return 0;
- return (short)((Integer)callResult).intValue ();
- }
-
-
- /*
- * Get the value of an INTEGER parameter as a Java int.
- *
- * @param parameterIndex the first parameter is 1, the second is 2,...
- * @return the parameter value; if the value is SQL NULL, the result is 0
- * @exception SQLException if a database-access error occurs.
- */
- public int getInt(int parameterIndex) throws SQLException
- {
- checkIndex (parameterIndex, Types.INTEGER, "Int");
- if (callResult == null)
- return 0;
- return ((Integer)callResult).intValue ();
- }
-
- /*
- * Get the value of a BIGINT parameter as a Java long.
- *
- * @param parameterIndex the first parameter is 1, the second is 2,...
- * @return the parameter value; if the value is SQL NULL, the result is 0
- * @exception SQLException if a database-access error occurs.
- */
- public long getLong(int parameterIndex) throws SQLException
- {
- checkIndex (parameterIndex, Types.BIGINT, "Long");
- if (callResult == null)
- return 0;
- return ((Long)callResult).longValue ();
- }
-
- /*
- * Get the value of a FLOAT parameter as a Java float.
- *
- * @param parameterIndex the first parameter is 1, the second is 2,...
- * @return the parameter value; if the value is SQL NULL, the result is 0
- * @exception SQLException if a database-access error occurs.
- */
- public float getFloat(int parameterIndex) throws SQLException
- {
- checkIndex (parameterIndex, Types.REAL, "Float");
- if (callResult == null)
- return 0;
- return ((Float)callResult).floatValue ();
- }
-
- /*
- * Get the value of a DOUBLE parameter as a Java double.
- *
- * @param parameterIndex the first parameter is 1, the second is 2,...
- * @return the parameter value; if the value is SQL NULL, the result is 0
- * @exception SQLException if a database-access error occurs.
- */
- public double getDouble(int parameterIndex) throws SQLException
- {
- checkIndex (parameterIndex, Types.DOUBLE, "Double");
- if (callResult == null)
- return 0;
- return ((Double)callResult).doubleValue ();
- }
-
- /*
- * Get the value of a NUMERIC parameter as a java.math.BigDecimal
- * object.
- *
- * @param parameterIndex the first parameter is 1, the second is 2,...
- * @param scale a value greater than or equal to zero representing the
- * desired number of digits to the right of the decimal point
- * @return the parameter value; if the value is SQL NULL, the result is null
- * @exception SQLException if a database-access error occurs.
- * @deprecated in Java2.0
- */
- public BigDecimal getBigDecimal(int parameterIndex, int scale)
- throws SQLException
- {
- checkIndex (parameterIndex, Types.NUMERIC, "BigDecimal");
- return ((BigDecimal)callResult);
- }
-
- /*
- * Get the value of a SQL BINARY or VARBINARY parameter as a Java
- * byte[]
- *
- * @param parameterIndex the first parameter is 1, the second is 2,...
- * @return the parameter value; if the value is SQL NULL, the result is null
- * @exception SQLException if a database-access error occurs.
- */
- public byte[] getBytes(int parameterIndex) throws SQLException
- {
- checkIndex (parameterIndex, Types.VARBINARY, Types.BINARY, "Bytes");
- return ((byte [])callResult);
- }
-
-
- /*
- * Get the value of a SQL DATE parameter as a java.sql.Date object
- *
- * @param parameterIndex the first parameter is 1, the second is 2,...
- * @return the parameter value; if the value is SQL NULL, the result is null
- * @exception SQLException if a database-access error occurs.
- */
- public java.sql.Date getDate(int parameterIndex) throws SQLException
- {
- checkIndex (parameterIndex, Types.DATE, "Date");
- return (java.sql.Date)callResult;
- }
-
- /*
- * Get the value of a SQL TIME parameter as a java.sql.Time object.
- *
- * @param parameterIndex the first parameter is 1, the second is 2,...
- * @return the parameter value; if the value is SQL NULL, the result is null
- * @exception SQLException if a database-access error occurs.
- */
- public java.sql.Time getTime(int parameterIndex) throws SQLException
- {
- checkIndex (parameterIndex, Types.TIME, "Time");
- return (java.sql.Time)callResult;
- }
-
- /*
- * Get the value of a SQL TIMESTAMP parameter as a java.sql.Timestamp object.
- *
- * @param parameterIndex the first parameter is 1, the second is 2,...
- * @return the parameter value; if the value is SQL NULL, the result is null
- * @exception SQLException if a database-access error occurs.
- */
- public java.sql.Timestamp getTimestamp(int parameterIndex)
- throws SQLException
- {
- checkIndex (parameterIndex, Types.TIMESTAMP, "Timestamp");
- return (java.sql.Timestamp)callResult;
- }
-
- // getObject returns a Java object for the parameter.
- // See the JDBC spec's "Dynamic Programming" chapter for details.
- /*
- * Get the value of a parameter as a Java object.
- *
- *
This method returns a Java object whose type coresponds to the
- * SQL type that was registered for this parameter using
- * registerOutParameter.
- *
- *
Note that this method may be used to read datatabase-specific,
- * abstract data types. This is done by specifying a targetSqlType
- * of java.sql.types.OTHER, which allows the driver to return a
- * database-specific Java type.
- *
- *
See the JDBC spec's "Dynamic Programming" chapter for details.
- *
- * @param parameterIndex the first parameter is 1, the second is 2,...
- * @return A java.lang.Object holding the OUT parameter value.
- * @exception SQLException if a database-access error occurs.
- */
- public Object getObject(int parameterIndex)
- throws SQLException
- {
- checkIndex (parameterIndex);
- return callResult;
- }
-
- //This method is implemeted in jdbc2
- public int getResultSetConcurrency() throws SQLException
- {
- return 0;
- }
-
- /*
- * Returns the SQL statement with the current template values
- * substituted.
- */
- public String toString()
- {
- if (m_sqlFragments == null)
- return super.toString();
-
- synchronized (sbuf)
- {
- sbuf.setLength(0);
- int i;
-
- for (i = 0 ; i < m_binds.length ; ++i)
- {
- sbuf.append (m_sqlFragments[i]);
- if (m_binds[i] == null)
- sbuf.append( '?' );
- else
- sbuf.append (m_binds[i]);
- }
- sbuf.append(m_sqlFragments[m_binds.length]);
- return sbuf.toString();
- }
- }
-
- /*
- * Note if s is a String it should be escaped by the caller to avoid SQL
- * injection attacks. It is not done here for efficency reasons as
- * most calls to this method do not require escaping as the source
- * of the string is known safe (i.e. Integer.toString())
- */
- private void bind(int paramIndex, Object s, String type) throws SQLException
- {
- if (paramIndex < 1 || paramIndex > m_binds.length)
- throw new PSQLException("postgresql.prep.range", PSQLState.INVALID_PARAMETER_VALUE);
- if (paramIndex == 1 && isFunction) // need to registerOut instead
- throw new PSQLException ("postgresql.call.funcover");
- m_binds[paramIndex - 1] = s;
- m_bindTypes[paramIndex - 1] = type;
- }
-
- /**
- * this method will turn a string of the form
- * {? = call (?, [?,..]) }
- * into the PostgreSQL format which is
- * select (?, [?, ...]) as result
- * or select * from (?, [?, ...]) as result (7.3)
- *
- */
- private String modifyJdbcCall(String p_sql) throws SQLException
- {
- //Check that this is actually a call which should start with a {
- //if not do nothing and treat this as a standard prepared sql
- if (!p_sql.trim().startsWith("{")) {
- return p_sql;
- }
-
- // syntax checking is not complete only a few basics :(
- originalSql = p_sql; // save for error msgs..
- String l_sql = p_sql;
- int index = l_sql.indexOf ("="); // is implied func or proc?
- boolean isValid = true;
- if (index > -1)
- {
- isFunction = true;
- isValid = l_sql.indexOf ("?") < index; // ? before =
- }
- l_sql = l_sql.trim ();
- if (l_sql.startsWith ("{") && l_sql.endsWith ("}"))
- {
- l_sql = l_sql.substring (1, l_sql.length() - 1);
- }
- else
- isValid = false;
- index = l_sql.indexOf ("call");
- if (index == -1 || !isValid)
- throw new PSQLException ("postgresql.call.malformed",PSQLState.STATEMENT_NOT_ALLOWED_IN_FUNCTION_CALL,
- new Object[]{l_sql, JDBC_SYNTAX});
- l_sql = l_sql.replace ('{', ' '); // replace these characters
- l_sql = l_sql.replace ('}', ' ');
- l_sql = l_sql.replace (';', ' ');
-
- // this removes the 'call' string and also puts a hidden '?'
- // at the front of the line for functions, this will
- // allow the registerOutParameter to work correctly
- // because in the source sql there was one more ? for the return
- // value that is not needed by the postgres syntax. But to make
- // sure that the parameter numbers are the same as in the original
- // sql we add a dummy parameter in this case
- l_sql = (isFunction ? "?" : "") + l_sql.substring (index + 4);
- if (connection.haveMinimumServerVersion("7.3")) {
- l_sql = "select * from " + l_sql + " as " + RESULT_ALIAS + ";";
- } else {
- l_sql = "select " + l_sql + " as " + RESULT_ALIAS + ";";
- }
- return l_sql;
- }
-
- /** helperfunction for the getXXX calls to check isFunction and index == 1
- * Compare BOTH type fields against the return type.
- */
- protected void checkIndex (int parameterIndex, int type1, int type2, String getName)
- throws SQLException
- {
- checkIndex (parameterIndex);
- if (type1 != this.testReturn && type2 != this.testReturn)
- throw new PSQLException("postgresql.call.wrongget", PSQLState.MOST_SPECIFIC_TYPE_DOES_NOT_MATCH,
- new Object[]{"java.sql.Types=" + testReturn,
- getName,
- "java.sql.Types=" + type1});
- }
-
- /** helperfunction for the getXXX calls to check isFunction and index == 1
- */
- protected void checkIndex (int parameterIndex, int type, String getName)
- throws SQLException
- {
- checkIndex (parameterIndex);
- if (type != this.testReturn)
- throw new PSQLException("postgresql.call.wrongget", PSQLState.MOST_SPECIFIC_TYPE_DOES_NOT_MATCH,
- new Object[]{"java.sql.Types=" + testReturn,
- getName,
- "java.sql.Types=" + type});
- }
-
- /** helperfunction for the getXXX calls to check isFunction and index == 1
- * @param parameterIndex index of getXXX (index)
- * check to make sure is a function and index == 1
- */
- private void checkIndex (int parameterIndex) throws SQLException
- {
- if (!isFunction)
- throw new PSQLException("postgresql.call.noreturntype", PSQLState.STATEMENT_NOT_ALLOWED_IN_FUNCTION_CALL);
- if (parameterIndex != 1)
- throw new PSQLException("postgresql.call.noinout", PSQLState.STATEMENT_NOT_ALLOWED_IN_FUNCTION_CALL);
- }
-
-
-
- public void setUseServerPrepare(boolean flag) throws SQLException {
- //Server side prepared statements were introduced in 7.3
- if (connection.haveMinimumServerVersion("7.3")) {
- if (m_useServerPrepare != flag)
- deallocateQuery();
- m_useServerPrepare = flag;
- } else {
- //This is a pre 7.3 server so no op this method
- //which means we will never turn on the flag to use server
- //prepared statements and thus regular processing will continue
- }
- }
-
- public boolean isUseServerPrepare()
- {
- return m_useServerPrepare;
- }
-
- private java.sql.Date dateFromString (String s) throws SQLException
- {
- int timezone = 0;
- long millis = 0;
- long localoffset = 0;
- int timezoneLocation = (s.indexOf('+') == -1) ? s.lastIndexOf("-") : s.indexOf('+');
- //if the last index of '-' or '+' is past 8. we are guaranteed that it is a timezone marker
- //shortest = yyyy-m-d
- //longest = yyyy-mm-dd
- try
- {
- timezone = (timezoneLocation>7) ? timezoneLocation : s.length();
- millis = java.sql.Date.valueOf(s.substring(0,timezone)).getTime();
- }
- catch (Exception e)
- {
- throw new PSQLException("postgresql.format.baddate", PSQLState.BAD_DATETIME_FORMAT, s , "yyyy-MM-dd[-tz]");
- }
- timezone = 0;
- if (timezoneLocation>7 && timezoneLocation+3 == s.length())
- {
- timezone = Integer.parseInt(s.substring(timezoneLocation+1,s.length()));
- localoffset = java.util.Calendar.getInstance().getTimeZone().getRawOffset();
- if (java.util.Calendar.getInstance().getTimeZone().inDaylightTime(new java.sql.Date(millis)))
- localoffset += 60*60*1000;
- if (s.charAt(timezoneLocation)=='+')
- timezone*=-1;
- }
- millis = millis + timezone*60*60*1000 + localoffset;
- return new java.sql.Date(millis);
- }
-
- private java.sql.Time timeFromString (String s) throws SQLException
- {
- int timezone = 0;
- long millis = 0;
- long localoffset = 0;
- int timezoneLocation = (s.indexOf('+') == -1) ? s.lastIndexOf("-") : s.indexOf('+');
- //if the index of the last '-' or '+' is greater than 0 that means this time has a timezone.
- //everything earlier than that position, we treat as the time and parse it as such.
- try
- {
- timezone = (timezoneLocation==-1) ? s.length() : timezoneLocation;
- millis = java.sql.Time.valueOf(s.substring(0,timezone)).getTime();
- }
- catch (Exception e)
- {
- throw new PSQLException("postgresql.format.badtime", PSQLState.BAD_DATETIME_FORMAT, s, "HH:mm:ss[-tz]");
- }
- timezone = 0;
- if (timezoneLocation != -1 && timezoneLocation+3 == s.length())
- {
- timezone = Integer.parseInt(s.substring(timezoneLocation+1,s.length()));
- localoffset = java.util.Calendar.getInstance().getTimeZone().getRawOffset();
- if (java.util.Calendar.getInstance().getTimeZone().inDaylightTime(new java.sql.Date(millis)))
- localoffset += 60*60*1000;
- if (s.charAt(timezoneLocation)=='+')
- timezone*=-1;
- }
- millis = millis + timezone*60*60*1000 + localoffset;
- return new java.sql.Time(millis);
- }
-
- private java.sql.Timestamp timestampFromString (String s) throws SQLException
- {
- int timezone = 0;
- long millis = 0;
- long localoffset = 0;
- int nanosVal = 0;
- int timezoneLocation = (s.indexOf('+') == -1) ? s.lastIndexOf("-") : s.indexOf('+');
- int nanospos = s.indexOf(".");
- //if there is a '.', that means there are nanos info, and we take the timestamp up to that point
- //if not, then we check to see if the last +/- (to indicate a timezone) is greater than 8
- //8 is because the shortest date, will have last '-' at position 7. e.g yyyy-x-x
- try
- {
- if (nanospos != -1)
- timezone = nanospos;
- else if (timezoneLocation > 8)
- timezone = timezoneLocation;
- else
- timezone = s.length();
- millis = java.sql.Timestamp.valueOf(s.substring(0,timezone)).getTime();
- }
- catch (Exception e)
- {
- throw new PSQLException("postgresql.format.badtimestamp", PSQLState.BAD_DATETIME_FORMAT, s, "yyyy-MM-dd HH:mm:ss[.xxxxxx][-tz]");
- }
- timezone = 0;
- if (nanospos != -1)
- {
- int tmploc = (timezoneLocation > 8) ? timezoneLocation : s.length();
- nanosVal = Integer.parseInt(s.substring(nanospos+1,tmploc));
- int diff = 8-((tmploc-1)-(nanospos+1));
- for (int i=0;i
- nanosVal*=10;
- }
- if (timezoneLocation>8 && timezoneLocation+3 == s.length())
- {
- timezone = Integer.parseInt(s.substring(timezoneLocation+1,s.length()));
- localoffset = java.util.Calendar.getInstance().getTimeZone().getRawOffset();
- if (java.util.Calendar.getInstance().getTimeZone().inDaylightTime(new java.sql.Date(millis)))
- localoffset += 60*60*1000;
- if (s.charAt(timezoneLocation)=='+')
- timezone*=-1;
- }
- millis = millis + timezone*60*60*1000 + localoffset;
- java.sql.Timestamp tmpts = new java.sql.Timestamp(millis);
- tmpts.setNanos(nanosVal);
- return tmpts;
- }
-
-
- private static final String PG_TEXT = "text";
- private static final String PG_INTEGER = "integer";
- private static final String PG_INT2 = "int2";
- private static final String PG_INT8 = "int8";
- private static final String PG_NUMERIC = "numeric";
- private static final String PG_FLOAT = "float";
- private static final String PG_DOUBLE = "double precision";
- private static final String PG_BOOLEAN = "boolean";
- private static final String PG_DATE = "date";
- private static final String PG_TIME = "time";
- private static final String PG_TIMESTAMPTZ = "timestamptz";
- private static final String PG_BYTEA = "bytea";
-
-
-}
+++ /dev/null
-package org.postgresql.jdbc1;
-
-
-import java.sql.*;
-import java.util.Vector;
-import org.postgresql.PGRefCursorResultSet;
-import org.postgresql.core.BaseResultSet;
-import org.postgresql.core.Field;
-
-public class Jdbc1CallableStatement extends AbstractJdbc1Statement implements java.sql.CallableStatement
-{
-
- public Jdbc1CallableStatement(Jdbc1Connection connection, String sql) throws SQLException
- {
- super(connection, sql);
- }
-
- public BaseResultSet createResultSet (Field[] fields, java.util.Vector tuples, String status, int updateCount, long insertOID, boolean binaryCursor) throws SQLException
- {
- return new Jdbc1ResultSet(this, fields, tuples, status, updateCount, insertOID, binaryCursor);
- }
-
- public PGRefCursorResultSet createRefCursorResultSet (String cursorName) throws SQLException
- {
- return new Jdbc1RefCursorResultSet(this, cursorName);
- }
-}
-
+++ /dev/null
-package org.postgresql.jdbc1;
-
-
-import java.util.Vector;
-import java.sql.*;
-import org.postgresql.core.Field;
-import org.postgresql.util.PSQLException;
-
-/* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/jdbc1/Jdbc1Connection.java,v 1.8 2003/11/29 19:52:10 pgsql Exp $
- * This class implements the java.sql.Connection interface for JDBC1.
- * However most of the implementation is really done in
- * org.postgresql.jdbc1.AbstractJdbc1Connection
- */
-public class Jdbc1Connection extends org.postgresql.jdbc1.AbstractJdbc1Connection implements java.sql.Connection
-{
-
- public java.sql.Statement createStatement() throws SQLException
- {
- return new org.postgresql.jdbc1.Jdbc1Statement(this);
- }
-
- public java.sql.PreparedStatement prepareStatement(String sql) throws SQLException
- {
- return new org.postgresql.jdbc1.Jdbc1PreparedStatement(this, sql);
- }
-
- public java.sql.CallableStatement prepareCall(String sql) throws SQLException
- {
- return new org.postgresql.jdbc1.Jdbc1CallableStatement(this, sql);
- }
-
- public java.sql.DatabaseMetaData getMetaData() throws SQLException
- {
- if (metadata == null)
- metadata = new org.postgresql.jdbc1.Jdbc1DatabaseMetaData(this);
- return metadata;
- }
-
-}
-
-
+++ /dev/null
-package org.postgresql.jdbc1;
-
-
-import java.sql.*;
-import java.util.*;
-import org.postgresql.core.Field;
-import org.postgresql.util.PSQLException;
-
-public class Jdbc1DatabaseMetaData extends AbstractJdbc1DatabaseMetaData implements java.sql.DatabaseMetaData
-{
- public Jdbc1DatabaseMetaData(Jdbc1Connection conn)
- {
- super(conn);
- }
-
-}
+++ /dev/null
-package org.postgresql.jdbc1;
-
-
-import java.sql.*;
-import org.postgresql.PGRefCursorResultSet;
-import org.postgresql.core.BaseResultSet;
-import org.postgresql.core.Field;
-
-public class Jdbc1PreparedStatement extends AbstractJdbc1Statement implements PreparedStatement
-{
-
- public Jdbc1PreparedStatement(Jdbc1Connection connection, String sql) throws SQLException
- {
- super(connection, sql);
- }
-
- public BaseResultSet createResultSet (Field[] fields, java.util.Vector tuples, String status, int updateCount, long insertOID, boolean binaryCursor) throws SQLException
- {
- return new Jdbc1ResultSet(this, fields, tuples, status, updateCount, insertOID, binaryCursor);
- }
-
- public PGRefCursorResultSet createRefCursorResultSet (String cursorName) throws SQLException
- {
- return new Jdbc1RefCursorResultSet(this, cursorName);
- }
-}
+++ /dev/null
-package org.postgresql.jdbc1;
-
-import java.sql.SQLException;
-import org.postgresql.core.QueryExecutor;
-import org.postgresql.core.BaseStatement;
-import org.postgresql.PGRefCursorResultSet;
-
-/** A real result set based on a ref cursor.
- *
- * @author Nic Ferrier
- */
-public class Jdbc1RefCursorResultSet extends Jdbc1ResultSet
- implements PGRefCursorResultSet
-{
-
- // The name of the cursor being used.
- String refCursorHandle;
-
- // Indicates when the result set has activaly bound to the cursor.
- boolean isInitialized = false;
-
-
- Jdbc1RefCursorResultSet(BaseStatement statement, String refCursorName)
- {
- super(statement, null, null, null, -1, 0L, false);
- this.refCursorHandle = refCursorName;
- }
-
- public String getRefCursor ()
- {
- return refCursorHandle;
- }
-
- public boolean next () throws SQLException
- {
- if (isInitialized)
- return super.next();
- // Initialize this res set with the rows from the cursor.
- String[] toExec = { "FETCH ALL IN \"" + refCursorHandle + "\";" };
- QueryExecutor.execute(toExec, new String[0], this);
- isInitialized = true;
- return super.next();
- }
-}
+++ /dev/null
-package org.postgresql.jdbc1;
-
-
-import java.sql.*;
-import java.util.Vector;
-import org.postgresql.core.BaseStatement;
-import org.postgresql.core.Field;
-
-/* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/jdbc1/Jdbc1ResultSet.java,v 1.7 2003/11/29 19:52:10 pgsql Exp $
- * This class implements the java.sql.ResultSet interface for JDBC1.
- * However most of the implementation is really done in
- * org.postgresql.jdbc1.AbstractJdbc1ResultSet
- */
-public class Jdbc1ResultSet extends org.postgresql.jdbc1.AbstractJdbc1ResultSet implements java.sql.ResultSet
-{
-
- public Jdbc1ResultSet(BaseStatement statement, Field[] fields, Vector tuples, String status, int updateCount, long insertOID, boolean binaryCursor)
- {
- super(statement, fields, tuples, status, updateCount, insertOID, binaryCursor);
- }
-
- public java.sql.ResultSetMetaData getMetaData() throws SQLException
- {
- return new Jdbc1ResultSetMetaData(rows, fields);
- }
-
-}
-
+++ /dev/null
-package org.postgresql.jdbc1;
-
-import java.util.Vector;
-import org.postgresql.core.Field;
-
-public class Jdbc1ResultSetMetaData extends AbstractJdbc1ResultSetMetaData implements java.sql.ResultSetMetaData
-{
- public Jdbc1ResultSetMetaData(Vector rows, Field[] fields)
- {
- super(rows, fields);
- }
-
-}
-
+++ /dev/null
-package org.postgresql.jdbc1;
-
-
-import java.sql.*;
-import java.util.Vector;
-import org.postgresql.PGRefCursorResultSet;
-import org.postgresql.core.BaseResultSet;
-import org.postgresql.core.Field;
-
-/* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/jdbc1/Jdbc1Statement.java,v 1.7 2003/11/29 19:52:10 pgsql Exp $
- * This class implements the java.sql.Statement interface for JDBC1.
- * However most of the implementation is really done in
- * org.postgresql.jdbc1.AbstractJdbc1Statement
- */
-public class Jdbc1Statement extends org.postgresql.jdbc1.AbstractJdbc1Statement implements java.sql.Statement
-{
-
- public Jdbc1Statement (Jdbc1Connection c)
- {
- super(c);
- }
-
- public BaseResultSet createResultSet (Field[] fields, Vector tuples, String status, int updateCount, long insertOID, boolean binaryCursor) throws SQLException
- {
- return new Jdbc1ResultSet(this, fields, tuples, status, updateCount, insertOID, binaryCursor);
- }
-
- public PGRefCursorResultSet createRefCursorResultSet (String cursorName) throws SQLException
- {
- return new Jdbc1RefCursorResultSet(this, cursorName);
- }
-}
+++ /dev/null
-package org.postgresql.jdbc2;
-
-import org.postgresql.PGConnection;
-import org.postgresql.largeobject.LargeObject;
-import org.postgresql.largeobject.LargeObjectManager;
-import java.io.InputStream;
-import java.sql.Blob;
-import java.sql.SQLException;
-
-public abstract class AbstractJdbc2Blob
-{
- private int oid;
- private LargeObject lo;
-
- public AbstractJdbc2Blob(PGConnection conn, int oid) throws SQLException
- {
- this.oid = oid;
- LargeObjectManager lom = conn.getLargeObjectAPI();
- this.lo = lom.open(oid);
- }
-
- public long length() throws SQLException
- {
- return lo.size();
- }
-
- public InputStream getBinaryStream() throws SQLException
- {
- return lo.getInputStream();
- }
-
- public byte[] getBytes(long pos, int length) throws SQLException
- {
- lo.seek((int)pos, LargeObject.SEEK_SET);
- return lo.read(length);
- }
-
- /*
- * For now, this is not implemented.
- */
- public long position(byte[] pattern, long start) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /*
- * This should be simply passing the byte value of the pattern Blob
- */
- public long position(Blob pattern, long start) throws SQLException
- {
- return position(pattern.getBytes(0, (int)pattern.length()), start);
- }
-
-}
+++ /dev/null
-package org.postgresql.jdbc2;
-
-
-import org.postgresql.PGConnection;
-import org.postgresql.largeobject.LargeObject;
-import org.postgresql.largeobject.LargeObjectManager;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.Reader;
-import java.sql.Clob;
-import java.sql.SQLException;
-
-public class AbstractJdbc2Clob
-{
- private int oid;
- private LargeObject lo;
-
- public AbstractJdbc2Clob(PGConnection conn, int oid) throws SQLException
- {
- this.oid = oid;
- LargeObjectManager lom = conn.getLargeObjectAPI();
- this.lo = lom.open(oid);
- }
-
- public long length() throws SQLException
- {
- return lo.size();
- }
-
- public InputStream getAsciiStream() throws SQLException
- {
- return lo.getInputStream();
- }
-
- public Reader getCharacterStream() throws SQLException
- {
- return new InputStreamReader(lo.getInputStream());
- }
-
- public String getSubString(long i, int j) throws SQLException
- {
- lo.seek((int)i - 1);
- return new String(lo.read(j));
- }
-
- /*
- * For now, this is not implemented.
- */
- public long position(String pattern, long start) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /*
- * This should be simply passing the byte value of the pattern Blob
- */
- public long position(Clob pattern, long start) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
-}
+++ /dev/null
-package org.postgresql.jdbc2;
-
-
-import java.io.PrintWriter;
-import java.sql.DriverManager;
-import java.sql.SQLData;
-import java.sql.SQLException;
-import java.sql.Types;
-
-/* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/jdbc2/AbstractJdbc2Connection.java,v 1.7 2003/11/29 19:52:10 pgsql Exp $
- * This class defines methods of the jdbc2 specification. This class extends
- * org.postgresql.jdbc1.AbstractJdbc1Connection which provides the jdbc1
- * methods. The real Connection class (for jdbc2) is org.postgresql.jdbc2.Jdbc2Connection
- */
-public abstract class AbstractJdbc2Connection extends org.postgresql.jdbc1.AbstractJdbc1Connection
-{
- /*
- * The current type mappings
- */
- protected java.util.Map typemap;
-
- public java.sql.Statement createStatement() throws SQLException
- {
- // The spec says default of TYPE_FORWARD_ONLY but everyone is used to
- // using TYPE_SCROLL_INSENSITIVE
- return createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE, java.sql.ResultSet.CONCUR_READ_ONLY);
- }
-
- public abstract java.sql.Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException;
-
- public java.sql.PreparedStatement prepareStatement(String sql) throws SQLException
- {
- return prepareStatement(sql, java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE, java.sql.ResultSet.CONCUR_READ_ONLY);
- }
-
- public abstract java.sql.PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException;
-
- public java.sql.CallableStatement prepareCall(String sql) throws SQLException
- {
- return prepareCall(sql, java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE, java.sql.ResultSet.CONCUR_READ_ONLY);
- }
-
- public abstract java.sql.CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException;
-
- public java.util.Map getTypeMap() throws SQLException
- {
- return typemap;
- }
-
-
- public void setTypeMap(java.util.Map map) throws SQLException
- {
- typemap = map;
- }
-
- /*
- * This overides the standard internal getObject method so that we can
- * check the jdbc2 type map first
- */
- public Object getObject(String type, String value) throws SQLException
- {
- if (typemap != null)
- {
- SQLData d = (SQLData) typemap.get(type);
- if (d != null)
- {
- // Handle the type (requires SQLInput & SQLOutput classes to be implemented)
- throw org.postgresql.Driver.notImplemented();
- }
- }
-
- // Default to the original method
- return super.getObject(type, value);
- }
-
-
- //Because the get/setLogStream methods are deprecated in JDBC2
- //we use the get/setLogWriter methods here for JDBC2 by overriding
- //the base version of this method
- protected void enableDriverManagerLogging()
- {
- if (DriverManager.getLogWriter() == null)
- {
- DriverManager.setLogWriter(new PrintWriter(System.out));
- }
- }
-
-
- /*
- * This implemetation uses the jdbc2Types array to support the jdbc2
- * datatypes. Basically jdbc1 and jdbc2 are the same, except that
- * jdbc2 adds the Array types.
- */
- public int getSQLType(String pgTypeName)
- {
- int sqlType = Types.OTHER; // default value
- for (int i = 0;i < jdbc2Types.length;i++)
- {
- if (pgTypeName.equals(jdbc2Types[i]))
- {
- sqlType = jdbc2Typei[i];
- break;
- }
- }
- return sqlType;
- }
-
- /*
- * 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
- */
- private static final String jdbc2Types[] = {
- "int2",
- "int4", "oid",
- "int8",
- "cash", "money",
- "numeric",
- "float4",
- "float8",
- "bpchar", "char", "char2", "char4", "char8", "char16",
- "varchar", "text", "name", "filename",
- "bytea",
- "bool",
- "bit",
- "date",
- "time",
- "abstime", "timestamp", "timestamptz",
- "_bool", "_char", "_int2", "_int4", "_text",
- "_oid", "_varchar", "_int8", "_float4", "_float8",
- "_abstime", "_date", "_time", "_timestamp", "_numeric",
- "_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
- */
- private static final int jdbc2Typei[] = {
- Types.SMALLINT,
- Types.INTEGER, Types.INTEGER,
- Types.BIGINT,
- Types.DOUBLE, Types.DOUBLE,
- Types.NUMERIC,
- Types.REAL,
- Types.DOUBLE,
- Types.CHAR, Types.CHAR, Types.CHAR, Types.CHAR, Types.CHAR, Types.CHAR,
- Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
- Types.BINARY,
- Types.BIT,
- Types.BIT,
- Types.DATE,
- Types.TIME,
- Types.TIMESTAMP, Types.TIMESTAMP, Types.TIMESTAMP,
- Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY,
- Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY,
- Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY,
- Types.ARRAY
- };
-
-
-
-
-}
-
-
+++ /dev/null
-package org.postgresql.jdbc2;
-
-import java.sql.SQLException;
-
-public abstract class AbstractJdbc2DatabaseMetaData extends org.postgresql.jdbc1.AbstractJdbc1DatabaseMetaData
-{
-
- public AbstractJdbc2DatabaseMetaData(AbstractJdbc2Connection conn)
- {
- super(conn);
- }
-
-
-
- // ** JDBC 2 Extensions **
-
- /*
- * Does the database support the given result set type?
- *
- * @param type - defined in java.sql.ResultSet
- * @return true if so; false otherwise
- * @exception SQLException - if a database access error occurs
- */
- public boolean supportsResultSetType(int type) throws SQLException
- {
- // The only type we don't support
- return type != java.sql.ResultSet.TYPE_SCROLL_SENSITIVE;
- }
-
-
- /*
- * Does the database support the concurrency type in combination
- * with the given result set type?
- *
- * @param type - defined in java.sql.ResultSet
- * @param concurrency - type defined in java.sql.ResultSet
- * @return true if so; false otherwise
- * @exception SQLException - if a database access error occurs
- */
- public boolean supportsResultSetConcurrency(int type, int concurrency) throws SQLException
- {
- // These combinations are not supported!
- if (type == java.sql.ResultSet.TYPE_SCROLL_SENSITIVE)
- return false;
-
- // We do support Updateable ResultSets
- if (concurrency == java.sql.ResultSet.CONCUR_UPDATABLE)
- return true;
-
- // Everything else we do
- return true;
- }
-
-
- /* lots of unsupported stuff... */
- public boolean ownUpdatesAreVisible(int type) throws SQLException
- {
- return true;
- }
-
- public boolean ownDeletesAreVisible(int type) throws SQLException
- {
- return true;
- }
-
- public boolean ownInsertsAreVisible(int type) throws SQLException
- {
- // indicates that
- return true;
- }
-
- public boolean othersUpdatesAreVisible(int type) throws SQLException
- {
- return false;
- }
-
- public boolean othersDeletesAreVisible(int i) throws SQLException
- {
- return false;
- }
-
- public boolean othersInsertsAreVisible(int type) throws SQLException
- {
- return false;
- }
-
- public boolean updatesAreDetected(int type) throws SQLException
- {
- return false;
- }
-
- public boolean deletesAreDetected(int i) throws SQLException
- {
- return false;
- }
-
- public boolean insertsAreDetected(int type) throws SQLException
- {
- return false;
- }
-
- /*
- * Indicates whether the driver supports batch updates.
- */
- public boolean supportsBatchUpdates() throws SQLException
- {
- return true;
- }
-
- /*
- * Return user defined types in a schema
- */
- public java.sql.ResultSet getUDTs(String catalog,
- String schemaPattern,
- String typeNamePattern,
- int[] types
- ) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
-
- /*
- * Retrieves the connection that produced this metadata object.
- *
- * @return the connection that produced this metadata object
- */
- public java.sql.Connection getConnection() throws SQLException
- {
- return (java.sql.Connection)connection;
- }
-
- /* I don't find these in the spec!?! */
-
- public boolean rowChangesAreDetected(int type) throws SQLException
- {
- return false;
- }
-
- public boolean rowChangesAreVisible(int type) throws SQLException
- {
- return false;
- }
-}
+++ /dev/null
-/*-------------------------------------------------------------------------
- *
- * AbstractJdbc2ResultSet.java
- * This class defines methods of the jdbc2 specification. This class
- * extends org.postgresql.jdbc1.AbstractJdbc1ResultSet which provides the
- * jdbc1 methods. The real Statement class (for jdbc2) is
- * org.postgresql.jdbc2.Jdbc2ResultSet
- *
- * Copyright (c) 2003, PostgreSQL Global Development Group
- *
- * IDENTIFICATION
- * $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/jdbc2/AbstractJdbc2ResultSet.java,v 1.28 2003/12/12 18:34:14 davec Exp $
- *
- *-------------------------------------------------------------------------
- */
-package org.postgresql.jdbc2;
-
-import java.io.CharArrayReader;
-import java.io.InputStream;
-import java.io.IOException;
-import java.math.BigDecimal;
-import java.sql.*;
-import java.util.Enumeration;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.StringTokenizer;
-import java.util.Vector;
-import org.postgresql.Driver;
-import org.postgresql.core.BaseStatement;
-import org.postgresql.core.Field;
-import org.postgresql.core.Encoding;
-import org.postgresql.util.PSQLException;
-import org.postgresql.util.PSQLState;
-
-
-public abstract class AbstractJdbc2ResultSet extends org.postgresql.jdbc1.AbstractJdbc1ResultSet
-{
-
- //needed for updateable result set support
- protected boolean updateable = false;
- protected boolean doingUpdates = false;
- protected boolean onInsertRow = false;
- protected Hashtable updateValues = new Hashtable();
- private boolean usingOID = false; // are we using the OID for the primary key?
- private Vector primaryKeys; // list of primary keys
- private int numKeys = 0;
- private boolean singleTable = false;
- protected String tableName = null;
- protected PreparedStatement updateStatement = null;
- protected PreparedStatement insertStatement = null;
- protected PreparedStatement deleteStatement = null;
- private PreparedStatement selectStatement = null;
-
-
- public AbstractJdbc2ResultSet(BaseStatement statement, Field[] fields, Vector tuples, String status, int updateCount, long insertOID, boolean binaryCursor)
- {
- super (statement, fields, tuples, status, updateCount, insertOID, binaryCursor);
- }
-
- public java.net.URL getURL(int columnIndex) throws SQLException
- {
- return null;
- }
-
-
- public java.net.URL getURL(String columnName) throws SQLException
- {
- return null;
- }
-
-
- /*
- * Get the value of a column in the current row as a Java object
- *
- *
This method will return the value of the given column as a
- * Java object. The type of the Java object will be the default
- * Java Object type corresponding to the column's SQL type, following
- * the mapping specified in the JDBC specification.
- *
- *
This method may also be used to read database specific abstract
- * data types.
- *
- * @param columnIndex the first column is 1, the second is 2...
- * @return a Object holding the column value
- * @exception SQLException if a database access error occurs
- */
- public Object getObject(int columnIndex) throws SQLException
- {
- Field field;
-
- checkResultSet( columnIndex );
-
- wasNullFlag = (this_row[columnIndex - 1] == null);
- if (wasNullFlag)
- return null;
-
- field = fields[columnIndex - 1];
-
- // some fields can be null, mainly from those returned by MetaData methods
- if (field == null)
- {
- wasNullFlag = true;
- return null;
- }
-
- switch (field.getSQLType())
- {
- case Types.BIT:
- return getBoolean(columnIndex) ? Boolean.TRUE : Boolean.FALSE;
-
- case Types.SMALLINT:
- return new Short(getShort(columnIndex));
-
- case Types.INTEGER:
- return new Integer(getInt(columnIndex));
-
- case Types.BIGINT:
- return new Long(getLong(columnIndex));
-
- case Types.NUMERIC:
- return getBigDecimal
- (columnIndex, (field.getMod() == -1) ? -1 : ((field.getMod() - 4) & 0xffff));
-
- case Types.REAL:
- return new Float(getFloat(columnIndex));
-
- case Types.DOUBLE:
- return new Double(getDouble(columnIndex));
-
- case Types.CHAR:
- case Types.VARCHAR:
- return getString(columnIndex);
-
- case Types.DATE:
- return getDate(columnIndex);
-
- case Types.TIME:
- return getTime(columnIndex);
-
- case Types.TIMESTAMP:
- return getTimestamp(columnIndex);
-
- case Types.BINARY:
- case Types.VARBINARY:
- return getBytes(columnIndex);
-
- case Types.ARRAY:
- return getArray(columnIndex);
-
- default:
- String type = field.getPGType();
-
- // if the backend doesn't know the type then coerce to String
- if (type.equals("unknown"))
- {
- return getString(columnIndex);
- }
- // Specialized support for ref cursors is neater.
- else if (type.equals("refcursor"))
- {
- String cursorName = getString(columnIndex);
- return statement.createRefCursorResultSet(cursorName);
- }
- else
- {
- return connection.getObject(field.getPGType(), getString(columnIndex));
- }
- }
- }
-
-
- public boolean absolute(int index) throws SQLException
- {
- // index is 1-based, but internally we use 0-based indices
- int internalIndex;
-
- if (index == 0)
- throw new SQLException("Cannot move to index of 0");
-
- final int rows_size = rows.size();
-
- //if index<0, count from the end of the result set, but check
- //to be sure that it is not beyond the first index
- if (index < 0)
- {
- if (index >= -rows_size)
- internalIndex = rows_size + index;
- else
- {
- beforeFirst();
- return false;
- }
- }
- else
- {
- //must be the case that index>0,
- //find the correct place, assuming that
- //the index is not too large
- if (index <= rows_size)
- internalIndex = index - 1;
- else
- {
- afterLast();
- return false;
- }
- }
-
- current_row = internalIndex;
- this_row = (byte[][]) rows.elementAt(internalIndex);
-
- rowBuffer = new byte[this_row.length][];
- System.arraycopy(this_row, 0, rowBuffer, 0, this_row.length);
-
- return true;
- }
-
-
- public void afterLast() throws SQLException
- {
- final int rows_size = rows.size();
- if (rows_size > 0)
- current_row = rows_size;
- }
-
-
- public void beforeFirst() throws SQLException
- {
- if (rows.size() > 0)
- current_row = -1;
- }
-
-
- public boolean first() throws SQLException
- {
- if (rows.size() <= 0)
- return false;
-
- onInsertRow = false;
- current_row = 0;
- this_row = (byte[][]) rows.elementAt(current_row);
-
- rowBuffer = new byte[this_row.length][];
- System.arraycopy(this_row, 0, rowBuffer, 0, this_row.length);
-
- return true;
- }
-
-
- public java.sql.Array getArray(String colName) throws SQLException
- {
- return getArray(findColumn(colName));
- }
-
-
- public java.sql.Array getArray(int i) throws SQLException
- {
- checkResultSet( i );
-
- wasNullFlag = (this_row[i - 1] == null);
- if (wasNullFlag)
- return null;
-
- if (i < 1 || i > fields.length)
- throw new PSQLException("postgresql.res.colrange", PSQLState.INVALID_PARAMETER_VALUE);
- return (java.sql.Array) new org.postgresql.jdbc2.Array( connection, i, fields[i - 1], this );
- }
-
-
- public java.math.BigDecimal getBigDecimal(int columnIndex) throws SQLException
- {
- return getBigDecimal(columnIndex, -1);
- }
-
-
- public java.math.BigDecimal getBigDecimal(String columnName) throws SQLException
- {
- return getBigDecimal(findColumn(columnName));
- }
-
-
- public Blob getBlob(String columnName) throws SQLException
- {
- return getBlob(findColumn(columnName));
- }
-
-
- public abstract Blob getBlob(int i) throws SQLException;
-
-
- public java.io.Reader getCharacterStream(String columnName) throws SQLException
- {
- return getCharacterStream(findColumn(columnName));
- }
-
-
- public java.io.Reader getCharacterStream(int i) throws SQLException
- {
- checkResultSet( i );
- wasNullFlag = (this_row[i - 1] == null);
- if (wasNullFlag)
- return null;
-
- if (((AbstractJdbc2Connection) connection).haveMinimumCompatibleVersion("7.2"))
- {
- //Version 7.2 supports AsciiStream for all the PG text types
- //As the spec/javadoc for this method indicate this is to be used for
- //large text values (i.e. LONGVARCHAR) PG doesn't have a separate
- //long string datatype, but with toast the text datatype is capable of
- //handling very large values. Thus the implementation ends up calling
- //getString() since there is no current way to stream the value from the server
- return new CharArrayReader(getString(i).toCharArray());
- }
- else
- {
- // In 7.1 Handle as BLOBS so return the LargeObject input stream
- Encoding encoding = connection.getEncoding();
- InputStream input = getBinaryStream(i);
- return encoding.getDecodingReader(input);
- }
- }
-
-
- public Clob getClob(String columnName) throws SQLException
- {
- return getClob(findColumn(columnName));
- }
-
-
- public abstract Clob getClob(int i) throws SQLException;
-
-
- public int getConcurrency() throws SQLException
- {
- if (statement == null)
- return java.sql.ResultSet.CONCUR_READ_ONLY;
- return statement.getResultSetConcurrency();
- }
-
-
- public java.sql.Date getDate(int i, java.util.Calendar cal) throws SQLException
- {
- // If I read the specs, this should use cal only if we don't
- // store the timezone, and if we do, then act just like getDate()?
- // for now...
- return getDate(i);
- }
-
-
- public Time getTime(int i, java.util.Calendar cal) throws SQLException
- {
- // If I read the specs, this should use cal only if we don't
- // store the timezone, and if we do, then act just like getTime()?
- // for now...
- return getTime(i);
- }
-
-
- public Timestamp getTimestamp(int i, java.util.Calendar cal) throws SQLException
- {
- // If I read the specs, this should use cal only if we don't
- // store the timezone, and if we do, then act just like getDate()?
- // for now...
- return getTimestamp(i);
- }
-
-
- public java.sql.Date getDate(String c, java.util.Calendar cal) throws SQLException
- {
- return getDate(findColumn(c), cal);
- }
-
-
- public Time getTime(String c, java.util.Calendar cal) throws SQLException
- {
- return getTime(findColumn(c), cal);
- }
-
-
- public Timestamp getTimestamp(String c, java.util.Calendar cal) throws SQLException
- {
- return getTimestamp(findColumn(c), cal);
- }
-
-
- public int getFetchDirection() throws SQLException
- {
- //PostgreSQL normally sends rows first->last
- return java.sql.ResultSet.FETCH_FORWARD;
- }
-
-
- public Object getObject(String columnName, java.util.Map map) throws SQLException
- {
- return getObject(findColumn(columnName), map);
- }
-
-
- /*
- * This checks against map for the type of column i, and if found returns
- * an object based on that mapping. The class must implement the SQLData
- * interface.
- */
- public Object getObject(int i, java.util.Map map) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
-
- public Ref getRef(String columnName) throws SQLException
- {
- return getRef(findColumn(columnName));
- }
-
-
- public Ref getRef(int i) throws SQLException
- {
- //The backend doesn't yet have SQL3 REF types
- throw new PSQLException("postgresql.psqlnotimp", PSQLState.NOT_IMPLEMENTED);
- }
-
-
- public int getRow() throws SQLException
- {
- final int rows_size = rows.size();
-
- if (current_row < 0 || current_row >= rows_size)
- return 0;
-
- return current_row + 1;
- }
-
-
- // This one needs some thought, as not all ResultSets come from a statement
- public Statement getStatement() throws SQLException
- {
- return (Statement) statement;
- }
-
-
- public int getType() throws SQLException
- {
- // This implementation allows scrolling but is not able to
- // see any changes. Sub-classes may overide this to return a more
- // meaningful result.
- return java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE;
- }
-
-
- public boolean isAfterLast() throws SQLException
- {
- final int rows_size = rows.size();
- return (current_row >= rows_size && rows_size > 0);
- }
-
-
- public boolean isBeforeFirst() throws SQLException
- {
- return (current_row < 0 && rows.size() > 0);
- }
-
-
- public boolean isFirst() throws SQLException
- {
- return (current_row == 0 && rows.size() >= 0);
- }
-
-
- public boolean isLast() throws SQLException
- {
- final int rows_size = rows.size();
- return (current_row == rows_size - 1 && rows_size > 0);
- }
-
-
- public boolean last() throws SQLException
- {
- final int rows_size = rows.size();
- if (rows_size <= 0)
- return false;
-
- current_row = rows_size - 1;
- this_row = (byte[][]) rows.elementAt(current_row);
-
- rowBuffer = new byte[this_row.length][];
- System.arraycopy(this_row, 0, rowBuffer, 0, this_row.length);
-
- return true;
- }
-
-
- public boolean previous() throws SQLException
- {
- if (--current_row < 0)
- return false;
- this_row = (byte[][]) rows.elementAt(current_row);
- rowBuffer = new byte[this_row.length][];
- System.arraycopy(this_row, 0, rowBuffer, 0, this_row.length);
- return true;
- }
-
-
- public boolean relative(int rows) throws SQLException
- {
- //have to add 1 since absolute expects a 1-based index
- return absolute(current_row + 1 + rows);
- }
-
-
- public void setFetchDirection(int direction) throws SQLException
- {
- throw new PSQLException("postgresql.psqlnotimp", PSQLState.NOT_IMPLEMENTED);
- }
-
-
- public synchronized void cancelRowUpdates()
- throws SQLException
- {
- if (doingUpdates)
- {
- doingUpdates = false;
-
- clearRowBuffer(true);
- }
- }
-
-
- public synchronized void deleteRow()
- throws SQLException
- {
- if ( !isUpdateable() )
- {
- throw new PSQLException( "postgresql.updateable.notupdateable" );
- }
-
- if (onInsertRow)
- {
- throw new PSQLException( "postgresql.updateable.oninsertrow" );
- }
-
- if (rows.size() == 0)
- {
- throw new PSQLException( "postgresql.updateable.emptydelete" );
- }
- if (isBeforeFirst())
- {
- throw new PSQLException( "postgresql.updateable.beforestartdelete" );
- }
- if (isAfterLast())
- {
- throw new PSQLException( "postgresql.updateable.afterlastdelete" );
- }
-
-
- int numKeys = primaryKeys.size();
- if ( deleteStatement == null )
- {
-
-
- StringBuffer deleteSQL = new StringBuffer("DELETE FROM " ).append(tableName).append(" where " );
-
- for ( int i = 0; i < numKeys; i++ )
- {
- deleteSQL.append( ((PrimaryKey) primaryKeys.get(i)).name ).append( " = ? " );
- if ( i < numKeys - 1 )
- {
- deleteSQL.append( " and " );
- }
- }
-
- deleteStatement = ((java.sql.Connection) connection).prepareStatement(deleteSQL.toString());
- }
- deleteStatement.clearParameters();
-
- for ( int i = 0; i < numKeys; i++ )
- {
- deleteStatement.setObject(i + 1, ((PrimaryKey) primaryKeys.get(i)).getValue());
- }
-
-
- deleteStatement.executeUpdate();
-
- rows.removeElementAt(current_row);
- }
-
-
- public synchronized void insertRow()
- throws SQLException
- {
- if ( !isUpdateable() )
- {
- throw new PSQLException( "postgresql.updateable.notupdateable" );
- }
-
- if (!onInsertRow)
- {
- throw new PSQLException( "postgresql.updateable.notoninsertrow" );
- }
- else
- {
-
- // loop through the keys in the insertTable and create the sql statement
- // we have to create the sql every time since the user could insert different
- // columns each time
-
- StringBuffer insertSQL = new StringBuffer("INSERT INTO ").append(tableName).append(" (");
- StringBuffer paramSQL = new StringBuffer(") values (" );
-
- Enumeration columnNames = updateValues.keys();
- int numColumns = updateValues.size();
-
- for ( int i = 0; columnNames.hasMoreElements(); i++ )
- {
- String columnName = (String) columnNames.nextElement();
-
- insertSQL.append( columnName );
- if ( i < numColumns - 1 )
- {
- insertSQL.append(", ");
- paramSQL.append("?,");
- }
- else
- {
- paramSQL.append("?)");
- }
-
- }
-
- insertSQL.append(paramSQL.toString());
- insertStatement = ((java.sql.Connection) connection).prepareStatement(insertSQL.toString());
-
- Enumeration keys = updateValues.keys();
-
- for ( int i = 1; keys.hasMoreElements(); i++)
- {
- String key = (String) keys.nextElement();
- Object o = updateValues.get(key);
- if (o instanceof NullObject)
- insertStatement.setNull(i,java.sql.Types.NULL);
- else
- insertStatement.setObject(i, o);
- }
-
- insertStatement.executeUpdate();
-
- if ( usingOID )
- {
- // we have to get the last inserted OID and put it in the resultset
-
- long insertedOID = ((AbstractJdbc2Statement) insertStatement).getLastOID();
-
- updateValues.put("oid", new Long(insertedOID) );
-
- }
-
- // update the underlying row to the new inserted data
- updateRowBuffer();
-
- rows.addElement(rowBuffer);
-
- // we should now reflect the current data in this_row
- // that way getXXX will get the newly inserted data
- this_row = rowBuffer;
-
- // need to clear this in case of another insert
- clearRowBuffer(false);
-
-
- }
- }
-
-
- public synchronized void moveToCurrentRow()
- throws SQLException
- {
- if (!updateable)
- {
- throw new PSQLException( "postgresql.updateable.notupdateable" );
- }
-
- if (current_row < 0) {
- this_row = null;
- rowBuffer = null;
- } else {
- this_row = (byte[][]) rows.elementAt(current_row);
-
- rowBuffer = new byte[this_row.length][];
- System.arraycopy(this_row, 0, rowBuffer, 0, this_row.length);
- }
-
- onInsertRow = false;
- doingUpdates = false;
- }
-
-
- public synchronized void moveToInsertRow()
- throws SQLException
- {
- if ( !isUpdateable() )
- {
- throw new PSQLException( "postgresql.updateable.notupdateable" );
- }
-
- if (insertStatement != null)
- {
- insertStatement = null;
- }
-
-
- // make sure the underlying data is null
- clearRowBuffer(false);
-
- onInsertRow = true;
- doingUpdates = false;
-
- }
-
-
- private synchronized void clearRowBuffer(boolean copyCurrentRow)
- throws SQLException
- {
- // rowBuffer is the temporary storage for the row
- rowBuffer = new byte[fields.length][];
-
- // inserts want an empty array while updates want a copy of the current row
- if (copyCurrentRow) {
- System.arraycopy(this_row, 0, rowBuffer, 0, this_row.length);
- }
-
- // clear the updateValues hashTable for the next set of updates
- updateValues.clear();
-
- }
-
-
- public boolean rowDeleted() throws SQLException
- {
- // only sub-classes implement CONCURuPDATEABLE
- throw Driver.notImplemented();
- }
-
-
- public boolean rowInserted() throws SQLException
- {
- // only sub-classes implement CONCURuPDATEABLE
- throw Driver.notImplemented();
- }
-
-
- public boolean rowUpdated() throws SQLException
- {
- // only sub-classes implement CONCURuPDATEABLE
- throw Driver.notImplemented();
- }
-
-
- public synchronized void updateAsciiStream(int columnIndex,
- java.io.InputStream x,
- int length
- )
- throws SQLException
- {
- byte[] theData = null;
- try
- {
- x.read(theData, 0, length);
- }
- catch (NullPointerException ex )
- {
- throw new PSQLException("postgresql.updateable.inputstream");
- }
- catch (IOException ie)
- {
- throw new PSQLException("postgresql.updateable.ioerror", ie);
- }
-
- updateValue(columnIndex, theData);
- }
-
-
- public synchronized void updateBigDecimal(int columnIndex,
- java.math.BigDecimal x )
- throws SQLException
- {
- updateValue(columnIndex, x);
- }
-
-
- public synchronized void updateBinaryStream(int columnIndex,
- java.io.InputStream x,
- int length
- )
- throws SQLException
- {
- byte[] theData = null;
- try
- {
- x.read(theData, 0, length);
-
- }
- catch ( NullPointerException ex )
- {
- throw new PSQLException("postgresql.updateable.inputstream");
- }
- catch (IOException ie)
- {
- throw new PSQLException("postgresql.updateable.ioerror", ie);
- }
- updateValue(columnIndex, theData);
- }
-
-
- public synchronized void updateBoolean(int columnIndex, boolean x)
- throws SQLException
- {
- if ( Driver.logDebug )
- Driver.debug("updating boolean " + fields[columnIndex - 1].getName() + "=" + x);
- updateValue(columnIndex, new Boolean(x));
- }
-
-
- public synchronized void updateByte(int columnIndex, byte x)
- throws SQLException
- {
- updateValue(columnIndex, String.valueOf(x));
- }
-
-
- public synchronized void updateBytes(int columnIndex, byte[] x)
- throws SQLException
- {
- updateValue(columnIndex, x);
- }
-
-
- public synchronized void updateCharacterStream(int columnIndex,
- java.io.Reader x,
- int length
- )
- throws SQLException
- {
- char[] theData = null;
- try
- {
- x.read(theData, 0, length);
-
- }
- catch (NullPointerException ex)
- {
- throw new PSQLException("postgresql.updateable.inputstream");
- }
- catch (IOException ie)
- {
- throw new PSQLException("postgresql.updateable.ioerror", ie);
- }
- updateValue(columnIndex, theData);
- }
-
-
- public synchronized void updateDate(int columnIndex, java.sql.Date x)
- throws SQLException
- {
- updateValue(columnIndex, x);
- }
-
-
- public synchronized void updateDouble(int columnIndex, double x)
- throws SQLException
- {
- if ( Driver.logDebug )
- Driver.debug("updating double " + fields[columnIndex - 1].getName() + "=" + x);
- updateValue(columnIndex, new Double(x));
- }
-
-
- public synchronized void updateFloat(int columnIndex, float x)
- throws SQLException
- {
- if ( Driver.logDebug )
- Driver.debug("updating float " + fields[columnIndex - 1].getName() + "=" + x);
- updateValue(columnIndex, new Float(x));
- }
-
-
- public synchronized void updateInt(int columnIndex, int x)
- throws SQLException
- {
- if ( Driver.logDebug )
- Driver.debug("updating int " + fields[columnIndex - 1].getName() + "=" + x);
- updateValue(columnIndex, new Integer(x));
- }
-
-
- public synchronized void updateLong(int columnIndex, long x)
- throws SQLException
- {
- if ( Driver.logDebug )
- Driver.debug("updating long " + fields[columnIndex - 1].getName() + "=" + x);
- updateValue(columnIndex, new Long(x));
- }
-
-
- public synchronized void updateNull(int columnIndex)
- throws SQLException
- {
- updateValue(columnIndex, new NullObject());
- }
-
-
- public synchronized void updateObject(int columnIndex, Object x)
- throws SQLException
- {
- if ( Driver.logDebug )
- Driver.debug("updating object " + fields[columnIndex - 1].getName() + " = " + x);
- updateValue(columnIndex, x);
- }
-
-
- public synchronized void updateObject(int columnIndex, Object x, int scale)
- throws SQLException
- {
- if ( !isUpdateable() )
- {
- throw new PSQLException( "postgresql.updateable.notupdateable" );
- }
-
- this.updateObject(columnIndex, x);
-
- }
-
-
- public void refreshRow() throws SQLException
- {
- if ( !isUpdateable() )
- {
- throw new PSQLException( "postgresql.updateable.notupdateable" );
- }
-
- try
- {
- StringBuffer selectSQL = new StringBuffer( "select ");
-
- final int numColumns = java.lang.reflect.Array.getLength(fields);
-
- for (int i = 0; i < numColumns; i++ )
- {
-
- selectSQL.append( fields[i].getName() );
-
- if ( i < numColumns - 1 )
- {
-
- selectSQL.append(", ");
- }
-
- }
- selectSQL.append(" from " ).append(tableName).append(" where ");
-
- int numKeys = primaryKeys.size();
-
- for ( int i = 0; i < numKeys; i++ )
- {
-
- PrimaryKey primaryKey = ((PrimaryKey) primaryKeys.get(i));
- selectSQL.append(primaryKey.name).append("= ?");
-
- if ( i < numKeys - 1 )
- {
- selectSQL.append(" and ");
- }
- }
- if ( Driver.logDebug )
- Driver.debug("selecting " + selectSQL.toString());
- selectStatement = ((java.sql.Connection) connection).prepareStatement(selectSQL.toString());
-
-
- for ( int j = 0, i = 1; j < numKeys; j++, i++)
- {
- selectStatement.setObject( i, ((PrimaryKey) primaryKeys.get(j)).getValue() );
- }
-
- AbstractJdbc2ResultSet rs = (AbstractJdbc2ResultSet) selectStatement.executeQuery();
-
- if ( rs.first() )
- {
- rowBuffer = rs.rowBuffer;
- }
-
- rows.setElementAt( rowBuffer, current_row );
- this_row = rowBuffer;
- if ( Driver.logDebug )
- Driver.debug("done updates");
-
- rs.close();
- selectStatement.close();
- selectStatement = null;
-
- }
- catch (Exception e)
- {
- if ( Driver.logDebug )
- Driver.debug(e.getClass().getName() + e);
- throw new SQLException( e.getMessage() );
- }
-
- }
-
-
- public synchronized void updateRow()
- throws SQLException
- {
- if ( !isUpdateable() )
- {
- throw new PSQLException( "postgresql.updateable.notupdateable" );
- }
-
- if (doingUpdates)
- {
-
- try
- {
-
- StringBuffer updateSQL = new StringBuffer("UPDATE " + tableName + " SET ");
-
- int numColumns = updateValues.size();
- Enumeration columns = updateValues.keys();
-
- for (int i = 0; columns.hasMoreElements(); i++ )
- {
-
- String column = (String) columns.nextElement();
- updateSQL.append("\"");
- updateSQL.append( column );
- updateSQL.append("\" = ?");
-
- if ( i < numColumns - 1 )
- {
-
- updateSQL.append(", ");
- }
-
- }
- updateSQL.append( " WHERE " );
-
- int numKeys = primaryKeys.size();
-
- for ( int i = 0; i < numKeys; i++ )
- {
-
- PrimaryKey primaryKey = ((PrimaryKey) primaryKeys.get(i));
- updateSQL.append("\"");
- updateSQL.append(primaryKey.name);
- updateSQL.append("\" = ?");
-
- if ( i < numKeys - 1 )
- {
- updateSQL.append(" and ");
- }
- }
- if ( Driver.logDebug )
- Driver.debug("updating " + updateSQL.toString());
- updateStatement = ((java.sql.Connection) connection).prepareStatement(updateSQL.toString());
-
- int i = 0;
- Iterator iterator = updateValues.values().iterator();
- for (; iterator.hasNext(); i++)
- {
- Object o = iterator.next();
- if (o instanceof NullObject)
- updateStatement.setNull(i+1,java.sql.Types.NULL);
- else
- updateStatement.setObject( i + 1, o );
-
- }
- for ( int j = 0; j < numKeys; j++, i++)
- {
- updateStatement.setObject( i + 1, ((PrimaryKey) primaryKeys.get(j)).getValue() );
- }
-
- updateStatement.executeUpdate();
- updateStatement.close();
-
- updateStatement = null;
- updateRowBuffer();
-
-
- if ( Driver.logDebug )
- Driver.debug("copying data");
- System.arraycopy(rowBuffer, 0, this_row, 0, rowBuffer.length);
-
- rows.setElementAt( rowBuffer, current_row );
- if ( Driver.logDebug )
- Driver.debug("done updates");
- updateValues.clear();
- doingUpdates = false;
- }
- catch (Exception e)
- {
- if ( Driver.logDebug )
- Driver.debug(e.getClass().getName() + e);
- throw new SQLException( e.getMessage() );
- }
-
- }
-
- }
-
-
- public synchronized void updateShort(int columnIndex, short x)
- throws SQLException
- {
- if ( Driver.logDebug )
- Driver.debug("in update Short " + fields[columnIndex - 1].getName() + " = " + x);
- updateValue(columnIndex, new Short(x));
- }
-
-
- public synchronized void updateString(int columnIndex, String x)
- throws SQLException
- {
- if ( Driver.logDebug )
- Driver.debug("in update String " + fields[columnIndex - 1].getName() + " = " + x);
- updateValue(columnIndex, x);
- }
-
-
- public synchronized void updateTime(int columnIndex, Time x)
- throws SQLException
- {
- if ( Driver.logDebug )
- Driver.debug("in update Time " + fields[columnIndex - 1].getName() + " = " + x);
- updateValue(columnIndex, x);
- }
-
-
- public synchronized void updateTimestamp(int columnIndex, Timestamp x)
- throws SQLException
- {
- if ( Driver.logDebug )
- Driver.debug("updating Timestamp " + fields[columnIndex - 1].getName() + " = " + x);
- updateValue(columnIndex, x);
-
- }
-
-
- public synchronized void updateNull(String columnName)
- throws SQLException
- {
- updateNull(findColumn(columnName));
- }
-
-
- public synchronized void updateBoolean(String columnName, boolean x)
- throws SQLException
- {
- updateBoolean(findColumn(columnName), x);
- }
-
-
- public synchronized void updateByte(String columnName, byte x)
- throws SQLException
- {
- updateByte(findColumn(columnName), x);
- }
-
-
- public synchronized void updateShort(String columnName, short x)
- throws SQLException
- {
- updateShort(findColumn(columnName), x);
- }
-
-
- public synchronized void updateInt(String columnName, int x)
- throws SQLException
- {
- updateInt(findColumn(columnName), x);
- }
-
-
- public synchronized void updateLong(String columnName, long x)
- throws SQLException
- {
- updateLong(findColumn(columnName), x);
- }
-
-
- public synchronized void updateFloat(String columnName, float x)
- throws SQLException
- {
- updateFloat(findColumn(columnName), x);
- }
-
-
- public synchronized void updateDouble(String columnName, double x)
- throws SQLException
- {
- updateDouble(findColumn(columnName), x);
- }
-
-
- public synchronized void updateBigDecimal(String columnName, BigDecimal x)
- throws SQLException
- {
- updateBigDecimal(findColumn(columnName), x);
- }
-
-
- public synchronized void updateString(String columnName, String x)
- throws SQLException
- {
- updateString(findColumn(columnName), x);
- }
-
-
- public synchronized void updateBytes(String columnName, byte x[])
- throws SQLException
- {
- updateBytes(findColumn(columnName), x);
- }
-
-
- public synchronized void updateDate(String columnName, java.sql.Date x)
- throws SQLException
- {
- updateDate(findColumn(columnName), x);
- }
-
-
- public synchronized void updateTime(String columnName, java.sql.Time x)
- throws SQLException
- {
- updateTime(findColumn(columnName), x);
- }
-
-
- public synchronized void updateTimestamp(String columnName, java.sql.Timestamp x)
- throws SQLException
- {
- updateTimestamp(findColumn(columnName), x);
- }
-
-
- public synchronized void updateAsciiStream(
- String columnName,
- java.io.InputStream x,
- int length)
- throws SQLException
- {
- updateAsciiStream(findColumn(columnName), x, length);
- }
-
-
- public synchronized void updateBinaryStream(
- String columnName,
- java.io.InputStream x,
- int length)
- throws SQLException
- {
- updateBinaryStream(findColumn(columnName), x, length);
- }
-
-
- public synchronized void updateCharacterStream(
- String columnName,
- java.io.Reader reader,
- int length)
- throws SQLException
- {
- updateCharacterStream(findColumn(columnName), reader, length);
- }
-
-
- public synchronized void updateObject(String columnName, Object x, int scale)
- throws SQLException
- {
- updateObject(findColumn(columnName), x);
- }
-
-
- public synchronized void updateObject(String columnName, Object x)
- throws SQLException
- {
- updateObject(findColumn(columnName), x);
- }
-
-
- /**
- * Is this ResultSet updateable?
- */
-
- boolean isUpdateable() throws SQLException
- {
-
- if (updateable)
- return true;
-
- if ( Driver.logDebug )
- Driver.debug("checking if rs is updateable");
-
- parseQuery();
-
- if ( singleTable == false )
- {
- if ( Driver.logDebug )
- Driver.debug("not a single table");
- return false;
- }
-
- if ( Driver.logDebug )
- Driver.debug("getting primary keys");
-
- //
- // Contains the primary key?
- //
-
- primaryKeys = new Vector();
-
- // this is not stricty jdbc spec, but it will make things much faster if used
- // the user has to select oid, * from table and then we will just use oid
-
-
- usingOID = false;
- int oidIndex = 0;
- try {
- oidIndex = findColumn( "oid" );
- } catch (SQLException l_se) {
- //Ignore if column oid isn't selected
- }
- int i = 0;
-
-
- // if we find the oid then just use it
-
- //oidIndex will be >0 if the oid was in the select list
- if ( oidIndex > 0 )
- {
- i++;
- primaryKeys.add( new PrimaryKey( oidIndex, "oid" ) );
- usingOID = true;
- }
- else
- {
- // otherwise go and get the primary keys and create a hashtable of keys
- String[] s = quotelessTableName(tableName);
- String quotelessTableName = s[0];
- String quotelessSchemaName = s[1];
- java.sql.ResultSet rs = ((java.sql.Connection) connection).getMetaData().getPrimaryKeys("", quotelessSchemaName, quotelessTableName);
- for (; rs.next(); i++ )
- {
- String columnName = rs.getString(4); // get the columnName
- int index = findColumn( columnName );
-
- if ( index > 0 )
- {
- primaryKeys.add( new PrimaryKey(index, columnName ) ); // get the primary key information
- }
- }
-
- rs.close();
- }
-
- numKeys = primaryKeys.size();
-
- if ( Driver.logDebug )
- Driver.debug( "no of keys=" + i );
-
- if ( i < 1 )
- {
- throw new SQLException("No Primary Keys");
- }
-
- updateable = primaryKeys.size() > 0;
-
- if ( Driver.logDebug )
- Driver.debug( "checking primary key " + updateable );
-
- return updateable;
- }
-
- /** Cracks out the table name and schema (if it exists) from a fully
- * qualified table name.
- * @param fullname string that we are trying to crack. Test cases:
- * Table: table ()
- * "Table": Table ()
- * Schema.Table: table (schema)
- * "Schema"."Table": Table (Schema)
- * "Schema"."Dot.Table": Dot.Table (Schema)
- * Schema."Dot.Table": Dot.Table (schema)
- *
- * @return String array with element zero always being the tablename and
- * element 1 the schema name which may be a zero length string.
- */
- public static String[] quotelessTableName(String fullname) {
- StringBuffer buf = new StringBuffer(fullname);
- String[] parts = new String[] {null, ""};
- StringBuffer acc = new StringBuffer();
- boolean betweenQuotes = false;
- for (int i = 0; i < buf.length(); i++) {
- char c = buf.charAt(i);
- switch (c) {
- case '"':
- if ((i < buf.length() - 1) && (buf.charAt(i+1) == '"')) {
- // two consecutive quotes - keep one
- i++;
- acc.append(c); // keep the quote
- }
- else { // Discard it
- betweenQuotes = !betweenQuotes;
- }
- break;
- case '.':
- if (betweenQuotes) { // Keep it
- acc.append(c);
- }
- else { // Have schema name
- parts[1] = acc.toString();
- acc = new StringBuffer();
- }
- break;
- default:
- acc.append((betweenQuotes) ? c : Character.toLowerCase(c));
- break;
- }
- }
- // Always put table in slot 0
- parts[0] = acc.toString();
- return parts;
- }
-
- public void parseQuery()
- {
- String[] l_sqlFragments = ((AbstractJdbc2Statement)statement).getSqlFragments();
- String l_sql = l_sqlFragments[0];
- StringTokenizer st = new StringTokenizer(l_sql, " \r\t\n");
- boolean tableFound = false, tablesChecked = false;
- String name = "";
-
- singleTable = true;
-
- while ( !tableFound && !tablesChecked && st.hasMoreTokens() )
- {
- name = st.nextToken();
- if ( !tableFound )
- {
- if (name.toLowerCase().equals("from"))
- {
- tableName = st.nextToken();
- tableFound = true;
- }
- }
- else
- {
- tablesChecked = true;
- // if the very next token is , then there are multiple tables
- singleTable = !name.equalsIgnoreCase(",");
- }
- }
- }
-
-
- private void updateRowBuffer() throws SQLException
- {
-
- Enumeration columns = updateValues.keys();
-
- while ( columns.hasMoreElements() )
- {
- String columnName = (String) columns.nextElement();
- int columnIndex = findColumn( columnName ) - 1;
-
- Object valueObject = updateValues.get(columnName);
- if (valueObject instanceof NullObject) {
- rowBuffer[columnIndex] = null;
- }
- else
- {
-
- switch ( connection.getSQLType( fields[columnIndex].getPGType() ) )
- {
-
- case Types.DECIMAL:
- case Types.BIGINT:
- case Types.DOUBLE:
- case Types.BIT:
- case Types.VARCHAR:
- case Types.DATE:
- case Types.TIME:
- case Types.TIMESTAMP:
- case Types.SMALLINT:
- case Types.FLOAT:
- case Types.INTEGER:
- case Types.CHAR:
- case Types.NUMERIC:
- case Types.REAL:
- case Types.TINYINT:
-
- rowBuffer[columnIndex] = connection.getEncoding().encode(String.valueOf( valueObject));
-
- case Types.NULL:
- continue;
-
- default:
- rowBuffer[columnIndex] = (byte[]) valueObject;
- }
-
- }
- }
- }
-
-
- public void setStatement(BaseStatement statement)
- {
- this.statement = statement;
- }
-
- protected void updateValue(int columnIndex, Object value) throws SQLException {
- if ( !isUpdateable() )
- {
- throw new PSQLException( "postgresql.updateable.notupdateable" );
- }
- doingUpdates = !onInsertRow;
- if (value == null)
- updateNull(columnIndex);
- else
- updateValues.put(fields[columnIndex - 1].getName(), value);
- }
-
- private class PrimaryKey
- {
- int index; // where in the result set is this primaryKey
- String name; // what is the columnName of this primary Key
-
- PrimaryKey( int index, String name)
- {
- this.index = index;
- this.name = name;
- }
- Object getValue() throws SQLException
- {
- return getObject(index);
- }
- };
-
- class NullObject {
- };
-
-}
-
+++ /dev/null
-package org.postgresql.jdbc2;
-
-
-import org.postgresql.core.Field;
-import org.postgresql.util.PSQLException;
-import org.postgresql.util.PSQLState;
-import java.sql.SQLException;
-import java.sql.Types;
-import java.util.Vector;
-
-public abstract class AbstractJdbc2ResultSetMetaData extends org.postgresql.jdbc1.AbstractJdbc1ResultSetMetaData
-{
-
- /*
- * Initialise for a result with a tuple set and
- * a field descriptor set
- *
- * @param rows the Vector of rows returned by the ResultSet
- * @param fields the array of field descriptors
- */
- public AbstractJdbc2ResultSetMetaData(Vector rows, Field[] fields)
- {
- super(rows, fields);
- }
-
- /*
- * Whats the number of columns in the ResultSet?
- *
- * @return the number
- * @exception SQLException if a database access error occurs
- */
- public int getColumnCount() throws SQLException
- {
- return fields.length;
- }
-
- /*
- * Is the column automatically numbered (and thus read-only)
- * I believe that PostgreSQL does not support this feature.
- *
- * @param column the first column is 1, the second is 2...
- * @return true if so
- * @exception SQLException if a database access error occurs
- */
- public boolean isAutoIncrement(int column) throws SQLException
- {
- return false;
- }
-
- /*
- * Does a column's case matter? ASSUMPTION: Any field that is
- * not obviously case insensitive is assumed to be case sensitive
- *
- * @param column the first column is 1, the second is 2...
- * @return true if so
- * @exception SQLException if a database access error occurs
- */
- public boolean isCaseSensitive(int column) throws SQLException
- {
- int sql_type = getField(column).getSQLType();
-
- switch (sql_type)
- {
- case Types.SMALLINT:
- case Types.INTEGER:
- case Types.FLOAT:
- case Types.REAL:
- case Types.DOUBLE:
- case Types.DATE:
- case Types.TIME:
- case Types.TIMESTAMP:
- return false;
- default:
- return true;
- }
- }
-
- /*
- * Can the column be used in a WHERE clause? Basically for
- * this, I split the functions into two types: recognised
- * types (which are always useable), and OTHER types (which
- * may or may not be useable). The OTHER types, for now, I
- * will assume they are useable. We should really query the
- * catalog to see if they are useable.
- *
- * @param column the first column is 1, the second is 2...
- * @return true if they can be used in a WHERE clause
- * @exception SQLException if a database access error occurs
- */
- public boolean isSearchable(int column) throws SQLException
- {
- int sql_type = getField(column).getSQLType();
-
- // This switch is pointless, I know - but it is a set-up
- // for further expansion.
- switch (sql_type)
- {
- case Types.OTHER:
- return true;
- default:
- return true;
- }
- }
-
- /*
- * Is the column a cash value? 6.1 introduced the cash/money
- * type, which haven't been incorporated as of 970414, so I
- * just check the type name for both 'cash' and 'money'
- *
- * @param column the first column is 1, the second is 2...
- * @return true if its a cash column
- * @exception SQLException if a database access error occurs
- */
- public boolean isCurrency(int column) throws SQLException
- {
- String type_name = getField(column).getPGType();
-
- return type_name.equals("cash") || type_name.equals("money");
- }
-
- /*
- * Indicates the nullability of values in the designated column.
- *
- * @param column the first column is 1, the second is 2...
- * @return one of the columnNullable values
- * @exception SQLException if a database access error occurs
- */
- public int isNullable(int column) throws SQLException
- {
- /*
- * TODO This needs a real implementation, taking into account columns
- * defined with NOT NULL or PRIMARY KEY, CHECK constraints, views,
- * functions etc.
- */
- return java.sql.ResultSetMetaData.columnNullableUnknown;
- }
-
- /*
- * Is the column a signed number? In PostgreSQL, all numbers
- * are signed, so this is trivial. However, strings are not
- * signed (duh!)
- *
- * @param column the first column is 1, the second is 2...
- * @return true if so
- * @exception SQLException if a database access error occurs
- */
- public boolean isSigned(int column) throws SQLException
- {
- int sql_type = getField(column).getSQLType();
-
- switch (sql_type)
- {
- case Types.SMALLINT:
- case Types.INTEGER:
- case Types.FLOAT:
- case Types.REAL:
- case Types.DOUBLE:
- return true;
- case Types.DATE:
- case Types.TIME:
- case Types.TIMESTAMP:
- return false; // I don't know about these?
- default:
- return false;
- }
- }
-
- /*
- * What is the column's normal maximum width in characters?
- *
- * @param column the first column is 1, the second is 2, etc.
- * @return the maximum width
- * @exception SQLException if a database access error occurs
- */
- public int getColumnDisplaySize(int column) throws SQLException
- {
- Field f = getField(column);
- String type_name = f.getPGType();
- int typmod = f.getMod();
-
- // I looked at other JDBC implementations and couldn't find a consistent
- // interpretation of the "display size" for numeric values, so this is our's
- // FIXME: currently, only types with a SQL92 or SQL3 pendant are implemented -
[email protected]
-
- // fixed length data types
- if (type_name.equals( "int2" ))
- return 6; // -32768 to +32768 (5 digits and a sign)
- if (type_name.equals( "int4" )
- || type_name.equals( "oid" ))
- return 11; // -2147483648 to +2147483647
- if (type_name.equals( "int8" ))
- return 20; // -9223372036854775808 to +9223372036854775807
- if (type_name.equals( "money" ))
- return 12; // MONEY = DECIMAL(9,2)
- if (type_name.equals( "float4" ))
- return 11; // i checked it out ans wasn't able to produce more than 11 digits
- if (type_name.equals( "float8" ))
- return 20; // dito, 20
- if (type_name.equals( "char" ))
- return 1;
- if (type_name.equals( "bool" ))
- return 1;
- if (type_name.equals( "date" ))
- return 14; // "01/01/4713 BC" - "31/12/32767 AD"
- if (type_name.equals( "time" ))
- return 8; // 00:00:00-23:59:59
- if (type_name.equals( "timestamp" ))
- return 22; // hhmmm ... the output looks like this: 1999-08-03 22:22:08+02
-
- // variable length fields
- typmod -= 4;
- if (type_name.equals( "bpchar" )
- || type_name.equals( "varchar" ))
- return typmod; // VARHDRSZ=sizeof(int32)=4
- if (type_name.equals( "numeric" ))
- return ( (typmod >> 16) & 0xffff )
- + 1 + ( typmod & 0xffff ); // DECIMAL(p,s) = (p digits).(s digits)
-
- // if we don't know better
- return f.getLength();
- }
-
- /*
- * What is the suggested column title for use in printouts and
- * displays? We suggest the ColumnName!
- *
- * @param column the first column is 1, the second is 2, etc.
- * @return the column label
- * @exception SQLException if a database access error occurs
- */
- public String getColumnLabel(int column) throws SQLException
- {
- return getColumnName(column);
- }
-
- /*
- * What's a column's name?
- *
- * @param column the first column is 1, the second is 2, etc.
- * @return the column name
- * @exception SQLException if a database access error occurs
- */
- public String getColumnName(int column) throws SQLException
- {
- Field f = getField(column);
- if (f != null)
- return f.getName();
- return "field" + column;
- }
-
- /*
- * What is a column's table's schema? This relies on us knowing
- * the table name....which I don't know how to do as yet. The
- * JDBC specification allows us to return "" if this is not
- * applicable.
- *
- * @param column the first column is 1, the second is 2...
- * @return the Schema
- * @exception SQLException if a database access error occurs
- */
- public String getSchemaName(int column) throws SQLException
- {
- return "";
- }
-
- /*
- * What is a column's number of decimal digits.
- *
- * @param column the first column is 1, the second is 2...
- * @return the precision
- * @exception SQLException if a database access error occurs
- */
- public int getPrecision(int column) throws SQLException
- {
- int sql_type = getField(column).getSQLType();
-
- switch (sql_type)
- {
- case Types.SMALLINT:
- return 5;
- case Types.INTEGER:
- return 10;
- case Types.REAL:
- return 8;
- case Types.FLOAT:
- return 16;
- case Types.DOUBLE:
- return 16;
- case Types.VARCHAR:
- return 0;
- case Types.NUMERIC:
- Field f = getField(column);
- if (f != null)
- return ((0xFFFF0000)&f.getMod()) >> 16;
- else
- return 0;
- default:
- return 0;
- }
- }
-
- /*
- * What is a column's number of digits to the right of the
- * decimal point?
- *
- * @param column the first column is 1, the second is 2...
- * @return the scale
- * @exception SQLException if a database access error occurs
- */
- public int getScale(int column) throws SQLException
- {
- int sql_type = getField(column).getSQLType();
-
- switch (sql_type)
- {
- case Types.SMALLINT:
- return 0;
- case Types.INTEGER:
- return 0;
- case Types.REAL:
- return 8;
- case Types.FLOAT:
- return 16;
- case Types.DOUBLE:
- return 16;
- case Types.VARCHAR:
- return 0;
- case Types.NUMERIC:
- Field f = getField(column);
- if (f != null)
- return (((0x0000FFFF)&f.getMod()) - 4);
- else
- return 0;
- default:
- return 0;
- }
- }
-
- /*
- * Whats a column's table's name? How do I find this out? Both
- * getSchemaName() and getCatalogName() rely on knowing the table
- * Name, so we need this before we can work on them.
- *
- * @param column the first column is 1, the second is 2...
- * @return column name, or "" if not applicable
- * @exception SQLException if a database access error occurs
- */
- public String getTableName(int column) throws SQLException
- {
- return "";
- }
-
- /*
- * What's a column's table's catalog name? As with getSchemaName(),
- * we can say that if getTableName() returns n/a, then we can too -
- * otherwise, we need to work on it.
- *
- * @param column the first column is 1, the second is 2...
- * @return catalog name, or "" if not applicable
- * @exception SQLException if a database access error occurs
- */
- public String getCatalogName(int column) throws SQLException
- {
- return "";
- }
-
- /*
- * What is a column's SQL Type? (java.sql.Type int)
- *
- * @param column the first column is 1, the second is 2, etc.
- * @return the java.sql.Type value
- * @exception SQLException if a database access error occurs
- * @see org.postgresql.Field#getSQLType
- * @see java.sql.Types
- */
- public int getColumnType(int column) throws SQLException
- {
- return getField(column).getSQLType();
- }
-
- /*
- * Whats is the column's data source specific type name?
- *
- * @param column the first column is 1, the second is 2, etc.
- * @return the type name
- * @exception SQLException if a database access error occurs
- */
- public String getColumnTypeName(int column) throws SQLException
- {
- return getField(column).getPGType();
- }
-
- /**
- * Is the column definitely not writable? In reality, we would
- * have to check the GRANT/REVOKE stuff for this to be effective,
- * and I haven't really looked into that yet, so this will get
- * re-visited.
- *
- * @param column the first column is 1, the second is 2, etc.
- * @return true if so
- * @exception SQLException if a database access error occurs
- */
- public boolean isReadOnly(int column) throws SQLException
- {
- return false;
- }
-
- /**
- * Is it possible for a write on the column to succeed? Again, we
- * would in reality have to check the GRANT/REVOKE stuff, which
- * I haven't worked with as yet. However, if it isn't ReadOnly, then
- * it is obviously writable.
- *
- * @param column the first column is 1, the second is 2, etc.
- * @return true if so
- * @exception SQLException if a database access error occurs
- */
- public boolean isWritable(int column) throws SQLException
- {
- return !isReadOnly(column);
- }
-
- /**
- * Will a write on this column definately succeed? Hmmm...this
- * is a bad one, since the two preceding functions have not been
- * really defined. I cannot tell is the short answer. I thus
- * return isWritable() just to give us an idea.
- *
- * @param column the first column is 1, the second is 2, etc..
- * @return true if so
- * @exception SQLException if a database access error occurs
- */
- public boolean isDefinitelyWritable(int column) throws SQLException
- {
- return false;
- }
-
- // ********************************************************
- // END OF PUBLIC INTERFACE
- // ********************************************************
-
- /**
- * For several routines in this package, we need to convert
- * a columnIndex into a Field[] descriptor. Rather than do
- * the same code several times, here it is.
- *
- * @param columnIndex the first column is 1, the second is 2...
- * @return the Field description
- * @exception SQLException if a database access error occurs
- */
- private Field getField(int columnIndex) throws SQLException
- {
- if (columnIndex < 1 || columnIndex > fields.length)
- throw new PSQLException("postgresql.res.colrange", PSQLState.INVALID_PARAMETER_VALUE);
- return fields[columnIndex - 1];
- }
-
- // ** JDBC 2 Extensions **
-
- // This can hook into our PG_Object mechanism
- /**
- * 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
- */
- public String getColumnClassName(int column) throws SQLException
- {
- /*
- The following data type mapping came from ../Field.java.
-
- "int2",
- "int4","oid",
- "int8",
- "cash","money",
- "numeric",
- "float4",
- "float8",
- "bpchar","char","char2","char4","char8","char16",
- "varchar","text","name","filename",
- "bool",
- "date",
- "time",
- "abstime","timestamp"
-
- Types.SMALLINT,
- Types.INTEGER,Types.INTEGER,
- Types.BIGINT,
- Types.DOUBLE,Types.DOUBLE,
- Types.NUMERIC,
- Types.REAL,
- Types.DOUBLE,
- Types.CHAR,Types.CHAR,Types.CHAR,Types.CHAR,Types.CHAR,Types.CHAR,
- Types.VARCHAR,Types.VARCHAR,Types.VARCHAR,Types.VARCHAR,
- Types.BIT,
- Types.DATE,
- Types.TIME,
- Types.TIMESTAMP,Types.TIMESTAMP
- */
-
- Field field = getField(column);
- int sql_type = field.getSQLType();
-
- switch (sql_type)
- {
- case Types.BIT:
- return ("java.lang.Boolean");
- case Types.SMALLINT:
- return ("java.lang.Short");
- case Types.INTEGER:
- return ("java.lang.Integer");
- case Types.BIGINT:
- return ("java.lang.Long");
- case Types.NUMERIC:
- return ("java.math.BigDecimal");
- case Types.REAL:
- return ("java.lang.Float");
- case Types.DOUBLE:
- return ("java.lang.Double");
- case Types.CHAR:
- case Types.VARCHAR:
- return ("java.lang.String");
- case Types.DATE:
- return ("java.sql.Date");
- case Types.TIME:
- return ("java.sql.Time");
- case Types.TIMESTAMP:
- return ("java.sql.Timestamp");
- case Types.BINARY:
- case Types.VARBINARY:
- return ("[B");
- case Types.ARRAY:
- return ("java.sql.Array");
- default:
- String type = field.getPGType();
- if ("unknown".equals(type))
- {
- return ("java.lang.String");
- }
- return ("java.lang.Object");
- }
- }
-}
-
+++ /dev/null
-package org.postgresql.jdbc2;
-
-
-import java.io.*;
-import java.math.*;
-import java.sql.*;
-import java.util.Vector;
-import org.postgresql.Driver;
-import org.postgresql.largeobject.*;
-import org.postgresql.util.PSQLException;
-import org.postgresql.util.PSQLState;
-
-/* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/jdbc2/AbstractJdbc2Statement.java,v 1.18 2003/11/29 19:52:10 pgsql Exp $
- * This class defines methods of the jdbc2 specification. This class extends
- * org.postgresql.jdbc1.AbstractJdbc1Statement which provides the jdbc1
- * methods. The real Statement class (for jdbc2) is org.postgresql.jdbc2.Jdbc2Statement
- */
-public abstract class AbstractJdbc2Statement extends org.postgresql.jdbc1.AbstractJdbc1Statement
-{
-
- protected Vector batch = null;
- protected int resultsettype; // the resultset type to return
- protected int concurrency; // is it updateable or not?
-
- public AbstractJdbc2Statement (AbstractJdbc2Connection c)
- {
- super(c);
- resultsettype = ResultSet.TYPE_SCROLL_INSENSITIVE;
- concurrency = ResultSet.CONCUR_READ_ONLY;
- }
-
- public AbstractJdbc2Statement(AbstractJdbc2Connection connection, String sql) throws SQLException
- {
- super(connection, sql);
- }
-
- /*
- * Execute a SQL statement that may return multiple results. We
- * don't have to worry about this since we do not support multiple
- * ResultSets. You can use getResultSet or getUpdateCount to
- * retrieve the result.
- *
- * @param sql any SQL statement
- * @return true if the next result is a ResulSet, false if it is
- * an update count or there are no more results
- * @exception SQLException if a database access error occurs
- */
- public boolean execute() throws SQLException
- {
- boolean l_return = super.execute();
- //Now do the jdbc2 specific stuff
- //required for ResultSet.getStatement() to work and updateable resultsets
- result.setStatement(this);
-
- return l_return;
- }
-
- // ** JDBC 2 Extensions **
-
- public void addBatch(String p_sql) throws SQLException
- {
- if (batch == null)
- batch = new Vector();
- Object[] l_statement = new Object[] {new String[] {p_sql}, new Object[0], new String[0]};
- batch.addElement(l_statement);
- }
-
- public void clearBatch() throws SQLException
- {
- batch = null;
- }
-
- public int[] executeBatch() throws SQLException
- {
- if (batch == null)
- batch = new Vector();
- int size = batch.size();
- int[] result = new int[size];
- int i = 0;
- try
- {
- //copy current state of statement
- String[] l_origSqlFragments = m_sqlFragments;
- Object[] l_origBinds = m_binds;
- String[] l_origBindTypes = m_bindTypes;
-
- for (i = 0;i < size;i++) {
- //set state from batch
- Object[] l_statement = (Object[])batch.elementAt(i);
- this.m_sqlFragments = (String[])l_statement[0];
- this.m_binds = (Object[])l_statement[1];
- this.m_bindTypes = (String[])l_statement[2];
- result[i] = this.executeUpdate();
- }
-
- //restore state of statement
- m_sqlFragments = l_origSqlFragments;
- m_binds = l_origBinds;
- m_bindTypes = l_origBindTypes;
-
- }
- catch (SQLException e)
- {
- int[] resultSucceeded = new int[i];
- System.arraycopy(result, 0, resultSucceeded, 0, i);
-
- PBatchUpdateException updex =
- new PBatchUpdateException("postgresql.stat.batch.error",
- new Integer(i), m_sqlFragments[0], resultSucceeded);
- updex.setNextException(e);
-
- throw updex;
- }
- finally
- {
- batch.removeAllElements();
- }
- return result;
- }
-
- public void cancel() throws SQLException
- {
- connection.cancelQuery();
- }
-
- public Connection getConnection() throws SQLException
- {
- return (Connection) connection;
- }
-
- public int getFetchDirection() throws SQLException
- {
- throw new PSQLException("postgresql.psqlnotimp", PSQLState.NOT_IMPLEMENTED);
- }
-
- public int getResultSetConcurrency() throws SQLException
- {
- return concurrency;
- }
-
- public int getResultSetType() throws SQLException
- {
- return resultsettype;
- }
-
- public void setFetchDirection(int direction) throws SQLException
- {
- // I don't think this should happen, since it's a hint it should just
- // fail quietly.
- // throw Driver.notImplemented();
- }
-
- public void setFetchSize(int rows) throws SQLException
- {
- if (rows<0) throw new PSQLException("postgresql.input.fetch.gt0");
- super.fetchSize = rows;
- }
-
- public void setResultSetConcurrency(int value) throws SQLException
- {
- concurrency = value;
- }
-
- public void setResultSetType(int value) throws SQLException
- {
- resultsettype = value;
- }
-
- public void addBatch() throws SQLException
- {
- if (batch == null)
- batch = new Vector();
-
- //we need to create copies, otherwise the values can be changed
- Object[] l_newSqlFragments = null;
- if (m_sqlFragments != null) {
- l_newSqlFragments = new String[m_sqlFragments.length];
- System.arraycopy(m_sqlFragments,0,l_newSqlFragments,0,m_sqlFragments.length);
- }
- Object[] l_newBinds = new Object[m_binds.length];
- System.arraycopy(m_binds,0,l_newBinds,0,m_binds.length);
- String[] l_newBindTypes = new String[m_bindTypes.length];
- System.arraycopy(m_bindTypes,0,l_newBindTypes,0,m_bindTypes.length);
- Object[] l_statement = new Object[] {l_newSqlFragments, l_newBinds, l_newBindTypes};
- batch.addElement(l_statement);
- }
-
- public ResultSetMetaData getMetaData() throws SQLException
- {
- ResultSet rs = getResultSet();
- if (rs != null)
- return rs.getMetaData();
-
- // Does anyone really know what this method does?
- return null;
- }
-
- public void setArray(int i, java.sql.Array x) throws SQLException
- {
- setString(i, x.toString());
- }
-
- public void setBlob(int i, Blob x) throws SQLException
- {
- InputStream l_inStream = x.getBinaryStream();
- LargeObjectManager lom = connection.getLargeObjectAPI();
- int oid = lom.create();
- LargeObject lob = lom.open(oid);
- OutputStream los = lob.getOutputStream();
- byte[] buf = new byte[4096];
- try
- {
- // could be buffered, but then the OutputStream returned by LargeObject
- // is buffered internally anyhow, so there would be no performance
- // boost gained, if anything it would be worse!
- int bytesRemaining = (int)x.length();
- int numRead = l_inStream.read(buf, 0, Math.min(buf.length, bytesRemaining));
- while (numRead != -1 && bytesRemaining > 0)
- {
- bytesRemaining -= numRead;
- if ( numRead == buf.length )
- los.write(buf); // saves a buffer creation and copy in LargeObject since it's full
- else
- los.write(buf,0,numRead);
- numRead = l_inStream.read(buf, 0, Math.min(buf.length, bytesRemaining));
- }
- }
- catch (IOException se)
- {
- throw new PSQLException("postgresql.unusual", PSQLState.UNEXPECTED_ERROR, se);
- }
- finally
- {
- try
- {
- los.close();
- l_inStream.close();
- }
- catch( Exception e ) {}
- }
- setInt(i, oid);
- }
-
- public void setCharacterStream(int i, java.io.Reader x, int length) throws SQLException
- {
- if (connection.haveMinimumCompatibleVersion("7.2"))
- {
- //Version 7.2 supports CharacterStream for for the PG text types
- //As the spec/javadoc for this method indicate this is to be used for
- //large text values (i.e. LONGVARCHAR) PG doesn't have a separate
- //long varchar datatype, but with toast all the text datatypes are capable of
- //handling very large values. Thus the implementation ends up calling
- //setString() since there is no current way to stream the value to the server
- char[] l_chars = new char[length];
- int l_charsRead;
- try
- {
- l_charsRead = x.read(l_chars, 0, length);
- }
- catch (IOException l_ioe)
- {
- throw new PSQLException("postgresql.unusual", PSQLState.UNEXPECTED_ERROR, l_ioe);
- }
- setString(i, new String(l_chars, 0, l_charsRead));
- }
- else
- {
- //Version 7.1 only supported streams for LargeObjects
- //but the jdbc spec indicates that streams should be
- //available for LONGVARCHAR instead
- LargeObjectManager lom = connection.getLargeObjectAPI();
- int oid = lom.create();
- LargeObject lob = lom.open(oid);
- OutputStream los = lob.getOutputStream();
- try
- {
- // could be buffered, but then the OutputStream returned by LargeObject
- // is buffered internally anyhow, so there would be no performance
- // boost gained, if anything it would be worse!
- int c = x.read();
- int p = 0;
- while (c > -1 && p < length)
- {
- los.write(c);
- c = x.read();
- p++;
- }
- los.close();
- }
- catch (IOException se)
- {
- throw new PSQLException("postgresql.unusual", PSQLState.UNEXPECTED_ERROR, se);
- }
- // lob is closed by the stream so don't call lob.close()
- setInt(i, oid);
- }
- }
-
- public void setClob(int i, Clob x) throws SQLException
- {
- InputStream l_inStream = x.getAsciiStream();
- int l_length = (int) x.length();
- LargeObjectManager lom = connection.getLargeObjectAPI();
- int oid = lom.create();
- LargeObject lob = lom.open(oid);
- OutputStream los = lob.getOutputStream();
- try
- {
- // could be buffered, but then the OutputStream returned by LargeObject
- // is buffered internally anyhow, so there would be no performance
- // boost gained, if anything it would be worse!
- int c = l_inStream.read();
- int p = 0;
- while (c > -1 && p < l_length)
- {
- los.write(c);
- c = l_inStream.read();
- p++;
- }
- los.close();
- }
- catch (IOException se)
- {
- throw new PSQLException("postgresql.unusual", PSQLState.UNEXPECTED_ERROR, se);
- }
- // lob is closed by the stream so don't call lob.close()
- setInt(i, oid);
- }
-
- public void setNull(int i, int t, String s) throws SQLException
- {
- setNull(i, t);
- }
-
- public void setRef(int i, Ref x) throws SQLException
- {
- throw Driver.notImplemented();
- }
-
- public void setDate(int i, java.sql.Date d, java.util.Calendar cal) throws SQLException
- {
- if (cal == null)
- setDate(i, d);
- else
- {
- cal.setTime(d);
- setDate(i, new java.sql.Date(cal.getTime().getTime()));
- }
- }
-
- public void setTime(int i, Time t, java.util.Calendar cal) throws SQLException
- {
- if (cal == null)
- setTime(i, t);
- else
- {
- cal.setTime(t);
- setTime(i, new java.sql.Time(cal.getTime().getTime()));
- }
- }
-
- public void setTimestamp(int i, Timestamp t, java.util.Calendar cal) throws SQLException
- {
- if (cal == null)
- setTimestamp(i, t);
- else
- {
- cal.setTime(t);
- setTimestamp(i, new java.sql.Timestamp(cal.getTime().getTime()));
- }
- }
-
- // ** JDBC 2 Extensions for CallableStatement**
-
- public java.sql.Array getArray(int i) throws SQLException
- {
- throw Driver.notImplemented();
- }
-
- public java.math.BigDecimal getBigDecimal(int parameterIndex) throws SQLException
- {
- checkIndex (parameterIndex, Types.NUMERIC, "BigDecimal");
- return ((BigDecimal)callResult);
- }
-
- public Blob getBlob(int i) throws SQLException
- {
- throw Driver.notImplemented();
- }
-
- public Clob getClob(int i) throws SQLException
- {
- throw Driver.notImplemented();
- }
-
- public Object getObject(int i, java.util.Map map) throws SQLException
- {
- throw Driver.notImplemented();
- }
-
- public Ref getRef(int i) throws SQLException
- {
- throw Driver.notImplemented();
- }
-
- public java.sql.Date getDate(int i, java.util.Calendar cal) throws SQLException
- {
- throw Driver.notImplemented();
- }
-
- public Time getTime(int i, java.util.Calendar cal) throws SQLException
- {
- throw Driver.notImplemented();
- }
-
- public Timestamp getTimestamp(int i, java.util.Calendar cal) throws SQLException
- {
- throw Driver.notImplemented();
- }
-
- // no custom types allowed yet..
- public void registerOutParameter(int parameterIndex, int sqlType, String typeName) throws SQLException
- {
- throw Driver.notImplemented();
- }
-
-
- //This is needed by AbstractJdbc2ResultSet to determine if the query is updateable or not
- protected String[] getSqlFragments()
- {
- return m_sqlFragments;
- }
-
-}
+++ /dev/null
-package org.postgresql.jdbc2;
-
-import org.postgresql.core.BaseConnection;
-import org.postgresql.core.BaseResultSet;
-import org.postgresql.core.BaseStatement;
-import org.postgresql.core.Field;
-import org.postgresql.util.PSQLException;
-import org.postgresql.util.PSQLState;
-
-import java.math.BigDecimal;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Timestamp;
-import java.sql.Types;
-import java.util.ArrayList;
-import java.util.Map;
-import java.util.Vector;
-
-/*
- * Array is used collect one column of query result data.
- *
- *
Read a field of type Array into either a natively-typed
- * Java array object or a ResultSet. Accessor methods provide
- * the ability to capture array slices.
- *
- *
Other than the constructor all methods are direct implementations
- * of those specified for java.sql.Array. Please refer to the javadoc
- * for java.sql.Array for detailed descriptions of the functionality
- * and parameters of the methods of this class.
- *
- * @see ResultSet#getArray
- */
-
-
-public class Array implements java.sql.Array
-{
- private BaseConnection conn = null;
- private Field field = null;
- private BaseResultSet rs;
- private int idx = 0;
- private String rawString = null;
-
- /*
- * Create a new Array
- *
- * @param conn a database connection
- * @param idx 1-based index of the query field to load into this Array
- * @param field the Field descriptor for the field to load into this Array
- * @param rs the ResultSet from which to get the data for this Array
- */
- public Array(BaseConnection conn, int idx, Field field, BaseResultSet rs )
- throws SQLException
- {
- this.conn = conn;
- this.field = field;
- this.rs = rs;
- this.idx = idx;
- this.rawString = rs.getFixedString(idx);
- }
-
- public Object getArray() throws SQLException
- {
- return getArray( 1, 0, null );
- }
-
- public Object getArray(long index, int count) throws SQLException
- {
- return getArray( index, count, null );
- }
-
- public Object getArray(Map map) throws SQLException
- {
- return getArray( 1, 0, map );
- }
-
- public Object getArray(long index, int count, Map map) throws SQLException
- {
- if ( map != null ) // For now maps aren't supported.
- throw org.postgresql.Driver.notImplemented();
-
- if (index < 1)
- throw new PSQLException("postgresql.arr.range", PSQLState.DATA_ERROR);
- Object retVal = null;
-
- ArrayList array = new ArrayList();
-
- /* Check if the String is also not an empty array
- * otherwise there will be an exception thrown below
- * in the ResultSet.toX with an empty string.
- * -- Doug Fields Feb 20, 2002 */
-
- if ( rawString != null && !rawString.equals("{}") )
- {
- char[] chars = rawString.toCharArray();
- StringBuffer sbuf = new StringBuffer();
- boolean foundOpen = false;
- boolean insideString = false;
- for ( int i = 0; i < chars.length; i++ )
- {
- if ( chars[i] == '\\' )
- //escape character that we need to skip
- i++;
- else if (!insideString && chars[i] == '{' )
- {
- if ( foundOpen ) // Only supports 1-D arrays for now
- throw org.postgresql.Driver.notImplemented();
- foundOpen = true;
- continue;
- }
- else if (chars[i] == '"')
- {
- insideString = !insideString;
- continue;
- }
- else if (!insideString && (chars[i] == ',' || chars[i] == '}') ||
- i == chars.length - 1)
- {
- if ( chars[i] != '"' && chars[i] != '}' && chars[i] != ',' )
- sbuf.append(chars[i]);
- array.add( sbuf.toString() );
- sbuf = new StringBuffer();
- continue;
- }
- sbuf.append( chars[i] );
- }
- }
- String[] arrayContents = (String[]) array.toArray( new String[array.size()] );
- if ( count == 0 )
- count = arrayContents.length;
- index--;
- if ( index + count > arrayContents.length )
- throw new PSQLException("postgresql.arr.range", PSQLState.DATA_ERROR);
-
- int i = 0;
- switch ( getBaseType() )
- {
- case Types.BIT:
- retVal = new boolean[ count ];
- for ( ; count > 0; count-- )
- ((boolean[])retVal)[i++] = AbstractJdbc2ResultSet.toBoolean( arrayContents[(int)index++] );
- break;
- case Types.SMALLINT:
- case Types.INTEGER:
- retVal = new int[ count ];
- for ( ; count > 0; count-- )
- ((int[])retVal)[i++] = AbstractJdbc2ResultSet.toInt( arrayContents[(int)index++] );
- break;
- case Types.BIGINT:
- retVal = new long[ count ];
- for ( ; count > 0; count-- )
- ((long[])retVal)[i++] = AbstractJdbc2ResultSet.toLong( arrayContents[(int)index++] );
- break;
- case Types.NUMERIC:
- retVal = new BigDecimal[ count ];
- for ( ; count > 0; count-- )
- ((BigDecimal[])retVal)[i++] = AbstractJdbc2ResultSet.toBigDecimal( arrayContents[(int)index++], 0 );
- break;
- case Types.REAL:
- retVal = new float[ count ];
- for ( ; count > 0; count-- )
- ((float[])retVal)[i++] = AbstractJdbc2ResultSet.toFloat( arrayContents[(int)index++] );
- break;
- case Types.DOUBLE:
- retVal = new double[ count ];
- for ( ; count > 0; count-- )
- ((double[])retVal)[i++] = AbstractJdbc2ResultSet.toDouble( arrayContents[(int)index++] );
- break;
- case Types.CHAR:
- case Types.VARCHAR:
- retVal = new String[ count ];
- for ( ; count > 0; count-- )
- ((String[])retVal)[i++] = arrayContents[(int)index++];
- break;
- case Types.DATE:
- retVal = new java.sql.Date[ count ];
- for ( ; count > 0; count-- )
- ((java.sql.Date[])retVal)[i++] = AbstractJdbc2ResultSet.toDate( arrayContents[(int)index++] );
- break;
- case Types.TIME:
- retVal = new java.sql.Time[ count ];
- for ( ; count > 0; count-- )
- ((java.sql.Time[])retVal)[i++] = AbstractJdbc2ResultSet.toTime( arrayContents[(int)index++], rs, getBaseTypeName() );
- break;
- case Types.TIMESTAMP:
- retVal = new Timestamp[ count ];
- for ( ; count > 0; count-- )
- ((java.sql.Timestamp[])retVal)[i++] = AbstractJdbc2ResultSet.toTimestamp( arrayContents[(int)index++], rs, getBaseTypeName() );
- break;
-
- // Other datatypes not currently supported. If you are really using other types ask
- // yourself if an array of non-trivial data types is really good database design.
- default:
- throw org.postgresql.Driver.notImplemented();
- }
- return retVal;
- }
-
- public int getBaseType() throws SQLException
- {
- return conn.getSQLType(getBaseTypeName());
- }
-
- public String getBaseTypeName() throws SQLException
- {
- String fType = field.getPGType();
- if ( fType.charAt(0) == '_' )
- fType = fType.substring(1);
- return fType;
- }
-
- public java.sql.ResultSet getResultSet() throws SQLException
- {
- return getResultSet( 1, 0, null );
- }
-
- public java.sql.ResultSet getResultSet(long index, int count) throws SQLException
- {
- return getResultSet( index, count, null );
- }
-
- public java.sql.ResultSet getResultSet(Map map) throws SQLException
- {
- return getResultSet( 1, 0, map );
- }
-
- public java.sql.ResultSet getResultSet(long index, int count, java.util.Map map) throws SQLException
- {
- Object array = getArray( index, count, map );
- Vector rows = new Vector();
- Field[] fields = new Field[2];
- fields[0] = new Field(conn, "INDEX", conn.getPGType("int2"), 2);
- switch ( getBaseType() )
- {
- case Types.BIT:
- boolean[] booleanArray = (boolean[]) array;
- fields[1] = new Field(conn, "VALUE", conn.getPGType("bool"), 1);
- for ( int i = 0; i < booleanArray.length; i++ )
- {
- byte[][] tuple = new byte[2][0];
- tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
- tuple[1] = conn.getEncoding().encode( (booleanArray[i] ? "YES" : "NO") ); // Value
- rows.addElement(tuple);
- }
- case Types.SMALLINT:
- fields[1] = new Field(conn, "VALUE", conn.getPGType("int2"), 2);
- case Types.INTEGER:
- int[] intArray = (int[]) array;
- if ( fields[1] == null )
- fields[1] = new Field(conn, "VALUE", conn.getPGType("int4"), 4);
- for ( int i = 0; i < intArray.length; i++ )
- {
- byte[][] tuple = new byte[2][0];
- tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
- tuple[1] = conn.getEncoding().encode( Integer.toString(intArray[i]) ); // Value
- rows.addElement(tuple);
- }
- break;
- case Types.BIGINT:
- long[] longArray = (long[]) array;
- fields[1] = new Field(conn, "VALUE", conn.getPGType("int8"), 8);
- for ( int i = 0; i < longArray.length; i++ )
- {
- byte[][] tuple = new byte[2][0];
- tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
- tuple[1] = conn.getEncoding().encode( Long.toString(longArray[i]) ); // Value
- rows.addElement(tuple);
- }
- break;
- case Types.NUMERIC:
- BigDecimal[] bdArray = (BigDecimal[]) array;
- fields[1] = new Field(conn, "VALUE", conn.getPGType("numeric"), -1);
- for ( int i = 0; i < bdArray.length; i++ )
- {
- byte[][] tuple = new byte[2][0];
- tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
- tuple[1] = conn.getEncoding().encode( bdArray[i].toString() ); // Value
- rows.addElement(tuple);
- }
- break;
- case Types.REAL:
- float[] floatArray = (float[]) array;
- fields[1] = new Field(conn, "VALUE", conn.getPGType("float4"), 4);
- for ( int i = 0; i < floatArray.length; i++ )
- {
- byte[][] tuple = new byte[2][0];
- tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
- tuple[1] = conn.getEncoding().encode( Float.toString(floatArray[i]) ); // Value
- rows.addElement(tuple);
- }
- break;
- case Types.DOUBLE:
- double[] doubleArray = (double[]) array;
- fields[1] = new Field(conn, "VALUE", conn.getPGType("float8"), 8);
- for ( int i = 0; i < doubleArray.length; i++ )
- {
- byte[][] tuple = new byte[2][0];
- tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
- tuple[1] = conn.getEncoding().encode( Double.toString(doubleArray[i]) ); // Value
- rows.addElement(tuple);
- }
- break;
- case Types.CHAR:
- fields[1] = new Field(conn, "VALUE", conn.getPGType("char"), 1);
- case Types.VARCHAR:
- String[] strArray = (String[]) array;
- if ( fields[1] == null )
- fields[1] = new Field(conn, "VALUE", conn.getPGType("varchar"), -1);
- for ( int i = 0; i < strArray.length; i++ )
- {
- byte[][] tuple = new byte[2][0];
- tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
- tuple[1] = conn.getEncoding().encode( strArray[i] ); // Value
- rows.addElement(tuple);
- }
- break;
- case Types.DATE:
- java.sql.Date[] dateArray = (java.sql.Date[]) array;
- fields[1] = new Field(conn, "VALUE", conn.getPGType("date"), 4);
- for ( int i = 0; i < dateArray.length; i++ )
- {
- byte[][] tuple = new byte[2][0];
- tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
- tuple[1] = conn.getEncoding().encode( dateArray[i].toString() ); // Value
- rows.addElement(tuple);
- }
- break;
- case Types.TIME:
- java.sql.Time[] timeArray = (java.sql.Time[]) array;
- fields[1] = new Field(conn, "VALUE", conn.getPGType("time"), 8);
- for ( int i = 0; i < timeArray.length; i++ )
- {
- byte[][] tuple = new byte[2][0];
- tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
- tuple[1] = conn.getEncoding().encode( timeArray[i].toString() ); // Value
- rows.addElement(tuple);
- }
- break;
- case Types.TIMESTAMP:
- java.sql.Timestamp[] timestampArray = (java.sql.Timestamp[]) array;
- fields[1] = new Field(conn, "VALUE", conn.getPGType("timestamp"), 8);
- for ( int i = 0; i < timestampArray.length; i++ )
- {
- byte[][] tuple = new byte[2][0];
- tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
- tuple[1] = conn.getEncoding().encode( timestampArray[i].toString() ); // Value
- rows.addElement(tuple);
- }
- break;
-
- // Other datatypes not currently supported. If you are really using other types ask
- // yourself if an array of non-trivial data types is really good database design.
- default:
- throw org.postgresql.Driver.notImplemented();
- }
- BaseStatement stat = (BaseStatement) conn.createStatement();
- return (ResultSet) stat.createResultSet(fields, rows, "OK", 1, 0, false);
- }
-
- public String toString()
- {
- return rawString;
- }
-}
-
+++ /dev/null
-package org.postgresql.jdbc2;
-
-
-public class Jdbc2Blob extends AbstractJdbc2Blob implements java.sql.Blob
-{
-
- public Jdbc2Blob(org.postgresql.PGConnection conn, int oid) throws java.sql.SQLException
- {
- super(conn, oid);
- }
-
-}
+++ /dev/null
-package org.postgresql.jdbc2;
-
-
-import java.sql.*;
-import java.util.Vector;
-import org.postgresql.PGRefCursorResultSet;
-import org.postgresql.core.BaseResultSet;
-import org.postgresql.core.Field;
-
-public class Jdbc2CallableStatement extends org.postgresql.jdbc2.AbstractJdbc2Statement implements java.sql.CallableStatement
-{
-
- public Jdbc2CallableStatement(Jdbc2Connection connection, String sql) throws SQLException
- {
- super(connection, sql);
- }
-
- public BaseResultSet createResultSet (Field[] fields, Vector tuples, String status, int updateCount, long insertOID, boolean binaryCursor) throws SQLException
- {
- return new Jdbc2ResultSet(this, fields, tuples, status, updateCount, insertOID, binaryCursor);
- }
-
- public PGRefCursorResultSet createRefCursorResultSet (String cursorName) throws SQLException
- {
- return new Jdbc2RefCursorResultSet(this, cursorName);
- }
-}
-
+++ /dev/null
-package org.postgresql.jdbc2;
-
-
-public class Jdbc2Clob extends AbstractJdbc2Clob implements java.sql.Clob
-{
-
- public Jdbc2Clob(org.postgresql.PGConnection conn, int oid) throws java.sql.SQLException
- {
- super(conn, oid);
- }
-
-}
+++ /dev/null
-package org.postgresql.jdbc2;
-
-
-import java.sql.*;
-import java.util.Vector;
-import java.util.Hashtable;
-import org.postgresql.core.Field;
-
-/* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/jdbc2/Jdbc2Connection.java,v 1.8 2003/11/29 19:52:10 pgsql Exp $
- * This class implements the java.sql.Connection interface for JDBC2.
- * However most of the implementation is really done in
- * org.postgresql.jdbc2.AbstractJdbc2Connection or one of it's parents
- */
-public class Jdbc2Connection extends org.postgresql.jdbc2.AbstractJdbc2Connection implements java.sql.Connection
-{
-
- public java.sql.Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException
- {
- Jdbc2Statement s = new Jdbc2Statement(this);
- s.setResultSetType(resultSetType);
- s.setResultSetConcurrency(resultSetConcurrency);
- return s;
- }
-
-
- public java.sql.PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException
- {
- Jdbc2PreparedStatement s = new Jdbc2PreparedStatement(this, sql);
- s.setResultSetType(resultSetType);
- s.setResultSetConcurrency(resultSetConcurrency);
- return s;
- }
-
- public java.sql.CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException
- {
- Jdbc2CallableStatement s = new org.postgresql.jdbc2.Jdbc2CallableStatement(this, sql);
- s.setResultSetType(resultSetType);
- s.setResultSetConcurrency(resultSetConcurrency);
- return s;
- }
-
- public java.sql.DatabaseMetaData getMetaData() throws SQLException
- {
- if (metadata == null)
- metadata = new org.postgresql.jdbc2.Jdbc2DatabaseMetaData(this);
- return metadata;
- }
-
-}
-
-
+++ /dev/null
-package org.postgresql.jdbc2;
-
-
-public class Jdbc2DatabaseMetaData extends org.postgresql.jdbc2.AbstractJdbc2DatabaseMetaData implements java.sql.DatabaseMetaData
-{
- public Jdbc2DatabaseMetaData(Jdbc2Connection conn)
- {
- super(conn);
- }
-
-}
+++ /dev/null
-package org.postgresql.jdbc2;
-
-
-import java.sql.*;
-import java.util.Vector;
-import org.postgresql.PGRefCursorResultSet;
-import org.postgresql.core.BaseResultSet;
-import org.postgresql.core.Field;
-
-public class Jdbc2PreparedStatement extends org.postgresql.jdbc2.AbstractJdbc2Statement implements java.sql.PreparedStatement
-{
-
- public Jdbc2PreparedStatement(Jdbc2Connection connection, String sql) throws SQLException
- {
- super(connection, sql);
- }
-
- public BaseResultSet createResultSet (Field[] fields, Vector tuples, String status, int updateCount, long insertOID, boolean binaryCursor) throws SQLException
- {
- return new Jdbc2ResultSet(this, fields, tuples, status, updateCount, insertOID, binaryCursor);
- }
-
-
- public PGRefCursorResultSet createRefCursorResultSet (String cursorName) throws SQLException
- {
- return new Jdbc2RefCursorResultSet(this, cursorName);
- }
-}
-
+++ /dev/null
-package org.postgresql.jdbc2;
-
-
-import org.postgresql.core.QueryExecutor;
-import org.postgresql.core.BaseStatement;
-import org.postgresql.PGRefCursorResultSet;
-
-
-/** A real result set based on a ref cursor.
- *
- * @author Nic Ferrier
- */
-public class Jdbc2RefCursorResultSet extends Jdbc2ResultSet
- implements PGRefCursorResultSet
-{
-
- String refCursorHandle;
-
- // Indicates when the result set has activaly bound to the cursor.
- boolean isInitialized = false;
-
- Jdbc2RefCursorResultSet(BaseStatement statement, String refCursorName) throws java.sql.SQLException
- {
- super(statement, null, null, null, -1, 0L, false);
- this.refCursorHandle = refCursorName;
- }
-
- public String getRefCursor ()
- {
- return refCursorHandle;
- }
-
- public boolean next () throws java.sql.SQLException
- {
- if (isInitialized)
- return super.next();
- // Initialize this res set with the rows from the cursor.
- String[] toExec = { "FETCH ALL IN \"" + refCursorHandle + "\";" };
- QueryExecutor.execute(toExec, new String[0], this);
- isInitialized = true;
- return super.next();
- }
-}
+++ /dev/null
-package org.postgresql.jdbc2;
-
-
-import java.sql.*;
-import java.util.Vector;
-import org.postgresql.core.BaseStatement;
-import org.postgresql.core.Field;
-
-/* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/jdbc2/Jdbc2ResultSet.java,v 1.9 2003/11/29 19:52:10 pgsql Exp $
- * This class implements the java.sql.ResultSet interface for JDBC2.
- * However most of the implementation is really done in
- * org.postgresql.jdbc2.AbstractJdbc2ResultSet or one of it's parents
- */
-public class Jdbc2ResultSet extends org.postgresql.jdbc2.AbstractJdbc2ResultSet implements java.sql.ResultSet
-{
-
- public Jdbc2ResultSet(BaseStatement statement, Field[] fields, Vector tuples, String status, int updateCount, long insertOID, boolean binaryCursor)
- {
- super(statement, fields, tuples, status, updateCount, insertOID, binaryCursor);
- }
-
- public ResultSetMetaData getMetaData() throws SQLException
- {
- return new Jdbc2ResultSetMetaData(rows, fields);
- }
-
- public java.sql.Clob getClob(int i) throws SQLException
- {
- wasNullFlag = (this_row[i - 1] == null);
- if (wasNullFlag)
- return null;
-
- return new org.postgresql.jdbc2.Jdbc2Clob(connection, getInt(i));
- }
-
- public java.sql.Blob getBlob(int i) throws SQLException
- {
- wasNullFlag = (this_row[i - 1] == null);
- if (wasNullFlag)
- return null;
-
- return new org.postgresql.jdbc2.Jdbc2Blob(connection, getInt(i));
- }
-
-}
-
+++ /dev/null
-package org.postgresql.jdbc2;
-
-import java.util.Vector;
-import org.postgresql.core.Field;
-
-public class Jdbc2ResultSetMetaData extends AbstractJdbc2ResultSetMetaData implements java.sql.ResultSetMetaData
-{
- public Jdbc2ResultSetMetaData(Vector rows, Field[] fields)
- {
- super(rows, fields);
- }
-}
-
+++ /dev/null
-package org.postgresql.jdbc2;
-
-
-import java.sql.*;
-import java.util.Vector;
-import org.postgresql.PGRefCursorResultSet;
-import org.postgresql.core.BaseResultSet;
-import org.postgresql.core.Field;
-
-/* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/jdbc2/Jdbc2Statement.java,v 1.7 2003/11/29 19:52:10 pgsql Exp $
- * This class implements the java.sql.Statement interface for JDBC2.
- * However most of the implementation is really done in
- * org.postgresql.jdbc2.AbstractJdbc2Statement or one of it's parents
- */
-public class Jdbc2Statement extends org.postgresql.jdbc2.AbstractJdbc2Statement implements java.sql.Statement
-{
-
- public Jdbc2Statement (Jdbc2Connection c)
- {
- super(c);
- }
-
- public BaseResultSet createResultSet (Field[] fields, Vector tuples, String status, int updateCount, long insertOID, boolean binaryCursor) throws SQLException
- {
- return new Jdbc2ResultSet(this, fields, tuples, status, updateCount, insertOID, binaryCursor);
- }
-
- public PGRefCursorResultSet createRefCursorResultSet (String cursorName) throws SQLException
- {
- return new Jdbc2RefCursorResultSet(this, cursorName);
- }
-}
+++ /dev/null
-package org.postgresql.jdbc2;
-
-import org.postgresql.util.MessageTranslator;
-
-/*
- * This class extends java.sql.BatchUpdateException, and provides our
- * internationalisation handling.
- */
-class PBatchUpdateException extends java.sql.BatchUpdateException
-{
-
- private String message;
-
- public PBatchUpdateException(
- String error, Object arg1, Object arg2, int[] updateCounts )
- {
-
- super(updateCounts);
-
- Object[] argv = new Object[2];
- argv[0] = arg1;
- argv[1] = arg2;
- translate(error, argv);
- }
-
- private void translate(String error, Object[] args)
- {
- message = MessageTranslator.translate(error, args);
- }
-
- // Overides Throwable
- public String getLocalizedMessage()
- {
- return message;
- }
-
- // Overides Throwable
- public String getMessage()
- {
- return message;
- }
-
- // Overides Object
- public String toString()
- {
- return message;
- }
-}
+++ /dev/null
-package org.postgresql.jdbc3;
-
-
-import java.sql.*;
-
-public abstract class AbstractJdbc3Blob extends org.postgresql.jdbc2.AbstractJdbc2Blob
-{
-
- public AbstractJdbc3Blob(org.postgresql.PGConnection conn, int oid) throws SQLException
- {
- super(conn, oid);
- }
-
- /**
- * Writes the given array of bytes to the BLOB
value that
- * this Blob
object represents, starting at position
- * pos
, and returns the number of bytes written.
- *
- * @param pos the position in the BLOB
object at which
- * to start writing
- * @param bytes the array of bytes to be written to the BLOB
- * value that this Blob
object represents
- * @return the number of bytes written
- * @exception SQLException if there is an error accessing the
- * BLOB
value
- * @see #getBytes
- * @since 1.4
- */
- public int setBytes(long pos, byte[] bytes) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Writes all or part of the given byte
array to the
- * BLOB
value that this Blob
object represents
- * and returns the number of bytes written.
- * Writing starts at position pos
in the BLOB
- * value; len
bytes from the given byte array are written.
- *
- * @param pos the position in the BLOB
object at which
- * to start writing
- * @param bytes the array of bytes to be written to this BLOB
- * object
- * @param offset the offset into the array bytes
at which
- * to start reading the bytes to be set
- * @param len the number of bytes to be written to the BLOB
- * value from the array of bytes bytes
- * @return the number of bytes written
- * @exception SQLException if there is an error accessing the
- * BLOB
value
- * @see #getBytes
- * @since 1.4
- */
- public int setBytes(long pos, byte[] bytes, int offset, int len) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves a stream that can be used to write to the BLOB
- * value that this Blob
object represents. The stream begins
- * at position pos
.
- *
- * @param pos the position in the BLOB
value at which
- * to start writing
- * @return a java.io.OutputStream
object to which data can
- * be written
- * @exception SQLException if there is an error accessing the
- * BLOB
value
- * @see #getBinaryStream
- * @since 1.4
- */
- public java.io.OutputStream setBinaryStream(long pos) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Truncates the BLOB
value that this Blob
- * object represents to be len
bytes in length.
- *
- * @param len the length, in bytes, to which the BLOB
value
- * that this Blob
object represents should be truncated
- * @exception SQLException if there is an error accessing the
- * BLOB
value
- * @since 1.4
- */
- public void truncate(long len) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
-}
+++ /dev/null
-package org.postgresql.jdbc3;
-
-
-import java.sql.*;
-
-public abstract class AbstractJdbc3Clob extends org.postgresql.jdbc2.AbstractJdbc2Clob
-{
-
- public AbstractJdbc3Clob(org.postgresql.PGConnection conn, int oid) throws SQLException
- {
- super(conn, oid);
- }
-
- /**
- * Writes the given Java String
to the CLOB
- * value that this Clob
object designates at the position
- * pos
.
- *
- * @param pos the position at which to start writing to the CLOB
- * value that this Clob
object represents
- * @param str the string to be written to the CLOB
- * value that this Clob
designates
- * @return the number of characters written
- * @exception SQLException if there is an error accessing the
- * CLOB
value
- *
- * @since 1.4
- */
- public int setString(long pos, String str) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Writes len
characters of str
, starting
- * at character offset
, to the CLOB
value
- * that this Clob
represents.
- *
- * @param pos the position at which to start writing to this
- * CLOB
object
- * @param str the string to be written to the CLOB
- * value that this Clob
object represents
- * @param offset the offset into str
to start reading
- * the characters to be written
- * @param len the number of characters to be written
- * @return the number of characters written
- * @exception SQLException if there is an error accessing the
- * CLOB
value
- *
- * @since 1.4
- */
- public int setString(long pos, String str, int offset, int len) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves a stream to be used to write Ascii characters to the
- * CLOB
value that this Clob
object represents,
- * starting at position pos
.
- *
- * @param pos the position at which to start writing to this
- * CLOB
object
- * @return the stream to which ASCII encoded characters can be written
- * @exception SQLException if there is an error accessing the
- * CLOB
value
- * @see #getAsciiStream
- *
- * @since 1.4
- */
- public java.io.OutputStream setAsciiStream(long pos) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves a stream to be used to write a stream of Unicode characters
- * to the CLOB
value that this Clob
object
- * represents, at position pos
.
- *
- * @param pos the position at which to start writing to the
- * CLOB
value
- *
- * @return a stream to which Unicode encoded characters can be written
- * @exception SQLException if there is an error accessing the
- * CLOB
value
- * @see #getCharacterStream
- *
- * @since 1.4
- */
- public java.io.Writer setCharacterStream(long pos) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Truncates the CLOB
value that this Clob
- * designates to have a length of len
- * characters.
- * @param len the length, in bytes, to which the CLOB
value
- * should be truncated
- * @exception SQLException if there is an error accessing the
- * CLOB
value
- *
- * @since 1.4
- */
- public void truncate(long len) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
-}
+++ /dev/null
-package org.postgresql.jdbc3;
-
-import java.sql.*;
-
-/* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/jdbc3/AbstractJdbc3Connection.java,v 1.5 2003/11/29 19:52:10 pgsql Exp $
- * This class defines methods of the jdbc3 specification. This class extends
- * org.postgresql.jdbc2.AbstractJdbc2Connection which provides the jdbc2
- * methods. The real Connection class (for jdbc3) is org.postgresql.jdbc3.Jdbc3Connection
- */
-public abstract class AbstractJdbc3Connection extends org.postgresql.jdbc2.AbstractJdbc2Connection
-{
-
- /**
- * Changes the holdability of ResultSet
objects
- * created using this Connection
object to the given
- * holdability.
- *
- * @param holdability a ResultSet
holdability constant; one of
- * ResultSet.HOLD_CURSORS_OVER_COMMIT
or
- * ResultSet.CLOSE_CURSORS_AT_COMMIT
- * @throws SQLException if a database access occurs, the given parameter
- * is not a ResultSet
constant indicating holdability,
- * or the given holdability is not supported
- * @see #getHoldability
- * @see ResultSet
- * @since 1.4
- */
- public void setHoldability(int holdability) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves the current holdability of ResultSet
objects
- * created using this Connection
object.
- *
- * @return the holdability, one of
- * ResultSet.HOLD_CURSORS_OVER_COMMIT
or
- * ResultSet.CLOSE_CURSORS_AT_COMMIT
- * @throws SQLException if a database access occurs
- * @see #setHoldability
- * @see ResultSet
- * @since 1.4
- */
- public int getHoldability() throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Creates an unnamed savepoint in the current transaction and
- * returns the new Savepoint
object that represents it.
- *
- * @return the new Savepoint
object
- * @exception SQLException if a database access error occurs
- * or this Connection
object is currently in
- * auto-commit mode
- * @see Savepoint
- * @since 1.4
- */
- public Savepoint setSavepoint() throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Creates a savepoint with the given name in the current transaction
- * and returns the new Savepoint
object that represents it.
- *
- * @param name a String
containing the name of the savepoint
- * @return the new Savepoint
object
- * @exception SQLException if a database access error occurs
- * or this Connection
object is currently in
- * auto-commit mode
- * @see Savepoint
- * @since 1.4
- */
- public Savepoint setSavepoint(String name) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Undoes all changes made after the given Savepoint
object
- * was set.
- * This method should be used only when auto-commit has been disabled.
- *
- * @param savepoint the Savepoint
object to roll back to
- * @exception SQLException if a database access error occurs,
- * the Savepoint
object is no longer valid,
- * or this Connection
object is currently in
- * auto-commit mode
- * @see Savepoint
- * @see #rollback
- * @since 1.4
- */
- public void rollback(Savepoint savepoint) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
-
- /**
- * Removes the given Savepoint
object from the current
- * transaction. Any reference to the savepoint after it have been removed
- * will cause an SQLException
to be thrown.
- *
- * @param savepoint the Savepoint
object to be removed
- * @exception SQLException if a database access error occurs or
- * the given Savepoint
object is not a valid
- * savepoint in the current transaction
- * @since 1.4
- */
- public void releaseSavepoint(Savepoint savepoint) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
-
- /**
- * Creates a Statement
object that will generate
- * ResultSet
objects with the given type, concurrency,
- * and holdability.
- * This method is the same as the createStatement
method
- * above, but it allows the default result set
- * type, concurrency, and holdability to be overridden.
- *
- * @param resultSetType one of the following ResultSet
- * constants:
- * ResultSet.TYPE_FORWARD_ONLY
,
- * ResultSet.TYPE_SCROLL_INSENSITIVE
, or
- * ResultSet.TYPE_SCROLL_SENSITIVE
- * @param resultSetConcurrency one of the following ResultSet
- * constants:
- * ResultSet.CONCUR_READ_ONLY
or
- * ResultSet.CONCUR_UPDATABLE
- * @param resultSetHoldability one of the following ResultSet
- * constants:
- * ResultSet.HOLD_CURSORS_OVER_COMMIT
or
- * ResultSet.CLOSE_CURSORS_AT_COMMIT
- * @return a new Statement
object that will generate
- * ResultSet
objects with the given type,
- * concurrency, and holdability
- * @exception SQLException if a database access error occurs
- * or the given parameters are not ResultSet
- * constants indicating type, concurrency, and holdability
- * @see ResultSet
- * @since 1.4
- */
- public Statement createStatement(int resultSetType, int resultSetConcurrency,
- int resultSetHoldability) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
-
- /**
- * Creates a PreparedStatement
object that will generate
- * ResultSet
objects with the given type, concurrency,
- * and holdability.
- * This method is the same as the prepareStatement
method
- * above, but it allows the default result set
- * type, concurrency, and holdability to be overridden.
- *
- * @param sql a String
object that is the SQL statement to
- * be sent to the database; may contain one or more ? IN
- * parameters
- * @param resultSetType one of the following ResultSet
- * constants:
- * ResultSet.TYPE_FORWARD_ONLY
,
- * ResultSet.TYPE_SCROLL_INSENSITIVE
, or
- * ResultSet.TYPE_SCROLL_SENSITIVE
- * @param resultSetConcurrency one of the following ResultSet
- * constants:
- * ResultSet.CONCUR_READ_ONLY
or
- * ResultSet.CONCUR_UPDATABLE
- * @param resultSetHoldability one of the following ResultSet
- * constants:
- * ResultSet.HOLD_CURSORS_OVER_COMMIT
or
- * ResultSet.CLOSE_CURSORS_AT_COMMIT
- * @return a new PreparedStatement
object, containing the
- * pre-compiled SQL statement, that will generate
- * ResultSet
objects with the given type,
- * concurrency, and holdability
- * @exception SQLException if a database access error occurs
- * or the given parameters are not ResultSet
- * constants indicating type, concurrency, and holdability
- * @see ResultSet
- * @since 1.4
- */
- public PreparedStatement prepareStatement(String sql, int resultSetType,
- int resultSetConcurrency, int resultSetHoldability)
- throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
-
- /**
- * Creates a CallableStatement
object that will generate
- * ResultSet
objects with the given type and concurrency.
- * This method is the same as the prepareCall
method
- * above, but it allows the default result set
- * type, result set concurrency type and holdability to be overridden.
- *
- * @param sql a String
object that is the SQL statement to
- * be sent to the database; may contain on or more ? parameters
- * @param resultSetType one of the following ResultSet
- * constants:
- * ResultSet.TYPE_FORWARD_ONLY
,
- * ResultSet.TYPE_SCROLL_INSENSITIVE
, or
- * ResultSet.TYPE_SCROLL_SENSITIVE
- * @param resultSetConcurrency one of the following ResultSet
- * constants:
- * ResultSet.CONCUR_READ_ONLY
or
- * ResultSet.CONCUR_UPDATABLE
- * @param resultSetHoldability one of the following ResultSet
- * constants:
- * ResultSet.HOLD_CURSORS_OVER_COMMIT
or
- * ResultSet.CLOSE_CURSORS_AT_COMMIT
- * @return a new CallableStatement
object, containing the
- * pre-compiled SQL statement, that will generate
- * ResultSet
objects with the given type,
- * concurrency, and holdability
- * @exception SQLException if a database access error occurs
- * or the given parameters are not ResultSet
- * constants indicating type, concurrency, and holdability
- * @see ResultSet
- * @since 1.4
- */
- public CallableStatement prepareCall(String sql, int resultSetType,
- int resultSetConcurrency,
- int resultSetHoldability) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
-
-
- /**
- * Creates a default PreparedStatement
object that has
- * the capability to retrieve auto-generated keys. The given constant
- * tells the driver whether it should make auto-generated keys
- * available for retrieval. This parameter is ignored if the SQL
- * statement is not an INSERT
statement.
- * Note: This method is optimized for handling
- * parametric SQL statements that benefit from precompilation. If
- * the driver supports precompilation,
- * the method prepareStatement
will send
- * the statement to the database for precompilation. Some drivers
- * may not support precompilation. In this case, the statement may
- * not be sent to the database until the PreparedStatement
- * object is executed. This has no direct effect on users; however, it does
- * affect which methods throw certain SQLExceptions.
- * Result sets created using the returned PreparedStatement
- * object will by default be type TYPE_FORWARD_ONLY
- * and have a concurrency level of CONCUR_READ_ONLY
.
- *
- * @param sql an SQL statement that may contain one or more '?' IN
- * parameter placeholders
- * @param autoGeneratedKeys a flag indicating whether auto-generated keys
- * should be returned; one of the following Statement
- * constants:
- * @param autoGeneratedKeys a flag indicating that auto-generated keys should be returned, one of
- * Statement.RETURN_GENERATED_KEYS
or
- * Statement.NO_GENERATED_KEYS
.
- * @return a new PreparedStatement
object, containing the
- * pre-compiled SQL statement, that will have the capability of
- * returning auto-generated keys
- * @exception SQLException if a database access error occurs
- * or the given parameter is not a Statement
- * constant indicating whether auto-generated keys should be
- * returned
- * @since 1.4
- */
- public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys)
- throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
-
- /**
- * Creates a default PreparedStatement
object capable
- * of returning the auto-generated keys designated by the given array.
- * This array contains the indexes of the columns in the target
- * table that contain the auto-generated keys that should be made
- * available. This array is ignored if the SQL
- * statement is not an INSERT
statement.
- * An SQL statement with or without IN parameters can be
- * pre-compiled and stored in a PreparedStatement
object. This
- * object can then be used to efficiently execute this statement
- * multiple times.
- * Note: This method is optimized for handling
- * parametric SQL statements that benefit from precompilation. If
- * the driver supports precompilation,
- * the method prepareStatement
will send
- * the statement to the database for precompilation. Some drivers
- * may not support precompilation. In this case, the statement may
- * not be sent to the database until the PreparedStatement
- * object is executed. This has no direct effect on users; however, it does
- * affect which methods throw certain SQLExceptions.
- * Result sets created using the returned PreparedStatement
- * object will by default be type TYPE_FORWARD_ONLY
- * and have a concurrency level of CONCUR_READ_ONLY
.
- *
- * @param sql an SQL statement that may contain one or more '?' IN
- * parameter placeholders
- * @param columnIndexes an array of column indexes indicating the columns
- * that should be returned from the inserted row or rows
- * @return a new PreparedStatement
object, containing the
- * pre-compiled statement, that is capable of returning the
- * auto-generated keys designated by the given array of column
- * indexes
- * @exception SQLException if a database access error occurs
- *
- * @since 1.4
- */
- public PreparedStatement prepareStatement(String sql, int columnIndexes[])
- throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
-
- /**
- * Creates a default PreparedStatement
object capable
- * of returning the auto-generated keys designated by the given array.
- * This array contains the names of the columns in the target
- * table that contain the auto-generated keys that should be returned.
- * This array is ignored if the SQL
- * statement is not an INSERT
statement.
- * An SQL statement with or without IN parameters can be
- * pre-compiled and stored in a PreparedStatement
object. This
- * object can then be used to efficiently execute this statement
- * multiple times.
- * Note: This method is optimized for handling
- * parametric SQL statements that benefit from precompilation. If
- * the driver supports precompilation,
- * the method prepareStatement
will send
- * the statement to the database for precompilation. Some drivers
- * may not support precompilation. In this case, the statement may
- * not be sent to the database until the PreparedStatement
- * object is executed. This has no direct effect on users; however, it does
- * affect which methods throw certain SQLExceptions.
- * Result sets created using the returned PreparedStatement
- * object will by default be type TYPE_FORWARD_ONLY
- * and have a concurrency level of CONCUR_READ_ONLY
.
- *
- * @param sql an SQL statement that may contain one or more '?' IN
- * parameter placeholders
- * @param columnNames an array of column names indicating the columns
- * that should be returned from the inserted row or rows
- * @return a new PreparedStatement
object, containing the
- * pre-compiled statement, that is capable of returning the
- * auto-generated keys designated by the given array of column
- * names
- * @exception SQLException if a database access error occurs
- *
- * @since 1.4
- */
- public PreparedStatement prepareStatement(String sql, String columnNames[])
- throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /*
- * 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)
- {
- int sqlType = Types.OTHER; // default value
- for (int i = 0;i < jdbc3Types.length;i++)
- {
- if (pgTypeName.equals(jdbc3Types[i]))
- {
- sqlType = jdbc3Typei[i];
- break;
- }
- }
- return sqlType;
- }
-
- /*
- * 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
- */
- private static final String jdbc3Types[] = {
- "int2",
- "int4", "oid",
- "int8",
- "cash", "money",
- "numeric",
- "float4",
- "float8",
- "bpchar", "char", "char2", "char4", "char8", "char16",
- "varchar", "text", "name", "filename",
- "bytea",
- "bool",
- "bit",
- "date",
- "time",
- "abstime", "timestamp", "timestamptz",
- "_bool", "_char", "_int2", "_int4", "_text",
- "_oid", "_varchar", "_int8", "_float4", "_float8",
- "_abstime", "_date", "_time", "_timestamp", "_numeric",
- "_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
- */
- private static final int jdbc3Typei[] = {
- Types.SMALLINT,
- Types.INTEGER, Types.INTEGER,
- Types.BIGINT,
- Types.DOUBLE, Types.DOUBLE,
- Types.NUMERIC,
- Types.REAL,
- Types.DOUBLE,
- Types.CHAR, Types.CHAR, Types.CHAR, Types.CHAR, Types.CHAR, Types.CHAR,
- Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
- Types.BINARY,
- Types.BIT,
- Types.BIT,
- Types.DATE,
- Types.TIME,
- Types.TIMESTAMP, Types.TIMESTAMP, Types.TIMESTAMP,
- Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY,
- Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY,
- Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY,
- Types.ARRAY
- };
-
-}
-
-
+++ /dev/null
-package org.postgresql.jdbc3;
-
-
-import java.sql.*;
-
-public abstract class AbstractJdbc3DatabaseMetaData extends org.postgresql.jdbc2.AbstractJdbc2DatabaseMetaData
-{
-
- public AbstractJdbc3DatabaseMetaData(AbstractJdbc3Connection conn)
- {
- super(conn);
- }
-
-
- /**
- * Retrieves whether this database supports savepoints.
- *
- * @return true
if savepoints are supported;
- * false
otherwise
- * @exception SQLException if a database access error occurs
- * @since 1.4
- */
- public boolean supportsSavepoints() throws SQLException
- {
- return false;
- }
-
- /**
- * Retrieves whether this database supports named parameters to callable
- * statements.
- *
- * @return true
if named parameters are supported;
- * false
otherwise
- * @exception SQLException if a database access error occurs
- * @since 1.4
- */
- public boolean supportsNamedParameters() throws SQLException
- {
- return false;
- }
-
- /**
- * Retrieves whether it is possible to have multiple ResultSet
objects
- * returned from a CallableStatement
object
- * simultaneously.
- *
- * @return true
if a CallableStatement
object
- * can return multiple ResultSet
objects
- * simultaneously; false
otherwise
- * @exception SQLException if a datanase access error occurs
- * @since 1.4
- */
- public boolean supportsMultipleOpenResults() throws SQLException
- {
- return false;
- }
-
- /**
- * Retrieves whether auto-generated keys can be retrieved after
- * a statement has been executed.
- *
- * @return true
if auto-generated keys can be retrieved
- * after a statement has executed; false
otherwise
- * @exception SQLException if a database access error occurs
- * @since 1.4
- */
- public boolean supportsGetGeneratedKeys() throws SQLException
- {
- return false;
- }
-
- /**
- * Retrieves a description of the user-defined type (UDT) hierarchies defined in a
- * particular schema in this database. Only the immediate super type/
- * sub type relationship is modeled.
- * Only supertype information for UDTs matching the catalog,
- * schema, and type name is returned. The type name parameter
- * may be a fully-qualified name. When the UDT name supplied is a
- * fully-qualified name, the catalog and schemaPattern parameters are
- * ignored.
- * If a UDT does not have a direct super type, it is not listed here.
- * A row of the ResultSet
object returned by this method
- * describes the designated UDT and a direct supertype. A row has the following
- * columns:
- *
TYPE_CAT String => the UDT's catalog (may be null
)
- *
TYPE_SCHEM String => UDT's schema (may be null
)
- *
TYPE_NAME String => type name of the UDT
- *
SUPERTYPE_CAT String => the direct super type's catalog
- * (may be null
)
- *
SUPERTYPE_SCHEM String => the direct super type's schema
- * (may be null
)
- *
SUPERTYPE_NAME String => the direct super type's name
- *
- *
- *
Note: If the driver does not support type hierarchies, an
- * empty result set is returned.
- *
- * @param catalog a catalog name; "" retrieves those without a catalog;
- * null
means drop catalog name from the selection criteria
- * @param schemaPattern a schema name pattern; "" retrieves those
- * without a schema
- * @param typeNamePattern a UDT name pattern; may be a fully-qualified
- * name
- * @return a ResultSet
object in which a row gives information
- * about the designated UDT
- * @throws SQLException if a database access error occurs
- * @since 1.4
- */
- public ResultSet getSuperTypes(String catalog, String schemaPattern,
- String typeNamePattern) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves a description of the table hierarchies defined in a particular
- * schema in this database.
- *
- *
Only supertable information for tables matching the catalog, schema
- * and table name are returned. The table name parameter may be a fully-
- * qualified name, in which case, the catalog and schemaPattern parameters
- * are ignored. If a table does not have a super table, it is not listed here.
- * Supertables have to be defined in the same catalog and schema as the
- * sub tables. Therefore, the type description does not need to include
- * this information for the supertable.
- *
- *
Each type description has the following columns:
- *
TABLE_CAT String => the type's catalog (may be null
)
- *
TABLE_SCHEM String => type's schema (may be null
)
- *
TABLE_NAME String => type name
- *
SUPERTABLE_NAME String => the direct super type's name
- *
- *
- *
Note: If the driver does not support type hierarchies, an
- * empty result set is returned.
- *
- * @param catalog a catalog name; "" retrieves those without a catalog;
- * null
means drop catalog name from the selection criteria
- * @param schemaPattern a schema name pattern; "" retrieves those
- * without a schema
- * @param tableNamePattern a table name pattern; may be a fully-qualified
- * name
- * @return a ResultSet
object in which each row is a type description
- * @throws SQLException if a database access error occurs
- * @since 1.4
- */
- public ResultSet getSuperTables(String catalog, String schemaPattern,
- String tableNamePattern) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves a description of the given attribute of the given type
- * for a user-defined type (UDT) that is available in the given schema
- * and catalog.
- * Descriptions are returned only for attributes of UDTs matching the
- * catalog, schema, type, and attribute name criteria. They are ordered by
- * TYPE_SCHEM, TYPE_NAME and ORDINAL_POSITION. This description
- * does not contain inherited attributes.
- * The ResultSet
object that is returned has the following
- * columns:
- *
TYPE_CAT String => type catalog (may be null
)
- *
TYPE_SCHEM String => type schema (may be null
)
- *
TYPE_NAME String => type name
- *
ATTR_NAME String => attribute name
- *
DATA_TYPE short => attribute type SQL type from java.sql.Types
- *
ATTR_TYPE_NAME String => Data source dependent type name.
- * For a UDT, the type name is fully qualified. For a REF, the type name is
- * fully qualified and represents the target type of the reference type.
- *
ATTR_SIZE int => column size. For char or date
- * types this is the maximum number of characters; for numeric or
- * decimal types this is precision.
- *
DECIMAL_DIGITS int => the number of fractional digits
- *
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
- *
- *
REMARKS String => comment describing column (may be null
)
- *
ATTR_DEF String => default value (may be null
)
- *
SQL_DATA_TYPE int => unused
- *
SQL_DATETIME_SUB int => unused
- *
CHAR_OCTET_LENGTH int => for char types the
- * maximum number of bytes in the column
- *
ORDINAL_POSITION int => index of column in table
- * (starting at 1)
- *
IS_NULLABLE String => "NO" means column definitely
- * does not allow NULL values; "YES" means the column might
- * allow NULL values. An empty string means unknown.
- *
SCOPE_CATALOG String => catalog of table that is the
- * scope of a reference attribute (null
if DATA_TYPE isn't REF)
- *
SCOPE_SCHEMA String => schema of table that is the
- * scope of a reference attribute (null
if DATA_TYPE isn't REF)
- *
SCOPE_TABLE String => table name that is the scope of a
- * reference attribute (null
if the DATA_TYPE isn't REF)
- *
SOURCE_DATA_TYPE short => source type of a distinct type or user-generated
- * Ref type,SQL type from java.sql.Types (null
if DATA_TYPE
- * isn't DISTINCT or user-generated REF)
- *
- * @param catalog a catalog name; must match the catalog name as it
- * is stored in the database; "" retrieves those without a catalog;
- * null
means that the catalog name should not be used to narrow
- * the search
- * @param schemaPattern a schema name pattern; must match the schema name
- * as it is stored in the database; "" retrieves those without a schema;
- * null
means that the schema name should not be used to narrow
- * the search
- * @param typeNamePattern a type name pattern; must match the
- * type name as it is stored in the database
- * @param attributeNamePattern an attribute name pattern; must match the attribute
- * name as it is declared in the database
- * @return a ResultSet
object in which each row is an
- * attribute description
- * @exception SQLException if a database access error occurs
- * @since 1.4
- */
- public ResultSet getAttributes(String catalog, String schemaPattern,
- String typeNamePattern, String attributeNamePattern)
- throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves whether this database supports the given result set holdability.
- *
- * @param holdability one of the following constants:
- * ResultSet.HOLD_CURSORS_OVER_COMMIT
or
- * ResultSet.CLOSE_CURSORS_AT_COMMIT
- * @return true
if so; false
otherwise
- * @exception SQLException if a database access error occurs
- * @see Connection
- * @since 1.4
- */
- public boolean supportsResultSetHoldability(int holdability) throws SQLException
- {
- return true;
- }
-
- /**
- * Retrieves the default holdability of this ResultSet
- * object.
- *
- * @return the default holdability; either
- * ResultSet.HOLD_CURSORS_OVER_COMMIT
or
- * ResultSet.CLOSE_CURSORS_AT_COMMIT
- * @exception SQLException if a database access error occurs
- * @since 1.4
- */
- public int getResultSetHoldability() throws SQLException
- {
- return ResultSet.HOLD_CURSORS_OVER_COMMIT;
- }
-
- /**
- * Retrieves the major version number of the underlying database.
- *
- * @return the underlying database's major version
- * @exception SQLException if a database access error occurs
- * @since 1.4
- */
- public int getDatabaseMajorVersion() throws SQLException
- {
- return connection.getServerMajorVersion();
- }
-
- /**
- * Retrieves the minor version number of the underlying database.
- *
- * @return underlying database's minor version
- * @exception SQLException if a database access error occurs
- * @since 1.4
- */
- public int getDatabaseMinorVersion() throws SQLException
- {
- return connection.getServerMinorVersion();
- }
-
- /**
- * Retrieves the major JDBC version number for this
- * driver.
- *
- * @return JDBC version major number
- * @exception SQLException if a database access error occurs
- * @since 1.4
- */
- public int getJDBCMajorVersion() throws SQLException
- {
- return 3; // This class implements JDBC 3.0
- }
-
- /**
- * Retrieves the minor JDBC version number for this
- * driver.
- *
- * @return JDBC version minor number
- * @exception SQLException if a database access error occurs
- * @since 1.4
- */
- public int getJDBCMinorVersion() throws SQLException
- {
- return 0; // This class implements JDBC 3.0
- }
-
- /**
- * Indicates whether the SQLSTATEs returned by SQLException.getSQLState
- * is X/Open (now known as Open Group) SQL CLI or SQL99.
- * @return the type of SQLSTATEs, one of:
- * sqlStateXOpen or
- * sqlStateSQL99
- * @throws SQLException if a database access error occurs
- * @since 1.4
- */
- public int getSQLStateType() throws SQLException
- {
- return DatabaseMetaData.sqlStateSQL99;
- }
-
- /**
- * Indicates whether updates made to a LOB are made on a copy or directly
- * to the LOB.
- * @return true
if updates are made to a copy of the LOB;
- * false
if updates are made directly to the LOB
- * @throws SQLException if a database access error occurs
- * @since 1.4
- */
- public boolean locatorsUpdateCopy() throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves weather this database supports statement pooling.
- *
- * @return true
is so;
- false
otherwise
- * @throws SQLExcpetion if a database access error occurs
- * @since 1.4
- */
- public boolean supportsStatementPooling() throws SQLException
- {
- return false;
- }
-
-}
+++ /dev/null
-package org.postgresql.jdbc3;
-
-
-import java.sql.*;
-import java.util.Vector;
-import org.postgresql.core.BaseStatement;
-import org.postgresql.core.Field;
-
-
-/* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/jdbc3/AbstractJdbc3ResultSet.java,v 1.5 2003/11/29 19:52:11 pgsql Exp $
- * This class defines methods of the jdbc3 specification. This class extends
- * org.postgresql.jdbc2.AbstractJdbc2ResultSet which provides the jdbc2
- * methods. The real Statement class (for jdbc3) is org.postgresql.jdbc3.Jdbc3ResultSet
- */
-public abstract class AbstractJdbc3ResultSet extends org.postgresql.jdbc2.AbstractJdbc2ResultSet
-{
-
- public AbstractJdbc3ResultSet(BaseStatement statement, Field[] fields, Vector tuples, String status, int updateCount, long insertOID, boolean binaryCursor)
- {
- super (statement, fields, tuples, status, updateCount, insertOID, binaryCursor);
- }
-
- /**
- * Retrieves the value of the designated column in the current row
- * of this ResultSet
object as a java.net.URL
- * object in the Java programming language.
- *
- * @param columnIndex the index of the column 1 is the first, 2 is the second,...
- * @return the column value as a java.net.URL
object;
- * if the value is SQL NULL
,
- * the value returned is null
in the Java programming language
- * @exception SQLException if a database access error occurs,
- * or if a URL is malformed
- * @since 1.4
- */
- public java.net.URL getURL(int columnIndex) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves the value of the designated column in the current row
- * of this ResultSet
object as a java.net.URL
- * object in the Java programming language.
- *
- * @param columnName the SQL name of the column
- * @return the column value as a java.net.URL
object;
- * if the value is SQL NULL
,
- * the value returned is null
in the Java programming language
- * @exception SQLException if a database access error occurs
- * or if a URL is malformed
- * @since 1.4
- */
- public java.net.URL getURL(String columnName) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Updates the designated column with a java.sql.Ref
value.
- * The updater methods are used to update column values in the
- * current row or the insert row. The updater methods do not
- * update the underlying database; instead the updateRow
or
- * insertRow
methods are called to update the database.
- *
- * @param columnIndex the first column is 1, the second is 2, ...
- * @param x the new column value
- * @exception SQLException if a database access error occurs
- * @since 1.4
- */
- public void updateRef(int columnIndex, java.sql.Ref x) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Updates the designated column with a java.sql.Ref
value.
- * The updater methods are used to update column values in the
- * current row or the insert row. The updater methods do not
- * update the underlying database; instead the updateRow
or
- * insertRow
methods are called to update the database.
- *
- * @param columnName the name of the column
- * @param x the new column value
- * @exception SQLException if a database access error occurs
- * @since 1.4
- */
- public void updateRef(String columnName, java.sql.Ref x) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Updates the designated column with a java.sql.Blob
value.
- * The updater methods are used to update column values in the
- * current row or the insert row. The updater methods do not
- * update the underlying database; instead the updateRow
or
- * insertRow
methods are called to update the database.
- *
- * @param columnIndex the first column is 1, the second is 2, ...
- * @param x the new column value
- * @exception SQLException if a database access error occurs
- * @since 1.4
- */
- public void updateBlob(int columnIndex, java.sql.Blob x) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Updates the designated column with a java.sql.Blob
value.
- * The updater methods are used to update column values in the
- * current row or the insert row. The updater methods do not
- * update the underlying database; instead the updateRow
or
- * insertRow
methods are called to update the database.
- *
- * @param columnName the name of the column
- * @param x the new column value
- * @exception SQLException if a database access error occurs
- * @since 1.4
- */
- public void updateBlob(String columnName, java.sql.Blob x) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Updates the designated column with a java.sql.Clob
value.
- * The updater methods are used to update column values in the
- * current row or the insert row. The updater methods do not
- * update the underlying database; instead the updateRow
or
- * insertRow
methods are called to update the database.
- *
- * @param columnIndex the first column is 1, the second is 2, ...
- * @param x the new column value
- * @exception SQLException if a database access error occurs
- * @since 1.4
- */
- public void updateClob(int columnIndex, java.sql.Clob x) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Updates the designated column with a java.sql.Clob
value.
- * The updater methods are used to update column values in the
- * current row or the insert row. The updater methods do not
- * update the underlying database; instead the updateRow
or
- * insertRow
methods are called to update the database.
- *
- * @param columnName the name of the column
- * @param x the new column value
- * @exception SQLException if a database access error occurs
- * @since 1.4
- */
- public void updateClob(String columnName, java.sql.Clob x) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Updates the designated column with a java.sql.Array
value.
- * The updater methods are used to update column values in the
- * current row or the insert row. The updater methods do not
- * update the underlying database; instead the updateRow
or
- * insertRow
methods are called to update the database.
- *
- * @param columnIndex the first column is 1, the second is 2, ...
- * @param x the new column value
- * @exception SQLException if a database access error occurs
- * @since 1.4
- */
- public void updateArray(int columnIndex, java.sql.Array x) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Updates the designated column with a java.sql.Array
value.
- * The updater methods are used to update column values in the
- * current row or the insert row. The updater methods do not
- * update the underlying database; instead the updateRow
or
- * insertRow
methods are called to update the database.
- *
- * @param columnName the name of the column
- * @param x the new column value
- * @exception SQLException if a database access error occurs
- * @since 1.4
- */
- public void updateArray(String columnName, java.sql.Array x) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
-}
-
+++ /dev/null
-package org.postgresql.jdbc3;
-
-
-import java.math.BigDecimal;
-import java.sql.*;
-import java.util.Calendar;
-
-/* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/jdbc3/AbstractJdbc3Statement.java,v 1.4 2003/11/29 19:52:11 pgsql Exp $
- * This class defines methods of the jdbc3 specification. This class extends
- * org.postgresql.jdbc2.AbstractJdbc2Statement which provides the jdbc2
- * methods. The real Statement class (for jdbc2) is org.postgresql.jdbc3.Jdbc3Statement
- */
-public abstract class AbstractJdbc3Statement extends org.postgresql.jdbc2.AbstractJdbc2Statement
-{
-
- public AbstractJdbc3Statement (AbstractJdbc3Connection c)
- {
- super(c);
- }
-
- public AbstractJdbc3Statement(AbstractJdbc3Connection connection, String sql) throws SQLException
- {
- super(connection, sql);
- }
-
- /**
- * Moves to this Statement
object's next result, deals with
- * any current ResultSet
object(s) according to the instructions
- * specified by the given flag, and returns
- * true
if the next result is a ResultSet
object.
- *
- *
There are no more results when the following is true:
- * (!getMoreResults() && (getUpdateCount() == -1)
- *
- *
- * @param current one of the following Statement
- * constants indicating what should happen to current
- * ResultSet
objects obtained using the method
- *
getResultSet
- * CLOSE_CURRENT_RESULT
,
- * KEEP_CURRENT_RESULT
, or
- * CLOSE_ALL_RESULTS
- * @return true
if the next result is a ResultSet
- * object; false
if it is an update count or there are no
- * more results
- * @exception SQLException if a database access error occurs
- * @since 1.4
- * @see #execute
- */
- public boolean getMoreResults(int current) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves any auto-generated keys created as a result of executing this
- * Statement
object. If this Statement
object did
- * not generate any keys, an empty ResultSet
- * object is returned.
- *
- * @return a ResultSet
object containing the auto-generated key(s)
- * generated by the execution of this Statement
object
- * @exception SQLException if a database access error occurs
- * @since 1.4
- */
- public ResultSet getGeneratedKeys() throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Executes the given SQL statement and signals the driver with the
- * given flag about whether the
- * auto-generated keys produced by this Statement
object
- * should be made available for retrieval.
- *
- * @param sql must be an SQL INSERT
, UPDATE
or
- * DELETE
statement or an SQL statement that
- * returns nothing
- * @param autoGeneratedKeys a flag indicating whether auto-generated keys
- * should be made available for retrieval;
- * one of the following constants:
- * Statement.RETURN_GENERATED_KEYS
- * Statement.NO_GENERATED_KEYS
- * @return either the row count for INSERT
, UPDATE
- * or DELETE
statements, or 0
for SQL
- * statements that return nothing
- * @exception SQLException if a database access error occurs, the given
- * SQL statement returns a ResultSet
object, or
- * the given constant is not one of those allowed
- * @since 1.4
- */
- public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Executes the given SQL statement and signals the driver that the
- * auto-generated keys indicated in the given array should be made available
- * for retrieval. The driver will ignore the array if the SQL statement
- * is not an INSERT
statement.
- *
- * @param sql an SQL INSERT
, UPDATE
or
- * DELETE
statement or an SQL statement that returns nothing,
- * such as an SQL DDL statement
- * @param columnIndexes an array of column indexes indicating the columns
- * that should be returned from the inserted row
- * @return either the row count for INSERT
, UPDATE
,
- * or DELETE
statements, or 0 for SQL statements
- * that return nothing
- * @exception SQLException if a database access error occurs or the SQL
- * statement returns a ResultSet
object
- * @since 1.4
- */
- public int executeUpdate(String sql, int columnIndexes[]) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Executes the given SQL statement and signals the driver that the
- * auto-generated keys indicated in the given array should be made available
- * for retrieval. The driver will ignore the array if the SQL statement
- * is not an INSERT
statement.
- *
- * @param sql an SQL INSERT
, UPDATE
or
- * DELETE
statement or an SQL statement that returns nothing
- * @param columnNames an array of the names of the columns that should be
- * returned from the inserted row
- * @return either the row count for INSERT
, UPDATE
,
- * or DELETE
statements, or 0 for SQL statements
- * that return nothing
- * @exception SQLException if a database access error occurs
- *
- * @since 1.4
- */
- public int executeUpdate(String sql, String columnNames[]) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Executes the given SQL statement, which may return multiple results,
- * and signals the driver that any
- * auto-generated keys should be made available
- * for retrieval. The driver will ignore this signal if the SQL statement
- * is not an INSERT
statement.
- * In some (uncommon) situations, a single SQL statement may return
- * multiple result sets and/or update counts. Normally you can ignore
- * this unless you are (1) executing a stored procedure that you know may
- * return multiple results or (2) you are dynamically executing an
- * unknown SQL string.
- * The execute
method executes an SQL statement and indicates the
- * form of the first result. You must then use the methods
- * getResultSet
or getUpdateCount
- * to retrieve the result, and getMoreResults
to
- * move to any subsequent result(s).
- *
- * @param sql any SQL statement
- * @param autoGeneratedKeys a constant indicating whether auto-generated
- * keys should be made available for retrieval using the method
- * getGeneratedKeys
; one of the following constants:
- * Statement.RETURN_GENERATED_KEYS
or
- * Statement.NO_GENERATED_KEYS
- * @return true
if the first result is a ResultSet
- * object; false
if it is an update count or there are
- * no results
- * @exception SQLException if a database access error occurs
- * @see #getResultSet
- * @see #getUpdateCount
- * @see #getMoreResults
- * @see #getGeneratedKeys
- *
- * @since 1.4
- */
- public boolean execute(String sql, int autoGeneratedKeys) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Executes the given SQL statement, which may return multiple results,
- * and signals the driver that the
- * auto-generated keys indicated in the given array should be made available
- * for retrieval. This array contains the indexes of the columns in the
- * target table that contain the auto-generated keys that should be made
- * available. The driver will ignore the array if the given SQL statement
- * is not an INSERT
statement.
- * Under some (uncommon) situations, a single SQL statement may return
- * multiple result sets and/or update counts. Normally you can ignore
- * this unless you are (1) executing a stored procedure that you know may
- * return multiple results or (2) you are dynamically executing an
- * unknown SQL string.
- * The execute
method executes an SQL statement and indicates the
- * form of the first result. You must then use the methods
- * getResultSet
or getUpdateCount
- * to retrieve the result, and getMoreResults
to
- * move to any subsequent result(s).
- *
- * @param sql any SQL statement
- * @param columnIndexes an array of the indexes of the columns in the
- * inserted row that should be made available for retrieval by a
- * call to the method getGeneratedKeys
- * @return true
if the first result is a ResultSet
- * object; false
if it is an update count or there
- * are no results
- * @exception SQLException if a database access error occurs
- * @see #getResultSet
- * @see #getUpdateCount
- * @see #getMoreResults
- *
- * @since 1.4
- */
- public boolean execute(String sql, int columnIndexes[]) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Executes the given SQL statement, which may return multiple results,
- * and signals the driver that the
- * auto-generated keys indicated in the given array should be made available
- * for retrieval. This array contains the names of the columns in the
- * target table that contain the auto-generated keys that should be made
- * available. The driver will ignore the array if the given SQL statement
- * is not an INSERT
statement.
- * In some (uncommon) situations, a single SQL statement may return
- * multiple result sets and/or update counts. Normally you can ignore
- * this unless you are (1) executing a stored procedure that you know may
- * return multiple results or (2) you are dynamically executing an
- * unknown SQL string.
- * The execute
method executes an SQL statement and indicates the
- * form of the first result. You must then use the methods
- * getResultSet
or getUpdateCount
- * to retrieve the result, and getMoreResults
to
- * move to any subsequent result(s).
- *
- * @param sql any SQL statement
- * @param columnNames an array of the names of the columns in the inserted
- * row that should be made available for retrieval by a call to the
- * method getGeneratedKeys
- * @return true
if the next result is a ResultSet
- * object; false
if it is an update count or there
- * are no more results
- * @exception SQLException if a database access error occurs
- * @see #getResultSet
- * @see #getUpdateCount
- * @see #getMoreResults
- * @see #getGeneratedKeys
- *
- * @since 1.4
- */
- public boolean execute(String sql, String columnNames[]) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves the result set holdability for ResultSet
objects
- * generated by this Statement
object.
- *
- * @return either ResultSet.HOLD_CURSORS_OVER_COMMIT
or
- * ResultSet.CLOSE_CURSORS_AT_COMMIT
- * @exception SQLException if a database access error occurs
- *
- * @since 1.4
- */
- public int getResultSetHoldability() throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Sets the designated parameter to the given java.net.URL
value.
- * The driver converts this to an SQL DATALINK
value
- * when it sends it to the database.
- *
- * @param parameterIndex the first parameter is 1, the second is 2, ...
- * @param x the java.net.URL
object to be set
- * @exception SQLException if a database access error occurs
- * @since 1.4
- */
- public void setURL(int parameterIndex, java.net.URL x) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves the number, types and properties of this
- * PreparedStatement
object's parameters.
- *
- * @return a ParameterMetaData
object that contains information
- * about the number, types and properties of this
- * PreparedStatement
object's parameters
- * @exception SQLException if a database access error occurs
- * @see ParameterMetaData
- * @since 1.4
- */
- public ParameterMetaData getParameterMetaData() throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Registers the OUT parameter named
- * parameterName
to the JDBC type
- * sqlType
. All OUT parameters must be registered
- * before a stored procedure is executed.
- * The JDBC type specified by sqlType
for an OUT
- * parameter determines the Java type that must be used
- * in the get
method to read the value of that parameter.
- * If the JDBC type expected to be returned to this output parameter
- * is specific to this particular database, sqlType
- * should be java.sql.Types.OTHER
. The method
- * {@link #getObject} retrieves the value.
- * @param parameterName the name of the parameter
- * @param sqlType the JDBC type code defined by java.sql.Types
.
- * If the parameter is of JDBC type NUMERIC
- * or DECIMAL
, the version of
- * registerOutParameter
that accepts a scale value
- * should be used.
- * @exception SQLException if a database access error occurs
- * @since 1.4
- * @see Types
- */
- public void registerOutParameter(String parameterName, int sqlType)
- throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Registers the parameter named
- * parameterName
to be of JDBC type
- * sqlType
. This method must be called
- * before a stored procedure is executed.
- * The JDBC type specified by sqlType
for an OUT
- * parameter determines the Java type that must be used
- * in the get
method to read the value of that parameter.
- * This version of registerOutParameter
should be
- * used when the parameter is of JDBC type NUMERIC
- * or DECIMAL
.
- * @param parameterName the name of the parameter
- * @param sqlType SQL type code defined by java.sql.Types
.
- * @param scale the desired number of digits to the right of the
- * decimal point. It must be greater than or equal to zero.
- * @exception SQLException if a database access error occurs
- * @since 1.4
- * @see Types
- */
- public void registerOutParameter(String parameterName, int sqlType, int scale)
- throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Registers the designated output parameter. This version of
- * the method registerOutParameter
- * should be used for a user-named or REF output parameter. Examples
- * of user-named types include: STRUCT, DISTINCT, JAVA_OBJECT, and
- * named array types.
- *
- * Before executing a stored procedure call, you must explicitly
- * call registerOutParameter
to register the type from
- * java.sql.Types
for each
- * OUT parameter. For a user-named parameter the fully-qualified SQL
- * type name of the parameter should also be given, while a REF
- * parameter requires that the fully-qualified type name of the
- * referenced type be given. A JDBC driver that does not need the
- * type code and type name information may ignore it. To be portable,
- * however, applications should always provide these values for
- * user-named and REF parameters.
- *
- * Although it is intended for user-named and REF parameters,
- * this method may be used to register a parameter of any JDBC type.
- * If the parameter does not have a user-named or REF type, the
- * typeName parameter is ignored.
- *
- *
Note: When reading the value of an out parameter, you
- * must use the getXXX
method whose Java type XXX corresponds to the
- * parameter's registered SQL type.
- *
- * @param parameterName the name of the parameter
- * @param sqlType a value from {@link java.sql.Types}
- * @param typeName the fully-qualified name of an SQL structured type
- * @exception SQLException if a database access error occurs
- * @see Types
- * @since 1.4
- */
- public void registerOutParameter (String parameterName, int sqlType, String typeName)
- throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves the value of the designated JDBC DATALINK
parameter as a
- * java.net.URL
object.
- *
- * @param parameterIndex the first parameter is 1, the second is 2,...
- * @return a java.net.URL
object that represents the
- * JDBC DATALINK
value used as the designated
- * parameter
- * @exception SQLException if a database access error occurs,
- * or if the URL being returned is
- * not a valid URL on the Java platform
- * @see #setURL
- * @since 1.4
- */
- public java.net.URL getURL(int parameterIndex) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Sets the designated parameter to the given java.net.URL
object.
- * The driver converts this to an SQL DATALINK
value when
- * it sends it to the database.
- *
- * @param parameterName the name of the parameter
- * @param val the parameter value
- * @exception SQLException if a database access error occurs,
- * or if a URL is malformed
- * @see #getURL
- * @since 1.4
- */
- public void setURL(String parameterName, java.net.URL val) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Sets the designated parameter to SQL NULL
.
- *
- *
Note: You must specify the parameter's SQL type.
- *
- * @param parameterName the name of the parameter
- * @param sqlType the SQL type code defined in java.sql.Types
- * @exception SQLException if a database access error occurs
- * @since 1.4
- */
- public void setNull(String parameterName, int sqlType) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Sets the designated parameter to the given Java boolean
value.
- * The driver converts this
- * to an SQL BIT
value when it sends it to the database.
- *
- * @param parameterName the name of the parameter
- * @param x the parameter value
- * @exception SQLException if a database access error occurs
- * @see #getBoolean
- * @since 1.4
- */
- public void setBoolean(String parameterName, boolean x) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Sets the designated parameter to the given Java byte
value.
- * The driver converts this
- * to an SQL TINYINT
value when it sends it to the database.
- *
- * @param parameterName the name of the parameter
- * @param x the parameter value
- * @exception SQLException if a database access error occurs
- * @see #getByte
- * @since 1.4
- */
- public void setByte(String parameterName, byte x) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Sets the designated parameter to the given Java short
value.
- * The driver converts this
- * to an SQL SMALLINT
value when it sends it to the database.
- *
- * @param parameterName the name of the parameter
- * @param x the parameter value
- * @exception SQLException if a database access error occurs
- * @see #getShort
- * @since 1.4
- */
- public void setShort(String parameterName, short x) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Sets the designated parameter to the given Java int
value.
- * The driver converts this
- * to an SQL INTEGER
value when it sends it to the database.
- *
- * @param parameterName the name of the parameter
- * @param x the parameter value
- * @exception SQLException if a database access error occurs
- * @see #getInt
- * @since 1.4
- */
- public void setInt(String parameterName, int x) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Sets the designated parameter to the given Java long
value.
- * The driver converts this
- * to an SQL BIGINT
value when it sends it to the database.
- *
- * @param parameterName the name of the parameter
- * @param x the parameter value
- * @exception SQLException if a database access error occurs
- * @see #getLong
- * @since 1.4
- */
- public void setLong(String parameterName, long x) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Sets the designated parameter to the given Java float
value.
- * The driver converts this
- * to an SQL FLOAT
value when it sends it to the database.
- *
- * @param parameterName the name of the parameter
- * @param x the parameter value
- * @exception SQLException if a database access error occurs
- * @see #getFloat
- * @since 1.4
- */
- public void setFloat(String parameterName, float x) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Sets the designated parameter to the given Java double
value.
- * The driver converts this
- * to an SQL DOUBLE
value when it sends it to the database.
- *
- * @param parameterName the name of the parameter
- * @param x the parameter value
- * @exception SQLException if a database access error occurs
- * @see #getDouble
- * @since 1.4
- */
- public void setDouble(String parameterName, double x) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Sets the designated parameter to the given
- * java.math.BigDecimal
value.
- * The driver converts this to an SQL NUMERIC
value when
- * it sends it to the database.
- *
- * @param parameterName the name of the parameter
- * @param x the parameter value
- * @exception SQLException if a database access error occurs
- * @see #getBigDecimal
- * @since 1.4
- */
- public void setBigDecimal(String parameterName, BigDecimal x) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Sets the designated parameter to the given Java String
value.
- * The driver converts this
- * to an SQL VARCHAR
or LONGVARCHAR
value
- * (depending on the argument's
- * size relative to the driver's limits on VARCHAR
values)
- * when it sends it to the database.
- *
- * @param parameterName the name of the parameter
- * @param x the parameter value
- * @exception SQLException if a database access error occurs
- * @see #getString
- * @since 1.4
- */
- public void setString(String parameterName, String x) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Sets the designated parameter to the given Java array of bytes.
- * The driver converts this to an SQL VARBINARY
or
- * LONGVARBINARY
(depending on the argument's size relative
- * to the driver's limits on VARBINARY
values) when it sends
- * it to the database.
- *
- * @param parameterName the name of the parameter
- * @param x the parameter value
- * @exception SQLException if a database access error occurs
- * @see #getBytes
- * @since 1.4
- */
- public void setBytes(String parameterName, byte x[]) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Sets the designated parameter to the given java.sql.Date
value.
- * The driver converts this
- * to an SQL DATE
value when it sends it to the database.
- *
- * @param parameterName the name of the parameter
- * @param x the parameter value
- * @exception SQLException if a database access error occurs
- * @see #getDate
- * @since 1.4
- */
- public void setDate(String parameterName, java.sql.Date x)
- throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Sets the designated parameter to the given java.sql.Time
value.
- * The driver converts this
- * to an SQL TIME
value when it sends it to the database.
- *
- * @param parameterName the name of the parameter
- * @param x the parameter value
- * @exception SQLException if a database access error occurs
- * @see #getTime
- * @since 1.4
- */
- public void setTime(String parameterName, java.sql.Time x)
- throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Sets the designated parameter to the given java.sql.Timestamp
value.
- * The driver
- * converts this to an SQL TIMESTAMP
value when it sends it to the
- * database.
- *
- * @param parameterName the name of the parameter
- * @param x the parameter value
- * @exception SQLException if a database access error occurs
- * @see #getTimestamp
- * @since 1.4
- */
- public void setTimestamp(String parameterName, java.sql.Timestamp x)
- throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Sets the designated parameter to the given input stream, which will have
- * the specified number of bytes.
- * When a very large ASCII value is input to a LONGVARCHAR
- * parameter, it may be more practical to send it via a
- * java.io.InputStream
. Data will be read from the stream
- * as needed until end-of-file is reached. The JDBC driver will
- * do any necessary conversion from ASCII to the database char format.
- *
- *
Note: This stream object can either be a standard
- * Java stream object or your own subclass that implements the
- * standard interface.
- *
- * @param parameterName the name of the parameter
- * @param x the Java input stream that contains the ASCII parameter value
- * @param length the number of bytes in the stream
- * @exception SQLException if a database access error occurs
- * @since 1.4
- */
- public void setAsciiStream(String parameterName, java.io.InputStream x, int length)
- throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Sets the designated parameter to the given input stream, which will have
- * the specified number of bytes.
- * When a very large binary value is input to a LONGVARBINARY
- * parameter, it may be more practical to send it via a
- * java.io.InputStream
object. The data will be read from the stream
- * as needed until end-of-file is reached.
- *
- *
Note: This stream object can either be a standard
- * Java stream object or your own subclass that implements the
- * standard interface.
- *
- * @param parameterName the name of the parameter
- * @param x the java input stream which contains the binary parameter value
- * @param length the number of bytes in the stream
- * @exception SQLException if a database access error occurs
- * @since 1.4
- */
- public void setBinaryStream(String parameterName, java.io.InputStream x,
- int length) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Sets the value of the designated parameter with the given object. The second
- * argument must be an object type; for integral values, the
- * java.lang
equivalent objects should be used.
- *
- *
The given Java object will be converted to the given targetSqlType
- * before being sent to the database.
- *
- * If the object has a custom mapping (is of a class implementing the
- * interface SQLData
),
- * the JDBC driver should call the method SQLData.writeSQL
to write it
- * to the SQL data stream.
- * If, on the other hand, the object is of a class implementing
- * Ref
, Blob
, Clob
, Struct
,
- * or Array
, the driver should pass it to the database as a
- * value of the corresponding SQL type.
- * Note that this method may be used to pass datatabase-
- * specific abstract data types.
- *
- * @param parameterName the name of the parameter
- * @param x the object containing the input parameter value
- * @param targetSqlType the SQL type (as defined in java.sql.Types) to be
- * sent to the database. The scale argument may further qualify this type.
- * @param scale for java.sql.Types.DECIMAL or java.sql.Types.NUMERIC types,
- * this is the number of digits after the decimal point. For all other
- * types, this value will be ignored.
- * @exception SQLException if a database access error occurs
- * @see Types
- * @see #getObject
- * @since 1.4
- */
- public void setObject(String parameterName, Object x, int targetSqlType, int scale)
- throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Sets the value of the designated parameter with the given object.
- * This method is like the method setObject
- * above, except that it assumes a scale of zero.
- *
- * @param parameterName the name of the parameter
- * @param x the object containing the input parameter value
- * @param targetSqlType the SQL type (as defined in java.sql.Types) to be
- * sent to the database
- * @exception SQLException if a database access error occurs
- * @see #getObject
- * @since 1.4
- */
- public void setObject(String parameterName, Object x, int targetSqlType)
- throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Sets the value of the designated parameter with the given object.
- * The second parameter must be of type Object
; therefore, the
- * java.lang
equivalent objects should be used for built-in types.
- *
- *
The JDBC specification specifies a standard mapping from
- * Java Object
types to SQL types. The given argument
- * will be converted to the corresponding SQL type before being
- * sent to the database.
- *
- *
Note that this method may be used to pass datatabase-
- * specific abstract data types, by using a driver-specific Java
- * type.
- *
- * If the object is of a class implementing the interface SQLData
,
- * the JDBC driver should call the method SQLData.writeSQL
- * to write it to the SQL data stream.
- * If, on the other hand, the object is of a class implementing
- * Ref
, Blob
, Clob
, Struct
,
- * or Array
, the driver should pass it to the database as a
- * value of the corresponding SQL type.
- * This method throws an exception if there is an ambiguity, for example, if the
- * object is of a class implementing more than one of the interfaces named above.
- *
- * @param parameterName the name of the parameter
- * @param x the object containing the input parameter value
- * @exception SQLException if a database access error occurs or if the given
- * Object
parameter is ambiguous
- * @see #getObject
- * @since 1.4
- */
- public void setObject(String parameterName, Object x) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
-
- /**
- * Sets the designated parameter to the given Reader
- * object, which is the given number of characters long.
- * When a very large UNICODE value is input to a LONGVARCHAR
- * parameter, it may be more practical to send it via a
- * java.io.Reader
object. The data will be read from the stream
- * as needed until end-of-file is reached. The JDBC driver will
- * do any necessary conversion from UNICODE to the database char format.
- *
- *
Note: This stream object can either be a standard
- * Java stream object or your own subclass that implements the
- * standard interface.
- *
- * @param parameterName the name of the parameter
- * @param reader the java.io.Reader
object that
- * contains the UNICODE data used as the designated parameter
- * @param length the number of characters in the stream
- * @exception SQLException if a database access error occurs
- * @since 1.4
- */
- public void setCharacterStream(String parameterName,
- java.io.Reader reader,
- int length) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Sets the designated parameter to the given java.sql.Date
value,
- * using the given Calendar
object. The driver uses
- * the Calendar
object to construct an SQL DATE
value,
- * which the driver then sends to the database. With a
- * a Calendar
object, the driver can calculate the date
- * taking into account a custom timezone. If no
- * Calendar
object is specified, the driver uses the default
- * timezone, which is that of the virtual machine running the application.
- *
- * @param parameterName the name of the parameter
- * @param x the parameter value
- * @param cal the Calendar
object the driver will use
- * to construct the date
- * @exception SQLException if a database access error occurs
- * @see #getDate
- * @since 1.4
- */
- public void setDate(String parameterName, java.sql.Date x, Calendar cal)
- throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Sets the designated parameter to the given java.sql.Time
value,
- * using the given Calendar
object. The driver uses
- * the Calendar
object to construct an SQL TIME
value,
- * which the driver then sends to the database. With a
- * a Calendar
object, the driver can calculate the time
- * taking into account a custom timezone. If no
- * Calendar
object is specified, the driver uses the default
- * timezone, which is that of the virtual machine running the application.
- *
- * @param parameterName the name of the parameter
- * @param x the parameter value
- * @param cal the Calendar
object the driver will use
- * to construct the time
- * @exception SQLException if a database access error occurs
- * @see #getTime
- * @since 1.4
- */
- public void setTime(String parameterName, java.sql.Time x, Calendar cal)
- throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Sets the designated parameter to the given java.sql.Timestamp
value,
- * using the given Calendar
object. The driver uses
- * the Calendar
object to construct an SQL TIMESTAMP
value,
- * which the driver then sends to the database. With a
- * a Calendar
object, the driver can calculate the timestamp
- * taking into account a custom timezone. If no
- * Calendar
object is specified, the driver uses the default
- * timezone, which is that of the virtual machine running the application.
- *
- * @param parameterName the name of the parameter
- * @param x the parameter value
- * @param cal the Calendar
object the driver will use
- * to construct the timestamp
- * @exception SQLException if a database access error occurs
- * @see #getTimestamp
- * @since 1.4
- */
- public void setTimestamp(String parameterName, java.sql.Timestamp x, Calendar cal)
- throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Sets the designated parameter to SQL NULL
.
- * This version of the method setNull
should
- * be used for user-defined types and REF type parameters. Examples
- * of user-defined types include: STRUCT, DISTINCT, JAVA_OBJECT, and
- * named array types.
- *
- *
Note: To be portable, applications must give the
- * SQL type code and the fully-qualified SQL type name when specifying
- * a NULL user-defined or REF parameter. In the case of a user-defined type
- * the name is the type name of the parameter itself. For a REF
- * parameter, the name is the type name of the referenced type. If
- * a JDBC driver does not need the type code or type name information,
- * it may ignore it.
- *
- * Although it is intended for user-defined and Ref parameters,
- * this method may be used to set a null parameter of any JDBC type.
- * If the parameter does not have a user-defined or REF type, the given
- * typeName is ignored.
- *
- *
- * @param paramName the name of the parameter
- * @param sqlType a value from java.sql.Types
- * @param typeName the fully-qualified name of an SQL user-defined type;
- * ignored if the parameter is not a user-defined type or
- * SQL REF
value
- * @exception SQLException if a database access error occurs
- * @since 1.4
- */
- public void setNull (String parameterName, int sqlType, String typeName)
- throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves the value of a JDBC CHAR
, VARCHAR
,
- * or LONGVARCHAR
parameter as a String
in
- * the Java programming language.
- * For the fixed-length type JDBC CHAR
,
- * the String
object
- * returned has exactly the same value the JDBC
- * CHAR
value had in the
- * database, including any padding added by the database.
- * @param parameterName the name of the parameter
- * @return the parameter value. If the value is SQL NULL
, the result
- * is null
.
- * @exception SQLException if a database access error occurs
- * @see #setString
- * @since 1.4
- */
- public String getString(String parameterName) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves the value of a JDBC BIT
parameter as a
- * boolean
in the Java programming language.
- * @param parameterName the name of the parameter
- * @return the parameter value. If the value is SQL NULL
, the result
- * is false
.
- * @exception SQLException if a database access error occurs
- * @see #setBoolean
- * @since 1.4
- */
- public boolean getBoolean(String parameterName) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves the value of a JDBC TINYINT
parameter as a byte
- * in the Java programming language.
- * @param parameterName the name of the parameter
- * @return the parameter value. If the value is SQL NULL
, the result
- * is 0
.
- * @exception SQLException if a database access error occurs
- * @see #setByte
- * @since 1.4
- */
- public byte getByte(String parameterName) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves the value of a JDBC SMALLINT
parameter as a short
- * in the Java programming language.
- * @param parameterName the name of the parameter
- * @return the parameter value. If the value is SQL NULL
, the result
- * is 0
.
- * @exception SQLException if a database access error occurs
- * @see #setShort
- * @since 1.4
- */
- public short getShort(String parameterName) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves the value of a JDBC INTEGER
parameter as an int
- * in the Java programming language.
- *
- * @param parameterName the name of the parameter
- * @return the parameter value. If the value is SQL NULL
,
- * the result is 0
.
- * @exception SQLException if a database access error occurs
- * @see #setInt
- * @since 1.4
- */
- public int getInt(String parameterName) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves the value of a JDBC BIGINT
parameter as a long
- * in the Java programming language.
- *
- * @param parameterName the name of the parameter
- * @return the parameter value. If the value is SQL NULL
,
- * the result is 0
.
- * @exception SQLException if a database access error occurs
- * @see #setLong
- * @since 1.4
- */
- public long getLong(String parameterName) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves the value of a JDBC FLOAT
parameter as a float
- * in the Java programming language.
- * @param parameterName the name of the parameter
- * @return the parameter value. If the value is SQL NULL
,
- * the result is 0
.
- * @exception SQLException if a database access error occurs
- * @see #setFloat
- * @since 1.4
- */
- public float getFloat(String parameterName) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves the value of a JDBC DOUBLE
parameter as a double
- * in the Java programming language.
- * @param parameterName the name of the parameter
- * @return the parameter value. If the value is SQL NULL
,
- * the result is 0
.
- * @exception SQLException if a database access error occurs
- * @see #setDouble
- * @since 1.4
- */
- public double getDouble(String parameterName) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves the value of a JDBC BINARY
or VARBINARY
- * parameter as an array of byte
values in the Java
- * programming language.
- * @param parameterName the name of the parameter
- * @return the parameter value. If the value is SQL NULL
, the result is
- * null
.
- * @exception SQLException if a database access error occurs
- * @see #setBytes
- * @since 1.4
- */
- public byte[] getBytes(String parameterName) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves the value of a JDBC DATE
parameter as a
- * java.sql.Date
object.
- * @param parameterName the name of the parameter
- * @return the parameter value. If the value is SQL NULL
, the result
- * is null
.
- * @exception SQLException if a database access error occurs
- * @see #setDate
- * @since 1.4
- */
- public java.sql.Date getDate(String parameterName) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves the value of a JDBC TIME
parameter as a
- * java.sql.Time
object.
- * @param parameterName the name of the parameter
- * @return the parameter value. If the value is SQL NULL
, the result
- * is null
.
- * @exception SQLException if a database access error occurs
- * @see #setTime
- * @since 1.4
- */
- public java.sql.Time getTime(String parameterName) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves the value of a JDBC TIMESTAMP
parameter as a
- * java.sql.Timestamp
object.
- * @param parameterName the name of the parameter
- * @return the parameter value. If the value is SQL NULL
, the result
- * is null
.
- * @exception SQLException if a database access error occurs
- * @see #setTimestamp
- * @since 1.4
- */
- public java.sql.Timestamp getTimestamp(String parameterName) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves the value of a parameter as an Object
in the Java
- * programming language. If the value is an SQL NULL
, the
- * driver returns a Java null
.
- * This method returns a Java object whose type corresponds to the JDBC
- * type that was registered for this parameter using the method
- * registerOutParameter
. By registering the target JDBC
- * type as java.sql.Types.OTHER
, this method can be used
- * to read database-specific abstract data types.
- * @param parameterName the name of the parameter
- * @return A java.lang.Object
holding the OUT parameter value.
- * @exception SQLException if a database access error occurs
- * @see Types
- * @see #setObject
- * @since 1.4
- */
- public Object getObject(String parameterName) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves the value of a JDBC NUMERIC
parameter as a
- * java.math.BigDecimal
object with as many digits to the
- * right of the decimal point as the value contains.
- * @param parameterName the name of the parameter
- * @return the parameter value in full precision. If the value is
- * SQL NULL
, the result is null
.
- * @exception SQLException if a database access error occurs
- * @see #setBigDecimal
- * @since 1.4
- */
- public BigDecimal getBigDecimal(String parameterName) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Returns an object representing the value of OUT parameter
- * i
and uses map
for the custom
- * mapping of the parameter value.
- * This method returns a Java object whose type corresponds to the
- * JDBC type that was registered for this parameter using the method
- * registerOutParameter
. By registering the target
- * JDBC type as java.sql.Types.OTHER
, this method can
- * be used to read database-specific abstract data types.
- * @param parameterName the name of the parameter
- * @param map the mapping from SQL type names to Java classes
- * @return a java.lang.Object
holding the OUT parameter value
- * @exception SQLException if a database access error occurs
- * @see #setObject
- * @since 1.4
- */
- public Object getObject (String parameterName, java.util.Map map) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves the value of a JDBC REF(<structured-type>)
- * parameter as a {@link Ref} object in the Java programming language.
- *
- * @param parameterName the name of the parameter
- * @return the parameter value as a Ref
object in the
- * Java programming language. If the value was SQL NULL
,
- * the value null
is returned.
- * @exception SQLException if a database access error occurs
- * @since 1.4
- */
- public Ref getRef (String parameterName) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves the value of a JDBC BLOB
parameter as a
- * {@link Blob} object in the Java programming language.
- *
- * @param parameterName the name of the parameter
- * @return the parameter value as a Blob
object in the
- * Java programming language. If the value was SQL NULL
,
- * the value null
is returned.
- * @exception SQLException if a database access error occurs
- * @since 1.4
- */
- public Blob getBlob (String parameterName) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves the value of a JDBC CLOB
parameter as a
- * Clob
object in the Java programming language.
- * @param parameterName the name of the parameter
- * @return the parameter value as a Clob
object in the
- * Java programming language. If the value was SQL NULL
,
- * the value null
is returned.
- * @exception SQLException if a database access error occurs
- * @since 1.4
- */
- public Clob getClob (String parameterName) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves the value of a JDBC ARRAY
parameter as an
- * {@link Array} object in the Java programming language.
- *
- * @param parameterName the name of the parameter
- * @return the parameter value as an Array
object in
- * Java programming language. If the value was SQL NULL
,
- * the value null
is returned.
- * @exception SQLException if a database access error occurs
- * @since 1.4
- */
- public Array getArray (String parameterName) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves the value of a JDBC DATE
parameter as a
- * java.sql.Date
object, using
- * the given Calendar
object
- * to construct the date.
- * With a Calendar
object, the driver
- * can calculate the date taking into account a custom timezone and locale.
- * If no Calendar
object is specified, the driver uses the
- * default timezone and locale.
- *
- * @param parameterName the name of the parameter
- * @param cal the Calendar
object the driver will use
- * to construct the date
- * @return the parameter value. If the value is SQL NULL
,
- * the result is null
.
- * @exception SQLException if a database access error occurs
- * @see #setDate
- * @since 1.4
- */
- public java.sql.Date getDate(String parameterName, Calendar cal)
- throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves the value of a JDBC TIME
parameter as a
- * java.sql.Time
object, using
- * the given Calendar
object
- * to construct the time.
- * With a Calendar
object, the driver
- * can calculate the time taking into account a custom timezone and locale.
- * If no Calendar
object is specified, the driver uses the
- * default timezone and locale.
- *
- * @param parameterName the name of the parameter
- * @param cal the Calendar
object the driver will use
- * to construct the time
- * @return the parameter value; if the value is SQL NULL
, the result is
- * null
.
- * @exception SQLException if a database access error occurs
- * @see #setTime
- * @since 1.4
- */
- public java.sql.Time getTime(String parameterName, Calendar cal)
- throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves the value of a JDBC TIMESTAMP
parameter as a
- * java.sql.Timestamp
object, using
- * the given Calendar
object to construct
- * the Timestamp
object.
- * With a Calendar
object, the driver
- * can calculate the timestamp taking into account a custom timezone and locale.
- * If no Calendar
object is specified, the driver uses the
- * default timezone and locale.
- *
- *
- * @param parameterName the name of the parameter
- * @param cal the Calendar
object the driver will use
- * to construct the timestamp
- * @return the parameter value. If the value is SQL NULL
, the result is
- * null
.
- * @exception SQLException if a database access error occurs
- * @see #setTimestamp
- * @since 1.4
- */
- public java.sql.Timestamp getTimestamp(String parameterName, Calendar cal)
- throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- /**
- * Retrieves the value of a JDBC DATALINK
parameter as a
- * java.net.URL
object.
- *
- * @param parameterName the name of the parameter
- * @return the parameter value as a java.net.URL
object in the
- * Java programming language. If the value was SQL NULL
, the
- * value null
is returned.
- * @exception SQLException if a database access error occurs,
- * or if there is a problem with the URL
- * @see #setURL
- * @since 1.4
- */
- public java.net.URL getURL(String parameterName) throws SQLException
- {
- throw org.postgresql.Driver.notImplemented();
- }
-
- public void setObject(int parameterIndex, Object x, int targetSqlType, int scale) throws SQLException
- {
- switch (targetSqlType)
- {
- case Types.BOOLEAN:
- super.setObject(parameterIndex, x, Types.BIT, scale);
- default:
- super.setObject(parameterIndex, x, targetSqlType, scale);
- }
- }
-
-}
+++ /dev/null
-package org.postgresql.jdbc3;
-
-
-import java.sql.*;
-
-public class Jdbc3Blob extends org.postgresql.jdbc3.AbstractJdbc3Blob implements java.sql.Blob
-{
-
- public Jdbc3Blob(org.postgresql.PGConnection conn, int oid) throws SQLException
- {
- super(conn, oid);
- }
-
-}
+++ /dev/null
-package org.postgresql.jdbc3;
-
-
-import java.sql.*;
-import java.util.Vector;
-import org.postgresql.PGRefCursorResultSet;
-import org.postgresql.core.BaseResultSet;
-import org.postgresql.core.Field;
-
-public class Jdbc3CallableStatement extends org.postgresql.jdbc3.AbstractJdbc3Statement implements java.sql.CallableStatement
-{
-
- public Jdbc3CallableStatement(Jdbc3Connection connection, String sql) throws SQLException
- {
- super(connection, sql);
- }
-
- public BaseResultSet createResultSet (Field[] fields, Vector tuples, String status, int updateCount, long insertOID, boolean binaryCursor) throws SQLException
- {
- return new Jdbc3ResultSet(this, fields, tuples, status, updateCount, insertOID, binaryCursor);
- }
-
- public PGRefCursorResultSet createRefCursorResultSet (String cursorName) throws SQLException
- {
- return new Jdbc3RefCursorResultSet(this, cursorName);
- }
-}
-
+++ /dev/null
-package org.postgresql.jdbc3;
-
-
-public class Jdbc3Clob extends org.postgresql.jdbc3.AbstractJdbc3Clob implements java.sql.Clob
-{
-
- public Jdbc3Clob(org.postgresql.PGConnection conn, int oid) throws java.sql.SQLException
- {
- super(conn, oid);
- }
-
-}
+++ /dev/null
-package org.postgresql.jdbc3;
-
-
-import java.sql.SQLException;
-
-/* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/jdbc3/Jdbc3Connection.java,v 1.6 2003/11/29 19:52:11 pgsql Exp $
- * This class implements the java.sql.Connection interface for JDBC3.
- * However most of the implementation is really done in
- * org.postgresql.jdbc3.AbstractJdbc3Connection or one of it's parents
- */
-public class Jdbc3Connection extends org.postgresql.jdbc3.AbstractJdbc3Connection implements java.sql.Connection
-{
-
- public java.sql.Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException
- {
- Jdbc3Statement s = new Jdbc3Statement(this);
- s.setResultSetType(resultSetType);
- s.setResultSetConcurrency(resultSetConcurrency);
- return s;
- }
-
-
- public java.sql.PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException
- {
- Jdbc3PreparedStatement s = new Jdbc3PreparedStatement(this, sql);
- s.setResultSetType(resultSetType);
- s.setResultSetConcurrency(resultSetConcurrency);
- return s;
- }
-
- public java.sql.CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException
- {
- Jdbc3CallableStatement s = new Jdbc3CallableStatement(this, sql);
- s.setResultSetType(resultSetType);
- s.setResultSetConcurrency(resultSetConcurrency);
- return s;
- }
-
- public java.sql.DatabaseMetaData getMetaData() throws SQLException
- {
- if (metadata == null)
- metadata = new Jdbc3DatabaseMetaData(this);
- return metadata;
- }
-
-}
+++ /dev/null
-package org.postgresql.jdbc3;
-
-import org.postgresql.jdbc2.optional.ConnectionPool;
-
-import javax.sql.PooledConnection;
-import javax.naming.Reference;
-import java.sql.SQLException;
-
-/**
- * Jdbc3 implementation of ConnectionPoolDataSource. This is
- * typically the interface used by an app server to interact
- * with connection pools provided by a JDBC driver. PostgreSQL
- * does not support XADataSource, the other common connection
- * pooling interface (for connections supporting the two-phase
- * commit protocol).
- *
- * @version $Revision: 1.1 $
- */
-public class Jdbc3ConnectionPool extends ConnectionPool
-{
- /**
- * Gets a description of this DataSource.
- */
- public String getDescription()
- {
- return "Jdbc3ConnectionPool from " + org.postgresql.Driver.getVersion();
- }
-
- /**
- * Gets a connection which may be pooled by the app server or middleware
- * implementation of DataSource.
- *
- * @throws java.sql.SQLException
- * Occurs when the physical database connection cannot be established.
- */
- public PooledConnection getPooledConnection() throws SQLException
- {
- return new Jdbc3PooledConnection(getConnection(), isDefaultAutoCommit());
- }
-
- /**
- * Gets a connection which may be pooled by the app server or middleware
- * implementation of DataSource.
- *
- * @throws java.sql.SQLException
- * Occurs when the physical database connection cannot be established.
- */
- public PooledConnection getPooledConnection(String user, String password) throws SQLException
- {
- return new Jdbc3PooledConnection(getConnection(user, password), isDefaultAutoCommit());
- }
-
- /**
- * Generates a JDBC object factory reference.
- */
- protected Reference createReference()
- {
- return new Reference(getClass().getName(), Jdbc3ObjectFactory.class.getName(), null);
- }
-}
+++ /dev/null
-package org.postgresql.jdbc3;
-
-
-public class Jdbc3DatabaseMetaData extends org.postgresql.jdbc3.AbstractJdbc3DatabaseMetaData implements java.sql.DatabaseMetaData
-{
-
- public Jdbc3DatabaseMetaData(Jdbc3Connection conn)
- {
- super(conn);
- }
-
-}
+++ /dev/null
-package org.postgresql.jdbc3;
-
-import java.util.*;
-import javax.naming.*;
-import org.postgresql.jdbc2.optional.PGObjectFactory;
-
-/**
- * JDBC3 version of the Object Factory used to recreate objects
- * from their JNDI references.
- *
- * @version $Revision: 1.1 $
- */
-public class Jdbc3ObjectFactory extends PGObjectFactory
-{
- /**
- * Dereferences a PostgreSQL DataSource. Other types of references are
- * ignored.
- */
- public Object getObjectInstance(Object obj, Name name, Context nameCtx,
- Hashtable environment) throws Exception
- {
- Reference ref = (Reference) obj;
- if (ref.getClassName().equals(Jdbc3SimpleDataSource.class.getName()))
- {
- return loadSimpleDataSource(ref);
- }
- else if (ref.getClassName().equals(Jdbc3ConnectionPool.class.getName()))
- {
- return loadConnectionPool(ref);
- }
- else if (ref.getClassName().equals(Jdbc3PoolingDataSource.class.getName()))
- {
- return loadPoolingDataSource(ref);
- }
- else
- {
- return null;
- }
- }
-
- private Object loadPoolingDataSource(Reference ref)
- {
- // If DataSource exists, return it
- String name = getProperty(ref, "dataSourceName");
- Jdbc3PoolingDataSource pds = Jdbc3PoolingDataSource.getDataSource(name);
- if (pds != null)
- {
- return pds;
- }
- // Otherwise, create a new one
- pds = new Jdbc3PoolingDataSource();
- pds.setDataSourceName(name);
- loadBaseDataSource(pds, ref);
- String min = getProperty(ref, "initialConnections");
- if (min != null)
- {
- pds.setInitialConnections(Integer.parseInt(min));
- }
- String max = getProperty(ref, "maxConnections");
- if (max != null)
- {
- pds.setMaxConnections(Integer.parseInt(max));
- }
- return pds;
- }
-
- private Object loadSimpleDataSource(Reference ref)
- {
- Jdbc3SimpleDataSource ds = new Jdbc3SimpleDataSource();
- return loadBaseDataSource(ds, ref);
- }
-
- private Object loadConnectionPool(Reference ref)
- {
- Jdbc3ConnectionPool cp = new Jdbc3ConnectionPool();
- return loadBaseDataSource(cp, ref);
- }
-
-}
+++ /dev/null
-package org.postgresql.jdbc3;
-
-import org.postgresql.jdbc2.optional.PooledConnectionImpl;
-
-import java.sql.Connection;
-
-/**
- * JDBC3 implementation of PooledConnection, which manages
- * a connection in a connection pool.
- *
- * @version $Revision: 1.1 $
- */
-public class Jdbc3PooledConnection extends PooledConnectionImpl
-{
- Jdbc3PooledConnection(Connection con, boolean autoCommit)
- {
- super(con, autoCommit);
- }
-}
+++ /dev/null
-package org.postgresql.jdbc3;
-
-import java.util.*;
-import org.postgresql.jdbc2.optional.PoolingDataSource;
-import org.postgresql.jdbc2.optional.ConnectionPool;
-
-import javax.naming.Reference;
-
-/**
- * JDBC 3 implementation of a pooling DataSource. This is best
- * used outside of an application server environment. Application
- * servers generally prefer to deal with instances of
- * ConnectionPoolDataSource (see ConnectionPool) or XADataSource
- * (not available for PostgreSQL).
- *
- * @version $Revision: 1.1 $
- */
-public class Jdbc3PoolingDataSource extends PoolingDataSource
-{
- /**
- * Store JDBC3 DataSources in different bucket than JDBC2 DataSources
- */
- private static Map dataSources = new HashMap();
-
- /**
- * Store JDBC3 DataSources in different bucket than JDBC2 DataSources
- */
- static Jdbc3PoolingDataSource getDataSource(String name)
- {
- return (Jdbc3PoolingDataSource) dataSources.get(name);
- }
-
- /**
- * Store JDBC3 DataSources in different bucket than JDBC2 DataSources
- */
- protected void removeStoredDataSource()
- {
- synchronized (dataSources)
- {
- dataSources.remove(dataSourceName);
- }
- }
-
- /**
- * Store JDBC3 DataSources in different bucket than JDBC2 DataSources
- */
- public void setDataSourceName(String dataSourceName)
- {
- if (isInitialized())
- {
- throw new IllegalStateException("Cannot set Data Source properties after DataSource has been used");
- }
- if (this.dataSourceName != null && dataSourceName != null && dataSourceName.equals(this.dataSourceName))
- {
- return;
- }
- synchronized (dataSources)
- {
- if (getDataSource(dataSourceName) != null)
- {
- throw new IllegalArgumentException("DataSource with name '" + dataSourceName + "' already exists!");
- }
- if (this.dataSourceName != null)
- {
- dataSources.remove(this.dataSourceName);
- }
- this.dataSourceName = dataSourceName;
- dataSources.put(dataSourceName, this);
- }
- }
-
- /**
- * Generates a JDBC3 object factory reference.
- */
- protected Reference createReference()
- {
- return new Reference(getClass().getName(), Jdbc3ObjectFactory.class.getName(), null);
- }
-
- /**
- * Creates a JDBC3 ConnectionPool to use with this DataSource.
- */
- protected ConnectionPool createConnectionPool()
- {
- return new Jdbc3ConnectionPool();
- }
-
- /**
- * Gets a description of this DataSource.
- */
- public String getDescription()
- {
- return "JDBC3 Pooling DataSource from " + org.postgresql.Driver.getVersion();
- }
-}
+++ /dev/null
-package org.postgresql.jdbc3;
-
-
-import java.sql.*;
-import org.postgresql.PGRefCursorResultSet;
-import org.postgresql.core.BaseResultSet;
-import org.postgresql.core.BaseStatement;
-import org.postgresql.core.Field;
-
-public class Jdbc3PreparedStatement extends org.postgresql.jdbc3.AbstractJdbc3Statement implements java.sql.PreparedStatement
-{
-
- public Jdbc3PreparedStatement(Jdbc3Connection connection, String sql) throws SQLException
- {
- super(connection, sql);
- }
-
- public BaseResultSet createResultSet (Field[] fields, java.util.Vector tuples, String status, int updateCount, long insertOID, boolean binaryCursor) throws SQLException
- {
- return new Jdbc3ResultSet((BaseStatement)this, fields, tuples, status, updateCount, insertOID, binaryCursor);
- }
-
- public PGRefCursorResultSet createRefCursorResultSet (String cursorName) throws SQLException
- {
- return new Jdbc3RefCursorResultSet(this, cursorName);
- }
-}
-
+++ /dev/null
-package org.postgresql.jdbc3;
-
-import org.postgresql.PGRefCursorResultSet;
-import org.postgresql.core.BaseStatement;
-import org.postgresql.core.Field;
-import org.postgresql.core.QueryExecutor;
-import java.util.Vector;
-
-/** A real result set based on a ref cursor.
- *
- * @author Nic Ferrier
- */
-public class Jdbc3RefCursorResultSet extends Jdbc3ResultSet implements PGRefCursorResultSet
-{
-
- String refCursorHandle;
-
- // Indicates when the result set has activaly bound to the cursor.
- boolean isInitialized = false;
-
- Jdbc3RefCursorResultSet(java.sql.Statement statement, String refCursorName) throws java.sql.SQLException
- {
- // This casting is a GCJ requirement.
- super((BaseStatement)statement,
- (Field[])null,
- (Vector)null,
- (String)null, -1, 0L, false);
- this.refCursorHandle = refCursorName;
- }
-
- public String getRefCursor ()
- {
- return refCursorHandle;
- }
-
- public boolean next () throws java.sql.SQLException
- {
- if (isInitialized)
- return super.next();
- // Initialize this res set with the rows from the cursor.
- String[] toExec = { "FETCH ALL IN \"" + refCursorHandle + "\";" };
- QueryExecutor.execute(toExec, new String[0], this);
- isInitialized = true;
- return super.next();
- }
-}
+++ /dev/null
-package org.postgresql.jdbc3;
-
-
-import java.sql.*;
-import java.util.Vector;
-import org.postgresql.core.Field;
-import org.postgresql.core.BaseStatement;
-
-/* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/jdbc3/Jdbc3ResultSet.java,v 1.6 2003/11/29 19:52:11 pgsql Exp $
- * This class implements the java.sql.ResultSet interface for JDBC3.
- * However most of the implementation is really done in
- * org.postgresql.jdbc3.AbstractJdbc3ResultSet or one of it's parents
- */
-public class Jdbc3ResultSet extends org.postgresql.jdbc3.AbstractJdbc3ResultSet implements java.sql.ResultSet
-{
-
- public Jdbc3ResultSet(BaseStatement statement, Field[] fields, Vector tuples, String status, int updateCount, long insertOID, boolean binaryCursor)
- {
- super(statement, fields, tuples, status, updateCount, insertOID, binaryCursor);
- }
-
- public java.sql.ResultSetMetaData getMetaData() throws SQLException
- {
- return new Jdbc3ResultSetMetaData(rows, fields);
- }
-
- public java.sql.Clob getClob(int i) throws SQLException
- {
- wasNullFlag = (this_row[i - 1] == null);
- if (wasNullFlag)
- return null;
-
- return new Jdbc3Clob(connection, getInt(i));
- }
-
- public java.sql.Blob getBlob(int i) throws SQLException
- {
- wasNullFlag = (this_row[i - 1] == null);
- if (wasNullFlag)
- return null;
-
- return new Jdbc3Blob(connection, getInt(i));
- }
-
-}
-
+++ /dev/null
-package org.postgresql.jdbc3;
-
-import org.postgresql.core.Field;
-
-public class Jdbc3ResultSetMetaData extends org.postgresql.jdbc2.AbstractJdbc2ResultSetMetaData implements java.sql.ResultSetMetaData
-{
-
- public Jdbc3ResultSetMetaData(java.util.Vector rows, Field[] fields)
- {
- super(rows, fields);
- }
-
-}
-
+++ /dev/null
-package org.postgresql.jdbc3;
-
-import org.postgresql.jdbc2.optional.SimpleDataSource;
-
-import javax.naming.Reference;
-
-/**
- * JDBC3 implementation of a non-pooling DataSource.
- *
- * @version $Revision: 1.1 $
- */
-public class Jdbc3SimpleDataSource extends SimpleDataSource
-{
- /**
- * Generates a JDBC3 object factory reference.
- */
- protected Reference createReference()
- {
- return new Reference(getClass().getName(), Jdbc3ObjectFactory.class.getName(), null);
- }
-
- /**
- * Gets a description of this DataSource.
- */
- public String getDescription()
- {
- return "JDBC3 Non-Pooling DataSource from " + org.postgresql.Driver.getVersion();
- }
-}
+++ /dev/null
-package org.postgresql.jdbc3;
-
-
-import java.sql.*;
-import java.util.Vector;
-import org.postgresql.PGRefCursorResultSet;
-import org.postgresql.core.BaseResultSet;
-import org.postgresql.core.Field;
-
-/* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/jdbc3/Jdbc3Statement.java,v 1.6 2003/11/29 19:52:11 pgsql Exp $
- * This class implements the java.sql.Statement interface for JDBC3.
- * However most of the implementation is really done in
- * org.postgresql.jdbc3.AbstractJdbc3Statement or one of it's parents
- */
-public class Jdbc3Statement extends org.postgresql.jdbc3.AbstractJdbc3Statement implements java.sql.Statement
-{
-
- public Jdbc3Statement (Jdbc3Connection c)
- {
- super(c);
- }
-
- public BaseResultSet createResultSet (Field[] fields, Vector tuples, String status, int updateCount, long insertOID, boolean binaryCursor) throws SQLException
- {
- return new Jdbc3ResultSet(this, fields, tuples, status, updateCount, insertOID, binaryCursor);
- }
-
- public PGRefCursorResultSet createRefCursorResultSet (String cursorName) throws SQLException
- {
- return new Jdbc3RefCursorResultSet(this, cursorName);
- }
-}
+++ /dev/null
-PostgreSQL/JDBC Test Suite Howto
-================================
-1 Introduction
-2 Installation
-3 Configuration
-4 Running the test suite
-5 Extending the test suite with new tests
-6 Guidelines for developing new tests
-7 Example
-8 Running the JDBC 2 test suite from Sun against PostgreSQL
-9 Credits, feedback
-
-
-1 Introduction
---------------
-The PostgreSQL source tree contains an automated test suite for
-the JDBC driver. This document explains how to install,
-configure and run this test suite. Furthermore, it offers
-guidelines and an example for developers to add new test cases.
-
-Sun provides two standard JDBC test suites that you may also
-find useful.
-http://java.sun.com/products/jdbc/download2.html (JDBC 1)
-http://java.sun.com/products/jdbc/jdbctestsuite-1_2_1.html (JDBC
-2, including J2EE requirements)
-The JDBC 2 test suite is covered in section 8 below. The JDBC 1
-test suite is not currently covered in this document.
-
-2 Installation
---------------
-Of course, you need to have a Java 2 JDK or JRE installed. The
-standard JDK from Sun is OK. You can download it from
-http://java.sun.com/.
-
-You need to install the Ant build utility. You can download it
-from http://jakarta.apache.org/ant/.
-
-You also need to install the JUnit testing framework. You can
-download it from http://www.junit.org/. Add junit.jar to your
-CLASSPATH before you perform the following steps. Ant will
-dynamically detect that JUnit is present and then build the JDBC
-test suite.
-
-You need to install and build the PostgreSQL source tree. You
-can download it from http://www.postgresql.org/devel-corner/.
-See README and INSTALL in the top of the tree for more
-information.
-
-You should run ./configure with the command line option
---with-java. You may also want to use --with-pgport to compile a
-non-standard default port number (e.g. 5433) into all
-components. This will cause the server to listen on this
-non-standard port and it will cause the JDBC driver to connect
-to this port by default. In this way your testing environment is
-easily separated from other PostgreSQL applications on the same
-system.
-
-In this Howto we'll use $JDBC_SRC to refer to the directory
-src/interfaces/jdbc of the PostgreSQL source tree in your
-environment. The test suite is located in the subdirectory
-$JDBC_SRC/org/postgresql/test.
-
-3 Configuration
----------------
-The test suite requires a PostgreSQL database to run the tests
-against and a user to login as. For a full regression test of
-the entire PostgreSQL system, you should run the test against a
-server built from the same source tree as the driver you're
-testing. The tests will create and drop many objects in this
-database, so it should not contain production tables to avoid
-loss of data. We recommend you assign the following names:
-
- database: test
- username: test
- password: password
-
-These names correspond with the default names set for the test
-suite in $JDBC_SRC/build.xml. If you have chosen other names you
-need to edit this file and change the properties "database",
-"username" and "password" accordingly.
-
-4 Running the test suite
-------------------------
-%cd $JDBC_SRC
-%make
-%make check
-
-This will run the command line version of JUnit. If you'd like
-to see an animated coloured progress bar as the tests are
-executed, you may want to use one of the GUI versions of the
-test runner. See the JUnit documentation for more information.
-
-If the test suite reports errors or failures that you cannot
-explain, please post the relevant parts of the output to the
-
-5 Extending the test suite with new tests
------------------------------------------
-If you're not familiar with JUnit, we recommend that you
-first read the introductory article "JUnit Test Infected:
-Programmers Love Writing Tests" on
-http://junit.sourceforge.net/doc/testinfected/testing.htm.
-Before continuing, you should ensure you understand the
-following concepts: test suite, test case, test, fixture,
-assertion, failure.
-
-The test suite consists of test cases, which consist of tests.
-A test case is a collection of tests that test a particular
-feature. The test suite is a collection of test cases that
-together test the driver - and to an extent the PostgreSQL
-backend - as a whole.
-
-If you decide to add a test to an existing test case, all you
-need to do is add a method with a name that begins with "test"
-and which takes no arguments. JUnit will dynamically find this
-method using reflection and run it when it runs the test case.
-In your test method you can use the fixture that is setup for it
-by the test case.
-
-If you decide to add a new test case, you should do two things:
-1) Add a class that extends junit.framework.TestCase. It should
-contain setUp() and tearDown() methods that create and destroy
-the fixture respectively.
-2) Edit $JDBC_SRC/org/postgresql/test/JDBC2Tests.java and add a
-suite.addTestSuite() call for your class. This will make the
-test case part of the test suite.
-
-6 Guidelines for developing new tests
--------------------------------------
-Every test should create and drop its own tables. We suggest to
-consider database objects (e.g. tables) part of the fixture for
-the tests in the test case. The test should also succeed when a
-table by the same name already exists in the test database, e.g.
-by dropping the table before running the test (ignoring errors).
-The recommended pattern for creating and dropping tables can be
-found in the example in section 7 below.
-
-Please note that JUnit provides several convenience methods to
-check for conditions. See the TestCase class in the Javadoc
-documentation of JUnit, which is installed on your system. For
-example, you can compare two integers using
-TestCase.assertEquals(int expected, int actual). This method
-will print both values in case of a failure.
-
-To simply report a failure use TestCase.fail().
-
-The JUnit FAQ explains how to test for a thrown exception.
-
-Avoid the use of the deprecated TestCase.assert(), since it will
-collide with the new assert keyword in the Java 2 platform
-version 1.4.
-
-As a rule, the test suite should succeed. Any errors or failures
-- which may be caused by bugs in the JDBC driver, the backend or
-the test suite - should be fixed ASAP. Don't let a test fail
-just to make it clear that something needs to be fixed somewhere.
-That's what the TODO lists are for.
-
-Add some comments to your tests to explain to others what it is
-you're testing. A long sequence of JDBC method calls and JUnit
-assertions can be hard to comprehend.
-
-For example, in the comments you can explain where a certain test
-condition originates from. Is it a JDBC requirement, PostgreSQL
-behaviour or the intended implementation of a feature?
-
-7 Example (incomplete)
-----------------------
-package org.postgresql.test.jdbc2;
-
-import org.postgresql.test.TestUtil;
-import junit.framework.TestCase;
-import java.sql.*;
-
-/*
- * Test case for ...
- */
-public class FooTest extends TestCase {
-
- private Connection con;
- private Statement stmt;
-
- public FooTest(String name) {
- super(name);
- }
-
- protected void setUp() throws Exception {
- con = TestUtil.openDB();
- stmt = con.createStatement();
-
- // Drop the test table if it already exists for some
- // reason. It is not an error if it doesn't exist.
- try {
- stmt.executeUpdate("DROP TABLE testfoo");
- } catch (SQLException e) {
- // Intentionally ignore. We cannot distinguish
- // "table does not exist" from other errors, since
- // PostgreSQL doesn't support error codes yet.
- }
-
- stmt.executeUpdate(
- "CREATE TABLE testfoo(pk INTEGER, col1 INTEGER)");
- stmt.executeUpdate("INSERT INTO testfoo VALUES(1, 0)");
-
- // You may want to call con.setAutoCommit(false) at
- // this point, if most tests in this test case require
- // the use of transactions.
- }
-
- protected void tearDown() throws Exception {
- con.setAutoCommit(true);
- if (stmt != null) {
- stmt.executeUpdate("DROP TABLE testfoo");
- stmt.close();
- }
- if (con != null) {
- TestUtil.closeDB(con);
- }
- }
-
- public void testFoo() {
- // Use the assert methods in junit.framework.TestCase
- // for the actual tests
-
- // Just some silly examples
- assertNotNull(con);
- if (stmt == null) {
- fail("Where is my statement?");
- }
- }
-
- public void testBar() {
- // Another test.
- }
-}
-
-8. Running the JDBC 2 test suite from Sun against PostgreSQL
-------------------------------------------------------------
-Download the test suite from
-http://java.sun.com/products/jdbc/jdbctestsuite-1_2_1.html
-This is the JDBC 2 test suite that includes J2EE requirements.
-
-1. Configure PostgreSQL so that it accepts TCP/IP connections and
- start the server. Prepare PostgreSQL by creating two users (cts1
- and cts2) and two databases (DB1 and DB2) in the cluster that is
- going to be used for JDBC testing.
-
-2. Download the latest release versions of the J2EE, J2SE, and JDBC
- test suite from Sun's Java site (http://java.sun.com), and install
- according to Sun's documentation.
-
-3. The following environment variables should be set:
-
- NO_JAVATEST=Y
-
-4. In $J2EE_HOME/config/default.properties:
-
- jdbc.drivers=org.postgresql.Driver
- jdbc.datasources=jdbc/DB1|jdbc:postgresql://localhost:5432/DB1|jdbc/DB2|jdbc:postgresq://localhost:5432/DB2
-
- Of course, if PostgreSQL is running on a computer different from
- the one running the application server, localhost should be changed
- to the proper host. Also, 5432 should be changed to whatever port
- PostgreSQL is listening on (5432 is the default).
-
- In $J2EE_HOME/bin/userconfig.sh:
-
- Add $CTS_HOME/lib/harness.jar, $CTS_HOME/lib/moo.jar,
- $CTS_HOME/lib/util.jar to J2EE_CLASSPATH. Also add the path to
- the PostgreSQL JDBC jar to J2EE_CLASSPATH. Set the JAVA_HOME
- variable to where you installed the J2SE. You should end up with
- something like this:
-
- CTS_HOME=/home/liams/linux/java/jdbccts
- J2EE_CLASSPATH=/home/liams/work/inst/postgresql-7.1.2/share/java/postgresql.jar:$CTS_HOME/lib/harness.jar:$CTS_HOME/lib/moo.jar:$CTS_HOME/lib/util.jar
- export J2EE_CLASSPATH
-
- JAVA_HOME=/home/liams/linux/java/jdk1.3.1
- export JAVA_HOME
-
- In $CTS_HOME/bin/cts.jte:
-
- webServerHost=localhost
- webServerPort=8000
- servletServerHost=localhost
- servletServerPort=8000
-
-5. Start the application server (j2ee):
-
- $ cd $J2EE_HOME
- $ bin/j2ee -verbose
-
- The server can be stopped after the tests have finished:
-
- $ cd $J2EE_HOME
- $ bin/j2ee -stop
-
-6. Run the JDBC tests:
-
- $ cd $CTS_HOME/tests/jdbc/ee
- $ make jdbc-tests
-
-At the time of writing of this document, a great number of tests
-in this test suite fail.
-
-9 Credits, feedback
--------------------
-The parts of this document describing the PostgreSQL test suite
-were originally written by Rene Pijlman. Liam Stewart contributed
-the section on the Sun JDBC 2 test suite.
-
-Please send your questions about the JDBC test suites or suggestions
-
-The source of this document is maintained in
-src/interfaces/jdbc/org/postgresql/test/README in CVS. Patches for
-improvement can be send to the mailing list
-
+++ /dev/null
-package org.postgresql.test;
-
-import java.sql.*;
-import junit.framework.TestCase;
-import java.util.Properties;
-
-/*
- * Utility class for JDBC tests
- */
-public class TestUtil
-{
- /*
- * Returns the Test database JDBC URL
- */
- public static String getURL()
- {
- return "jdbc:postgresql://"+getServer()+":"+getPort()+"/"+getDatabase();
- }
-
- /*
- * Returns the Test server
- */
- public static String getServer()
- {
- return System.getProperty("server");
- }
-
- /*
- * Returns the Test port
- */
- public static int getPort()
- {
- return Integer.parseInt(System.getProperty("port"));
- }
-
- /*
- * Returns the Test database
- */
- public static String getDatabase()
- {
- return System.getProperty("database");
- }
-
- /*
- * Returns the Postgresql username
- */
- public static String getUser()
- {
- return System.getProperty("username");
- }
-
- /*
- * Returns the user's password
- */
- public static String getPassword()
- {
- return System.getProperty("password");
- }
-
- /*
- * Helper - opens a connection.
- */
- public static java.sql.Connection openDB()
- {
- return openDB(new Properties());
- }
-
- /*
- * Helper - opens a connection with the allowance for passing
- * additional parameters, like "compatible".
- */
- public static java.sql.Connection openDB(Properties props)
- {
- props.setProperty("user",getUser());
- props.setProperty("password",getPassword());
- try
- {
- Class.forName("org.postgresql.Driver");
- return java.sql.DriverManager.getConnection(getURL(), props);
- }
- catch (ClassNotFoundException ex)
- {
- TestCase.fail(ex.getMessage());
- }
- catch (SQLException ex)
- {
- TestCase.fail(ex.getMessage());
- }
- return null;
- }
-
- /*
- * Helper - closes an open connection. This rewrites SQLException to a failed
- * assertion. It's static so other classes can use it.
- */
- public static void closeDB(Connection con)
- {
- try
- {
- if (con != null)
- con.close();
- }
- catch (SQLException ex)
- {
- TestCase.fail(ex.getMessage());
- }
- }
-
- /*
- * Helper - creates a test table for use by a test
- */
- public static void createTable(Connection con,
- String table,
- String columns)
- {
- try
- {
- Statement st = con.createStatement();
- try
- {
- // Drop the table
- dropTable(con, table);
-
- // Now create the table
- st.executeUpdate("create table " + table + " (" + columns + ")");
- }
- finally
- {
- st.close();
- }
- }
- catch (SQLException ex)
- {
- TestCase.fail(ex.getMessage());
- }
- }
-
- /*
- * Helper - drops a table
- */
- public static void dropTable(Connection con, String table)
- {
- try
- {
- Statement stmt = con.createStatement();
- try
- {
- String sql = "DROP TABLE " + table;
- if (haveMinimumServerVersion(con,"7.3")) {
- sql += " CASCADE ";
- }
- stmt.executeUpdate(sql);
- }
- catch (SQLException ex)
- {
- // Since every create table issues a drop table
- // it's easy to get a table doesn't exist error.
- // we want to ignore these, but if we're in a
- // transaction we need to restart.
- // If the test case wants to catch this error
- // itself it should issue the drop SQL directly.
- if (ex.getMessage().indexOf("does not exist") != -1) {
- if (!con.getAutoCommit()) {
- con.rollback();
- }
-
- }
- }
- }
- catch (SQLException ex)
- {
- TestCase.fail(ex.getMessage());
- }
- }
-
- /*
- * Helper - generates INSERT SQL - very simple
- */
- public static String insertSQL(String table, String values)
- {
- return insertSQL(table, null, values);
- }
-
- public static String insertSQL(String table, String columns, String values)
- {
- String s = "INSERT INTO " + table;
-
- if (columns != null)
- s = s + " (" + columns + ")";
-
- return s + " VALUES (" + values + ")";
- }
-
- /*
- * Helper - generates SELECT SQL - very simple
- */
- public static String selectSQL(String table, String columns)
- {
- return selectSQL(table, columns, null, null);
- }
-
- public static String selectSQL(String table, String columns, String where)
- {
- return selectSQL(table, columns, where, null);
- }
-
- public static String selectSQL(String table, String columns, String where, String other)
- {
- String s = "SELECT " + columns + " FROM " + table;
-
- if (where != null)
- s = s + " WHERE " + where;
- if (other != null)
- s = s + " " + other;
-
- return s;
- }
-
- /*
- * Helper to prefix a number with leading zeros - ugly but it works...
- * @param v value to prefix
- * @param l number of digits (0-10)
- */
- public static String fix(int v, int l)
- {
- String s = "0000000000".substring(0, l) + Integer.toString(v);
- return s.substring(s.length() - l);
- }
-
- /**
- * Determine if the given connection is connected to a server with
- * a version of at least the given version.
- * This is convenient because we are working with a java.sql.Connection,
- * not an Postgres connection.
- */
- public static boolean haveMinimumServerVersion(Connection con, String version) throws SQLException {
- if (con instanceof org.postgresql.jdbc1.AbstractJdbc1Connection) {
- return ((org.postgresql.jdbc1.AbstractJdbc1Connection)con).haveMinimumServerVersion(version);
- }
- return false;
- }
-
- /**
- * Print a ResultSet to System.out.
- * This is useful for debugging tests.
- */
- public static void printResultSet(ResultSet rs) throws SQLException {
- ResultSetMetaData rsmd = rs.getMetaData();
- for (int i=1; i<=rsmd.getColumnCount(); i++) {
- if (i != 1) {
- System.out.print(", ");
- }
- System.out.print(rsmd.getColumnName(i));
- }
- System.out.println();
- while (rs.next()) {
- for (int i=1; i<=rsmd.getColumnCount(); i++) {
- if (i != 1) {
- System.out.print(", ");
- }
- System.out.print(rs.getString(i));
- }
- System.out.println();
- }
- }
-}
+++ /dev/null
-package org.postgresql.test.jdbc2;
-
-import junit.framework.TestCase;
-
-public class ANTTest extends TestCase
-{
- public ANTTest(String name)
- {
- super(name);
- }
-
- /*
- * This tests the acceptsURL() method with a couple of good and badly formed
- * jdbc urls
- */
- public void testANT()
- {
- String url = System.getProperty("database");
- String usr = System.getProperty("username");
- String psw = System.getProperty("password");
-
- assertNotNull(url);
- assertNotNull(usr);
- assertNotNull(psw);
-
- assertTrue(! url.equals(""));
- assertTrue(! usr.equals(""));
- }
-}
+++ /dev/null
-package org.postgresql.test.jdbc2;
-
-import org.postgresql.test.TestUtil;
-import junit.framework.TestCase;
-import java.sql.*;
-
-/* TODO tests that can be added to this test case
- * - SQLExceptions chained to a BatchUpdateException
- * - test PreparedStatement as thoroughly as Statement
- */
-
-/*
- * Test case for Statement.batchExecute()
- */
-public class BatchExecuteTest extends TestCase
-{
-
- private Connection con;
-
- public BatchExecuteTest(String name)
- {
- super(name);
- }
-
- // Set up the fixture for this testcase: a connection to a database with
- // a table for this test.
- protected void setUp() throws Exception
- {
- con = TestUtil.openDB();
- Statement stmt = con.createStatement();
-
- // Drop the test table if it already exists for some reason. It is
- // not an error if it doesn't exist.
- TestUtil.createTable(con, "testbatch", "pk INTEGER, col1 INTEGER");
-
- stmt.executeUpdate("INSERT INTO testbatch VALUES (1, 0)");
-
- // Generally recommended with batch updates. By default we run all
- // tests in this test case with autoCommit disabled.
- con.setAutoCommit(false);
- }
-
- // Tear down the fixture for this test case.
- protected void tearDown() throws Exception
- {
- con.setAutoCommit(true);
-
- TestUtil.dropTable(con, "testbatch");
- TestUtil.closeDB(con);
- }
-
- public void testSupportsBatchUpdates() throws Exception
- {
- DatabaseMetaData dbmd = con.getMetaData();
- assertTrue(dbmd.supportsBatchUpdates());
- }
-
- private void assertCol1HasValue(int expected) throws Exception
- {
- Statement getCol1 = con.createStatement();
-
- ResultSet rs =
- getCol1.executeQuery("SELECT col1 FROM testbatch WHERE pk = 1");
- assertTrue(rs.next());
-
- int actual = rs.getInt("col1");
-
- assertEquals(expected, actual);
-
- assertEquals(false, rs.next());
-
- rs.close();
- getCol1.close();
- }
-
- public void testExecuteEmptyBatch() throws Exception
- {
- Statement stmt = con.createStatement();
- int[] updateCount = stmt.executeBatch();
- assertEquals(0, updateCount.length);
-
- stmt.addBatch("UPDATE testbatch SET col1 = col1 + 1 WHERE pk = 1");
- stmt.clearBatch();
- updateCount = stmt.executeBatch();
- assertEquals(0, updateCount.length);
- stmt.close();
- }
-
- public void testClearBatch() throws Exception
- {
- Statement stmt = con.createStatement();
-
- stmt.addBatch("UPDATE testbatch SET col1 = col1 + 1 WHERE pk = 1");
- assertCol1HasValue(0);
- stmt.addBatch("UPDATE testbatch SET col1 = col1 + 2 WHERE pk = 1");
- assertCol1HasValue(0);
- stmt.clearBatch();
- assertCol1HasValue(0);
- stmt.addBatch("UPDATE testbatch SET col1 = col1 + 4 WHERE pk = 1");
- assertCol1HasValue(0);
- stmt.executeBatch();
- assertCol1HasValue(4);
- con.commit();
- assertCol1HasValue(4);
-
- stmt.close();
- }
-
- public void testSelectThrowsException() throws Exception
- {
- Statement stmt = con.createStatement();
-
- stmt.addBatch("UPDATE testbatch SET col1 = col1 + 1 WHERE pk = 1");
- stmt.addBatch("SELECT col1 FROM testbatch WHERE pk = 1");
- stmt.addBatch("UPDATE testbatch SET col1 = col1 + 2 WHERE pk = 1");
-
- try
- {
- stmt.executeBatch();
- fail("Should raise a BatchUpdateException because of the SELECT");
- }
- catch (BatchUpdateException e)
- {
- int [] updateCounts = e.getUpdateCounts();
- assertEquals(1, updateCounts.length);
- assertEquals(1, updateCounts[0]);
- }
- catch (SQLException e)
- {
- fail( "Should throw a BatchUpdateException instead of " +
- "a generic SQLException: " + e);
- }
-
- stmt.close();
- }
-
- public void testPreparedStatement() throws Exception
- {
- PreparedStatement pstmt = con.prepareStatement(
- "UPDATE testbatch SET col1 = col1 + ? WHERE PK = ?" );
-
- // Note that the first parameter changes for every statement in the
- // batch, whereas the second parameter remains constant.
- pstmt.setInt(1, 1);
- pstmt.setInt(2, 1);
- pstmt.addBatch();
- assertCol1HasValue(0);
-
- pstmt.setInt(1, 2);
- pstmt.addBatch();
- assertCol1HasValue(0);
-
- pstmt.setInt(1, 4);
- pstmt.addBatch();
- assertCol1HasValue(0);
-
- pstmt.executeBatch();
- assertCol1HasValue(7);
-
- //now test to see that we can still use the statement after the execute
- pstmt.setInt(1, 3);
- pstmt.addBatch();
- assertCol1HasValue(7);
-
- pstmt.executeBatch();
- assertCol1HasValue(10);
-
- con.commit();
- assertCol1HasValue(10);
-
- con.rollback();
- assertCol1HasValue(10);
-
- pstmt.close();
- }
-
- public void testTransactionalBehaviour() throws Exception
- {
- Statement stmt = con.createStatement();
-
- stmt.addBatch("UPDATE testbatch SET col1 = col1 + 1 WHERE pk = 1");
- stmt.addBatch("UPDATE testbatch SET col1 = col1 + 2 WHERE pk = 1");
- stmt.executeBatch();
- con.rollback();
- assertCol1HasValue(0);
-
- stmt.addBatch("UPDATE testbatch SET col1 = col1 + 4 WHERE pk = 1");
- stmt.addBatch("UPDATE testbatch SET col1 = col1 + 8 WHERE pk = 1");
-
- // The statement has been added to the batch, but it should not yet
- // have been executed.
- assertCol1HasValue(0);
-
- int[] updateCounts = stmt.executeBatch();
- assertEquals(2, updateCounts.length);
- assertEquals(1, updateCounts[0]);
- assertEquals(1, updateCounts[1]);
-
- assertCol1HasValue(12);
- con.commit();
- assertCol1HasValue(12);
- con.rollback();
- assertCol1HasValue(12);
-
- stmt.close();
- }
-}
+++ /dev/null
-package org.postgresql.test.jdbc2;
-
-import org.postgresql.test.TestUtil;
-import junit.framework.TestCase;
-import java.io.*;
-import java.sql.*;
-
-import org.postgresql.largeobject.*;
-
-/*
- * $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/test/jdbc2/BlobTest.java,v 1.10 2003/11/29 22:41:23 pgsql Exp $
- *
- * Some simple tests based on problems reported by users. Hopefully these will
- * help prevent previous problems from re-occuring ;-)
- *
- */
-public class BlobTest extends TestCase
-{
-
- private Connection con;
-
- private static final int LOOP = 0; // LargeObject API using loop
- private static final int NATIVE_STREAM = 1; // LargeObject API using OutputStream
- private static final int JDBC_STREAM = 2; // JDBC API using OutputStream
-
- public BlobTest(String name)
- {
- super(name);
- }
-
- protected void setUp() throws Exception
- {
- con = TestUtil.openDB();
- TestUtil.createTable(con, "testblob", "id name,lo oid");
- }
-
- protected void tearDown() throws Exception
- {
- TestUtil.dropTable(con, "testblob");
- TestUtil.closeDB(con);
- }
-
- /*
- * Tests one method of uploading a blob to the database
- */
- public void testUploadBlob_LOOP()
- {
- try
- {
- con.setAutoCommit(false);
- assertTrue(!con.getAutoCommit());
-
- assertTrue(uploadFile("build.xml", LOOP) > 0);
-
- // Now compare the blob & the file. Note this actually tests the
- // InputStream implementation!
- assertTrue(compareBlobsLOAPI());
- assertTrue(compareBlobs());
- assertTrue(compareClobs());
-
- con.setAutoCommit(true);
- }
- catch (Exception ex)
- {
- fail(ex.getMessage());
- }
- }
-
- /*
- * Tests one method of uploading a blob to the database
- */
- public void testUploadBlob_NATIVE()
- {
- try
- {
- con.setAutoCommit(false);
- assertTrue(!con.getAutoCommit());
-
- assertTrue(uploadFile("build.xml", NATIVE_STREAM) > 0);
-
- // Now compare the blob & the file. Note this actually tests the
- // InputStream implementation!
- assertTrue(compareBlobs());
-
- con.setAutoCommit(true);
- }
- catch (Exception ex)
- {
- fail(ex.getMessage());
- }
- }
-
- /*
- * Helper - uploads a file into a blob using old style methods. We use this
- * because it always works, and we can use it as a base to test the new
- * methods.
- */
- private int uploadFile(String file, int method) throws Exception
- {
- LargeObjectManager lom = ((org.postgresql.PGConnection)con).getLargeObjectAPI();
-
- FileInputStream fis = new FileInputStream(file);
-
- int oid = lom.create(LargeObjectManager.READWRITE);
- LargeObject blob = lom.open(oid);
-
- int s, t;
- byte buf[];
- OutputStream os;
-
- switch (method)
- {
- case LOOP:
- buf = new byte[2048];
- t = 0;
- while ((s = fis.read(buf, 0, buf.length)) > 0)
- {
- t += s;
- blob.write(buf, 0, s);
- }
- break;
-
- case NATIVE_STREAM:
- os = blob.getOutputStream();
- s = fis.read();
- while (s > -1)
- {
- os.write(s);
- s = fis.read();
- }
- os.close();
- break;
-
- case JDBC_STREAM:
- File f = new File(file);
- PreparedStatement ps = con.prepareStatement(TestUtil.insertSQL("testblob", "?"));
- ps.setBinaryStream(1, fis, (int) f.length());
- ps.execute();
- break;
-
- default:
- assertTrue("Unknown method in uploadFile", false);
- }
-
- blob.close();
- fis.close();
-
- // Insert into the table
- Statement st = con.createStatement();
- st.executeUpdate(TestUtil.insertSQL("testblob", "id,lo", "'" + file + "'," + oid));
- con.commit();
- st.close();
-
- return oid;
- }
-
- /*
- * Helper - compares the blobs in a table with a local file. Note this uses
- * the postgresql specific Large Object API
- */
- private boolean compareBlobsLOAPI() throws Exception
- {
- boolean result = true;
-
- LargeObjectManager lom = ((org.postgresql.PGConnection)con).getLargeObjectAPI();
-
- Statement st = con.createStatement();
- ResultSet rs = st.executeQuery(TestUtil.selectSQL("testblob", "id,lo"));
- assertNotNull(rs);
-
- while (rs.next())
- {
- String file = rs.getString(1);
- int oid = rs.getInt(2);
-
- FileInputStream fis = new FileInputStream(file);
- LargeObject blob = lom.open(oid);
- InputStream bis = blob.getInputStream();
-
- int f = fis.read();
- int b = bis.read();
- int c = 0;
- while (f >= 0 && b >= 0 & result)
- {
- result = (f == b);
- f = fis.read();
- b = bis.read();
- c++;
- }
- result = result && f == -1 && b == -1;
-
- if (!result)
- assertTrue("Large Object API Blob compare failed at " + c + " of " + blob.size(), false);
-
- blob.close();
- fis.close();
- }
- rs.close();
- st.close();
-
- return result;
- }
-
- /*
- * Helper - compares the blobs in a table with a local file. This uses the
- * jdbc java.sql.Blob api
- */
- private boolean compareBlobs() throws Exception
- {
- boolean result = true;
-
- Statement st = con.createStatement();
- ResultSet rs = st.executeQuery(TestUtil.selectSQL("testblob", "id,lo"));
- assertNotNull(rs);
-
- while (rs.next())
- {
- String file = rs.getString(1);
- Blob blob = rs.getBlob(2);
-
- FileInputStream fis = new FileInputStream(file);
- InputStream bis = blob.getBinaryStream();
-
- int f = fis.read();
- int b = bis.read();
- int c = 0;
- while (f >= 0 && b >= 0 & result)
- {
- result = (f == b);
- f = fis.read();
- b = bis.read();
- c++;
- }
- result = result && f == -1 && b == -1;
-
- if (!result)
- assertTrue("JDBC API Blob compare failed at " + c + " of " + blob.length(), false);
-
- bis.close();
- fis.close();
- }
- rs.close();
- st.close();
-
- return result;
- }
-
- /*
- * Helper - compares the clobs in a table with a local file.
- */
- private boolean compareClobs() throws Exception
- {
- boolean result = true;
-
- Statement st = con.createStatement();
- ResultSet rs = st.executeQuery(TestUtil.selectSQL("testblob", "id,lo"));
- assertNotNull(rs);
-
- while (rs.next())
- {
- String file = rs.getString(1);
- Clob clob = rs.getClob(2);
-
- FileInputStream fis = new FileInputStream(file);
- InputStream bis = clob.getAsciiStream();
-
- int f = fis.read();
- int b = bis.read();
- int c = 0;
- while (f >= 0 && b >= 0 & result)
- {
- result = (f == b);
- f = fis.read();
- b = bis.read();
- c++;
- }
- result = result && f == -1 && b == -1;
-
- if (!result)
- assertTrue("Clob compare failed at " + c + " of " + clob.length(), false);
-
- bis.close();
- fis.close();
- }
- rs.close();
- st.close();
-
- return result;
- }
-}
+++ /dev/null
-package org.postgresql.test.jdbc2;
-
-import org.postgresql.test.TestUtil;
-import java.sql.CallableStatement;
-import java.sql.Connection;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.sql.Types;
-
-import junit.framework.TestCase;
-
-/*
- * CallableStatement tests.
- * @author Paul Bethe
- */
-public class CallableStmtTest extends TestCase
-{
- private Connection con;
-
- public CallableStmtTest (String name)
- {
- super(name);
- }
-
- protected void setUp() throws Exception
- {
- con = TestUtil.openDB();
- Statement stmt = con.createStatement ();
- stmt.execute ("CREATE OR REPLACE FUNCTION testspg__getString (varchar) " +
- "RETURNS varchar AS ' DECLARE inString alias for $1; begin " +
- "return ''bob''; end; ' LANGUAGE 'plpgsql';");
- stmt.execute ("CREATE OR REPLACE FUNCTION testspg__getDouble (float) " +
- "RETURNS float AS ' DECLARE inString alias for $1; begin " +
- "return 42.42; end; ' LANGUAGE 'plpgsql';");
- stmt.execute ("CREATE OR REPLACE FUNCTION testspg__getInt (int) RETURNS int " +
- " AS 'DECLARE inString alias for $1; begin " +
- "return 42; end;' LANGUAGE 'plpgsql';");
- stmt.execute ("CREATE OR REPLACE FUNCTION testspg__getNumeric (numeric) " +
- "RETURNS numeric AS ' DECLARE inString alias for $1; " +
- "begin return 42; end; ' LANGUAGE 'plpgsql';");
- stmt.close ();
- }
-
- protected void tearDown() throws Exception
- {
- Statement stmt = con.createStatement ();
- stmt.execute ("drop FUNCTION testspg__getString (varchar);");
- stmt.execute ("drop FUNCTION testspg__getDouble (float);");
- stmt.execute ("drop FUNCTION testspg__getInt (int);");
- stmt.execute ("drop FUNCTION testspg__getNumeric (numeric);");
- TestUtil.closeDB(con);
- }
-
-
- final String func = "{ ? = call ";
- final String pkgName = "testspg__";
- // protected void runTest () throws Throwable {
- //testGetString ();
- //}
-
- public void testGetDouble () throws Throwable
- {
- CallableStatement call = con.prepareCall (func + pkgName + "getDouble (?) }");
- call.setDouble (2, (double)3.04);
- call.registerOutParameter (1, Types.DOUBLE);
- call.execute ();
- double result = call.getDouble (1);
- assertTrue ("correct return from getString ()", result == 42.42);
- }
-
- public void testGetInt () throws Throwable
- {
- CallableStatement call = con.prepareCall (func + pkgName + "getInt (?) }");
- call.setInt (2, 4);
- call.registerOutParameter (1, Types.INTEGER);
- call.execute ();
- int result = call.getInt (1);
- assertTrue ("correct return from getString ()", result == 42);
- }
-
- public void testGetNumeric () throws Throwable
- {
- CallableStatement call = con.prepareCall (func + pkgName + "getNumeric (?) }");
- call.setBigDecimal (2, new java.math.BigDecimal(4));
- call.registerOutParameter (1, Types.NUMERIC);
- call.execute ();
- java.math.BigDecimal result = call.getBigDecimal (1);
- assertTrue ("correct return from getString ()",
- result.equals (new java.math.BigDecimal(42)));
- }
-
- public void testGetString () throws Throwable
- {
- CallableStatement call = con.prepareCall (func + pkgName + "getString (?) }");
- call.setString (2, "foo");
- call.registerOutParameter (1, Types.VARCHAR);
- call.execute ();
- String result = call.getString (1);
- assertTrue ("correct return from getString ()", result.equals ("bob"));
-
- }
-
- public void testBadStmt () throws Throwable
- {
- tryOneBadStmt ("{ ?= " + pkgName + "getString (?) }");
- tryOneBadStmt ("{ ?= call getString (?) ");
- tryOneBadStmt ("{ = ? call getString (?); }");
- }
-
- protected void tryOneBadStmt (String sql) throws Throwable
- {
- boolean wasCaught = false;
- try
- {
- CallableStatement call = con.prepareCall (sql);
- }
- catch (SQLException e)
- {
- wasCaught = true; // good -> this statement was missing something
- }
- assertTrue ("bad statment ('" + sql + "')was not caught", wasCaught);
- }
-
-}
+++ /dev/null
-package org.postgresql.test.jdbc2;
-
-import org.postgresql.test.TestUtil;
-import junit.framework.TestCase;
-import java.sql.*;
-
-/*
- * TestCase to test the internal functionality of org.postgresql.jdbc2.Connection
- * and it's superclass.
- *
- * PS: Do you know how difficult it is to type on a train? ;-)
- *
- * $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/test/jdbc2/ConnectionTest.java,v 1.11 2003/11/29 22:41:23 pgsql Exp $
- */
-
-public class ConnectionTest extends TestCase
-{
-
- /*
- * Constructor
- */
- public ConnectionTest(String name)
- {
- super(name);
- }
-
- // Set up the fixture for this testcase: the tables for this test.
- protected void setUp() throws Exception
- {
- Connection con = TestUtil.openDB();
-
- TestUtil.createTable(con, "test_a", "imagename name,image oid,id int4");
- TestUtil.createTable(con, "test_c", "source text,cost money,imageid int4");
-
- TestUtil.closeDB(con);
- }
-
- // Tear down the fixture for this test case.
- protected void tearDown() throws Exception
- {
- Connection con = TestUtil.openDB();
-
- TestUtil.dropTable(con, "test_a");
- TestUtil.dropTable(con, "test_c");
-
- TestUtil.closeDB(con);
- }
-
- /*
- * Tests the two forms of createStatement()
- */
- public void testCreateStatement()
- {
- try
- {
- java.sql.Connection conn = TestUtil.openDB();
-
- // A standard Statement
- java.sql.Statement stat = conn.createStatement();
- assertNotNull(stat);
- stat.close();
-
- // Ask for Updateable ResultSets
- stat = conn.createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE, java.sql.ResultSet.CONCUR_UPDATABLE);
- assertNotNull(stat);
- stat.close();
-
- }
- catch (SQLException ex)
- {
- assertTrue(ex.getMessage(), false);
- }
- }
-
- /*
- * Tests the two forms of prepareStatement()
- */
- public void testPrepareStatement()
- {
- try
- {
- java.sql.Connection conn = TestUtil.openDB();
-
- String sql = "select source,cost,imageid from test_c";
-
- // A standard Statement
- java.sql.PreparedStatement stat = conn.prepareStatement(sql);
- assertNotNull(stat);
- stat.close();
-
- // Ask for Updateable ResultSets
- stat = conn.prepareStatement(sql, java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE, java.sql.ResultSet.CONCUR_UPDATABLE);
- assertNotNull(stat);
- stat.close();
-
- }
- catch (SQLException ex)
- {
- assertTrue(ex.getMessage(), false);
- }
- }
-
- /*
- * Put the test for createPrepareCall here
- */
- public void testPrepareCall()
- {}
-
- /*
- * Test nativeSQL
- */
- public void testNativeSQL()
- {
- // For now do nothing as it returns itself
- }
-
- /*
- * Test autoCommit (both get & set)
- */
- public void testTransactions()
- {
- try
- {
- java.sql.Connection con = TestUtil.openDB();
- java.sql.Statement st;
- java.sql.ResultSet rs;
-
- // Turn it off
- con.setAutoCommit(false);
- assertTrue(!con.getAutoCommit());
-
- // Turn it back on
- con.setAutoCommit(true);
- assertTrue(con.getAutoCommit());
-
- // Now test commit
- st = con.createStatement();
- st.executeUpdate("insert into test_a (imagename,image,id) values ('comttest',1234,5678)");
-
- con.setAutoCommit(false);
-
- // Now update image to 9876 and commit
- st.executeUpdate("update test_a set image=9876 where id=5678");
- con.commit();
- rs = st.executeQuery("select image from test_a where id=5678");
- assertTrue(rs.next());
- assertEquals(9876, rs.getInt(1));
- rs.close();
-
- // Now try to change it but rollback
- st.executeUpdate("update test_a set image=1111 where id=5678");
- con.rollback();
- rs = st.executeQuery("select image from test_a where id=5678");
- assertTrue(rs.next());
- assertEquals(9876, rs.getInt(1)); // Should not change!
- rs.close();
-
- TestUtil.closeDB(con);
- }
- catch (SQLException ex)
- {
- assertTrue(ex.getMessage(), false);
- }
- }
-
- /*
- * Simple test to see if isClosed works.
- */
- public void testIsClosed()
- {
- try
- {
- Connection con = TestUtil.openDB();
-
- // Should not say closed
- assertTrue(!con.isClosed());
-
- TestUtil.closeDB(con);
-
- // Should now say closed
- assertTrue(con.isClosed());
-
- }
- catch (SQLException ex)
- {
- assertTrue(ex.getMessage(), false);
- }
- }
-
- /*
- * Test the warnings system
- */
- public void testWarnings()
- {
- try
- {
- Connection con = TestUtil.openDB();
-
- String testStr = "This Is OuR TeSt message";
-
- // The connection must be ours!
- assertTrue(con instanceof org.postgresql.PGConnection);
-
- // Clear any existing warnings
- con.clearWarnings();
-
- // Set the test warning
- ((org.postgresql.jdbc2.AbstractJdbc2Connection)con).addWarning(testStr);
-
- // Retrieve it
- SQLWarning warning = con.getWarnings();
- assertNotNull(warning);
- assertEquals(testStr, warning.getMessage());
-
- // Finally test clearWarnings() this time there must be something to delete
- con.clearWarnings();
- assertTrue(con.getWarnings() == null);
-
- TestUtil.closeDB(con);
- }
- catch (SQLException ex)
- {
- assertTrue(ex.getMessage(), false);
- }
- }
-
- /*
- * Transaction Isolation Levels
- */
- public void testTransactionIsolation()
- {
- try
- {
- Connection con = TestUtil.openDB();
-
- // PostgreSQL defaults to READ COMMITTED
- assertEquals(Connection.TRANSACTION_READ_COMMITTED,
- con.getTransactionIsolation());
-
- // Begin a transaction
- con.setAutoCommit(false);
-
- // The isolation level should not have changed
- assertEquals(Connection.TRANSACTION_READ_COMMITTED,
- con.getTransactionIsolation());
-
-
- // Note the behavior on when a transaction starts is different
- // under 7.3 than previous versions. In 7.3 a transaction
- // starts with the first sql command, whereas previously
- // you were always in a transaction in autocommit=false
- // so we issue a select to ensure we are in a transaction
- Statement stmt = con.createStatement();
- stmt.executeQuery("select 1");
-
- // Now change the default for future transactions
- con.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
-
- // Since the call to setTransactionIsolation() above was made
- // inside the transaction, the isolation level of the current
- // transaction did not change. It affects only future ones.
- // This behaviour is recommended by the JDBC spec.
- assertEquals(Connection.TRANSACTION_READ_COMMITTED,
- con.getTransactionIsolation());
-
- // Begin a new transaction
- con.commit();
- stmt.executeQuery("select 1");
-
- // Now we should see the new isolation level
- assertEquals(Connection.TRANSACTION_SERIALIZABLE,
- con.getTransactionIsolation());
-
- // Repeat the steps above with the transition back to
- // READ COMMITTED.
- con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
- assertEquals(Connection.TRANSACTION_SERIALIZABLE,
- con.getTransactionIsolation());
- con.commit();
- assertEquals(Connection.TRANSACTION_READ_COMMITTED,
- con.getTransactionIsolation());
-
- // Now run some tests with autocommit enabled.
- con.setAutoCommit(true);
-
- assertEquals(Connection.TRANSACTION_READ_COMMITTED,
- con.getTransactionIsolation());
-
- con.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
- assertEquals(Connection.TRANSACTION_SERIALIZABLE,
- con.getTransactionIsolation());
-
- con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
- assertEquals(Connection.TRANSACTION_READ_COMMITTED, con.getTransactionIsolation());
-
- // Test if a change of isolation level before beginning the
- // transaction affects the isolation level inside the transaction.
- con.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
- assertEquals(Connection.TRANSACTION_SERIALIZABLE,
- con.getTransactionIsolation());
- con.setAutoCommit(false);
- assertEquals(Connection.TRANSACTION_SERIALIZABLE,
- con.getTransactionIsolation());
- con.setAutoCommit(true);
- assertEquals(Connection.TRANSACTION_SERIALIZABLE,
- con.getTransactionIsolation());
- con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
- assertEquals(Connection.TRANSACTION_READ_COMMITTED,
- con.getTransactionIsolation());
- con.setAutoCommit(false);
- assertEquals(Connection.TRANSACTION_READ_COMMITTED,
- con.getTransactionIsolation());
-
- TestUtil.closeDB(con);
- }
- catch ( SQLException ex )
- {
- fail( ex.getMessage() );
- }
- }
-
- /*
- * JDBC2 Type mappings
- */
- public void testTypeMaps()
- {
- try
- {
- Connection con = TestUtil.openDB();
-
- // preserve the current map
- java.util.Map oldmap = con.getTypeMap();
-
- // now change it for an empty one
- java.util.Map newmap = new java.util.HashMap();
- con.setTypeMap(newmap);
- assertEquals(newmap, con.getTypeMap());
-
- // restore the old one
- con.setTypeMap(oldmap);
- assertEquals(oldmap, con.getTypeMap());
-
- TestUtil.closeDB(con);
- }
- catch (SQLException ex)
- {
- assertTrue(ex.getMessage(), false);
- }
- }
-}
+++ /dev/null
-package org.postgresql.test.jdbc2;
-
-import java.sql.*;
-
-import junit.framework.TestCase;
-
-import org.postgresql.test.TestUtil;
-
-/*
- * Tests for using non-zero setFetchSize().
- */
-public class CursorFetchTest extends TestCase
-{
- private Connection con;
-
- public CursorFetchTest(String name)
- {
- super(name);
- }
-
- protected void setUp() throws Exception
- {
- con = TestUtil.openDB();
- TestUtil.createTable(con, "test_fetch", "value integer");
- con.setAutoCommit(false);
- }
-
- protected void tearDown() throws Exception
- {
- con.rollback();
- con.setAutoCommit(true);
- TestUtil.dropTable(con, "test_fetch");
- TestUtil.closeDB(con);
- }
-
- protected void createRows(int count) throws Exception
- {
- PreparedStatement stmt = con.prepareStatement("insert into test_fetch(value) values(?)");
- for (int i = 0; i < count; ++i) {
- stmt.setInt(1,i);
- stmt.executeUpdate();
- }
- }
-
- // Test various fetchsizes.
- public void testBasicFetch() throws Exception
- {
- createRows(100);
-
- PreparedStatement stmt = con.prepareStatement("select * from test_fetch order by value");
- int[] testSizes = { 0, 1, 49, 50, 51, 99, 100, 101 };
- for (int i = 0; i < testSizes.length; ++i) {
- stmt.setFetchSize(testSizes[i]);
- assertEquals(testSizes[i], stmt.getFetchSize());
-
- ResultSet rs = stmt.executeQuery();
- assertEquals(testSizes[i], rs.getFetchSize());
-
- int count = 0;
- while (rs.next()) {
- assertEquals("query value error with fetch size " + testSizes[i], count, rs.getInt(1));
- ++count;
- }
-
- assertEquals("total query size error with fetch size " + testSizes[i], 100, count);
- }
- }
-
- //
- // Tests for ResultSet.setFetchSize().
- //
-
- // test one:
- // set fetchsize = 0
- // run query (all rows should be fetched)
- // set fetchsize = 50 (should have no effect)
- // process results
- public void testResultSetFetchSizeOne() throws Exception
- {
- createRows(100);
-
- PreparedStatement stmt = con.prepareStatement("select * from test_fetch order by value");
- stmt.setFetchSize(0);
- ResultSet rs = stmt.executeQuery();
- rs.setFetchSize(50); // Should have no effect.
-
- int count = 0;
- while (rs.next()) {
- assertEquals(count, rs.getInt(1));
- ++count;
- }
-
- assertEquals(100, count);
- }
-
- // test two:
- // set fetchsize = 25
- // run query (25 rows fetched)
- // set fetchsize = 0
- // process results:
- // process 25 rows
- // should do a FETCH ALL to get more data
- // process 75 rows
- public void testResultSetFetchSizeTwo() throws Exception
- {
- createRows(100);
-
- PreparedStatement stmt = con.prepareStatement("select * from test_fetch order by value");
- stmt.setFetchSize(25);
- ResultSet rs = stmt.executeQuery();
- rs.setFetchSize(0);
-
- int count = 0;
- while (rs.next()) {
- assertEquals(count, rs.getInt(1));
- ++count;
- }
-
- assertEquals(100, count);
- }
-
- // test three:
- // set fetchsize = 25
- // run query (25 rows fetched)
- // set fetchsize = 50
- // process results:
- // process 25 rows. should NOT hit end-of-results here.
- // do a FETCH FORWARD 50
- // process 50 rows
- // do a FETCH FORWARD 50
- // process 25 rows. end of results.
- public void testResultSetFetchSizeThree() throws Exception
- {
- createRows(100);
-
- PreparedStatement stmt = con.prepareStatement("select * from test_fetch order by value");
- stmt.setFetchSize(25);
- ResultSet rs = stmt.executeQuery();
- rs.setFetchSize(50);
-
- int count = 0;
- while (rs.next()) {
- assertEquals(count, rs.getInt(1));
- ++count;
- }
-
- assertEquals(100, count);
- }
-
- // test four:
- // set fetchsize = 50
- // run query (50 rows fetched)
- // set fetchsize = 25
- // process results:
- // process 50 rows.
- // do a FETCH FORWARD 25
- // process 25 rows
- // do a FETCH FORWARD 25
- // process 25 rows. end of results.
- public void testResultSetFetchSizeFour() throws Exception
- {
- createRows(100);
-
- PreparedStatement stmt = con.prepareStatement("select * from test_fetch order by value");
- stmt.setFetchSize(50);
- ResultSet rs = stmt.executeQuery();
- rs.setFetchSize(25);
-
- int count = 0;
- while (rs.next()) {
- assertEquals(count, rs.getInt(1));
- ++count;
- }
-
- assertEquals(100, count);
- }
-
- // Test odd queries that should not be transformed into cursor-based fetches.
- public void TODO_FAILS_testInsert() throws Exception
- {
- // INSERT should not be transformed.
- PreparedStatement stmt = con.prepareStatement("insert into test_fetch(value) values(1)");
- stmt.setFetchSize(100); // Should be meaningless.
- stmt.executeUpdate();
- }
-
- public void TODO_FAILS_testMultistatement() throws Exception
- {
- // Queries with multiple statements should not be transformed.
-
- createRows(100); // 0 .. 99
- PreparedStatement stmt = con.prepareStatement("insert into test_fetch(value) values(100); select * from test_fetch order by value");
- stmt.setFetchSize(10);
- ResultSet rs = stmt.executeQuery();
-
- int count = 0;
- while (rs.next()) {
- assertEquals(count, rs.getInt(1));
- ++count;
- }
-
- assertEquals(101, count);
- }
-}
+++ /dev/null
-package org.postgresql.test.jdbc2;
-
-import org.postgresql.test.TestUtil;
-import junit.framework.TestCase;
-import java.sql.*;
-
-/*
- * TestCase to test the internal functionality of
- * org.postgresql.jdbc2.DatabaseMetaData's various properties.
- * Methods which return a ResultSet are tested elsewhere.
- * This avoids a complicated setUp/tearDown for something like
- * assertTrue(dbmd.nullPlusNonNullIsNull());
- */
-
-public class DatabaseMetaDataPropertiesTest extends TestCase
-{
-
- private Connection con;
- /*
- * Constructor
- */
- public DatabaseMetaDataPropertiesTest(String name)
- {
- super(name);
- }
-
- protected void setUp() throws Exception
- {
- con = TestUtil.openDB();
- }
- protected void tearDown() throws Exception
- {
- TestUtil.closeDB( con );
- }
-
- /*
- * The spec says this may return null, but we always do!
- */
- public void testGetMetaData()
- {
- try
- {
-
- DatabaseMetaData dbmd = con.getMetaData();
- assertNotNull(dbmd);
-
- }
- catch (SQLException ex)
- {
- fail(ex.getMessage());
- }
- }
-
- /*
- * Test default capabilities
- */
- public void testCapabilities()
- {
- try
- {
-
- DatabaseMetaData dbmd = con.getMetaData();
- assertNotNull(dbmd);
-
- assertTrue(dbmd.allProceduresAreCallable());
- assertTrue(dbmd.allTablesAreSelectable()); // not true all the time
-
- // This should always be false for postgresql (at least for 7.x)
- assertTrue(!dbmd.isReadOnly());
-
- // does the backend support this yet? The protocol does...
- assertTrue(!dbmd.supportsMultipleResultSets());
-
- // yes, as multiple backends can have transactions open
- assertTrue(dbmd.supportsMultipleTransactions());
-
- assertTrue(dbmd.supportsMinimumSQLGrammar());
- assertTrue(!dbmd.supportsCoreSQLGrammar());
- assertTrue(!dbmd.supportsExtendedSQLGrammar());
- if (TestUtil.haveMinimumServerVersion(con,"7.3"))
- assertTrue(dbmd.supportsANSI92EntryLevelSQL());
- else
- assertTrue(!dbmd.supportsANSI92EntryLevelSQL());
- assertTrue(!dbmd.supportsANSI92IntermediateSQL());
- assertTrue(!dbmd.supportsANSI92FullSQL());
-
- assertTrue(dbmd.supportsIntegrityEnhancementFacility());
-
- }
- catch (SQLException ex)
- {
- fail(ex.getMessage());
- }
- }
-
-
- public void testJoins()
- {
- try
- {
-
- DatabaseMetaData dbmd = con.getMetaData();
- assertNotNull(dbmd);
-
- assertTrue(dbmd.supportsOuterJoins());
- assertTrue(dbmd.supportsFullOuterJoins());
- assertTrue(dbmd.supportsLimitedOuterJoins());
-
- }
- catch (SQLException ex)
- {
- fail(ex.getMessage());
- }
- }
-
- public void testCursors()
- {
- try
- {
-
- DatabaseMetaData dbmd = con.getMetaData();
- assertNotNull(dbmd);
-
- assertTrue(!dbmd.supportsPositionedDelete());
- assertTrue(!dbmd.supportsPositionedUpdate());
-
- }
- catch (SQLException ex)
- {
- fail(ex.getMessage());
- }
- }
-
- public void testValues()
- {
- try {
- DatabaseMetaData dbmd = con.getMetaData();
- assertNotNull(dbmd);
- int indexMaxKeys = dbmd.getMaxColumnsInIndex();
- if (TestUtil.haveMinimumServerVersion(con,"7.3")) {
- assertEquals(indexMaxKeys,32);
- } else {
- assertEquals(indexMaxKeys,16);
- }
- } catch (SQLException sqle) {
- fail(sqle.getMessage());
- }
- }
-
- public void testNulls()
- {
- try
- {
-
- DatabaseMetaData dbmd = con.getMetaData();
- assertNotNull(dbmd);
-
- assertTrue(!dbmd.nullsAreSortedAtStart());
- assertTrue( dbmd.nullsAreSortedAtEnd() != TestUtil.haveMinimumServerVersion(con,"7.2"));
- assertTrue( dbmd.nullsAreSortedHigh() == TestUtil.haveMinimumServerVersion(con,"7.2"));
- assertTrue(!dbmd.nullsAreSortedLow());
-
- assertTrue(dbmd.nullPlusNonNullIsNull());
-
- assertTrue(dbmd.supportsNonNullableColumns());
-
- }
- catch (SQLException ex)
- {
- fail(ex.getMessage());
- }
- }
-
- public void testLocalFiles()
- {
- try
- {
-
- DatabaseMetaData dbmd = con.getMetaData();
- assertNotNull(dbmd);
-
- assertTrue(!dbmd.usesLocalFilePerTable());
- assertTrue(!dbmd.usesLocalFiles());
-
- }
- catch (SQLException ex)
- {
- fail(ex.getMessage());
- }
- }
-
- public void testIdentifiers()
- {
- try
- {
-
- DatabaseMetaData dbmd = con.getMetaData();
- assertNotNull(dbmd);
-
- assertTrue(!dbmd.supportsMixedCaseIdentifiers()); // always false
- assertTrue(dbmd.supportsMixedCaseQuotedIdentifiers()); // always true
-
- assertTrue(!dbmd.storesUpperCaseIdentifiers()); // always false
- assertTrue(dbmd.storesLowerCaseIdentifiers()); // always true
- assertTrue(!dbmd.storesUpperCaseQuotedIdentifiers()); // always false
- assertTrue(!dbmd.storesLowerCaseQuotedIdentifiers()); // always false
- assertTrue(!dbmd.storesMixedCaseQuotedIdentifiers()); // always false
-
- assertTrue(dbmd.getIdentifierQuoteString().equals("\""));
-
-
- }
- catch (SQLException ex)
- {
- fail(ex.getMessage());
- }
- }
-
- public void testTables()
- {
- try
- {
-
- DatabaseMetaData dbmd = con.getMetaData();
- assertNotNull(dbmd);
-
- // we can add columns
- assertTrue(dbmd.supportsAlterTableWithAddColumn());
-
- // we can only drop columns in >= 7.3
- if (TestUtil.haveMinimumServerVersion(con,"7.3")) {
- assertTrue(dbmd.supportsAlterTableWithDropColumn());
- } else {
- assertTrue(!dbmd.supportsAlterTableWithDropColumn());
- }
- }
- catch (SQLException ex)
- {
- fail(ex.getMessage());
- }
- }
-
- public void testSelect()
- {
- try
- {
-
- DatabaseMetaData dbmd = con.getMetaData();
- assertNotNull(dbmd);
-
- // yes we can?: SELECT col a FROM a;
- assertTrue(dbmd.supportsColumnAliasing());
-
- // yes we can have expressions in ORDERBY
- assertTrue(dbmd.supportsExpressionsInOrderBy());
-
- // Yes, an ORDER BY clause can contain columns that are not in the
- // SELECT clause.
- assertTrue(dbmd.supportsOrderByUnrelated());
-
- assertTrue(dbmd.supportsGroupBy());
- assertTrue(dbmd.supportsGroupByUnrelated());
- assertTrue(dbmd.supportsGroupByBeyondSelect()); // needs checking
-
- }
- catch (SQLException ex)
- {
- fail(ex.getMessage());
- }
- }
-
- public void testDBParams()
- {
- try
- {
-
- DatabaseMetaData dbmd = con.getMetaData();
- assertNotNull(dbmd);
-
- assertTrue(dbmd.getURL().equals(TestUtil.getURL()));
- assertTrue(dbmd.getUserName().equals(TestUtil.getUser()));
-
- }
- catch (SQLException ex)
- {
- fail(ex.getMessage());
- }
- }
-
- public void testDbProductDetails()
- {
- try
- {
- assertTrue(con instanceof org.postgresql.PGConnection);
- org.postgresql.jdbc2.AbstractJdbc2Connection pc = (org.postgresql.jdbc2.AbstractJdbc2Connection) con;
-
- DatabaseMetaData dbmd = con.getMetaData();
- assertNotNull(dbmd);
-
- assertTrue(dbmd.getDatabaseProductName().equals("PostgreSQL"));
- //The test below doesn't make sense to me, it tests that
- //the version of the driver = the version of the database it is connected to
- //since the driver should be backwardly compatible this test is commented out
- //assertTrue(dbmd.getDatabaseProductVersion().startsWith(
- // Integer.toString(pc.getDriver().getMajorVersion())
- // + "."
- // + Integer.toString(pc.getDriver().getMinorVersion())));
- assertTrue(dbmd.getDriverName().equals("PostgreSQL Native Driver"));
-
- }
- catch (SQLException ex)
- {
- fail(ex.getMessage());
- }
- }
-
- public void testDriverVersioning()
- {
- try
- {
- assertTrue(con instanceof org.postgresql.PGConnection);
- org.postgresql.jdbc2.AbstractJdbc2Connection pc = (org.postgresql.jdbc2.AbstractJdbc2Connection) con;
-
- DatabaseMetaData dbmd = con.getMetaData();
- assertNotNull(dbmd);
-
- assertTrue(dbmd.getDriverVersion().equals(org.postgresql.Driver.getVersion()));
- assertTrue(dbmd.getDriverMajorVersion() == pc.getDriver().getMajorVersion());
- assertTrue(dbmd.getDriverMinorVersion() == pc.getDriver().getMinorVersion());
-
-
- }
- catch (SQLException ex)
- {
- fail(ex.getMessage());
- }
- }
-}
-
+++ /dev/null
-package org.postgresql.test.jdbc2;
-
-import org.postgresql.test.TestUtil;
-import junit.framework.TestCase;
-import java.sql.*;
-
-/*
- * TestCase to test the internal functionality of org.postgresql.jdbc2.DatabaseMetaData
- *
- * PS: Do you know how difficult it is to type on a train? ;-)
- *
- * $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/test/jdbc2/DatabaseMetaDataTest.java,v 1.22 2003/12/12 18:30:27 davec Exp $
- */
-
-public class DatabaseMetaDataTest extends TestCase
-{
-
- private Connection con;
- /*
- * Constructor
- */
- public DatabaseMetaDataTest(String name)
- {
- super(name);
- }
-
- protected void setUp() throws Exception
- {
- con = TestUtil.openDB();
- TestUtil.createTable( con, "testmetadata", "id int4, name text, updated timestamp" );
- Statement stmt = con.createStatement();
- //we add the following comments to ensure the joins to the comments
- //are done correctly. This ensures we correctly test that case.
- stmt.execute("comment on table testmetadata is 'this is a table comment'");
- stmt.execute("comment on column testmetadata.id is 'this is a column comment'");
- }
- protected void tearDown() throws Exception
- {
- TestUtil.dropTable( con, "testmetadata" );
-
- TestUtil.closeDB( con );
- }
-
- public void testTables()
- {
- try
- {
-
- DatabaseMetaData dbmd = con.getMetaData();
- assertNotNull(dbmd);
-
- ResultSet rs = dbmd.getTables( null, null, "testmetadat%", new String[] {"TABLE"});
- assertTrue( rs.next() );
- String tableName = rs.getString("TABLE_NAME");
- assertEquals( "testmetadata", tableName );
- String tableType = rs.getString("TABLE_TYPE");
- assertEquals( "TABLE", tableType );
- //There should only be one row returned
- assertTrue( "getTables() returned too many rows", rs.next() == false);
- rs.close();
-
- rs = dbmd.getColumns("", "", "test%", "%" );
- assertTrue( rs.next() );
- assertEquals( "testmetadata", rs.getString("TABLE_NAME") );
- assertEquals( "id", rs.getString("COLUMN_NAME") );
- assertEquals( java.sql.Types.INTEGER, rs.getInt("DATA_TYPE") );
-
- assertTrue( rs.next() );
- assertEquals( "testmetadata", rs.getString("TABLE_NAME") );
- assertEquals( "name", rs.getString("COLUMN_NAME") );
- assertEquals( java.sql.Types.VARCHAR, rs.getInt("DATA_TYPE") );
-
- assertTrue( rs.next() );
- assertEquals( "testmetadata", rs.getString("TABLE_NAME") );
- assertEquals( "updated", rs.getString("COLUMN_NAME") );
- assertEquals( java.sql.Types.TIMESTAMP, rs.getInt("DATA_TYPE") );
-
- }
- catch (SQLException ex)
- {
- fail(ex.getMessage());
- }
- }
-
- public void testCrossReference()
- {
- try
- {
- Connection con1 = TestUtil.openDB();
-
- TestUtil.createTable( con1, "vv", "a int not null, b int not null, primary key ( a, b )" );
-
- TestUtil.createTable( con1, "ww", "m int not null, n int not null, primary key ( m, n ), foreign key ( m, n ) references vv ( a, b )" );
-
-
- DatabaseMetaData dbmd = con.getMetaData();
- assertNotNull(dbmd);
-
- ResultSet rs = dbmd.getCrossReference(null, "", "vv", null, "", "ww" );
-
- for (int j = 1; rs.next(); j++ )
- {
-
- String pkTableName = rs.getString( "PKTABLE_NAME" );
- assertEquals ( "vv", pkTableName );
-
- String pkColumnName = rs.getString( "PKCOLUMN_NAME" );
- assertTrue( pkColumnName.equals("a") || pkColumnName.equals("b"));
-
- String fkTableName = rs.getString( "FKTABLE_NAME" );
- assertEquals( "ww", fkTableName );
-
- String fkColumnName = rs.getString( "FKCOLUMN_NAME" );
- assertTrue( fkColumnName.equals( "m" ) || fkColumnName.equals( "n" ) ) ;
-
- String fkName = rs.getString( "FK_NAME" );
- if (TestUtil.haveMinimumServerVersion(con1,"7.3")) {
- assertTrue(fkName.startsWith("$1"));
- } else {
- assertTrue( fkName.startsWith( "") );
- }
-
- String pkName = rs.getString( "PK_NAME" );
- assertEquals( "vv_pkey", pkName );
-
- int keySeq = rs.getInt( "KEY_SEQ" );
- assertEquals( j, keySeq );
- }
-
-
- TestUtil.dropTable( con1, "vv" );
- TestUtil.dropTable( con1, "ww" );
-
- }
- catch (SQLException ex)
- {
- fail(ex.getMessage());
- }
- }
-
- public void testForeignKeyActions()
- {
- try {
- Connection conn = TestUtil.openDB();
- TestUtil.createTable(conn, "pkt", "id int primary key");
- TestUtil.createTable(conn, "fkt1", "id int references pkt on update restrict on delete cascade");
- TestUtil.createTable(conn, "fkt2", "id int references pkt on update set null on delete set default");
- DatabaseMetaData dbmd = conn.getMetaData();
-
- ResultSet rs = dbmd.getImportedKeys(null,"","fkt1");
- assertTrue(rs.next());
- assertTrue(rs.getInt("UPDATE_RULE") == DatabaseMetaData.importedKeyRestrict);
- assertTrue(rs.getInt("DELETE_RULE") == DatabaseMetaData.importedKeyCascade);
- rs.close();
-
- rs = dbmd.getImportedKeys(null,"","fkt2");
- assertTrue(rs.next());
- assertTrue(rs.getInt("UPDATE_RULE") == DatabaseMetaData.importedKeySetNull);
- assertTrue(rs.getInt("DELETE_RULE") == DatabaseMetaData.importedKeySetDefault);
- rs.close();
-
- TestUtil.dropTable(conn,"fkt2");
- TestUtil.dropTable(conn,"fkt1");
- TestUtil.dropTable(conn,"pkt");
- }
- catch (SQLException ex)
- {
- fail(ex.getMessage());
- }
- }
-
- public void testForeignKeysToUniqueIndexes()
- {
- try
- {
- if (!TestUtil.haveMinimumServerVersion(con,"7.4"))
- return;
-
- Connection con1 = TestUtil.openDB();
- TestUtil.createTable( con1, "pkt", "a int not null, b int not null, CONSTRAINT pkt_pk_a PRIMARY KEY (a), CONSTRAINT pkt_un_b UNIQUE (b)");
- TestUtil.createTable( con1, "fkt", "c int, d int, CONSTRAINT fkt_fk_c FOREIGN KEY (c) REFERENCES pkt(b)");
-
- DatabaseMetaData dbmd = con.getMetaData();
- ResultSet rs = dbmd.getImportedKeys("","","fkt");
- int j = 0;
- for (; rs.next(); j++)
- {
- assertTrue("pkt".equals(rs.getString("PKTABLE_NAME")));
- assertTrue("fkt".equals(rs.getString("FKTABLE_NAME")));
- assertTrue("pkt_un_b".equals(rs.getString("PK_NAME")));
- assertTrue("b".equals(rs.getString("PKCOLUMN_NAME")));
- }
- assertTrue(j == 1);
-
- TestUtil.dropTable(con1, "fkt");
- TestUtil.dropTable(con1, "pkt");
- con1.close();
- }
- catch (SQLException ex)
- {
- fail(ex.getMessage());
- }
- }
-
- public void testMultiColumnForeignKeys()
- {
- try
- {
- Connection con1 = TestUtil.openDB();
- TestUtil.createTable( con1, "pkt", "a int not null, b int not null, CONSTRAINT pkt_pk PRIMARY KEY (a,b)");
- TestUtil.createTable( con1, "fkt", "c int, d int, CONSTRAINT fkt_fk_pkt FOREIGN KEY (c,d) REFERENCES pkt(b,a)");
-
- DatabaseMetaData dbmd = con.getMetaData();
- ResultSet rs = dbmd.getImportedKeys("","","fkt");
- int j = 0;
- for (; rs.next(); j++)
- {
- assertTrue("pkt".equals(rs.getString("PKTABLE_NAME")));
- assertTrue("fkt".equals(rs.getString("FKTABLE_NAME")));
- assertTrue(j+1 == rs.getInt("KEY_SEQ"));
- if (j == 0) {
- assertTrue("b".equals(rs.getString("PKCOLUMN_NAME")));
- assertTrue("c".equals(rs.getString("FKCOLUMN_NAME")));
- } else {
- assertTrue("a".equals(rs.getString("PKCOLUMN_NAME")));
- assertTrue("d".equals(rs.getString("FKCOLUMN_NAME")));
- }
- }
- assertTrue(j == 2);
-
- TestUtil.dropTable(con1, "fkt");
- TestUtil.dropTable(con1, "pkt");
- con1.close();
- }
- catch (SQLException ex)
- {
- fail(ex.getMessage());
- }
- }
-
- public void testForeignKeys()
- {
- try
- {
- Connection con1 = TestUtil.openDB();
- TestUtil.createTable( con1, "people", "id int4 primary key, name text" );
- TestUtil.createTable( con1, "policy", "id int4 primary key, name text" );
-
- TestUtil.createTable( con1, "users", "id int4 primary key, people_id int4, policy_id int4," +
- "CONSTRAINT people FOREIGN KEY (people_id) references people(id)," +
- "constraint policy FOREIGN KEY (policy_id) references policy(id)" );
-
-
- DatabaseMetaData dbmd = con.getMetaData();
- assertNotNull(dbmd);
-
- ResultSet rs = dbmd.getImportedKeys(null, "", "users" );
- int j = 0;
- for (; rs.next(); j++ )
- {
-
- String pkTableName = rs.getString( "PKTABLE_NAME" );
- assertTrue ( pkTableName.equals("people") || pkTableName.equals("policy") );
-
- String pkColumnName = rs.getString( "PKCOLUMN_NAME" );
- assertEquals( "id", pkColumnName );
-
- String fkTableName = rs.getString( "FKTABLE_NAME" );
- assertEquals( "users", fkTableName );
-
- String fkColumnName = rs.getString( "FKCOLUMN_NAME" );
- assertTrue( fkColumnName.equals( "people_id" ) || fkColumnName.equals( "policy_id" ) ) ;
-
- String fkName = rs.getString( "FK_NAME" );
- assertTrue( fkName.startsWith( "people") || fkName.startsWith( "policy" ) );
-
- String pkName = rs.getString( "PK_NAME" );
- assertTrue( pkName.equals( "people_pkey") || pkName.equals( "policy_pkey" ) );
-
- }
-
- assertTrue ( j == 2 );
-
- rs = dbmd.getExportedKeys( null, "", "people" );
-
- // this is hacky, but it will serve the purpose
- assertTrue ( rs.next() );
-
- assertEquals( "people", rs.getString( "PKTABLE_NAME" ) );
- assertEquals( "id", rs.getString( "PKCOLUMN_NAME" ) );
-
- assertEquals( "users", rs.getString( "FKTABLE_NAME" ) );
- assertEquals( "people_id", rs.getString( "FKCOLUMN_NAME" ) );
-
- assertTrue( rs.getString( "FK_NAME" ).startsWith( "people" ) );
-
-
- TestUtil.dropTable( con1, "users" );
- TestUtil.dropTable( con1, "people" );
- TestUtil.dropTable( con1, "policy" );
-
- }
- catch (SQLException ex)
- {
- fail(ex.getMessage());
- }
- }
-
- public void testColumns()
- {
- // At the moment just test that no exceptions are thrown KJ
- try
- {
- DatabaseMetaData dbmd = con.getMetaData();
- assertNotNull(dbmd);
- ResultSet rs = dbmd.getColumns(null,null,"pg_class",null);
- rs.close();
- } catch (SQLException sqle) {
- sqle.printStackTrace();
- fail(sqle.getMessage());
- }
- }
-
- public void testColumnPrivileges()
- {
- // At the moment just test that no exceptions are thrown KJ
- try
- {
- DatabaseMetaData dbmd = con.getMetaData();
- assertNotNull(dbmd);
- ResultSet rs = dbmd.getColumnPrivileges(null,null,"pg_statistic",null);
- rs.close();
- } catch (SQLException sqle) {
- sqle.printStackTrace();
- fail(sqle.getMessage());
- }
- }
-
- public void testTablePrivileges()
- {
- try
- {
- DatabaseMetaData dbmd = con.getMetaData();
- assertNotNull(dbmd);
- ResultSet rs = dbmd.getTablePrivileges(null,null,"testmetadata");
- boolean l_foundSelect = false;
- while (rs.next()) {
- if (rs.getString("GRANTEE").equals(TestUtil.getUser())
- && rs.getString("PRIVILEGE").equals("SELECT")) l_foundSelect = true;
- }
- rs.close();
- //Test that the table owner has select priv
- assertTrue("Couldn't find SELECT priv on table testmetadata for " + TestUtil.getUser(),l_foundSelect);
- } catch (SQLException sqle) {
- sqle.printStackTrace();
- fail(sqle.getMessage());
- }
- }
-
- public void testPrimaryKeys()
- {
- // At the moment just test that no exceptions are thrown KJ
- try
- {
- DatabaseMetaData dbmd = con.getMetaData();
- assertNotNull(dbmd);
- ResultSet rs = dbmd.getPrimaryKeys(null,null,"pg_class");
- rs.close();
- } catch (SQLException sqle) {
- sqle.printStackTrace();
- fail(sqle.getMessage());
- }
- }
-
- public void testIndexInfo()
- {
- // At the moment just test that no exceptions are thrown KJ
- try
- {
- DatabaseMetaData dbmd = con.getMetaData();
- assertNotNull(dbmd);
- ResultSet rs = dbmd.getIndexInfo(null,null,"pg_class",false,false);
- rs.close();
- } catch (SQLException sqle) {
- sqle.printStackTrace();
- fail(sqle.getMessage());
- }
- }
-
- public void testTableTypes()
- {
- // At the moment just test that no exceptions are thrown KJ
- try
- {
- DatabaseMetaData dbmd = con.getMetaData();
- assertNotNull(dbmd);
- ResultSet rs = dbmd.getTableTypes();
- rs.close();
- } catch (SQLException sqle) {
- sqle.printStackTrace();
- fail(sqle.getMessage());
- }
- }
-
- public void testProcedureColumns()
- {
- // At the moment just test that no exceptions are thrown KJ
- try
- {
- DatabaseMetaData dbmd = con.getMetaData();
- assertNotNull(dbmd);
- ResultSet rs = dbmd.getProcedureColumns(null,null,null,null);
- rs.close();
- } catch (SQLException sqle) {
- sqle.printStackTrace();
- fail(sqle.getMessage());
- }
- }
-
- public void testVersionColumns()
- {
- // At the moment just test that no exceptions are thrown KJ
- try
- {
- DatabaseMetaData dbmd = con.getMetaData();
- assertNotNull(dbmd);
- ResultSet rs = dbmd.getVersionColumns(null,null,"pg_class");
- rs.close();
- } catch (SQLException sqle) {
- fail(sqle.getMessage());
- }
- }
-
- public void testBestRowIdentifier()
- {
- // At the moment just test that no exceptions are thrown KJ
- try
- {
- DatabaseMetaData dbmd = con.getMetaData();
- assertNotNull(dbmd);
- ResultSet rs = dbmd.getBestRowIdentifier(null,null,"pg_type",DatabaseMetaData.bestRowSession,false);
- rs.close();
- } catch (SQLException sqle) {
- fail(sqle.getMessage());
- }
- }
-
- public void testProcedures()
- {
- // At the moment just test that no exceptions are thrown KJ
- try
- {
- DatabaseMetaData dbmd = con.getMetaData();
- assertNotNull(dbmd);
- ResultSet rs = dbmd.getProcedures(null,null,null);
- rs.close();
- } catch (SQLException sqle) {
- fail(sqle.getMessage());
- }
- }
-
- public void testCatalogs()
- {
- try
- {
- DatabaseMetaData dbmd = con.getMetaData();
- assertNotNull(dbmd);
- ResultSet rs = dbmd.getCatalogs();
- boolean foundTemplate0 = false;
- boolean foundTemplate1 = false;
- while(rs.next()) {
- String database = rs.getString("TABLE_CAT");
- if ("template0".equals(database)) {
- foundTemplate0 = true;
- } else if ("template1".equals(database)) {
- foundTemplate1 = true;
- }
- }
- rs.close();
- assertTrue(foundTemplate0);
- assertTrue(foundTemplate1);
- } catch(SQLException sqle) {
- fail(sqle.getMessage());
- }
- }
-
- public void testSchemas()
- {
- try
- {
- DatabaseMetaData dbmd = con.getMetaData();
- assertNotNull(dbmd);
-
- ResultSet rs = dbmd.getSchemas();
- boolean foundPublic = false;
- boolean foundEmpty = false;
- boolean foundPGCatalog = false;
- int count;
-
- for(count=0; rs.next(); count++) {
- String schema = rs.getString("TABLE_SCHEM");
- if ("public".equals(schema)) {
- foundPublic = true;
- } else if ("".equals(schema)) {
- foundEmpty = true;
- } else if ("pg_catalog".equals(schema)) {
- foundPGCatalog = true;
- }
- }
- rs.close();
- if (TestUtil.haveMinimumServerVersion(con,"7.3")) {
- assertTrue(count >= 2);
- assertTrue(foundPublic);
- assertTrue(foundPGCatalog);
- assertTrue(!foundEmpty);
- } else {
- assertEquals(count,1);
- assertTrue(foundEmpty);
- assertTrue(!foundPublic);
- assertTrue(!foundPGCatalog);
- }
- } catch (SQLException sqle) {
- fail(sqle.getMessage());
- }
- }
-
-}
+++ /dev/null
-package org.postgresql.test.jdbc2;
-
-import org.postgresql.test.TestUtil;
-import junit.framework.TestCase;
-import java.sql.*;
-
-/*
- * $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/test/jdbc2/DateTest.java,v 1.7 2003/11/29 22:41:23 pgsql Exp $
- *
- * Some simple tests based on problems reported by users. Hopefully these will
- * help prevent previous problems from re-occuring ;-)
- *
- */
-public class DateTest extends TestCase
-{
-
- private Connection con;
- private boolean testingSetDate = false;
-
- public DateTest(String name)
- {
- super(name);
- }
-
- protected void setUp() throws Exception
- {
- con = TestUtil.openDB();
- TestUtil.createTable(con, "testdate", "dt date");
- }
-
- protected void tearDown() throws Exception
- {
- TestUtil.dropTable(con, "testdate");
- TestUtil.closeDB(con);
- }
-
- /*
- * Tests the time methods in ResultSet
- */
- public void testGetDate()
- {
- try
- {
- Statement stmt = con.createStatement();
-
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL("testdate", "'1950-02-07'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL("testdate", "'1970-06-02'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL("testdate", "'1999-08-11'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL("testdate", "'2001-02-13'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL("testdate", "'1950-04-02'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL("testdate", "'1970-11-30'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL("testdate", "'1988-01-01'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL("testdate", "'2003-07-09'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL("testdate", "'1934-02-28'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL("testdate", "'1969-04-03'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL("testdate", "'1982-08-03'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL("testdate", "'2012-03-15'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL("testdate", "'1912-05-01'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL("testdate", "'1971-12-15'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL("testdate", "'1984-12-03'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL("testdate", "'2000-01-01'")));
-
- /* dateTest() contains all of the tests */
- dateTest();
-
- assertEquals(16, stmt.executeUpdate("DELETE FROM " + "testdate"));
- stmt.close();
- }
- catch (Exception ex)
- {
- fail(ex.getMessage());
- }
- }
-
- /*
- * Tests the time methods in PreparedStatement
- */
- public void testSetDate()
- {
- try
- {
- Statement stmt = con.createStatement();
- PreparedStatement ps = con.prepareStatement(TestUtil.insertSQL("testdate", "?"));
-
- ps.setDate(1, makeDate(1950, 2, 7));
- assertEquals(1, ps.executeUpdate());
-
- ps.setDate(1, makeDate(1970, 6, 2));
- assertEquals(1, ps.executeUpdate());
-
- ps.setDate(1, makeDate(1999, 8, 11));
- assertEquals(1, ps.executeUpdate());
-
- ps.setDate(1, makeDate(2001, 2, 13));
- assertEquals(1, ps.executeUpdate());
-
- ps.setObject(1, java.sql.Timestamp.valueOf("1950-04-02 12:00:00"), java.sql.Types.DATE);
- assertEquals(1, ps.executeUpdate());
-
- ps.setObject(1, java.sql.Timestamp.valueOf("1970-11-30 3:00:00"), java.sql.Types.DATE);
- assertEquals(1, ps.executeUpdate());
-
- ps.setObject(1, java.sql.Timestamp.valueOf("1988-1-1 13:00:00"), java.sql.Types.DATE);
- assertEquals(1, ps.executeUpdate());
-
- ps.setObject(1, java.sql.Timestamp.valueOf("2003-07-09 12:00:00"), java.sql.Types.DATE);
- assertEquals(1, ps.executeUpdate());
-
- ps.setObject(1, "1934-02-28", java.sql.Types.DATE);
- assertEquals(1, ps.executeUpdate());
-
- ps.setObject(1, "1969-04-3", java.sql.Types.DATE);
- assertEquals(1, ps.executeUpdate());
-
- ps.setObject(1, "1982-08-03", java.sql.Types.DATE);
- assertEquals(1, ps.executeUpdate());
-
- ps.setObject(1, "2012-3-15", java.sql.Types.DATE);
- assertEquals(1, ps.executeUpdate());
-
- ps.setObject(1, java.sql.Date.valueOf("1912-5-1"), java.sql.Types.DATE);
- assertEquals(1, ps.executeUpdate());
-
- ps.setObject(1, java.sql.Date.valueOf("1971-12-15"), java.sql.Types.DATE);
- assertEquals(1, ps.executeUpdate());
-
- ps.setObject(1, java.sql.Date.valueOf("1984-12-03"), java.sql.Types.DATE);
- assertEquals(1, ps.executeUpdate());
-
- ps.setObject(1, java.sql.Date.valueOf("2000-1-1"), java.sql.Types.DATE);
- assertEquals(1, ps.executeUpdate());
-
- ps.setObject(1, "1944-4-04-01", java.sql.Types.DATE);
- assertEquals(1, ps.executeUpdate());
-
- ps.setObject(1, "1970-01-1-10", java.sql.Types.DATE);
- assertEquals(1, ps.executeUpdate());
-
- ps.setObject(1, "1982-12-14+13", java.sql.Types.DATE);
- assertEquals(1, ps.executeUpdate());
-
- ps.setObject(1, "2010-08-3+05", java.sql.Types.DATE);
- assertEquals(1, ps.executeUpdate());
-
- ps.close();
-
- // Need to set a flag so that the method knows there is an extra test.
- testingSetDate = true;
- // Fall through helper
- dateTest();
- testingSetDate = false;
-
- assertEquals(20, stmt.executeUpdate("DELETE FROM testdate"));
- stmt.close();
- }
- catch (Exception ex)
- {
- fail(ex.getMessage());
- }
- }
-
- /*
- * Helper for the date tests. It tests what should be in the db
- */
- private void dateTest() throws SQLException
- {
- Statement st = con.createStatement();
- ResultSet rs;
- java.sql.Date d;
-
- rs = st.executeQuery(TestUtil.selectSQL("testdate", "dt"));
- assertNotNull(rs);
-
- assertTrue(rs.next());
- d = rs.getDate(1);
- assertNotNull(d);
- assertEquals(d, makeDate(1950, 2, 7));
-
- assertTrue(rs.next());
- d = rs.getDate(1);
- assertNotNull(d);
- assertEquals(d, makeDate(1970, 6, 2));
-
- assertTrue(rs.next());
- d = rs.getDate(1);
- assertNotNull(d);
- assertEquals(d, makeDate(1999, 8, 11));
-
- assertTrue(rs.next());
- d = rs.getDate(1);
- assertNotNull(d);
- assertEquals(d, makeDate(2001, 2, 13));
-
- assertTrue(rs.next());
- d = rs.getDate(1);
- assertNotNull(d);
- assertEquals(d, makeDate(1950, 4, 2));
-
- assertTrue(rs.next());
- d = rs.getDate(1);
- assertNotNull(d);
- assertEquals(d, makeDate(1970, 11, 30));
-
- assertTrue(rs.next());
- d = rs.getDate(1);
- assertNotNull(d);
- assertEquals(d, makeDate(1988, 1, 1));
-
- assertTrue(rs.next());
- d = rs.getDate(1);
- assertNotNull(d);
- assertEquals(d, makeDate(2003, 7, 9));
-
- assertTrue(rs.next());
- d = rs.getDate(1);
- assertNotNull(d);
- assertEquals(d, makeDate(1934, 2, 28));
-
- assertTrue(rs.next());
- d = rs.getDate(1);
- assertNotNull(d);
- assertEquals(d, makeDate(1969, 4, 3));
-
- assertTrue(rs.next());
- d = rs.getDate(1);
- assertNotNull(d);
- assertEquals(d, makeDate(1982, 8, 3));
-
- assertTrue(rs.next());
- d = rs.getDate(1);
- assertNotNull(d);
- assertEquals(d, makeDate(2012, 3, 15));
-
- assertTrue(rs.next());
- d = rs.getDate(1);
- assertNotNull(d);
- assertEquals(d, makeDate(1912, 5, 1));
-
- assertTrue(rs.next());
- d = rs.getDate(1);
- assertNotNull(d);
- assertEquals(d, makeDate(1971, 12, 15));
-
- assertTrue(rs.next());
- d = rs.getDate(1);
- assertNotNull(d);
- assertEquals(d, makeDate(1984, 12, 3));
-
- assertTrue(rs.next());
- d = rs.getDate(1);
- assertNotNull(d);
- assertEquals(d, makeDate(2000, 1, 1));
-
- //now we have to convert the date, cause I fed it a timezone. IF it used it. hence the check
- if (testingSetDate)
- {
- assertTrue(rs.next());
- d = rs.getDate(1);
- assertNotNull(d);
- java.sql.Date tmpDate = java.sql.Date.valueOf("1944-4-4");
- int localoffset = java.util.Calendar.getInstance().getTimeZone().getRawOffset();
- if (java.util.Calendar.getInstance().getTimeZone().inDaylightTime(tmpDate))
- {
- localoffset += 60 * 60 * 1000;
- }
- int Dateoffset = 60 * 60 * 1000;
- tmpDate.setTime(tmpDate.getTime() + Dateoffset + localoffset);
- assertEquals(d, makeDate(tmpDate.getYear() + 1900, tmpDate.getMonth()+1, tmpDate.getDate()));
-
- assertTrue(rs.next());
- d = rs.getDate(1);
- assertNotNull(d);
- tmpDate = java.sql.Date.valueOf("1970-1-1");
- localoffset = java.util.Calendar.getInstance().getTimeZone().getRawOffset();
- if (java.util.Calendar.getInstance().getTimeZone().inDaylightTime(tmpDate))
- {
- localoffset += 60 * 60 * 1000;
- }
- Dateoffset = 10 * 60 * 60 * 1000;
- tmpDate.setTime(tmpDate.getTime() + Dateoffset + localoffset);
- assertEquals(d, makeDate(tmpDate.getYear() + 1900, tmpDate.getMonth()+1, tmpDate.getDate()));
-
- assertTrue(rs.next());
- d = rs.getDate(1);
- assertNotNull(d);
- tmpDate = java.sql.Date.valueOf("1982-12-14");
- localoffset = java.util.Calendar.getInstance().getTimeZone().getRawOffset();
- if (java.util.Calendar.getInstance().getTimeZone().inDaylightTime(tmpDate))
- {
- localoffset += 60 * 60 * 1000;
- }
- Dateoffset = -13 * 60 * 60 * 1000;
- tmpDate.setTime(tmpDate.getTime() + Dateoffset + localoffset);
- assertEquals(d, makeDate(tmpDate.getYear() + 1900, tmpDate.getMonth()+1, tmpDate.getDate()));
-
- assertTrue(rs.next());
- d = rs.getDate(1);
- assertNotNull(d);
- tmpDate = java.sql.Date.valueOf("2010-08-03");
- localoffset = java.util.Calendar.getInstance().getTimeZone().getRawOffset();
- if (java.util.Calendar.getInstance().getTimeZone().inDaylightTime(tmpDate))
- {
- localoffset += 60 * 60 * 1000;
- }
- Dateoffset = -5 * 60 * 60 * 1000;
- tmpDate.setTime(tmpDate.getTime() + Dateoffset + localoffset);
- assertEquals(d, makeDate(tmpDate.getYear() + 1900, tmpDate.getMonth()+1, tmpDate.getDate()));
- }
-
- assertTrue(!rs.next());
-
- rs.close();
- st.close();
- }
-
- private java.sql.Date makeDate(int y, int m, int d)
- {
- return java.sql.Date.valueOf(TestUtil.fix(y, 4) + "-" +
- TestUtil.fix(m, 2) + "-" +
- TestUtil.fix(d, 2));
- }
-}
+++ /dev/null
-package org.postgresql.test.jdbc2;
-
-import org.postgresql.test.TestUtil;
-import junit.framework.TestCase;
-import java.sql.*;
-
-/*
- * $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/test/jdbc2/DriverTest.java,v 1.7 2003/11/29 22:41:23 pgsql Exp $
- *
- * Tests the dynamically created class org.postgresql.Driver
- *
- */
-public class DriverTest extends TestCase
-{
-
- public DriverTest(String name)
- {
- super(name);
- }
-
- /*
- * This tests the acceptsURL() method with a couple of good and badly formed
- * jdbc urls
- */
- public void testAcceptsURL()
- {
- try
- {
-
- // Load the driver (note clients should never do it this way!)
- org.postgresql.Driver drv = new org.postgresql.Driver();
- assertNotNull(drv);
-
- // These are always correct
- assertTrue(drv.acceptsURL("jdbc:postgresql:test"));
- assertTrue(drv.acceptsURL("jdbc:postgresql://localhost/test"));
- assertTrue(drv.acceptsURL("jdbc:postgresql://localhost:5432/test"));
- assertTrue(drv.acceptsURL("jdbc:postgresql://127.0.0.1/anydbname"));
- assertTrue(drv.acceptsURL("jdbc:postgresql://127.0.0.1:5433/hidden"));
- assertTrue(drv.acceptsURL("jdbc:postgresql://[::1]:5740/db"));
-
- // Badly formatted url's
- assertTrue(!drv.acceptsURL("jdbc:postgres:test"));
- assertTrue(!drv.acceptsURL("postgresql:test"));
- assertTrue(!drv.acceptsURL("db"));
-
- }
- catch (SQLException ex)
- {
- fail(ex.getMessage());
- }
- }
-
- /*
- * Tests parseURL (internal)
- */
- /*
- * Tests the connect method by connecting to the test database
- */
- public void testConnect()
- {
- Connection con = null;
- try
- {
- Class.forName("org.postgresql.Driver");
-
- // Test with the url, username & password
- con = DriverManager.getConnection(TestUtil.getURL(), TestUtil.getUser(), TestUtil.getPassword());
- assertNotNull(con);
- con.close();
-
- // Test with the username in the url
- con = DriverManager.getConnection(TestUtil.getURL() + "?user=" + TestUtil.getUser() + "&password=" + TestUtil.getPassword());
- assertNotNull(con);
- con.close();
- }
- catch (ClassNotFoundException ex)
- {
- fail(ex.getMessage());
- }
- catch (SQLException ex)
- {
- fail(ex.getMessage());
- }
- }
-}
+++ /dev/null
-
-package org.postgresql.test.jdbc2;
-
-import junit.framework.*;
-import org.postgresql.core.Encoding;
-import java.io.*;
-
-/*
- * Tests for the Encoding class.
- *
- * $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/test/jdbc2/EncodingTest.java,v 1.5 2003/11/29 22:41:23 pgsql Exp $
- */
-
-
-public class EncodingTest extends TestCase
-{
-
- public EncodingTest(String name)
- {
- super(name);
- }
-
- public void testCreation() throws Exception
- {
- Encoding encoding;
- encoding = Encoding.getEncoding("UNICODE", null);
- assertEquals("UTF", encoding.name().substring(0, 3).toUpperCase());
- encoding = Encoding.getEncoding("SQL_ASCII", null);
- assertTrue(encoding.name().toUpperCase().indexOf("ASCII") != -1);
- assertEquals("When encoding is unknown the default encoding should be used",
- Encoding.defaultEncoding(),
- Encoding.getEncoding("UNKNOWN", null));
- encoding = Encoding.getEncoding("SQL_ASCII", "utf-8");
- assertTrue("Encoding passed in by the user should be preferred",
- encoding.name().toUpperCase().indexOf("UTF") != -1);
- }
-
- public void testTransformations() throws Exception
- {
- Encoding encoding = Encoding.getEncoding("UNICODE", null);
- assertEquals("ab", encoding.decode(new byte[] { 97, 98 }));
-
- assertEquals(2, encoding.encode("ab").length);
- assertEquals(97, encoding.encode("a")[0]);
- assertEquals(98, encoding.encode("b")[0]);
-
- encoding = Encoding.defaultEncoding();
- assertEquals("a".getBytes()[0], encoding.encode("a")[0]);
- assertEquals(new String(new byte[] { 97 }),
- encoding.decode(new byte[] { 97 }));
- }
-
- public void testReader() throws Exception
- {
- Encoding encoding = Encoding.getEncoding("SQL_ASCII", null);
- InputStream stream = new ByteArrayInputStream(new byte[] { 97, 98 });
- Reader reader = encoding.getDecodingReader(stream);
- assertEquals(97, reader.read());
- assertEquals(98, reader.read());
- assertEquals( -1, reader.read());
- }
-}
+++ /dev/null
-package org.postgresql.test.jdbc2;
-
-import org.postgresql.test.TestUtil;
-import java.sql.Connection;
-import java.sql.ResultSet;
-import java.sql.Statement;
-
-import junit.framework.TestCase;
-
-/*
- * $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/test/jdbc2/JBuilderTest.java,v 1.9 2003/11/29 22:41:23 pgsql Exp $
- *
- * Some simple tests to check that the required components needed for JBuilder
- * stay working
- *
- */
-public class JBuilderTest extends TestCase
-{
-
- public JBuilderTest(String name)
- {
- super(name);
- }
-
- // Set up the fixture for this testcase: the tables for this test.
- protected void setUp() throws Exception
- {
- Connection con = TestUtil.openDB();
-
- TestUtil.createTable( con, "test_c",
- "source text,cost money,imageid int4" );
-
- TestUtil.closeDB(con);
- }
-
- // Tear down the fixture for this test case.
- protected void tearDown() throws Exception
- {
- Connection con = TestUtil.openDB();
- TestUtil.dropTable(con, "test_c");
- TestUtil.closeDB(con);
- }
-
- /*
- * This tests that Money types work. JDBCExplorer barfs if this fails.
- */
- public void testMoney()
- {
- try
- {
- Connection con = TestUtil.openDB();
-
- Statement st = con.createStatement();
- ResultSet rs = st.executeQuery("select cost from test_c");
- assertNotNull(rs);
-
- while (rs.next())
- {
- rs.getDouble(1);
- }
-
- rs.close();
- st.close();
-
- TestUtil.closeDB(con);
- }
- catch (Exception ex)
- {
- fail(ex.getMessage());
- }
- }
-}
+++ /dev/null
-package org.postgresql.test.jdbc2;
-
-import junit.framework.TestSuite;
-
-/*
- * Executes all known tests for JDBC2 and includes some utility methods.
- */
-public class Jdbc2TestSuite extends TestSuite
-{
-
- /*
- * The main entry point for JUnit
- */
- public static TestSuite suite()
- {
- TestSuite suite = new TestSuite();
-
- //
- // Add one line per class in our test cases. These should be in order of
- // complexity.
-
- // ANTTest should be first as it ensures that test parameters are
- // being sent to the suite.
- //
- suite.addTestSuite(ANTTest.class);
-
- // Basic Driver internals
- suite.addTestSuite(DriverTest.class);
- suite.addTestSuite(ConnectionTest.class);
- suite.addTestSuite(DatabaseMetaDataTest.class);
- suite.addTestSuite(DatabaseMetaDataPropertiesTest.class);
- suite.addTestSuite(EncodingTest.class);
-
- // Connectivity/Protocols
-
- // ResultSet
- suite.addTestSuite(ResultSetTest.class);
-
- // Time, Date, Timestamp
- suite.addTestSuite(DateTest.class);
- suite.addTestSuite(TimeTest.class);
- suite.addTestSuite(TimestampTest.class);
-
- // PreparedStatement
-
- // ServerSide Prepared Statements
- suite.addTestSuite(ServerPreparedStmtTest.class);
-
- // BatchExecute
- suite.addTestSuite(BatchExecuteTest.class);
-
-
- // Other misc tests, based on previous problems users have had or specific
- // features some applications require.
- suite.addTestSuite(JBuilderTest.class);
- suite.addTestSuite(MiscTest.class);
-
- // Fastpath/LargeObject
- suite.addTestSuite(BlobTest.class);
- suite.addTestSuite(OID74Test.class);
-
- suite.addTestSuite(UpdateableResultTest.class );
-
- suite.addTestSuite(CallableStmtTest.class );
- suite.addTestSuite(CursorFetchTest.class);
-
- // That's all folks
- return suite;
- }
-}
+++ /dev/null
-package org.postgresql.test.jdbc2;
-
-import org.postgresql.test.TestUtil;
-import junit.framework.TestCase;
-import java.sql.*;
-import java.io.*;
-
-/*
- * $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/test/jdbc2/MiscTest.java,v 1.12 2003/12/11 15:11:43 davec Exp $
- *
- * Some simple tests based on problems reported by users. Hopefully these will
- * help prevent previous problems from re-occuring ;-)
- *
- */
-public class MiscTest extends TestCase
-{
-
- public MiscTest(String name)
- {
- super(name);
- }
-
- /*
- * Some versions of the driver would return rs as a null?
- *
- * Sasha was having this problem.
- *
- * Added Feb 13 2001
- */
- public void testDatabaseSelectNullBug()
- {
- try
- {
- Connection con = TestUtil.openDB();
-
- Statement st = con.createStatement();
- ResultSet rs = st.executeQuery("select datname from pg_database");
- assertNotNull(rs);
-
- while (rs.next())
- {
- rs.getString(1);
- }
-
- rs.close();
- st.close();
-
- TestUtil.closeDB(con);
- }
- catch (Exception ex)
- {
- fail(ex.getMessage());
- }
- }
-
- public void testError()
- {
- Connection con = TestUtil.openDB();
- try
- {
-
- // transaction mode
- con.setAutoCommit(false);
- Statement stmt = con.createStatement();
- stmt.execute("select 1/0");
- fail( "Should not execute this, as a SQLException s/b thrown" );
- con.commit();
- }
- catch ( SQLException ex )
- {
- // Verify that the SQLException is serializable.
- try {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ObjectOutputStream oos = new ObjectOutputStream(baos);
- oos.writeObject(ex);
- oos.close();
- } catch (IOException ioe) {
- fail(ioe.getMessage());
- }
- }
- try
- {
- con.commit();
- con.close();
- }
- catch ( Exception ex)
- {}
- }
-
- public void xtestLocking()
- {
-
- try
- {
- Connection con = TestUtil.openDB();
- Connection con2 = TestUtil.openDB();
-
- TestUtil.createTable(con, "test_lock", "name text");
- Statement st = con.createStatement();
- Statement st2 = con2.createStatement();
- con.setAutoCommit(false);
- st.execute("lock table test_lock");
- st2.executeUpdate( "insert into test_lock ( name ) values ('hello')" );
- con.commit();
- TestUtil.dropTable(con, "test_lock");
- con.close();
- }
- catch ( Exception ex )
- {
- fail( ex.getMessage() );
- }
- }
-}
+++ /dev/null
-package org.postgresql.test.jdbc2;
-
-import org.postgresql.test.TestUtil;
-import junit.framework.TestCase;
-import java.io.*;
-import java.sql.*;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.util.Properties;
-import java.sql.*;
-
-/**
- * User: alexei
- * Date: 17-Dec-2003
- * Time: 11:01:44
- * @version $Id: OID74Test.java,v 1.3 2003/12/18 04:08:30 davec Exp $
- */
-public class OID74Test extends TestCase
-{
-
- public OID74Test( String name )
- {
- super(name);
- }
- public void setUp() throws Exception
- {
- }
- public void tearDown() throws Exception
- {
- }
- public void testBinaryStream() throws SQLException
- {
- //set up conection here
- Properties props = new Properties();
- props.setProperty("compatible","7.1");
- Connection c = TestUtil.openDB(props);
- c.setAutoCommit(false);
-
- TestUtil.createTable(c,"temp","col oid");
-
- Statement st = null;
-
- PreparedStatement pstmt = null;
- try
- {
-
- pstmt = c.prepareStatement("INSERT INTO temp VALUES (?)");
- pstmt.setBinaryStream(1, new ByteArrayInputStream(new byte[]{1, 2, 3, 4, 5}), 5);
- assertTrue( (pstmt.executeUpdate() == 1) );
- pstmt.close();
-
- pstmt = c.prepareStatement("SELECT col FROM temp LIMIT 1");
- ResultSet rs = pstmt.executeQuery();
-
- assertTrue("No results from query", rs.next() );
-
- InputStream in = rs.getBinaryStream(1);
- int data;
- int i = 1;
- while ((data = in.read()) != -1)
- assertEquals(data,i++);
- rs.close();
- pstmt.close();
- c.createStatement().executeUpdate("DELETE FROM temp");
- c.commit();
- }
- catch ( IOException ioex )
- {
- fail( ioex.getMessage() );
- }
- catch (SQLException ex)
- {
- fail( ex.getMessage() );
- }
-
- TestUtil.dropTable(c,"temp");
- TestUtil.closeDB(c);
- }
-}
+++ /dev/null
-package org.postgresql.test.jdbc2;
-
-import org.postgresql.test.TestUtil;
-import java.sql.CallableStatement;
-import java.sql.Connection;
-import java.sql.ResultSet;
-import java.sql.Statement;
-import java.sql.Types;
-
-import junit.framework.TestCase;
-
-/*
- * RefCursor ResultSet tests.
- * This test case is basically the same as the ResultSet test case.
- *
- * @author Nic Ferrier
- */
-public class RefCursorTest extends TestCase
-{
- private Connection con;
-
- public RefCursorTest(String name)
- {
- super(name);
- }
-
- protected void setUp() throws Exception
- {
- // this is the same as the ResultSet setup.
- con = TestUtil.openDB();
- Statement stmt = con.createStatement();
-
- TestUtil.createTable(con, "testrs", "id integer");
-
- stmt.executeUpdate("INSERT INTO testrs VALUES (1)");
- stmt.executeUpdate("INSERT INTO testrs VALUES (2)");
- stmt.executeUpdate("INSERT INTO testrs VALUES (3)");
- stmt.executeUpdate("INSERT INTO testrs VALUES (4)");
- stmt.executeUpdate("INSERT INTO testrs VALUES (6)");
- stmt.executeUpdate("INSERT INTO testrs VALUES (9)");
-
-
- // Create the functions.
- stmt.execute ("CREATE OR REPLACE FUNCTION testspg__getRefcursor () RETURNS refcursor AS '"
- + "declare v_resset; begin open v_resset for select id from testrs order by id; "
- + "return v_resset; end;' LANGUAGE 'plpgsql';");
- stmt.execute ("CREATE OR REPLACE FUNCTION testspg__getEmptyRefcursor () RETURNS refcursor AS '"
- + "declare v_resset; begin open v_resset for select id from testrs where id < 1 order by id; "
- + "return v_resset; end;' LANGUAGE 'plpgsql';");
- stmt.close();
- }
-
- protected void tearDown() throws Exception
- {
- Statement stmt = con.createStatement ();
- stmt.execute ("drop FUNCTION testspg__getRefcursor ();");
- stmt.execute ("drop FUNCTION testspg__getEmptyRefcursor ();");
- TestUtil.dropTable(con, "testrs");
- TestUtil.closeDB(con);
- }
-
- public void testResult() throws Exception
- {
- CallableStatement call = con.prepareCall("{ ? = call testspg__getRefcursor () }");
- call.registerOutParameter(1, Types.OTHER);
- call.execute();
- ResultSet rs = (ResultSet) call.getObject(1);
-
- assertTrue(rs.next());
- assertTrue(rs.getInt(1) == 1);
-
- assertTrue(rs.next());
- assertTrue(rs.getInt(1) == 2);
-
- assertTrue(rs.next());
- assertTrue(rs.getInt(1) == 3);
-
- assertTrue(rs.next());
- assertTrue(rs.getInt(1) == 4);
-
- assertTrue(rs.next());
- assertTrue(rs.getInt(1) == 6);
-
- assertTrue(rs.next());
- assertTrue(rs.getInt(1) == 9);
-
- assertTrue(!rs.next());
-
- call.close();
- }
-
-
- public void testEmptyResult() throws Exception
- {
- CallableStatement call = con.prepareCall("{ ? = call testspg__getRefcursor () }");
- call.registerOutParameter(1, Types.OTHER);
- call.execute();
-
- ResultSet rs = (ResultSet) call.getObject(1);
- assertTrue(!rs.next());
-
- call.close();
- }
-}
+++ /dev/null
-package org.postgresql.test.jdbc2;
-
-import org.postgresql.test.TestUtil;
-import java.sql.Connection;
-import java.sql.ResultSet;
-import java.sql.Statement;
-
-import junit.framework.TestCase;
-
-/*
- * ResultSet tests.
- */
-public class ResultSetTest extends TestCase
-{
- private Connection con;
-
- public ResultSetTest(String name)
- {
- super(name);
- }
-
- protected void setUp() throws Exception
- {
- con = TestUtil.openDB();
- Statement stmt = con.createStatement();
-
- TestUtil.createTable(con, "testrs", "id integer");
-
- stmt.executeUpdate("INSERT INTO testrs VALUES (1)");
- stmt.executeUpdate("INSERT INTO testrs VALUES (2)");
- stmt.executeUpdate("INSERT INTO testrs VALUES (3)");
- stmt.executeUpdate("INSERT INTO testrs VALUES (4)");
- stmt.executeUpdate("INSERT INTO testrs VALUES (6)");
- stmt.executeUpdate("INSERT INTO testrs VALUES (9)");
-
- TestUtil.createTable(con, "teststring", "a text");
- stmt.executeUpdate("INSERT INTO teststring VALUES ('12345')");
-
- TestUtil.createTable(con, "testint", "a int");
- stmt.executeUpdate("INSERT INTO testint VALUES (12345)");
-
- TestUtil.createTable(con, "testbool", "a boolean");
-
- TestUtil.createTable(con, "testbit", "a bit");
-
- TestUtil.createTable(con, "testboolstring", "a varchar(30)");
-
- stmt.executeUpdate("INSERT INTO testboolstring VALUES('true')");
- stmt.executeUpdate("INSERT INTO testboolstring VALUES('false')");
- stmt.executeUpdate("INSERT INTO testboolstring VALUES('t')");
- stmt.executeUpdate("INSERT INTO testboolstring VALUES('f')");
- stmt.executeUpdate("INSERT INTO testboolstring VALUES('1.0')");
- stmt.executeUpdate("INSERT INTO testboolstring VALUES('0.0')");
- stmt.executeUpdate("INSERT INTO testboolstring VALUES('TRUE')");
- stmt.executeUpdate("INSERT INTO testboolstring VALUES('this is not true')");
-
- TestUtil.createTable(con, "testnumeric", "a numeric");
- stmt.executeUpdate("INSERT INTO testnumeric VALUES('1.0')");
- stmt.executeUpdate("INSERT INTO testnumeric VALUES('0.0')");
- stmt.executeUpdate("INSERT INTO testnumeric VALUES('-1.0')");
- stmt.executeUpdate("INSERT INTO testnumeric VALUES('1.2')");
- stmt.executeUpdate("INSERT INTO testnumeric VALUES('99999.2')");
- stmt.executeUpdate("INSERT INTO testnumeric VALUES('99999')");
- stmt.executeUpdate("INSERT INTO testnumeric VALUES('-2.5')");
- stmt.executeUpdate("INSERT INTO testnumeric VALUES('-99999.2')");
- stmt.executeUpdate("INSERT INTO testnumeric VALUES('-99999')");
-
- stmt.close();
-
-
- stmt.close();
- }
-
- protected void tearDown() throws Exception
- {
- TestUtil.dropTable(con, "testrs");
- TestUtil.dropTable(con, "teststring");
- TestUtil.dropTable(con, "testint");
- TestUtil.dropTable(con, "testbool");
- TestUtil.dropTable(con, "testbit");
- TestUtil.dropTable(con, "testboolstring");
- TestUtil.dropTable(con, "testnumeric");
- TestUtil.closeDB(con);
- }
-
- public void testBackward() throws Exception
- {
- Statement stmt = con.createStatement();
- ResultSet rs = stmt.executeQuery("SELECT * FROM testrs");
- rs.afterLast();
- assertTrue(rs.previous());
- rs.close();
- stmt.close();
- }
-
- public void testAbsolute() throws Exception
- {
- Statement stmt = con.createStatement();
- ResultSet rs = stmt.executeQuery("SELECT * FROM testrs");
-
- assertTrue(rs.absolute( -1));
- assertEquals(6, rs.getRow());
-
- assertTrue(rs.absolute(1));
- assertEquals(1, rs.getRow());
-
- assertTrue(!rs.absolute( -10));
- assertEquals(0, rs.getRow());
- assertTrue(rs.next());
- assertEquals(1, rs.getRow());
-
- assertTrue(!rs.absolute(10));
- assertEquals(0, rs.getRow());
- assertTrue(rs.previous());
- assertEquals(6, rs.getRow());
-
- stmt.close();
- }
- public void testEmptyResult()
- {
- try
- {
- Statement stmt = con.createStatement();
- ResultSet rs = stmt.executeQuery("SELECT * FROM testrs where id=100");
- rs.beforeFirst();
- rs.afterLast();
- assertTrue(!rs.first());
- assertTrue(!rs.last());
- assertTrue(!rs.next());
-
-
- }
- catch ( Exception ex )
- {
- fail( ex.getMessage() );
- }
-
- }
-
- public void testMaxFieldSize() throws Exception
- {
- Statement stmt = con.createStatement();
- stmt.setMaxFieldSize(2);
-
- ResultSet rs = stmt.executeQuery("select * from testint");
-
- //max should not apply to the following since per the spec
- //it should apply only to binary and char/varchar columns
- rs.next();
- assertEquals(rs.getString(1),"12345");
- assertEquals(new String(rs.getBytes(1)), "12345");
-
- //max should apply to the following since the column is
- //a varchar column
- rs = stmt.executeQuery("select * from teststring");
- rs.next();
- assertEquals(rs.getString(1), "12");
- assertEquals(new String(rs.getBytes(1)), "12");
- }
-
- public void booleanTests(boolean useServerPrepare) throws Exception
- {
- java.sql.PreparedStatement pstmt = con.prepareStatement("insert into testbool values (?)");
- if (useServerPrepare)
- ((org.postgresql.PGStatement)pstmt).setUseServerPrepare(true);
-
- pstmt.setObject(1, new Float(0), java.sql.Types.BIT);
- pstmt.executeUpdate();
-
- pstmt.setObject(1, new Float(1), java.sql.Types.BIT);
- pstmt.executeUpdate();
-
- pstmt.setObject(1, "False", java.sql.Types.BIT);
- pstmt.executeUpdate();
-
- pstmt.setObject(1, "True", java.sql.Types.BIT);
- pstmt.executeUpdate();
-
- ResultSet rs = con.createStatement().executeQuery("select * from testbool");
- for (int i = 0; i<2; i++)
- {
- assertTrue(rs.next());
- assertEquals(false, rs.getBoolean(1));
- assertTrue(rs.next());
- assertEquals(true, rs.getBoolean(1));
- }
-
- pstmt = con.prepareStatement("insert into testbit values (?)");
-
- pstmt.setObject(1, new Float(0), java.sql.Types.BIT);
- pstmt.executeUpdate();
-
- pstmt.setObject(1, new Float(1), java.sql.Types.BIT);
- pstmt.executeUpdate();
-
- pstmt.setObject(1, "false", java.sql.Types.BIT);
- pstmt.executeUpdate();
-
- pstmt.setObject(1, "true", java.sql.Types.BIT);
- pstmt.executeUpdate();
-
- rs = con.createStatement().executeQuery("select * from testbit");
-
- for (int i = 0;i<2; i++)
- {
- assertTrue(rs.next());
- assertEquals(false, rs.getBoolean(1));
- assertTrue(rs.next());
- assertEquals(true, rs.getBoolean(1));
- }
-
- rs = con.createStatement().executeQuery("select * from testboolstring");
-
- for (int i = 0;i<4; i++)
- {
- assertTrue(rs.next());
- assertEquals(true, rs.getBoolean(1));
- assertTrue(rs.next());
- assertEquals(false, rs.getBoolean(1));
- }
- }
-
- public void testBoolean() throws Exception
- {
- booleanTests(true);
- booleanTests(false);
- }
-
- public void testgetByte() throws Exception
- {
- ResultSet rs = con.createStatement().executeQuery("select * from testnumeric");
- boolean thrown = false;
-
- assertTrue(rs.next());
- assertEquals(1,rs.getByte(1));
-
- assertTrue(rs.next());
- assertEquals(0,rs.getByte(1));
-
- assertTrue(rs.next());
- assertEquals(-1,rs.getByte(1));
-
- while (rs.next())
- {
- thrown = false;
- try
- {
- rs.getByte(1);
- }
- catch (Exception e)
- {
- thrown = true;
- }
- if (!thrown)
- fail("Exception expected.");
- }
- }
-
- public void testgetShort() throws Exception
- {
- ResultSet rs = con.createStatement().executeQuery("select * from testnumeric");
- boolean thrown = false;
-
- assertTrue(rs.next());
- assertEquals(1,rs.getShort(1));
-
- assertTrue(rs.next());
- assertEquals(0,rs.getShort(1));
-
- assertTrue(rs.next());
- assertEquals(-1,rs.getShort(1));
-
- while (rs.next())
- {
- thrown = false;
- try
- {
- rs.getShort(1);
- }
- catch (Exception e)
- {
- thrown = true;
- }
- if (!thrown)
- fail("Exception expected.");
- }
- }
-
-}
+++ /dev/null
-package org.postgresql.test.jdbc2;
-
-import org.postgresql.PGStatement;
-import org.postgresql.test.TestUtil;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.Statement;
-
-import junit.framework.TestCase;
-
-/*
- * Tests for using server side prepared statements
- */
-public class ServerPreparedStmtTest extends TestCase
-{
- private Connection con;
-
- public ServerPreparedStmtTest(String name)
- {
- super(name);
- }
-
- protected void setUp() throws Exception
- {
- con = TestUtil.openDB();
- Statement stmt = con.createStatement();
-
- TestUtil.createTable(con, "testsps", "id integer, value boolean");
-
- stmt.executeUpdate("INSERT INTO testsps VALUES (1,'t')");
- stmt.executeUpdate("INSERT INTO testsps VALUES (2,'t')");
- stmt.executeUpdate("INSERT INTO testsps VALUES (3,'t')");
- stmt.executeUpdate("INSERT INTO testsps VALUES (4,'t')");
- stmt.executeUpdate("INSERT INTO testsps VALUES (6,'t')");
- stmt.executeUpdate("INSERT INTO testsps VALUES (9,'f')");
-
- stmt.close();
- }
-
- protected void tearDown() throws Exception
- {
- TestUtil.dropTable(con, "testsps");
- TestUtil.closeDB(con);
- }
-
- public void testPreparedStatementsNoBinds() throws Exception
- {
- PreparedStatement pstmt = con.prepareStatement("SELECT * FROM testsps WHERE id = 2");
- ((PGStatement)pstmt).setUseServerPrepare(true);
- if (TestUtil.haveMinimumServerVersion(con,"7.3")) {
- assertTrue(((PGStatement)pstmt).isUseServerPrepare());
- } else {
- assertTrue(!((PGStatement)pstmt).isUseServerPrepare());
- }
-
- //Test that basic functionality works
- ResultSet rs = pstmt.executeQuery();
- assertTrue(rs.next());
- assertEquals(2, rs.getInt(1));
- rs.close();
-
- //Verify that subsequent calls still work
- rs = pstmt.executeQuery();
- assertTrue(rs.next());
- assertEquals(2, rs.getInt(1));
- rs.close();
-
- //Verify that using the statement to execute a different query works
- rs = pstmt.executeQuery("SELECT * FROM testsps WHERE id = 9");
- assertTrue(rs.next());
- assertEquals(9, rs.getInt(1));
- rs.close();
-
- ((PGStatement)pstmt).setUseServerPrepare(false);
- assertTrue(!((PGStatement)pstmt).isUseServerPrepare());
-
- //Verify that using the statement still works after turning off prepares
- rs = pstmt.executeQuery("SELECT * FROM testsps WHERE id = 9");
- assertTrue(rs.next());
- assertEquals(9, rs.getInt(1));
- rs.close();
-
- pstmt.close();
- }
-
- public void testPreparedStatementsWithOneBind() throws Exception
- {
- PreparedStatement pstmt = con.prepareStatement("SELECT * FROM testsps WHERE id = ?");
- ((PGStatement)pstmt).setUseServerPrepare(true);
- if (TestUtil.haveMinimumServerVersion(con,"7.3")) {
- assertTrue(((PGStatement)pstmt).isUseServerPrepare());
- } else {
- assertTrue(!((PGStatement)pstmt).isUseServerPrepare());
- }
-
- //Test that basic functionality works
- pstmt.setInt(1,2);
- ResultSet rs = pstmt.executeQuery();
- assertTrue(rs.next());
- assertEquals(2, rs.getInt(1));
- rs.close();
-
- //Verify that subsequent calls still work
- rs = pstmt.executeQuery();
- assertTrue(rs.next());
- assertEquals(2, rs.getInt(1));
- rs.close();
-
- //Verify that using the statement to execute a different query works
- rs = pstmt.executeQuery("SELECT * FROM testsps WHERE id = 9");
- assertTrue(rs.next());
- assertEquals(9, rs.getInt(1));
- rs.close();
-
- ((PGStatement)pstmt).setUseServerPrepare(false);
- assertTrue(!((PGStatement)pstmt).isUseServerPrepare());
-
- //Verify that using the statement still works after turning off prepares
- rs = pstmt.executeQuery("SELECT * FROM testsps WHERE id = 9");
- assertTrue(rs.next());
- assertEquals(9, rs.getInt(1));
- rs.close();
-
- pstmt.close();
- }
-
- // Verify we can bind booleans-as-objects ok.
- public void testBooleanObjectBind() throws Exception
- {
- PreparedStatement pstmt = con.prepareStatement("SELECT * FROM testsps WHERE value = ?");
- ((PGStatement)pstmt).setUseServerPrepare(true);
- if (TestUtil.haveMinimumServerVersion(con,"7.3")) {
- assertTrue(((PGStatement)pstmt).isUseServerPrepare());
- } else {
- assertTrue(!((PGStatement)pstmt).isUseServerPrepare());
- }
-
- pstmt.setObject(1, new Boolean(false), java.sql.Types.BIT);
- ResultSet rs = pstmt.executeQuery();
- assertTrue(rs.next());
- assertEquals(9, rs.getInt(1));
- rs.close();
- }
-
- // Verify we can bind booleans-as-integers ok.
- public void testBooleanIntegerBind() throws Exception
- {
- PreparedStatement pstmt = con.prepareStatement("SELECT * FROM testsps WHERE id = ?");
- ((PGStatement)pstmt).setUseServerPrepare(true);
- if (TestUtil.haveMinimumServerVersion(con,"7.3")) {
- assertTrue(((PGStatement)pstmt).isUseServerPrepare());
- } else {
- assertTrue(!((PGStatement)pstmt).isUseServerPrepare());
- }
-
- pstmt.setObject(1, new Boolean(true), java.sql.Types.INTEGER);
- ResultSet rs = pstmt.executeQuery();
- assertTrue(rs.next());
- assertEquals(1, rs.getInt(1));
- rs.close();
- }
-
- // Verify we can bind booleans-as-native-types ok.
- public void testBooleanBind() throws Exception
- {
- PreparedStatement pstmt = con.prepareStatement("SELECT * FROM testsps WHERE value = ?");
- ((PGStatement)pstmt).setUseServerPrepare(true);
- if (TestUtil.haveMinimumServerVersion(con,"7.3")) {
- assertTrue(((PGStatement)pstmt).isUseServerPrepare());
- } else {
- assertTrue(!((PGStatement)pstmt).isUseServerPrepare());
- }
-
- pstmt.setBoolean(1, false);
- ResultSet rs = pstmt.executeQuery();
- assertTrue(rs.next());
- assertEquals(9, rs.getInt(1));
- rs.close();
- }
-
- public void testPreparedStatementsWithBinds() throws Exception
- {
- PreparedStatement pstmt = con.prepareStatement("SELECT * FROM testsps WHERE id = ? or id = ?");
- ((PGStatement)pstmt).setUseServerPrepare(true);
- if (TestUtil.haveMinimumServerVersion(con,"7.3")) {
- assertTrue(((PGStatement)pstmt).isUseServerPrepare());
- } else {
- assertTrue(!((PGStatement)pstmt).isUseServerPrepare());
- }
-
- //Test that basic functionality works
- //bind different datatypes
- pstmt.setInt(1,2);
- pstmt.setString(2,"2");
- ResultSet rs = pstmt.executeQuery();
- assertTrue(rs.next());
- assertEquals(2, rs.getInt(1));
- rs.close();
-
- //Verify that subsequent calls still work
- rs = pstmt.executeQuery();
- assertTrue(rs.next());
- assertEquals(2, rs.getInt(1));
- rs.close();
-
- pstmt.close();
- }
-
- public void testSPSToggle() throws Exception
- {
- // Verify we can toggle UseServerPrepare safely before a query is executed.
- PreparedStatement pstmt = con.prepareStatement("SELECT * FROM testsps WHERE id = 2");
- ((PGStatement)pstmt).setUseServerPrepare(true);
- ((PGStatement)pstmt).setUseServerPrepare(false);
- }
-
- public void testBytea() throws Exception
- {
- // Verify we can use setBytes() with a server-prepared update.
- try {
- TestUtil.createTable(con, "testsps_bytea", "data bytea");
-
- PreparedStatement pstmt = con.prepareStatement("INSERT INTO testsps_bytea(data) VALUES (?)");
- ((PGStatement)pstmt).setUseServerPrepare(true);
- pstmt.setBytes(1, new byte[100]);
- pstmt.executeUpdate();
- } finally {
- TestUtil.dropTable(con, "testsps_bytea");
- }
- }
-
- // Check statements are not transformed when they shouldn't be.
- public void TODO_FAILS_testCreateTable() throws Exception {
- // CREATE TABLE isn't supported by PREPARE; the driver should realize this and
- // still complete without error.
- PreparedStatement pstmt = con.prepareStatement("CREATE TABLE testsps_bad(data int)");
- ((PGStatement)pstmt).setUseServerPrepare(true);
- pstmt.executeUpdate();
- TestUtil.dropTable(con, "testsps_bad");
- }
-
- public void TODO_FAILS_testMultistatement() throws Exception {
- // Shouldn't try to PREPARE this one, if we do we get:
- // PREPARE x(int,int) AS INSERT .... $1 ; INSERT ... $2 -- syntax error
- try {
- TestUtil.createTable(con, "testsps_multiple", "data int");
- PreparedStatement pstmt = con.prepareStatement("INSERT INTO testsps_multiple(data) VALUES (?); INSERT INTO testsps_multiple(data) VALUES (?)");
- ((PGStatement)pstmt).setUseServerPrepare(true);
- pstmt.setInt(1, 1);
- pstmt.setInt(2, 2);
- pstmt.executeUpdate(); // Two inserts.
-
- pstmt.setInt(1, 3);
- pstmt.setInt(2, 4);
- pstmt.executeUpdate(); // Two more inserts.
-
- ResultSet check = con.createStatement().executeQuery("SELECT COUNT(*) FROM testsps_multiple");
- assertTrue(check.next());
- assertEquals(4, check.getInt(1));
- } finally {
- TestUtil.dropTable(con, "testsps_multiple");
- }
- }
-}
+++ /dev/null
-package org.postgresql.test.jdbc2;
-
-import org.postgresql.test.TestUtil;
-import junit.framework.TestCase;
-import java.sql.*;
-
-/*
- * $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/test/jdbc2/TimeTest.java,v 1.7 2003/11/29 22:41:23 pgsql Exp $
- *
- * Some simple tests based on problems reported by users. Hopefully these will
- * help prevent previous problems from re-occuring ;-)
- *
- */
-public class TimeTest extends TestCase
-{
-
- private Connection con;
- private boolean testSetTime = false;
-
- public TimeTest(String name)
- {
- super(name);
- }
-
- protected void setUp() throws Exception
- {
- con = TestUtil.openDB();
- TestUtil.createTable(con, "testtime", "tm time");
- }
-
- protected void tearDown() throws Exception
- {
- TestUtil.dropTable(con, "testtime");
- TestUtil.closeDB(con);
- }
-
- /*
- * Tests the time methods in ResultSet
- */
- public void testGetTime()
- {
- try
- {
- Statement stmt = con.createStatement();
-
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL("testtime", "'01:02:03'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL("testtime", "'23:59:59'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL("testtime", "'12:00:00'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL("testtime", "'05:15:21'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL("testtime", "'16:21:51'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL("testtime", "'12:15:12'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL("testtime", "'22:12:01'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL("testtime", "'08:46:44'")));
-
-
- // Fall through helper
- timeTest();
-
- assertEquals(8, stmt.executeUpdate("DELETE FROM testtime"));
- stmt.close();
- }
- catch (Exception ex)
- {
- fail(ex.getMessage());
- }
- }
-
- /*
- * Tests the time methods in PreparedStatement
- */
- public void testSetTime()
- {
- try
- {
- PreparedStatement ps = con.prepareStatement(TestUtil.insertSQL("testtime", "?"));
- Statement stmt = con.createStatement();
-
- ps.setTime(1, makeTime(1, 2, 3));
- assertEquals(1, ps.executeUpdate());
-
- ps.setTime(1, makeTime(23, 59, 59));
- assertEquals(1, ps.executeUpdate());
-
- ps.setObject(1, java.sql.Time.valueOf("12:00:00"), java.sql.Types.TIME);
- assertEquals(1, ps.executeUpdate());
-
- ps.setObject(1, java.sql.Time.valueOf("05:15:21"), java.sql.Types.TIME);
- assertEquals(1, ps.executeUpdate());
-
- ps.setObject(1, java.sql.Time.valueOf("16:21:51"), java.sql.Types.TIME);
- assertEquals(1, ps.executeUpdate());
-
- ps.setObject(1, java.sql.Time.valueOf("12:15:12"), java.sql.Types.TIME);
- assertEquals(1, ps.executeUpdate());
-
- ps.setObject(1, "22:12:1", java.sql.Types.TIME);
- assertEquals(1, ps.executeUpdate());
-
- ps.setObject(1, "8:46:44", java.sql.Types.TIME);
- assertEquals(1, ps.executeUpdate());
-
- ps.setObject(1, "5:1:2-03", java.sql.Types.TIME);
- assertEquals(1, ps.executeUpdate());
-
- ps.setObject(1, "23:59:59+11", java.sql.Types.TIME);
- assertEquals(1, ps.executeUpdate());
-
- // Need to let the test know this one has extra test cases.
- testSetTime = true;
- // Fall through helper
- timeTest();
- testSetTime = false;
-
- assertEquals(10, stmt.executeUpdate("DELETE FROM testtime"));
- stmt.close();
- ps.close();
- }
- catch (Exception ex)
- {
- fail(ex.getMessage());
- }
- }
-
- /*
- * Helper for the TimeTests. It tests what should be in the db
- */
- private void timeTest() throws SQLException
- {
- Statement st = con.createStatement();
- ResultSet rs;
- java.sql.Time t;
-
- rs = st.executeQuery(TestUtil.selectSQL("testtime", "tm"));
- assertNotNull(rs);
-
- assertTrue(rs.next());
- t = rs.getTime(1);
- assertNotNull(t);
- assertEquals(makeTime(1, 2, 3), t);
-
- assertTrue(rs.next());
- t = rs.getTime(1);
- assertNotNull(t);
- assertEquals(makeTime(23, 59, 59), t);
-
- assertTrue(rs.next());
- t = rs.getTime(1);
- assertNotNull(t);
- assertEquals(makeTime(12, 0, 0), t);
-
- assertTrue(rs.next());
- t = rs.getTime(1);
- assertNotNull(t);
- assertEquals(makeTime(5, 15, 21), t);
-
- assertTrue(rs.next());
- t = rs.getTime(1);
- assertNotNull(t);
- assertEquals(makeTime(16, 21, 51), t);
-
- assertTrue(rs.next());
- t = rs.getTime(1);
- assertNotNull(t);
- assertEquals(makeTime(12, 15, 12), t);
-
- assertTrue(rs.next());
- t = rs.getTime(1);
- assertNotNull(t);
- assertEquals(makeTime(22, 12, 1), t);
-
- assertTrue(rs.next());
- t = rs.getTime(1);
- assertNotNull(t);
- assertEquals(makeTime(8, 46, 44), t);
-
- // If we're checking for timezones.
- if (testSetTime)
- {
- assertTrue(rs.next());
- t = rs.getTime(1);
- assertNotNull(t);
- java.sql.Time tmpTime = java.sql.Time.valueOf("5:1:2");
- int localoffset = java.util.Calendar.getInstance().getTimeZone().getRawOffset();
- if (java.util.Calendar.getInstance().getTimeZone().inDaylightTime(tmpTime))
- {
- localoffset += 60 * 60 * 1000;
- }
- int Timeoffset = 3 * 60 * 60 * 1000;
- tmpTime.setTime(tmpTime.getTime() + Timeoffset + localoffset);
- assertEquals(t, makeTime(tmpTime.getHours(), tmpTime.getMinutes(), tmpTime.getSeconds()));
-
- assertTrue(rs.next());
- t = rs.getTime(1);
- assertNotNull(t);
- tmpTime= java.sql.Time.valueOf("23:59:59");
- localoffset = java.util.Calendar.getInstance().getTimeZone().getRawOffset();
- if (java.util.Calendar.getInstance().getTimeZone().inDaylightTime(tmpTime))
- {
- localoffset += 60 * 60 * 1000;
- }
- Timeoffset = -11 * 60 * 60 * 1000;
- tmpTime.setTime(tmpTime.getTime() + Timeoffset + localoffset);
- assertEquals(t, makeTime(tmpTime.getHours(), tmpTime.getMinutes(), tmpTime.getSeconds()));
- }
-
- assertTrue(! rs.next());
-
- rs.close();
- }
-
- private java.sql.Time makeTime(int h, int m, int s)
- {
- return java.sql.Time.valueOf(TestUtil.fix(h, 2) + ":" +
- TestUtil.fix(m, 2) + ":" +
- TestUtil.fix(s, 2));
- }
-}
+++ /dev/null
-package org.postgresql.test.jdbc2;
-
-import org.postgresql.test.TestUtil;
-import junit.framework.TestCase;
-import java.sql.*;
-
-/*
- * $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/test/jdbc2/TimestampTest.java,v 1.13 2003/11/29 22:41:23 pgsql Exp $
- *
- * Test get/setTimestamp for both timestamp with time zone and
- * timestamp without time zone datatypes
- *
- */
-public class TimestampTest extends TestCase
-{
-
- private Connection con;
-
- public TimestampTest(String name)
- {
- super(name);
- }
-
- protected void setUp() throws Exception
- {
- con = TestUtil.openDB();
- TestUtil.createTable(con, TSWTZ_TABLE, "ts timestamp with time zone");
- TestUtil.createTable(con, TSWOTZ_TABLE, "ts timestamp without time zone");
- }
-
- protected void tearDown() throws Exception
- {
- TestUtil.dropTable(con, TSWTZ_TABLE);
- TestUtil.dropTable(con, TSWOTZ_TABLE);
- TestUtil.closeDB(con);
- }
-
- /*
- * Tests the timestamp methods in ResultSet on timestamp with time zone
- * we insert a known string value (don't use setTimestamp) then see that
- * we get back the same value from getTimestamp
- */
- public void testGetTimestampWTZ()
- {
- try
- {
- Statement stmt = con.createStatement();
-
- //Insert the three timestamp values in raw pg format
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + TS1WTZ_PGFORMAT + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + TS2WTZ_PGFORMAT + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + TS3WTZ_PGFORMAT + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + TS4WTZ_PGFORMAT + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + TS1WTZ_PGFORMAT + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + TS2WTZ_PGFORMAT + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + TS3WTZ_PGFORMAT + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + TS4WTZ_PGFORMAT + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + TS1WTZ_PGFORMAT + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + TS2WTZ_PGFORMAT + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + TS3WTZ_PGFORMAT + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + TS4WTZ_PGFORMAT + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + new java.sql.Timestamp(tmpDate1.getTime()) + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + new java.sql.Timestamp(tmpDate2.getTime()) + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + new java.sql.Timestamp(tmpDate3.getTime()) + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + new java.sql.Timestamp(tmpDate4.getTime()) + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + new java.sql.Timestamp(tmpTime1.getTime()) + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + new java.sql.Timestamp(tmpTime2.getTime()) + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + new java.sql.Timestamp(tmpTime3.getTime()) + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + new java.sql.Timestamp(tmpTime4.getTime()) + "'")));
-
-
- // Fall through helper
- timestampTestWTZ();
-
- assertEquals(20, stmt.executeUpdate("DELETE FROM " + TSWTZ_TABLE));
-
- stmt.close();
- }
- catch (Exception ex)
- {
- fail(ex.getMessage());
- }
- }
-
- /*
- * Tests the timestamp methods in PreparedStatement on timestamp with time zone
- * we insert a value using setTimestamp then see that
- * we get back the same value from getTimestamp (which we know works as it was tested
- * independently of setTimestamp
- */
- public void testSetTimestampWTZ()
- {
- try
- {
- Statement stmt = con.createStatement();
- PreparedStatement pstmt = con.prepareStatement(TestUtil.insertSQL(TSWTZ_TABLE, "?"));
-
- pstmt.setTimestamp(1, TS1WTZ);
- assertEquals(1, pstmt.executeUpdate());
-
- pstmt.setTimestamp(1, TS2WTZ);
- assertEquals(1, pstmt.executeUpdate());
-
- pstmt.setTimestamp(1, TS3WTZ);
- assertEquals(1, pstmt.executeUpdate());
-
- pstmt.setTimestamp(1, TS4WTZ);
- assertEquals(1, pstmt.executeUpdate());
-
- // With java.sql.Timestamp
- pstmt.setObject(1,TS1WTZ, java.sql.Types.TIMESTAMP);
- assertEquals(1, pstmt.executeUpdate());
- pstmt.setObject(1,TS2WTZ, java.sql.Types.TIMESTAMP);
- assertEquals(1, pstmt.executeUpdate());
- pstmt.setObject(1,TS3WTZ, java.sql.Types.TIMESTAMP);
- assertEquals(1, pstmt.executeUpdate());
- pstmt.setObject(1,TS4WTZ, java.sql.Types.TIMESTAMP);
- assertEquals(1, pstmt.executeUpdate());
-
- // With Strings
- pstmt.setObject(1,TS1WTZ_PGFORMAT, java.sql.Types.TIMESTAMP);
- assertEquals(1, pstmt.executeUpdate());
- pstmt.setObject(1,TS2WTZ_PGFORMAT, java.sql.Types.TIMESTAMP);
- assertEquals(1, pstmt.executeUpdate());
- pstmt.setObject(1,TS3WTZ_PGFORMAT, java.sql.Types.TIMESTAMP);
- assertEquals(1, pstmt.executeUpdate());
- pstmt.setObject(1,TS4WTZ_PGFORMAT, java.sql.Types.TIMESTAMP);
- assertEquals(1, pstmt.executeUpdate());
-
- // With java.sql.Date
- pstmt.setObject(1,tmpDate1, java.sql.Types.TIMESTAMP);
- assertEquals(1, pstmt.executeUpdate());
- pstmt.setObject(1,tmpDate2, java.sql.Types.TIMESTAMP);
- assertEquals(1, pstmt.executeUpdate());
- pstmt.setObject(1,tmpDate3, java.sql.Types.TIMESTAMP);
- assertEquals(1, pstmt.executeUpdate());
- pstmt.setObject(1,tmpDate4, java.sql.Types.TIMESTAMP);
- assertEquals(1, pstmt.executeUpdate());
-
- // With java.sql.Time
- pstmt.setObject(1,tmpTime1, java.sql.Types.TIMESTAMP);
- assertEquals(1, pstmt.executeUpdate());
- pstmt.setObject(1,tmpTime2, java.sql.Types.TIMESTAMP);
- assertEquals(1, pstmt.executeUpdate());
- pstmt.setObject(1,tmpTime3, java.sql.Types.TIMESTAMP);
- assertEquals(1, pstmt.executeUpdate());
- pstmt.setObject(1,tmpTime4, java.sql.Types.TIMESTAMP);
- assertEquals(1, pstmt.executeUpdate());
-
- // Fall through helper
- timestampTestWTZ();
-
- assertEquals(20, stmt.executeUpdate("DELETE FROM " + TSWTZ_TABLE));
-
- pstmt.close();
- stmt.close();
- }
- catch (Exception ex)
- {
- fail(ex.getMessage());
- }
- }
-
- /*
- * Tests the timestamp methods in ResultSet on timestamp without time zone
- * we insert a known string value (don't use setTimestamp) then see that
- * we get back the same value from getTimestamp
- */
- public void testGetTimestampWOTZ()
- {
- try
- {
- Statement stmt = con.createStatement();
-
- //Insert the three timestamp values in raw pg format
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + TS1WOTZ_PGFORMAT + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + TS2WOTZ_PGFORMAT + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + TS3WOTZ_PGFORMAT + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + TS4WOTZ_PGFORMAT + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + TS1WOTZ_PGFORMAT + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + TS2WOTZ_PGFORMAT + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + TS3WOTZ_PGFORMAT + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + TS4WOTZ_PGFORMAT + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + TS1WOTZ_PGFORMAT + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + TS2WOTZ_PGFORMAT + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + TS3WOTZ_PGFORMAT + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + TS4WOTZ_PGFORMAT + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + new java.sql.Timestamp(tmpDate1WOTZ.getTime()) + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + new java.sql.Timestamp(tmpDate2WOTZ.getTime()) + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + new java.sql.Timestamp(tmpDate3WOTZ.getTime()) + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + new java.sql.Timestamp(tmpDate4WOTZ.getTime()) + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + new java.sql.Timestamp(tmpTime1WOTZ.getTime()) + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + new java.sql.Timestamp(tmpTime2WOTZ.getTime()) + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + new java.sql.Timestamp(tmpTime3WOTZ.getTime()) + "'")));
- assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + new java.sql.Timestamp(tmpTime4WOTZ.getTime()) + "'")));
-
- // Fall through helper
- timestampTestWOTZ();
-
- assertEquals(20, stmt.executeUpdate("DELETE FROM " + TSWOTZ_TABLE));
-
- stmt.close();
- }
- catch (Exception ex)
- {
- fail(ex.getMessage());
- }
- }
-
-
- /*
- * Tests the timestamp methods in PreparedStatement on timestamp without time zone
- * we insert a value using setTimestamp then see that
- * we get back the same value from getTimestamp (which we know works as it was tested
- * independently of setTimestamp
- */
- public void testSetTimestampWOTZ()
- {
- try
- {
- Statement stmt = con.createStatement();
- PreparedStatement pstmt = con.prepareStatement(TestUtil.insertSQL(TSWOTZ_TABLE, "?"));
-
- pstmt.setTimestamp(1, TS1WOTZ);
- assertEquals(1, pstmt.executeUpdate());
-
- pstmt.setTimestamp(1, TS2WOTZ);
- assertEquals(1, pstmt.executeUpdate());
-
- pstmt.setTimestamp(1, TS3WOTZ);
- assertEquals(1, pstmt.executeUpdate());
-
- pstmt.setTimestamp(1, TS4WOTZ);
- assertEquals(1, pstmt.executeUpdate());
-
-
- // With java.sql.Timestamp
- pstmt.setObject(1,TS1WOTZ, java.sql.Types.TIMESTAMP);
- assertEquals(1, pstmt.executeUpdate());
- pstmt.setObject(1,TS2WOTZ, java.sql.Types.TIMESTAMP);
- assertEquals(1, pstmt.executeUpdate());
- pstmt.setObject(1,TS3WOTZ, java.sql.Types.TIMESTAMP);
- assertEquals(1, pstmt.executeUpdate());
- pstmt.setObject(1,TS4WOTZ, java.sql.Types.TIMESTAMP);
- assertEquals(1, pstmt.executeUpdate());
-
- // With Strings
- pstmt.setObject(1,TS1WOTZ_PGFORMAT, java.sql.Types.TIMESTAMP);
- assertEquals(1, pstmt.executeUpdate());
- pstmt.setObject(1,TS2WOTZ_PGFORMAT, java.sql.Types.TIMESTAMP);
- assertEquals(1, pstmt.executeUpdate());
- pstmt.setObject(1,TS3WOTZ_PGFORMAT, java.sql.Types.TIMESTAMP);
- assertEquals(1, pstmt.executeUpdate());
- pstmt.setObject(1,TS4WOTZ_PGFORMAT, java.sql.Types.TIMESTAMP);
- assertEquals(1, pstmt.executeUpdate());
-
- // With java.sql.Date
- pstmt.setObject(1,tmpDate1WOTZ, java.sql.Types.TIMESTAMP);
- assertEquals(1, pstmt.executeUpdate());
- pstmt.setObject(1,tmpDate2WOTZ, java.sql.Types.TIMESTAMP);
- assertEquals(1, pstmt.executeUpdate());
- pstmt.setObject(1,tmpDate3WOTZ, java.sql.Types.TIMESTAMP);
- assertEquals(1, pstmt.executeUpdate());
- pstmt.setObject(1,tmpDate4WOTZ, java.sql.Types.TIMESTAMP);
- assertEquals(1, pstmt.executeUpdate());
-
- // With java.sql.Time
- pstmt.setObject(1,tmpTime1WOTZ, java.sql.Types.TIMESTAMP);
- assertEquals(1, pstmt.executeUpdate());
- pstmt.setObject(1,tmpTime2WOTZ, java.sql.Types.TIMESTAMP);
- assertEquals(1, pstmt.executeUpdate());
- pstmt.setObject(1,tmpTime3WOTZ, java.sql.Types.TIMESTAMP);
- assertEquals(1, pstmt.executeUpdate());
- pstmt.setObject(1,tmpTime4WOTZ, java.sql.Types.TIMESTAMP);
- assertEquals(1, pstmt.executeUpdate());
-
- // Fall through helper
- timestampTestWOTZ();
-
- assertEquals(20, stmt.executeUpdate("DELETE FROM " + TSWOTZ_TABLE));
-
- pstmt.close();
- stmt.close();
- }
- catch (Exception ex)
- {
- fail(ex.getMessage());
- }
- }
-
- /*
- * Helper for the TimestampTests. It tests what should be in the db
- */
- private void timestampTestWTZ() throws SQLException
- {
- Statement stmt = con.createStatement();
- ResultSet rs;
- java.sql.Timestamp t;
-
- rs = stmt.executeQuery("select ts from " + TSWTZ_TABLE); //removed the order by ts
- assertNotNull(rs);
-
- for (int i=0; i<3; i++)
- {
- assertTrue(rs.next());
- t = rs.getTimestamp(1);
- assertNotNull(t);
- assertTrue(t.equals(TS1WTZ));
-
- assertTrue(rs.next());
- t = rs.getTimestamp(1);
- assertNotNull(t);
- assertTrue(t.equals(TS2WTZ));
-
- assertTrue(rs.next());
- t = rs.getTimestamp(1);
- assertNotNull(t);
- assertTrue(t.equals(TS3WTZ));
-
- assertTrue(rs.next());
- t = rs.getTimestamp(1);
- assertNotNull(t);
- assertTrue(t.equals(TS4WTZ));
- }
-
- // Testing for Date
- assertTrue(rs.next());
- t = rs.getTimestamp(1);
- assertNotNull(t);
- assertEquals(t.getTime(), tmpDate1.getTime());
-
- assertTrue(rs.next());
- t = rs.getTimestamp(1);
- assertNotNull(t);
- assertEquals(t.getTime(), tmpDate2.getTime());
-
- assertTrue(rs.next());
- t = rs.getTimestamp(1);
- assertNotNull(t);
- assertEquals(t.getTime(), tmpDate3.getTime());
-
- assertTrue(rs.next());
- t = rs.getTimestamp(1);
- assertNotNull(t);
- assertEquals(t.getTime(), tmpDate4.getTime());
-
- // Testing for Time
- assertTrue(rs.next());
- t = rs.getTimestamp(1);
- assertNotNull(t);
- assertEquals(t.getTime(), tmpTime1.getTime());
-
- assertTrue(rs.next());
- t = rs.getTimestamp(1);
- assertNotNull(t);
- assertEquals(t.getTime(), tmpTime2.getTime());
-
- assertTrue(rs.next());
- t = rs.getTimestamp(1);
- assertNotNull(t);
- assertEquals(t.getTime(), tmpTime3.getTime());
-
- assertTrue(rs.next());
- t = rs.getTimestamp(1);
- assertNotNull(t);
- assertEquals(t.getTime(), tmpTime4.getTime());
-
- assertTrue(! rs.next()); // end of table. Fail if more entries exist.
-
- rs.close();
- stmt.close();
- }
-
- /*
- * Helper for the TimestampTests. It tests what should be in the db
- */
- private void timestampTestWOTZ() throws SQLException
- {
- Statement stmt = con.createStatement();
- ResultSet rs;
- java.sql.Timestamp t;
-
- rs = stmt.executeQuery("select ts from " + TSWOTZ_TABLE); //removed the order by ts
- assertNotNull(rs);
-
- for (int i=0; i<3; i++)
- {
- assertTrue(rs.next());
- t = rs.getTimestamp(1);
- assertNotNull(t);
- assertTrue(t.equals(TS1WOTZ));
-
- assertTrue(rs.next());
- t = rs.getTimestamp(1);
- assertNotNull(t);
- assertTrue(t.equals(TS2WOTZ));
-
- assertTrue(rs.next());
- t = rs.getTimestamp(1);
- assertNotNull(t);
- assertTrue(t.equals(TS3WOTZ));
-
- assertTrue(rs.next());
- t = rs.getTimestamp(1);
- assertNotNull(t);
- assertTrue(t.equals(TS4WOTZ));
- }
-
- // Testing for Date
- assertTrue(rs.next());
- t = rs.getTimestamp(1);
- assertNotNull(t);
- assertEquals(t.getTime(), tmpDate1WOTZ.getTime());
-
- assertTrue(rs.next());
- t = rs.getTimestamp(1);
- assertNotNull(t);
- assertEquals(t.getTime(), tmpDate2WOTZ.getTime());
-
- assertTrue(rs.next());
- t = rs.getTimestamp(1);
- assertNotNull(t);
- assertEquals(t.getTime(), tmpDate3WOTZ.getTime());
-
- assertTrue(rs.next());
- t = rs.getTimestamp(1);
- assertNotNull(t);
- assertEquals(t.getTime(), tmpDate4WOTZ.getTime());
-
- // Testing for Time
- assertTrue(rs.next());
- t = rs.getTimestamp(1);
- assertNotNull(t);
- assertEquals(t.getTime(), tmpTime1WOTZ.getTime());
-
- assertTrue(rs.next());
- t = rs.getTimestamp(1);
- assertNotNull(t);
- assertEquals(t.getTime(), tmpTime2WOTZ.getTime());
-
- assertTrue(rs.next());
- t = rs.getTimestamp(1);
- assertNotNull(t);
- assertEquals(t.getTime(), tmpTime3WOTZ.getTime());
-
- assertTrue(rs.next());
- t = rs.getTimestamp(1);
- assertNotNull(t);
- assertEquals(t.getTime(), tmpTime4WOTZ.getTime());
-
- assertTrue(! rs.next()); // end of table. Fail if more entries exist.
-
- rs.close();
- stmt.close();
- }
-
- private static java.sql.Timestamp getTimestamp(int y, int m, int d, int h, int mn, int se, int f, String tz)
- {
- java.sql.Timestamp l_return = null;
- java.text.DateFormat l_df;
- try
- {
- String l_ts;
- l_ts = TestUtil.fix(y, 4) + "-" +
- TestUtil.fix(m, 2) + "-" +
- TestUtil.fix(d, 2) + " " +
- TestUtil.fix(h, 2) + ":" +
- TestUtil.fix(mn, 2) + ":" +
- TestUtil.fix(se, 2) + " ";
-
- if (tz == null)
- {
- l_df = new java.text.SimpleDateFormat("y-M-d H:m:s");
- }
- else
- {
- l_ts = l_ts + tz;
- l_df = new java.text.SimpleDateFormat("y-M-d H:m:s z");
- }
- java.util.Date l_date = l_df.parse(l_ts);
- l_return = new java.sql.Timestamp(l_date.getTime());
- l_return.setNanos(f);
- }
- catch (Exception ex)
- {
- fail(ex.getMessage());
- }
- return l_return;
- }
-
- private static final java.sql.Timestamp TS1WTZ = getTimestamp(1950, 2, 7, 15, 0, 0, 100000000, "PST");
- private static final String TS1WTZ_PGFORMAT = "1950-02-07 15:00:00.1-08";
-
- private static final java.sql.Timestamp TS2WTZ = getTimestamp(2000, 2, 7, 15, 0, 0, 120000000, "GMT");
- private static final String TS2WTZ_PGFORMAT = "2000-02-07 15:00:00.12+00";
-
- private static final java.sql.Timestamp TS3WTZ = getTimestamp(2000, 7, 7, 15, 0, 0, 123000000, "GMT");
- private static final String TS3WTZ_PGFORMAT = "2000-07-07 15:00:00.123+00";
-
- private static final java.sql.Timestamp TS4WTZ = getTimestamp(2000, 7, 7, 15, 0, 0, 123456000, "GMT");
- private static final String TS4WTZ_PGFORMAT = "2000-07-07 15:00:00.123456+00";
-
-
- private static final java.sql.Timestamp TS1WOTZ = getTimestamp(1950, 2, 7, 15, 0, 0, 100000000, null);
- private static final String TS1WOTZ_PGFORMAT = "1950-02-07 15:00:00.1";
-
- private static final java.sql.Timestamp TS2WOTZ = getTimestamp(2000, 2, 7, 15, 0, 0, 120000000, null);
- private static final String TS2WOTZ_PGFORMAT = "2000-02-07 15:00:00.12";
-
- private static final java.sql.Timestamp TS3WOTZ = getTimestamp(2000, 7, 7, 15, 0, 0, 123000000, null);
- private static final String TS3WOTZ_PGFORMAT = "2000-07-07 15:00:00.123";
-
- private static final java.sql.Timestamp TS4WOTZ = getTimestamp(2000, 7, 7, 15, 0, 0, 123456000, null);
- private static final String TS4WOTZ_PGFORMAT = "2000-07-07 15:00:00.123456";
-
- private static final String TSWTZ_TABLE = "testtimestampwtz";
- private static final String TSWOTZ_TABLE = "testtimestampwotz";
-
- private static final java.sql.Date tmpDate1 = new java.sql.Date(TS1WTZ.getTime());
- private static final java.sql.Time tmpTime1 = new java.sql.Time(TS1WTZ.getTime());
- private static final java.sql.Date tmpDate2 = new java.sql.Date(TS2WTZ.getTime());
- private static final java.sql.Time tmpTime2 = new java.sql.Time(TS2WTZ.getTime());
- private static final java.sql.Date tmpDate3 = new java.sql.Date(TS3WTZ.getTime());
- private static final java.sql.Time tmpTime3 = new java.sql.Time(TS3WTZ.getTime());
- private static final java.sql.Date tmpDate4 = new java.sql.Date(TS4WTZ.getTime());
- private static final java.sql.Time tmpTime4 = new java.sql.Time(TS4WTZ.getTime());
-
- private static final java.sql.Date tmpDate1WOTZ = new java.sql.Date(TS1WOTZ.getTime());
- private static final java.sql.Time tmpTime1WOTZ = new java.sql.Time(TS1WOTZ.getTime());
- private static final java.sql.Date tmpDate2WOTZ = new java.sql.Date(TS2WOTZ.getTime());
- private static final java.sql.Time tmpTime2WOTZ = new java.sql.Time(TS2WOTZ.getTime());
- private static final java.sql.Date tmpDate3WOTZ = new java.sql.Date(TS3WOTZ.getTime());
- private static final java.sql.Time tmpTime3WOTZ = new java.sql.Time(TS3WOTZ.getTime());
- private static final java.sql.Date tmpDate4WOTZ = new java.sql.Date(TS4WOTZ.getTime());
- private static final java.sql.Time tmpTime4WOTZ = new java.sql.Time(TS4WOTZ.getTime());
-
-
-}
+++ /dev/null
-package org.postgresql.test.jdbc2;
-
-import java.sql.*;
-import junit.framework.TestCase;
-
-import org.postgresql.test.TestUtil;
-/**
- *
Copyright: Copyright (c) 2001
- * @author unascribed
- * @version 1.0
- */
-
-public class UpdateableResultTest extends TestCase
-{
- private Connection con;
-
- public UpdateableResultTest( String name )
- {
- super( name );
- }
-
- protected void setUp() throws Exception
- {
- con = TestUtil.openDB();
- TestUtil.createTable(con, "updateable", "id int primary key, name text, notselected text");
- TestUtil.createTable(con, "second", "id1 int primary key, name1 text");
-
- // put some dummy data into second
- Statement st2 = con.createStatement();
- st2.execute( "insert into second values (1,'anyvalue' )");
- st2.close();
-
- }
-
- protected void tearDown() throws Exception
- {
- TestUtil.dropTable(con, "updateable");
- TestUtil.dropTable(con, "second");
- TestUtil.closeDB(con);
- }
-
- public void testCancelRowUpdates() throws Exception
- {
- Statement st = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE );
- ResultSet rs = st.executeQuery( "select * from second");
-
- // make sure we're dealing with the correct row.
- rs.first();
- assertEquals(1,rs.getInt(1));
- assertEquals("anyvalue",rs.getString(2));
-
- // update, cancel and make sure nothings changed.
- rs.updateInt(1,99);
- rs.cancelRowUpdates();
- assertEquals(1,rs.getInt(1));
- assertEquals("anyvalue",rs.getString(2));
-
- // real update
- rs.updateInt(1,999);
- rs.updateRow();
- assertEquals(999,rs.getInt(1));
- assertEquals("anyvalue",rs.getString(2));
-
- // scroll some and make sure the update is still there
- rs.beforeFirst();
- rs.next();
- assertEquals(999,rs.getInt(1));
- assertEquals("anyvalue",rs.getString(2));
-
-
- // make sure the update got to the db and the driver isn't lying to us.
- rs.close();
- rs = st.executeQuery( "select * from second");
- rs.first();
- assertEquals(999,rs.getInt(1));
- assertEquals("anyvalue",rs.getString(2));
-
- rs.close();
- st.close();
- }
-
-
-
- public void testUpdateable()
- {
- try
- {
- Statement st = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE );
- ResultSet rs = st.executeQuery( "select * from updateable");
- assertNotNull( rs );
- rs.moveToInsertRow();
- rs.updateInt( 1, 1 );
- rs.updateString( 2, "jake" );
- rs.updateString( 3, "avalue" );
- rs.insertRow();
- rs.first();
-
- rs.updateInt( "id", 2 );
- rs.updateString( "name", "dave" );
- rs.updateRow();
-
- assertTrue( rs.getInt("id") == 2 );
- assertTrue( rs.getString("name").equals("dave"));
- assertTrue( rs.getString("notselected").equals("avalue") );
-
- rs.deleteRow();
- rs.moveToInsertRow();
- rs.updateInt("id", 3);
- rs.updateString("name", "paul");
-
- rs.insertRow();
- rs.refreshRow();
- assertTrue( rs.getInt("id") == 3 );
- assertTrue( rs.getString("name").equals("paul"));
- assertTrue( rs.getString("notselected") == null );
-
-
- rs.close();
-
- rs = st.executeQuery("select id1, id, name, name1 from updateable, second" );
- try
- {
- while ( rs.next() )
- {
- rs.updateInt( "id", 2 );
- rs.updateString( "name", "dave" );
- rs.updateRow();
- }
-
-
- assertTrue( "should not get here, update should fail", false );
- }
- catch (SQLException ex)
- {}
-
- try
- {
- rs = st.executeQuery("select oid,* from updateable");
- if ( rs.first() )
- {
- rs.updateInt( "id", 3 );
- rs.updateString( "name", "dave3");
- rs.updateRow();
- assertTrue(rs.getInt("id") == 3 );
- assertTrue(rs.getString("name").equals("dave3"));
-
- rs.moveToInsertRow();
- rs.updateInt( "id", 4 );
- rs.updateString( "name", "dave4" );
-
- rs.insertRow();
- rs.updateInt("id", 5 );
- rs.updateString( "name", "dave5" );
- rs.insertRow();
-
- rs.moveToCurrentRow();
- assertTrue(rs.getInt("id") == 3 );
- assertTrue(rs.getString("name").equals("dave3"));
-
- assertTrue( rs.next() );
- assertTrue(rs.getInt("id") == 4 );
- assertTrue(rs.getString("name").equals("dave4"));
-
- assertTrue( rs.next() );
- assertTrue(rs.getInt("id") == 5 );
- assertTrue(rs.getString("name").equals("dave5"));
-
- }
- }
- catch (SQLException ex)
- {
- fail(ex.getMessage());
- }
-
- st.close();
-
- }
- catch (Exception ex)
- {
- ex.printStackTrace();
- fail(ex.getMessage());
- }
- }
-
-
-}
+++ /dev/null
-package org.postgresql.test.jdbc2.optional;
-
-import junit.framework.TestCase;
-import org.postgresql.test.TestUtil;
-import org.postgresql.jdbc2.optional.BaseDataSource;
-import org.postgresql.PGConnection;
-
-import java.sql.*;
-import java.util.*;
-import javax.naming.*;
-
-/**
- * Common tests for all the BaseDataSource implementations. This is
- * a small variety to make sure that a connection can be opened and
- * some basic queries run. The different BaseDataSource subclasses
- * have different subclasses of this which add additional custom
- * tests.
- *
- * @version $Revision: 1.6 $
- */
-public abstract class BaseDataSourceTest extends TestCase
-{
- public static String DATA_SOURCE_JNDI = "BaseDataSource";
- protected Connection con;
- protected BaseDataSource bds;
-
- /**
- * Constructor required by JUnit
- */
- public BaseDataSourceTest(String name)
- {
- super(name);
- }
-
- /**
- * Creates a test table using a standard connection (not from a
- * DataSource).
- */
- protected void setUp() throws Exception
- {
- con = TestUtil.openDB();
- TestUtil.createTable(con, "poolingtest", "id int4 not null primary key, name varchar(50)");
- Statement stmt = con.createStatement();
- stmt.executeUpdate("INSERT INTO poolingtest VALUES (1, 'Test Row 1')");
- stmt.executeUpdate("INSERT INTO poolingtest VALUES (2, 'Test Row 2')");
- TestUtil.closeDB(con);
- }
-
- /**
- * Removes the test table using a standard connection (not from
- * a DataSource)
- */
- protected void tearDown() throws Exception
- {
- con = TestUtil.openDB();
- TestUtil.dropTable(con, "poolingtest");
- TestUtil.closeDB(con);
- }
-
- /**
- * Gets a connection from the current BaseDataSource
- */
- protected Connection getDataSourceConnection() throws SQLException
- {
- if(bds == null)
- {
- initializeDataSource();
- }
- return bds.getConnection();
- }
-
- /**
- * Creates an instance of the current BaseDataSource for
- * testing. Must be customized by each subclass.
- */
- protected abstract void initializeDataSource();
-
- /**
- * Test to make sure you can instantiate and configure the
- * appropriate DataSource
- */
- public void testCreateDataSource()
- {
- initializeDataSource();
- }
-
- /**
- * Test to make sure you can get a connection from the DataSource,
- * which in turn means the DataSource was able to open it.
- */
- public void testGetConnection()
- {
- try
- {
- con = getDataSourceConnection();
- con.close();
- }
- catch (SQLException e)
- {
- fail(e.getMessage());
- }
- }
-
- /**
- * A simple test to make sure you can execute SQL using the
- * Connection from the DataSource
- */
- public void testUseConnection()
- {
- try
- {
- con = getDataSourceConnection();
- Statement st = con.createStatement();
- ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM poolingtest");
- if (rs.next())
- {
- int count = rs.getInt(1);
- if (rs.next())
- {
- fail("Should only have one row in SELECT COUNT result set");
- }
- if (count != 2)
- {
- fail("Count returned " + count + " expecting 2");
- }
- }
- else
- {
- fail("Should have one row in SELECT COUNT result set");
- }
- rs.close();
- st.close();
- con.close();
- }
- catch (SQLException e)
- {
- fail(e.getMessage());
- }
- }
-
- /**
- * A test to make sure you can execute DDL SQL using the
- * Connection from the DataSource.
- */
- public void testDdlOverConnection()
- {
- try
- {
- con = getDataSourceConnection();
- TestUtil.createTable(con, "poolingtest", "id int4 not null primary key, name varchar(50)");
- con.close();
- }
- catch (SQLException e)
- {
- fail(e.getMessage());
- }
- }
-
- /**
- * A test to make sure the connections are not being pooled by the
- * current DataSource. Obviously need to be overridden in the case
- * of a pooling Datasource.
- */
- public void testNotPooledConnection()
- {
- try
- {
- con = getDataSourceConnection();
- String name = con.toString();
- con.close();
- con = getDataSourceConnection();
- String name2 = con.toString();
- con.close();
- assertTrue(!name.equals(name2));
- }
- catch (SQLException e)
- {
- fail(e.getMessage());
- }
- }
-
- /**
- * Test to make sure that PGConnection methods can be called on the
- * pooled Connection.
- */
- public void testPGConnection()
- {
- try
- {
- con = getDataSourceConnection();
- ((PGConnection)con).getNotifications();
- con.close();
- }
- catch (Exception e)
- {
- fail("Unable to call PGConnection method on pooled connection due to "+e.getClass().getName()+" ("+e.getMessage()+")");
- }
- }
-
- /**
- * Uses the mini-JNDI implementation for testing purposes
- */
- protected InitialContext getInitialContext()
- {
- Hashtable env = new Hashtable();
- env.put(Context.INITIAL_CONTEXT_FACTORY, "org.postgresql.test.util.MiniJndiContextFactory");
- try {
- return new InitialContext(env);
- } catch(NamingException e) {
- fail("Unable to create InitialContext: "+e.getMessage());
- return null;
- }
- }
-
- /**
- * Eventually, we must test stuffing the DataSource in JNDI and
- * then getting it back out and make sure it's still usable. This
- * should ideally test both Serializable and Referenceable
- * mechanisms. Will probably be multiple tests when implemented.
- */
- public void testJndi()
- {
- initializeDataSource();
- BaseDataSource oldbds = bds;
- InitialContext ic = getInitialContext();
- try {
- ic.rebind(DATA_SOURCE_JNDI, bds);
- bds = (BaseDataSource)ic.lookup(DATA_SOURCE_JNDI);
- assertTrue("Got null looking up DataSource from JNDI!", bds != null);
- compareJndiDataSource(oldbds, bds);
- } catch (NamingException e) {
- fail(e.getMessage());
- }
- oldbds = bds;
- testUseConnection();
- assertTrue("Test should not have changed DataSource ("+bds+" != "+oldbds+")!", bds == oldbds);
- }
-
- /**
- * Check whether a DS was dereferenced from JNDI or recreated.
- */
- protected void compareJndiDataSource(BaseDataSource oldbds, BaseDataSource bds) {
- assertTrue("DataSource was dereferenced, should have been serialized or recreated", bds != oldbds);
- }
-}
+++ /dev/null
-package org.postgresql.test.jdbc2.optional;
-
-import org.postgresql.jdbc2.optional.ConnectionPool;
-import org.postgresql.test.TestUtil;
-import javax.sql.*;
-import java.sql.*;
-
-/**
- * Tests for the ConnectionPoolDataSource and PooledConnection
- * implementations. They are tested together because the only client
- * interface to the PooledConnection is through the CPDS.
- *
- * @version $Revision: 1.8 $
- */
-public class ConnectionPoolTest extends BaseDataSourceTest
-{
- /**
- * Constructor required by JUnit
- */
- public ConnectionPoolTest(String name)
- {
- super(name);
- }
-
- /**
- * Creates and configures a ConnectionPool
- */
- protected void initializeDataSource()
- {
- if (bds == null)
- {
- bds = new ConnectionPool();
- bds.setServerName(TestUtil.getServer());
- bds.setPortNumber(TestUtil.getPort());
- bds.setDatabaseName(TestUtil.getDatabase());
- bds.setUser(TestUtil.getUser());
- bds.setPassword(TestUtil.getPassword());
- }
- }
-
- /**
- * Though the normal client interface is to grab a Connection, in
- * order to test the middleware/server interface, we need to deal
- * with PooledConnections. Some tests use each.
- */
- protected PooledConnection getPooledConnection() throws SQLException
- {
- initializeDataSource();
- return ((ConnectionPool)bds).getPooledConnection();
- }
-
- /**
- * Instead of just fetching a Connection from the ConnectionPool,
- * get a PooledConnection, add a listener to close it when the
- * Connection is closed, and then get the Connection. Without
- * the listener the PooledConnection (and thus the physical connection)
- * would never by closed. Probably not a disaster during testing, but
- * you never know.
- */
- protected Connection getDataSourceConnection() throws SQLException
- {
- initializeDataSource();
- final PooledConnection pc = getPooledConnection();
- // Since the pooled connection won't be reused in these basic tests, close it when the connection is closed
- pc.addConnectionEventListener(new ConnectionEventListener()
- {
- public void connectionClosed(ConnectionEvent event)
- {
- try
- {
- pc.close();
- }
- catch (SQLException e)
- {
- fail("Unable to close PooledConnection: " + e);
- }
- }
-
- public void connectionErrorOccurred(ConnectionEvent event)
- {}
- }
- );
- return pc.getConnection();
- }
-
- /**
- * Makes sure that if you get a connection from a PooledConnection,
- * close it, and then get another one, you're really using the same
- * physical connection. Depends on the implementation of toString
- * for the connection handle.
- */
- public void testPoolReuse()
- {
- try
- {
- PooledConnection pc = getPooledConnection();
- con = pc.getConnection();
- String name = con.toString();
- con.close();
- con = pc.getConnection();
- String name2 = con.toString();
- con.close();
- pc.close();
- assertTrue("Physical connection doesn't appear to be reused across PooledConnection wrappers", name.equals(name2));
- }
- catch (SQLException e)
- {
- fail(e.getMessage());
- }
- }
-
- /**
- * Makes sure that when you request a connection from the
- * PooledConnection, and previous connection it might have given
- * out is closed. See JDBC 2.0 Optional Package spec section
- * 6.2.3
- */
- public void testPoolCloseOldWrapper()
- {
- try
- {
- PooledConnection pc = getPooledConnection();
- con = pc.getConnection();
- Connection con2 = pc.getConnection();
- try
- {
- con.createStatement();
- fail("Original connection wrapper should be closed when new connection wrapper is generated");
- }
- catch (SQLException e)
- {}
- try
- {
- con.close();
- fail("Original connection wrapper should be closed when new connection wrapper is generated");
- }
- catch (SQLException e)
- {}
- con2.close();
- pc.close();
- }
- catch (SQLException e)
- {
- fail(e.getMessage());
- }
- }
-
- /**
- * Makes sure that if you get two connection wrappers from the same
- * PooledConnection, they are different, even though the represent
- * the same physical connection. See JDBC 2.0 Optional Pacakge spec
- * section 6.2.2
- */
- public void testPoolNewWrapper()
- {
- try
- {
- PooledConnection pc = getPooledConnection();
- con = pc.getConnection();
- Connection con2 = pc.getConnection();
- con2.close();
- pc.close();
- assertTrue("Two calls to PooledConnection.getConnection should not return the same connection wrapper", con != con2);
- }
- catch (SQLException e)
- {
- fail(e.getMessage());
- }
- }
-
- /**
- * Makes sure that exactly one close event is fired for each time a
- * connection handle is closed. Also checks that events are not
- * fired after a given handle has been closed once.
- */
- public void testCloseEvent()
- {
- try
- {
- PooledConnection pc = getPooledConnection();
- CountClose cc = new CountClose();
- pc.addConnectionEventListener(cc);
- con = pc.getConnection();
- assertTrue(cc.getCount() == 0);
- assertTrue(cc.getErrorCount() == 0);
- con.close();
- assertTrue(cc.getCount() == 1);
- assertTrue(cc.getErrorCount() == 0);
- con = pc.getConnection();
- assertTrue(cc.getCount() == 1);
- assertTrue(cc.getErrorCount() == 0);
- con.close();
- assertTrue(cc.getCount() == 2);
- assertTrue(cc.getErrorCount() == 0);
- try
- {
- con.close();
- fail("Should not be able to close a connection wrapper twice");
- }
- catch (SQLException e)
- {}
- assertTrue(cc.getCount() == 2);
- assertTrue(cc.getErrorCount() == 0);
- pc.close();
- }
- catch (SQLException e)
- {
- fail(e.getMessage());
- }
- }
-
- /**
- * Makes sure that close events are not fired after a listener has
- * been removed.
- */
- public void testNoCloseEvent()
- {
- try
- {
- PooledConnection pc = getPooledConnection();
- CountClose cc = new CountClose();
- pc.addConnectionEventListener(cc);
- con = pc.getConnection();
- assertTrue(cc.getCount() == 0);
- assertTrue(cc.getErrorCount() == 0);
- con.close();
- assertTrue(cc.getCount() == 1);
- assertTrue(cc.getErrorCount() == 0);
- pc.removeConnectionEventListener(cc);
- con = pc.getConnection();
- assertTrue(cc.getCount() == 1);
- assertTrue(cc.getErrorCount() == 0);
- con.close();
- assertTrue(cc.getCount() == 1);
- assertTrue(cc.getErrorCount() == 0);
- }
- catch (SQLException e)
- {
- fail(e.getMessage());
- }
- }
-
- /**
- * Makes sure that a listener can be removed while dispatching
- * events. Sometimes this causes a ConcurrentModificationException
- * or something.
- */
- public void testInlineCloseEvent()
- {
- try
- {
- PooledConnection pc = getPooledConnection();
- RemoveClose rc1 = new RemoveClose();
- RemoveClose rc2 = new RemoveClose();
- RemoveClose rc3 = new RemoveClose();
- pc.addConnectionEventListener(rc1);
- pc.addConnectionEventListener(rc2);
- pc.addConnectionEventListener(rc3);
- con = pc.getConnection();
- con.close();
- con = pc.getConnection();
- con.close();
- }
- catch (Exception e)
- {
- fail(e.getMessage());
- }
- }
-
- /**
- * Tests that a close event is not generated when a connection
- * handle is closed automatically due to a new connection handle
- * being opened for the same PooledConnection. See JDBC 2.0
- * Optional Package spec section 6.3
- */
- public void testAutomaticCloseEvent()
- {
- try
- {
- PooledConnection pc = getPooledConnection();
- CountClose cc = new CountClose();
- pc.addConnectionEventListener(cc);
- con = pc.getConnection();
- assertTrue(cc.getCount() == 0);
- assertTrue(cc.getErrorCount() == 0);
- con.close();
- assertTrue(cc.getCount() == 1);
- assertTrue(cc.getErrorCount() == 0);
- con = pc.getConnection();
- assertTrue(cc.getCount() == 1);
- assertTrue(cc.getErrorCount() == 0);
- // Open a 2nd connection, causing the first to be closed. No even should be generated.
- Connection con2 = pc.getConnection();
- assertTrue("Connection handle was not closed when new handle was opened", con.isClosed());
- assertTrue(cc.getCount() == 1);
- assertTrue(cc.getErrorCount() == 0);
- con2.close();
- assertTrue(cc.getCount() == 2);
- assertTrue(cc.getErrorCount() == 0);
- pc.close();
- }
- catch (SQLException e)
- {
- fail(e.getMessage());
- }
- }
-
- /**
- * Makes sure the isClosed method on a connection wrapper does what
- * you'd expect. Checks the usual case, as well as automatic
- * closure when a new handle is opened on the same physical connection.
- */
- public void testIsClosed()
- {
- try
- {
- PooledConnection pc = getPooledConnection();
- Connection con = pc.getConnection();
- assertTrue(!con.isClosed());
- con.close();
- assertTrue(con.isClosed());
- con = pc.getConnection();
- Connection con2 = pc.getConnection();
- assertTrue(con.isClosed());
- assertTrue(!con2.isClosed());
- con2.close();
- assertTrue(con.isClosed());
- pc.close();
- }
- catch (SQLException e)
- {
- fail(e.getMessage());
- }
- }
-
- /**
- * Ensures that a statement generated by a proxied connection returns the
- * proxied connection from getConnection() [not the physical connection].
- */
- public void testStatementConnection() {
- try {
- PooledConnection pc = getPooledConnection();
- Connection con = pc.getConnection();
- Statement s = con.createStatement();
- Connection conRetrieved = s.getConnection();
-
- assertTrue(con.getClass().equals(conRetrieved.getClass()));
- assertTrue(con.equals(conRetrieved));
- } catch (SQLException e) {
- fail(e.getMessage());
- }
- }
-
- /**
- * Ensures that the Statement proxy generated by the Connection handle
- * throws the correct kind of exception.
- */
- public void testStatementProxy() {
- Statement s = null;
- try
- {
- PooledConnection pc = getPooledConnection();
- Connection con = pc.getConnection();
- s = con.createStatement();
- }
- catch (SQLException e)
- {
- fail(e.getMessage());
- }
- try
- {
- s.executeQuery("SELECT * FROM THIS_TABLE_SHOULD_NOT_EXIST");
- fail("An SQL exception was not thrown that should have been");
- }
- catch (SQLException e)
- {
- ; // This is the expected and correct path
- }
- catch (Exception e)
- {
- fail("bad exception; was expecting SQLException, not" +
- e.getClass().getName());
- }
- }
-
- /**
- * Ensures that a prepared statement generated by a proxied connection
- * returns the proxied connection from getConnection() [not the physical
- * connection].
- */
- public void testPreparedStatementConnection() {
- try {
- PooledConnection pc = getPooledConnection();
- Connection con = pc.getConnection();
- PreparedStatement s = con.prepareStatement("select 'x'");
- Connection conRetrieved = s.getConnection();
-
- assertTrue(con.getClass().equals(conRetrieved.getClass()));
- assertTrue(con.equals(conRetrieved));
- } catch (SQLException e) {
- fail(e.getMessage());
- }
- }
-
- /**
- * Ensures that a callable statement generated by a proxied connection
- * returns the proxied connection from getConnection() [not the physical
- * connection].
- */
- public void testCallableStatementConnection() {
- try {
- PooledConnection pc = getPooledConnection();
- Connection con = pc.getConnection();
- CallableStatement s = con.prepareCall("select 'x'");
- Connection conRetrieved = s.getConnection();
-
- assertTrue(con.getClass().equals(conRetrieved.getClass()));
- assertTrue(con.equals(conRetrieved));
- } catch (SQLException e) {
- fail(e.getMessage());
- }
- }
-
- /**
- * Ensure that a statement created from a pool can be used
- * like any other statement in regard to pg extensions.
- */
- public void testStatementsProxyPGStatement() {
- try {
- PooledConnection pc = getPooledConnection();
- con = pc.getConnection();
-
- Statement s = con.createStatement();
- boolean b = ((org.postgresql.PGStatement)s).isUseServerPrepare();
-
- PreparedStatement ps = con.prepareStatement("select 'x'");
- b = ((org.postgresql.PGStatement)ps).isUseServerPrepare();
-
- CallableStatement cs = con.prepareCall("select 'x'");
- b = ((org.postgresql.PGStatement)cs).isUseServerPrepare();
-
- } catch (SQLException e) {
- fail(e.getMessage());
- }
- }
-
- /**
- * Helper class to remove a listener during event dispatching.
- */
- private class RemoveClose implements ConnectionEventListener
- {
- public void connectionClosed(ConnectionEvent event)
- {
- ((PooledConnection)event.getSource()).removeConnectionEventListener(this);
- }
-
- public void connectionErrorOccurred(ConnectionEvent event)
- {
- ((PooledConnection)event.getSource()).removeConnectionEventListener(this);
- }
- }
-
- /**
- * Helper class that implements the event listener interface, and
- * counts the number of events it sees.
- */
- private class CountClose implements ConnectionEventListener
- {
- private int count = 0, errorCount = 0;
- public void connectionClosed(ConnectionEvent event)
- {
- count++;
- }
-
- public void connectionErrorOccurred(ConnectionEvent event)
- {
- errorCount++;
- }
-
- public int getCount()
- {
- return count;
- }
-
- public int getErrorCount()
- {
- return errorCount;
- }
-
- public void clear()
- {
- count = errorCount = 0;
- }
- }
-}
+++ /dev/null
-package org.postgresql.test.jdbc2.optional;
-
-import junit.framework.TestSuite;
-
-/**
- * Test suite for the JDBC 2.0 Optional Package implementation. This
- * includes the DataSource, ConnectionPoolDataSource, and
- * PooledConnection implementations.
- *
- * @version $Revision: 1.4 $
- */
-public class OptionalTestSuite extends TestSuite
-{
- /**
- * Gets the test suite for the entire JDBC 2.0 Optional Package
- * implementation.
- */
- public static TestSuite suite()
- {
- TestSuite suite = new TestSuite();
- suite.addTestSuite(SimpleDataSourceTest.class);
- suite.addTestSuite(ConnectionPoolTest.class);
- suite.addTestSuite(PoolingDataSourceTest.class);
- return suite;
- }
-}
+++ /dev/null
-package org.postgresql.test.jdbc2.optional;
-
-import java.sql.SQLException;
-import org.postgresql.test.TestUtil;
-import org.postgresql.jdbc2.optional.PoolingDataSource;
-import org.postgresql.jdbc2.optional.BaseDataSource;
-
-/**
- * Minimal tests for pooling DataSource. Needs many more.
- *
- * @version $Revision: 1.2 $
- */
-public class PoolingDataSourceTest extends BaseDataSourceTest
-{
- private final static String DS_NAME = "JDBC 2 SE Test DataSource";
-
- /**
- * Constructor required by JUnit
- */
- public PoolingDataSourceTest(String name)
- {
- super(name);
- }
-
- protected void tearDown() throws Exception
- {
- super.tearDown();
- if (bds instanceof PoolingDataSource)
- {
- ((PoolingDataSource) bds).close();
- }
- }
-
- /**
- * Creates and configures a new SimpleDataSource.
- */
- protected void initializeDataSource()
- {
- if (bds == null)
- {
- bds = new PoolingDataSource();
- bds.setServerName(TestUtil.getServer());
- bds.setPortNumber(TestUtil.getPort());
- bds.setDatabaseName(TestUtil.getDatabase());
- bds.setUser(TestUtil.getUser());
- bds.setPassword(TestUtil.getPassword());
- ((PoolingDataSource) bds).setDataSourceName(DS_NAME);
- ((PoolingDataSource) bds).setInitialConnections(2);
- ((PoolingDataSource) bds).setMaxConnections(10);
- }
- }
-
- /**
- * In this case, we *do* want it to be pooled.
- */
- public void testNotPooledConnection()
- {
- try
- {
- con = getDataSourceConnection();
- String name = con.toString();
- con.close();
- con = getDataSourceConnection();
- String name2 = con.toString();
- con.close();
- assertTrue("Pooled DS doesn't appear to be pooling connections!", name.equals(name2));
- }
- catch (SQLException e)
- {
- fail(e.getMessage());
- }
- }
-
- /**
- * In this case, the desired behavior is dereferencing.
- */
- protected void compareJndiDataSource(BaseDataSource oldbds, BaseDataSource bds)
- {
- assertTrue("DataSource was serialized or recreated, should have been dereferenced", bds == oldbds);
- }
-
- /**
- * Check that 2 DS instances can't use the same name.
- */
- public void testCantReuseName()
- {
- initializeDataSource();
- PoolingDataSource pds = new PoolingDataSource();
- try
- {
- pds.setDataSourceName(DS_NAME);
- fail("Should have denied 2nd DataSource with same name");
- }
- catch (IllegalArgumentException e)
- {
- }
- }
-}
+++ /dev/null
-package org.postgresql.test.jdbc2.optional;
-
-import org.postgresql.test.TestUtil;
-import org.postgresql.jdbc2.optional.SimpleDataSource;
-
-/**
- * Performs the basic tests defined in the superclass. Just adds the
- * configuration logic.
- *
- * @version $Revision: 1.4 $
- */
-public class SimpleDataSourceTest extends BaseDataSourceTest
-{
- /**
- * Constructor required by JUnit
- */
- public SimpleDataSourceTest(String name)
- {
- super(name);
- }
-
- /**
- * Creates and configures a new SimpleDataSource.
- */
- protected void initializeDataSource()
- {
- if (bds == null)
- {
- bds = new SimpleDataSource();
- bds.setServerName(TestUtil.getServer());
- bds.setPortNumber(TestUtil.getPort());
- bds.setDatabaseName(TestUtil.getDatabase());
- bds.setUser(TestUtil.getUser());
- bds.setPassword(TestUtil.getPassword());
- }
- }
-}
+++ /dev/null
-package org.postgresql.test.jdbc3;
-
-import org.postgresql.jdbc3.Jdbc3ConnectionPool;
-import org.postgresql.jdbc3.Jdbc3PooledConnection;
-import org.postgresql.test.TestUtil;
-import org.postgresql.test.jdbc2.optional.ConnectionPoolTest;
-import java.sql.SQLException;
-
-import javax.sql.PooledConnection;
-
-/**
- * Tests JDBC3 implementation of ConnectionPoolDataSource.
- *
- * @version $Revision: 1.3 $
- */
-public class Jdbc3ConnectionPoolTest extends ConnectionPoolTest
-{
- public Jdbc3ConnectionPoolTest(String name)
- {
- super(name);
- }
-
- /**
- * Creates and configures a Jdbc3ConnectionPool
- */
- protected void initializeDataSource()
- {
- if (bds == null)
- {
- bds = new Jdbc3ConnectionPool();
- bds.setServerName(TestUtil.getServer());
- bds.setPortNumber(TestUtil.getPort());
- bds.setDatabaseName(TestUtil.getDatabase());
- bds.setUser(TestUtil.getUser());
- bds.setPassword(TestUtil.getPassword());
- }
- }
-
- /**
- * Makes sure this is a JDBC 3 implementation producing JDBC3
- * connections. Depends on toString implementation of
- * connection wrappers.
- */
- public void testConfirmJdbc3Impl()
- {
- try
- {
- initializeDataSource();
- assertTrue("Wrong ConnectionPool impl used by test: " + bds.getClass().getName(), bds instanceof Jdbc3ConnectionPool);
- PooledConnection pc = ((Jdbc3ConnectionPool) bds).getPooledConnection();
- assertTrue("Wrong PooledConnection impl generated by JDBC3 ConnectionPoolDataSource: " + pc.getClass().getName(), pc instanceof Jdbc3PooledConnection);
- assertTrue("Wrong Connnection class used in JDBC3 ConnectionPoolDataSource's PooledConnection impl: " + pc.getConnection().toString(), pc.getConnection().toString().indexOf("Jdbc3") > -1);
- pc.close();
- }
- catch (SQLException e)
- {
- fail(e.getMessage());
- }
- }
-}
+++ /dev/null
-package org.postgresql.test.jdbc3;
-
-import java.sql.Connection;
-import java.sql.SQLException;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-import org.postgresql.test.jdbc2.optional.PoolingDataSourceTest;
-import org.postgresql.test.TestUtil;
-import org.postgresql.jdbc3.Jdbc3PoolingDataSource;
-import org.postgresql.jdbc2.optional.PoolingDataSource;
-
-/**
- * Minimal tests for JDBC3 pooling DataSource. Needs many more.
- *
- * @version $Revision: 1.2 $
- */
-public class Jdbc3PoolingDataSourceTest extends PoolingDataSourceTest
-{
- private final static String DS_NAME = "JDBC 3 Test DataSource";
-
- /**
- * Constructor required by JUnit
- */
- public Jdbc3PoolingDataSourceTest(String name)
- {
- super(name);
- }
-
- /**
- * Creates and configures a new SimpleDataSource.
- */
- protected void initializeDataSource()
- {
- if (bds == null)
- {
- bds = new Jdbc3PoolingDataSource();
- configureDataSource((Jdbc3PoolingDataSource) bds);
- }
- }
-
- private void configureDataSource(PoolingDataSource source)
- {
- String db = TestUtil.getURL();
- source.setServerName(TestUtil.getServer());
- source.setPortNumber(TestUtil.getPort());
- source.setDatabaseName(TestUtil.getDatabase());
- source.setUser(TestUtil.getUser());
- source.setPassword(TestUtil.getPassword());
- source.setDataSourceName(DS_NAME);
- source.setInitialConnections(2);
- source.setMaxConnections(10);
- }
-
- /**
- * Check that 2 DS instances can't use the same name.
- */
- public void testCantReuseName()
- {
- initializeDataSource();
- Jdbc3PoolingDataSource pds = new Jdbc3PoolingDataSource();
- try
- {
- pds.setDataSourceName(DS_NAME);
- fail("Should have denied 2nd DataSource with same name");
- }
- catch (IllegalArgumentException e)
- {
- }
- }
-
- /**
- * Test that JDBC 2 and JDBC 3 DSs come from different buckets
- * as far as creating with the same name
- */
- public void testDifferentImplPools()
- {
- initializeDataSource();
- PoolingDataSource pds = new PoolingDataSource();
- try
- {
- configureDataSource(pds);
- PoolingDataSource p2 = new PoolingDataSource();
- try
- {
- configureDataSource(p2);
- fail("Shouldn't be able to create 2 JDBC 2 DSs with same name");
- }
- catch (IllegalArgumentException e)
- {
- }
- Jdbc3PoolingDataSource p3 = new Jdbc3PoolingDataSource();
- try
- {
- configureDataSource(p3);
- fail("Shouldn't be able to create 2 JDBC 3 DSs with same name");
- }
- catch (IllegalArgumentException e)
- {
- }
- }
- finally
- {
- pds.close();
- }
- }
-
- /**
- * Test that JDBC 2 and JDBC 3 DSs come from different buckets
- * as far as fetching from JNDI
- */
- public void testDifferentImplJndi()
- {
- initializeDataSource();
- PoolingDataSource pds = new PoolingDataSource();
- try
- {
- configureDataSource(pds);
- try
- {
- Connection j3c = getDataSourceConnection();
- Connection j2c = pds.getConnection();
- j2c.close();
- j3c.close();
- InitialContext ctx = getInitialContext();
- ctx.bind("JDBC2", pds);
- ctx.bind("JDBC3", bds);
- pds = (PoolingDataSource) ctx.lookup("JDBC2");
- bds = (Jdbc3PoolingDataSource) ctx.lookup("JDBC3");
- j2c = pds.getConnection();
- j3c = bds.getConnection();
- j2c.close();
- j3c.close();
- }
- catch (SQLException e)
- {
- fail(e.getMessage());
- }
- catch (NamingException e)
- {
- fail(e.getMessage());
- }
- }
- finally
- {
- pds.close();
- }
- }
-}
+++ /dev/null
-package org.postgresql.test.jdbc3;
-
-import java.sql.Connection;
-import java.sql.SQLException;
-import org.postgresql.test.jdbc2.optional.SimpleDataSourceTest;
-import org.postgresql.test.TestUtil;
-import org.postgresql.jdbc3.*;
-
-/**
- * Tests JDBC3 non-pooling DataSource.
- *
- * @version $Revision: 1.2 $
- */
-public class Jdbc3SimpleDataSourceTest extends SimpleDataSourceTest {
- /**
- * Constructor required by JUnit
- */
- public Jdbc3SimpleDataSourceTest(String name)
- {
- super(name);
- }
-
- /**
- * Creates and configures a new SimpleDataSource.
- */
- protected void initializeDataSource()
- {
- if (bds == null)
- {
- bds = new Jdbc3SimpleDataSource();
- bds.setServerName(TestUtil.getServer());
- bds.setPortNumber(TestUtil.getPort());
- bds.setDatabaseName(TestUtil.getDatabase());
- bds.setUser(TestUtil.getUser());
- bds.setPassword(TestUtil.getPassword());
- }
- }
- /**
- * Makes sure this is a JDBC 3 implementation producing JDBC3
- * connections.
- */
- public void testConfirmJdbc3Impl()
- {
- try {
- Connection con = getDataSourceConnection();
- assertTrue("Wrong SimpleDataSource impl used by test: "+bds.getClass().getName(), bds instanceof Jdbc3SimpleDataSource);
- assertTrue("Wrong Connnection class generated by JDBC3 DataSource: "+con.getClass().getName(), con instanceof Jdbc3Connection);
- } catch (SQLException e) {
- fail(e.getMessage());
- }
- }
-}
+++ /dev/null
-package org.postgresql.test.jdbc3;
-
-import junit.framework.TestSuite;
-
-/*
- * Executes all known tests for JDBC3
- */
-public class Jdbc3TestSuite extends TestSuite
-{
-
- /*
- * The main entry point for JUnit
- */
- public static TestSuite suite()
- {
- TestSuite suite = new TestSuite();
- suite.addTestSuite(Jdbc3SimpleDataSourceTest.class);
- suite.addTestSuite(Jdbc3ConnectionPoolTest.class);
- suite.addTestSuite(Jdbc3PoolingDataSourceTest.class);
- return suite;
- }
-}
+++ /dev/null
-package org.postgresql.test.util;
-
-import java.util.*;
-import java.rmi.MarshalledObject;
-import java.io.Serializable;
-import javax.naming.*;
-import javax.naming.spi.ObjectFactory;
-
-/**
- * The Context for a trivial JNDI implementation. This is not meant to
- * be very useful, beyond testing JNDI features of the connection
- * pools. It is not a complete JNDI implementations.
- *
- * @version $Revision: 1.1 $
- */
-public class MiniJndiContext implements Context
-{
- private Map map = new HashMap();
-
- public MiniJndiContext()
- {
- }
-
- public Object lookup(Name name) throws NamingException
- {
- return lookup(name.get(0));
- }
-
- public Object lookup(String name) throws NamingException
- {
- Object o = map.get(name);
- if (o == null)
- {
- return null;
- }
- if (o instanceof Reference)
- {
- Reference ref = (Reference) o;
- try
- {
- Class factoryClass = Class.forName(ref.getFactoryClassName());
- ObjectFactory fac = (ObjectFactory) factoryClass.newInstance();
- Object result = fac.getObjectInstance(ref, null, this, null);
- return result;
- }
- catch (Exception e)
- {
- throw new NamingException("Unable to dereference to object: " + e);
- }
- }
- else if (o instanceof MarshalledObject)
- {
- try
- {
- Object result = ((MarshalledObject) o).get();
- return result;
- }
- catch (java.io.IOException e)
- {
- throw new NamingException("Unable to deserialize object: " + e);
- }
- catch (ClassNotFoundException e)
- {
- throw new NamingException("Unable to deserialize object: " + e);
- }
- }
- else
- {
- throw new NamingException("JNDI Object is neither Referenceable nor Serializable");
- }
- }
-
- public void bind(Name name, Object obj) throws NamingException
- {
- rebind(name.get(0), obj);
- }
-
- public void bind(String name, Object obj) throws NamingException
- {
- rebind(name, obj);
- }
-
- public void rebind(Name name, Object obj) throws NamingException
- {
- rebind(name.get(0), obj);
- }
-
- public void rebind(String name, Object obj) throws NamingException
- {
- if (obj instanceof Referenceable)
- {
- Reference ref = ((Referenceable) obj).getReference();
- map.put(name, ref);
- }
- else if (obj instanceof Serializable)
- {
- try
- {
- MarshalledObject mo = new MarshalledObject(obj);
- map.put(name, mo);
- }
- catch (java.io.IOException e)
- {
- throw new NamingException("Unable to serialize object to JNDI: " + e);
- }
- }
- else
- {
- throw new NamingException("Object to store in JNDI is neither Referenceable nor Serializable");
- }
- }
-
- public void unbind(Name name) throws NamingException
- {
- unbind(name.get(0));
- }
-
- public void unbind(String name) throws NamingException
- {
- map.remove(name);
- }
-
- public void rename(Name oldName, Name newName) throws NamingException
- {
- rename(oldName.get(0), newName.get(0));
- }
-
- public void rename(String oldName, String newName) throws NamingException
- {
- map.put(newName, map.remove(oldName));
- }
-
- public NamingEnumeration list(Name name) throws NamingException
- {
- return null;
- }
-
- public NamingEnumeration list(String name) throws NamingException
- {
- return null;
- }
-
- public NamingEnumeration listBindings(Name name) throws NamingException
- {
- return null;
- }
-
- public NamingEnumeration listBindings(String name) throws NamingException
- {
- return null;
- }
-
- public void destroySubcontext(Name name) throws NamingException
- {
- }
-
- public void destroySubcontext(String name) throws NamingException
- {
- }
-
- public Context createSubcontext(Name name) throws NamingException
- {
- return null;
- }
-
- public Context createSubcontext(String name) throws NamingException
- {
- return null;
- }
-
- public Object lookupLink(Name name) throws NamingException
- {
- return null;
- }
-
- public Object lookupLink(String name) throws NamingException
- {
- return null;
- }
-
- public NameParser getNameParser(Name name) throws NamingException
- {
- return null;
- }
-
- public NameParser getNameParser(String name) throws NamingException
- {
- return null;
- }
-
- public Name composeName(Name name, Name prefix) throws NamingException
- {
- return null;
- }
-
- public String composeName(String name, String prefix)
- throws NamingException
- {
- return null;
- }
-
- public Object addToEnvironment(String propName, Object propVal)
- throws NamingException
- {
- return null;
- }
-
- public Object removeFromEnvironment(String propName)
- throws NamingException
- {
- return null;
- }
-
- public Hashtable getEnvironment() throws NamingException
- {
- return null;
- }
-
- public void close() throws NamingException
- {
- }
-
- public String getNameInNamespace() throws NamingException
- {
- return null;
- }
-}
+++ /dev/null
-package org.postgresql.test.util;
-
-import java.util.*;
-import javax.naming.*;
-import javax.naming.spi.InitialContextFactory;
-
-/**
- * The ICF for a trivial JNDI implementation. This is not meant to
- * be very useful, beyond testing JNDI features of the connection
- * pools.
- *
- * @version $Revision: 1.1 $
- */
-public class MiniJndiContextFactory implements InitialContextFactory
-{
- public Context getInitialContext(Hashtable environment)
- throws NamingException
- {
- return new MiniJndiContext();
- }
-}
+++ /dev/null
-/*-------------------------------------------------------------------------
- *
- * MD5Digest.java
- * MD5-based utility function to obfuscate passwords before network
- * transmission
- *
- * Copyright (c) 2003, PostgreSQL Global Development Group
- *
- * IDENTIFICATION
- * $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/util/MD5Digest.java,v 1.6 2003/11/29 19:52:11 pgsql Exp $
- *
- *-------------------------------------------------------------------------
- */
-package org.postgresql.util;
-
-/*
- * @author Jeremy Wohl
- */
-
-import java.security.*;
-
-public class MD5Digest
-{
- private MD5Digest()
- {}
-
-
- /*
- * Encodes user/password/salt information in the following way:
- * MD5(MD5(password + user) + salt)
- *
- * @param user The connecting user.
- * @param password The connecting user's password.
- * @param salt A four-salt sent by the server.
- *
- * @return A 35-byte array, comprising the string "md5" and an MD5 digest.
- */
- public static byte[] encode(String user, String password, byte []salt)
- {
- MessageDigest md;
- byte[] temp_digest, pass_digest;
- byte[] hex_digest = new byte[35];
-
- try
- {
- md = MessageDigest.getInstance("MD5");
-
- md.update(password.getBytes());
- md.update(user.getBytes());
- temp_digest = md.digest();
-
- bytesToHex(temp_digest, hex_digest, 0);
- md.update(hex_digest, 0, 32);
- md.update(salt);
- pass_digest = md.digest();
-
- bytesToHex(pass_digest, hex_digest, 3);
- hex_digest[0] = (byte) 'm';
- hex_digest[1] = (byte) 'd';
- hex_digest[2] = (byte) '5';
- }
- catch (Exception e)
- {
- ; // "MessageDigest failure; " + e
- }
-
- return hex_digest;
- }
-
-
- /*
- * Turn 16-byte stream into a human-readable 32-byte hex string
- */
- private static void bytesToHex(byte[] bytes, byte[] hex, int offset)
- {
- final char lookup[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
- 'a', 'b', 'c', 'd', 'e', 'f' };
-
- int i, c, j, pos = offset;
-
- for (i = 0; i < 16; i++)
- {
- c = bytes[i] & 0xFF;
- j = c >> 4;
- hex[pos++] = (byte) lookup[j];
- j = (c & 0xF);
- hex[pos++] = (byte) lookup[j];
- }
- }
-}
+++ /dev/null
-/*-------------------------------------------------------------------------
- *
- * MessageTranslator.java
- * A singleton class to translate JDBC driver messages in SQLException's.
- *
- * Copyright (c) 2003, PostgreSQL Global Development Group
- *
- * IDENTIFICATION
- * $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/util/MessageTranslator.java,v 1.6 2003/11/29 19:52:11 pgsql Exp $
- *
- *-------------------------------------------------------------------------
- */
-package org.postgresql.util;
-
-import java.text.MessageFormat;
-import java.util.MissingResourceException;
-import java.util.ResourceBundle;
-
-public class MessageTranslator
-{
-
- // The singleton instance.
- private static MessageTranslator instance = null;
-
- private ResourceBundle bundle;
-
- private MessageTranslator()
- {
- try
- {
- bundle = ResourceBundle.getBundle("org.postgresql.errors");
- }
- catch (MissingResourceException e)
- {
- // translation files have not been installed.
- bundle = null;
- }
- }
-
- // Synchronized, otherwise multiple threads may perform the test and
- // assign to the singleton instance simultaneously.
- private synchronized final static MessageTranslator getInstance()
- {
- if (instance == null)
- {
- instance = new MessageTranslator();
- }
- return instance;
- }
-
- public final static String translate(String id, Object[] args)
- {
-
- MessageTranslator translator = MessageTranslator.getInstance();
-
- return translator._translate(id, args);
- }
-
- public final static String translate(String id, Object arg)
- {
- MessageTranslator translator = MessageTranslator.getInstance();
- Object[] args = new Object[1];
- args[0] = arg;
- return translator._translate(id, args);
- }
-
- private final String _translate(String id, Object[] args)
- {
- String message;
-
- if (bundle != null && id != null)
- {
- // Now look up a localized message. If one is not found, then use
- // the supplied message instead.
- try
- {
- message = bundle.getString(id);
- }
- catch (MissingResourceException e)
- {
- message = id;
- }
- }
- else
- {
- message = id;
- }
-
- // Expand any arguments
- if (args != null && message != null)
- {
- message = MessageFormat.format(message, args);
- }
-
- return message;
- }
-}
+++ /dev/null
-/*-------------------------------------------------------------------------
- *
- * PGbytea.java
- * Converts to and from the postgresql bytea datatype used by the backend.
- *
- * Copyright (c) 2003, PostgreSQL Global Development Group
- *
- * IDENTIFICATION
- * $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/util/PGbytea.java,v 1.9 2003/11/29 19:52:11 pgsql Exp $
- *
- *-------------------------------------------------------------------------
- */
-package org.postgresql.util;
-
-import java.sql.*;
-
-public class PGbytea
-{
-
- /*
- * Converts a PG bytea raw value (i.e. the raw binary representation
- * of the bytea data type) into a java byte[]
- */
- public static byte[] toBytes(byte[] s) throws SQLException
- {
- if (s == null)
- return null;
- int slength = s.length;
- byte[] buf = new byte[slength];
- int bufpos = 0;
- int thebyte;
- byte nextbyte;
- byte secondbyte;
- for (int i = 0; i < slength; i++)
- {
- nextbyte = s[i];
- if (nextbyte == (byte)'\\')
- {
- secondbyte = s[++i];
- if (secondbyte == (byte)'\\')
- {
- //escaped \
- buf[bufpos++] = (byte)'\\';
- }
- else
- {
- thebyte = (secondbyte - 48) * 64 + (s[++i] - 48) * 8 + (s[++i] - 48);
- if (thebyte > 127)
- thebyte -= 256;
- buf[bufpos++] = (byte)thebyte;
- }
- }
- else
- {
- buf[bufpos++] = nextbyte;
- }
- }
- byte[] l_return = new byte[bufpos];
- System.arraycopy(buf, 0, l_return, 0, bufpos);
- return l_return;
- }
-
- /*
- * Converts a java byte[] into a PG bytea string (i.e. the text
- * representation of the bytea data type)
- */
- public static String toPGString(byte[] p_buf) throws SQLException
- {
- if (p_buf == null)
- return null;
- StringBuffer l_strbuf = new StringBuffer(2 * p_buf.length);
- for (int i = 0; i < p_buf.length; i++)
- {
- int l_int = (int)p_buf[i];
- if (l_int < 0)
- {
- l_int = 256 + l_int;
- }
- //we escape the same non-printable characters as the backend
- //we must escape all 8bit characters otherwise when convering
- //from java unicode to the db character set we may end up with
- //question marks if the character set is SQL_ASCII
- if (l_int < 040 || l_int > 0176)
- {
- //escape charcter with the form \000, but need two \\ because of
- //the parser
- l_strbuf.append("\\");
- l_strbuf.append((char)(((l_int >> 6) & 0x3) + 48));
- l_strbuf.append((char)(((l_int >> 3) & 0x7) + 48));
- l_strbuf.append((char)((l_int & 0x07) + 48));
- }
- else if (p_buf[i] == (byte)'\\')
- {
- //escape the backslash character as \\, but need four \\\\ because
- //of the parser
- l_strbuf.append("\\\\");
- }
- else
- {
- //other characters are left alone
- l_strbuf.append((char)p_buf[i]);
- }
- }
- return l_strbuf.toString();
- }
-
-
-}
+++ /dev/null
-/*-------------------------------------------------------------------------
- *
- * PGmoney.java
- * This implements a class that handles the PostgreSQL money and cash types
- *
- * Copyright (c) 2003, PostgreSQL Global Development Group
- *
- * IDENTIFICATION
- * $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/util/PGmoney.java,v 1.7 2003/11/29 19:52:11 pgsql Exp $
- *
- *-------------------------------------------------------------------------
- */
-package org.postgresql.util;
-
-
-import java.io.Serializable;
-import java.sql.SQLException;
-
-public class PGmoney extends PGobject implements Serializable, Cloneable
-{
- /*
- * The value of the field
- */
- public double val;
-
- /*
- * @param value of field
- */
- public PGmoney(double value)
- {
- this();
- val = value;
- }
-
- public PGmoney(String value) throws SQLException
- {
- this();
- setValue(value);
- }
-
- /*
- * Required by the driver
- */
- public PGmoney()
- {
- setType("money");
- }
-
- public void setValue(String s) throws SQLException
- {
- try
- {
- String s1;
- boolean negative;
-
- negative = (s.charAt(0) == '(') ;
-
- // Remove any () (for negative) & currency symbol
- s1 = PGtokenizer.removePara(s).substring(1);
-
- // Strip out any , in currency
- int pos = s1.indexOf(',');
- while (pos != -1)
- {
- s1 = s1.substring(0, pos) + s1.substring(pos + 1);
- pos = s1.indexOf(',');
- }
-
- val = Double.valueOf(s1).doubleValue();
- val = negative ? -val : val;
-
- }
- catch (NumberFormatException e)
- {
- throw new PSQLException("postgresql.money", PSQLState.NUMERIC_CONSTANT_OUT_OF_RANGE, e);
- }
- }
-
- public boolean equals(Object obj)
- {
- if (obj instanceof PGmoney)
- {
- PGmoney p = (PGmoney)obj;
- return val == p.val;
- }
- return false;
- }
-
- /*
- * This must be overidden to allow the object to be cloned
- */
- public Object clone()
- {
- return new PGmoney(val);
- }
-
- public String getValue()
- {
- if (val < 0)
- {
- return "-$" + ( -val);
- }
- else
- {
- return "$" + val;
- }
- }
-}
+++ /dev/null
-/*-------------------------------------------------------------------------
- *
- * PGobject.java
- * PGobject is a class used to describe unknown types
- * An unknown type is any type that is unknown by JDBC Standards
- *
- * Copyright (c) 2003, PostgreSQL Global Development Group
- *
- * IDENTIFICATION
- * $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/util/PGobject.java,v 1.5 2003/11/29 19:52:11 pgsql Exp $
- *
- *-------------------------------------------------------------------------
- */
-package org.postgresql.util;
-
-import java.io.Serializable;
-import java.sql.SQLException;
-
-public class PGobject implements Serializable, Cloneable
-{
- protected String type;
- protected String value;
-
- /*
- * This is called by org.postgresql.Connection.getObject() to create the
- * object.
- */
- public PGobject()
- {}
-
- /*
- * This method sets the type of this object.
- *
- *
It should not be extended by subclasses, hence its final
- *
- * @param type a string describing the type of the object
- */
- public final void setType(String type)
- {
- this.type = type;
- }
-
- /*
- * This method sets the value of this object. It must be overidden.
- *
- * @param value a string representation of the value of the object
- * @exception SQLException thrown if value is invalid for this type
- */
- public void setValue(String value) throws SQLException
- {
- this.value = value;
- }
-
- /*
- * As this cannot change during the life of the object, it's final.
- * @return the type name of this object
- */
- public final String getType()
- {
- return type;
- }
-
- /*
- * This must be overidden, to return the value of the object, in the
- * form required by org.postgresql.
- * @return the value of this object
- */
- public String getValue()
- {
- return value;
- }
-
- /*
- * This must be overidden to allow comparisons of objects
- * @param obj Object to compare with
- * @return true if the two boxes are identical
- */
- public boolean equals(Object obj)
- {
- if (obj instanceof PGobject)
- return ((PGobject)obj).getValue().equals(getValue());
- return false;
- }
-
- /*
- * This must be overidden to allow the object to be cloned
- */
- public Object clone()
- {
- PGobject obj = new PGobject();
- obj.type = type;
- obj.value = value;
- return obj;
- }
-
- /*
- * This is defined here, so user code need not overide it.
- * @return the value of this object, in the syntax expected by org.postgresql
- */
- public String toString()
- {
- return getValue();
- }
-}
+++ /dev/null
-/*-------------------------------------------------------------------------
- *
- * PGtokenizer.java
- * This class is used to tokenize the text output of org.postgres.
- *
- * Copyright (c) 2003, PostgreSQL Global Development Group
- *
- * IDENTIFICATION
- * $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/util/PGtokenizer.java,v 1.8 2003/11/29 19:52:11 pgsql Exp $
- *
- *-------------------------------------------------------------------------
- */
-package org.postgresql.util;
-
-import java.util.Vector;
-
-/*
- * It's mainly used by the geometric classes, but is useful in parsing any
- * output from custom data types output from org.postgresql.
- *
- * @see org.postgresql.geometric.PGbox
- * @see org.postgresql.geometric.PGcircle
- * @see org.postgresql.geometric.PGlseg
- * @see org.postgresql.geometric.PGpath
- * @see org.postgresql.geometric.PGpoint
- * @see org.postgresql.geometric.PGpolygon
- */
-public class PGtokenizer
-{
- // Our tokens
- protected Vector tokens;
-
- /*
- * Create a tokeniser.
- *
- *
We could have used StringTokenizer to do this, however, we needed to
- * handle nesting of '(' ')' '[' ']' '<' and '>' as these are used
- * by the geometric data types.
- *
- * @param string containing tokens
- * @param delim single character to split the tokens
- */
- public PGtokenizer(String string, char delim)
- {
- tokenize(string, delim);
- }
-
- /*
- * This resets this tokenizer with a new string and/or delimiter.
- *
- * @param string containing tokens
- * @param delim single character to split the tokens
- */
- public int tokenize(String string, char delim)
- {
- tokens = new Vector();
-
- // nest holds how many levels we are in the current token.
- // if this is > 0 then we don't split a token when delim is matched.
- //
- // The Geometric datatypes use this, because often a type may have others
- // (usualls PGpoint) imbedded within a token.
- //
- // Peter 1998 Jan 6 - Added < and > to the nesting rules
- int nest = 0, p, s;
-
- for (p = 0, s = 0;p < string.length();p++)
- {
- char c = string.charAt(p);
-
- // increase nesting if an open character is found
- if (c == '(' || c == '[' || c == '<')
- nest++;
-
- // decrease nesting if a close character is found
- if (c == ')' || c == ']' || c == '>')
- nest--;
-
- if (nest == 0 && c == delim)
- {
- tokens.addElement(string.substring(s, p));
- s = p + 1; // +1 to skip the delimiter
- }
-
- }
-
- // Don't forget the last token ;-)
-
-
-
- if (s < string.length())
- tokens.addElement(string.substring(s));
-
- return tokens.size();
- }
-
- /*
- * @return the number of tokens available
- */
- public int getSize()
- {
- return tokens.size();
- }
-
- /*
- * @param n Token number ( 0 ... getSize()-1 )
- * @return The token value
- */
- public String getToken(int n)
- {
- return (String)tokens.elementAt(n);
- }
-
- /*
- * This returns a new tokenizer based on one of our tokens.
- *
- * The geometric datatypes use this to process nested tokens (usually
- * PGpoint).
- *
- * @param n Token number ( 0 ... getSize()-1 )
- * @param delim The delimiter to use
- * @return A new instance of PGtokenizer based on the token
- */
- public PGtokenizer tokenizeToken(int n, char delim)
- {
- return new PGtokenizer(getToken(n), delim);
- }
-
- /*
- * This removes the lead/trailing strings from a string
- * @param s Source string
- * @param l Leading string to remove
- * @param t Trailing string to remove
- * @return String without the lead/trailing strings
- */
- public static String remove(String s, String l, String t)
- {
- if (s.startsWith(l))
- s = s.substring(l.length());
- if (s.endsWith(t))
- s = s.substring(0, s.length() - t.length());
- return s;
- }
-
- /*
- * This removes the lead/trailing strings from all tokens
- * @param l Leading string to remove
- * @param t Trailing string to remove
- */
- public void remove(String l, String t)
- {
- for (int i = 0;i < tokens.size();i++)
- {
- tokens.setElementAt(remove((String)tokens.elementAt(i), l, t), i);
- }
- }
-
- /*
- * Removes ( and ) from the beginning and end of a string
- * @param s String to remove from
- * @return String without the ( or )
- */
- public static String removePara(String s)
- {
- return remove(s, "(", ")");
- }
-
- /*
- * Removes ( and ) from the beginning and end of all tokens
- * @return String without the ( or )
- */
- public void removePara()
- {
- remove("(", ")");
- }
-
- /*
- * Removes [ and ] from the beginning and end of a string
- * @param s String to remove from
- * @return String without the [ or ]
- */
- public static String removeBox(String s)
- {
- return remove(s, "[", "]");
- }
-
- /*
- * Removes [ and ] from the beginning and end of all tokens
- * @return String without the [ or ]
- */
- public void removeBox()
- {
- remove("[", "]");
- }
-
- /*
- * Removes < and > from the beginning and end of a string
- * @param s String to remove from
- * @return String without the < or >
- */
- public static String removeAngle(String s)
- {
- return remove(s, "<", ">");
- }
-
- /*
- * Removes < and > from the beginning and end of all tokens
- * @return String without the < or >
- */
- public void removeAngle()
- {
- remove("<", ">");
- }
-}
+++ /dev/null
-/*-------------------------------------------------------------------------
- *
- * PSQLException.java
- * This class extends SQLException, and provides our internationalisation
- * handling
- *
- * Copyright (c) 2003, PostgreSQL Global Development Group
- *
- * IDENTIFICATION
- * $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/util/PSQLException.java,v 1.15 2003/12/12 18:36:20 davec Exp $
- *
- *-------------------------------------------------------------------------
- */
-package org.postgresql.util;
-
-import java.io.ByteArrayOutputStream;
-import java.io.PrintWriter;
-import java.sql.SQLException;
-import java.util.Hashtable;
-import org.postgresql.Driver;
-
-public class PSQLException extends SQLException
-{
- private String message;
- private PSQLState state;
-
- //-------start new constructors-------
-
- public PSQLException(String msg, PSQLState state)
- {
- this.state = state;
- translate(msg, null);
- if (Driver.logDebug)
- Driver.debug("Exception: " + this);
- }
-
- public PSQLException(String msg, PSQLState state, Object[] argv)
- {
- this.state = state;
- translate(msg, argv);
- if (Driver.logDebug)
- Driver.debug("Exception: " + this);
- }
-
- //Helper version for one arg
- public PSQLException(String msg, PSQLState state, Object arg1)
- {
- this.state = state;
- Object[] argv = new Object[1];
- argv[0] = arg1;
- translate(msg, argv);
- if (Driver.logDebug)
- Driver.debug("Exception: " + this);
- }
-
- //Helper version for two args
- public PSQLException(String msg, PSQLState state, Object arg1, Object arg2)
- {
- this.state = state;
- Object[] argv = new Object[2];
- argv[0] = arg1;
- argv[1] = arg2;
- translate(msg, argv);
- if (Driver.logDebug)
- Driver.debug("Exception: " + this);
- }
-
- //-------end new constructors-------
-
- public static PSQLException parseServerError(String p_serverError)
- {
- if (Driver.logDebug)
- Driver.debug("Constructing exception from server message: " + p_serverError);
- char[] l_chars = p_serverError.toCharArray();
- int l_pos = 0;
- int l_length = l_chars.length;
- Hashtable l_mesgParts = new Hashtable();
- while (l_pos < l_length) {
- char l_mesgType = l_chars[l_pos];
- if (l_mesgType != '\0') {
- l_pos++;
- int l_startString = l_pos;
- while (l_chars[l_pos] != '\0' && l_pos < l_length) {
- l_pos++;
- }
- String l_mesgPart = new String(l_chars, l_startString, l_pos - l_startString);
- l_mesgParts.put(new Character(l_mesgType),l_mesgPart);
- }
- l_pos++;
- }
-
- //Now construct the message from what the server sent
- //The general format is:
- //SEVERITY: Message \n
- // Detail: \n
- // Hint: \n
- // Position: \n
- // Where: \n
- // Location: File:Line:Routine \n
- // SQLState: \n
- //
- //Normally only the message and detail is included.
- //If INFO level logging is enabled then detail, hint, position and where are
- //included. If DEBUG level logging is enabled then all information
- //is included.
-
- StringBuffer l_totalMessage = new StringBuffer();
- String l_message = (String)l_mesgParts.get(MESSAGE_TYPE_S);
- if (l_message != null)
- l_totalMessage.append(l_message).append(": ");
- l_message = (String)l_mesgParts.get(MESSAGE_TYPE_M);
- if (l_message != null)
- l_totalMessage.append(l_message).append('\n');
- if (Driver.logInfo) {
- l_message = (String)l_mesgParts.get(MESSAGE_TYPE_D);
- if (l_message != null)
- l_totalMessage.append(" ").append(MessageTranslator.translate("postgresql.error.detail", l_message)).append('\n');
- l_message = (String)l_mesgParts.get(MESSAGE_TYPE_H);
- if (l_message != null)
- l_totalMessage.append(" ").append(MessageTranslator.translate("postgresql.error.hint", l_message)).append('\n');
- l_message = (String)l_mesgParts.get(MESSAGE_TYPE_P);
- if (l_message != null)
- l_totalMessage.append(" ").append(MessageTranslator.translate("postgresql.error.position", l_message)).append('\n');
- l_message = (String)l_mesgParts.get(MESSAGE_TYPE_W);
- if (l_message != null)
- l_totalMessage.append(" ").append(MessageTranslator.translate("postgresql.error.where", l_message)).append('\n');
- }
- if (Driver.logDebug) {
- String l_file = (String)l_mesgParts.get(MESSAGE_TYPE_F);
- String l_line = (String)l_mesgParts.get(MESSAGE_TYPE_L);
- String l_routine = (String)l_mesgParts.get(MESSAGE_TYPE_R);
- if (l_file != null || l_line != null || l_routine != null)
- l_totalMessage.append(" ").append(MessageTranslator.translate("postgresql.error.location", l_file+":"+l_line+":"+l_routine)).append('\n');
- l_message = (String)l_mesgParts.get(MESSAGE_TYPE_C);
- if (l_message != null)
- l_totalMessage.append(" ").append("ServerSQLState: " + l_message).append('\n');
- }
-
- PSQLException l_return = new PSQLException(l_totalMessage.toString(), PSQLState.UNKNOWN_STATE);
- l_return.state = new PSQLState((String)l_mesgParts.get(MESSAGE_TYPE_C));
- return l_return;
- }
-
- private static final Character MESSAGE_TYPE_S = new Character('S');
- private static final Character MESSAGE_TYPE_M = new Character('M');
- private static final Character MESSAGE_TYPE_D = new Character('D');
- private static final Character MESSAGE_TYPE_H = new Character('H');
- private static final Character MESSAGE_TYPE_P = new Character('P');
- private static final Character MESSAGE_TYPE_W = new Character('W');
- private static final Character MESSAGE_TYPE_F = new Character('F');
- private static final Character MESSAGE_TYPE_L = new Character('L');
- private static final Character MESSAGE_TYPE_R = new Character('R');
- private static final Character MESSAGE_TYPE_C = new Character('C');
-
- /*
- * This provides the same functionality to SQLException
- * @param error Error string
- */
- public PSQLException(String error)
- {
- translate(error, null);
- if (Driver.logDebug)
- Driver.debug("Exception: " + this);
- }
-
- /*
- * Helper version for 1 arg
- */
- public PSQLException(String error, Object arg)
- {
- Object[] argv = new Object[1];
- argv[0] = arg;
- translate(error, argv);
- if (Driver.logDebug)
- Driver.debug("Exception: " + this);
- }
-
-
- private void translate(String error, Object[] args) {
- //We convert exception objects to Strings that
- //contain the full stack trace
- if (args != null) {
- for (int i = 0; i < args.length; i++) {
- if (args[i] instanceof Exception && !(args[i] instanceof PSQLException)) {
- Exception ex = (Exception) args[i];
- try {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- PrintWriter pw = new PrintWriter(baos);
- pw.println("Exception: " + ex.toString() + "\nStack Trace:\n");
- ex.printStackTrace(pw);
- pw.println("End of Stack Trace");
- pw.flush();
- args[i] = baos.toString();
- pw.close();
- baos.close();
- }
- catch (Exception ioe)
- {
- args[i] = ex.toString() + "\nIO Error on stack trace generation! " + ioe.toString();
- }
- }
- }
- }
-
- message = MessageTranslator.translate(error, args);
-
- }
-
- /*
- * Overides Throwable
- */
- public String getLocalizedMessage()
- {
- return message;
- }
-
- /*
- * Overides Throwable
- */
- public String getMessage()
- {
- return message;
- }
-
- public String getSQLState()
- {
- if (state == null)
- return PSQLState.UNKNOWN_STATE.getState();
- return state.getState();
- }
-}
+++ /dev/null
-/*-------------------------------------------------------------------------
- *
- * PSQLState.java
- * This class is used for holding SQLState codes.
- *
- * Copyright (c) 2003, PostgreSQL Global Development Group
- *
- *-------------------------------------------------------------------------
- */
-
- package org.postgresql.util;
-
- public class PSQLState implements java.io.Serializable
- {
- private String state;
-
- public String getState()
- {
- return this.state;
- }
-
- public PSQLState(String state)
- {
- this.state = state;
- }
-
-
- // begin constant state codes
- public final static PSQLState UNKNOWN_STATE = new PSQLState("");
- public final static PSQLState NO_DATA = new PSQLState("02000");
- public final static PSQLState INVALID_PARAMETER_TYPE = new PSQLState("07006");
- public final static PSQLState CONNECTION_UNABLE_TO_CONNECT = new PSQLState("08001");
- public final static PSQLState CONNECTION_DOES_NOT_EXIST = new PSQLState("08003");
- public final static PSQLState CONNECTION_REJECTED = new PSQLState("08004");
- public final static PSQLState CONNECTION_FAILURE = new PSQLState("08006");
- public final static PSQLState CONNECTION_FAILURE_DURING_TRANSACTION = new PSQLState("08007");
- public final static PSQLState COMMUNICATION_ERROR = new PSQLState("08S01");
- public final static PSQLState NOT_IMPLEMENTED = new PSQLState("0A000");
- public final static PSQLState DATA_ERROR = new PSQLState("22000");
- public final static PSQLState NUMERIC_VALUE_OUT_OF_RANGE = new PSQLState("22003");
- public final static PSQLState BAD_DATETIME_FORMAT = new PSQLState("22007");
- public final static PSQLState MOST_SPECIFIC_TYPE_DOES_NOT_MATCH = new PSQLState("2200G");
- public final static PSQLState INVALID_PARAMETER_VALUE = new PSQLState("22023");
- public final static PSQLState TRANSACTION_STATE_INVALID = new PSQLState("25000");
- public final static PSQLState STATEMENT_NOT_ALLOWED_IN_FUNCTION_CALL = new PSQLState("2F003");
- public final static PSQLState NUMERIC_CONSTANT_OUT_OF_RANGE = new PSQLState("42820'");
- public final static PSQLState DATA_TYPE_MISMATCH = new PSQLState("42821");
- public final static PSQLState SYSTEM_ERROR = new PSQLState("60000");
- public final static PSQLState UNEXPECTED_ERROR = new PSQLState("99999");
-
-}
+++ /dev/null
-/*-------------------------------------------------------------------------
- *
- * UnixCrypt.java
- * Contains static methods to encrypt and compare
- * passwords with Unix encrypted passwords.
- *
- * Copyright (c) 2003, PostgreSQL Global Development Group
- *
- * IDENTIFICATION
- * $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/util/UnixCrypt.java,v 1.5 2003/11/29 19:52:11 pgsql Exp $
- *
- *-------------------------------------------------------------------------
- */
-package org.postgresql.util;
-
-/*
- * John Dumas's Java Crypt page for the original source.
- *
- */
-public class UnixCrypt extends Object
-{
- //
- // Null constructor - can't instantiate class
- private UnixCrypt()
- {}
-
- private static final char[] saltChars =
- ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./".toCharArray());
-
- private static final int ITERATIONS = 16;
-
- private static final int con_salt[] =
- {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
- 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
- 0x0A, 0x0B, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A,
- 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12,
- 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A,
- 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22,
- 0x23, 0x24, 0x25, 0x20, 0x21, 0x22, 0x23, 0x24,
- 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C,
- 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34,
- 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C,
- 0x3D, 0x3E, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00,
- };
-
- private static final boolean shifts2[] =
- {
- false, false, true, true, true, true, true, true,
- false, true, true, true, true, true, true, false
- };
-
- private static final int skb[][] =
- {
- {
- /* for C bits (numbered as per FIPS 46) 1 2 3 4 5 6 */
- 0x00000000, 0x00000010, 0x20000000, 0x20000010,
- 0x00010000, 0x00010010, 0x20010000, 0x20010010,
- 0x00000800, 0x00000810, 0x20000800, 0x20000810,
- 0x00010800, 0x00010810, 0x20010800, 0x20010810,
- 0x00000020, 0x00000030, 0x20000020, 0x20000030,
- 0x00010020, 0x00010030, 0x20010020, 0x20010030,
- 0x00000820, 0x00000830, 0x20000820, 0x20000830,
- 0x00010820, 0x00010830, 0x20010820, 0x20010830,
- 0x00080000, 0x00080010, 0x20080000, 0x20080010,
- 0x00090000, 0x00090010, 0x20090000, 0x20090010,
- 0x00080800, 0x00080810, 0x20080800, 0x20080810,
- 0x00090800, 0x00090810, 0x20090800, 0x20090810,
- 0x00080020, 0x00080030, 0x20080020, 0x20080030,
- 0x00090020, 0x00090030, 0x20090020, 0x20090030,
- 0x00080820, 0x00080830, 0x20080820, 0x20080830,
- 0x00090820, 0x00090830, 0x20090820, 0x20090830,
- },
- {
- /* for C bits (numbered as per FIPS 46) 7 8 10 11 12 13 */
- 0x00000000, 0x02000000, 0x00002000, 0x02002000,
- 0x00200000, 0x02200000, 0x00202000, 0x02202000,
- 0x00000004, 0x02000004, 0x00002004, 0x02002004,
- 0x00200004, 0x02200004, 0x00202004, 0x02202004,
- 0x00000400, 0x02000400, 0x00002400, 0x02002400,
- 0x00200400, 0x02200400, 0x00202400, 0x02202400,
- 0x00000404, 0x02000404, 0x00002404, 0x02002404,
- 0x00200404, 0x02200404, 0x00202404, 0x02202404,
- 0x10000000, 0x12000000, 0x10002000, 0x12002000,
- 0x10200000, 0x12200000, 0x10202000, 0x12202000,
- 0x10000004, 0x12000004, 0x10002004, 0x12002004,
- 0x10200004, 0x12200004, 0x10202004, 0x12202004,
- 0x10000400, 0x12000400, 0x10002400, 0x12002400,
- 0x10200400, 0x12200400, 0x10202400, 0x12202400,
- 0x10000404, 0x12000404, 0x10002404, 0x12002404,
- 0x10200404, 0x12200404, 0x10202404, 0x12202404,
- },
- {
- /* for C bits (numbered as per FIPS 46) 14 15 16 17 19 20 */
- 0x00000000, 0x00000001, 0x00040000, 0x00040001,
- 0x01000000, 0x01000001, 0x01040000, 0x01040001,
- 0x00000002, 0x00000003, 0x00040002, 0x00040003,
- 0x01000002, 0x01000003, 0x01040002, 0x01040003,
- 0x00000200, 0x00000201, 0x00040200, 0x00040201,
- 0x01000200, 0x01000201, 0x01040200, 0x01040201,
- 0x00000202, 0x00000203, 0x00040202, 0x00040203,
- 0x01000202, 0x01000203, 0x01040202, 0x01040203,
- 0x08000000, 0x08000001, 0x08040000, 0x08040001,
- 0x09000000, 0x09000001, 0x09040000, 0x09040001,
- 0x08000002, 0x08000003, 0x08040002, 0x08040003,
- 0x09000002, 0x09000003, 0x09040002, 0x09040003,
- 0x08000200, 0x08000201, 0x08040200, 0x08040201,
- 0x09000200, 0x09000201, 0x09040200, 0x09040201,
- 0x08000202, 0x08000203, 0x08040202, 0x08040203,
- 0x09000202, 0x09000203, 0x09040202, 0x09040203,
- },
- {
- /* for C bits (numbered as per FIPS 46) 21 23 24 26 27 28 */
- 0x00000000, 0x00100000, 0x00000100, 0x00100100,
- 0x00000008, 0x00100008, 0x00000108, 0x00100108,
- 0x00001000, 0x00101000, 0x00001100, 0x00101100,
- 0x00001008, 0x00101008, 0x00001108, 0x00101108,
- 0x04000000, 0x04100000, 0x04000100, 0x04100100,
- 0x04000008, 0x04100008, 0x04000108, 0x04100108,
- 0x04001000, 0x04101000, 0x04001100, 0x04101100,
- 0x04001008, 0x04101008, 0x04001108, 0x04101108,
- 0x00020000, 0x00120000, 0x00020100, 0x00120100,
- 0x00020008, 0x00120008, 0x00020108, 0x00120108,
- 0x00021000, 0x00121000, 0x00021100, 0x00121100,
- 0x00021008, 0x00121008, 0x00021108, 0x00121108,
- 0x04020000, 0x04120000, 0x04020100, 0x04120100,
- 0x04020008, 0x04120008, 0x04020108, 0x04120108,
- 0x04021000, 0x04121000, 0x04021100, 0x04121100,
- 0x04021008, 0x04121008, 0x04021108, 0x04121108,
- },
- {
- /* for D bits (numbered as per FIPS 46) 1 2 3 4 5 6 */
- 0x00000000, 0x10000000, 0x00010000, 0x10010000,
- 0x00000004, 0x10000004, 0x00010004, 0x10010004,
- 0x20000000, 0x30000000, 0x20010000, 0x30010000,
- 0x20000004, 0x30000004, 0x20010004, 0x30010004,
- 0x00100000, 0x10100000, 0x00110000, 0x10110000,
- 0x00100004, 0x10100004, 0x00110004, 0x10110004,
- 0x20100000, 0x30100000, 0x20110000, 0x30110000,
- 0x20100004, 0x30100004, 0x20110004, 0x30110004,
- 0x00001000, 0x10001000, 0x00011000, 0x10011000,
- 0x00001004, 0x10001004, 0x00011004, 0x10011004,
- 0x20001000, 0x30001000, 0x20011000, 0x30011000,
- 0x20001004, 0x30001004, 0x20011004, 0x30011004,
- 0x00101000, 0x10101000, 0x00111000, 0x10111000,
- 0x00101004, 0x10101004, 0x00111004, 0x10111004,
- 0x20101000, 0x30101000, 0x20111000, 0x30111000,
- 0x20101004, 0x30101004, 0x20111004, 0x30111004,
- },
- {
- /* for D bits (numbered as per FIPS 46) 8 9 11 12 13 14 */
- 0x00000000, 0x08000000, 0x00000008, 0x08000008,
- 0x00000400, 0x08000400, 0x00000408, 0x08000408,
- 0x00020000, 0x08020000, 0x00020008, 0x08020008,
- 0x00020400, 0x08020400, 0x00020408, 0x08020408,
- 0x00000001, 0x08000001, 0x00000009, 0x08000009,
- 0x00000401, 0x08000401, 0x00000409, 0x08000409,
- 0x00020001, 0x08020001, 0x00020009, 0x08020009,
- 0x00020401, 0x08020401, 0x00020409, 0x08020409,
- 0x02000000, 0x0A000000, 0x02000008, 0x0A000008,
- 0x02000400, 0x0A000400, 0x02000408, 0x0A000408,
- 0x02020000, 0x0A020000, 0x02020008, 0x0A020008,
- 0x02020400, 0x0A020400, 0x02020408, 0x0A020408,
- 0x02000001, 0x0A000001, 0x02000009, 0x0A000009,
- 0x02000401, 0x0A000401, 0x02000409, 0x0A000409,
- 0x02020001, 0x0A020001, 0x02020009, 0x0A020009,
- 0x02020401, 0x0A020401, 0x02020409, 0x0A020409,
- },
- {
- /* for D bits (numbered as per FIPS 46) 16 17 18 19 20 21 */
- 0x00000000, 0x00000100, 0x00080000, 0x00080100,
- 0x01000000, 0x01000100, 0x01080000, 0x01080100,
- 0x00000010, 0x00000110, 0x00080010, 0x00080110,
- 0x01000010, 0x01000110, 0x01080010, 0x01080110,
- 0x00200000, 0x00200100, 0x00280000, 0x00280100,
- 0x01200000, 0x01200100, 0x01280000, 0x01280100,
- 0x00200010, 0x00200110, 0x00280010, 0x00280110,
- 0x01200010, 0x01200110, 0x01280010, 0x01280110,
- 0x00000200, 0x00000300, 0x00080200, 0x00080300,
- 0x01000200, 0x01000300, 0x01080200, 0x01080300,
- 0x00000210, 0x00000310, 0x00080210, 0x00080310,
- 0x01000210, 0x01000310, 0x01080210, 0x01080310,
- 0x00200200, 0x00200300, 0x00280200, 0x00280300,
- 0x01200200, 0x01200300, 0x01280200, 0x01280300,
- 0x00200210, 0x00200310, 0x00280210, 0x00280310,
- 0x01200210, 0x01200310, 0x01280210, 0x01280310,
- },
- {
- /* for D bits (numbered as per FIPS 46) 22 23 24 25 27 28 */
- 0x00000000, 0x04000000, 0x00040000, 0x04040000,
- 0x00000002, 0x04000002, 0x00040002, 0x04040002,
- 0x00002000, 0x04002000, 0x00042000, 0x04042000,
- 0x00002002, 0x04002002, 0x00042002, 0x04042002,
- 0x00000020, 0x04000020, 0x00040020, 0x04040020,
- 0x00000022, 0x04000022, 0x00040022, 0x04040022,
- 0x00002020, 0x04002020, 0x00042020, 0x04042020,
- 0x00002022, 0x04002022, 0x00042022, 0x04042022,
- 0x00000800, 0x04000800, 0x00040800, 0x04040800,
- 0x00000802, 0x04000802, 0x00040802, 0x04040802,
- 0x00002800, 0x04002800, 0x00042800, 0x04042800,
- 0x00002802, 0x04002802, 0x00042802, 0x04042802,
- 0x00000820, 0x04000820, 0x00040820, 0x04040820,
- 0x00000822, 0x04000822, 0x00040822, 0x04040822,
- 0x00002820, 0x04002820, 0x00042820, 0x04042820,
- 0x00002822, 0x04002822, 0x00042822, 0x04042822,
- },
- };
-
- private static final int SPtrans[][] =
- {
- {
- /* nibble 0 */
- 0x00820200, 0x00020000, 0x80800000, 0x80820200,
- 0x00800000, 0x80020200, 0x80020000, 0x80800000,
- 0x80020200, 0x00820200, 0x00820000, 0x80000200,
- 0x80800200, 0x00800000, 0x00000000, 0x80020000,
- 0x00020000, 0x80000000, 0x00800200, 0x00020200,
- 0x80820200, 0x00820000, 0x80000200, 0x00800200,
- 0x80000000, 0x00000200, 0x00020200, 0x80820000,
- 0x00000200, 0x80800200, 0x80820000, 0x00000000,
- 0x00000000, 0x80820200, 0x00800200, 0x80020000,
- 0x00820200, 0x00020000, 0x80000200, 0x00800200,
- 0x80820000, 0x00000200, 0x00020200, 0x80800000,
- 0x80020200, 0x80000000, 0x80800000, 0x00820000,
- 0x80820200, 0x00020200, 0x00820000, 0x80800200,
- 0x00800000, 0x80000200, 0x80020000, 0x00000000,
- 0x00020000, 0x00800000, 0x80800200, 0x00820200,
- 0x80000000, 0x80820000, 0x00000200, 0x80020200,
- },
- {
- /* nibble 1 */
- 0x10042004, 0x00000000, 0x00042000, 0x10040000,
- 0x10000004, 0x00002004, 0x10002000, 0x00042000,
- 0x00002000, 0x10040004, 0x00000004, 0x10002000,
- 0x00040004, 0x10042000, 0x10040000, 0x00000004,
- 0x00040000, 0x10002004, 0x10040004, 0x00002000,
- 0x00042004, 0x10000000, 0x00000000, 0x00040004,
- 0x10002004, 0x00042004, 0x10042000, 0x10000004,
- 0x10000000, 0x00040000, 0x00002004, 0x10042004,
- 0x00040004, 0x10042000, 0x10002000, 0x00042004,
- 0x10042004, 0x00040004, 0x10000004, 0x00000000,
- 0x10000000, 0x00002004, 0x00040000, 0x10040004,
- 0x00002000, 0x10000000, 0x00042004, 0x10002004,
- 0x10042000, 0x00002000, 0x00000000, 0x10000004,
- 0x00000004, 0x10042004, 0x00042000, 0x10040000,
- 0x10040004, 0x00040000, 0x00002004, 0x10002000,
- 0x10002004, 0x00000004, 0x10040000, 0x00042000,
- },
- {
- /* nibble 2 */
- 0x41000000, 0x01010040, 0x00000040, 0x41000040,
- 0x40010000, 0x01000000, 0x41000040, 0x00010040,
- 0x01000040, 0x00010000, 0x01010000, 0x40000000,
- 0x41010040, 0x40000040, 0x40000000, 0x41010000,
- 0x00000000, 0x40010000, 0x01010040, 0x00000040,
- 0x40000040, 0x41010040, 0x00010000, 0x41000000,
- 0x41010000, 0x01000040, 0x40010040, 0x01010000,
- 0x00010040, 0x00000000, 0x01000000, 0x40010040,
- 0x01010040, 0x00000040, 0x40000000, 0x00010000,
- 0x40000040, 0x40010000, 0x01010000, 0x41000040,
- 0x00000000, 0x01010040, 0x00010040, 0x41010000,
- 0x40010000, 0x01000000, 0x41010040, 0x40000000,
- 0x40010040, 0x41000000, 0x01000000, 0x41010040,
- 0x00010000, 0x01000040, 0x41000040, 0x00010040,
- 0x01000040, 0x00000000, 0x41010000, 0x40000040,
- 0x41000000, 0x40010040, 0x00000040, 0x01010000,
- },
- {
- /* nibble 3 */
- 0x00100402, 0x04000400, 0x00000002, 0x04100402,
- 0x00000000, 0x04100000, 0x04000402, 0x00100002,
- 0x04100400, 0x04000002, 0x04000000, 0x00000402,
- 0x04000002, 0x00100402, 0x00100000, 0x04000000,
- 0x04100002, 0x00100400, 0x00000400, 0x00000002,
- 0x00100400, 0x04000402, 0x04100000, 0x00000400,
- 0x00000402, 0x00000000, 0x00100002, 0x04100400,
- 0x04000400, 0x04100002, 0x04100402, 0x00100000,
- 0x04100002, 0x00000402, 0x00100000, 0x04000002,
- 0x00100400, 0x04000400, 0x00000002, 0x04100000,
- 0x04000402, 0x00000000, 0x00000400, 0x00100002,
- 0x00000000, 0x04100002, 0x04100400, 0x00000400,
- 0x04000000, 0x04100402, 0x00100402, 0x00100000,
- 0x04100402, 0x00000002, 0x04000400, 0x00100402,
- 0x00100002, 0x00100400, 0x04100000, 0x04000402,
- 0x00000402, 0x04000000, 0x04000002, 0x04100400,
- },
- {
- /* nibble 4 */
- 0x02000000, 0x00004000, 0x00000100, 0x02004108,
- 0x02004008, 0x02000100, 0x00004108, 0x02004000,
- 0x00004000, 0x00000008, 0x02000008, 0x00004100,
- 0x02000108, 0x02004008, 0x02004100, 0x00000000,
- 0x00004100, 0x02000000, 0x00004008, 0x00000108,
- 0x02000100, 0x00004108, 0x00000000, 0x02000008,
- 0x00000008, 0x02000108, 0x02004108, 0x00004008,
- 0x02004000, 0x00000100, 0x00000108, 0x02004100,
- 0x02004100, 0x02000108, 0x00004008, 0x02004000,
- 0x00004000, 0x00000008, 0x02000008, 0x02000100,
- 0x02000000, 0x00004100, 0x02004108, 0x00000000,
- 0x00004108, 0x02000000, 0x00000100, 0x00004008,
- 0x02000108, 0x00000100, 0x00000000, 0x02004108,
- 0x02004008, 0x02004100, 0x00000108, 0x00004000,
- 0x00004100, 0x02004008, 0x02000100, 0x00000108,
- 0x00000008, 0x00004108, 0x02004000, 0x02000008,
- },
- {
- /* nibble 5 */
- 0x20000010, 0x00080010, 0x00000000, 0x20080800,
- 0x00080010, 0x00000800, 0x20000810, 0x00080000,
- 0x00000810, 0x20080810, 0x00080800, 0x20000000,
- 0x20000800, 0x20000010, 0x20080000, 0x00080810,
- 0x00080000, 0x20000810, 0x20080010, 0x00000000,
- 0x00000800, 0x00000010, 0x20080800, 0x20080010,
- 0x20080810, 0x20080000, 0x20000000, 0x00000810,
- 0x00000010, 0x00080800, 0x00080810, 0x20000800,
- 0x00000810, 0x20000000, 0x20000800, 0x00080810,
- 0x20080800, 0x00080010, 0x00000000, 0x20000800,
- 0x20000000, 0x00000800, 0x20080010, 0x00080000,
- 0x00080010, 0x20080810, 0x00080800, 0x00000010,
- 0x20080810, 0x00080800, 0x00080000, 0x20000810,
- 0x20000010, 0x20080000, 0x00080810, 0x00000000,
- 0x00000800, 0x20000010, 0x20000810, 0x20080800,
- 0x20080000, 0x00000810, 0x00000010, 0x20080010,
- },
- {
- /* nibble 6 */
- 0x00001000, 0x00000080, 0x00400080, 0x00400001,
- 0x00401081, 0x00001001, 0x00001080, 0x00000000,
- 0x00400000, 0x00400081, 0x00000081, 0x00401000,
- 0x00000001, 0x00401080, 0x00401000, 0x00000081,
- 0x00400081, 0x00001000, 0x00001001, 0x00401081,
- 0x00000000, 0x00400080, 0x00400001, 0x00001080,
- 0x00401001, 0x00001081, 0x00401080, 0x00000001,
- 0x00001081, 0x00401001, 0x00000080, 0x00400000,
- 0x00001081, 0x00401000, 0x00401001, 0x00000081,
- 0x00001000, 0x00000080, 0x00400000, 0x00401001,
- 0x00400081, 0x00001081, 0x00001080, 0x00000000,
- 0x00000080, 0x00400001, 0x00000001, 0x00400080,
- 0x00000000, 0x00400081, 0x00400080, 0x00001080,
- 0x00000081, 0x00001000, 0x00401081, 0x00400000,
- 0x00401080, 0x00000001, 0x00001001, 0x00401081,
- 0x00400001, 0x00401080, 0x00401000, 0x00001001,
- },
- {
- /* nibble 7 */
- 0x08200020, 0x08208000, 0x00008020, 0x00000000,
- 0x08008000, 0x00200020, 0x08200000, 0x08208020,
- 0x00000020, 0x08000000, 0x00208000, 0x00008020,
- 0x00208020, 0x08008020, 0x08000020, 0x08200000,
- 0x00008000, 0x00208020, 0x00200020, 0x08008000,
- 0x08208020, 0x08000020, 0x00000000, 0x00208000,
- 0x08000000, 0x00200000, 0x08008020, 0x08200020,
- 0x00200000, 0x00008000, 0x08208000, 0x00000020,
- 0x00200000, 0x00008000, 0x08000020, 0x08208020,
- 0x00008020, 0x08000000, 0x00000000, 0x00208000,
- 0x08200020, 0x08008020, 0x08008000, 0x00200020,
- 0x08208000, 0x00000020, 0x00200020, 0x08008000,
- 0x08208020, 0x00200000, 0x08200000, 0x08000020,
- 0x00208000, 0x00008020, 0x08008020, 0x08200000,
- 0x00000020, 0x08208000, 0x00208020, 0x00000000,
- 0x08000000, 0x08200020, 0x00008000, 0x00208020
- }
- };
-
- private static final int cov_2char[] =
- {
- 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35,
- 0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44,
- 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C,
- 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54,
- 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x61, 0x62,
- 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A,
- 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72,
- 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A
- };
-
- private static final int byteToUnsigned(byte b)
- {
- int value = (int)b;
-
- return (value >= 0 ? value : value + 256);
- }
-
- private static int fourBytesToInt(byte b[], int offset)
- {
- int value;
-
- value = byteToUnsigned(b[offset++]);
- value |= (byteToUnsigned(b[offset++]) << 8);
- value |= (byteToUnsigned(b[offset++]) << 16);
- value |= (byteToUnsigned(b[offset++]) << 24);
-
- return (value);
- }
-
- private static final void intToFourBytes(int iValue, byte b[], int offset)
- {
- b[offset++] = (byte)((iValue) & 0xff);
- b[offset++] = (byte)((iValue >>> 8 ) & 0xff);
- b[offset++] = (byte)((iValue >>> 16) & 0xff);
- b[offset++] = (byte)((iValue >>> 24) & 0xff);
- }
-
- private static final void PERM_OP(int a, int b, int n, int m, int results[])
- {
- int t;
-
- t = ((a >>> n) ^ b) & m;
- a ^= t << n;
- b ^= t;
-
- results[0] = a;
- results[1] = b;
- }
-
- private static final int HPERM_OP(int a, int n, int m)
- {
- int t;
-
- t = ((a << (16 - n)) ^ a) & m;
- a = a ^ t ^ (t >>> (16 - n));
-
- return (a);
- }
-
- private static int [] des_set_key(byte key[])
- {
- int schedule[] = new int[ITERATIONS * 2];
-
- int c = fourBytesToInt(key, 0);
- int d = fourBytesToInt(key, 4);
-
- int results[] = new int[2];
-
- PERM_OP(d, c, 4, 0x0f0f0f0f, results);
- d = results[0];
- c = results[1];
-
- c = HPERM_OP(c, -2, 0xcccc0000);
- d = HPERM_OP(d, -2, 0xcccc0000);
-
- PERM_OP(d, c, 1, 0x55555555, results);
- d = results[0];
- c = results[1];
-
- PERM_OP(c, d, 8, 0x00ff00ff, results);
- c = results[0];
- d = results[1];
-
- PERM_OP(d, c, 1, 0x55555555, results);
- d = results[0];
- c = results[1];
-
- d = (((d & 0x000000ff) << 16) | (d & 0x0000ff00) |
- ((d & 0x00ff0000) >>> 16) | ((c & 0xf0000000) >>> 4));
- c &= 0x0fffffff;
-
- int s, t;
- int j = 0;
-
- for (int i = 0; i < ITERATIONS; i ++)
- {
- if (shifts2[i])
- {
- c = (c >>> 2) | (c << 26);
- d = (d >>> 2) | (d << 26);
- }
- else
- {
- c = (c >>> 1) | (c << 27);
- d = (d >>> 1) | (d << 27);
- }
-
- c &= 0x0fffffff;
- d &= 0x0fffffff;
-
- s = skb[0][ (c ) & 0x3f ] |
- skb[1][((c >>> 6) & 0x03) | ((c >>> 7) & 0x3c)] |
- skb[2][((c >>> 13) & 0x0f) | ((c >>> 14) & 0x30)] |
- skb[3][((c >>> 20) & 0x01) | ((c >>> 21) & 0x06) |
- ((c >>> 22) & 0x38)];
-
- t = skb[4][ (d ) & 0x3f ] |
- skb[5][((d >>> 7) & 0x03) | ((d >>> 8) & 0x3c)] |
- skb[6][ (d >>> 15) & 0x3f ] |
- skb[7][((d >>> 21) & 0x0f) | ((d >>> 22) & 0x30)];
-
- schedule[j++] = ((t << 16) | (s & 0x0000ffff)) & 0xffffffff;
- s = ((s >>> 16) | (t & 0xffff0000));
-
- s = (s << 4) | (s >>> 28);
- schedule[j++] = s & 0xffffffff;
- }
- return (schedule);
- }
-
- private static final int D_ENCRYPT
- (
- int L, int R, int S, int E0, int E1, int s[]
- )
- {
- int t, u, v;
-
- v = R ^ (R >>> 16);
- u = v & E0;
- v = v & E1;
- u = (u ^ (u << 16)) ^ R ^ s[S];
- t = (v ^ (v << 16)) ^ R ^ s[S + 1];
- t = (t >>> 4) | (t << 28);
-
- L ^= SPtrans[1][(t ) & 0x3f] |
- SPtrans[3][(t >>> 8) & 0x3f] |
- SPtrans[5][(t >>> 16) & 0x3f] |
- SPtrans[7][(t >>> 24) & 0x3f] |
- SPtrans[0][(u ) & 0x3f] |
- SPtrans[2][(u >>> 8) & 0x3f] |
- SPtrans[4][(u >>> 16) & 0x3f] |
- SPtrans[6][(u >>> 24) & 0x3f];
-
- return (L);
- }
-
- private static final int [] body(int schedule[], int Eswap0, int Eswap1)
- {
- int left = 0;
- int right = 0;
- int t = 0;
-
- for (int j = 0; j < 25; j ++)
- {
- for (int i = 0; i < ITERATIONS * 2; i += 4)
- {
- left = D_ENCRYPT(left, right, i, Eswap0, Eswap1, schedule);
- right = D_ENCRYPT(right, left, i + 2, Eswap0, Eswap1, schedule);
- }
- t = left;
- left = right;
- right = t;
- }
-
- t = right;
-
- right = (left >>> 1) | (left << 31);
- left = (t >>> 1) | (t << 31);
-
- left &= 0xffffffff;
- right &= 0xffffffff;
-
- int results[] = new int[2];
-
- PERM_OP(right, left, 1, 0x55555555, results);
- right = results[0];
- left = results[1];
-
- PERM_OP(left, right, 8, 0x00ff00ff, results);
- left = results[0];
- right = results[1];
-
- PERM_OP(right, left, 2, 0x33333333, results);
- right = results[0];
- left = results[1];
-
- PERM_OP(left, right, 16, 0x0000ffff, results);
- left = results[0];
- right = results[1];
-
- PERM_OP(right, left, 4, 0x0f0f0f0f, results);
- right = results[0];
- left = results[1];
-
- int out[] = new int[2];
-
- out[0] = left;
- out[1] = right;
-
- return (out);
- }
-
- /*
- *
Encrypt a password given the cleartext password and a "salt".
- * @param salt A two-character string representing the salt used to
- * iterate the encryption engine in lots of different ways. If you
- * are generating a new encryption then this value should be
- * randomised.
- * @param original The password to be encrypted.
- * @return A string consisting of the 2-character salt followed by the
- * encrypted password.
- */
- public static final String crypt(String salt, String original)
- {
- while (salt.length() < 2)
- salt += "A";
-
- StringBuffer buffer = new StringBuffer(" ");
-
- char charZero = salt.charAt(0);
- char charOne = salt.charAt(1);
-
- buffer.setCharAt(0, charZero);
- buffer.setCharAt(1, charOne);
-
- int Eswap0 = con_salt[(int)charZero];
- int Eswap1 = con_salt[(int)charOne] << 4;
-
- byte key[] = new byte[8];
-
- for (int i = 0; i < key.length; i ++)
- key[i] = (byte)0;
-
- for (int i = 0; i < key.length && i < original.length(); i ++)
- {
- int iChar = (int)original.charAt(i);
-
- key[i] = (byte)(iChar << 1);
- }
-
- int schedule[] = des_set_key(key);
- int out[] = body(schedule, Eswap0, Eswap1);
-
- byte b[] = new byte[9];
-
- intToFourBytes(out[0], b, 0);
- intToFourBytes(out[1], b, 4);
- b[8] = 0;
-
- for (int i = 2, y = 0, u = 0x80; i < 13; i ++)
- {
- for (int j = 0, c = 0; j < 6; j ++)
- {
- c <<= 1;
-
- if (((int)b[y] & u) != 0)
- c |= 1;
-
- u >>>= 1;
-
- if (u == 0)
- {
- y++;
- u = 0x80;
- }
- buffer.setCharAt(i, (char)cov_2char[c]);
- }
- }
- return (buffer.toString());
- }
-
- /*
- *
Encrypt a password given the cleartext password. This method
- * generates a random salt using the 'java.util.Random' class.
- * @param original The password to be encrypted.
- * @return A string consisting of the 2-character salt followed by the
- * encrypted password.
- */
- public static final String crypt(String original)
- {
- java.util.Random randomGenerator = new java.util.Random();
- int numSaltChars = saltChars.length;
- String salt;
-
- salt = (new StringBuffer()).append(saltChars[Math.abs(randomGenerator.nextInt()) % numSaltChars]).append(saltChars[Math.abs(randomGenerator.nextInt()) % numSaltChars]).toString();
-
- return crypt(salt, original);
- }
-
- /*
- *
Check that enteredPassword encrypts to
- * encryptedPassword.
- * @param encryptedPassword The encryptedPassword. The first
- * two characters are assumed to be the salt. This string would
- * be the same as one found in a Unix /etc/passwd file.
- * @param enteredPassword The password as entered by the user (or
- * otherwise aquired).
- * @return true if the password should be considered correct.
- */
- public final static boolean matches(String encryptedPassword, String enteredPassword)
- {
- String salt = encryptedPassword.substring(0, 3);
- String newCrypt = crypt(salt, enteredPassword);
-
- return newCrypt.equals(encryptedPassword);
- }
-}
-