QueryImpl rtn=new QueryImpl(headers,0,"query");
rtn.setSql(sql);
// loop records
Vector orders = query.getOrderBy();
ZExp where = query.getWhere();
//print.out(headers);
// int newRecCount=0;
boolean hasMaxrow=maxrows>-1 && (orders==null || orders.size()==0);
for(int row=1;row<=recCount;row++) {
sql.setPosition(0);
if(hasMaxrow && maxrows<=rtn.getRecordcount())break;
boolean useRow=where==null || Caster.toBooleanValue(executeExp(pc,sql,qr, where, row));
if(useRow) {
rtn.addRow(1);
for(int cell=0;cell<headers.length;cell++){
Object value = selects.get(headers[cell]);
rtn.setAt(
headers[cell],
rtn.getRecordcount(),
getValue(pc,sql,qr,row,headers[cell],value)
//executeExp(qr, selects[cell].getExpression(),row)
);
}
}
}
// Group By
if(query.getGroupBy()!=null)
throw new DatabaseException("group by are not supported at the moment",null,sql,null);
// Order By
if(orders!=null && orders.size()>0) {
int len=orders.size();
for(int i=len-1;i>=0;i--) {
ZOrderBy order=(ZOrderBy) orders.get(i);
ZConstant name=(ZConstant)order.getExpression();
rtn.sort(name.getValue().toLowerCase(),order.getAscOrder()?Query.ORDER_ASC:Query.ORDER_DESC);
}
if(maxrows>-1) {
rtn.cutRowsTo(maxrows);
}
}
// Distinct
if(query.isDistinct()) {
String[] keys=rtn.getColumns();
QueryColumn[] columns=new QueryColumn[keys.length];
for(int i=0;i<columns.length;i++) {
columns[i]=rtn.getColumn(keys[i]);
}
int i;
outer:for(int row=rtn.getRecordcount();row>1;row--) {
for(i=0;i<columns.length;i++) {
if(!Operator.equals(QueryUtil.getValue(columns[i],row),QueryUtil.getValue(columns[i],row-1),true))
continue outer;
}
rtn.removeRow(row);
}
}
// UNION // TODO support it
ZExpression set = query.getSet();
if(set!=null){
ZExp op = set.getOperand(0);
if(op instanceof ZQuery) throw new DatabaseException("union is not supported at the moment",null,sql,null);
//getInvokedTables((ZQuery)op, tablesNames);
}
return rtn;