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.dataset;
23  
24  import java.util.ArrayList;
25  import java.util.List;
26  import java.util.StringTokenizer;
27  
28  import org.dbunit.Assertion;
29  import org.dbunit.dataset.datatype.DataType;
30  import org.dbunit.dataset.datatype.TypeCastException;
31  import org.dbunit.util.QualifiedTableName;
32  import org.slf4j.Logger;
33  import org.slf4j.LoggerFactory;
34  
35  /**
36   * This class contains various methods for manipulating datasets.
37   *
38   * @author Manuel Laflamme
39   * @version $Revision$
40   * @since Feb 19, 2002
41   */
42  public class DataSetUtils
43  {
44  
45      /**
46       * Logger for this class
47       */
48      private static final Logger logger = LoggerFactory.getLogger(DataSetUtils.class);
49  
50      private DataSetUtils()
51      {
52      }
53  
54      /**
55       * Asserts that the two specified dataset are equals. This method ignore
56       * the tables order.
57       *
58       * @deprecated Use Assertion.assertEquals
59       */
60      public static void assertEquals(IDataSet expectedDataSet,
61              IDataSet actualDataSet) throws Exception
62      {
63          logger.debug("assertEquals(expectedDataSet={}, actualDataSet={}) - start", expectedDataSet, actualDataSet);
64  
65          Assertion.assertEquals(expectedDataSet, actualDataSet);
66      }
67  
68  
69      /**
70       * Asserts that the two specified tables are equals. This method ignore the
71       * table names, the columns order, the columns data type and the primary
72       * keys.
73       *
74       * @deprecated Use Assertion.assertEquals
75       */
76      public static void assertEquals(ITable expectedTable, ITable actualTable)
77              throws Exception
78      {
79          logger.debug("assertEquals(expectedTable={}, actualTable={}) - start", expectedTable, actualTable);
80  
81          Assertion.assertEquals(expectedTable, actualTable);
82      }
83  
84      /**
85       * Returns the specified name qualified with the specified prefix. The name
86       * is not modified if the prefix is <code>null</code> or if the name is
87       * already qualified.
88       * <p>
89       * Example: <br>
90       * <code>getQualifiedName(null, "NAME")</code> returns
91       * <code>"NAME"</code>. <code>getQualifiedName("PREFIX", "NAME")</code>
92       * returns <code>"PREFIX.NAME"</code> and
93       * <code>getQualifiedName("PREFIX2", "PREFIX1.NAME")</code>
94       * returns <code>"PREFIX1.NAME"</code>.
95       *
96       * @param prefix the prefix that qualifies the name and is prepended if the name is not qualified yet
97       * @param name the name The name to be qualified if it is not qualified already
98       * @return the qualified name
99       * @deprecated since 2.3.0. Prefer usage of {@link QualifiedTableName#getQualifiedName()} creating a new {@link QualifiedTableName} object
100      */
101     public static String getQualifiedName(String prefix, String name)
102     {
103         logger.debug("getQualifiedName(prefix={}, name={}) - start", prefix, name);
104 
105         return new QualifiedTableName(name, prefix, (String)null).getQualifiedName();
106     }
107 
108     /**
109      * @param prefix the prefix that qualifies the name and is prepended if the name is not qualified yet
110      * @param name the name The name to be qualified if it is not qualified already
111      * @param escapePattern The escape pattern to be applied on the prefix and the name. Can be null.
112      * @return The qualified name
113      * @deprecated since 2.3.0. Prefer usage of {@link QualifiedTableName#getQualifiedName()} creating a new {@link QualifiedTableName} object
114      */
115     public static String getQualifiedName(String prefix, String name,
116             String escapePattern)
117     {
118         if(logger.isDebugEnabled())
119             logger.debug("getQualifiedName(prefix={}, name={}, escapePattern={}) - start", 
120                     new String[] {prefix, name, escapePattern});
121         
122         return new QualifiedTableName(name, prefix, escapePattern).getQualifiedName();
123     }
124 
125     /**
126      * @param name
127      * @param escapePattern
128      * @return The escaped name if the escape pattern is not null
129      * @deprecated since 2.3.0. Prefer usage of {@link QualifiedTableName#getQualifiedName()} creating a new {@link QualifiedTableName} object
130      */
131     public static String getEscapedName(String name, String escapePattern)
132     {
133         logger.debug("getEscapedName(name={}, escapePattern={}) - start", name, escapePattern);
134         return new QualifiedTableName(name, null, escapePattern).getQualifiedName();
135     }
136 
137     /**
138      * Returns the specified value as a string to be use in an SQL Statement.
139      * For example the string <code>myValue</code> is returned as
140      * <code>'myValue'</code>.
141      *
142      * @param value the value
143      * @param dataType the value data type
144      * @return the SQL string value
145      */
146     public static String getSqlValueString(Object value, DataType dataType)
147             throws TypeCastException
148     {
149         logger.debug("getSqlValueString(value={}, dataType={}) - start", value, dataType);
150 
151         if (value == null || value == ITable.NO_VALUE)
152         {
153             return "NULL";
154         }
155 
156         String stringValue = DataType.asString(value);
157         if (dataType == DataType.DATE)
158         {
159             return "{d '" + stringValue + "'}";
160         }
161 
162         if (dataType == DataType.TIME)
163         {
164             return "{t '" + stringValue + "'}";
165         }
166 
167         if (dataType == DataType.TIMESTAMP)
168         {
169             return "{ts '" + stringValue + "'}";
170         }
171 
172         if (!dataType.isNumber())
173         {
174             // no single quotes
175             if (stringValue.indexOf("'") < 0)
176             {
177                 return stringValue = "'" + stringValue + "'";
178             }
179 
180             // escaping single quotes
181             StringBuffer buffer = new StringBuffer(stringValue.length() * 2);
182             StringTokenizer tokenizer = new StringTokenizer(stringValue, "'", true);
183 
184             buffer.append("'");
185             while (tokenizer.hasMoreTokens())
186             {
187                 String token = tokenizer.nextToken();
188                 buffer.append(token);
189                 if (token.equals("'"))
190                 {
191                     buffer.append("'");
192                 }
193             }
194             buffer.append("'");
195             return buffer.toString();
196 
197         }
198 
199         return stringValue;
200     }
201 
202     /**
203      * Search and returns the specified column from the specified column array.
204      *
205      * @param columnName the name of the column to search.
206      * @param columns the array of columns from which the column must be searched.
207      * @return the column or <code>null</code> if the column is not found
208      * @deprecated since 2.3.0 - prefer usage of {@link Columns#getColumn(String, Column[])}
209      */
210     public static Column getColumn(String columnName, Column[] columns)
211     {
212         logger.debug("getColumn(columnName={}, columns={}) - start", columnName, columns);
213         return Columns.getColumn(columnName, columns);
214     }
215 
216     /**
217      * Search and returns the specified tables from the specified dataSet.
218      *
219      * @param names the names of the tables to search.
220      * @param dataSet the dataset from which the tables must be searched.
221      * @return the tables or an empty array if no tables are found.
222      */
223     public static ITable[] getTables(String[] names, IDataSet dataSet)
224             throws DataSetException
225     {
226         logger.debug("getTables(names={}, dataSet={}) - start", names, dataSet);
227 
228         ITable[] tables = new ITable[names.length];
229         for (int i = 0; i < names.length; i++)
230         {
231             String name = names[i];
232             tables[i] = dataSet.getTable(name);
233         }
234 
235         return tables;
236     }
237 
238     /**
239      * Returns the tables from the specified dataset.
240      */
241     public static ITable[] getTables(IDataSet dataSet) throws DataSetException
242     {
243         logger.debug("getTables(dataSet={}) - start", dataSet);
244 
245         return getTables(dataSet.iterator());
246     }
247 
248     /**
249      * Returns the tables from the specified iterator.
250      */
251     public static ITable[] getTables(ITableIterator iterator) throws DataSetException
252     {
253         logger.debug("getTables(iterator={}) - start", iterator);
254 
255         List tableList = new ArrayList();
256         while(iterator.next())
257         {
258             tableList.add(iterator.getTable());
259         }
260         return (ITable[])tableList.toArray(new ITable[0]);
261     }
262 
263     /**
264      * Returns the table names from the specified dataset in reverse order.
265      */
266     public static String[] getReverseTableNames(IDataSet dataSet)
267             throws DataSetException
268     {
269         logger.debug("getReverseTableNames(dataSet={}) - start", dataSet);
270         return reverseStringArray(dataSet.getTableNames());
271     }
272 
273     /**
274      * reverses a String array.
275      * @param array
276      * @return String[] - reversed array.
277      */
278     public static String[] reverseStringArray(String[] array)
279 	{
280 		logger.debug("reverseStringArray(array={}) - start", array);
281         String[] newArray = new String[array.length];
282         for (int i = 0; i < array.length; i++)
283         {
284             newArray[array.length - 1 - i] = array[i];
285         }
286         return newArray;
287 	}
288 
289 }