/**
* @throws QueryException
* @see org.gdbms.engine.customQuery.CustomQuery#evaluate(org.gdbms.engine.data.DataSource[], org.gdbms.engine.instruction.Expression[])
*/
public OperationDataSource evaluate(DataSource[] tables, Expression[] values) throws ExecutionException {
if (tables.length != 1) throw new ExecutionException("SUM only operates on one table");
if (values.length != 1) throw new ExecutionException("SUM only operates with one value");
((Adapter) values[0]).getInstructionContext().setFromTables(new DataSource[]{tables[0]});
((Adapter) values[0]).getInstructionContext().setDs(tables[0]);
String fieldName = values[0].getFieldName();
if (fieldName == null) throw new ExecutionException("field not found " + Utilities.getText(((Adapter)values[0]).getEntity()));
double res = 0;
try {
tables[0].start();
int fieldIndex = tables[0].getFieldIndexByName(fieldName);
if (fieldIndex == -1) throw new RuntimeException("we found the field name of the expression but could not find the field index?");
for (int i = 0; i < tables[0].getRowCount(); i++) {
Value v = tables[0].getFieldValue(i, fieldIndex);
if (v instanceof NumericValue){
res += ((NumericValue) v).doubleValue();
}else{
throw new ExecutionException("SUM only operates with numeric fields");
}
}
tables[0].stop();
} catch (DriverException e) {
throw new ExecutionException("Error reading data", e);
}
return new SumDataSource(res);
}