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 ResultSet tables = dataSource.getConnection().getMetaData().getTables(
150 null, SCHEMA_PATTERN, "%", new String[] { "TABLE" });
151 while (tables.next()) {
152 String table = tables.getString("TABLE_NAME");
153 if (aSelection.accept(table)) {
157 return (String[]) result.toArray(new String[0]);
160 public void emptyTables() throws Exception {
161 executeOnTables(tables, new TableSetOperation() {
162 public void execute(String aTable) throws Exception {
170 * @throws SQLException
172 public void emptyTables(final ITableFilterSimple aSelection)
174 executeOnTables(aSelection, new TableSetOperation() {
175 public void execute(String aTable) throws Exception {
183 * @throws SQLException
185 public void emptyTable(String aTable) throws Exception {
186 executeSql("delete from " + aTable);
189 public void dropTables() throws Exception {
190 executeOnTables(tables, new TableSetOperation() {
192 public void execute(String aTable) throws Exception {
198 public void dropTables(ITableFilterSimple aTables) throws Exception {
199 executeOnTables(aTables, new TableSetOperation() {
201 public void execute(String aTable) throws Exception {
209 * @throws SQLException
211 public void dropTable(final String aTable) throws Exception {
212 executeInTransaction(new JdbcUnitOfWork<Void>() {
213 public Void execute(Connection aConnection) throws Exception {
214 executeUpdate(aConnection, "drop table " + aTable);
222 * Executes an SQL statement within a transaction.
226 * @return Return code of the corresponding JDBC call.
228 public int executeSql(final String aSql) throws Exception {
229 return executeSql(aSql, new Object[0]);
233 * Executes an SQL statement within a transaction. See
234 * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
235 * supported argument types.
240 * Argument of the sql statement.
241 * @return Return code of the corresponding JDBC call.
243 public int executeSql(final String aSql, final Object aArg)
245 return executeSql(aSql, new Object[] { aArg });
249 * Executes an sql statement. See
250 * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
251 * supported argument types.
254 * SQL query to execute.
257 * @return Number of rows updated.
259 public int executeSql(final String aSql, final Object[] aArgs)
261 return executeInTransaction(new JdbcUnitOfWork<Integer>() {
262 public Integer execute(Connection aConnection) throws Exception {
263 PreparedStatement stmt = aConnection.prepareStatement(aSql);
264 setPreparedParams(aArgs, stmt);
265 return stmt.executeUpdate();
271 * Executes an SQL query.
275 * @return Result set.
277 public ResultSet executeQuery(Connection aConnection, String aSql) {
278 return executeQuery(aConnection, aSql, new Object[0]);
282 * Executes a query with a single argument. See
283 * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
284 * supported argument types.
290 * @return Result set.
292 public ResultSet executeQuery(Connection aConnection, String aSql,
294 return executeQuery(aConnection, aSql, new Object[] { aArg });
298 * Executes a query. See
299 * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
300 * supported argument types.
305 * Arguments to the query.
306 * @return Result set.
308 public ResultSet executeQuery(Connection aConnection, final String aSql,
309 final Object[] aArgs) {
311 PreparedStatement statement = aConnection.prepareStatement(aSql);
312 setPreparedParams(aArgs, statement);
314 return statement.executeQuery();
315 } catch (SQLException e) {
316 throw new RuntimeException(e);
320 public int executeUpdate(Connection aConnection, final String aSql,
321 final Object... aArgs) {
323 PreparedStatement statement = aConnection.prepareStatement(aSql);
324 setPreparedParams(aArgs, statement);
326 return statement.executeUpdate();
327 } catch (SQLException e) {
328 throw new RuntimeException(e);
333 * Sets the values of a prepared statement. See
334 * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
335 * supported argument types.
338 * Arguments to the prepared statement.
341 * @throws SQLException
343 private void setPreparedParams(final Object[] aArgs,
344 PreparedStatement aStatement) throws SQLException {
345 for (int i = 1; i <= aArgs.length; i++) {
346 setPreparedParam(i, aStatement, aArgs[i - 1]);
351 * Sets a prepared statement parameter.
354 * Index of the parameter.
356 * Prepared statement.
358 * Value Must be of type Integer, Long, or String.
359 * @throws SQLException
361 private void setPreparedParam(int aIndex, PreparedStatement aStatement,
362 Object aObject) throws SQLException {
363 if (aObject instanceof Integer) {
364 aStatement.setInt(aIndex, ((Integer) aObject).intValue());
365 } else if (aObject instanceof Long) {
366 aStatement.setLong(aIndex, ((Integer) aObject).longValue());
367 } else if (aObject instanceof String) {
368 aStatement.setString(aIndex, (String) aObject);
370 TestCase.fail("Unsupported object type for prepared statement: " +
371 aObject.getClass() + " value: " + aObject + " statement: " +
378 * @throws SQLException
380 public int getTableSize(final String aTable) throws Exception {
381 return executeInTransaction(new JdbcUnitOfWork<Integer>() {
382 public Integer execute(Connection aConnection) throws Exception {
383 ResultSet resultSet = executeQuery(aConnection,
384 "select count(*) from " + aTable);
386 return resultSet.getInt(1);
392 public int countResultSet(ResultSet aResultSet) throws SQLException {
395 while (aResultSet.next()) {