View Javadoc
1   /*
2    *
3    * The DbUnit Database Testing Framework
4    * Copyright (C)2002-2004, DbUnit.org
5    *
6    * This library is free software; you can redistribute it and/or
7    * modify it under the terms of the GNU Lesser General Public
8    * License as published by the Free Software Foundation; either
9    * version 2.1 of the License, or (at your option) any later version.
10   *
11   * This library is distributed in the hope that it will be useful,
12   * but WITHOUT ANY WARRANTY; without even the implied warranty of
13   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14   * Lesser General Public License for more details.
15   *
16   * You should have received a copy of the GNU Lesser General Public
17   * License along with this library; if not, write to the Free Software
18   * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19   *
20   */
21  
22  package org.dbunit.database;
23  
24  import java.sql.PreparedStatement;
25  import java.sql.ResultSet;
26  import java.sql.SQLException;
27  import java.sql.Statement;
28  
29  import org.dbunit.DatabaseUnitRuntimeException;
30  import org.dbunit.database.statement.IStatementFactory;
31  import org.dbunit.dataset.DataSetException;
32  import org.dbunit.dataset.FilteredDataSet;
33  import org.dbunit.dataset.IDataSet;
34  import org.dbunit.dataset.ITable;
35  import org.dbunit.util.QualifiedTableName;
36  import org.dbunit.util.SQLHelper;
37  import org.slf4j.Logger;
38  import org.slf4j.LoggerFactory;
39  
40  /**
41   * @author Manuel Laflamme
42   * @version $Revision$
43   * @since Mar 6, 2002
44   */
45  public abstract class AbstractDatabaseConnection implements IDatabaseConnection
46  {
47  
48      /**
49       * Logger for this class
50       */
51      private static final Logger logger =
52              LoggerFactory.getLogger(AbstractDatabaseConnection.class);
53  
54      private IDataSet _dataSet = null;
55      private final DatabaseConfig _databaseConfig;
56  
57      public AbstractDatabaseConnection()
58      {
59          _databaseConfig = new DatabaseConfig();
60      }
61  
62      ////////////////////////////////////////////////////////////////////////////
63      // IDatabaseConnection interface
64  
65      public IDataSet createDataSet() throws SQLException
66      {
67          logger.debug("createDataSet() - start");
68  
69          if (_dataSet == null)
70          {
71              _dataSet = new DatabaseDataSet(this);
72          }
73  
74          return _dataSet;
75      }
76  
77      public IDataSet createDataSet(String[] tableNames)
78              throws DataSetException, SQLException
79      {
80          logger.debug("createDataSet(tableNames={}) - start", tableNames);
81  
82          return new FilteredDataSet(tableNames, createDataSet());
83      }
84  
85      public ITable createQueryTable(String resultName, String sql)
86              throws DataSetException, SQLException
87      {
88          logger.debug("createQueryTable(resultName={}, sql={}) - start",
89                  resultName, sql);
90  
91          IResultSetTableFactory tableFactory = getResultSetTableFactory();
92          IResultSetTable rsTable =
93                  tableFactory.createTable(resultName, sql, this);
94          if (logger.isDebugEnabled())
95          {
96              String rowCount = null;
97              try
98              {
99                  int rowCountInt = rsTable.getRowCount();
100                 rowCount = String.valueOf(rowCountInt);
101             } catch (Exception e)
102             {
103                 rowCount = "Unable to determine row count due to Exception: "
104                         + e.getLocalizedMessage();
105             }
106             logger.debug("createQueryTable: rowCount={}", rowCount);
107         }
108         return rsTable;
109     }
110 
111     public ITable createTable(String resultName,
112             PreparedStatement preparedStatement)
113             throws DataSetException, SQLException
114     {
115         logger.debug(
116                 "createQueryTable(resultName={}, preparedStatement={}) - start",
117                 resultName, preparedStatement);
118 
119         IResultSetTableFactory tableFactory = getResultSetTableFactory();
120         IResultSetTable rsTable =
121                 tableFactory.createTable(resultName, preparedStatement, this);
122         return rsTable;
123     }
124 
125     public ITable createTable(String tableName)
126             throws DataSetException, SQLException
127     {
128         logger.debug("createTable(tableName={}) - start", tableName);
129 
130         if (tableName == null)
131         {
132             throw new NullPointerException(
133                     "The parameter 'tableName' must not be null");
134         }
135 
136         String escapePattern = (String) getConfig()
137                 .getProperty(DatabaseConfig.PROPERTY_ESCAPE_PATTERN);
138 
139         // qualify with schema if configured
140         QualifiedTableName qualifiedTableName = new QualifiedTableName(
141                 tableName, this.getSchema(), escapePattern);
142         String qualifiedName = qualifiedTableName.getQualifiedName();
143         String sql = "select * from " + qualifiedName;
144         return this.createQueryTable(tableName, sql);
145     }
146 
147     public int getRowCount(String tableName) throws SQLException
148     {
149         logger.debug("getRowCount(tableName={}) - start", tableName);
150 
151         return getRowCount(tableName, null);
152     }
153 
154     public int getRowCount(String tableName, String whereClause)
155             throws SQLException
156     {
157         logger.debug("getRowCount(tableName={}, whereClause={}) - start",
158                 tableName, whereClause);
159 
160         StringBuffer sqlBuffer = new StringBuffer(128);
161         sqlBuffer.append("select count(*) from ");
162 
163         // add table name and schema (schema only if available)
164         QualifiedTableName qualifiedTableName =
165                 new QualifiedTableName(tableName, this.getSchema());
166         String qualifiedName = qualifiedTableName.getQualifiedName();
167         sqlBuffer.append(qualifiedName);
168         if (whereClause != null)
169         {
170             sqlBuffer.append(" ");
171             sqlBuffer.append(whereClause);
172         }
173 
174         Statement statement = getConnection().createStatement();
175         ResultSet resultSet = null;
176         try
177         {
178             resultSet = statement.executeQuery(sqlBuffer.toString());
179             if (resultSet.next())
180             {
181                 return resultSet.getInt(1);
182             } else
183             {
184                 throw new DatabaseUnitRuntimeException(
185                         "Select count did not return any results for table '"
186                                 + tableName + "'. Statement: "
187                                 + sqlBuffer.toString());
188             }
189         } finally
190         {
191             SQLHelper.close(resultSet, statement);
192         }
193     }
194 
195     public DatabaseConfig getConfig()
196     {
197         return _databaseConfig;
198     }
199 
200     /**
201      * @deprecated Use {@link #getConfig}
202      */
203     @Deprecated
204     public IStatementFactory getStatementFactory()
205     {
206         return (IStatementFactory) _databaseConfig
207                 .getProperty(DatabaseConfig.PROPERTY_STATEMENT_FACTORY);
208     }
209 
210     private IResultSetTableFactory getResultSetTableFactory()
211     {
212         return (IResultSetTableFactory) _databaseConfig
213                 .getProperty(DatabaseConfig.PROPERTY_RESULTSET_TABLE_FACTORY);
214 
215     }
216 
217     @Override
218     public String toString()
219     {
220         StringBuffer sb = new StringBuffer();
221         sb.append("_databaseConfig=").append(_databaseConfig);
222         sb.append(", _dataSet=").append(_dataSet);
223         return sb.toString();
224     }
225 }