org.apache.derbyTesting.junit
Class BaseJDBCTestCase

java.lang.Object
  extended by junit.framework.Assert
      extended by junit.framework.TestCase
          extended by org.apache.derbyTesting.junit.BaseTestCase
              extended by org.apache.derbyTesting.junit.BaseJDBCTestCase
All Implemented Interfaces:
junit.framework.Test
Direct Known Subclasses:
_Suite, AggregateClassLoadingTest, AIjdbcTest, AlterColumnTest, AlterTableTest, AnsiSignaturesTest, AnsiTrimTest, ArithmeticTest, AuthenticationTest, AutoGenJDBC30Test, AutoloadTest, BackupRestoreTest, BadConnectionTest, BasicInMemoryDbTest, BatchUpdateTest, BigDataTest, BlobClob4BlobTest, BlobMemTest, BlobSetMethodsTest, BlobStoredProcedureTest, BlobTest, BLOBTest, BlobUpdatableStreamTest, BootAllTest, Bug4356Test, Bug5052rtsTest, Bug5054Test, CacheSessionDataTest, CallableStatementTest, CallableTest, CanonTestCase, CaseExpressionTest, CastingTest, CharacterStreamsTest, CharUTF8Test, CheckConstraintTest, CheckSecurityManager, CheckToursDBTest, ClassLoaderBootTest, ClientConnectionPoolDataSourceTest, ClientRunner, ClientSideSystemPropertiesTest, ClobMemTest, ClobReclamationTest, ClobStoredProcedureTest, ClobTest, ClobTest, ClobTruncateTest, ClobUpdatableReaderTest, ClosedObjectTest, CoalesceTest, CollationTest, CollationTest2, ColumnDefaultsTest, CommentTest, CompressTableTest, ConglomerateSharingTest, ConnectionHandlingJunit, ConnectionMethodsTest, ConnectionTest, ConnectTest, ConstantExpressionTest, CreateTableFromQueryTest, CurrentOfTest, CursorTest, CustomMBeanServerBuilderTest, DatabaseClassLoadingTest, DatabaseMetaDataTest, DataSourcePropertiesTest, DataSourceReferenceTest, DataSourceSerializationTest, DataSourceTest, DataSourceTest, DateTimeTest, DBInJarTest, DboPowersTest, DeadlockModeTest, DeclareGlobalTempTableJavaJDBC30Test, DeclareGlobalTempTableJavaTest, Derby3650Test, Derby3980DeadlockTest, DestroySlaveDB, DistinctTest, DMDBugsTest, DRDAProtocolTest, DriverTest, DropTableTest, DropWhileConnectingTest, DSCreateShutdownDBTest, DynamicLikeOptimizationTest, EncryptionAESTest, EncryptionKeyTest, EncryptionSuite, ErrorCodeTest, ErrorMessageTest, ErrorStreamTest, ExistsWithSubqueriesTest, FloatTypesTest, ForBitDataTest, ForUpdateTest, GeneratedColumnsHelper, GetCurrentPropertiesTest, GrantRevokeDDLTest, GrantRevokeTest, GroupByExpressionTest, GroupByTest, HoldCursorExternalSortJDBC30Test, HoldCursorJDBC30Test, HoldCursorTest, IJRunScriptTest, ImportExportBaseTest, ImportExportProcedureTest, ImportExportTest, InbetweenTest, IndexSplitDeadlockTest, InListMultiProbeTest, InsertTest, InternalClobTest, InternationalConnectSimpleDSTest, InternationalConnectTest, InvalidLDAPServerAuthenticationTest, J2EEDataSourceTest, JDBC4FromJDBC3DataSourceTest, JDBCPerfTestCase, JDBCStatementCacheTest, JoinTest, KillMaster, KillSlave, LangProcedureTest, largeCodeGen, LargeDataLocksTest, LazyDefaultSchemaCreationTest, LDAPAuthenticationTest, LiveLockTest, LobLengthTest, LOBLocatorReleaseTest, LobSortTest, LobStreamsTest, LobStreamTest, LogicalStatementEntityTest, MathTrigFunctionsTest, MBeanTest, metadataMultiConnTest, MiscErrorsTest, MixedCaseExpressionTest, ModuleLoadingTest, MogTest, MultiByteClobTest, NestedWhereSubqueryTest, NetworkServerControlApiTest, NetworkServerControlClientCommandTest, NSinSameJVMTest, NSSecurityMechanismTest, NullableUniqueConstraintTest, NullIfTest, NullSQLTextTest, NullsTest, OETest, OfflineBackupTest, OffsetFetchNextTest, OLAPTest, OperationsTester, OptimizerOverridesTest, OrderByAndSortAvoidance, OSReadOnlyTest, OutBufferedStreamTest, ParameterMappingTest, ParameterMetaDataJdbc30Test, ParameterMetaDataWrapperTest, PoolXADSCreateShutdownDBTest, PrecedenceTest, PredicatePushdownTest, PreparedStatementTest, PrepareExecuteDDL, PrepareStatementTest, PrepStmtMetaDataTest, PrepStmtNullTest, PrimaryKeyTest, ProcedureInTriggerTest, ProcedureTest, ReferentialActionsTest, RelativeTest, ReleaseCompileLocksTest, RenameIndexTest, RenameTableTest, ReplicationTestRun, ReplicationTestRun_Verify, ResultSetCloseTest, ResultSetJDBC30Test, ResultSetMetaDataTest, ResultSetMiscTest, ResultSetsFromPreparedStatementTest, ResultSetStreamTest, ResultSetTest, RolesConferredPrivilegesTest, RolesTest, RoutineSecurityTest, RoutineTest, RowIdNotImplementedTest, RuntimeInfoTest, SavepointJdbc30Test, ScrollCursors1Test, ScrollCursors2Test, ScrollResultSetTest, SecureServerTest, SecurityPolicyReloadingTest, SelectivityTest, SequenceTest, ServerPropertiesTest, SetObjectUnsupportedTest, SetTransactionIsolationTest, ShutdownDatabaseTest, ShutDownDBWhenNSShutsDownTest, ShutdownMaster, ShutdownSlave, SimplePerfTest, SimpleTest, SpillHashTest, SQLAuthorizationPropTest, SqlExceptionTest, SQLSessionContextTest, SSLTest, StalePlansTest, StandardTests, StartupExistingDBTest, StartupNewDBTest, StatementEventsTest, StatementJdbc20Test, StatementJdbc30Test, StatementPlanCacheTest, StatementPoolingTest, StatementTest, StoreBaseTest, StreamingColumnTest, StreamsTest, StreamTest, StreamTruncationTest, StressMultiTest, SubqueryFlatteningTest, SuicideOfStreamingTest, SURBaseTest, SynonymTest, SysDiagVTIMappingTest, SysinfoAPITest, SysinfoCPCheckTest, SysinfoTest, SystemCatalogTest, TableFunctionTest, TestDbMetaData, TestJDBC40Exception, TimeHandlingTest, TimestampArithTest, TriggerTest, TruncateTableTest, UnaryArithmeticParameterTest, UngroupedAggregatesNegativeTest, UniqueConstraintMultiThreadedTest, UniqueConstraintSetNullTest, UnsupportedVetter, UpdatableResultSetTest, UpdatableResultSetTest, UpdateCursorTest, UpdateStatisticsTest, UpdateXXXTest, UpgradeChange, UpgradeTrajectoryTest, URCoveringIndexTest, UTF8ReaderTest, ViewsTest, VTITest, XA40Test, XAJNDITest, XATest, XATransactionTest, XMLBindingTest, XMLMissingClassesTest, XMLTypeAndOpsTest, XplainStatisticsTest

public abstract class BaseJDBCTestCase
extends BaseTestCase

Base class for JDBC JUnit tests. A method for getting a default connection is provided, along with methods for telling if a specific JDBC client is used.


Field Summary
private  java.sql.Connection conn
          Maintain a single connection to the default database, opened at the first call to getConnection.
private  java.util.List statements
          Maintain a list of statement objects that were returned by utility methods and close them at teardown.
 
Fields inherited from class org.apache.derbyTesting.junit.BaseTestCase
DEFAULT_DB_DIR, DERBY_LOG, ERRORSTACKTRACEFILE
 
Constructor Summary
BaseJDBCTestCase(java.lang.String name)
          Create a test case with the given name.
 
Method Summary
private  void addStatement(java.sql.Statement s)
          Add a statement into the list we will close at tearDown.
 void assertCallError(java.lang.String expectedSE, java.lang.String callSQL)
          Executes the Callable statement that is expected to fail and verifies that it throws the expected SQL exception.
 void assertCheckTable(java.lang.String table)
          Check the table using SYSCS_UTIL.SYSCS_CHECK_TABLE.
 void assertCompileError(java.lang.String sqlState, java.lang.String sql)
          Assert that the SQL statement does not compile and throws a SQLException with the expected state.
static void assertEquals(java.sql.Blob b1, java.sql.Blob b2)
          Assert equality between two Blob objects.
static void assertEquals(java.sql.Clob c1, java.sql.Clob c2)
          Assert equality between two Clob objects.
static void assertEquals(java.lang.String msg, java.sql.Time t1, java.sql.Time t2)
          Assert equality between two java.sql.Time objects.
static void assertEquivalentDataType(int expectedType, int type)
          Compares two JDBC types to see if they are equivalent.
private  void assertEscapedTableRowCount(java.lang.String escapedTableName, int rowCount)
          Assert that the number of rows in a table is an expected value.
static void assertGetIntError(int position, java.lang.String sqlState, java.sql.ResultSet rs)
          Perform getInt(position) with expected error
static void assertNextError(java.lang.String sqlState, java.sql.ResultSet rs)
          Perform a fetch on the ResultSet with an expected failure
static void assertPreparedStatementError(java.lang.String sqlState, java.sql.PreparedStatement ps)
          Assert that the query fails (either in execution, or retrieval of results--doesn't matter) and throws a SQLException with the expected state and error code Parameters must have been already bound, if any.
static void assertSQLExceptionEquals(java.sql.SQLException se1, java.sql.SQLException se2)
          Assert that the two (2) passed-in SQLException's are equals and not just '=='.
static void assertSQLState(java.lang.String expected, java.sql.SQLException exception)
          Assert that SQLState is as expected.
static void assertSQLState(java.lang.String message, java.lang.String expected, java.sql.SQLException exception)
          Assert that SQLState is as expected.
static void assertStatementError(java.lang.String[] sqlStates, java.sql.Statement st, java.lang.String query)
          Assert that the query fails (either in compilation, execution, or retrieval of results--doesn't matter) and throws a SQLException with the expected states.
static void assertStatementError(java.lang.String sqlState, int errorCode, java.sql.Statement st, java.lang.String query)
          Assert that the query fails (either in compilation, execution, or retrieval of results--doesn't matter) and throws a SQLException with the expected state and error code Assumption is that 'query' does *not* have parameters that need binding and thus can be executed using a simple Statement.execute() call.
static void assertStatementError(java.lang.String sqlState, java.sql.PreparedStatement pSt)
          Assert that execution of the received PreparedStatement object fails (either in execution or when retrieving results) and throws a SQLException with the expected state.
static void assertStatementError(java.lang.String sqlState, java.sql.Statement st, java.lang.String query)
          Assert that the query fails with a single error
protected  void assertTableRowCount(java.lang.String table, int rowCount)
          Assert that the number of rows in a table is an expected value.
static void assertUpdateCount(java.sql.PreparedStatement pSt, int expectedRC)
          Assert that a call to "executeUpdate()" on the received PreparedStatement object returns a row count that matches the received row count.
static void assertUpdateCount(java.sql.Statement st, int expectedRC, java.lang.String sql)
          Take a Statement object and a SQL statement, execute it via the "executeUpdate()" method, and assert that the resultant row count matches the received row count.
protected  void checkAllConsistency(java.sql.Connection conn)
          Check consistency of all tables
static void checkEstimatedRowCount(java.sql.Connection conn, double expectedCount)
          Return estimated row count for runtime statistics.
 void commit()
          Utility method to commit using the connection returned by getConnection.
 java.sql.Statement createStatement()
          Utility method to create a Statement using the connection returned by getConnection.
 java.sql.Statement createStatement(int resultSetType, int resultSetConcurrency)
          Utility method to create a Statement using the connection returned by getConnection.
 java.sql.Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability)
          Utility method to create a Statement using the connection returned by getConnection.
static void dropTable(java.sql.Connection conn, java.lang.String tableName)
          Execute a DROP TABLE command using the passed in tableName as-is.
 void dropTable(java.lang.String tableName)
          Execute a DROP TABLE command using the passed in tableName as-is and the default connection.
private static void fetchAndDiscardAllResults(java.sql.Statement st, boolean haveRS)
          Take the received Statement--on which a query has been executed--and fetch all rows of all result sets (if any) returned from execution.
 java.sql.Connection getConnection()
          Obtain the connection to the default database.
 java.lang.String getDatabaseProperty(java.lang.String propertyName)
          Get the value of a database property using the default connection
 java.sql.SQLException getLastSQLException(java.sql.SQLException sqle)
          Get the last SQLException in chain.
protected  void initializeConnection(java.sql.Connection conn)
          Allow a sub-class to initialize a connection to provide consistent connection state for its tests.
 java.sql.Connection openConnection(java.lang.String databaseName)
          Open a connection to the specified database.
 java.sql.Connection openDefaultConnection()
          Open a connection to the default database.
 java.sql.Connection openDefaultConnection(java.lang.String user, java.lang.String password)
          Open a connection to the current default database using the specified user name and password.
 java.sql.Connection openUserConnection(java.lang.String user)
          Open a connection to the current default database using the specified user name.
 java.sql.CallableStatement prepareCall(java.lang.String sql)
          Utility method to create a CallableStatement using the connection returned by getConnection.
 java.sql.CallableStatement prepareCall(java.lang.String sql, int resultSetType, int resultSetConcurrency)
          Utility method to create a CallableStatement using the connection returned by getConnection.
 java.sql.CallableStatement prepareCall(java.lang.String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability)
          Utility method to create a CallableStatement using the connection returned by getConnection.
 java.sql.PreparedStatement prepareStatement(java.lang.String sql)
          Utility method to create a PreparedStatement using the connection returned by getConnection.
 java.sql.PreparedStatement prepareStatement(java.lang.String sql, int autoGeneratedKeys)
          Utility method to create a PreparedStatement using the connection returned by getConnection and a flag that signals the driver whether the auto-generated keys produced by this Statement object should be made available for retrieval.
 java.sql.PreparedStatement prepareStatement(java.lang.String sql, int[] columnIndexes)
          Utility method to create a PreparedStatement using the connection returned by getConnection and an array of column indexes that indicates which auto-generated keys produced by this Statement object should be made available for retrieval.
 java.sql.PreparedStatement prepareStatement(java.lang.String sql, int resultSetType, int resultSetConcurrency)
          Utility method to create a PreparedStatement using the connection returned by getConnection with result set type and concurrency.
 java.sql.PreparedStatement prepareStatement(java.lang.String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability)
          Utility method to create a PreparedStatement using the connection returned by getConnection with result set type and concurrency.
 java.sql.PreparedStatement prepareStatement(java.lang.String sql, java.lang.String[] columnNames)
          Utility method to create a PreparedStatement using the connection returned by getConnection and an array of column names that indicates which auto-generated keys produced by this Statement object should be made available for retrieval.
 void rollback()
          Utility method to rollback using the connection returned by getConnection.
 int runScript(java.io.InputStream script, java.lang.String encoding)
          Run a SQL script through ij discarding the output using this object's default connection.
 int runScript(java.lang.String resource, java.lang.String encoding)
          Run a SQL script through ij discarding the output using this object's default connection.
 int runSQLCommands(java.lang.String sqlCommands)
          Run a set of SQL commands from a String discarding the output.
 void setAutoCommit(boolean commit)
          Utility method to set auto commit behaviour.
protected  void tearDown()
          Tear down this fixture, sub-classes should call super.tearDown().
static boolean usingDB2Client()
          Tell if the client is DB2Client.
static boolean usingDerbyNetClient()
          Tell if the client is DerbyNetClient.
static boolean usingEmbedded()
          Tell if the client is embedded.
 
Methods inherited from class org.apache.derbyTesting.junit.BaseTestCase
alarm, assertEquals, assertEquals, assertEquals, assertExecJavaCmdAsExpected, assertSecurityManager, assertThrowableEquals, execJavaCmd, fail, getFailureFolder, getJavaExecutableName, getSystemProperty, getTestConfiguration, getTestResource, openTestResource, println, printStackTrace, readProcessOutput, removeDirectory, removeDirectory, removeSystemProperty, runBare, setSystemProperty, traceit
 
Methods inherited from class junit.framework.TestCase
countTestCases, createResult, getName, run, run, runTest, setName, setUp, toString
 
Methods inherited from class junit.framework.Assert
assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertEquals, assertFalse, assertFalse, assertNotNull, assertNotNull, assertNotSame, assertNotSame, assertNull, assertNull, assertSame, assertSame, assertTrue, assertTrue, fail, fail
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

conn

private java.sql.Connection conn
Maintain a single connection to the default database, opened at the first call to getConnection. Typical setup will just require a single connection.

See Also:
getConnection()

statements

private java.util.List statements
Maintain a list of statement objects that were returned by utility methods and close them at teardown.

Constructor Detail

BaseJDBCTestCase

public BaseJDBCTestCase(java.lang.String name)
Create a test case with the given name.

Parameters:
name - of the test case.
Method Detail

getConnection

public java.sql.Connection getConnection()
                                  throws java.sql.SQLException
Obtain the connection to the default database. This class maintains a single connection returned by this class, it is opened on the first call to this method. Subsequent calls will return the same connection object unless it has been closed. In that case a new connection object will be returned.

The tearDown method will close the connection if it is open.
The connection will be initialized by calling initializeConnection. A sub-class may provide an implementation of initializeConnection to ensure its connections are in a consistent state that is different to the default.

Throws:
java.sql.SQLException
See Also:
openDefaultConnection()

initializeConnection

protected void initializeConnection(java.sql.Connection conn)
                             throws java.sql.SQLException
Allow a sub-class to initialize a connection to provide consistent connection state for its tests. Called once for each time these method calls open a connection: Default action is to not modify the connection's state from the initialization provided by the data source.

Parameters:
conn - Connection to be intialized
Throws:
java.sql.SQLException - Error setting the initial state.

createStatement

public java.sql.Statement createStatement()
                                   throws java.sql.SQLException
Utility method to create a Statement using the connection returned by getConnection. The returned statement object will be closed automatically at tearDown() but may be closed earlier by the test if required.

Returns:
Statement object from getConnection.createStatement()
Throws:
java.sql.SQLException

addStatement

private void addStatement(java.sql.Statement s)
Add a statement into the list we will close at tearDown.


createStatement

public java.sql.Statement createStatement(int resultSetType,
                                          int resultSetConcurrency)
                                   throws java.sql.SQLException
Utility method to create a Statement using the connection returned by getConnection. The returned statement object will be closed automatically at tearDown() but may be closed earlier by the test if required.

Returns:
Statement object from getConnection.createStatement(resultSetType, resultSetConcurrency)
Throws:
java.sql.SQLException

createStatement

public java.sql.Statement createStatement(int resultSetType,
                                          int resultSetConcurrency,
                                          int resultSetHoldability)
                                   throws java.sql.SQLException
Utility method to create a Statement using the connection returned by getConnection.

Returns:
Statement object from getConnection.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability)
Throws:
java.sql.SQLException

prepareStatement

public java.sql.PreparedStatement prepareStatement(java.lang.String sql)
                                            throws java.sql.SQLException
Utility method to create a PreparedStatement using the connection returned by getConnection. The returned statement object will be closed automatically at tearDown() but may be closed earlier by the test if required.

Returns:
Statement object from getConnection.prepareStatement(sql)
Throws:
java.sql.SQLException

prepareStatement

public java.sql.PreparedStatement prepareStatement(java.lang.String sql,
                                                   int resultSetType,
                                                   int resultSetConcurrency)
                                            throws java.sql.SQLException
Utility method to create a PreparedStatement using the connection returned by getConnection with result set type and concurrency. The returned statement object will be closed automatically at tearDown() but may be closed earlier by the test if required.

Returns:
Statement object from getConnection.prepareStatement(sql)
Throws:
java.sql.SQLException

prepareStatement

public java.sql.PreparedStatement prepareStatement(java.lang.String sql,
                                                   int resultSetType,
                                                   int resultSetConcurrency,
                                                   int resultSetHoldability)
                                            throws java.sql.SQLException
Utility method to create a PreparedStatement using the connection returned by getConnection with result set type and concurrency. The returned statement object will be closed automatically at tearDown() but may be closed earlier by the test if required.

Returns:
Statement object from getConnection.prepareStatement(sql)
Throws:
java.sql.SQLException

prepareStatement

public java.sql.PreparedStatement prepareStatement(java.lang.String sql,
                                                   int autoGeneratedKeys)
                                            throws java.sql.SQLException
Utility method to create a PreparedStatement using the connection returned by getConnection and a flag that signals the driver whether the auto-generated keys produced by this Statement object should be made available for retrieval. The returned statement object will be closed automatically at tearDown() but may be closed earlier by the test if required.

Returns:
Statement object from prepareStatement(sql, autoGeneratedKeys)
Throws:
java.sql.SQLException

prepareStatement

public java.sql.PreparedStatement prepareStatement(java.lang.String sql,
                                                   int[] columnIndexes)
                                            throws java.sql.SQLException
Utility method to create a PreparedStatement using the connection returned by getConnection and an array of column indexes that indicates which auto-generated keys produced by this Statement object should be made available for retrieval. The returned statement object will be closed automatically at tearDown() but may be closed earlier by the test if required.

Returns:
Statement object from: prepareStatement(sql, columnIndexes)
Throws:
java.sql.SQLException

prepareStatement

public java.sql.PreparedStatement prepareStatement(java.lang.String sql,
                                                   java.lang.String[] columnNames)
                                            throws java.sql.SQLException
Utility method to create a PreparedStatement using the connection returned by getConnection and an array of column names that indicates which auto-generated keys produced by this Statement object should be made available for retrieval. The returned statement object will be closed automatically at tearDown() but may be closed earlier by the test if required.

Returns:
Statement object from: prepareStatement(sql, columnNames)
Throws:
java.sql.SQLException

prepareCall

public java.sql.CallableStatement prepareCall(java.lang.String sql)
                                       throws java.sql.SQLException
Utility method to create a CallableStatement using the connection returned by getConnection. The returned statement object will be closed automatically at tearDown() but may be closed earlier by the test if required.

Returns:
Statement object from getConnection().prepareCall(sql)
Throws:
java.sql.SQLException

prepareCall

public java.sql.CallableStatement prepareCall(java.lang.String sql,
                                              int resultSetType,
                                              int resultSetConcurrency)
                                       throws java.sql.SQLException
Utility method to create a CallableStatement using the connection returned by getConnection. The returned statement object will be closed automatically at tearDown() but may be closed earlier by the test if required.

Returns:
Statement object from getConnection().prepareCall(sql, resultSetType, resultSetConcurrency)
Throws:
java.sql.SQLException

prepareCall

public java.sql.CallableStatement prepareCall(java.lang.String sql,
                                              int resultSetType,
                                              int resultSetConcurrency,
                                              int resultSetHoldability)
                                       throws java.sql.SQLException
Utility method to create a CallableStatement using the connection returned by getConnection. The returned statement object will be closed automatically at tearDown() but may be closed earlier by the test if required.

Returns:
Statement object from getConnection().prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability)
Throws:
java.sql.SQLException

setAutoCommit

public void setAutoCommit(boolean commit)
                   throws java.sql.SQLException
Utility method to set auto commit behaviour.

Parameters:
commit - false if autoCommit should be disabled.
Throws:
java.sql.SQLException

commit

public void commit()
            throws java.sql.SQLException
Utility method to commit using the connection returned by getConnection.

Throws:
java.sql.SQLException

rollback

public void rollback()
              throws java.sql.SQLException
Utility method to rollback using the connection returned by getConnection.

Throws:
java.sql.SQLException

tearDown

protected void tearDown()
                 throws java.lang.Exception
Tear down this fixture, sub-classes should call super.tearDown(). This cleanups & closes the connection if it is open and any statement objects returned through the utility methods.

Overrides:
tearDown in class junit.framework.TestCase
Throws:
java.lang.Exception

openDefaultConnection

public java.sql.Connection openDefaultConnection()
                                          throws java.sql.SQLException
Open a connection to the default database. If the database does not exist, it will be created. A default username and password will be used for the connection. The connection will be initialized by calling initializeConnection. A sub-class may provide an implementation of initializeConnection to ensure its connections are in a consistent state that is different to the default.

Returns:
connection to default database.
Throws:
java.sql.SQLException
See Also:
TestConfiguration.openDefaultConnection(), initializeConnection(Connection)

openDefaultConnection

public java.sql.Connection openDefaultConnection(java.lang.String user,
                                                 java.lang.String password)
                                          throws java.sql.SQLException
Open a connection to the current default database using the specified user name and password.
This connection is not automaticaly closed on tearDown, the test fixture must ensure the connection is closed. The connection will be initialized by calling initializeConnection. A sub-class may provide an implementation of initializeConnection to ensure its connections are in a consistent state that is different to the default.

Throws:
java.sql.SQLException
See Also:
initializeConnection(Connection)

openUserConnection

public java.sql.Connection openUserConnection(java.lang.String user)
                                       throws java.sql.SQLException
Open a connection to the current default database using the specified user name. The password is a function of the user name and the password token setup by the builtin authentication decorators.
If the fixture is not wrapped in one of the decorators that setup BUILTIN authentication then the password is a function of the user name and the empty string as the password token. This mode is not recommended.
This connection is not automaticaly closed on tearDown, the test fixture must ensure the connection is closed.
The connection will be initialized by calling initializeConnection. A sub-class may provide an implementation of initializeConnection to ensure its connections are in a consistent state that is different to the default.

Throws:
java.sql.SQLException
See Also:
DatabasePropertyTestSetup.builtinAuthentication(Test, String[], String), TestConfiguration.sqlAuthorizationDecorator(Test, String[], String), initializeConnection(Connection)

openConnection

public java.sql.Connection openConnection(java.lang.String databaseName)
                                   throws java.sql.SQLException
Open a connection to the specified database. If the database does not exist, it will be created. A default username and password will be used for the connection. Requires that the test has been decorated with a additionalDatabaseDecorator with the matching name.
The connection will be initialized by calling initializeConnection. A sub-class may provide an implementation of initializeConnection to ensure its connections are in a consistent state that is different to the default.

Returns:
connection to default database.
Throws:
java.sql.SQLException
See Also:
TestConfiguration.additionalDatabaseDecorator(Test, String), initializeConnection(Connection)

runScript

public int runScript(java.io.InputStream script,
                     java.lang.String encoding)
              throws java.io.UnsupportedEncodingException,
                     java.sql.SQLException
Run a SQL script through ij discarding the output using this object's default connection. Intended for setup scripts.

Throws:
java.io.UnsupportedEncodingException
java.sql.SQLException

runScript

public int runScript(java.lang.String resource,
                     java.lang.String encoding)
              throws java.io.UnsupportedEncodingException,
                     java.sql.SQLException,
                     java.security.PrivilegedActionException,
                     java.io.IOException
Run a SQL script through ij discarding the output using this object's default connection. Intended for setup scripts.

Returns:
Number of errors executing the script
Throws:
java.io.UnsupportedEncodingException
java.security.PrivilegedActionException
java.sql.SQLException
java.io.IOException

runSQLCommands

public int runSQLCommands(java.lang.String sqlCommands)
                   throws java.io.UnsupportedEncodingException,
                          java.sql.SQLException
Run a set of SQL commands from a String discarding the output. Commands are separated by a semi-colon. Connection used is this objects default connection.

Parameters:
sqlCommands -
Returns:
Number of errors executing the script.
Throws:
java.io.UnsupportedEncodingException
java.sql.SQLException

usingEmbedded

public static boolean usingEmbedded()
Tell if the client is embedded.

Returns:
true if using the embedded client false otherwise.

usingDerbyNetClient

public static boolean usingDerbyNetClient()
Tell if the client is DerbyNetClient.

Returns:
true if using the DerbyNetClient client false otherwise.

usingDB2Client

public static boolean usingDB2Client()
Tell if the client is DB2Client.

Returns:
true if using the DB2 client driver, false otherwise.

getDatabaseProperty

public java.lang.String getDatabaseProperty(java.lang.String propertyName)
                                     throws java.sql.SQLException
Get the value of a database property using the default connection

Parameters:
propertyName - Property key
Returns:
null if the property is not set at the database level, otherwise the value of the property.
Throws:
java.sql.SQLException

assertEquals

public static void assertEquals(java.sql.Blob b1,
                                java.sql.Blob b2)
                         throws java.io.IOException,
                                java.sql.SQLException
Assert equality between two Blob objects. If both input references are null, they are considered equal. The same is true if both blobs have null-streams.

Parameters:
b1 - first Blob.
b2 - second Blob.
Throws:
junit.framework.AssertionFailedError - if blobs are not equal.
java.io.IOException - if reading or closing a stream fails
java.sql.SQLException - if obtaining a stream fails

assertEquals

public static void assertEquals(java.sql.Clob c1,
                                java.sql.Clob c2)
                         throws java.io.IOException,
                                java.sql.SQLException
Assert equality between two Clob objects. If both input references are null, they are considered equal. The same is true if both clobs have null-streams.

Parameters:
c1 - first Clob.
c2 - second Clob.
Throws:
junit.framework.AssertionFailedError - if clobs are not equal.
java.io.IOException - if reading or closing a stream fails
java.sql.SQLException - if obtaining a stream fails

assertEquals

public static void assertEquals(java.lang.String msg,
                                java.sql.Time t1,
                                java.sql.Time t2)
Assert equality between two java.sql.Time objects. If both input references are null, they are considered equal.

Parameters:
msg - String with message to supply with AssertionFailedError
t1 - first java.sql.Time object.
t2 - second java.sql.Time object.
Throws:
junit.framework.AssertionFailedError - if Time objects are not equal.

assertSQLState

public static void assertSQLState(java.lang.String message,
                                  java.lang.String expected,
                                  java.sql.SQLException exception)
Assert that SQLState is as expected. If the SQLState for the top-level exception doesn't match, look for nested exceptions and, if there are any, see if they have the desired SQLState.

Parameters:
message - message to print on failure.
expected - the expected SQLState.
exception - the exception to check the SQLState of.

assertSQLState

public static void assertSQLState(java.lang.String expected,
                                  java.sql.SQLException exception)
Assert that SQLState is as expected.

Parameters:
expected - the expected SQLState.
exception - the exception to check the SQLState of.

assertCompileError

public void assertCompileError(java.lang.String sqlState,
                               java.lang.String sql)
Assert that the SQL statement does not compile and throws a SQLException with the expected state.

Parameters:
sqlState - expected sql state.
sql - the SQL to compile.

assertCheckTable

public void assertCheckTable(java.lang.String table)
                      throws java.sql.SQLException
Check the table using SYSCS_UTIL.SYSCS_CHECK_TABLE.

Throws:
java.sql.SQLException

assertTableRowCount

protected void assertTableRowCount(java.lang.String table,
                                   int rowCount)
                            throws java.sql.SQLException
Assert that the number of rows in a table is an expected value. Query uses a SELECT COUNT(*) FROM "table".

Parameters:
table - Name of table in current schema, will be quoted
rowCount - Number of rows expected in the table
Throws:
java.sql.SQLException - Error accessing the database.

assertEscapedTableRowCount

private void assertEscapedTableRowCount(java.lang.String escapedTableName,
                                        int rowCount)
                                 throws java.sql.SQLException
Assert that the number of rows in a table is an expected value. Query uses a SELECT COUNT(*) FROM table.

Parameters:
escapedTableName - Escaped name of table, will be used as-is.
rowCount - Number of rows expected in the table
Throws:
java.sql.SQLException - Error accessing the database.

dropTable

public final void dropTable(java.lang.String tableName)
                     throws java.sql.SQLException
Execute a DROP TABLE command using the passed in tableName as-is and the default connection. If the DROP TABLE fails because the table does not exist then the exception is ignored.

Parameters:
tableName - Table to be dropped.
Throws:
java.sql.SQLException

dropTable

public static void dropTable(java.sql.Connection conn,
                             java.lang.String tableName)
                      throws java.sql.SQLException
Execute a DROP TABLE command using the passed in tableName as-is. If the DROP TABLE fails because the table does not exist then the exception is ignored.

Parameters:
conn - Connection to execute the DROP TABLE
tableName - Table to be dropped.
Throws:
java.sql.SQLException

assertStatementError

public static void assertStatementError(java.lang.String[] sqlStates,
                                        java.sql.Statement st,
                                        java.lang.String query)
Assert that the query fails (either in compilation, execution, or retrieval of results--doesn't matter) and throws a SQLException with the expected states. Assumption is that 'query' does *not* have parameters that need binding and thus can be executed using a simple Statement.execute() call. If there are extra chained SQLExceptions that are not in sqlStates, this method will not fail.

Parameters:
sqlStates - expected sql states.
st - Statement object on which to execute.
query - the query to compile and execute.

assertStatementError

public static void assertStatementError(java.lang.String sqlState,
                                        java.sql.Statement st,
                                        java.lang.String query)
Assert that the query fails with a single error

Parameters:
sqlState - Expected SQLState of exception
st -
query -
See Also:
assertStatementError(String[], Statement, String)

assertStatementError

public static void assertStatementError(java.lang.String sqlState,
                                        int errorCode,
                                        java.sql.Statement st,
                                        java.lang.String query)
Assert that the query fails (either in compilation, execution, or retrieval of results--doesn't matter) and throws a SQLException with the expected state and error code Assumption is that 'query' does *not* have parameters that need binding and thus can be executed using a simple Statement.execute() call.

Parameters:
sqlState - expected sql state.
errorCode - expected error code.
st - Statement object on which to execute.
query - the query to compile and execute.

assertPreparedStatementError

public static void assertPreparedStatementError(java.lang.String sqlState,
                                                java.sql.PreparedStatement ps)
Assert that the query fails (either in execution, or retrieval of results--doesn't matter) and throws a SQLException with the expected state and error code Parameters must have been already bound, if any.

Parameters:
sqlState - expected sql state.
ps - PreparedStatement query object to execute.

assertStatementError

public static void assertStatementError(java.lang.String sqlState,
                                        java.sql.PreparedStatement pSt)
Assert that execution of the received PreparedStatement object fails (either in execution or when retrieving results) and throws a SQLException with the expected state. Assumption is that "pSt" is either a PreparedStatement or a CallableStatement that has already been prepared and whose parameters (if any) have already been bound. Thus the only thing left to do is to call "execute()" and look for the expected SQLException.

Parameters:
sqlState - expected sql state.
pSt - A PreparedStatement or CallableStatement on which to call "execute()".

assertCallError

public void assertCallError(java.lang.String expectedSE,
                            java.lang.String callSQL)
                     throws java.sql.SQLException
Executes the Callable statement that is expected to fail and verifies that it throws the expected SQL exception.

Parameters:
expectedSE - The expected SQL exception
callSQL - The SQL to execute
Throws:
java.sql.SQLException

assertNextError

public static void assertNextError(java.lang.String sqlState,
                                   java.sql.ResultSet rs)
Perform a fetch on the ResultSet with an expected failure

Parameters:
sqlState - Expected SQLState
rs - ResultSet upon which next() will be called

assertGetIntError

public static void assertGetIntError(int position,
                                     java.lang.String sqlState,
                                     java.sql.ResultSet rs)
Perform getInt(position) with expected error

Parameters:
position - position argument to pass to getInt
sqlState - sqlState of expected error
rs - ResultSet upon which to call getInt(position)

assertUpdateCount

public static void assertUpdateCount(java.sql.Statement st,
                                     int expectedRC,
                                     java.lang.String sql)
                              throws java.sql.SQLException
Take a Statement object and a SQL statement, execute it via the "executeUpdate()" method, and assert that the resultant row count matches the received row count. Assumption is that 'sql' does *not* have parameters that need binding and that it can be executed using a simple Statement.executeUpdate() call.

Parameters:
st - Statement object on which to execute.
expectedRC - Expected row count.
sql - SQL to execute.
Throws:
java.sql.SQLException

assertUpdateCount

public static void assertUpdateCount(java.sql.PreparedStatement pSt,
                                     int expectedRC)
                              throws java.sql.SQLException
Assert that a call to "executeUpdate()" on the received PreparedStatement object returns a row count that matches the received row count. Assumption is that "pSt" is either a PreparedStatement or a CallableStatement that has already been prepared and whose parameters (if any) have already been bound. Also assumes the statement's SQL is such that a call executeUpdate() is allowed. Thus the only thing left to do is to call the "executeUpdate" method.

Parameters:
pSt - The PreparedStatement on which to execute.
expectedRC - The expected row count.
Throws:
java.sql.SQLException

getLastSQLException

public java.sql.SQLException getLastSQLException(java.sql.SQLException sqle)
Get the last SQLException in chain.

Parameters:
sqle - SQLException
Returns:
the last exception in the chain.

fetchAndDiscardAllResults

private static void fetchAndDiscardAllResults(java.sql.Statement st,
                                              boolean haveRS)
                                       throws java.sql.SQLException
Take the received Statement--on which a query has been executed--and fetch all rows of all result sets (if any) returned from execution. The rows themselves are discarded. This is useful when we expect there to be an error when processing the results but do not know (or care) at what point the error occurs.

Parameters:
st - An already-executed statement from which we get the result set to process (if there is one).
haveRS - Whether or not the the statement's first result is a result set (as opposed to an update count).
Throws:
java.sql.SQLException

assertSQLExceptionEquals

public static void assertSQLExceptionEquals(java.sql.SQLException se1,
                                            java.sql.SQLException se2)
Assert that the two (2) passed-in SQLException's are equals and not just '=='.

Parameters:
se1 - first SQLException to compare
se2 - second SQLException to compare

assertEquivalentDataType

public static void assertEquivalentDataType(int expectedType,
                                            int type)
Compares two JDBC types to see if they are equivalent. DECIMAL and NUMERIC and DOUBLE and FLOAT are considered equivalent.

Parameters:
expectedType - Expected jdbctype from java.sql.Types
type - Actual type from metadata

checkEstimatedRowCount

public static void checkEstimatedRowCount(java.sql.Connection conn,
                                          double expectedCount)
                                   throws java.sql.SQLException
Return estimated row count for runtime statistics. Requires caller first turned on RuntimeStatistics, executed a query and closed the ResultSet. For client calls we just return as we can't find out this information.

Parameters:
conn -
expectedCount -
Throws:
java.sql.SQLException

checkAllConsistency

protected void checkAllConsistency(java.sql.Connection conn)
                            throws java.sql.SQLException
Check consistency of all tables

Parameters:
conn -
Throws:
java.sql.SQLException

Built on Wed 2009-11-25 18:43:31-0800, from revision 884373

Apache Derby V10.6 Internals - Copyright © 2004,2008 The Apache Software Foundation. All Rights Reserved.