harmony-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From lvj...@apache.org
Subject svn commit: r599755 - in /harmony/enhanced/classlib/trunk/modules/sql/src: main/java/org/apache/harmony/sql/internal/rowset/ test/java/org/apache/harmony/sql/tests/internal/rowset/
Date Fri, 30 Nov 2007 09:40:48 GMT
Author: lvjing
Date: Fri Nov 30 01:40:46 2007
New Revision: 599755

URL: http://svn.apache.org/viewvc?rev=599755&view=rev
Log:
Apply patch for HARMONY-5227 ([classlib][sql] implement CachedRowSetWriter update and delete
rows from database)

Modified:
    harmony/enhanced/classlib/trunk/modules/sql/src/main/java/org/apache/harmony/sql/internal/rowset/CachedRow.java
    harmony/enhanced/classlib/trunk/modules/sql/src/main/java/org/apache/harmony/sql/internal/rowset/CachedRowSetImpl.java
    harmony/enhanced/classlib/trunk/modules/sql/src/main/java/org/apache/harmony/sql/internal/rowset/CachedRowSetWriter.java
    harmony/enhanced/classlib/trunk/modules/sql/src/test/java/org/apache/harmony/sql/tests/internal/rowset/CachedRowSetImplTest.java

Modified: harmony/enhanced/classlib/trunk/modules/sql/src/main/java/org/apache/harmony/sql/internal/rowset/CachedRow.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/trunk/modules/sql/src/main/java/org/apache/harmony/sql/internal/rowset/CachedRow.java?rev=599755&r1=599754&r2=599755&view=diff
==============================================================================
--- harmony/enhanced/classlib/trunk/modules/sql/src/main/java/org/apache/harmony/sql/internal/rowset/CachedRow.java
(original)
+++ harmony/enhanced/classlib/trunk/modules/sql/src/main/java/org/apache/harmony/sql/internal/rowset/CachedRow.java
Fri Nov 30 01:40:46 2007
@@ -70,6 +70,8 @@
 
     public void setDelete() {
         isDelete = true;
+        isUpdate = false;
+        isInsert = false;
     }
 
     public void undoDelete() {
@@ -82,6 +84,8 @@
 
     public void setInsert() {
         isInsert = true;
+        isUpdate = false;
+        isDelete = false;
     }
 
     public boolean isInsert() {
@@ -90,6 +94,8 @@
 
     public void setUpdate() {
         isUpdate = true;
+        isInsert = false;
+        isDelete = false;
     }
 
     public void undoUpdate() {

Modified: harmony/enhanced/classlib/trunk/modules/sql/src/main/java/org/apache/harmony/sql/internal/rowset/CachedRowSetImpl.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/trunk/modules/sql/src/main/java/org/apache/harmony/sql/internal/rowset/CachedRowSetImpl.java?rev=599755&r1=599754&r2=599755&view=diff
==============================================================================
--- harmony/enhanced/classlib/trunk/modules/sql/src/main/java/org/apache/harmony/sql/internal/rowset/CachedRowSetImpl.java
(original)
+++ harmony/enhanced/classlib/trunk/modules/sql/src/main/java/org/apache/harmony/sql/internal/rowset/CachedRowSetImpl.java
Fri Nov 30 01:40:46 2007
@@ -156,14 +156,16 @@
         try {
             CachedRowSetWriter rowSetWriter = (CachedRowSetWriter) syncProvider
                     .getRowSetWriter();
-            CachedRowSetImpl input = (CachedRowSetImpl) createCopy();
             rowSetWriter.setConnection(con);
-            rowSetWriter.writeData(input);
+            int beforeWriteIndex = currentRowIndex;
+            rowSetWriter.writeData(this);
+            absolute(beforeWriteIndex);
             /*
              * FIXME: if no conflicts happen when writeData, then call
              * setOriginalRow()
              */
             notifyRowSetChanged();
+
         } catch (SyncProviderException e) {
             throw e;
         } catch (SQLException e) {
@@ -1127,12 +1129,15 @@
     }
 
     public boolean rowUpdated() throws SQLException {
-
-        boolean sign = false;
-        for (int i = 0; i < meta.getColumnCount(); ++i) {
-            sign = currentRow.getUpdateMask(i) | sign;
+        if (!currentRow.isUpdate()) {
+            return false;
+        } else {
+            boolean sign = false;
+            for (int i = 0; i < meta.getColumnCount(); ++i) {
+                sign = currentRow.getUpdateMask(i) | sign;
+            }
+            return sign;
         }
-        return sign;
     }
 
     public void updateArray(int columnIndex, Array x) throws SQLException {
@@ -1303,7 +1308,7 @@
             // TODO add error messages
             throw new SQLException();
         }
-        rows.set(currentRowIndex, currentRow);
+        currentRow.setUpdate();
         notifyRowChanged();
     }
 

Modified: harmony/enhanced/classlib/trunk/modules/sql/src/main/java/org/apache/harmony/sql/internal/rowset/CachedRowSetWriter.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/trunk/modules/sql/src/main/java/org/apache/harmony/sql/internal/rowset/CachedRowSetWriter.java?rev=599755&r1=599754&r2=599755&view=diff
==============================================================================
--- harmony/enhanced/classlib/trunk/modules/sql/src/main/java/org/apache/harmony/sql/internal/rowset/CachedRowSetWriter.java
(original)
+++ harmony/enhanced/classlib/trunk/modules/sql/src/main/java/org/apache/harmony/sql/internal/rowset/CachedRowSetWriter.java
Fri Nov 30 01:40:46 2007
@@ -19,25 +19,17 @@
 import java.sql.Connection;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
-import java.sql.ResultSetMetaData;
 import java.sql.SQLException;
-import java.sql.Statement;
 
 import javax.sql.RowSetInternal;
 import javax.sql.RowSetWriter;
 import javax.sql.rowset.CachedRowSet;
 import javax.sql.rowset.spi.SyncProviderException;
 
-import org.apache.harmony.sql.internal.nls.Messages;
-
 public class CachedRowSetWriter implements RowSetWriter {
 
-    private ResultSet primaryKeys;
-
     private CachedRowSet originalRowSet;
 
-    private CachedRowSet cachedKeySet;
-
     private CachedRowSetImpl currentRowSet;
 
     private Connection originalConnection;
@@ -46,17 +38,8 @@
 
     private String[] colNames;
 
-    private String sql;
-
     private int columnCount;
 
-    private int signal = 0;
-
-    private Statement statement;
-
-    private String keyColumnName, whereStatementForOriginal,
-            whereStatementForCurrent;
-
     public void setConnection(Connection conn) {
         originalConnection = conn;
     }
@@ -74,40 +57,39 @@
         currentRowSet.beforeFirst();// currentRowSet.first();
         originalRowSet.beforeFirst();// originalRowSet.first();
         while (currentRowSet.next()) {
-            // inserted a new row
             if (currentRowSet.rowInserted()) {
                 insertCurrentRow();
+            } else if (currentRowSet.rowDeleted()) {
+                if (isConflictExistForCurrentRow()) {
+                    // TODO: conflict exists, should throw SyncProviderException
+                    throw new SyncProviderException();
+                }
+
+                deleteCurrentRow();
+
+            } else if (currentRowSet.rowUpdated()) {
+                if (isConflictExistForCurrentRow()) {
+                    // TODO: conflict exists, should throw SyncProviderException
+                    throw new SyncProviderException();
+                }
+                
+                updateCurrentRow();
             }
-            // TODO: other change, such as update and delete
         }
         // TODO release resource
         return true;
     }
 
-    private void initial(RowSetInternal theRowSet) throws SQLException {
-        currentRowSet = (CachedRowSetImpl) theRowSet;
-        // initial environment
-        originalRowSet = (CachedRowSet) currentRowSet.getOriginal();
-        // originalConnection = currentRowSet.getConnection();
-        cachedKeySet = new CachedRowSetImpl();
-        tableName = currentRowSet.getTableName();
-        columnCount = currentRowSet.getMetaData().getColumnCount();
-        primaryKeys = originalConnection.getMetaData().getPrimaryKeys("",
-                currentRowSet.getMetaData().getSchemaName(1), tableName);
-        cachedKeySet.populate(primaryKeys);
-        colNames = new String[columnCount];
-        for (int i = 1; i <= columnCount; i++) {
-            colNames[i - 1] = currentRowSet.getMetaData().getColumnName(i);
-        }
-    }
-
     /**
      * Insert the RowSet's current row to DB
      * 
      * @throws SQLException
      */
+    @SuppressWarnings("nls")
     private void insertCurrentRow() throws SQLException {
-        // the first step: generate the insert SQL
+        /*
+         * the first step: generate the insert SQL
+         */
         StringBuffer insertSQL = new StringBuffer("INSERT INTO " + tableName
                 + "(");
         StringBuffer insertColNames = new StringBuffer();
@@ -133,9 +115,11 @@
         insertSQL.append(subStringN(insertPlaceholder.toString(), 1));
         insertSQL.append(")");
 
-        // the second step: execute SQL
-        PreparedStatement preSt = originalConnection.prepareStatement(insertSQL
-                .toString());
+        /*
+         * the second step: execute SQL
+         */
+        PreparedStatement preSt = getConnection().prepareStatement(
+                insertSQL.toString());
         for (int i = 0; i < updateCount; i++) {
             preSt.setObject(i + 1, insertColValues[i]);
         }
@@ -144,153 +128,178 @@
         } catch (SQLException e) {
             // TODO generate SyncProviderException
             throw new SyncProviderException();
+        } finally {
+            preSt.close();
         }
-        preSt.close();
     }
 
-    private void writeRowData() throws SQLException {
-        try {
-            createScriptForWriteBack();
-            statement = originalConnection.prepareStatement(sql);
-            switch (signal) {
-            case 0:
-                fillParasOfKeys(currentRowSet, 0);
-                break;
-            case 1:
-                fillParasOfAllColumn();
-                break;
-            case 2:
-                fillParasOfAllColumn();
-                fillParasOfKeys(currentRowSet, columnCount);
-                break;
-            default:
-                break;
-            }
-            ((PreparedStatement) statement).executeUpdate();
-        } catch (SQLException e) {
-            e.printStackTrace();
-            new SQLException(Messages.getString("rowset.6"));
-        }
-
+    /**
+     * Delete the current row from DB
+     * 
+     * @throws SQLException
+     */
+    private void deleteCurrentRow() throws SQLException {
+        /*
+         * the first step: generate the delete SQL
+         */
+        StringBuffer deleteSQL = new StringBuffer("DELETE FROM " + tableName //$NON-NLS-1$
+                + " WHERE "); //$NON-NLS-1$
+        deleteSQL.append(generateQueryCondition());
+
+        /*
+         * the second step: execute SQL
+         */
+        PreparedStatement preSt = getConnection().prepareStatement(
+                deleteSQL.toString());
+        fillParamInPreStatement(preSt, 1);
+        preSt.executeUpdate();
     }
 
-    private void createScriptForWriteBack() throws SQLException {
-        cachedKeySet.first();
-        whereStatementForCurrent = "";
-        String insertCollector = "", updateCollector = "";
-        // FIXME:uses getUpdateMask()
-
-        do {
-            keyColumnName = cachedKeySet.getString("COLUMN_NAME");
-            whereStatementForCurrent = whereStatementForCurrent + keyColumnName
-                    + " = ? " + " and ";
-        } while (cachedKeySet.next());
-
-        whereStatementForCurrent = subStringN(whereStatementForCurrent, 5);
+    /**
+     * Update the current row to DB
+     * 
+     * @throws SQLException
+     */
+    @SuppressWarnings("nls")
+    private void updateCurrentRow() throws SQLException {
+        /*
+         * the first step: generate the delete SQL
+         */
+        StringBuffer updateSQL = new StringBuffer("UPDATE " + tableName
+                + " SET ");
+        StringBuffer updateCols = new StringBuffer();
+        Object[] updateColValues = new Object[columnCount];
+        int[] updateColIndexs = new int[columnCount];
 
-        // insertCollector: all column
+        int updateCount = 0;
         for (int i = 1; i <= columnCount; i++) {
-            insertCollector = insertCollector + " ? " + " , ";
+            boolean isColUpdate = currentRowSet.columnUpdated(i);
+            if (isColUpdate) {
+                updateCols.append(colNames[i - 1] + " = ?, ");
+                updateColValues[updateCount] = currentRowSet.getObject(i);
+                updateColIndexs[updateCount] = i;
+                updateCount++;
+            }
         }
-        insertCollector = subStringN(insertCollector, 3);
-
-        // update: all column
-        ResultSetMetaData tempRSMD = currentRowSet.getMetaData();
-        for (int i = 1; i <= columnCount; i++) {
-            updateCollector = updateCollector + tempRSMD.getColumnName(i)
-                    + "= ? , ";
+        if (updateCount == 0) {
+            return;
         }
-        updateCollector = subStringN(updateCollector, 3);
-
-        if (currentRowSet.getCurrentRow().isDelete()) {
-            // paras of where: pks
-            sql = " delete from " + tableName + " where "
-                    + whereStatementForCurrent;
-            signal = 0;
-        } else if (currentRowSet.getCurrentRow().isInsert()) {
-            // paras of insert : all
-            sql = " insert into " + tableName + " values " + " ( "
-                    + insertCollector + " ) ";
-            signal = 1;
-        } else {
-            // paras of update and where : all + pks
-            sql = " update " + tableName + " set " + updateCollector
-                    + " where " + whereStatementForCurrent;
-            signal = 2;
+        updateSQL.append(subStringN(updateCols.toString(), 2));
+        updateSQL.append(" WHERE ");
+        updateSQL.append(generateQueryCondition());
+
+        /*
+         * the second step: execute SQL
+         */
+        PreparedStatement preSt = getConnection().prepareStatement(
+                updateSQL.toString());
+        // the SET part of SQL
+        for (int i = 0; i < updateCount; i++) {
+            if (updateColValues[i] == null) {
+                preSt.setNull(i + 1, currentRowSet.getMetaData().getColumnType(
+                        updateColIndexs[i]));
+            } else {
+                preSt.setObject(i + 1, updateColValues[i]);
+            }
+        }
+        // the WHERE part of SQL
+        fillParamInPreStatement(preSt, updateCount + 1);
+        try {
+            preSt.executeUpdate();
+        } catch (SQLException e) {
+            // TODO generate SyncProviderException
+            throw new SyncProviderException();
+        } finally {
+            preSt.close();
         }
     }
 
-    private String subStringN(String input, int n) {
-        input = input.substring(0, input.length() - n);
-        return input;
+    private void initial(RowSetInternal theRowSet) throws SQLException {
+        currentRowSet = (CachedRowSetImpl) theRowSet;
+        // initial environment
+        originalRowSet = (CachedRowSet) currentRowSet.getOriginal();
+        // originalConnection = currentRowSet.getConnection();
+        tableName = currentRowSet.getTableName();
+        columnCount = currentRowSet.getMetaData().getColumnCount();
+        colNames = new String[columnCount];
+        for (int i = 1; i <= columnCount; i++) {
+            colNames[i - 1] = currentRowSet.getMetaData().getColumnName(i);
+        }
     }
 
-    private void createScriptForCheck() throws SQLException {
-        // formulate the Query SQL
-        String tempSelector = "";
-        whereStatementForOriginal = "";
-        cachedKeySet.first();
-        for (int i = 1; i <= columnCount; i++)
-            tempSelector = tempSelector
-                    + originalRowSet.getMetaData().getColumnName(i) + ", ";
-        tempSelector = tempSelector.substring(0, tempSelector.length() - 2);
-        sql = "select " + tempSelector + " from " + tableName + " where ";
-        do {
-            keyColumnName = cachedKeySet.getString("COLUMN_NAME");
-            whereStatementForOriginal = whereStatementForOriginal
-                    + keyColumnName + " = ? " + " and ";
-            whereStatementForOriginal = subStringN(whereStatementForOriginal, 5);
-        } while (cachedKeySet.next());
-        cachedKeySet.first();
-        sql = sql + whereStatementForOriginal;
-    }
+    /**
+     * Compare the current row's data between database and CachedRowSet to check
+     * whether it has been changed in database.
+     * 
+     * @return if conflict exists, return true; else, return false
+     * @throws SQLException
+     */
+    private boolean isConflictExistForCurrentRow() throws SQLException {
+        boolean isExist = true;
+        originalRowSet.absolute(currentRowSet.getRow()); // the original data
+
+        StringBuffer querySQL = new StringBuffer("SELECT COUNT(*) FROM " //$NON-NLS-1$
+                + tableName + " WHERE "); //$NON-NLS-1$
+        querySQL.append(generateQueryCondition());
+
+        PreparedStatement preSt = getConnection().prepareStatement(
+                querySQL.toString());
+        fillParamInPreStatement(preSt, 1);
+        ResultSet queryRs = preSt.executeQuery();
+        if (queryRs.next()) {
+            if (queryRs.getInt(1) == 1) {
+                isExist = false;
+            }
+        }
+        queryRs.close();
+        preSt.close();
 
-    private void fillParasOfKeys(CachedRowSet inputRS, int from)
-            throws SQLException {
-        cachedKeySet.first();
-        int i = from + 1;
-        do {
-            keyColumnName = cachedKeySet.getString("COLUMN_NAME");
-            ((PreparedStatement) statement).setObject(i++, inputRS
-                    .getObject(keyColumnName));
-        } while (cachedKeySet.next());
+        return isExist;
     }
 
-    private void fillParasOfAllColumn() throws SQLException {
-        for (int i = 1; i <= columnCount; i++) {
-            ResultSetMetaData rsmd = currentRowSet.getMetaData();
-            if (currentRowSet.getObject(i) == null) {
-                ((PreparedStatement) statement).setNull(i, rsmd
-                        .getColumnType(i));
+    /**
+     * Generate the query condition after the keyword "WHERE" in SQL. Expression
+     * likes as: COLUMN1 = ? AND COLUMN2 = ?
+     * 
+     * @return the SQL query expression
+     */
+    @SuppressWarnings("nls")
+    private String generateQueryCondition() throws SQLException {
+        StringBuffer queryCondtion = new StringBuffer(" ");
+        for (int i = 0; i < colNames.length; i++) {
+            if (originalRowSet.getObject(i + 1) == null) {
+                queryCondtion.append(colNames[i] + " is null ");
             } else {
-                ((PreparedStatement) statement).setObject(i, currentRowSet
-                        .getObject(i));
+                queryCondtion.append(colNames[i] + " = ? ");
+            }
+            if (i != colNames.length - 1) {
+                queryCondtion.append(" and ");
             }
         }
+        return queryCondtion.toString();
     }
 
-    private boolean checkConflictNotExist(CachedRowSet crs) {
-        try {
-            createScriptForCheck();
-            statement = originalConnection.prepareStatement(sql);
-            fillParasOfKeys(originalRowSet, 0);
-            ResultSet dataInDB = ((PreparedStatement) statement).executeQuery();
-            sql = "";
-            // compare line by line, column by column
-            if (dataInDB.next()) {
-                for (int i = 1; i <= dataInDB.getMetaData().getColumnCount(); i++) {
-                    if (dataInDB.getObject(i) == crs.getObject(i)) {
-                        continue;
-                    }
-                    if (!(dataInDB.getObject(i).equals(crs.getObject(i)))) {
-                        return false;
-                    }
-                }
+    /**
+     * Fill all the parameters in PreparedStatement
+     * 
+     * @param preSt
+     *            PreparedStatement
+     * @param fromIndex
+     *            It must be greater than 0
+     * @throws SQLException
+     */
+    private void fillParamInPreStatement(PreparedStatement preSt, int fromIndex)
+            throws SQLException {
+        int notNullCount = fromIndex;
+        for (int i = 1; i <= columnCount; i++) {
+            if (originalRowSet.getObject(i) != null) {
+                preSt.setObject(notNullCount, originalRowSet.getObject(i));
+                notNullCount++;
             }
-        } catch (Exception e) {
-            e.printStackTrace();
         }
-        return true;
     }
 
+    private String subStringN(String input, int n) {
+        return input.substring(0, input.length() - n);
+    }
 }

Modified: harmony/enhanced/classlib/trunk/modules/sql/src/test/java/org/apache/harmony/sql/tests/internal/rowset/CachedRowSetImplTest.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/trunk/modules/sql/src/test/java/org/apache/harmony/sql/tests/internal/rowset/CachedRowSetImplTest.java?rev=599755&r1=599754&r2=599755&view=diff
==============================================================================
--- harmony/enhanced/classlib/trunk/modules/sql/src/test/java/org/apache/harmony/sql/tests/internal/rowset/CachedRowSetImplTest.java
(original)
+++ harmony/enhanced/classlib/trunk/modules/sql/src/test/java/org/apache/harmony/sql/tests/internal/rowset/CachedRowSetImplTest.java
Fri Nov 30 01:40:46 2007
@@ -21,6 +21,7 @@
 import java.sql.Connection;
 import java.sql.Date;
 import java.sql.DriverManager;
+import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.sql.Time;
@@ -1393,7 +1394,6 @@
         /*
          * Insert a new row one time
          */
-        crset.setReadOnly(false);
         crset.moveToInsertRow();
         crset.updateInt(1, 5);
         crset.updateString(2, "test5");
@@ -1424,18 +1424,306 @@
         assertTrue(rs.next());
         assertEquals(5, rs.getInt(1));
 
+        /*
+         * TODO Insert multiple rows one time, uncomment after implemented
+         */
+        // TODO uncomment it after insert methods are implemented
+        // noInitialCrset = newNoInitialInstance();
+        // rs = st.executeQuery("select * from USER_INFO");
+        // noInitialCrset.populate(rs);
+        // noInitialCrset.setReadOnly(false);
+        // noInitialCrset.moveToInsertRow();
+        // for (int i = 6; i <= 20; i++) {
+        // noInitialCrset.updateInt(1, i);
+        // noInitialCrset.updateString(2, "test" + i);
+        // noInitialCrset.insertRow();
+        // }
+        // noInitialCrset.moveToCurrentRow();
+        // noInitialCrset.acceptChanges(conn);
+        // // check the new rows in CachedRowSet
+        // assertEquals(20, noInitialCrset.size());
+        // // check the new rows in DB
+        // rs = st.executeQuery("select * from USER_INFO");
+        // int cursorIndex = 0;
+        // while (rs.next()) {
+        // cursorIndex++;
+        // }
+        // assertEquals(20, cursorIndex);
+    }
+
+    public void testAcceptChanges_InsertException() throws Exception {
+        /*
+         * Insert a new row. One given column's value exceeds the max range.
+         * Therefore, it should throw SyncProviderException.
+         */
         crset.moveToInsertRow();
-        // already exist
-        crset.updateInt(1, 5);
+        crset.updateInt(1, 4);
         crset.updateString(2, "test5");
+        crset.updateLong(3, 555555L);
+        crset.updateInt(4, 200000); // 200000 exceeds the NUMERIC's range
+        crset.updateBigDecimal(5, new BigDecimal(23));
+        crset.updateFloat(8, 4.888F);
+        crset.insertRow();
+        crset.moveToCurrentRow();
+        try {
+            crset.acceptChanges(conn);
+            fail("should throw SyncProviderException");
+        } catch (SyncProviderException e) {
+            // TODO analysis SyncProviderException
+        }
 
+        /*
+         * Insert a new row. The new row's primary key has existed. Therefore,
+         * it should throw SyncProviderException.
+         */
+        crset = newNoInitialInstance();
+        rs = st.executeQuery("select * from USER_INFO");
+        crset.populate(rs);
+        crset.moveToInsertRow();
+        crset.updateInt(1, 4); // The ID valued 4 has existed in db.
+        crset.updateString(2, "test5");
+        crset.updateBigDecimal(4, new BigDecimal(12));
+        crset.updateTimestamp(12, new Timestamp(874532105));
         crset.insertRow();
         crset.moveToCurrentRow();
         try {
             crset.acceptChanges(conn);
-            fail("Should throw SyncProviderException");
+            fail("should throw SyncProviderException");
+        } catch (SyncProviderException e) {
+            // TODO analysis SyncProviderException
+        }
+
+        /*
+         * Insert a new row. Before inserting the new row, another new row which
+         * has the same data is inserted into the DB. However, the current
+         * CachedRowSet doesn't know it. In this situation, it should throw
+         * SyncProviderException.
+         */
+        crset = newNoInitialInstance();
+        rs = st.executeQuery("select * from USER_INFO");
+        crset.populate(rs);
+        String insertSQL = "INSERT INTO USER_INFO(ID, NAME, BIGINT_T, NUMERIC_T,DECIMAL_T,
SMALLINT_T, "
+                + "FLOAT_T, REAL_T, DOUBLE_T, DATE_T, TIME_T, TIMESTAMP_T) VALUES(?, ?, ?,
?, ?, ?,"
+                + "?, ?, ?, ?, ?, ? )";
+        PreparedStatement preStmt = conn.prepareStatement(insertSQL);
+        preStmt.setInt(1, 80);
+        preStmt.setString(2, "test" + 80);
+        preStmt.setLong(3, 444423L);
+        preStmt.setBigDecimal(4, new BigDecimal(12));
+        preStmt.setBigDecimal(5, new BigDecimal(23));
+        preStmt.setInt(6, 41);
+        preStmt.setFloat(7, 4.8F);
+        preStmt.setFloat(8, 4.888F);
+        preStmt.setDouble(9, 4.9999);
+        preStmt.setDate(10, new Date(965324512));
+        preStmt.setTime(11, new Time(452368512));
+        preStmt.setTimestamp(12, new Timestamp(874532105));
+        preStmt.executeUpdate();
+        if (preStmt != null) {
+            preStmt.close();
+        }
+        // check the new row in DB
+        rs = st.executeQuery("select * from USER_INFO where ID = 80");
+        assertTrue(rs.next());
+        assertEquals(80, rs.getInt(1));
+        assertEquals("test80", rs.getString(2));
+
+        // now call CachedRowSet.insertRow()
+        crset.moveToInsertRow();
+        crset.updateInt(1, 80);
+        crset.updateString(2, "test" + 80);
+        crset.updateLong(3, 444423L);
+        crset.updateBigDecimal(4, new BigDecimal(12));
+        crset.updateBigDecimal(5, new BigDecimal(23));
+        crset.updateInt(6, 41);
+        crset.updateFloat(7, 4.8F);
+        crset.updateFloat(8, 4.888F);
+        crset.updateDouble(9, 4.9999);
+        crset.updateDate(10, new Date(965324512));
+        crset.updateTime(11, new Time(452368512));
+        crset.updateTimestamp(12, new Timestamp(874532105));
+        crset.insertRow();
+        crset.moveToCurrentRow();
+        try {
+            crset.acceptChanges(conn);
+            fail("should throw SyncProviderException");
+        } catch (SyncProviderException e) {
+            // TODO analysis SyncProviderException
+        }
+    }
+
+    public void testAcceptChanges_Delete() throws Exception {
+        /*
+         * Delete all the row. On the first and second row, only two columns
+         * have value, all the others are NULL. When run on RI, deleteRow() will
+         * go wrong and throw Exception. According to the spec, deleteRow() is
+         * supposed to ok.
+         */
+        crset.beforeFirst();
+        while (crset.next()) {
+            crset.deleteRow();
+        }
+        if ("true".equals(System.getProperty("Testing Harmony"))) {
+            crset.acceptChanges(conn);
+        } else {
+            try {
+                crset.acceptChanges(conn);
+            } catch (NullPointerException e) {
+                // RI would throw NullPointerException when deleting a row in
+                // which some columns' value are null
+            }
+        }
+        // check DB
+        rs = st.executeQuery("select * from USER_INFO");
+        int rowCount = 0;
+        while (rs.next()) {
+            rowCount++;
+        }
+        if ("true".equals(System.getProperty("Testing Harmony"))) {
+            assertEquals(0, rowCount);
+        } else {
+            assertEquals(4, rowCount);
+        }
+    }
+
+    public void testAcceptChanges_DeleteException() throws Exception {
+        /*
+         * Delete a row which has been deleted from database
+         */
+        int result = st.executeUpdate("delete from USER_INFO where ID = 3");
+        assertEquals(1, result);
+        // move to the third row which doesn't exist in database
+        assertTrue(crset.absolute(3));
+        assertEquals(3, crset.getInt(1));
+        crset.deleteRow();
+        try {
+            crset.acceptChanges(conn);
+            fail("should throw SyncProviderException");
+        } catch (SyncProviderException e) {
+            // TODO analysis SyncProviderException
+        }
+
+        /*
+         * Delete a row which has been updated in database
+         */
+        crset = newNoInitialInstance();
+        rs = st.executeQuery("select * from USER_INFO");
+        crset.populate(rs);
+        result = st
+                .executeUpdate("update USER_INFO set NAME = 'update44' where ID = 4");
+        assertEquals(1, result);
+        // move to the updated row
+        crset.absolute(3);
+        assertEquals(4, crset.getInt(1));
+        assertEquals("test4", crset.getString(2));
+        crset.deleteRow();
+        try {
+            crset.acceptChanges(conn);
+            fail("should throw SyncProviderException");
+        } catch (SyncProviderException e) {
+            // TODO analysis SyncProviderException
+        }
+    }
+
+    public void testAcceptChanges_Update() throws Exception {
+        // update the first row
+        assertTrue(crset.absolute(1));
+        crset.updateInt(1, 11);
+        crset.updateString(2, "test11");
+        crset.updateRow();
+        crset.acceptChanges(conn);
+        // check DB
+        rs = st.executeQuery("select * from USER_INFO where ID = 11");
+        assertTrue(rs.next());
+        assertEquals(11, rs.getInt(1));
+        assertEquals("test11", rs.getString(2));
+
+        // update the third row
+        noInitialCrset = newNoInitialInstance();
+        rs = st.executeQuery("select * from USER_INFO");
+        noInitialCrset.populate(rs);
+        assertTrue(noInitialCrset.absolute(1));
+        noInitialCrset.updateInt(1, 111);
+        noInitialCrset.updateString(2, "update111");
+        noInitialCrset.updateRow();
+        assertTrue(noInitialCrset.absolute(3));
+        noInitialCrset.updateInt(1, 333);
+        noInitialCrset.updateString(2, "update333");
+        noInitialCrset.updateLong(3, 33333L);
+        noInitialCrset.updateRow();
+        noInitialCrset.acceptChanges(conn);
+        // check DB
+        rs = st.executeQuery("select * from USER_INFO where ID = 111");
+        assertTrue(rs.next());
+        assertEquals(111, rs.getInt(1));
+        assertEquals("update111", rs.getString(2));
+        rs = st.executeQuery("select * from USER_INFO where ID = 333");
+        assertTrue(rs.next());
+        assertEquals(333, rs.getInt(1));
+        assertEquals("update333", rs.getString(2));
+        assertEquals(33333L, rs.getLong(3));
+    }
+
+    public void testAcceptChanges_UpdateException() throws Exception {
+        /*
+         * Update a row which has been deleted from database
+         */
+        int result = st.executeUpdate("delete from USER_INFO where ID = 3");
+        assertEquals(1, result);
+        // move to the third row which doesn't exist in database
+        assertTrue(crset.absolute(3));
+        assertEquals(3, crset.getInt(1));
+        crset.updateString(2, "update33");
+        crset.updateRow();
+        try {
+            crset.acceptChanges(conn);
+            fail("should throw SyncProviderException");
+        } catch (SyncProviderException e) {
+            // TODO analysis SyncProviderException
+        }
+
+        /*
+         * Update a row which has been updated in database
+         */
+        crset = newNoInitialInstance();
+        rs = st.executeQuery("select * from USER_INFO");
+        crset.populate(rs);
+        result = st
+                .executeUpdate("update USER_INFO set NAME = 'update44' where ID = 4");
+        assertEquals(1, result);
+        // move to the updated row
+        assertTrue(crset.absolute(3));
+        assertEquals(4, crset.getInt(1));
+        assertEquals("test4", crset.getString(2));
+        crset.updateString(2, "change4");
+        crset.updateRow();
+        try {
+            crset.acceptChanges(conn);
+            fail("should throw SyncProviderException");
+        } catch (SyncProviderException e) {
+            // TODO analysis SyncProviderException
+        }
+
+        /*
+         * Update a row in which one column's value is out of range
+         */
+        crset = newNoInitialInstance();
+        rs = st.executeQuery("select * from USER_INFO");
+        crset.populate(rs);
+        assertEquals(3, crset.size());
+        assertTrue(crset.absolute(3));
+        assertEquals(4, crset.getInt(1));
+        crset.updateString(2, "update4");
+        crset.updateLong(3, 555555L);
+        crset.updateInt(4, 200000); // 200000 exceeds the NUMERIC's range
+        crset.updateBigDecimal(5, new BigDecimal(23));
+        crset.updateFloat(8, 4.888F);
+        crset.updateRow();
+        try {
+            crset.acceptChanges(conn);
+            fail("should throw SyncProviderException");
         } catch (SyncProviderException e) {
-            // TODO test SyncResolver
+            // TODO analysis SyncProviderException
         }
     }
 



Mime
View raw message