2 * Copyright 2005-2010 the original author or authors.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org.wamblee.support.persistence;
18 import java.sql.Connection;
19 import java.sql.PreparedStatement;
20 import java.sql.ResultSet;
21 import java.sql.SQLException;
22 import java.util.ArrayList;
23 import java.util.List;
24 import java.util.logging.Logger;
26 import javax.sql.DataSource;
28 import junit.framework.TestCase;
30 import org.dbunit.DataSourceDatabaseTester;
31 import org.dbunit.IDatabaseTester;
32 import org.dbunit.database.DatabaseConnection;
33 import org.dbunit.database.DatabaseSequenceFilter;
34 import org.dbunit.database.IDatabaseConnection;
35 import org.dbunit.dataset.FilteredDataSet;
36 import org.dbunit.dataset.IDataSet;
37 import org.dbunit.dataset.filter.ITableFilter;
38 import org.dbunit.dataset.filter.ITableFilterSimple;
39 import org.dbunit.operation.DatabaseOperation;
42 * Database utilities is a simple support class for common tasks in working with
45 public class DatabaseUtils {
47 public static interface TableSet {
48 boolean contains(String aTableName);
51 public static interface JdbcUnitOfWork<T> {
52 T execute(Connection aConnection) throws Exception;
55 public static interface TableSetOperation {
56 void execute(String aTable) throws Exception;
59 private static final Logger LOG = Logger.getLogger(DatabaseUtils.class
65 private static final String SCHEMA_PATTERN = "%";
66 private DataSource dataSource;
67 private ITableFilterSimple tables;
69 public DatabaseUtils(DataSource aDataSource, ITableFilterSimple aTables) {
70 dataSource = aDataSource;
74 public IDatabaseTester createDbTester() throws Exception {
75 return createDbTester(getTableNames(tables));
78 public IDatabaseTester createDbTester(String[] aTables) throws Exception {
79 IDatabaseTester dbtester = new DataSourceDatabaseTester(dataSource);
80 dbtester.setDataSet(dbtester.getConnection().createDataSet(aTables));
84 public void cleanDatabase() throws Exception {
85 cleanDatabase(tables);
88 public void executeOnTables(ITableFilterSimple aTables,
89 final TableSetOperation aOperation) throws Exception {
90 final String[] tables = getTableNames(aTables);
91 executeInTransaction(new JdbcUnitOfWork<Void>() {
92 public Void execute(Connection aConnection) throws Exception {
93 for (int i = tables.length-1; i >= 0; i--) {
94 aOperation.execute(tables[i]);
99 for (String table : tables) {
104 public void cleanDatabase(ITableFilterSimple aSelection) throws Exception {
106 final String[] tables = getTableNames(aSelection);
107 executeInTransaction(new JdbcUnitOfWork<Void>() {
109 public Void execute(Connection aConnection) throws Exception {
110 IDatabaseConnection connection = new DatabaseConnection(
112 ITableFilter filter = new DatabaseSequenceFilter(connection,
114 IDataSet dataset = new FilteredDataSet(filter, connection
115 .createDataSet(tables));
116 DatabaseOperation.DELETE_ALL.execute(connection, dataset);
123 public <T> T executeInTransaction(JdbcUnitOfWork<T> aCallback)
125 Connection connection = dataSource.getConnection();
127 T value = aCallback.execute(connection);
135 public String[] getTableNames() throws Exception {
136 return getTableNames(tables);
140 * @throws SQLException
142 public String[] getTableNames(ITableFilterSimple aSelection)
145 List<String> result = new ArrayList<String>();
146 LOG.fine("Getting database table names to clean (schema: '" +
147 SCHEMA_PATTERN + "'");
149 Connection connection = dataSource.getConnection();
151 ResultSet tables = connection.getMetaData().getTables(null,
152 SCHEMA_PATTERN, "%", new String[] { "TABLE" });
153 while (tables.next()) {
154 String table = tables.getString("TABLE_NAME");
155 if (aSelection.accept(table)) {
159 return (String[]) result.toArray(new String[0]);
165 public void emptyTables() throws Exception {
166 executeOnTables(tables, new TableSetOperation() {
167 public void execute(String aTable) throws Exception {
175 * @throws SQLException
177 public void emptyTables(final ITableFilterSimple aSelection)
179 executeOnTables(aSelection, new TableSetOperation() {
180 public void execute(String aTable) throws Exception {
188 * @throws SQLException
190 public void emptyTable(String aTable) throws Exception {
191 executeSql("delete from " + aTable);
194 public void dropTables() throws Exception {
195 executeOnTables(tables, new TableSetOperation() {
197 public void execute(String aTable) throws Exception {
203 public void dropTables(ITableFilterSimple aTables) throws Exception {
204 executeOnTables(aTables, new TableSetOperation() {
206 public void execute(String aTable) throws Exception {
214 * @throws SQLException
216 public void dropTable(final String aTable) throws Exception {
217 executeInTransaction(new JdbcUnitOfWork<Void>() {
218 public Void execute(Connection aConnection) throws Exception {
219 executeUpdate(aConnection, "drop table " + aTable);
227 * Executes an SQL statement within a transaction.
231 * @return Return code of the corresponding JDBC call.
233 public int executeSql(final String aSql) throws Exception {
234 return executeSql(aSql, new Object[0]);
238 * Executes an SQL statement within a transaction. See
239 * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
240 * supported argument types.
245 * Argument of the sql statement.
246 * @return Return code of the corresponding JDBC call.
248 public int executeSql(final String aSql, final Object aArg)
250 return executeSql(aSql, new Object[] { aArg });
254 * Executes an sql statement. See
255 * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
256 * supported argument types.
259 * SQL query to execute.
262 * @return Number of rows updated.
264 public int executeSql(final String aSql, final Object[] aArgs)
266 return executeInTransaction(new JdbcUnitOfWork<Integer>() {
267 public Integer execute(Connection aConnection) throws Exception {
268 PreparedStatement stmt = aConnection.prepareStatement(aSql);
269 setPreparedParams(aArgs, stmt);
270 return stmt.executeUpdate();
276 * Executes an SQL query.
280 * @return Result set.
282 public ResultSet executeQuery(Connection aConnection, String aSql) {
283 return executeQuery(aConnection, aSql, new Object[0]);
287 * Executes a query with a single argument. See
288 * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
289 * supported argument types.
295 * @return Result set.
297 public ResultSet executeQuery(Connection aConnection, String aSql,
299 return executeQuery(aConnection, aSql, new Object[] { aArg });
303 * Executes a query. See
304 * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
305 * supported argument types.
310 * Arguments to the query.
311 * @return Result set.
313 public ResultSet executeQuery(Connection aConnection, final String aSql,
314 final Object[] aArgs) {
316 PreparedStatement statement = aConnection.prepareStatement(aSql);
317 setPreparedParams(aArgs, statement);
319 return statement.executeQuery();
320 } catch (SQLException e) {
321 throw new RuntimeException(e);
325 public int executeUpdate(Connection aConnection, final String aSql,
326 final Object... aArgs) {
328 PreparedStatement statement = aConnection.prepareStatement(aSql);
329 setPreparedParams(aArgs, statement);
331 return statement.executeUpdate();
332 } catch (SQLException e) {
333 throw new RuntimeException(e);
338 * Sets the values of a prepared statement. See
339 * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
340 * supported argument types.
343 * Arguments to the prepared statement.
346 * @throws SQLException
348 private void setPreparedParams(final Object[] aArgs,
349 PreparedStatement aStatement) throws SQLException {
350 for (int i = 1; i <= aArgs.length; i++) {
351 setPreparedParam(i, aStatement, aArgs[i - 1]);
356 * Sets a prepared statement parameter.
359 * Index of the parameter.
361 * Prepared statement.
363 * Value Must be of type Integer, Long, or String.
364 * @throws SQLException
366 private void setPreparedParam(int aIndex, PreparedStatement aStatement,
367 Object aObject) throws SQLException {
368 if (aObject instanceof Integer) {
369 aStatement.setInt(aIndex, ((Integer) aObject).intValue());
370 } else if (aObject instanceof Long) {
371 aStatement.setLong(aIndex, ((Long) aObject).longValue());
372 } else if (aObject instanceof String) {
373 aStatement.setString(aIndex, (String) aObject);
375 TestCase.fail("Unsupported object type for prepared statement: " +
376 aObject.getClass() + " value: " + aObject + " statement: " +
383 * @throws SQLException
385 public int getTableSize(final String aTable) throws Exception {
386 return executeInTransaction(new JdbcUnitOfWork<Integer>() {
387 public Integer execute(Connection aConnection) throws Exception {
388 ResultSet resultSet = executeQuery(aConnection,
389 "select count(*) from " + aTable);
391 return resultSet.getInt(1);
397 public int countResultSet(ResultSet aResultSet) throws SQLException {
400 while (aResultSet.next()) {