KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opensubsystems > core > persist > db > driver > GeneratedKeyTest


1 /*
2  * Copyright (c) 2003 - 2007 OpenSubsystems s.r.o. Slovak Republic. All rights reserved.
3  *
4  * Project: OpenSubsystems
5  *
6  * $Id: GeneratedKeyTest.java,v 1.11 2007/01/07 06:14:51 bastafidli Exp $
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; version 2 of the License.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20  */

21
22 package org.opensubsystems.core.persist.db.driver;
23
24 import java.sql.PreparedStatement JavaDoc;
25 import java.sql.ResultSet JavaDoc;
26 import java.sql.Types JavaDoc;
27 import java.util.logging.Logger JavaDoc;
28
29 import junit.extensions.TestSetup;
30 import junit.framework.Test;
31 import junit.framework.TestSuite;
32
33 import org.opensubsystems.core.error.OSSException;
34 import org.opensubsystems.core.persist.db.Database;
35 import org.opensubsystems.core.persist.db.DatabaseImpl;
36 import org.opensubsystems.core.persist.db.DatabaseSchemaManager;
37 import org.opensubsystems.core.persist.db.DatabaseTest;
38 import org.opensubsystems.core.persist.db.DatabaseTestSetup;
39 import org.opensubsystems.core.persist.db.DatabaseTestSuite;
40 import org.opensubsystems.core.util.DatabaseUtils;
41 import org.opensubsystems.core.util.GlobalConstants;
42 import org.opensubsystems.core.util.Log;
43
44 /**
45  * All tests related to test key generation by database.
46  *
47  * @version $Id: GeneratedKeyTest.java,v 1.11 2007/01/07 06:14:51 bastafidli Exp $
48  * @author Miro Halas
49  * @code.reviewer Miro Halas
50  * @code.reviewed Initial revision
51  */

52 public final class GeneratedKeyTest
53 {
54    // Constructors /////////////////////////////////////////////////////////////
55

56    /**
57     * Private constructor since this class cannot be instantiated
58     */

59    private GeneratedKeyTest(
60    )
61    {
62       // Do nothing
63
}
64    
65    // Public methods ///////////////////////////////////////////////////////////
66

67    /**
68     * Create the suite for this test since this is the only way how to create
69     * test setup which can initialize and shutdown the database for us
70     *
71     * @return Test - suite of tests to run for this database
72     */

73    public static Test suite(
74    )
75    {
76       TestSuite suite = new DatabaseTestSuite("GeneratedKeyTest");
77       suite.addTestSuite(GeneratedKeyTestInternal.class);
78       TestSetup wrapper = new DatabaseTestSetup(suite);
79
80       return wrapper;
81    }
82
83    /**
84     * Internal class which can be included in other test suites directly without
85     * including the above suite. This allows us to group multiple tests
86     * together and the execute the DatabaseTestSetup only once
87     */

88    public static class GeneratedKeyTestInternal extends DatabaseTest
89    {
90       // Cached values ////////////////////////////////////////////////////////////
91

92       /**
93        * Logger for this class
94        */

95       private static Logger JavaDoc s_logger = Log.getInstance(GeneratedKeyTest.class);
96    
97       /**
98        * Static initializer
99        */

100       static
101       {
102          // This test use special database schema so make the database aware of it
103
Database dbDatabase;
104    
105          try
106          {
107             dbDatabase = DatabaseImpl.getInstance();
108             // Add schema database tests needs to the database
109
dbDatabase.add(DatabaseTestSchema.class);
110          }
111          catch (OSSException bfeExc)
112          {
113             throw new RuntimeException JavaDoc("Unexpected exception.", bfeExc);
114          }
115       }
116       
117       /**
118        * Create new test.
119        *
120        * @param strTestName - name of the test
121        */

122       public GeneratedKeyTestInternal(
123          String JavaDoc strTestName
124       )
125       {
126          super(strTestName);
127       }
128       
129       /**
130        * Test if the database driver supports fetching of generated keys.
131        *
132        * Uses the already setup connection and transaction.
133        * No need to close the connection since base class is doing it for us.
134        *
135        * @throws Throwable - an error has occured during test
136        */

137       public void testGeneratedKey(
138       ) throws Throwable JavaDoc
139       {
140          final String JavaDoc INSERT_VALUE = ((DatabaseTestSchema)DatabaseSchemaManager.getInstance(
141                                         DatabaseTestSchema.class)).getInsertGeneratedKey();
142          final String JavaDoc DELETE_VALUE = "delete from GENERATEDKEY_TEST where TEST_VALUE = ?";
143          final String JavaDoc VALUE_TEST = "test value";
144           
145          PreparedStatement JavaDoc insertStatement = null;
146          ResultSet JavaDoc rsResults = null;
147          int iInsertCount;
148          
149          m_transaction.begin();
150    
151          try
152          {
153             insertStatement = m_connection.prepareStatement(INSERT_VALUE);
154             insertStatement.setString(1, VALUE_TEST);
155    
156             iInsertCount = insertStatement.executeUpdate();
157    
158             // Now try to retrieve the generated key
159
try
160             {
161                rsResults = insertStatement.getGeneratedKeys();
162                rsResults.getInt(1);
163             }
164             catch (Throwable JavaDoc throwable)
165             {
166                // I really don't want to fail this test, just to detect that
167
// this database driver still doesn't support the updatable result set
168
s_logger.warning("Warning: Database driver " + getDataSourceName()
169                                          + " still doesn't support retrieval of generated keys: "
170                                          + throwable);
171             }
172    
173             m_transaction.commit();
174          }
175          catch (Throwable JavaDoc throwable)
176          {
177             m_transaction.rollback();
178             throw throwable;
179          }
180          finally
181          {
182             DatabaseUtils.closeResultSetAndStatement(rsResults, insertStatement);
183          }
184          
185          assertEquals("Exactly one record have been inserted.",
186                              iInsertCount, 1);
187                                                              
188          // Now select it back to be sure it is there so we can delete it
189
int iDeletedCount = 0;
190    
191          m_transaction.begin();
192    
193          try
194          {
195             PreparedStatement JavaDoc deleteStatement;
196             
197             deleteStatement = m_connection.prepareStatement(DELETE_VALUE);
198             deleteStatement.setString(1, VALUE_TEST);
199             iDeletedCount = DatabaseUtils.executeUpdateAndClose(deleteStatement);
200             m_transaction.commit();
201             
202             assertEquals("Exactly one record with date data shoud have been deleted.",
203                                 1, iDeletedCount);
204          }
205          catch (Throwable JavaDoc throwable)
206          {
207             m_transaction.rollback();
208             throw throwable;
209          }
210       }
211       
212       /**
213        * Test if we can fetch generated keys using stored procedure
214        *
215        * Uses the already setup connection and transaction.
216        * No need to close the connection since base class is doing it for us.
217        *
218        * @throws Throwable - an error has occured during test
219        */

220       public void testGeneratedKeyUsingStoredProcedure(
221       ) throws Throwable JavaDoc
222       {
223          final String JavaDoc DELETE_VALUE = "delete from GENERATEDKEY_TEST where TEST_VALUE = ?";
224          final String JavaDoc VALUE_TEST = "test value";
225           
226          int iInsertCount = 0;
227          int iGeneratedKey = 0;
228          
229          m_transaction.begin();
230    
231          try
232          {
233             int[] returnValues;
234             
235             returnValues = ((DatabaseTestSchema)DatabaseSchemaManager.getInstance(
236                               DatabaseTestSchema.class)).executeInsertGeneratedKey2(
237                                  m_connection, VALUE_TEST);
238             if (returnValues != null)
239             {
240                iInsertCount = returnValues[0];
241                iGeneratedKey = returnValues[1];
242             }
243             
244             m_transaction.commit();
245          }
246          catch (Throwable JavaDoc throwable)
247          {
248             m_transaction.rollback();
249             throw throwable;
250          }
251          
252          assertEquals("Exactly one record have been inserted.",
253                              1, iInsertCount);
254          assertTrue("Generated key must be greater than 0", iGeneratedKey > 0);
255          s_logger.finest("Database generated and using stored procedure returned key "
256                                   + iGeneratedKey);
257                                                              
258          // Now select it back to be sure it is there so we can delete it
259
int iDeletedCount = 0;
260    
261          m_transaction.begin();
262    
263          try
264          {
265             PreparedStatement JavaDoc deleteStatement;
266             
267             deleteStatement = m_connection.prepareStatement(DELETE_VALUE);
268             deleteStatement.setString(1, VALUE_TEST);
269             iDeletedCount = DatabaseUtils.executeUpdateAndClose(deleteStatement);
270             m_transaction.commit();
271             
272             assertEquals("Exactly one record with date data shoud have been deleted.",
273                                 iDeletedCount, 1);
274          }
275          catch (Throwable JavaDoc throwable)
276          {
277             m_transaction.rollback();
278             throw throwable;
279          }
280       }
281       
282       /**
283        * Test if the database driver supports inserting into tables where the foreign key
284        * pointing to the same row which is being inserted.
285        *
286        * Uses the already setup connection and transaction.
287        * No need to close the connection since base class is doing it for us.
288        *
289        * @throws Throwable - an error has occured during test
290        */

291       public void testForeignKey(
292       ) throws Throwable JavaDoc
293       {
294          final String JavaDoc INSERT_VALUE = "insert into OWN_FK_TEST (TEST_ID,FK_ID) values (?,?)";
295          final String JavaDoc UPDATE_VALUE = "update OWN_FK_TEST set FK_ID = ? where TEST_ID = ?";
296          final String JavaDoc DELETE_VALUE = "delete from OWN_FK_TEST where TEST_ID = ?";
297           
298          PreparedStatement JavaDoc insertStatement = null;
299          PreparedStatement JavaDoc deleteStatement = null;
300          int iInsertCount;
301          int iDeleteCount;
302          
303          m_transaction.begin();
304    
305          try
306          {
307             try
308             {
309                insertStatement = m_connection.prepareStatement(INSERT_VALUE);
310                insertStatement.setInt(1, 1);
311                insertStatement.setInt(2, 1);
312                iInsertCount = insertStatement.executeUpdate();
313                if (GlobalConstants.ERROR_CHECKING)
314                {
315                   // This is here to avoid Checkstyle warning
316
assert iInsertCount >= 0 : "executeUpdate cannot return negative value.";
317                }
318             }
319             catch (Throwable JavaDoc throwable)
320             {
321                assertTrue("Not possible to insert data which FK is pointing to themselves.", false);
322    
323                insertStatement = m_connection.prepareStatement(INSERT_VALUE);
324                insertStatement.setInt(1, 1);
325                insertStatement.setNull(2, Types.INTEGER);
326                iInsertCount = insertStatement.executeUpdate();
327    
328                insertStatement = m_connection.prepareStatement(UPDATE_VALUE);
329                insertStatement.setInt(1, 1);
330                insertStatement.setInt(2, 1);
331                iInsertCount = insertStatement.executeUpdate();
332    
333             }
334             
335             // Now try to retrieve the generated key
336
try
337             {
338                deleteStatement = m_connection.prepareStatement(DELETE_VALUE);
339                deleteStatement.setInt(1, 1);
340                iDeleteCount = deleteStatement.executeUpdate();
341                if (GlobalConstants.ERROR_CHECKING)
342                {
343                   // This is here to avoid Checkstyle warning
344
assert iDeleteCount >= 0 : "executeUpdate cannot return negative value.";
345                }
346             }
347             catch (Throwable JavaDoc throwable)
348             {
349                assertTrue("Not possible to delete data which FK is pointing to themselves.",
350                                     false);
351                throw throwable;
352             }
353    
354             m_transaction.commit();
355          }
356          catch (Throwable JavaDoc throwable)
357          {
358             m_transaction.rollback();
359             throw throwable;
360          }
361          finally
362          {
363             DatabaseUtils.closeStatement(deleteStatement);
364             DatabaseUtils.closeStatement(insertStatement);
365          }
366       }
367    }
368 }
369
Popular Tags