FR [ 2493023 ] Adding getIDs new method in Query

https://sourceforge.net/tracker/?func=detail&atid=879335&aid=2493023&group_id=176962

refactored + added test case
This commit is contained in:
teo_sarca 2009-01-08 10:30:37 +00:00
parent f3e8cd0e28
commit fb473ceeea
2 changed files with 47 additions and 11 deletions

View File

@ -506,37 +506,46 @@ public class Query
* Get a Array with the IDs for this Query
* @return Get a Array with the IDs
*/
public int[] getIDs ()
{
String[] keys = table.getKeyColumns();
if (keys.length != 1)
{
throw new DBException("Table "+table+" has 0 or more than 1 key columns");
}
StringBuffer selectClause = new StringBuffer("SELECT ");
selectClause.append(keys[0]);
selectClause.append(" FROM ").append(table.getTableName());
String sql = buildSQL(selectClause, true);
ArrayList<Integer> list = new ArrayList<Integer>();
StringBuffer sql = new StringBuffer("SELECT ");
sql.append(table.getTableName()).append("_ID FROM ").append(table.getTableName());
if (whereClause != null && whereClause.length() > 0)
sql.append(" WHERE ").append(whereClause);
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql.toString(), trxName);
pstmt = DB.prepareStatement(sql, trxName);
rs = createResultSet(pstmt);
while (rs.next())
list.add(new Integer(rs.getInt(1)));
{
list.add(rs.getInt(1));
}
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql.toString(), e);
return null;
throw new DBException(e, sql);
}
finally {
finally
{
DB.close(rs, pstmt);
rs = null; pstmt = null;
}
// Convert to array
int[] retValue = new int[list.size()];
for (int i = 0; i < retValue.length; i++)
retValue[i] = ((Integer)list.get(i)).intValue();
{
retValue[i] = list.get(i);
}
return retValue;
} // get_IDs

View File

@ -11,6 +11,7 @@ import org.compiere.model.MTable;
import org.compiere.model.POResultSet;
import org.compiere.model.Query;
import org.compiere.util.DB;
import org.compiere.util.Env;
import test.AdempiereTestCase;
@ -170,4 +171,30 @@ public class QueryTest extends AdempiereTestCase
}
assertNotNull("Exception should be throwed", ex);
}
public void testSetClient_ID() throws Exception
{
int AD_Client_ID = Env.getAD_Client_ID(getCtx());
String sql = "SELECT COUNT(*) FROM C_Invoice WHERE IsActive='Y' AND AD_Client_ID="+AD_Client_ID;
int targetCount = DB.getSQLValue(null, sql);
//
int count = new Query(getCtx(), "C_Invoice", "1=1", getTrxName())
.setOnlyActiveRecords(true)
.setClient_ID()
.count();
assertEquals("Invoice # not match", targetCount, count);
}
public void testGet_IDs() throws Exception
{
final String whereClause = "AD_Element_ID IN (101, 102)";
int[] ids = new Query(getCtx(), "AD_Element", whereClause, getTrxName())
.setOrderBy("AD_Element_ID")
.getIDs();
assertNotNull(ids);
assertEquals(2, ids.length);
assertEquals(101, ids[0]);
assertEquals(102, ids[1]);
}
}