Author: tfischer
Date: Mon May 20 21:03:07 2013
New Revision: 1484594
URL: http://svn.apache.org/r1484594
Log:
TORQUE-277 make updates possible with verbatim SQL
TORQUE-286 BasePeerImpl.doUpdate(ColumnValues) and
BasePeerImpl.doUpdate(ColumnValues, Connection) did not work
TORQUE-284 Object ColumnValues contains unused constructor arguments table
Added:
db/torque/torque4/trunk/torque-test/src/test/java/org/apache/torque/generated/peer/DoInsertTest.java
db/torque/torque4/trunk/torque-test/src/test/java/org/apache/torque/generated/peer/DoUpdateTest.java
Modified:
db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/sql/Query.java
db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/BasePeerImpl.java
db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/ColumnValues.java
db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/JdbcTypedValue.java
db/torque/torque4/trunk/torque-runtime/src/test/java/org/apache/torque/BaseTestCase.java
db/torque/torque4/trunk/torque-runtime/src/test/java/org/apache/torque/util/BasePeerImplTest.java
db/torque/torque4/trunk/torque-templates/src/main/resources/org/apache/torque/templates/om/templates/peer/impl/base/doUpdate.vm
db/torque/torque4/trunk/torque-templates/src/main/resources/org/apache/torque/templates/om/templates/peer/impl/base/imports.vm
Modified:
db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/sql/Query.java
URL:
http://svn.apache.org/viewvc/db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/sql/Query.java?rev=1484594&r1=1484593&r2=1484594&view=diff
==============================================================================
---
db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/sql/Query.java
(original)
+++
db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/sql/Query.java
Mon May 20 21:03:07 2013
@@ -23,10 +23,14 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
+import java.util.Map;
import org.apache.commons.lang.StringUtils;
+import org.apache.torque.Column;
import org.apache.torque.TorqueException;
import org.apache.torque.criteria.FromElement;
+import org.apache.torque.util.ColumnValues;
+import org.apache.torque.util.JdbcTypedValue;
import org.apache.torque.util.UniqueList;
/**
@@ -90,13 +94,17 @@ public class Query
private final UniqueList<String> selectModifiers = new
UniqueList<String>();
/**
- * The select columns for a select statement, or the columns to update
- * for an update statement.
+ * The select columns for a select statement.
*/
-
private final UniqueList<String> columns = new UniqueList<String>();
/**
+ * The columns to update and the values to update to
+ * for an update statement.
+ */
+ private final ColumnValues updateValues = new ColumnValues();
+
+ /**
* The tables to select from (including join operators) for
* a select clause, or the tables to update or delete for update
* or delete statements.
@@ -185,6 +193,17 @@ public class Query
}
/**
+ * Retrieve the values to update to in case of an update statement.
+ *
+ * @return A modifiable ColumnValues object containing the current
+ * update values.
+ */
+ public ColumnValues getUpdateValues()
+ {
+ return updateValues;
+ }
+
+ /**
* Retrieve the from buffer in order to specify which tables are
* involved in this query.
*
@@ -276,7 +295,7 @@ public class Query
*
* @param having A String.
*/
- public void setHaving(String having)
+ public void setHaving(final String having)
{
this.having = having;
}
@@ -298,7 +317,7 @@ public class Query
*
* @param limit A String.
*/
- public void setLimit(String limit)
+ public void setLimit(final String limit)
{
this.limit = limit;
}
@@ -320,7 +339,7 @@ public class Query
*
* @param preLimit A String with the preLimit.
*/
- public void setPreLimit(String preLimit)
+ public void setPreLimit(final String preLimit)
{
this.preLimit = preLimit;
}
@@ -342,7 +361,7 @@ public class Query
*
* @param postLimit A String with the postLimit.
*/
- public void setPostLimit(String postLimit)
+ public void setPostLimit(final String postLimit)
{
this.postLimit = postLimit;
}
@@ -364,7 +383,7 @@ public class Query
*
* @param offset A String.
*/
- public void setOffset(String offset)
+ public void setOffset(final String offset)
{
this.offset = offset;
}
@@ -386,7 +405,7 @@ public class Query
*
* @param rowcount A String.
*/
- public void setRowcount(String rowcount)
+ public void setRowcount(final String rowcount)
{
this.rowcount = rowcount;
}
@@ -399,7 +418,7 @@ public class Query
*
* @return this object.
*/
- public void setForUpdate(String forUpdate)
+ public void setForUpdate(final String forUpdate)
{
this.forUpdate = forUpdate;
}
@@ -443,7 +462,7 @@ public class Query
*
* @throws NullPointerException if <code>type</code> is null.
*/
- public void setType(Type type)
+ public void setType(final Type type)
{
if (type == null)
{
@@ -467,7 +486,7 @@ public class Query
*
* @param fetchSize the fetch size, or null for not set.
*/
- public void setFetchSize(Integer fetchSize)
+ public void setFetchSize(final Integer fetchSize)
{
this.fetchSize = fetchSize;
}
@@ -477,6 +496,7 @@ public class Query
*
* @return A String with the query statement.
*/
+ @Override
public String toString()
{
return toStringBuilder(new StringBuilder()).toString();
@@ -489,7 +509,7 @@ public class Query
*
* @return the modified passed in string builder.
*/
- public StringBuilder toStringBuilder(StringBuilder stringBuilder)
+ public StringBuilder toStringBuilder(final StringBuilder stringBuilder)
{
if (preLimit != null)
{
@@ -541,11 +561,26 @@ public class Query
if (Type.UPDATE == type)
{
- stringBuilder.append(SET)
- .append(StringUtils.join(columns, "=?, "));
- if (!columns.isEmpty())
+ stringBuilder.append(SET);
+ first = true;
+ for (Map.Entry<Column, JdbcTypedValue> entry
+ : updateValues.entrySet())
{
- stringBuilder.append("=?");
+ if (!first)
+ {
+ stringBuilder.append(",");
+ }
+ stringBuilder.append(entry.getKey().getSqlExpression());
+ if (entry.getValue().getVerbatimSql() == null)
+ {
+ stringBuilder.append("=?");
+ }
+ else
+ {
+ stringBuilder.append("=")
+ .append(entry.getValue().getVerbatimSql());
+ }
+ first = false;
}
}
Modified:
db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/BasePeerImpl.java
URL:
http://svn.apache.org/viewvc/db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/BasePeerImpl.java?rev=1484594&r1=1484593&r2=1484594&view=diff
==============================================================================
---
db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/BasePeerImpl.java
(original)
+++
db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/BasePeerImpl.java
Mon May 20 21:03:07 2013
@@ -432,15 +432,11 @@ public class BasePeerImpl<T> implements
}
List<String> columnNames = new ArrayList<String>();
- List<JdbcTypedValue> replacementObjects
- = new ArrayList<JdbcTypedValue>();
for (Map.Entry<Column, JdbcTypedValue> columnValue
: insertValues.entrySet())
{
Column column = columnValue.getKey();
columnNames.add(column.getColumnName());
- JdbcTypedValue value = columnValue.getValue();
- replacementObjects.add(value);
}
String fullTableName = SqlBuilder.getFullTableName(
@@ -451,13 +447,27 @@ public class BasePeerImpl<T> implements
.append("(")
.append(StringUtils.join(columnNames, ","))
.append(") VALUES (");
- for (int i = 0; i < columnNames.size(); ++i)
+
+ boolean first = true;
+ List<JdbcTypedValue> replacementObjects
+ = new ArrayList<JdbcTypedValue>();
+ for (Map.Entry<Column, JdbcTypedValue> columnValue
+ : insertValues.entrySet())
{
- if (i != 0)
+ if (!first)
{
query.append(",");
}
- query.append("?");
+ if (columnValue.getValue().getVerbatimSql() == null)
+ {
+ query.append("?");
+ replacementObjects.add(columnValue.getValue());
+ }
+ else
+ {
+ query.append(columnValue.getValue().getVerbatimSql());
+ }
+ first = false;
}
query.append(")");
@@ -1228,11 +1238,11 @@ public class BasePeerImpl<T> implements
ColumnMap pk = getTableMap().getPrimaryKey();
Criteria selectCriteria = null;
- if (pk != null && updateValues.containsKey(pk.getSqlExpression()))
+ if (pk != null && updateValues.containsKey(pk))
{
selectCriteria = new Criteria();
selectCriteria.where(pk,
- updateValues.remove(pk.getSqlExpression()));
+ updateValues.remove(pk).getValue());
}
else
{
@@ -1311,23 +1321,25 @@ public class BasePeerImpl<T> implements
criteria.getDbName());
query.getFromClause().add(new FromElement(fullTableName));
- List<JdbcTypedValue> replacementObjects
- = new ArrayList<JdbcTypedValue>();
- for (Map.Entry<Column, JdbcTypedValue> updateValue
- : updateValues.entrySet())
- {
- Column column = updateValue.getKey();
- query.getSelectClause().add(column.getColumnName());
- replacementObjects.add(updateValue.getValue());
- }
+ query.getUpdateValues().putAll(updateValues);
PreparedStatement preparedStatement = null;
try
{
preparedStatement = connection.prepareStatement(query.toString());
int position = 1;
- for (JdbcTypedValue replacementObject : replacementObjects)
+ List<JdbcTypedValue> replacementObjects
+ = new ArrayList<JdbcTypedValue>();
+ for (Map.Entry<Column, JdbcTypedValue> updateValue
+ : updateValues.entrySet())
{
+ JdbcTypedValue replacementObject = updateValue.getValue();
+ if (replacementObject.getVerbatimSql() != null)
+ {
+ // replacementObject is no real value but contains
+ // a sql snippet which was (hopefully) processed earlier.
+ continue;
+ }
Object value = replacementObject.getValue();
if (value != null)
{
@@ -1339,6 +1351,7 @@ public class BasePeerImpl<T> implements
position,
replacementObject.getJdbcType());
}
+ replacementObjects.add(replacementObject);
position++;
}
List<Object> replacements = setPreparedStatementReplacements(
Modified:
db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/ColumnValues.java
URL:
http://svn.apache.org/viewvc/db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/ColumnValues.java?rev=1484594&r1=1484593&r2=1484594&view=diff
==============================================================================
---
db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/ColumnValues.java
(original)
+++
db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/ColumnValues.java
Mon May 20 21:03:07 2013
@@ -20,22 +20,23 @@ package org.apache.torque.util;
*/
import java.util.Collection;
-import java.util.HashMap;
+import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.apache.torque.Column;
-import org.apache.torque.map.TableMap;
/**
* A class containing values for database columns.
+ * The insertion order of the entries is preserved.
*
* @version $Id$
*/
public class ColumnValues implements Map<Column, JdbcTypedValue>
{
/** The column values, keyed by the column names. */
- private Map<Column, JdbcTypedValue> columnValues;
+ private final Map<Column, JdbcTypedValue> columnValues
+ = new LinkedHashMap<Column, JdbcTypedValue>();
/**
* The name of the database handle to use for connection opening if needed,
@@ -50,7 +51,6 @@ public class ColumnValues implements Map
*/
public ColumnValues()
{
- this.columnValues = new HashMap<Column, JdbcTypedValue>();
}
/**
@@ -62,7 +62,7 @@ public class ColumnValues implements Map
*
* @throws NullPointerException if table is null.
*/
- public ColumnValues(TableMap table, String dbName)
+ public ColumnValues(final String dbName)
{
this();
this.dbName = dbName;
@@ -76,15 +76,11 @@ public class ColumnValues implements Map
* @throws NullPointerException if table is null.
*/
public ColumnValues(
- Map<Column, JdbcTypedValue> columnValues)
+ final Map<Column, JdbcTypedValue> columnValues)
{
- if (columnValues == null)
+ if (columnValues != null)
{
- this.columnValues = new HashMap<Column, JdbcTypedValue>();
- }
- else
- {
- this.columnValues = columnValues;
+ this.columnValues.putAll(columnValues);
}
}
@@ -99,9 +95,8 @@ public class ColumnValues implements Map
* @throws NullPointerException if table is null.
*/
public ColumnValues(
- Map<Column, JdbcTypedValue> columnValues,
- TableMap table,
- String dbName)
+ final Map<Column, JdbcTypedValue> columnValues,
+ final String dbName)
{
this(columnValues);
this.dbName = dbName;
@@ -129,32 +124,32 @@ public class ColumnValues implements Map
return columnValues.isEmpty();
}
- public boolean containsKey(Object key)
+ public boolean containsKey(final Object key)
{
return columnValues.containsKey(key);
}
- public boolean containsValue(Object value)
+ public boolean containsValue(final Object value)
{
return columnValues.containsValue(value);
}
- public JdbcTypedValue get(Object key)
+ public JdbcTypedValue get(final Object key)
{
return columnValues.get(key);
}
- public JdbcTypedValue put(Column key, JdbcTypedValue value)
+ public JdbcTypedValue put(final Column key, final JdbcTypedValue value)
{
return columnValues.put(key, value);
}
- public JdbcTypedValue remove(Object key)
+ public JdbcTypedValue remove(final Object key)
{
return columnValues.remove(key);
}
- public void putAll(Map<? extends Column, ? extends JdbcTypedValue> t)
+ public void putAll(final Map<? extends Column, ? extends JdbcTypedValue> t)
{
columnValues.putAll(t);
}
Modified:
db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/JdbcTypedValue.java
URL:
http://svn.apache.org/viewvc/db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/JdbcTypedValue.java?rev=1484594&r1=1484593&r2=1484594&view=diff
==============================================================================
---
db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/JdbcTypedValue.java
(original)
+++
db/torque/torque4/trunk/torque-runtime/src/main/java/org/apache/torque/util/JdbcTypedValue.java
Mon May 20 21:03:07 2013
@@ -19,6 +19,7 @@ package org.apache.torque.util;
* under the License.
*/
+import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
@@ -35,19 +36,37 @@ public class JdbcTypedValue
/** The value; may be null. */
private Object value;
+ /** A verbatim SQL to use instead of the value. */
+ private String verbatimSql;
+
/**
- * Constructor.
+ * Constructs a JdbcTypedValue with a value and a type.
*
* @param jdbcType The JDBC type as in <code>java.sql.Types</code>.
* @param value The value; may be null.
*/
- public JdbcTypedValue(Object value, int jdbcType)
+ public JdbcTypedValue(final Object value, final int jdbcType)
{
this.jdbcType = jdbcType;
this.value = value;
}
/**
+ * Constructs a JdbcTypedValue with a verbatim SQL.
+ *
+ * @param verbatimSql The verbatim sql to use instead of the value.
+ */
+ public JdbcTypedValue(final String verbatimSql)
+ {
+ if (StringUtils.isBlank(verbatimSql))
+ {
+ throw new IllegalArgumentException(
+ "verbatimSql must not be null or blank");
+ }
+ this.verbatimSql = verbatimSql;
+ }
+
+ /**
* Returns the JDBC type as in <code>java.sql.Types</code>.
*
* @return the JDBC type of the value.
@@ -61,9 +80,16 @@ public class JdbcTypedValue
* Sets the JDBC type as in <code>java.sql.Types</code>.
*
* @param jdbcType the JDBC type of the value.
+ *
+ * @throws IllegalStateException if verbatimSql is set.
*/
- public void setJdbcType(int jdbcType)
+ public void setJdbcType(final int jdbcType)
{
+ if (verbatimSql != null)
+ {
+ throw new IllegalStateException(
+ "jdbcType may not be set if verbatimSql is set");
+ }
this.jdbcType = jdbcType;
}
@@ -78,12 +104,29 @@ public class JdbcTypedValue
}
/**
+ * Returns the verbatimSql to use instead of the value.
+ *
+ * @return value the verbatimSql, or null if not set.
+ */
+ public String getVerbatimSql()
+ {
+ return verbatimSql;
+ }
+
+ /**
* Sets the value.
*
* @param value the value, may be null.
+ *
+ * @throws IllegalStateException if verbatimSql is set.
*/
- public void setValue(Object value)
+ public void setValue(final Object value)
{
+ if (verbatimSql != null)
+ {
+ throw new IllegalStateException(
+ "value may not be set if verbatimSql is set");
+ }
this.value = value;
}
@@ -92,12 +135,13 @@ public class JdbcTypedValue
{
HashCodeBuilder hashCodeBuilder = new HashCodeBuilder()
.append(jdbcType)
- .append(value);
+ .append(value)
+ .append(verbatimSql);
return hashCodeBuilder.toHashCode();
}
@Override
- public boolean equals(Object obj)
+ public boolean equals(final Object obj)
{
if (this == obj)
{
@@ -114,14 +158,22 @@ public class JdbcTypedValue
JdbcTypedValue other = (JdbcTypedValue) obj;
EqualsBuilder equalsBuilder = new EqualsBuilder()
.append(jdbcType, other.jdbcType)
- .append(value, other.value);
+ .append(value, other.value)
+ .append(verbatimSql, other.verbatimSql);
return equalsBuilder.isEquals();
}
@Override
public String toString()
{
- return "JdbcTypedValue [jdbcType=" + jdbcType
- + ", value=" + value + "]";
+ if (verbatimSql == null)
+ {
+ return "JdbcTypedValue [jdbcType=" + jdbcType
+ + ", value=" + value + "]";
+ }
+ else
+ {
+ return "JdbcTypedValue [verbatimSql=" + verbatimSql + "]";
+ }
}
}
Modified:
db/torque/torque4/trunk/torque-runtime/src/test/java/org/apache/torque/BaseTestCase.java
URL:
http://svn.apache.org/viewvc/db/torque/torque4/trunk/torque-runtime/src/test/java/org/apache/torque/BaseTestCase.java?rev=1484594&r1=1484593&r2=1484594&view=diff
==============================================================================
---
db/torque/torque4/trunk/torque-runtime/src/test/java/org/apache/torque/BaseTestCase.java
(original)
+++
db/torque/torque4/trunk/torque-runtime/src/test/java/org/apache/torque/BaseTestCase.java
Mon May 20 21:03:07 2013
@@ -21,6 +21,7 @@ package org.apache.torque;
import junit.framework.TestCase;
+import org.apache.torque.adapter.IDMethod;
import org.apache.torque.map.ColumnMap;
import org.apache.torque.map.DatabaseMap;
import org.apache.torque.map.TableMap;
@@ -60,6 +61,12 @@ public abstract class BaseTestCase exten
/** A pre-filled String column map. */
protected ColumnMap stringColumnMap;
+ /** A pre-filled String column map. */
+ protected ColumnMap stringColumnMap2;
+
+ /** A pre-filled String column map. */
+ protected ColumnMap stringColumnMap3;
+
/** A pre-filled Integer column map. */
protected ColumnMap integerColumnMap;
@@ -81,6 +88,7 @@ public abstract class BaseTestCase exten
databaseMysql = Torque.getDatabase("mysql");
databaseOracle = Torque.getDatabase("oracle");
tableMap = databaseMap.addTable("TABLE");
+ tableMap.setPrimaryKeyMethod(IDMethod.SEQUENCE);
{
stringColumnMap = new ColumnMap("COLUMN1", tableMap);
stringColumnMap.setType(new String(""));
@@ -88,21 +96,22 @@ public abstract class BaseTestCase exten
tableMap.addColumn(stringColumnMap);
}
{
- ColumnMap columnMap2 = new ColumnMap("COLUMN2", tableMap);
- columnMap2.setType(new String(""));
- columnMap2.setJavaType("String");
- tableMap.addColumn(columnMap2);
+ stringColumnMap2 = new ColumnMap("COLUMN2", tableMap);
+ stringColumnMap2.setType(new String(""));
+ stringColumnMap2.setJavaType("String");
+ tableMap.addColumn(stringColumnMap2);
}
{
- ColumnMap columnMap3 = new ColumnMap("COLUMN3", tableMap);
- columnMap3.setType(new String(""));
- columnMap3.setJavaType("String");
- tableMap.addColumn(columnMap3);
+ stringColumnMap3 = new ColumnMap("COLUMN3", tableMap);
+ stringColumnMap3.setType(new String(""));
+ stringColumnMap3.setJavaType("String");
+ tableMap.addColumn(stringColumnMap3);
}
{
integerColumnMap = new ColumnMap("COLUMN4", tableMap);
integerColumnMap.setType(new Integer(0));
integerColumnMap.setJavaType("Integer");
+ integerColumnMap.setPk(true);
tableMap.addColumn(integerColumnMap);
}
}
Modified:
db/torque/torque4/trunk/torque-runtime/src/test/java/org/apache/torque/util/BasePeerImplTest.java
URL:
http://svn.apache.org/viewvc/db/torque/torque4/trunk/torque-runtime/src/test/java/org/apache/torque/util/BasePeerImplTest.java?rev=1484594&r1=1484593&r2=1484594&view=diff
==============================================================================
---
db/torque/torque4/trunk/torque-runtime/src/test/java/org/apache/torque/util/BasePeerImplTest.java
(original)
+++
db/torque/torque4/trunk/torque-runtime/src/test/java/org/apache/torque/util/BasePeerImplTest.java
Mon May 20 21:03:07 2013
@@ -25,17 +25,25 @@ import static org.mockito.Mockito.verify
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
+import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Types;
import java.util.List;
import org.apache.torque.BaseTestCase;
import org.apache.torque.Torque;
+import org.apache.torque.TorqueException;
+import org.apache.torque.adapter.IDMethod;
import org.apache.torque.criteria.Criteria;
import org.apache.torque.map.ColumnMap;
import org.apache.torque.map.DatabaseMap;
import org.apache.torque.map.TableMap;
+import org.apache.torque.oid.IdGenerator;
+import org.apache.torque.om.NumberKey;
+import org.apache.torque.om.ObjectKey;
import org.apache.torque.om.mapper.CompositeMapper;
import org.apache.torque.om.mapper.IntegerMapper;
import org.apache.torque.om.mapper.StringMapper;
@@ -49,8 +57,10 @@ import org.mockito.MockitoAnnotations;
*/
public class BasePeerImplTest extends BaseTestCase
{
+ private static final BigDecimal DEFAULT_GENERATED_ID = new BigDecimal(56);
+
/** System under test. */
- private BasePeerImpl<?> basePeerImpl;
+ private BasePeerImpl<List<Object>> basePeerImpl;
/** Mock db connection. */
@Mock
@@ -64,31 +74,57 @@ public class BasePeerImplTest extends Ba
@Mock
private ResultSet resultSet;
+ @Mock
+ private TransactionManager transactionManager;
+
+ private TransactionManager oldTransactionManager;
+
+ @Mock
+ private IdGenerator idGenerator;
+
@Override
public void setUp() throws Exception
{
- basePeerImpl = new BasePeerImpl<Object>();
+ basePeerImpl = new BasePeerImpl<List<Object>>();
super.setUp();
basePeerImpl.setTableMap(tableMap);
basePeerImpl.setDatabaseName("databaseName");
+ oldTransactionManager = Transaction.getTransactionManager();
MockitoAnnotations.initMocks(this);
when(connection.prepareStatement((String) any()))
.thenReturn(preparedStatement);
+ when(connection.createStatement()).thenReturn(preparedStatement);
when(preparedStatement.executeQuery()).thenReturn(resultSet);
+ when(preparedStatement.executeQuery((String)
any())).thenReturn(resultSet);
when(preparedStatement.executeUpdate()).thenReturn(1);
+
when(transactionManager.begin(databaseMap.getName())).thenReturn(connection);
+
when(transactionManager.begin(basePeerImpl.getDatabaseName())).thenReturn(connection);
+ when(transactionManager.begin(null)).thenReturn(connection);
+ when(idGenerator.getIdAsBigDecimal(connection, null))
+ .thenReturn(DEFAULT_GENERATED_ID);
+ when(idGenerator.isPriorToInsert()).thenReturn(true);
+ when(idGenerator.isPostInsert()).thenReturn(false);
+ Transaction.setTransactionManager(transactionManager);
+ }
+
+ @Override
+ public void tearDown()
+ {
+ Transaction.setTransactionManager(oldTransactionManager);
}
/**
- * Check that the fetch size gets set on the prepared statement when
- * set in the criteria.
+ * Check that a doSelect.
*
* @throws Exception if the test fails.
*/
- public void testDoSelectAll() throws Exception
+ public void testDoSelect() throws Exception
{
Criteria criteria = new Criteria();
criteria.addSelectColumn(stringColumnMap);
criteria.addSelectColumn(integerColumnMap);
+ criteria.setOffset(2);
+ criteria.setLimit(1);
// single result "fd", 23 found
when(resultSet.next()).thenReturn(true, false);
when(resultSet.getString(1)).thenReturn("fd");
@@ -99,18 +135,58 @@ public class BasePeerImplTest extends Ba
mapper.addMapper(new IntegerMapper(), 1);
List<List<Object>> result = basePeerImpl.doSelect(
- criteria, mapper, connection);
+ criteria, mapper);
// verify mock (verification order not relevant)
verify(connection).prepareStatement(
- "SELECT TABLE.COLUMN1, TABLE.COLUMN4 FROM TABLE");
+ "SELECT TABLE.COLUMN1, TABLE.COLUMN4 FROM TABLE LIMIT 1 OFFSET
2");
verify(preparedStatement).executeQuery();
verify(preparedStatement).close();
verify(resultSet, times(2)).next();
verify(resultSet).getString(1);
verify(resultSet).getInt(2);
verify(resultSet).close();
- verifyNoMoreInteractions(connection, preparedStatement, resultSet);
+ verify(transactionManager).begin(null);
+ verify(transactionManager).commit(connection);
+ verifyNoMoreInteractions(connection, preparedStatement, resultSet,
transactionManager);
+ // verify result
+ assertEquals(1, result.size()); // one row
+ assertEquals(2, result.get(0).size()); // two columns
+ assertEquals("fd", result.get(0).get(0));
+ assertEquals(23, result.get(0).get(1));
+ }
+
+ /**
+ * Check that a doSelect with a query.
+ *
+ * @throws Exception if the test fails.
+ */
+ public void testDoSelectWithQuery() throws Exception
+ {
+ // single result "fd", 23 found
+ when(resultSet.next()).thenReturn(true, false);
+ when(resultSet.getString(1)).thenReturn("fd");
+ when(resultSet.getInt(2)).thenReturn(23);
+
+ CompositeMapper mapper = new CompositeMapper();
+ mapper.addMapper(new StringMapper(), 0);
+ mapper.addMapper(new IntegerMapper(), 1);
+ basePeerImpl.setRecordMapper(mapper);
+
+ List<List<Object>> result = basePeerImpl.doSelect(
+ "SELECT * from TABLE");
+
+ // verify mock (verification order not relevant)
+ verify(connection).createStatement();
+ verify(preparedStatement).executeQuery("SELECT * from TABLE");
+ verify(preparedStatement).close();
+ verify(resultSet, times(2)).next();
+ verify(resultSet).getString(1);
+ verify(resultSet).getInt(2);
+ verify(resultSet).close();
+ verify(transactionManager).begin("databaseName");
+ verify(transactionManager).commit(connection);
+ verifyNoMoreInteractions(connection, preparedStatement, resultSet,
transactionManager);
// verify result
assertEquals(1, result.size()); // one row
assertEquals(2, result.get(0).size()); // two columns
@@ -118,6 +194,23 @@ public class BasePeerImplTest extends Ba
assertEquals(23, result.get(0).get(1));
}
+ public void testAddSelectColumns()
+ {
+ // prepare
+ Criteria criteria = new Criteria();
+
+ // execute
+ basePeerImpl.addSelectColumns(criteria);
+
+ // verify
+ UniqueColumnList selectColumns = criteria.getSelectColumns();
+ assertEquals(4, selectColumns.size());
+ assertSame(stringColumnMap, selectColumns.get(0));
+ assertSame(stringColumnMap2, selectColumns.get(1));
+ assertSame(stringColumnMap3, selectColumns.get(2));
+ assertSame(integerColumnMap, selectColumns.get(3));
+ }
+
/**
* Check that the fetch size gets set on the prepared statement when
* set in the criteria.
@@ -150,7 +243,7 @@ public class BasePeerImplTest extends Ba
criteria.where(columnMap, 42);
// execute
- int deleteCount = basePeerImpl.doDelete(criteria, connection);
+ int deleteCount = basePeerImpl.doDelete(criteria);
// verify mock
verify(connection).prepareStatement(
@@ -159,10 +252,254 @@ public class BasePeerImplTest extends Ba
verify(preparedStatement).setInt(1, 42);
verify(preparedStatement).executeUpdate();
verify(preparedStatement).close();
- verifyNoMoreInteractions(connection, preparedStatement, resultSet);
+ verify(transactionManager).begin("databaseName");
+ verify(transactionManager).commit(connection);
+ verifyNoMoreInteractions(connection, preparedStatement, resultSet,
transactionManager);
// verify result
assertEquals(1, deleteCount);
}
+ public void testDeleteWithError()
+ throws Exception
+ {
+ // prepare
+ Criteria criteria = new Criteria();
+ criteria.where(stringColumnMap, "abc");
+ SQLException toThrow = new SQLException("message");
+ when(preparedStatement.executeUpdate()).thenThrow(toThrow);
+
+ // execute
+ try
+ {
+ basePeerImpl.doDelete(criteria);
+ fail("Exception expected");
+ }
+ catch (TorqueException e)
+ {
+ assertEquals("java.sql.SQLException: message", e.getMessage());
+ assertSame(toThrow, e.getCause());
+ }
+
+ // verify mock
+ verify(connection).prepareStatement(
+ "DELETE FROM TABLE WHERE TABLE.COLUMN1=?");
+ verify(preparedStatement).setString(1, "abc");
+ verify(preparedStatement).executeUpdate();
+ verify(preparedStatement).close();
+ verify(transactionManager).begin("databaseName");
+ verify(transactionManager).safeRollback(connection);
+ verifyNoMoreInteractions(connection, preparedStatement, resultSet,
transactionManager);
+ }
+
+ /**
+ * Check that a simple doInsert works.
+ *
+ * @throws Exception if the test fails.
+ */
+ public void testDoInsertWithoutKeygen() throws Exception
+ {
+ // prepare
+ ColumnValues insertValues = new ColumnValues(databaseMap.getName());
+ insertValues.put(stringColumnMap, new JdbcTypedValue("value",
Types.VARCHAR));
+ insertValues.put(stringColumnMap2, new
JdbcTypedValue("someDbFunction"));
+ insertValues.put(stringColumnMap3, new JdbcTypedValue(null,
Types.VARCHAR));
+ insertValues.put(integerColumnMap, new JdbcTypedValue(42,
Types.INTEGER));
+
+ // execute
+ ObjectKey result = basePeerImpl.doInsert(insertValues);
+
+ // verify mock (verification order not relevant)
+ verify(connection).prepareStatement(
+ "INSERT INTO TABLE(COLUMN1,COLUMN2,COLUMN3,COLUMN4) VALUES
(?,someDbFunction,?,?)");
+ verify(preparedStatement).executeUpdate();
+ verify(preparedStatement).setObject(
+ 1,
+ "value",
+ Types.VARCHAR);
+ verify(preparedStatement).setNull(
+ 2,
+ Types.VARCHAR);
+ verify(preparedStatement).setObject(
+ 3,
+ 42,
+ Types.INTEGER);
+ verify(preparedStatement).close();
+ verify(transactionManager).begin(databaseMap.getName());
+ verify(transactionManager).commit(connection);
+ verifyNoMoreInteractions(connection, preparedStatement, resultSet,
transactionManager);
+ // verify result
+ // returns null because no id generator is defined
+ assertEquals(null, result);
+ }
+
+ /**
+ * Check that Exception handling for doInsert works.
+ *
+ * @throws Exception if the test fails.
+ */
+ public void testDoInsertWithException() throws Exception
+ {
+ // prepare
+ ColumnValues insertValues = new ColumnValues(databaseMap.getName());
+ insertValues.put(stringColumnMap, new JdbcTypedValue("value",
Types.VARCHAR));
+ insertValues.put(integerColumnMap, new JdbcTypedValue(42,
Types.INTEGER));
+ SQLException toThrow = new SQLException("message");
+ when(preparedStatement.executeUpdate()).thenThrow(toThrow);
+
+ // execute
+ try
+ {
+ basePeerImpl.doInsert(insertValues);
+ fail("Exception expected");
+ }
+ catch (TorqueException e)
+ {
+ assertEquals("java.sql.SQLException: message", e.getMessage());
+ assertSame(toThrow, e.getCause());
+ }
+
+ // verify mock (verification order not relevant)
+ verify(connection).prepareStatement(
+ "INSERT INTO TABLE(COLUMN1,COLUMN4) VALUES (?,?)");
+ verify(preparedStatement).executeUpdate();
+ verify(preparedStatement).setObject(
+ 1,
+ "value",
+ Types.VARCHAR);
+ verify(preparedStatement).setObject(
+ 2,
+ 42,
+ Types.INTEGER);
+ verify(preparedStatement).close();
+ verify(transactionManager).begin(databaseMap.getName());
+ verify(transactionManager).safeRollback(connection);
+ verifyNoMoreInteractions(connection, preparedStatement, resultSet,
transactionManager);
+ }
+
+ /**
+ * Check that a doInsert with a key generator works.
+ *
+ * @throws Exception if the test fails.
+ */
+ public void testDoInsertWithKeygen() throws Exception
+ {
+ // prepare
+ database.addIdGenerator(IDMethod.SEQUENCE, idGenerator);
+ ColumnValues insertValues = new ColumnValues(databaseMap.getName());
+ insertValues.put(stringColumnMap, new JdbcTypedValue("value",
Types.VARCHAR));
+
+ // execute
+ ObjectKey result = basePeerImpl.doInsert(insertValues);
+
+ // verify mock (verification order not relevant)
+ verify(connection).prepareStatement(
+ "INSERT INTO TABLE(COLUMN1,COLUMN4) VALUES (?,?)");
+ verify(preparedStatement).executeUpdate();
+ verify(preparedStatement).setObject(
+ 1,
+ "value",
+ Types.VARCHAR);
+ verify(preparedStatement).setObject(
+ 2,
+ DEFAULT_GENERATED_ID,
+ Types.NUMERIC);
+ verify(preparedStatement).close();
+ verify(transactionManager).begin(databaseMap.getName());
+ verify(transactionManager).commit(connection);
+ verify(idGenerator).isPriorToInsert();
+ verify(idGenerator).isPostInsert();
+ verify(idGenerator).getIdAsBigDecimal(connection, null);
+ verifyNoMoreInteractions(connection, preparedStatement, resultSet,
transactionManager, idGenerator);
+ // verify result
+ assertEquals(new NumberKey(DEFAULT_GENERATED_ID), result);
+ }
+
+ /**
+ * Check that a simple doUpdate works.
+ *
+ * @throws Exception if the test fails.
+ */
+ public void testDoUpdate() throws Exception
+ {
+ Criteria criteria = new Criteria();
+ criteria.where(integerColumnMap, 37);
+
+ ColumnValues updateValues = new ColumnValues(databaseMap.getName());
+ updateValues.put(stringColumnMap, new JdbcTypedValue("value",
Types.VARCHAR));
+ updateValues.put(stringColumnMap2, new
JdbcTypedValue("someDbFunction"));
+ updateValues.put(stringColumnMap3, new JdbcTypedValue(null,
Types.VARCHAR));
+ updateValues.put(integerColumnMap, new JdbcTypedValue(42,
Types.INTEGER));
+
+ int result = basePeerImpl.doUpdate(criteria, updateValues);
+
+ // verify mock (verification order not relevant)
+ verify(connection).prepareStatement(
+ "UPDATE TABLE SET TABLE.COLUMN1=?,"
+ + "TABLE.COLUMN2=someDbFunction,"
+ + "TABLE.COLUMN3=?,"
+ + "TABLE.COLUMN4=? "
+ + "WHERE TABLE.COLUMN4=?");
+ verify(preparedStatement).executeUpdate();
+ verify(preparedStatement).setObject(
+ 1,
+ "value");
+ verify(preparedStatement).setNull(
+ 2,
+ Types.VARCHAR);
+ verify(preparedStatement).setObject(
+ 3,
+ 42);
+ verify(preparedStatement).setInt(
+ 4,
+ 37);
+ verify(preparedStatement).close();
+ verify(transactionManager).begin(databaseMap.getName());
+ verify(transactionManager).commit(connection);
+ verifyNoMoreInteractions(connection, preparedStatement, resultSet,
transactionManager);
+ // verify result
+ // returns null because no id generator is defined
+ assertEquals(1, result);
+ }
+
+ /**
+ * Check that a simple doUpdate works.
+ *
+ * @throws Exception if the test fails.
+ */
+ public void testDoUpdateWithPk() throws Exception
+ {
+ ColumnValues updateValues = new ColumnValues(databaseMap.getName());
+ updateValues.put(stringColumnMap, new JdbcTypedValue("value",
Types.VARCHAR));
+ updateValues.put(stringColumnMap2, new
JdbcTypedValue("someDbFunction"));
+ updateValues.put(stringColumnMap3, new JdbcTypedValue(null,
Types.VARCHAR));
+ updateValues.put(integerColumnMap, new JdbcTypedValue(42,
Types.INTEGER));
+
+ int result = basePeerImpl.doUpdate(updateValues);
+
+ // verify mock (verification order not relevant)
+ verify(connection).prepareStatement(
+ "UPDATE TABLE SET TABLE.COLUMN1=?,"
+ + "TABLE.COLUMN2=someDbFunction,"
+ + "TABLE.COLUMN3=? "
+ + "WHERE TABLE.COLUMN4=?");
+ verify(preparedStatement).executeUpdate();
+ verify(preparedStatement).setObject(
+ 1,
+ "value");
+ verify(preparedStatement).setNull(
+ 2,
+ Types.VARCHAR);
+ verify(preparedStatement).setInt(
+ 3,
+ 42);
+ verify(preparedStatement).close();
+ verify(transactionManager).begin(databaseMap.getName());
+ verify(transactionManager).commit(connection);
+ verifyNoMoreInteractions(connection, preparedStatement, resultSet,
transactionManager);
+ // verify result
+ // returns null because no id generator is defined
+ assertEquals(1, result);
+ }
+
}
Modified:
db/torque/torque4/trunk/torque-templates/src/main/resources/org/apache/torque/templates/om/templates/peer/impl/base/doUpdate.vm
URL:
http://svn.apache.org/viewvc/db/torque/torque4/trunk/torque-templates/src/main/resources/org/apache/torque/templates/om/templates/peer/impl/base/doUpdate.vm?rev=1484594&r1=1484593&r2=1484594&view=diff
==============================================================================
---
db/torque/torque4/trunk/torque-templates/src/main/resources/org/apache/torque/templates/om/templates/peer/impl/base/doUpdate.vm
(original)
+++
db/torque/torque4/trunk/torque-templates/src/main/resources/org/apache/torque/templates/om/templates/peer/impl/base/doUpdate.vm
Mon May 20 21:03:07 2013
@@ -82,9 +82,29 @@
#foreach ($columnElement in $torqueGen.getChildren("column"))
#if($columnElement.getAttribute("primaryKey") == "true")
#set ( $peerColumnName = $columnElement.getAttribute("peerColumnName") )
- selectCriteria.where(
- ${peerClassName}.${peerColumnName},
-
columnValues.remove(${peerClassName}.${peerColumnName}).getValue());
+ {
+ JdbcTypedValue pkValue
+ = columnValues.remove(${peerClassName}.${peerColumnName});
+ if (pkValue == null)
+ {
+ throw new TorqueException(
+ "The value for the primary key column "
+ + "${peerClassName}.${peerColumnName}"
+ + " must be set");
+ }
+ if (pkValue.getVerbatimSql() == null)
+ {
+ selectCriteria.where(
+ ${peerClassName}.${peerColumnName},
+ pkValue.getValue());
+ }
+ else
+ {
+ selectCriteria.where(
+ ${peerClassName}.${peerColumnName},
+ new ColumnImpl(pkValue.getVerbatimSql()));
+ }
+ }
#end
#end
Modified:
db/torque/torque4/trunk/torque-templates/src/main/resources/org/apache/torque/templates/om/templates/peer/impl/base/imports.vm
URL:
http://svn.apache.org/viewvc/db/torque/torque4/trunk/torque-templates/src/main/resources/org/apache/torque/templates/om/templates/peer/impl/base/imports.vm?rev=1484594&r1=1484593&r2=1484594&view=diff
==============================================================================
---
db/torque/torque4/trunk/torque-templates/src/main/resources/org/apache/torque/templates/om/templates/peer/impl/base/imports.vm
(original)
+++
db/torque/torque4/trunk/torque-templates/src/main/resources/org/apache/torque/templates/om/templates/peer/impl/base/imports.vm
Mon May 20 21:03:07 2013
@@ -63,6 +63,7 @@ import org.apache.torque.TorqueException
import org.apache.torque.TorqueRuntimeException;
import $torqueGen.option("torque.om.criteriaClass");
import $torqueGen.option("torque.om.criterionClass");
+import org.apache.torque.ColumnImpl;
import org.apache.torque.om.mapper.RecordMapper;
import org.apache.torque.om.mapper.CompositeMapper;
import org.apache.torque.om.DateKey;
Added:
db/torque/torque4/trunk/torque-test/src/test/java/org/apache/torque/generated/peer/DoInsertTest.java
URL:
http://svn.apache.org/viewvc/db/torque/torque4/trunk/torque-test/src/test/java/org/apache/torque/generated/peer/DoInsertTest.java?rev=1484594&view=auto
==============================================================================
---
db/torque/torque4/trunk/torque-test/src/test/java/org/apache/torque/generated/peer/DoInsertTest.java
(added)
+++
db/torque/torque4/trunk/torque-test/src/test/java/org/apache/torque/generated/peer/DoInsertTest.java
Mon May 20 21:03:07 2013
@@ -0,0 +1,133 @@
+package org.apache.torque.generated.peer;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import java.math.BigDecimal;
+import java.sql.Types;
+import java.util.List;
+
+import org.apache.torque.BaseDatabaseTestCase;
+import org.apache.torque.criteria.Criteria;
+import org.apache.torque.om.ObjectKey;
+import org.apache.torque.test.dbobject.Author;
+import org.apache.torque.test.dbobject.IntegerType;
+import org.apache.torque.test.peer.AuthorPeer;
+import org.apache.torque.test.peer.IntegerTypePeer;
+import org.apache.torque.util.ColumnValues;
+import org.apache.torque.util.JdbcTypedValue;
+
+/**
+ * Tests the doInsert Methods in the Peer classes.
+ *
+ * @version $Id: SaveMethodsInPeerTest.java 1395238 2012-10-07 07:30:25Z
tfischer $
+ */
+public class DoInsertTest extends BaseDatabaseTestCase
+{
+ private List<Author> authorList;
+
+ @Override
+ public void setUp() throws Exception
+ {
+ super.setUp();
+ cleanBookstore();
+ authorList = insertBookstoreData();
+ }
+
+ /**
+ * Tests the doInsert method for a simple object.
+ *
+ * @throws Exception if a database error occurs.
+ */
+ public void testDoInsert() throws Exception
+ {
+ Author author = new Author();
+ author.setName("newName");
+
+ // execute
+ AuthorPeer.doInsert(author);
+
+ // verify
+ assertNotNull(author.getAuthorId());
+ assertEquals("newName", author.getName());
+
+ authorList.add(author);
+ verifyBookstore(authorList);
+ }
+
+ /**
+ * Tests the doInsert method with ColumnValues.
+ *
+ * @throws Exception if a database error occurs.
+ */
+ public void testDoInsertWithColumnValues() throws Exception
+ {
+ ColumnValues columnValues = new ColumnValues();
+ columnValues.put(
+ AuthorPeer.NAME,
+ new JdbcTypedValue("newName", Types.VARCHAR));
+
+ // execute
+ ObjectKey result = AuthorPeer.doInsert(columnValues);
+
+ // verify
+ Author author = new Author();
+ author.setName("newName");
+ author.setAuthorId(((BigDecimal) result.getValue()).intValue());
+
+ authorList.add(author);
+ verifyBookstore(authorList);
+ }
+
+ /**
+ * Tests the doInsert method with ColumnValues only where a non-primary-key
+ * Column value is a verbatim SQL expression.
+ *
+ * @throws Exception if a database error occurs.
+ */
+ public void testDoInsertWithColumnValuesAndVerbatimSqlValue()
+ throws Exception
+ {
+ IntegerTypePeer.doDelete(new Criteria());
+
+ IntegerType integerType = new IntegerType();
+ integerType.save();
+
+ ColumnValues columnValues = new ColumnValues();
+ columnValues.put(
+ IntegerTypePeer.INTEGER_VALUE,
+ new JdbcTypedValue(5, Types.INTEGER));
+ columnValues.put(
+ IntegerTypePeer.INTEGER_OBJECT_VALUE,
+ new JdbcTypedValue("ABS(-3)"));
+
+ // execute
+ ObjectKey objectKey = IntegerTypePeer.doInsert(columnValues);
+
+ // verify
+ List<IntegerType> allIntegerTypes = IntegerTypePeer.doSelect(
+ new Criteria().addDescendingOrderByColumn(IntegerTypePeer.ID));
+ assertEquals(2, allIntegerTypes.size());
+ assertEquals(5, allIntegerTypes.get(0).getIntegerValue());
+ assertEquals(new Integer(3),
allIntegerTypes.get(0).getIntegerObjectValue());
+ assertEquals(
+ ((BigDecimal) objectKey.getValue()).intValue(),
+ allIntegerTypes.get(0).getId());
+ }
+}
Added:
db/torque/torque4/trunk/torque-test/src/test/java/org/apache/torque/generated/peer/DoUpdateTest.java
URL:
http://svn.apache.org/viewvc/db/torque/torque4/trunk/torque-test/src/test/java/org/apache/torque/generated/peer/DoUpdateTest.java?rev=1484594&view=auto
==============================================================================
---
db/torque/torque4/trunk/torque-test/src/test/java/org/apache/torque/generated/peer/DoUpdateTest.java
(added)
+++
db/torque/torque4/trunk/torque-test/src/test/java/org/apache/torque/generated/peer/DoUpdateTest.java
Mon May 20 21:03:07 2013
@@ -0,0 +1,190 @@
+package org.apache.torque.generated.peer;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import java.sql.Types;
+import java.util.List;
+
+import org.apache.torque.BaseDatabaseTestCase;
+import org.apache.torque.criteria.Criteria;
+import org.apache.torque.test.dbobject.Author;
+import org.apache.torque.test.dbobject.IntegerType;
+import org.apache.torque.test.peer.AuthorPeer;
+import org.apache.torque.test.peer.IntegerTypePeer;
+import org.apache.torque.util.ColumnValues;
+import org.apache.torque.util.JdbcTypedValue;
+
+/**
+ * Tests the doUpdate Methods in the Peer classes.
+ *
+ * @version $Id: SaveMethodsInPeerTest.java 1395238 2012-10-07 07:30:25Z
tfischer $
+ */
+public class DoUpdateTest extends BaseDatabaseTestCase
+{
+ private List<Author> authorList;
+
+ @Override
+ public void setUp() throws Exception
+ {
+ super.setUp();
+ cleanBookstore();
+ authorList = insertBookstoreData();
+ }
+
+ /**
+ * Tests the doUpdate method for a simple object.
+ *
+ * @throws Exception if a database error occurs.
+ */
+ public void testDoUpdate() throws Exception
+ {
+ Author author = authorList.get(1).copy();
+ author.setNew(false);
+ author.setAuthorId(authorList.get(1).getAuthorId());
+
+ // execute
+ author.setName("newName");
+ int numberOfRows = AuthorPeer.doUpdate(author);
+
+ // verify
+ assertEquals(1, numberOfRows);
+ assertEquals(authorList.get(1).getAuthorId(), author.getAuthorId());
+ assertEquals("newName", author.getName());
+
+ authorList.get(1).setName("newName");
+ verifyBookstore(authorList);
+ }
+
+ /**
+ * Tests the doUpdate method with Criteria and ColumnValues.
+ *
+ * @throws Exception if a database error occurs.
+ */
+ public void testDoUpdateWithCriteraAndColumnValues() throws Exception
+ {
+ ColumnValues columnValues = new ColumnValues();
+ columnValues.put(
+ AuthorPeer.NAME,
+ new JdbcTypedValue("newName", Types.VARCHAR));
+ Criteria criteria = new Criteria().where(
+ AuthorPeer.AUTHOR_ID,
+ authorList.get(1).getAuthorId());
+
+ // execute
+ int numberOfRows = AuthorPeer.doUpdate(criteria, columnValues);
+
+ // verify
+ assertEquals(1, numberOfRows);
+ authorList.get(1).setName("newName");
+ verifyBookstore(authorList);
+ }
+
+ /**
+ * Tests the doUpdate method with ColumnValues only.
+ *
+ * @throws Exception if a database error occurs.
+ */
+ public void testDoUpdateWithColumnValues() throws Exception
+ {
+ ColumnValues columnValues = new ColumnValues();
+ columnValues.put(
+ AuthorPeer.NAME,
+ new JdbcTypedValue("newName", Types.VARCHAR));
+ columnValues.put(
+ AuthorPeer.AUTHOR_ID,
+ new JdbcTypedValue(
+ authorList.get(1).getAuthorId(),
+ Types.INTEGER));
+
+ // execute
+ int numberOfRows = AuthorPeer.doUpdate(columnValues);
+
+ // verify
+ assertEquals(1, numberOfRows);
+ authorList.get(1).setName("newName");
+ verifyBookstore(authorList);
+ }
+
+ /**
+ * Tests the doUpdate method with ColumnValues only where the primary key
+ * Column value is a verbatim SQL expression.
+ *
+ * @throws Exception if a database error occurs.
+ */
+ public void testDoUpdateWithColumnValuesAndVerbatimSqlValueInPk()
+ throws Exception
+ {
+ ColumnValues columnValues = new ColumnValues();
+ columnValues.put(
+ AuthorPeer.NAME,
+ new JdbcTypedValue("newName", Types.VARCHAR));
+ columnValues.put(
+ AuthorPeer.AUTHOR_ID,
+ new JdbcTypedValue(
+ Integer.toString(authorList.get(1).getAuthorId())));
+
+ // execute
+ int numberOfRows = AuthorPeer.doUpdate(columnValues);
+
+ // verify
+ assertEquals(1, numberOfRows);
+ authorList.get(1).setName("newName");
+ verifyBookstore(authorList);
+ }
+
+ /**
+ * Tests the doUpdate method with ColumnValues only where a non-primary-key
+ * Column value is a verbatim SQL expression.
+ *
+ * @throws Exception if a database error occurs.
+ */
+ public void testDoUpdateWithColumnValuesAndVerbatimSqlValue()
+ throws Exception
+ {
+ IntegerTypePeer.doDelete(new Criteria());
+
+ IntegerType integerType = new IntegerType();
+ integerType.save();
+ integerType = new IntegerType();
+ integerType.save();
+
+ ColumnValues columnValues = new ColumnValues();
+ columnValues.put(
+ IntegerTypePeer.INTEGER_VALUE,
+ new JdbcTypedValue(5, Types.INTEGER));
+ columnValues.put(
+ IntegerTypePeer.INTEGER_OBJECT_VALUE,
+ new JdbcTypedValue("ABS(-3)"));
+ columnValues.put(
+ IntegerTypePeer.ID,
+ new JdbcTypedValue(integerType.getId(), Types.INTEGER));
+
+ // execute
+ int numberOfRows = IntegerTypePeer.doUpdate(columnValues);
+
+ // verify
+ assertEquals(1, numberOfRows);
+ List<IntegerType> allIntegerTypes = IntegerTypePeer.doSelect(
+ new Criteria().addDescendingOrderByColumn(IntegerTypePeer.ID));
+ assertEquals(2, allIntegerTypes.size());
+ assertEquals(5, allIntegerTypes.get(0).getIntegerValue());
+ assertEquals(new Integer(3),
allIntegerTypes.get(0).getIntegerObjectValue());
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]