import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
+import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sql.DataSource;
private DataSource dataSource;
private ITableFilterSimple tables;
+ private IDatabaseTester dbtester;
+ /**
+ * List of connections that were created for dbtesters.
+ * This list will be closed in the {@link #stop()} method.
+ */
+ private List<IDatabaseConnection> connections;
+
+ /**
+ * Constructs the database utils.
+ * Before use, {@link #start()} must be called.
+ * @param aDataSource Datasource.
+ * @param aTables Tables to work with.
+ */
public DatabaseUtils(DataSource aDataSource, ITableFilterSimple aTables) {
dataSource = aDataSource;
tables = aTables;
+ dbtester = new DataSourceDatabaseTester(dataSource);
+ connections = new ArrayList<IDatabaseConnection>();
+ }
+
+ /**
+ * Starts the database utils.
+ */
+ public void start() {
+ // Empty. No operation currently.
+ }
+
+ /**
+ * Stops the database utils, closing any JDBC connections that were created
+ * by this utility. Note that connections obtained from the datasource directly
+ * must still be closed by the user. The involved connections are only those that
+ * are created by this utility.
+ */
+ public void stop() {
+ for (IDatabaseConnection connection: connections) {
+ try {
+ connection.close();
+ } catch (SQLException e) {
+ LOG.log(Level.WARNING, "Could not close connection", e);
+ }
+ }
}
public IDatabaseTester createDbTester() throws Exception {
}
public IDatabaseTester createDbTester(String[] aTables) throws Exception {
- IDatabaseTester dbtester = new DataSourceDatabaseTester(dataSource);
- dbtester.setDataSet(dbtester.getConnection().createDataSet(aTables));
+ IDatabaseConnection connection = dbtester.getConnection();
+ connections.add(connection);
+ dbtester.setDataSet(connection.createDataSet(aTables));
return dbtester;
}
final String[] tables = getTableNames(aTables);
executeInTransaction(new JdbcUnitOfWork<Void>() {
public Void execute(Connection aConnection) throws Exception {
- for (int i = tables.length-1; i >= 0; i--) {
+ for (int i = tables.length - 1; i >= 0; i--) {
aOperation.execute(tables[i]);
}
return null;
public void emptyTable(String aTable) throws Exception {
executeSql("delete from " + aTable);
}
-
- public void dropTables() throws Exception {
+
+ public void dropTables() throws Exception {
dropTables(tables);
}
return dataset.getTableNames();
}
});
- for (int i = sortedTables.length-1; i >= 0; i--) {
+ for (int i = sortedTables.length - 1; i >= 0; i--) {
dropTable(sortedTables[i]);
}
}
-
+
/**
* @return
* @throws SQLException