package org.postgresql.jdbc2;

// IMPORTANT NOTE: This is the begining of supporting updateable ResultSets.
// It is not a working solution (yet)!
//
// You will notice here we really do throw org.postgresql.Driver.notImplemented()
// This is because here we should be updateable, so any unimplemented methods
// must say so.
//
// Also you'll notice that the String columnName based calls are not present.
// They are not required as they are in the super class.
//

import java.lang.*;
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.sql.*;
import org.postgresql.Field;
import org.postgresql.largeobject.*;
import org.postgresql.util.*;

/*
 * @see ResultSet
 * @see ResultSetMetaData
 * @see java.sql.ResultSet
 */
public class UpdateableResultSet extends org.postgresql.jdbc2.ResultSet
{


	protected StringBuffer updateSQL = null;

	protected StringBuffer deleteSQL = null;



	protected String tableName = null;

	/**
	 * PreparedStatement used to delete data
	 */

	protected java.sql.Statement updater = null;

	/**
	 * PreparedStatement used to insert data
	 */

	protected java.sql.Statement inserter = null;

	/**
	 * PreparedStatement used to delete data
	 */

	protected java.sql.Statement deleter = null;

	/**
	 * List of primary keys
	 */

	protected Vector primaryKeyIndices = null;

	/**
	 * Is this result set updateable?
	 */

	protected boolean updateable = false;

	/**
	 * Are we in the middle of doing updates to the current row?
	 */

	protected boolean doingUpdates = false;


	/**
	 * Are we on the insert row?
	 */

	protected boolean onInsertRow = false;


	protected Vector primkeys=null;

	protected boolean removedOID=false;

	protected int oidIndex=0;

	protected Hashtable insertTable=new Hashtable();

	protected StringBuffer insertSQL=null;

	// The Row Buffer will be used to cache updated rows..then we shall sync this with the rows vector


	private final static String UPDATEABLE_MESSAGE =
		"Result Set not updateable. The "
			+ "query that generated this result set must select only one table, and must "
			+ "select all primary keys from that table. See the JDBC 2.1 API Specification, "
			+ "section 5.6 for more details.";

	/*
	 * Create a new ResultSet - Note that we create ResultSets to
	 * represent the results of everything.
	 *
	 * @param fields an array of Field objects (basically, the
	 *	ResultSet MetaData)
	 * @param tuples Vector of the actual data
	 * @param status the status string returned from the back end
	 * @param updateCount the number of rows affected by the operation
	 * @param cursor the positioned update/delete cursor name
	 */
	public UpdateableResultSet(Connection conn, Field[] fields, Vector tuples, String status, int updateCount, long insertOID, boolean binaryCursor)
	{
		super(conn, fields, tuples, status, updateCount, insertOID, binaryCursor);
		System.out.println("updatable constructor");


	}

	/*
	 * Create a new ResultSet - Note that we create ResultSets to
	 * represent the results of everything.
	 *
	 * @param fields an array of Field objects (basically, the
	 *	ResultSet MetaData)
	 * @param tuples Vector of the actual data
	 * @param status the status string returned from the back end
	 * @param updateCount the number of rows affected by the operation
	 * @param cursor the positioned update/delete cursor name
	 */
	//	public UpdateableResultSet(Connection conn, Field[] fields, Vector tuples, String status, int updateCount)
	//	{
	//	   super(conn,fields,tuples,status,updateCount,0,false);
	//}

	public synchronized void cancelRowUpdates() throws SQLException {
		if (doingUpdates) {
			doingUpdates = false;

			updateSQL=null;
			insertTable.clear();
			clearRowBuffer();
		}
	}


	public synchronized void deleteRow() throws SQLException {
		if (!updateable) {
			throw new SQLException(UPDATEABLE_MESSAGE, "S1000");
		}

		if (onInsertRow) {
			throw new SQLException("Can not call deleteRow() when on insert row");
		}
		else
			if (rows.size() == 0) {
				throw new SQLException("Can't deleteRow() on empty result set");
			}
			else
				if (isBeforeFirst()) {
					throw new SQLException("Before start of result set. Can not call deleteRow().");
				}
				else
					if (isAfterLast()) {
						throw new SQLException("After end of result set. Can not call deleteRow().");
					}






			int numKeys = primaryKeyIndices.size();
			int index=0;
			deleteSQL=new StringBuffer("DELETE FROM "+tableName);
			if (numKeys == 1) {


				index = ((Integer) primaryKeyIndices.elementAt(0)).intValue();
				deleteSQL.append(" WHERE "+fields[index].getName()+"="+new String(this_row[index]));
			}
			else {
				deleteSQL.append(" WHERE ");
				boolean firstTime=true;
				for (int i = 0; i < numKeys; i++) {
						index=((Integer) primaryKeyIndices.elementAt(i)).intValue();
						byte[] currentVal = this_row[index];
						if (firstTime) {
							deleteSQL.append(fields[index]+"="+new String(currentVal));
							firstTime=false;
						}
						else {
							deleteSQL.append(" AND "+fields[index]+"="+new String(currentVal));
						}
				}
			}
			System.out.println("deleting "+deleteSQL.toString());
			deleter=connection.createStatement();
			deleter.executeUpdate(deleteSQL.toString());
			rows.removeElementAt(current_row);
			clearRowBuffer();




	}


	public int getConcurrency() throws SQLException
	{
		// New in 7.1 - The updateable ResultSet class will now return
		// CONCURuPDATEABLE.
		return CONCUR_UPDATABLE;
	}

	public synchronized void insertRow() throws SQLException {
		if (!onInsertRow) {
			throw new SQLException("Not on insert row");
		}
		else {
			insertSQL=new StringBuffer("INSERT INTO "+tableName+" ");
			StringBuffer columnNames=new StringBuffer();
			StringBuffer columnValues=new StringBuffer();
			Enumeration keys=insertTable.keys();
			System.out.println("no of columns "+insertTable.size());
			boolean firstTime=true;
			while (keys.hasMoreElements()) {
				String key=(String)keys.nextElement();
				System.out.println(key+"="+insertTable.get(key));
				if (firstTime) {
					columnNames.append("("+key);
					columnValues.append(" VALUES ("+insertTable.get(key));
					firstTime=false;

				}
				else {
					columnNames.append(","+key);
					columnValues.append(","+insertTable.get(key));
				}

			}
			insertSQL.append(columnNames.toString()).append(")").append(columnValues.toString()).append(")");
			insertTable.clear();

			//System.out.println("inserting "+insertSQL.toString());
			java.sql.Statement inserter=connection.createStatement();
			int insertcount=inserter.executeUpdate(insertSQL.toString());
			//System.out.println("inserted "+insertcount);
			//long autoIncrementId = inserter.getLastOID();

			int numfields = fields.length;
			if (this_row==null) {
				System.out.println(" is null ");
			}
			//System.arraycopy(rowBuffer,0,this_row,0,rowBuffer.length);
			rows.addElement(rowBuffer);

			insertSQL=null;
			insertTable.clear();


		}
	}



	public synchronized void moveToCurrentRow() throws SQLException
	{
		// only sub-classes implement CONCURuPDATEABLE
		throw org.postgresql.Driver.notImplemented();
	}

	public synchronized void  moveToInsertRow() throws SQLException
	{
		// only sub-classes implement CONCURuPDATEABLE
		if (!updateable) {
			throw new SQLException(UPDATEABLE_MESSAGE, "S1000");
		}

		if (insertSQL != null) {

			insertSQL=null;
			insertTable.clear();

		}
		//System.out.println("clearing row buffer");
		clearRowBuffer();
		onInsertRow = true;
		doingUpdates = false;

	}

	private synchronized void clearRowBuffer() throws SQLException {
		rowBuffer=new byte[fields.length][];

	}



	public boolean rowDeleted() throws SQLException
	{
		// only sub-classes implement CONCURuPDATEABLE
		throw org.postgresql.Driver.notImplemented();
		//return false; // javac complains about not returning a value!
	}

	public boolean rowInserted() throws SQLException
	{
		// only sub-classes implement CONCURuPDATEABLE
		throw org.postgresql.Driver.notImplemented();
		//return false; // javac complains about not returning a value!
	}

	public boolean rowUpdated() throws SQLException
	{
		// only sub-classes implement CONCURuPDATEABLE
		throw org.postgresql.Driver.notImplemented();
		//return false; // javac complains about not returning a value!
	}

	public synchronized void updateAsciiStream(int columnIndex,
								  java.io.InputStream x,
								  int length
								 ) throws SQLException
	{


		byte[] theData=null;

		try {
			x.read(theData,0,length);

		}
		catch (IOException ie) {
			throw new SQLException("InputStream Error "+ie);
		}

		if (!onInsertRow) {
						if (!doingUpdates) {
				doingUpdates = true;

				;
			}

			insertTable.put(fields[columnIndex-1].getName(),String.valueOf(theData));
		}
		else {
			insertTable.put(fields[columnIndex-1].getName(),String.valueOf(theData));
			//inserter.setAsciiStream(columnIndex, y, length);
		}
		rowBuffer[columnIndex-1]=theData;

	}

	public synchronized void updateBigDecimal(int columnIndex,
								 java.math.BigDecimal x
								) throws SQLException
	{


		if (!onInsertRow) {

			if (!doingUpdates) {
				doingUpdates = true;


			}

			insertTable.put(fields[columnIndex-1].getName(),x.toString());
		}
		else {
			insertTable.put(fields[columnIndex-1].getName(),x.toString());
			//inserter.setBigDecimal(columnIndex, x);
		}

		try {
			rowBuffer[columnIndex-1]=x.toString().getBytes(connection.getEncoding().name());
		}
		catch(UnsupportedEncodingException use) {
			throw new SQLException("Unsupported Encoding "+connection.getEncoding().name());
		}


	}

	public synchronized void updateBinaryStream(int columnIndex,
								   java.io.InputStream x,
								   int length
								  ) throws SQLException
	{


		byte[] theData=null;

		try {
			x.read(theData,0,length);

		}
		catch (IOException ie) {
			throw new SQLException("InputStream Error "+ie);
		}
		if (!onInsertRow) {

			if (!doingUpdates) {
				doingUpdates = true;


			}


			insertTable.put(fields[columnIndex-1].getName(),new String(theData));
		}
		else {
			insertTable.put(fields[columnIndex-1].getName(),new String(theData));
		}
		rowBuffer[columnIndex-1]=theData;

	}

	public synchronized void updateBoolean(int columnIndex, boolean x) throws SQLException
	{

		System.out.println("updating boolean "+fields[columnIndex-1].getName()+"="+x);

		if (!onInsertRow) {

			if (!doingUpdates) {
				doingUpdates = true;

				;
			}

			insertTable.put(fields[columnIndex-1].getName(),"'"+String.valueOf(x)+"'");
		}
		else {
			insertTable.put(fields[columnIndex-1].getName(),"'"+String.valueOf(x)+"'");
		}
		try {
			rowBuffer[columnIndex-1]=String.valueOf(x).getBytes(connection.getEncoding().name());
		}
		catch(UnsupportedEncodingException use) {
			throw new SQLException("Unsupported Encoding "+connection.getEncoding().name());
		}


	}

	public synchronized void updateByte(int columnIndex, byte x) throws SQLException
	{

		if (!onInsertRow) {

			if (!doingUpdates) {
				doingUpdates = true;

				;
			}

			insertTable.put(fields[columnIndex-1].getName(),String.valueOf(x));
		}
		else {
			insertTable.put(fields[columnIndex-1].getName(),String.valueOf(x));
		}
		byte[] y=new byte[0];
		y[0]=x;
		rowBuffer[columnIndex-1]=y;

	}

	public synchronized void updateBytes(int columnIndex, byte[] x) throws SQLException
	{

		if (!onInsertRow) {

			if (!doingUpdates) {
				doingUpdates = true;

				;
			}

			insertTable.put(fields[columnIndex-1].getName(),String.valueOf(x));
		}
		else {
			insertTable.put(fields[columnIndex-1].getName(),String.valueOf(x));
		}

		rowBuffer[columnIndex-1]=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 (IOException ie) {
			throw new SQLException("InputStream Error "+ie);
		}

		if (!onInsertRow) {

			if (!doingUpdates) {
				doingUpdates = true;

				;
			}

			insertTable.put(fields[columnIndex-1].getName(),String.valueOf(theData));
		}
		else {
			insertTable.put(fields[columnIndex-1].getName(),String.valueOf(theData));
		}
		rowBuffer[columnIndex-1]=String.valueOf(theData).getBytes();

	}

	public synchronized void updateDate(int columnIndex, java.sql.Date x) throws SQLException
	{

		if (!onInsertRow) {

			if (!doingUpdates) {
				doingUpdates = true;

				;
			}

			insertTable.put(fields[columnIndex-1].getName(),"'"+x.toString()+"'");
		}
		else {
			insertTable.put(fields[columnIndex-1].getName(),"'"+x.toString()+"'");
		}
		try {
			rowBuffer[columnIndex-1]=x.toString().getBytes(connection.getEncoding().name());
		}
		catch(UnsupportedEncodingException use) {
			throw new SQLException("Unsupported Encoding "+connection.getEncoding().name());
		}


	}

	public synchronized void updateDouble(int columnIndex, double x) throws SQLException
	{
		System.out.println("updating double "+fields[columnIndex-1].getName()+"="+x);

		if (!onInsertRow) {

			if (!doingUpdates) {
				doingUpdates = true;

				;
			}

			insertTable.put(fields[columnIndex-1].getName(),String.valueOf(x));
		}
		else {
			insertTable.put(fields[columnIndex-1].getName(),String.valueOf(x));
		}
		try {
			rowBuffer[columnIndex-1]=String.valueOf(x).getBytes(connection.getEncoding().name());
		}
		catch(UnsupportedEncodingException use) {
			throw new SQLException("Unsupported Encoding "+connection.getEncoding().name());
		}



	}

	public synchronized void updateFloat(int columnIndex, float x) throws SQLException
	{
		System.out.println("updating float "+fields[columnIndex-1].getName()+"="+x);

		if (!onInsertRow) {

			if (!doingUpdates) {
				doingUpdates = true;

				;
			}

			insertTable.put(fields[columnIndex-1].getName(),String.valueOf(x));
		}
		else {
			insertTable.put(fields[columnIndex-1].getName(),String.valueOf(x));
		}
		try {
			rowBuffer[columnIndex-1]=String.valueOf(x).getBytes(connection.getEncoding().name());
		}
		catch(UnsupportedEncodingException use) {
			throw new SQLException("Unsupported Encoding "+connection.getEncoding().name());
		}



	}

	public synchronized void updateInt(int columnIndex, int x) throws SQLException
	{
		System.out.println("updating int "+fields[columnIndex-1].getName()+"="+x);

		if (!onInsertRow) {

			if (!doingUpdates) {
				doingUpdates = true;

				;
			}

			insertTable.put(fields[columnIndex-1].getName(),String.valueOf(x));
		}
		else {
			insertTable.put(fields[columnIndex-1].getName(),String.valueOf(x));
		}
		try {
			rowBuffer[columnIndex-1]=String.valueOf(x).getBytes(connection.getEncoding().name());
		}
		catch(UnsupportedEncodingException use) {
			throw new SQLException("Unsupported Encoding "+connection.getEncoding().name());
		}



	}

	public synchronized void updateLong(int columnIndex, long x) throws SQLException
	{
		System.out.println("updating long "+fields[columnIndex-1].getName()+"="+x);

		if (!onInsertRow) {

			if (!doingUpdates) {
				doingUpdates = true;

				;
			}

			insertTable.put(fields[columnIndex-1].getName(),String.valueOf(x));
		}
		else {
			insertTable.put(fields[columnIndex-1].getName(),String.valueOf(x));
		}

		try {
			rowBuffer[columnIndex-1]=String.valueOf(x).getBytes(connection.getEncoding().name());
		}
		catch(UnsupportedEncodingException use) {
			throw new SQLException("Unsupported Encoding "+connection.getEncoding().name());
		}


	}

	public synchronized void updateNull(int columnIndex) throws SQLException
	{

		if (!onInsertRow) {

			if (!doingUpdates) {
				doingUpdates = true;

				;
			}

			insertTable.put(fields[columnIndex-1].getName(),"null");
		}
		else {
			insertTable.put(fields[columnIndex-1].getName(),"null");
		}


	}

	public synchronized void updateObject(int columnIndex, Object x) throws SQLException
	{


		if (!onInsertRow) {

			if (!doingUpdates) {
				doingUpdates = true;

				;
			}

			insertTable.put(fields[columnIndex-1].getName(),x.toString());
		}
		else {
			insertTable.put(fields[columnIndex-1].getName(),x.toString());
		}

		if (x instanceof byte[]) {
			rowBuffer[columnIndex-1]=(byte[])x;
		}
		else {
			try {
				rowBuffer[columnIndex-1]=x.toString().getBytes(connection.getEncoding().name());
			}
			catch(UnsupportedEncodingException use) {
				throw new SQLException("Unsupported Encoding "+connection.getEncoding().name());
			}

		}
	}

	public synchronized void updateObject(int columnIndex, Object x, int scale) throws SQLException
	{

		if (!onInsertRow) {

			if (!doingUpdates) {
				doingUpdates = true;

				;
			}

			insertTable.put(fields[columnIndex-1].getName(),x.toString());
		}
		else {
			insertTable.put(fields[columnIndex-1].getName(),x.toString());
		}
		if (x instanceof byte[]) {
			rowBuffer[columnIndex-1]=(byte[])x;
		}
		else {
			try {
				rowBuffer[columnIndex-1]=x.toString().getBytes(connection.getEncoding().name());
			}
			catch(UnsupportedEncodingException use) {
				throw new SQLException("Unsupported Encoding "+connection.getEncoding().name());
			}

		}


	}

	public synchronized void updateRow() throws SQLException {
		if (!updateable) {
			throw new SQLException(UPDATEABLE_MESSAGE, "S1000");
		}

		if (doingUpdates) {

			int status=0;
			try {
				updateSQL=new StringBuffer("UPDATE "+tableName+" SET  ");
				Enumeration keys=insertTable.keys();
				//System.out.println("no of columns "+insertTable.size());
				boolean firstTime=true;
				while (keys.hasMoreElements()) {
					String key=(String)keys.nextElement();
					System.out.println(key+"="+insertTable.get(key));
					if (firstTime) {
						updateSQL.append(key+"="+insertTable.get(key)+" ");

						firstTime=false;
					}
					else {
						updateSQL.append(","+key+"="+insertTable.get(key)+" ");
					}

				}

				insertTable.clear();
				int numKeys = primaryKeyIndices.size();
				int index=0;
				if (numKeys == 1) {


					index = ((Integer) primaryKeyIndices.elementAt(0)).intValue();
					updateSQL.append(" WHERE "+fields[index].getName()+"="+new String(this_row[index]));

				}
				else {
				updateSQL.append(" WHERE ");
				firstTime=true;
				for (int i = 0; i < numKeys; i++) {
						index=((Integer) primaryKeyIndices.elementAt(i)).intValue();
						byte[] currentVal = this_row[index];

								if (firstTime) {
									updateSQL.append(fields[index]+"="+new String(currentVal));
									firstTime=false;
								}
								else {
									updateSQL.append(" AND "+fields[index]+"="+new String(currentVal));
								}
							}

						}
				System.out.println("updating "+updateSQL.toString());
				updater=connection.createStatement();
				status=updater.executeUpdate(updateSQL.toString());
				System.out.println("updated");

			}
			catch(Exception e) {
				System.out.println(e.getClass().getName()+e);
			}

			if (status>0) {
				System.out.println("copying data");
				System.arraycopy(rowBuffer,0,this_row,0,rowBuffer.length);
				rows.setElementAt(rowBuffer,current_row);

			}

			System.out.println("done updates");
			doingUpdates = false;
		}

	}

	public synchronized void updateShort(int columnIndex, short x) throws SQLException
	{
		System.out.println("updating short "+fields[columnIndex-1].getName()+"="+x);


		if (!onInsertRow) {

			if (!doingUpdates) {
				doingUpdates = true;

				;
			}



			insertTable.put(fields[columnIndex-1].getName(),String.valueOf(x));
		}
		else {
			insertTable.put(fields[columnIndex-1].getName(),String.valueOf(x));
		}
		try {
			rowBuffer[columnIndex-1]=String.valueOf(x).getBytes(connection.getEncoding().name());
		}
		catch(UnsupportedEncodingException use) {
			throw new SQLException("Unsupported Encoding "+connection.getEncoding().name());
		}




	}

	public synchronized void updateString(int columnIndex, String x) throws SQLException
	{
		System.out.println("in update String"+fields[columnIndex-1].getName()+"="+x);

		if (!onInsertRow) {

			if (!doingUpdates) {
				doingUpdates = true;
				//System.out.println("syncing");
				;
			}
			//System.out.println("setting in prepared statement "+fields[columnIndex-1].getName());
			//System.out.println("fields="+insertTable.size());
			insertTable.put(fields[columnIndex-1].getName(),"'"+x+"'");
		}
		else {
			insertTable.put(fields[columnIndex-1].getName(),"'"+x+"'");
		}

		//System.out.println("fields="+insertTable.size()+" updating rowbuffer");
		try {
			rowBuffer[columnIndex-1]=x.getBytes(connection.getEncoding().name());
		}
		catch(UnsupportedEncodingException use) {
			throw new SQLException("Unsupported Encoding "+connection.getEncoding().name());
		}
	}

	public synchronized void updateTime(int columnIndex, Time x) throws SQLException
	{


		if (!onInsertRow) {

			if (!doingUpdates) {
				doingUpdates = true;

				;
			}

			insertTable.put(fields[columnIndex-1].getName(),"'"+x.toString()+"'");
		}
		else {
			insertTable.put(fields[columnIndex-1].getName(),"'"+x.toString()+"'");
		}

		try {
			rowBuffer[columnIndex-1]=x.toString().getBytes(connection.getEncoding().name());
		}
		catch(UnsupportedEncodingException use) {
			throw new SQLException("Unsupported Encoding "+connection.getEncoding().name());
		}

	}

	public synchronized void updateTimestamp(int columnIndex, Timestamp x) throws SQLException
	{
		System.out.println("updating Timestamp "+fields[columnIndex-1].getName()+"="+x);

		if (!onInsertRow) {

			if (!doingUpdates) {
				doingUpdates = true;

				;
			}

			insertTable.put(fields[columnIndex-1].getName(),"'"+x.toString()+"'");
		}
		else {
			insertTable.put(fields[columnIndex-1].getName(),"'"+x.toString()+"'");
		}
		try {
			rowBuffer[columnIndex-1]=x.toString().getBytes(connection.getEncoding().name());
		}
		catch(UnsupportedEncodingException use) {
			throw new SQLException("Unsupported Encoding "+connection.getEncoding().name());
		}


	}

	public synchronized void updateNull(String columnName) throws SQLException {
		updateNull(findColumn(columnName));
	}

	/**
	 * JDBC 2.0
	 *
	 * Update a column with a boolean value.
	 *
	 * The updateXXX() methods are used to update column values in the
	 * current row, or the insert row.  The updateXXX() 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
	 */

	public synchronized void updateBoolean(String columnName, boolean x) throws SQLException {
		updateBoolean(findColumn(columnName), x);
	}

	/**
	 * JDBC 2.0
	 *
	 * Update a column with a byte value.
	 *
	 * The updateXXX() methods are used to update column values in the
	 * current row, or the insert row.  The updateXXX() 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
	 */

	public synchronized void updateByte(String columnName, byte x) throws SQLException {
		updateByte(findColumn(columnName), x);
	}

	/**
	 * JDBC 2.0
	 *
	 * Update a column with a short value.
	 *
	 * The updateXXX() methods are used to update column values in the
	 * current row, or the insert row.  The updateXXX() 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
	 */

	public synchronized void updateShort(String columnName, short x) throws SQLException {
		updateShort(findColumn(columnName), x);
	}

	/**
	 * JDBC 2.0
	 *
	 * Update a column with an integer value.
	 *
	 * The updateXXX() methods are used to update column values in the
	 * current row, or the insert row.  The updateXXX() 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
	 */

	public synchronized void updateInt(String columnName, int x) throws SQLException {
		updateInt(findColumn(columnName), x);
	}

	/**
	 * JDBC 2.0
	 *
	 * Update a column with a long value.
	 *
	 * The updateXXX() methods are used to update column values in the
	 * current row, or the insert row.  The updateXXX() 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
	 */

	public synchronized void updateLong(String columnName, long x) throws SQLException {
		updateLong(findColumn(columnName), x);
	}

	/**
	 * JDBC 2.0
	 *
	 * Update a column with a float value.
	 *
	 * The updateXXX() methods are used to update column values in the
	 * current row, or the insert row.  The updateXXX() 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
	 */

	public synchronized void updateFloat(String columnName, float x) throws SQLException {
		updateFloat(findColumn(columnName), x);
	}

	/**
	 * JDBC 2.0
	 *
	 * Update a column with a double value.
	 *
	 * The updateXXX() methods are used to update column values in the
	 * current row, or the insert row.  The updateXXX() 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
	 */

	public synchronized void updateDouble(String columnName, double x) throws SQLException {
		updateDouble(findColumn(columnName), x);
	}

	/**
	 * JDBC 2.0
	 *
	 * Update a column with a BigDecimal value.
	 *
	 * The updateXXX() methods are used to update column values in the
	 * current row, or the insert row.  The updateXXX() 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
	 */

	public synchronized void updateBigDecimal(String columnName, BigDecimal x)
		throws SQLException {
		updateBigDecimal(findColumn(columnName), x);
	}

	/**
	 * JDBC 2.0
	 *
	 * Update a column with a String value.
	 *
	 * The updateXXX() methods are used to update column values in the
	 * current row, or the insert row.  The updateXXX() 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
	 */

	public synchronized void updateString(String columnName, String x) throws SQLException {
		updateString(findColumn(columnName), x);
	}

	/**
	 * JDBC 2.0
	 *
	 * Update a column with a byte array value.
	 *
	 * The updateXXX() methods are used to update column values in the
	 * current row, or the insert row.  The updateXXX() 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
	 */

	public synchronized void updateBytes(String columnName, byte x[]) throws SQLException {
		updateBytes(findColumn(columnName), x);
	}

	/**
	 * JDBC 2.0
	 *
	 * Update a column with a Date value.
	 *
	 * The updateXXX() methods are used to update column values in the
	 * current row, or the insert row.  The updateXXX() 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
	 */

	public synchronized void updateDate(String columnName, java.sql.Date x)
		throws SQLException {
		updateDate(findColumn(columnName), x);
	}

	/**
	 * JDBC 2.0
	 *
	 * Update a column with a Time value.
	 *
	 * The updateXXX() methods are used to update column values in the
	 * current row, or the insert row.  The updateXXX() 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
	 */

	public synchronized void updateTime(String columnName, java.sql.Time x)
		throws SQLException {
		updateTime(findColumn(columnName), x);
	}

	/**
	 * JDBC 2.0
	 *
	 * Update a column with a Timestamp value.
	 *
	 * The updateXXX() methods are used to update column values in the
	 * current row, or the insert row.  The updateXXX() 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
	 */

	public synchronized void updateTimestamp(String columnName, java.sql.Timestamp x)
		throws SQLException {
		updateTimestamp(findColumn(columnName), x);
	}

	/**
	 * JDBC 2.0
	 *
	 * Update a column with an ascii stream value.
	 *
	 * The updateXXX() methods are used to update column values in the
	 * current row, or the insert row.  The updateXXX() 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
	 * @param length of the stream
	 * @exception SQLException if a database-access error occurs
	 */

	public synchronized void updateAsciiStream(
		String columnName,
		java.io.InputStream x,
		int length)
		throws SQLException {
		updateAsciiStream(findColumn(columnName), x, length);
	}

	/**
	 * JDBC 2.0
	 *
	 * Update a column with a binary stream value.
	 *
	 * The updateXXX() methods are used to update column values in the
	 * current row, or the insert row.  The updateXXX() 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
	 * @param length of the stream
	 * @exception SQLException if a database-access error occurs
	 */

	public synchronized void updateBinaryStream(
		String columnName,
		java.io.InputStream x,
		int length)
		throws SQLException {
		updateBinaryStream(findColumn(columnName), x, length);
	}

	/**
	 * JDBC 2.0
	 *
	 * Update a column with a character stream value.
	 *
	 * The updateXXX() methods are used to update column values in the
	 * current row, or the insert row.  The updateXXX() 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
	 * @param length of the stream
	 * @exception SQLException if a database-access error occurs
	 */

	public synchronized void updateCharacterStream(
		String columnName,
		java.io.Reader reader,
		int length)
		throws SQLException {
		updateCharacterStream(findColumn(columnName), reader,length);
	}

	/**
	 * JDBC 2.0
	 *
	 * Update a column with an Object value.
	 *
	 * The updateXXX() methods are used to update column values in the
	 * current row, or the insert row.  The updateXXX() 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
	 * @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 synchronized void updateObject(String columnName, Object x, int scale)
		throws SQLException {
		updateObject(findColumn(columnName), x);
	}

	/**
	 * JDBC 2.0
	 *
	 * Update a column with an Object value.
	 *
	 * The updateXXX() methods are used to update column values in the
	 * current row, or the insert row.  The updateXXX() 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
	 */

	public synchronized void updateObject(String columnName, Object x) throws SQLException {
		updateObject(findColumn(columnName), x);
	}




	public void setSQLQuery(String sqlQuery) {
		this.sqlQuery=sqlQuery;
		//System.out.println("sqlquery is "+sqlQuery);
		try {
			updateable=isUpdateable();

		}
		catch (SQLException se) {
			updateable=false;
		}
		if (updateable) {
		//System.out.println("No of primary keys="+primkeys.size());
		primaryKeyIndices = new Vector();
		for (int i = 0; i < fields.length; i++) {
				if (fields[i].getName().toUpperCase().equals("OID")) {
						removedOID=true;
						oidIndex=i;
				}
				//System.out.println("testing "+fields[i].getName());
				if (primkeys.contains(fields[i].getName())) {

						primaryKeyIndices.addElement(new Integer(i));
				}
		}
		}


	}



	/**
	 * Is this ResultSet updateable?
	 */

	boolean isUpdateable() throws SQLException {

			System.out.println("checking if rs is updateable");
			if (hasSingleTable()) {
				System.out.println("getting tablename");
				getTableName();
			}
			else
				return false;

		System.out.println("getting primary keys");
		//
		// Contains the primary key?
		//
		primkeys=new Vector();
		java.sql.ResultSet primkeynames=((org.postgresql.jdbc2.Connection)connection).getMetaData().getPrimaryKeys("","",tableName);
		while (primkeynames.next()) {
			primkeys.addElement(primkeynames.getString("COLUMN_NAME"));
		}
		primkeynames.close();
		//System.out.println("no of keys="+primkeys.size());
		if (primkeys.size()<1) {
			throw new SQLException("No Primary Keys");

		}
		boolean hasPrimaryKey = false;

		for (int i = 0; i < fields.length; i++) {
			if (primkeys.contains(fields[i].getName())) {
				hasPrimaryKey = true;

				break;
			}
		}
		//System.out.println("checking primary key "+hasPrimaryKey);
		if (!hasPrimaryKey) {
			return false;
		}

		return true;
	}

	public void getTableName() {
		StringTokenizer st=new StringTokenizer(sqlQuery," ");
		boolean found=false;
		String name="";
		while (!found && st.hasMoreTokens()) {
			name=st.nextToken();
			if (name.toLowerCase().equals("from")) {
				tableName=st.nextToken();
				found=true;
			}
		}
	}
	public boolean hasSingleTable() {

		String temp=sqlQuery.substring(sqlQuery.toLowerCase().indexOf(" from "));
		//System.out.println("tablenames "+temp);
		if (temp.toLowerCase().indexOf("where")>-1) {
			temp=temp.substring(0,temp.toLowerCase().indexOf("where"));
		}
		//System.out.println("tablenames "+temp);
		return temp.indexOf(",")==-1;
	}

}

