src/batch/sql/syntax/SQLQuery.java
public class SQLQuery extends Base {
  Loop loop;
  public String var;

  Op op;
  SQLTranslation body;
  boolean singleRow = false;
  List<Output> bindings = new ArrayList<Output>();
  List<SQLQuery> subqueries = new ArrayList<SQLQuery>();
  int sortLocation = 0; // where to insert the sorts
  List<Sorting> sorts;
  List<SQLTranslation> groupBy;
  SQLTable tables;
  private SQLTranslation where;
  private Output outputKey;
  SQLTranslation parent;
  SQLQuery parentQuery;
  long limit = -1;
  private boolean distinct;
  // actions
  public SQLAction sqlAction = SQLAction.NONE;
  List<SQLTranslation> actions;
  ISchema schema;
  public Env env;
  public String insertResultName;

  // used for root query
  public SQLQuery(ISchema schema, Loop loop, SQLAction sqlAction,
      boolean isValue, SQLQuery parentQuery) {
    this.schema = schema;
    this.loop = loop;
    this.isValue = isValue;
    this.sqlAction = sqlAction;
    this.parentQuery = parentQuery;
    op = loop.getOp();
    var = loop.getVar();
  }

  public <E> E run(BatchFactory<E> f) {
    StringBuilder b = new StringBuilder();
    this.toString(b);
    return f.Var(b.toString());
  }

  // used for root query
  public SQLQuery(boolean singleRow) {
    this.singleRow = singleRow;
  }

  public void setTables(SQLTable tables) {
    this.tables = tables;
  }

  public void addProjection(Output n) {
    if (sqlAction == SQLAction.NONE || sqlAction == SQLAction.VALUE)
      sqlAction = SQLAction.SELECT;
    else if (sqlAction != SQLAction.SELECT && sqlAction != SQLAction.INSERT)
      throw new Error("Mixed SELECT and " + sqlAction);
    if (getAggOp() != null)
      parentQuery.addProjection(n);
    else {
      // merge a aggregate value in a group-by query into the query
      if (groupBy != null && n.getExpr() instanceof SQLQuery) {
        SQLQuery inner = (SQLQuery) n.getExpr();
        List<SQLTranslation> args = new ArrayList<SQLTranslation>();
        SQLTranslation body = inner.getBody();
        args.add(body instanceof SQLTable ? new Var("*") : body);
        n = new Output(n.getLocation(), new Call(
            batch.sql.syntax.Factory.factory.Root(), inner.getAggOp(), args));
      }
      bindings.add(n);
    }
  }

  private String getAggOp() {
    return loop == null ? null : loop.getAggOp();
  }

  private SQLTranslation getBody() {
    return body;
  }

  final static List<SQLTranslation> nullArgs = new ArrayList<SQLTranslation>();

  public void setLimit(long limit) {
    if (this.limit == -1 || limit < this.limit)
      this.limit = limit;
  }

  public void addSubquery(SQLQuery subquery, SQLTranslation parentBase) {
    subqueries.add(subquery);

    if (outputKey == null && parentBase != null) {
      SQLTranslation exp = parentBase.normalize(schema, this, null, env,
          NormType.NORMAL);
      SQLField key = exp.getTable().getRealTable().getKey();
      outputKey = new Output(getSubTag(), key);
      addProjection(outputKey);
    }
    if (outputKey != null)
      addSort(true, outputKey);
  }

  void setContainer(SQLQuery parentQuery) {
    this.parentQuery = parentQuery;
  }

  // parent exp is the key that ties this 
  // query to its parent query
  void setParent(SQLTranslation parent) {
    this.parent = parent; /// new Output("parent", 
    addProjection(new Output("parent", parent));
    addSort(true, new Var("parent"));
    if (groupBy != null)
      groupBy.add(parent);
  }

  void addSort(boolean ascending, SQLTranslation data) {
    if (sorts == null)
      sorts = new ArrayList<Sorting>();
    if (data instanceof Output)
      data = new Var(((Output) data).getLocation());
    sorts.add(sortLocation++, new Sorting(ascending, data));
  }

  public String getSubTag() {
    return "id";
  }

  public List<SQLQuery> getSubqueries() {
    return subqueries;
  }

  public void addWhere(SQLTranslation cond) {
    where = batch.syntax.Parser.binary(Factory.factory, Op.AND, cond, where);
  }

  public void setDistinct() {
    distinct = true;
  }

  public List<Output> getProjections() {
    return bindings;
  }

  //	public String getVar() {
  //		return me.var;
  //	}

  @Override
  public SQLTable getTableNoJoins(Env env) {
    return tables;
  }

  public void addGroupBy(SQLTranslation exp) {
    if (groupBy == null)
      groupBy = new ArrayList<SQLTranslation>();
    groupBy.add(exp);
    if (parent != null)
      groupBy.add(parent);
    outputKey = new Output(getSubTag(), exp);
    addProjection(outputKey);
  }

  // Department
  // d.emps
  // d.manager.projects
  // d.manager.projects
  @Override
  public void toSQL(StringBuilder sb, List<Object> params, ForestReader data) {
    int count = 0;
    switch (sqlAction) {
    case DELETE:
      /*
      DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
          tbl_name[.*] [, tbl_name[.*]] ...
          FROM table_references
          [WHERE where_condition]
       */
      sb.append("DELETE ");
      count = 0;
      for (SQLTranslation e : actions) {
        if (++count > 1)
          sb.append(",");
        e.toSQL(sb, params, data);
      }
      outputFrom(sb, params, data);
      return;
    case UPDATE:
      /*
      UPDATE [LOW_PRIORITY] [IGNORE] table_references
          SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
          [WHERE where_condition]
       */
      sb.append("UPDATE ");
      tables.fromClause(sb);
      sb.append(" SET ");
      count = 0;
      for (SQLTranslation e : actions) {
        if (++count > 1)
          sb.append(",");
        e.toSQL(sb, params, data);
      }
      outputWhere(sb, params, data);
      return;
    case INSERT:
      //INSERT INTO suppliers(supplier_id, supplier_name)
      //SELECT account_no, name
      //FROM customers
      //WHERE city = 'Newark';
      sb.append("INSERT INTO ");
      Call insert = (Call) actions.get(0);
      insert.toSQL(sb, params, data);
      sb.append('\n');
      // fall through
    case VALUE:
    case SELECT:
      SQLAction savedAction = sqlAction;
      boolean aggregate = getAggOp() != null;
      if (aggregate || isValue) {
        if (op == Op.OR)
          sb.append(getAggOp());
        sb.append('(');
      }

      sb.append("SELECT ");
      if (distinct)
        sb.append("DISTINCT ");
      count = 0;
      if (aggregate && op != Op.OR) {
        sb.append(getAggOp());
        sb.append('(');
        if (op == Op.COUNT)
          sb.append('*');
        else
          getBody().toSQL(sb, params, data);
        sb.append(')');
      } else if (isValue && body != null && bindings.size() == 0) {
        if (body instanceof SQLTable)
          body = ((SQLTable) body).getKey();
        body.toSQL(sb, params, data);
      } else {
        for (SQLTranslation b : bindings) {
          if (++count > 1)
            sb.append(",\n\t");
          else
            sb.append("\n\t");
          b.toSQL(sb, params, data);
        }
        if (count == 0)
          sb.append('*');
      }
      outputFrom(sb, params, data);
      if (aggregate || isValue)
        sb.append(')');
      sqlAction = savedAction;
      return;
    }
  }

  private void outputFrom(StringBuilder sb, List<Object> params,
      ForestReader data) {
    if (tables != null) {
      sb.append("\nFROM ");
      tables.fromClause(sb);
    }
    outputWhere(sb, params, data);
  }

  private void outputWhere(StringBuilder sb, List<Object> params,
      ForestReader data) {
    if (where != null) {
      sb.append("\nWHERE ");
      where.toSQL(sb, params, data);
    }
    if (groupBy != null) {
      sb.append("\nGROUP BY ");
      int i = 0;
      for (SQLTranslation e : groupBy) {
        if (i++ > 0)
          sb.append(",");
        e.toSQL(sb, params, data);
      }
    }
    if (sorts != null) {
      sb.append("\nORDER BY ");
      int i = 0;
      for (Sorting s : sorts) {
        if (i++ > 0)
          sb.append(",");
        s.value.toSQL(sb, params, data);
        sb.append(s.ascending ? " ASC" : " DESC");
      }
    }
    if (limit >= 0)
      sb.append("\nLIMIT " + limit);
  }

  public SQLTable getTable() {
    return tables;
  }

  public void doAction(SQLAction kind, SQLTranslation table) {
    if (sqlAction == SQLAction.NONE || sqlAction == SQLAction.SELECT || sqlAction == SQLAction.VALUE)
      sqlAction = kind;
    else if (kind != sqlAction)
      throw new Error("Combined actions");
    if (actions == null)
      actions = new ArrayList<SQLTranslation>();
    actions.add(table);
  }

  public SQLAction getAction() {
    return sqlAction;
  }

  public boolean isSingleRow() {
    return singleRow || isValue;
  }

  //	public void setSingleRow() {
  //		singleRow = true;
  //	}

  public SQLTranslation normalize(ISchema schema, SQLQuery query,
      SQLTranslation outerCond, Env env, NormType normType) {
    return this;
  }

  public SQLTranslation finalize(SQLTranslation body, SQLTranslation testId) {
    this.body = body;
    if (op == Op.AND) {
      // have to use AND(x,y) = NOT(OR(NOT(x),NOT(y))
      where = Factory.factory.Prim(Op.NOT, where);
      op = Op.OR;
    }
    if (op == Op.OR) {
      addWhere(body);
    }
    if (testId != null) {
      SQLTranslation id = testId.normalize(schema, this, null, env,
          NormType.NORMAL);
      addWhere(Factory.factory.Prim(Op.EQ, env.lookup(getVar()).getTable()
          .getKey(), id));
    }
    if (isValue || getAggOp() != null) {
      body.getTable();
      return this;
    } else
      return env.lookup(getVar());
  }

  public String getVar() {
    return var;
  }

  public void resetSortOrder() {
    sortLocation = 0; // start parents sorting above ours!
  }

  public void toString(StringBuilder sb) {
    try {
      toSQL(sb, null, null);
    } catch (Error x) {
      sb.append("ERROR");
    }
  }

  @Override
  public SQLTranslation getTransformations(SQLTranslation base) {
    return loop.getTransformations(base);
  }

  public SQLTranslation dot(String field, ISchema schema, SQLQuery query,
      Env env, NormType normType) {
    if (isValue) {
      body = new Dot(body, field).normalize(schema, query, null, env, normType);
      return this;
    } else {
      return super.dot(field, schema, query, env, normType);
    }
  }

}
src/batch/sql/syntax/SQLTranslation.java
public interface SQLTranslation {
	public enum NormType {
		NORMAL, PARENT, EXTERNAL
	}

	public enum SQLAction {
		NONE, VALUE, SELECT, INSERT, UPDATE, DELETE
	}

	public abstract void setValue();
	
	public abstract SQLTable getTable();

	public abstract SQLTranslation invertPath(SQLTranslation inverted, Env env,
			boolean fromChild);

	public abstract SQLTranslation normalize(ISchema schema, SQLQuery query,
			SQLTranslation outerCond, Env env, NormType normType);

	public abstract void toSQL(StringBuilder sb, List<Object> params, ForestReader data);

	public abstract SQLTable getTableNoJoins(Env env);

	public abstract SQLTable getBase(Env env);

	public abstract SQLTranslation withoutTransformations();

	public abstract SQLTranslation getTransformations(SQLTranslation base);

	public abstract SQLTranslation trimLast(Env env);

	public abstract SQLTranslation collectInsertArguments(String var,
			batch.sql.syntax.Call call);

	public abstract SQLTranslation dot(String field, ISchema schema,
			SQLQuery query, Env env, NormType normType);

  public abstract <E> E run(BatchFactory<E> f);
}
src/batch/sql/schema/ISchema.java
public interface ISchema {

	public IEntityType getEntity(String name);

}
src/batch/sql/syntax/Prim.java
public class Prim extends ValueExpression {

  Op op;
  List<SQLTranslation> args;

  public Prim(Op op, List<SQLTranslation> args) {
    super();
    this.op = op;
    this.args = args;
    if (op != Op.SEQ)
      for (SQLTranslation s : args)
        s.setValue();
    setValue();
  }

  public <E> E run(BatchFactory<E> f) {
    List<E> trans = new ArrayList<E>();
    for (SQLTranslation x : args)
      trans.add(x.run(f));
    return f.Prim(op, trans);
  }

  @Override
  public SQLTranslation normalize(ISchema schema, SQLQuery query,
      SQLTranslation outerCond, Env env, NormType normType) {
    if (op != Op.SEQ)
      outerCond = null;
    List<SQLTranslation> newargs = new ArrayList<SQLTranslation>();
    for (SQLTranslation x : args) {
      SQLTranslation n = x.normalize(schema, query, outerCond, env, normType);
      newargs.add(n);
    }
    return new Prim(op, newargs);
  }

  public SQLTable getTable() {
    for (SQLTranslation e : args) {
      SQLTable t = e.getTable();
      if (t != null)
        return t;
    }
    return null;
  }

  public String sqlOp(Op op) {
    switch (op) {
    case ADD:
      return "+";
    case SUB:
      return "-";
    case MUL:
      return "*";
    case DIV:
      return "/";
    case MOD:
      return "%";
    case AND:
      return "\nAND ";
    case OR:
      return "\nOR ";
    case NOT:
      return " NOT ";
    case EQ:
      return "=";
    case NE:
      return "!=";
    case LT:
      return "<";
    case GT:
      return ">";
    case LE:
      return "<=";
    case GE:
      return ">=";
    }
    return "INVALID";
  }

  @Override
  public void toSQL(StringBuilder sb, List<Object> params, ForestReader data) {
    if (args.size() == 0) {
      sb.append(op.toString());
    } else {
      sb.append("(");
      int i = 0;
      for (SQLTranslation e : args) {
        if (i > 0 || args.size() == 1)
          sb.append(sqlOp(op));
        e.toSQL(sb, params, data);
        i++;
      }
      sb.append(")");
    }
  }

  public List<SQLTranslation> getArgs() {
    return args;
  }

  public Op getOp() {
    return op;
  }

  @Override
  public SQLTranslation collectInsertArguments(String var, Call call) {
    int i = 0;
    while (i < args.size()) {
      SQLTranslation x = args.get(i).collectInsertArguments(var, call);
      if (x == null)
        args.remove(i);
      else
        args.set(i++, x);
    }
    if (i == 0)
      return null;
    else
      return this;
  }
}
src/batch/sql/schema/javareflect/Schema.java
public class Schema implements ISchema {

	Map<String, EntityType> entities = new HashMap<String, EntityType>();

	public Schema(Class<?> cls) {
		setup(cls);
	}

	public static IEntityType MakeGroupByEntityType(SQLTranslation group, IEntityType itemType, Fun alias) {
		return new EntityType(group, itemType, alias);
	}
	
	public void setup(Class<?> cls) {
		for (Field f : cls.getFields()) {
			String name = f.getName();
			addMember(name, f.getGenericType());
		}
		for (Method m : cls.getMethods()) {
			if (m.getDeclaringClass() == Object.class)
				continue;
			String name = m.getName();
			if (name.startsWith("insert") && m.getParameterTypes().length == 1)
				addMember(name, m.getParameterTypes()[0]);
			if (name.startsWith("get") && m.getParameterTypes().length == 0)
				addMember(name, m.getGenericReturnType());
		}
		for (EntityType e : entities.values())
			e.complete();
	}

	private void addMember(String name, Type type) {
		if (type instanceof ParameterizedType) {
			type = ((ParameterizedType) type).getActualTypeArguments()[0];
		}
		entities.put(name, createEntityTypeFromJavaType(type));
	}

	public EntityType createEntityTypeFromJavaType(Type type) {
		Type rawType = type;
		if (type instanceof ParameterizedType)
			rawType = ((ParameterizedType) type).getRawType();
		Class<?> cls = (Class<?>) rawType;
		String name = cls.getSimpleName();
		EntityType e = entities.get(name);
		if (e == null) {
			e = new EntityType(this, name);
			entities.put(name, e);
			e.load(cls);
		}
		return e;
	}

	@Override
	public IEntityType getEntity(String name) {
		IEntityType e = entities.get(name);
		if (e == null)
			throw new Error("Missing entity type " + name);
		return e;
	}
}
src/batch/util/ForestReader.java
public interface ForestReader {

  /**
   * Retrieves the object value of the given variable name.
   * 
   * @param variable
   *            the name of the variable
   * @return the object value of the given variable name.
   */
  Object get(String variable);

  int getByte(String variable);

  short getShort(String variable);

  int getInteger(String variable);

  long getLong(String variable);

  /**
   * Retrieves the object value of the given variable name.
   * 
   * @param variable
   *            the name of the variable
   * @return the object value of the given variable name.
   */
  double getDouble(String variable);

  float getFloat(String variable);

  java.math.BigDecimal getBigDecimal(String variable);

  /**
   * Retrieves the object value of the given variable name.
   * 
   * @param variable
   *            the name of the variable
   * @return the object value of the given variable name.
   */
  String getString(String variable);

  char getCharacter(String variable);

  /**
   * Retrieves the object value of the given variable name.
   * 
   * @param variable
   *            the name of the variable
   * @return the object value of the given variable name.
   */
  boolean getBoolean(String variable);

  /**
   * Retrieves the object value of the given variable name.
   * 
   * @param variable
   *            the name of the variable
   * @return the object value of the given variable name.
   */
  java.sql.Date getDate(String variable);

  java.util.Date getUtilDate(String variable);

  /**
   * Retrieves the object value of the given variable name.
   * 
   * @param variable
   *            the name of the variable
   * @return the object value of the given variable name.
   */
  java.sql.Time getTime(String variable);

  /**
   * Retrieves the object value of the given variable name.
   * 
   * @param variable
   *            the name of the variable
   * @return the object value of the given variable name.
   */
  java.sql.Timestamp getTimestamp(String variable);

  byte[] getRawData(String variable);

  /**
   * Retrieves the iteration of the given variable name.
   * 
   * @param variable
   *            the name of the variable.
   * @return the iteration object of the given variable name.
   */
  Iterable<ForestReader> getTable(String variable);

  void complete();

  void copyTo(ForestWriter out);
}
src/batch/util/Forest.java
public class Forest extends ForestReaderHelper implements ForestWriter {

  // instance variables
  private Map<String, Object> values;
  private Map<String, MultiForest> iterations;
  private Forest parent;

  /**
   * Default constructor
   */
  public Forest() {
    this.values = new HashMap<String, Object>();
    this.iterations = new HashMap<String, MultiForest>();
  }

  public void setParent(Forest parent) {
    this.parent = parent;
  }

  public void put(String name, Object value) {
    // Feature: ENUM turned off
    //		if (value instanceof Enum)
    //			value = value.toString();
    values.put(name, value);
  }

  /**
   * Retrieves the object value of the given variable name.
   * 
   * @param variable
   *          the name of the variable
   * @return the object value of the given variable name.
   */
  public Object get(String variable) {
    Object val = values.get(variable);
    if (val == null && parent != null)
      val = parent.get(variable);
    if (val instanceof Error)
      throw (Error) val;
    else if (val instanceof RuntimeException)
      throw (RuntimeException) val;
    else
      return val;
  }

  /**
   * Retrieves the iteration of the given variable name.
   * 
   * @param variable
   *          the name of the variable.
   * @return the iteration object of the given variable name.
   */
  public Iterable<ForestReader> getTable(String variable) {
    MultiForest mf = iterations.get(variable);
    if (mf == null && parent != null)
      return parent.getTable(variable);
    else
      return mf;
  }

  // only used for when you want to read and write
  public Iterator<Forest> getForestIteration(String variable) {
    MultiForest mf = iterations.get(variable);
    if (mf == null && parent != null)
      return parent.getForestIteration(variable);
    else
      return mf.forestIterator();
  }

  public boolean isEmpty() {
    return values.size() == 0 && iterations.size() == 0;
  }

  public String toString() {
    StringBuilder sb = new StringBuilder();
    if (values.size() > 0)
      sb.append(values.toString());
    if (iterations.size() > 0)
      sb.append(iterations.toString());
    return sb.toString();
  }

  /**
   * Creates a new iteration object and inserts it into the iteration store for
   * the given variable name.
   * 
   * @param variable
   *          the name of the variable.
   * @return a new iteration object for the given variable name.
   */
  @Override
  public ForestListWriter newTable(String variable) {
    return newForestIteration(variable);
  }

  public MultiForest newForestIteration(String variable) {
    final MultiForest iteration = new MultiForest(this);
    iterations.put(variable, iteration);
    return iteration;
  }

  @Override
  public void complete() {
    // TODO Auto-generated method stub
    
  }

  public void copyTo(ForestWriter out) {
    for (Map.Entry<String, Object> e : values.entrySet())
      out.put(e.getKey(), e.getValue());
    for (Map.Entry<String, MultiForest> e : iterations.entrySet())
      e.getValue().copyTo( out.newTable(e.getKey()));
    out.complete();
  }

}
src/batch/util/ForestWriter.java
public interface ForestWriter {
  void put(String name, Object value);
  ForestListWriter newTable(String variable);
  void complete();
}
src/batch/Service.java
public interface Service<E, I> extends batch.util.BatchFactory<E>, Iterable<I> {

	public void executeServer(E exp, ForestReader in, ForestWriter out);

	public ForestReader execute(E exp, ForestReader in);
}
src/batch/sql/syntax/Env.java
public class Env {

	String name;
	SQLTranslation value;
	Env rest;
	SQLQuery rootQuery;

	public Env(SQLQuery rootQuery) {
		this.rootQuery = rootQuery;
	}
	
	public Env(String name, SQLTranslation value, Env rest) {
		super();
		this.name = name;
		this.value = value;
		this.rest = rest;
		this.rootQuery = rest.getRootQuery();
	}

	public SQLQuery getRootQuery() {
		return rootQuery;
	}

	SQLTranslation lookup(String name) {
		if (this.name.equals(name))
			return value;
		else
			return rest.lookup(name);
	}
}


Question: import batch.sql.syntax.Env;
import batch.sql.syntax.Prim;
import batch.sql.syntax.SQLQuery;
import batch.sql.syntax.SQLTranslation;
import batch.util.Forest;
import batch.util.ForestReader;
import batch.util.ForestWriter;
import java.util.Iterator;
import java.util.List;
import batch.Service;
import batch.sql.schema.ISchema;
import batch.sql.schema.javareflect.Schema;
/*******************************************************************************
 * The accompanying source code is made available to you under the terms of 
 * the UT Research License (this "UTRL"). By installing or using the code, 
 * you are consenting to be bound by the UTRL. See LICENSE.html for a 
 * full copy of the license.
 * 
 * Copyright � 2009, The University of Texas at Austin. All rights reserved.
 * 
 * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS 
 * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES 
 * OF PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE 
 * OF DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED 
 * WITH RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances 
 * shall University be liable for incidental, special, indirect, direct 
 * or consequential damages or loss of profits, interruption of business, 
 * or related expenses which may arise from use of Software or Documentation, 
 * including but not limited to those resulting from defects in Software 
 * and/or Documentation, or loss or inaccuracy of data of any kind.
 * 
 * Created by: William R. Cook and Eli Tilevich
 * with: Jose Falcon, Marc Fisher II, Ali Ibrahim, Yang Jiao, Ben Wiedermann
 * University of Texas at Austin and Virginia Tech
 ******************************************************************************/
package batch.sql;



public class SQLBatch<T> extends batch.sql.syntax.Factory implements Service<SQLTranslation, T> {

	SQLQuery rootQuery;
	ISchema schema;
	
	public SQLBatch(ISchema schema) {
		super();
		this.schema = schema;
	}

	public SQLBatch(Class<T> rootClass) {
		super();
		this.schema = new Schema(rootClass);
	}

Answer: 	public ForestReader execute(SQLTranslation exp, ForestReader in) {