root / trunk / libraries / libGDBMS / src / test / java / com / hardcode / gdbms / engine / strategies / SumQuery.java @ 10627
History | View | Annotate | Download (2.24 KB)
1 |
package com.hardcode.gdbms.engine.strategies; |
---|---|
2 |
|
3 |
import com.hardcode.gdbms.driver.exceptions.ReadDriverException; |
4 |
import com.hardcode.gdbms.engine.customQuery.CustomQuery; |
5 |
import com.hardcode.gdbms.engine.customQuery.QueryException; |
6 |
import com.hardcode.gdbms.engine.data.DataSource; |
7 |
import com.hardcode.gdbms.engine.instruction.Adapter; |
8 |
import com.hardcode.gdbms.engine.instruction.Expression; |
9 |
import com.hardcode.gdbms.engine.instruction.Utilities; |
10 |
import com.hardcode.gdbms.engine.values.NumericValue; |
11 |
import com.hardcode.gdbms.engine.values.Value; |
12 |
|
13 |
/**
|
14 |
* @author Fernando Gonz?lez Cort?s
|
15 |
*/
|
16 |
public class SumQuery implements CustomQuery{ |
17 |
|
18 |
/**
|
19 |
* @throws QueryException
|
20 |
* @see com.hardcode.gdbms.engine.customQuery.CustomQuery#evaluate(com.hardcode.gdbms.engine.data.DataSource[], com.hardcode.gdbms.engine.instruction.Expression[])
|
21 |
*/
|
22 |
public OperationDataSource evaluate(DataSource[] tables, Expression[] values) throws QueryException { |
23 |
if (tables.length != 1) throw new QueryException("SUM only operates on one table"); |
24 |
if (values.length != 1) throw new QueryException("SUM only operates with one value"); |
25 |
|
26 |
((Adapter) values[0]).getInstructionContext().setFromTables(new DataSource[]{tables[0]}); |
27 |
((Adapter) values[0]).getInstructionContext().setDs(tables[0]); |
28 |
|
29 |
String fieldName = values[0].getFieldName(); |
30 |
if (fieldName == null) throw new QueryException("field not found " + Utilities.getText(((Adapter)values[0]).getEntity())); |
31 |
|
32 |
double res = 0; |
33 |
try {
|
34 |
|
35 |
tables[0].start();
|
36 |
|
37 |
int fieldIndex = tables[0].getFieldIndexByName(fieldName); |
38 |
if (fieldIndex == -1) throw new RuntimeException("we found the field name of the expression but could not find the field index?"); |
39 |
|
40 |
for (int i = 0; i < tables[0].getRowCount(); i++) { |
41 |
Value v = tables[0].getFieldValue(i, fieldIndex);
|
42 |
if (v instanceof NumericValue){ |
43 |
res += ((NumericValue) v).doubleValue(); |
44 |
}else{
|
45 |
throw new QueryException("SUM only operates with numeric fields"); |
46 |
} |
47 |
} |
48 |
|
49 |
tables[0].stop();
|
50 |
} catch (ReadDriverException e) {
|
51 |
throw new QueryException("Error reading data", e); |
52 |
} |
53 |
|
54 |
return new SumDataSource(res); |
55 |
} |
56 |
|
57 |
/**
|
58 |
* @see com.hardcode.gdbms.engine.customQuery.CustomQuery#getName()
|
59 |
*/
|
60 |
public String getName() { |
61 |
return "SUMQUERY"; |
62 |
} |
63 |
} |