You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@drill.apache.org by ja...@apache.org on 2013/08/06 23:46:32 UTC

[3/3] git commit: Sort operator using HyperBatch concept. Supports single and multikey asc/desc sort. One comparator function definition. Add abstract record batch, vector container and vector wrapper. Various fixes to return to client when query fails.

Sort operator using HyperBatch concept.  Supports single and multikey asc/desc sort.
One comparator function definition.
Add abstract record batch, vector container and vector wrapper.
Various fixes to return to client when query fails.


Project: http://git-wip-us.apache.org/repos/asf/incubator-drill/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-drill/commit/db3afaa8
Tree: http://git-wip-us.apache.org/repos/asf/incubator-drill/tree/db3afaa8
Diff: http://git-wip-us.apache.org/repos/asf/incubator-drill/diff/db3afaa8

Branch: refs/heads/master
Commit: db3afaa854fc8475592907dba97162ecf869f9df
Parents: 31f1964
Author: Jacques Nadeau <ja...@apache.org>
Authored: Sun Aug 4 15:47:31 2013 -0700
Committer: Jacques Nadeau <ja...@apache.org>
Committed: Tue Aug 6 14:37:27 2013 -0700

----------------------------------------------------------------------
 .../drill/common/expression/FunctionCall.java   |   1 +
 .../templates/NullableValueVectors.java         |   2 +-
 .../templates/RepeatedValueVectors.java         |   2 +-
 .../templates/VariableLengthVectors.java        |   5 +-
 .../apache/drill/exec/expr/CodeGenerator.java   |  39 ++-
 .../drill/exec/expr/EvaluationVisitor.java      |  62 ++---
 .../exec/expr/ExpressionTreeMaterializer.java   |   2 +-
 .../exec/expr/ValueVectorReadExpression.java    |  33 ++-
 .../exec/expr/ValueVectorWriteExpression.java   |  13 +-
 .../drill/exec/expr/fn/impl/Alternator.java     |  53 ++--
 .../exec/expr/fn/impl/ComparatorFunctions.java  |  58 +++++
 .../apache/drill/exec/ops/FragmentContext.java  |   5 +-
 .../apache/drill/exec/physical/base/Sender.java |   1 +
 .../exec/physical/impl/FilterRecordBatch.java   | 130 ----------
 .../impl/FilteringRecordBatchTransformer.java   |  58 -----
 .../drill/exec/physical/impl/ImplCreator.java   |   9 +
 .../drill/exec/physical/impl/RootExec.java      |   1 -
 .../drill/exec/physical/impl/ScanBatch.java     |  26 +-
 .../drill/exec/physical/impl/ScreenCreator.java |   4 +-
 .../exec/physical/impl/SingleSenderCreator.java |   2 +-
 .../drill/exec/physical/impl/VectorHolder.java  |  39 ---
 .../exec/physical/impl/WireRecordBatch.java     |  15 +-
 .../physical/impl/filter/FilterRecordBatch.java | 129 ++--------
 .../impl/materialize/RecordMaterializer.java    |   6 -
 .../impl/project/ProjectRecordBatch.java        | 141 ++---------
 .../exec/physical/impl/sort/Comparator.java     |  11 +
 .../physical/impl/sort/ReadIndexRewriter.java   |  87 +++++++
 .../physical/impl/sort/RecordBatchData.java     |  47 ++++
 .../exec/physical/impl/sort/SortBatch.java      | 171 +++++++++++++
 .../physical/impl/sort/SortBatchCreator.java    |  23 ++
 .../impl/sort/SortRecordBatchBuilder.java       | 130 ++++++++++
 .../exec/physical/impl/sort/SortTemplate.java   |  45 ++++
 .../drill/exec/physical/impl/sort/Sorter.java   |  17 ++
 .../exec/physical/impl/svremover/Copier.java    |   7 +-
 .../physical/impl/svremover/CopierTemplate.java |  43 ----
 .../impl/svremover/CopierTemplate2.java         |  43 ++++
 .../impl/svremover/CopierTemplate4.java         |  47 ++++
 .../impl/svremover/RemovingRecordBatch.java     | 246 ++++++++-----------
 .../impl/svremover/SVRemoverCreator.java        |   2 +-
 .../drill/exec/record/AbstractRecordBatch.java  |  78 ++++++
 .../exec/record/AbstractSingleRecordBatch.java  |  52 ++++
 .../drill/exec/record/HyperVectorWrapper.java   |  54 ++++
 .../drill/exec/record/InvalidValueAccessor.java |  46 ----
 .../apache/drill/exec/record/RecordBatch.java   |  45 +---
 .../drill/exec/record/RecordBatchLoader.java    |  66 ++---
 .../apache/drill/exec/record/RecordMaker.java   |  22 --
 .../drill/exec/record/RecordRemapper.java       |   8 -
 .../drill/exec/record/SimpleVectorWrapper.java  |  49 ++++
 .../apache/drill/exec/record/TypedFieldId.java  |  58 +++++
 .../drill/exec/record/VectorContainer.java      | 130 ++++++++++
 .../apache/drill/exec/record/VectorWrapper.java |  14 ++
 .../apache/drill/exec/record/WritableBatch.java |  12 +-
 .../exec/record/selection/SelectionVector4.java |  56 ++++-
 .../selection/SelectionVector4Builder.java      |  37 +++
 .../drill/exec/rpc/user/QueryResultHandler.java |  60 +++--
 .../drill/exec/vector/BaseDataValueVector.java  |   1 +
 .../drill/exec/vector/SerializableVector.java   |   7 +
 .../apache/drill/exec/vector/ValueVector.java   |   2 +
 .../work/AbstractFragmentRunnerListener.java    |   7 +-
 .../work/RemotingFragmentRunnerListener.java    |   2 +
 .../drill/exec/work/foreman/ErrorHelper.java    |  19 +-
 .../work/foreman/RunningFragmentManager.java    |   7 +-
 .../org/apache/drill/exec/expr/EscapeTest1.java | 181 ++++++++++++++
 .../apache/drill/exec/expr/ExpressionTest.java  |  22 +-
 .../exec/physical/impl/SimpleRootExec.java      |  16 +-
 .../physical/impl/TestSimpleFragmentRun.java    |  11 +-
 .../exec/physical/impl/sort/TestSimpleSort.java | 145 +++++++++++
 .../record/ExpressionTreeMaterializerTest.java  |   1 -
 .../src/test/resources/sort/one_key_sort.json   |  44 ++++
 .../src/test/resources/sort/two_key_sort.json   |  54 ++++
 .../drill/sql/client/full/BatchListener.java    |  17 +-
 .../drill/sql/client/full/BatchLoaderMap.java   |   5 +-
 .../apache/drill/jdbc/test/FullEngineTest.java  |  10 +
 .../org/apache/drill/jdbc/test/JdbcTest.java    |   5 +
 74 files changed, 2150 insertions(+), 948 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/db3afaa8/sandbox/prototype/common/src/main/java/org/apache/drill/common/expression/FunctionCall.java
----------------------------------------------------------------------
diff --git a/sandbox/prototype/common/src/main/java/org/apache/drill/common/expression/FunctionCall.java b/sandbox/prototype/common/src/main/java/org/apache/drill/common/expression/FunctionCall.java
index d27b584..d343fd6 100644
--- a/sandbox/prototype/common/src/main/java/org/apache/drill/common/expression/FunctionCall.java
+++ b/sandbox/prototype/common/src/main/java/org/apache/drill/common/expression/FunctionCall.java
@@ -76,4 +76,5 @@ public class FunctionCall extends LogicalExpressionBase implements Iterable<Logi
   }
 
   
+  
 }

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/db3afaa8/sandbox/prototype/exec/java-exec/src/main/codegen/ValueVectors/templates/NullableValueVectors.java
----------------------------------------------------------------------
diff --git a/sandbox/prototype/exec/java-exec/src/main/codegen/ValueVectors/templates/NullableValueVectors.java b/sandbox/prototype/exec/java-exec/src/main/codegen/ValueVectors/templates/NullableValueVectors.java
index 644019e..ca222df 100644
--- a/sandbox/prototype/exec/java-exec/src/main/codegen/ValueVectors/templates/NullableValueVectors.java
+++ b/sandbox/prototype/exec/java-exec/src/main/codegen/ValueVectors/templates/NullableValueVectors.java
@@ -68,7 +68,7 @@ public final class ${className} extends BaseValueVector implements <#if type.maj
     values.clear();
   }
   
-  int getBufferSize(){
+  public int getBufferSize(){
     return values.getBufferSize() + bits.getBufferSize();
   }
 

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/db3afaa8/sandbox/prototype/exec/java-exec/src/main/codegen/ValueVectors/templates/RepeatedValueVectors.java
----------------------------------------------------------------------
diff --git a/sandbox/prototype/exec/java-exec/src/main/codegen/ValueVectors/templates/RepeatedValueVectors.java b/sandbox/prototype/exec/java-exec/src/main/codegen/ValueVectors/templates/RepeatedValueVectors.java
index 26564c1..79f05b6 100644
--- a/sandbox/prototype/exec/java-exec/src/main/codegen/ValueVectors/templates/RepeatedValueVectors.java
+++ b/sandbox/prototype/exec/java-exec/src/main/codegen/ValueVectors/templates/RepeatedValueVectors.java
@@ -59,7 +59,7 @@ import com.google.common.collect.Lists;
     return values.getValueCapacity();
   }
   
-  int getBufferSize(){
+  public int getBufferSize(){
     return offsets.getBufferSize() + values.getBufferSize();
   }
   

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/db3afaa8/sandbox/prototype/exec/java-exec/src/main/codegen/ValueVectors/templates/VariableLengthVectors.java
----------------------------------------------------------------------
diff --git a/sandbox/prototype/exec/java-exec/src/main/codegen/ValueVectors/templates/VariableLengthVectors.java b/sandbox/prototype/exec/java-exec/src/main/codegen/ValueVectors/templates/VariableLengthVectors.java
index 95965f7..4492aa9 100644
--- a/sandbox/prototype/exec/java-exec/src/main/codegen/ValueVectors/templates/VariableLengthVectors.java
+++ b/sandbox/prototype/exec/java-exec/src/main/codegen/ValueVectors/templates/VariableLengthVectors.java
@@ -49,7 +49,10 @@ public final class ${minor.class}Vector extends BaseDataValueVector implements V
     this.offsetVector = new UInt${type.width}Vector(null, allocator);
   }
 
-
+  public int getBufferSize(){
+    return offsetVector.getBufferSize() + data.writerIndex();
+  }
+  
   int getSizeFromCount(int valueCount) {
     return valueCount * ${type.width};
   }

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/db3afaa8/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/CodeGenerator.java
----------------------------------------------------------------------
diff --git a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/CodeGenerator.java b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/CodeGenerator.java
index 67ca614..9895782 100644
--- a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/CodeGenerator.java
+++ b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/CodeGenerator.java
@@ -12,14 +12,18 @@ import org.apache.drill.exec.exception.SchemaChangeException;
 import org.apache.drill.exec.expr.fn.FunctionImplementationRegistry;
 import org.apache.drill.exec.ops.FragmentContext;
 import org.apache.drill.exec.record.RecordBatch;
+import org.apache.drill.exec.record.TypedFieldId;
+import org.apache.drill.exec.record.VectorWrapper;
 import org.apache.drill.exec.vector.TypeHelper;
 
 import com.google.common.base.Preconditions;
 import com.sun.codemodel.JBlock;
+import com.sun.codemodel.JClass;
 import com.sun.codemodel.JClassAlreadyExistsException;
 import com.sun.codemodel.JCodeModel;
 import com.sun.codemodel.JDefinedClass;
 import com.sun.codemodel.JExpr;
+import com.sun.codemodel.JExpression;
 import com.sun.codemodel.JFieldRef;
 import com.sun.codemodel.JMethod;
 import com.sun.codemodel.JMod;
@@ -61,11 +65,42 @@ public class CodeGenerator<T> {
   }
   
 
+  public JVar declareVectorValueSetupAndMember(String batchName, TypedFieldId fieldId){
+    Class<?> valueVectorClass = TypeHelper.getValueVectorClass(fieldId.getType().getMinorType(), fieldId.getType().getMode());
+    JClass vvClass = model.ref(valueVectorClass);
+    JClass retClass = vvClass;
+    String vectorAccess = "getValueVector";
+    if(fieldId.isHyperReader()){
+      retClass = retClass.array();
+      vectorAccess = "getValueVectors";
+    }
+    
+    JVar vv = declareClassField("vv", retClass);
+    JClass t = model.ref(SchemaChangeException.class);
+    JType wrapperClass = model.ref(VectorWrapper.class);
+    JType objClass = model.ref(Object.class);
+    JBlock b = getSetupBlock();
+    JVar obj = b.decl( //
+        objClass, //
+        getNextVar("tmp"), // 
+        JExpr.direct(batchName)
+          .invoke("getValueAccessorById") //
+          .arg(JExpr.lit(fieldId.getFieldId())) //
+          .arg( vvClass.dotclass())
+          .invoke(vectorAccess)//
+          );
+        
+        b._if(obj.eq(JExpr._null()))._then()._throw(JExpr._new(t).arg(JExpr.lit(String.format("Failure while loading vector %s with id: %s.", vv.name(), fieldId.toString()))));
+        //b.assign(vv, JExpr.cast(retClass, ((JExpression) JExpr.cast(wrapperClass, obj) ).invoke(vectorAccess)));
+        b.assign(vv, JExpr.cast(retClass, obj ));
+        
+    return vv;
+  }
 
-  public void addExpr(LogicalExpression ex){
+  public HoldingContainer addExpr(LogicalExpression ex){
     logger.debug("Adding next write {}", ex);
     rotateBlock();
-    ex.accept(evaluationVisitor, this);
+    return ex.accept(evaluationVisitor, this);
   }
   
   public void rotateBlock(){

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/db3afaa8/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/EvaluationVisitor.java
----------------------------------------------------------------------
diff --git a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/EvaluationVisitor.java b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/EvaluationVisitor.java
index 03a2a6b..93d5b5b 100644
--- a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/EvaluationVisitor.java
+++ b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/EvaluationVisitor.java
@@ -1,7 +1,5 @@
 package org.apache.drill.exec.expr;
 
-import com.google.common.base.Charsets;
-import com.sun.codemodel.*;
 import org.apache.drill.common.expression.FunctionCall;
 import org.apache.drill.common.expression.IfExpression;
 import org.apache.drill.common.expression.IfExpression.IfCondition;
@@ -13,15 +11,17 @@ import org.apache.drill.common.expression.ValueExpressions.LongExpression;
 import org.apache.drill.common.expression.ValueExpressions.QuotedString;
 import org.apache.drill.common.expression.visitors.AbstractExprVisitor;
 import org.apache.drill.common.types.TypeProtos;
-import org.apache.drill.common.types.Types;
 import org.apache.drill.exec.expr.CodeGenerator.HoldingContainer;
 import org.apache.drill.exec.expr.fn.FunctionHolder;
 import org.apache.drill.exec.expr.fn.FunctionImplementationRegistry;
 import org.apache.drill.exec.physical.impl.filter.ReturnValueExpression;
-import org.apache.drill.exec.record.selection.SelectionVector2;
-import org.apache.drill.exec.vector.TypeHelper;
 
-import com.google.common.base.Preconditions;
+import com.sun.codemodel.JBlock;
+import com.sun.codemodel.JConditional;
+import com.sun.codemodel.JExpr;
+import com.sun.codemodel.JExpression;
+import com.sun.codemodel.JInvocation;
+import com.sun.codemodel.JVar;
 
 public class EvaluationVisitor extends AbstractExprVisitor<HoldingContainer, CodeGenerator<?>, RuntimeException> {
 
@@ -122,7 +122,7 @@ public class EvaluationVisitor extends AbstractExprVisitor<HoldingContainer, Cod
   @Override
   public HoldingContainer visitUnknown(LogicalExpression e, CodeGenerator<?> generator) throws RuntimeException {
     if(e instanceof ValueVectorReadExpression){
-      return visitValueVectorExpression((ValueVectorReadExpression) e, generator);
+      return visitValueVectorReadExpression((ValueVectorReadExpression) e, generator);
     }else if(e instanceof ValueVectorWriteExpression){
       return visitValueVectorWriteExpression((ValueVectorWriteExpression) e, generator);
     }else if(e instanceof ReturnValueExpression){
@@ -138,16 +138,7 @@ public class EvaluationVisitor extends AbstractExprVisitor<HoldingContainer, Cod
     HoldingContainer hc = child.accept(this, generator);
     JBlock block = generator.getBlock();
     
-    Class<?> vvClass = TypeHelper.getValueVectorClass(child.getMajorType().getMinorType(), child.getMajorType().getMode());
-    JType vvType = generator.getModel()._ref(vvClass);
-    JVar vv = generator.declareClassField("vv", vvType);
-    
-    // get value vector in setup block.
-    JVar obj = generator.getSetupBlock().decl( //
-        generator.getModel()._ref(Object.class), //
-        generator.getNextVar("obj"), // 
-        JExpr.direct("outgoing").invoke("getValueVectorById").arg(JExpr.lit(e.getFieldId())).arg( ((JClass)vvType).dotclass()));
-    generator.getSetupBlock().assign(vv, JExpr.cast(vvType, obj));
+    JVar vv = generator.declareVectorValueSetupAndMember("outgoing", e.getFieldId());
     
     if(hc.isOptional()){
       vv.invoke("getMutator").invoke("set").arg(JExpr.direct("outIndex"));
@@ -162,42 +153,42 @@ public class EvaluationVisitor extends AbstractExprVisitor<HoldingContainer, Cod
     return null;
   }
   
-  private HoldingContainer visitValueVectorExpression(ValueVectorReadExpression e, CodeGenerator<?> generator) throws RuntimeException{
+  private HoldingContainer visitValueVectorReadExpression(ValueVectorReadExpression e, CodeGenerator<?> generator) throws RuntimeException{
     // declare value vector
-    Class<?> vvClass = TypeHelper.getValueVectorClass(e.getMajorType().getMinorType(), e.getMajorType().getMode());
-    JType vvType = generator.getModel()._ref(vvClass);
-    JVar vv1 = generator.declareClassField("vv", vvType);
     
-    // get value vector from incoming batch and 
-    // get value vector in setup block.
-    JVar obj = generator.getSetupBlock().decl( //
-        generator.getModel()._ref(Object.class), //
-        generator.getNextVar("obj"), // 
-        JExpr.direct("incoming").invoke("getValueVectorById").arg(JExpr.lit(e.getFieldId())).arg( ((JClass)vvType).dotclass()));
-    generator.getSetupBlock().assign(vv1, JExpr.cast(vvType, obj));
-
+    JVar vv1 = generator.declareVectorValueSetupAndMember("incoming", e.getFieldId());
+    final String indexVariableName = e.isNamed() ? e.getIndexVariableName() : "inIndex";
+    JExpression indexVariable = JExpr.direct(indexVariableName);
+    
+    JInvocation getValueAccessor = vv1.invoke("getAccessor").invoke("get");
+    if(e.isSuperReader()){
+      
+      getValueAccessor = ((JExpression) vv1.component(indexVariable.shrz(JExpr.lit(16)))).invoke("getAccessor").invoke("get");
+      indexVariable = indexVariable.band(JExpr.lit((int) Character.MAX_VALUE));
+    }
+    
+    
     // evaluation work.
     HoldingContainer out = generator.declare(e.getMajorType());
     
-    
     if(out.isOptional()){
       JBlock blk = generator.getBlock();
-      blk.assign(out.getIsSet(), vv1.invoke("getAccessor").invoke("isSet").arg(JExpr.direct("inIndex")));
+      blk.assign(out.getIsSet(), vv1.invoke("getAccessor").invoke("isSet").arg(indexVariable));
       JConditional jc = blk._if(out.getIsSet().eq(JExpr.lit(1)));
       if (e.getMajorType().getMinorType() == TypeProtos.MinorType.VARCHAR ||
           e.getMajorType().getMinorType() == TypeProtos.MinorType.VARBINARY) {
         jc._then()
-            .add(vv1.invoke("getAccessor").invoke("get").arg(JExpr.direct("inIndex")).arg(out.getHolder()));
+            .add(getValueAccessor.arg(JExpr.direct("inIndex")).arg(out.getHolder()));
       } else {
         jc._then()
-            .assign(out.getValue(), vv1.invoke("getAccessor").invoke("get").arg(JExpr.direct("inIndex")));
+            .assign(out.getValue(), getValueAccessor.arg(indexVariable));
       }
     }else{
       if (e.getMajorType().getMinorType() == TypeProtos.MinorType.VARCHAR ||
           e.getMajorType().getMinorType() == TypeProtos.MinorType.VARBINARY) {
-        generator.getBlock().add(vv1.invoke("getAccessor").invoke("get").arg(JExpr.direct("inIndex")).arg(out.getHolder()));
+        generator.getBlock().add(getValueAccessor.arg(indexVariable).arg(out.getHolder()));
       } else {
-        generator.getBlock().assign(out.getValue(), vv1.invoke("getAccessor").invoke("get").arg(JExpr.direct("inIndex")));
+        generator.getBlock().assign(out.getValue(), getValueAccessor.arg(indexVariable));
       }
     }
     return out;
@@ -215,6 +206,7 @@ public class EvaluationVisitor extends AbstractExprVisitor<HoldingContainer, Cod
   @Override
   public HoldingContainer visitQuotedStringConstant(QuotedString e, CodeGenerator<?> CodeGenerator) throws RuntimeException {
     throw new UnsupportedOperationException("We don't yet support string literals as we need to build the string value holders.");
+    
 //    JExpr stringLiteral = JExpr.lit(e.value);
 //    CodeGenerator.block.decl(stringLiteral.invoke("getBytes").arg(JExpr.ref(Charsets.UTF_8));
   }

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/db3afaa8/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/ExpressionTreeMaterializer.java
----------------------------------------------------------------------
diff --git a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/ExpressionTreeMaterializer.java b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/ExpressionTreeMaterializer.java
index 72e5c93..07db72c 100644
--- a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/ExpressionTreeMaterializer.java
+++ b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/ExpressionTreeMaterializer.java
@@ -30,7 +30,7 @@ import org.apache.drill.common.expression.ValueExpressions;
 import org.apache.drill.common.expression.visitors.SimpleExprVisitor;
 import org.apache.drill.exec.record.NullExpression;
 import org.apache.drill.exec.record.RecordBatch;
-import org.apache.drill.exec.record.RecordBatch.TypedFieldId;
+import org.apache.drill.exec.record.TypedFieldId;
 
 import com.google.common.collect.Lists;
 

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/db3afaa8/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/ValueVectorReadExpression.java
----------------------------------------------------------------------
diff --git a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/ValueVectorReadExpression.java b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/ValueVectorReadExpression.java
index b1888d6..f86bd29 100644
--- a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/ValueVectorReadExpression.java
+++ b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/ValueVectorReadExpression.java
@@ -4,19 +4,42 @@ import org.apache.drill.common.expression.ExpressionPosition;
 import org.apache.drill.common.expression.LogicalExpression;
 import org.apache.drill.common.expression.visitors.ExprVisitor;
 import org.apache.drill.common.types.TypeProtos.MajorType;
-import org.apache.drill.exec.record.RecordBatch.TypedFieldId;
+import org.apache.drill.exec.record.TypedFieldId;
 
 public class ValueVectorReadExpression implements LogicalExpression{
   static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ValueVectorReadExpression.class);
 
   private final MajorType type;
-  private final int fieldId;
+  private final TypedFieldId fieldId;
+  private final boolean superReader;
+  private final String indexVariableName;
   
-  public ValueVectorReadExpression(TypedFieldId tfId) {
+  public ValueVectorReadExpression(TypedFieldId tfId){
+    this(tfId, null);
+  }
+  
+  public ValueVectorReadExpression(TypedFieldId tfId, String indexVariableName) {
     this.type = tfId.getType();
-    this.fieldId = tfId.getFieldId();
+    this.fieldId = tfId;
+    this.superReader = tfId.isHyperReader();
+    this.indexVariableName = indexVariableName;
   }
 
+  public boolean isNamed(){
+    return indexVariableName != null;
+  }
+  
+  public String getIndexVariableName(){
+    return indexVariableName;
+  }
+  
+  public TypedFieldId getTypedFieldId(){
+    return fieldId;
+  }
+  
+  public boolean isSuperReader(){
+    return superReader;
+  }
   @Override
   public MajorType getMajorType() {
     return type;
@@ -27,7 +50,7 @@ public class ValueVectorReadExpression implements LogicalExpression{
     return visitor.visitUnknown(this, value);
   }
 
-  public int getFieldId() {
+  public TypedFieldId getFieldId() {
     return fieldId;
   }
 

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/db3afaa8/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/ValueVectorWriteExpression.java
----------------------------------------------------------------------
diff --git a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/ValueVectorWriteExpression.java b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/ValueVectorWriteExpression.java
index 417b975..58141d8 100644
--- a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/ValueVectorWriteExpression.java
+++ b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/ValueVectorWriteExpression.java
@@ -5,19 +5,26 @@ import org.apache.drill.common.expression.LogicalExpression;
 import org.apache.drill.common.expression.visitors.ExprVisitor;
 import org.apache.drill.common.types.TypeProtos.MajorType;
 import org.apache.drill.common.types.Types;
+import org.apache.drill.exec.record.TypedFieldId;
 
 public class ValueVectorWriteExpression implements LogicalExpression {
   static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ValueVectorWriteExpression.class);
 
-  private final int fieldId;
+  private final TypedFieldId fieldId;
   private final LogicalExpression child;
+  private final String indexVariableName;
   
-  public ValueVectorWriteExpression(int fieldId, LogicalExpression child){
+  public ValueVectorWriteExpression(TypedFieldId fieldId, LogicalExpression child){
+    this(fieldId, child, null);
+  }
+  
+  public ValueVectorWriteExpression(TypedFieldId fieldId, LogicalExpression child, String indexVariableName){
     this.fieldId = fieldId;
     this.child = child;
+    this.indexVariableName = indexVariableName;
   }
   
-  public int getFieldId() {
+  public TypedFieldId getFieldId() {
     return fieldId;
   }
 

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/db3afaa8/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/fn/impl/Alternator.java
----------------------------------------------------------------------
diff --git a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/fn/impl/Alternator.java b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/fn/impl/Alternator.java
index 0915fa3..d2bcaa2 100644
--- a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/fn/impl/Alternator.java
+++ b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/fn/impl/Alternator.java
@@ -16,24 +16,48 @@ import org.apache.drill.exec.vector.BigIntHolder;
 
 
 
-@FunctionTemplate(name = "alternate", scope = FunctionScope.SIMPLE)
-public class Alternator implements DrillFunc{
-
-  @Workspace int val;
-  @Output BigIntHolder out;
+public class Alternator {
   
-  public void setup(RecordBatch incoming) {
-    val = 0;
-  }
+  @FunctionTemplate(name = "alternate", scope = FunctionScope.SIMPLE)
+  public static class Alternate2 implements DrillFunc{
+    @Workspace int val;
+    @Output BigIntHolder out;
+    
+    public void setup(RecordBatch incoming) {
+      val = 0;
+    }
+
 
+    public void eval() {
+      out.value = val;
+      if(val == 0){
+        val = 1;
+      }else{
+        val = 0;
+      }
+    }
+  }
 
-  public void eval() {
-    out.value = val;
-    if(val == 0){
-      val = 1;
-    }else{
+  @FunctionTemplate(name = "alternate3", scope = FunctionScope.SIMPLE)
+  public static class Alternate3 implements DrillFunc{
+    @Workspace int val;
+    @Output BigIntHolder out;
+    
+    public void setup(RecordBatch incoming) {
       val = 0;
     }
+
+
+    public void eval() {
+      out.value = val;
+      if(val == 0){
+        val = 1;
+      }else if(val == 1){
+        val = 2;
+      }else{
+        val = 0;
+      }
+    }
   }
   
   public static class Provider implements CallProvider{
@@ -41,7 +65,8 @@ public class Alternator implements DrillFunc{
     @Override
     public FunctionDefinition[] getFunctionDefintions() {
       return new FunctionDefinition[]{
-          FunctionDefinition.simple("alternate", NoArgValidator.VALIDATOR, new OutputTypeDeterminer.FixedType(Types.required(MinorType.BIGINT)), "alternate")
+          FunctionDefinition.simple("alternate", NoArgValidator.VALIDATOR, new OutputTypeDeterminer.FixedType(Types.required(MinorType.BIGINT)), "alternate"),
+          FunctionDefinition.simple("alternate3", NoArgValidator.VALIDATOR, new OutputTypeDeterminer.FixedType(Types.required(MinorType.BIGINT)), "alternate3")
       };
     }
     

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/db3afaa8/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/fn/impl/ComparatorFunctions.java
----------------------------------------------------------------------
diff --git a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/fn/impl/ComparatorFunctions.java b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/fn/impl/ComparatorFunctions.java
new file mode 100644
index 0000000..471bdf0
--- /dev/null
+++ b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/expr/fn/impl/ComparatorFunctions.java
@@ -0,0 +1,58 @@
+package org.apache.drill.exec.expr.fn.impl;
+
+import org.apache.drill.common.expression.ArgumentValidators;
+import org.apache.drill.common.expression.CallProvider;
+import org.apache.drill.common.expression.FunctionDefinition;
+import org.apache.drill.common.expression.OutputTypeDeterminer;
+import org.apache.drill.common.types.TypeProtos.MinorType;
+import org.apache.drill.common.types.Types;
+import org.apache.drill.exec.expr.DrillFunc;
+import org.apache.drill.exec.expr.annotations.FunctionTemplate;
+import org.apache.drill.exec.expr.annotations.Output;
+import org.apache.drill.exec.expr.annotations.Param;
+import org.apache.drill.exec.record.RecordBatch;
+import org.apache.drill.exec.vector.BigIntHolder;
+import org.apache.drill.exec.vector.IntHolder;
+
+public class ComparatorFunctions {
+  static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ComparatorFunctions.class);
+  
+  @FunctionTemplate(name = "compare_to", scope = FunctionTemplate.FunctionScope.SIMPLE)
+  public static class IntComparator implements DrillFunc {
+
+      @Param IntHolder left;
+      @Param IntHolder right;
+      @Output IntHolder out;
+
+      public void setup(RecordBatch b) {}
+
+      public void eval() {
+        out.value = left.value < right.value ? -1 : ((left.value == right.value)? 0 : 1);
+      }
+  }
+  
+  @FunctionTemplate(name = "compare_to", scope = FunctionTemplate.FunctionScope.SIMPLE)
+  public static class Long implements DrillFunc {
+
+      @Param BigIntHolder left;
+      @Param BigIntHolder right;
+      @Output IntHolder out;
+
+      public void setup(RecordBatch b) {}
+
+      public void eval() {
+        out.value = left.value < right.value ? -1 : ((left.value == right.value)? 0 : 1);
+      }
+  }
+  public static final FunctionDefinition COMPARE_TO = FunctionDefinition.simple("compare_to", new ArgumentValidators.AllowedTypeList(2, Types.required(MinorType.INT)), new OutputTypeDeterminer.FixedType(Types.required(MinorType.INT)));
+  public static class Provider implements CallProvider{
+
+    @Override
+    public FunctionDefinition[] getFunctionDefintions() {
+      return new FunctionDefinition[]{
+          COMPARE_TO
+      };
+    }
+    
+  }
+}

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/db3afaa8/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/ops/FragmentContext.java
----------------------------------------------------------------------
diff --git a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/ops/FragmentContext.java b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/ops/FragmentContext.java
index 64f3eb4..bbe4cfb 100644
--- a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/ops/FragmentContext.java
+++ b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/ops/FragmentContext.java
@@ -19,16 +19,13 @@ package org.apache.drill.exec.ops;
 
 import java.io.IOException;
 
-import org.apache.drill.common.expression.LogicalExpression;
 import org.apache.drill.exec.compile.ClassTransformer;
 import org.apache.drill.exec.compile.QueryClassLoader;
-import org.apache.drill.exec.compile.TemplateClassDefinition;
 import org.apache.drill.exec.exception.ClassTransformationException;
 import org.apache.drill.exec.expr.CodeGenerator;
 import org.apache.drill.exec.expr.fn.FunctionImplementationRegistry;
 import org.apache.drill.exec.memory.BufferAllocator;
 import org.apache.drill.exec.metrics.SingleThreadNestedCounter;
-import org.apache.drill.exec.physical.impl.FilteringRecordBatchTransformer;
 import org.apache.drill.exec.proto.CoordinationProtos.DrillbitEndpoint;
 import org.apache.drill.exec.proto.ExecProtos.FragmentHandle;
 import org.apache.drill.exec.proto.ExecProtos.FragmentStatus;
@@ -106,7 +103,7 @@ public class FragmentContext {
   public <T> T getImplementationClass(CodeGenerator<T> cg) throws ClassTransformationException, IOException{
     long t1 = System.nanoTime();
     T t= transformer.getImplementationClass(this.loader, cg.getDefinition(), cg.generate(), cg.getMaterializedClassName());
-    logger.debug("Compile time: {} micros.", (System.nanoTime() - t1)/1000/1000 );
+    logger.debug("Compile time: {} millis.", (System.nanoTime() - t1)/1000/1000 );
     return t;
     
   }

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/db3afaa8/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/base/Sender.java
----------------------------------------------------------------------
diff --git a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/base/Sender.java b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/base/Sender.java
index 71513c7..77d3f69 100644
--- a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/base/Sender.java
+++ b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/base/Sender.java
@@ -41,4 +41,5 @@ public interface Sender extends FragmentRoot {
    */
   @JsonProperty("receiver-major-fragment")
   public int getOppositeMajorFragmentId();
+
 }

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/db3afaa8/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/FilterRecordBatch.java
----------------------------------------------------------------------
diff --git a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/FilterRecordBatch.java b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/FilterRecordBatch.java
deleted file mode 100644
index acabe30..0000000
--- a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/FilterRecordBatch.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*******************************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- * http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- ******************************************************************************/
-package org.apache.drill.exec.physical.impl;
-
-import org.apache.drill.common.expression.SchemaPath;
-import org.apache.drill.exec.ops.FragmentContext;
-import org.apache.drill.exec.record.BatchSchema;
-import org.apache.drill.exec.record.RecordBatch;
-import org.apache.drill.exec.record.WritableBatch;
-import org.apache.drill.exec.record.selection.SelectionVector2;
-import org.apache.drill.exec.record.selection.SelectionVector4;
-import org.apache.drill.exec.vector.ValueVector;
-
-public abstract class FilterRecordBatch implements RecordBatch {
-  static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(FilterRecordBatch.class);
-
-  private RecordBatch incoming;
-  private SelectionVector2 selectionVector;
-  private BatchSchema schema;
-  private FilteringRecordBatchTransformer transformer;
-  private int outstanding;
-
-  public FilterRecordBatch(RecordBatch batch) {
-    this.incoming = batch;
-  }
-
-  @Override
-  public FragmentContext getContext() {
-    return incoming.getContext();
-  }
-
-  @Override
-  public BatchSchema getSchema() {
-    return schema;
-  }
-
-  @Override
-  public int getRecordCount() {
-    return 0;
-  }
-
-  @Override
-  public void kill() {
-    incoming.kill();
-  }
-
-
-  @Override
-  public SelectionVector2 getSelectionVector2() {
-    return null;
-  }
-
-  @Override
-  public SelectionVector4 getSelectionVector4() {
-    return null;
-  }
-
-  @Override
-  public TypedFieldId getValueVectorId(SchemaPath path) {
-    return null;
-  }
-
-  @Override
-  public <T extends ValueVector> T getValueVectorById(int fieldId, Class<?> vvClass) {
-    return null;
-  }
-
-  public WritableBatch getWritableBatch() {
-    return null;
-  }
-
-  abstract int applyFilter(SelectionVector2 vector, int count);
-
-  /**
-   * Release all assets.
-   */
-  private void close() {
-
-  }
-
-  @Override
-  public IterOutcome next() {
-    while (true) {
-      IterOutcome o = incoming.next();
-      switch (o) {
-      case OK_NEW_SCHEMA:
-        transformer = null;
-        schema = transformer.getSchema();
-        // fall through to ok.
-      case OK:
-
-      case NONE:
-      case STOP:
-        close();
-        return IterOutcome.STOP;
-      }
-
-      if (outstanding > 0) {
-        // move data to output location.
-
-        for (int i = incoming.getRecordCount() - outstanding; i < incoming.getRecordCount(); i++) {
-
-        }
-      }
-
-//      // make sure the bit vector is as large as the current record batch.
-//      if (selectionVector.capacity() < incoming.getRecordCount()) {
-//        selectionVector.allocateNew(incoming.getRecordCount());
-//      }
-
-      return null;
-    }
-
-  }
-}

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/db3afaa8/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/FilteringRecordBatchTransformer.java
----------------------------------------------------------------------
diff --git a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/FilteringRecordBatchTransformer.java b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/FilteringRecordBatchTransformer.java
deleted file mode 100644
index 0813481..0000000
--- a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/FilteringRecordBatchTransformer.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*******************************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- * http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- ******************************************************************************/
-package org.apache.drill.exec.physical.impl;
-
-import org.apache.drill.exec.record.BatchSchema;
-import org.apache.drill.exec.record.RecordBatch;
-import org.apache.drill.exec.record.selection.SelectionVector2;
-
-public abstract class FilteringRecordBatchTransformer {
-  static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(FilteringRecordBatchTransformer.class);
-  
-  final RecordBatch incoming;
-  final SelectionVector2 selectionVector;
-  final BatchSchema schema;
-  
-  public FilteringRecordBatchTransformer(RecordBatch incoming, OutputMutator output, SelectionVector2 selectionVector) {
-    super();
-    this.incoming = incoming;
-    this.selectionVector = selectionVector;
-    this.schema = innerSetup();
-  }
-
-  public abstract BatchSchema innerSetup();
-  
-  /**
-   * Applies the filter to the selection index.  Ignores any values in the selection vector, instead creating a.
-   * @return
-   */
-  public abstract int apply();
-  
-  /**
-   * Applies the filter to the selection index.  Utilizes the existing selection index and only evaluates on those records.
-   * @return
-   */
-  public abstract int applyWithSelection();
-
-  public BatchSchema getSchema() {
-    return schema;
-  }
-  
-  
-  
-}

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/db3afaa8/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/ImplCreator.java
----------------------------------------------------------------------
diff --git a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/ImplCreator.java b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/ImplCreator.java
index 7740955..c31e9e4 100644
--- a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/ImplCreator.java
+++ b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/ImplCreator.java
@@ -34,8 +34,10 @@ import org.apache.drill.exec.physical.config.RandomReceiver;
 import org.apache.drill.exec.physical.config.Screen;
 import org.apache.drill.exec.physical.config.SelectionVectorRemover;
 import org.apache.drill.exec.physical.config.SingleSender;
+import org.apache.drill.exec.physical.config.Sort;
 import org.apache.drill.exec.physical.impl.filter.FilterBatchCreator;
 import org.apache.drill.exec.physical.impl.project.ProjectBatchCreator;
+import org.apache.drill.exec.physical.impl.sort.SortBatchCreator;
 import org.apache.drill.exec.physical.impl.svremover.SVRemoverCreator;
 import org.apache.drill.exec.record.RecordBatch;
 
@@ -52,6 +54,7 @@ public class ImplCreator extends AbstractPhysicalVisitor<RecordBatch, FragmentCo
   private ProjectBatchCreator pbc = new ProjectBatchCreator();
   private FilterBatchCreator fbc = new FilterBatchCreator();
   private SVRemoverCreator svc = new SVRemoverCreator();
+  private SortBatchCreator sbc = new SortBatchCreator();
   private RootExec root = null;
   
   private ImplCreator(){}
@@ -88,6 +91,12 @@ public class ImplCreator extends AbstractPhysicalVisitor<RecordBatch, FragmentCo
     }
   }
 
+  
+  @Override
+  public RecordBatch visitSort(Sort sort, FragmentContext context) throws ExecutionSetupException {
+    return sbc.getBatch(context, sort, getChildren(sort, context));
+  }
+
   @Override
   public RecordBatch visitScreen(Screen op, FragmentContext context) throws ExecutionSetupException {
     Preconditions.checkArgument(root == null);

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/db3afaa8/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/RootExec.java
----------------------------------------------------------------------
diff --git a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/RootExec.java b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/RootExec.java
index 3f8aac7..9bcfe10 100644
--- a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/RootExec.java
+++ b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/RootExec.java
@@ -17,7 +17,6 @@
  ******************************************************************************/
 package org.apache.drill.exec.physical.impl;
 
-import org.apache.drill.exec.exception.FragmentSetupException;
 
 /**
  * A FragmentRoot is a node which is the last processing node in a query plan. FragmentTerminals include Exchange

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/db3afaa8/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/ScanBatch.java
----------------------------------------------------------------------
diff --git a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/ScanBatch.java b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/ScanBatch.java
index a8a62ca..5a543b0 100644
--- a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/ScanBatch.java
+++ b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/ScanBatch.java
@@ -18,7 +18,6 @@
 package org.apache.drill.exec.physical.impl;
 
 import java.util.Iterator;
-import java.util.List;
 import java.util.Map;
 
 import org.apache.drill.common.exceptions.ExecutionSetupException;
@@ -29,13 +28,15 @@ import org.apache.drill.exec.record.BatchSchema;
 import org.apache.drill.exec.record.MaterializedField;
 import org.apache.drill.exec.record.RecordBatch;
 import org.apache.drill.exec.record.SchemaBuilder;
+import org.apache.drill.exec.record.TypedFieldId;
+import org.apache.drill.exec.record.VectorContainer;
+import org.apache.drill.exec.record.VectorWrapper;
 import org.apache.drill.exec.record.WritableBatch;
 import org.apache.drill.exec.record.selection.SelectionVector2;
 import org.apache.drill.exec.record.selection.SelectionVector4;
 import org.apache.drill.exec.store.RecordReader;
 import org.apache.drill.exec.vector.ValueVector;
 
-import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
 
 /**
@@ -44,10 +45,9 @@ import com.google.common.collect.Maps;
 public class ScanBatch implements RecordBatch {
   static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ScanBatch.class);
 
-  final List<ValueVector> vectors = Lists.newLinkedList();
   final Map<MaterializedField, ValueVector> fieldVectorMap = Maps.newHashMap();
 
-  private VectorHolder holder = new VectorHolder(vectors);
+  private VectorContainer holder = new VectorContainer();
   private BatchSchema schema;
   private int recordCount;
   private boolean schemaChanged = true;
@@ -91,9 +91,7 @@ public class ScanBatch implements RecordBatch {
   }
 
   private void releaseAssets() {
-    for (ValueVector v : vectors) {
-      v.close();
-    }
+    holder.clear();
   }
 
   @Override
@@ -139,10 +137,12 @@ public class ScanBatch implements RecordBatch {
   }
 
   @Override
-  public <T extends ValueVector> T getValueVectorById(int fieldId, Class<?> clazz) {
-    return holder.getValueVector(fieldId, clazz);
+  public VectorWrapper<?> getValueAccessorById(int fieldId, Class<?> clazz) {
+    return holder.getVectorAccessor(fieldId, clazz);
   }
 
+
+
   private class Mutator implements OutputMutator {
     private SchemaBuilder builder = BatchSchema.newBuilder();
 
@@ -150,12 +150,12 @@ public class ScanBatch implements RecordBatch {
       schemaChanged();
       ValueVector vector = fieldVectorMap.remove(field);
       if (vector == null) throw new SchemaChangeException("Failure attempting to remove an unknown field.");
-      vectors.remove(vector);
+      holder.remove(vector);
       vector.close();
     }
 
     public void addField(ValueVector vector) {
-      vectors.add(vector);
+      holder.add(vector);
       fieldVectorMap.put(vector.getField(), vector);
       builder.addField(vector.getField());
     }
@@ -169,8 +169,8 @@ public class ScanBatch implements RecordBatch {
   }
 
   @Override
-  public Iterator<ValueVector> iterator() {
-    return vectors.iterator();
+  public Iterator<VectorWrapper<?>> iterator() {
+    return holder.iterator();
   }
 
   @Override

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/db3afaa8/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/ScreenCreator.java
----------------------------------------------------------------------
diff --git a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/ScreenCreator.java b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/ScreenCreator.java
index 516b5af..5c5e2e5 100644
--- a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/ScreenCreator.java
+++ b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/ScreenCreator.java
@@ -17,8 +17,6 @@
  ******************************************************************************/
 package org.apache.drill.exec.physical.impl;
 
-import io.netty.buffer.ByteBuf;
-
 import java.util.List;
 
 import org.apache.drill.exec.ops.FragmentContext;
@@ -27,7 +25,6 @@ import org.apache.drill.exec.physical.impl.materialize.QueryWritableBatch;
 import org.apache.drill.exec.physical.impl.materialize.RecordMaterializer;
 import org.apache.drill.exec.physical.impl.materialize.VectorRecordMaterializer;
 import org.apache.drill.exec.proto.GeneralRPCProtos.Ack;
-import org.apache.drill.exec.proto.UserBitShared.DrillPBError;
 import org.apache.drill.exec.proto.UserBitShared.RecordBatchDef;
 import org.apache.drill.exec.proto.UserProtos.QueryResult;
 import org.apache.drill.exec.record.RecordBatch;
@@ -45,6 +42,7 @@ public class ScreenCreator implements RootCreator<Screen>{
   
   @Override
   public RootExec getRoot(FragmentContext context, Screen config, List<RecordBatch> children) {
+    Preconditions.checkNotNull(children);
     Preconditions.checkArgument(children.size() == 1);
     return new ScreenRoot(context, children.iterator().next());
   }

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/db3afaa8/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/SingleSenderCreator.java
----------------------------------------------------------------------
diff --git a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/SingleSenderCreator.java b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/SingleSenderCreator.java
index 231bc6c..bad3a03 100644
--- a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/SingleSenderCreator.java
+++ b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/SingleSenderCreator.java
@@ -76,8 +76,8 @@ public class SingleSenderCreator implements RootCreator<SingleSender>{
         tunnel.sendRecordBatch(new RecordSendFailure(), context, b2);
         return false;
 
-      case OK:
       case OK_NEW_SCHEMA:
+      case OK:
         FragmentWritableBatch batch = new FragmentWritableBatch(false, handle.getQueryId(), handle.getMajorFragmentId(), handle.getMinorFragmentId(), recMajor, 0, incoming.getWritableBatch());
         tunnel.sendRecordBatch(new RecordSendFailure(), context, batch);
         return true;

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/db3afaa8/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/VectorHolder.java
----------------------------------------------------------------------
diff --git a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/VectorHolder.java b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/VectorHolder.java
deleted file mode 100644
index 65a7365..0000000
--- a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/VectorHolder.java
+++ /dev/null
@@ -1,39 +0,0 @@
-package org.apache.drill.exec.physical.impl;
-
-import java.util.List;
-
-import org.apache.drill.common.expression.SchemaPath;
-import org.apache.drill.exec.record.RecordBatch.TypedFieldId;
-import org.apache.drill.exec.vector.ValueVector;
-
-public class VectorHolder {
-  static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(VectorHolder.class);
-  
-  private List<ValueVector> vectors;
-
-  public VectorHolder(List<ValueVector> vectors) {
-    super();
-    this.vectors = vectors;
-  }
-  
-  public TypedFieldId getValueVector(SchemaPath path) {
-    for(int i =0; i < vectors.size(); i++){
-      ValueVector vv = vectors.get(i);
-      if(vv.getField().matches(path)) return new TypedFieldId(vv.getField().getType(), i); 
-    }
-    return null;
-  }
-  
-  @SuppressWarnings("unchecked")
-  public <T extends ValueVector> T getValueVector(int fieldId, Class<?> clazz) {
-    ValueVector v = vectors.get(fieldId);
-    assert v != null;
-    if (v.getClass() != clazz){
-      logger.warn(String.format(
-          "Failure while reading vector.  Expected vector class of %s but was holding vector class %s.",
-          clazz.getCanonicalName(), v.getClass().getCanonicalName()));
-      return null;
-    }
-    return (T) v;
-  }
-}

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/db3afaa8/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/WireRecordBatch.java
----------------------------------------------------------------------
diff --git a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/WireRecordBatch.java b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/WireRecordBatch.java
index a575f69..93f643d 100644
--- a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/WireRecordBatch.java
+++ b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/WireRecordBatch.java
@@ -24,11 +24,12 @@ import org.apache.drill.exec.exception.SchemaChangeException;
 import org.apache.drill.exec.ops.FragmentContext;
 import org.apache.drill.exec.proto.UserBitShared.RecordBatchDef;
 import org.apache.drill.exec.record.BatchSchema;
-import org.apache.drill.exec.record.InvalidValueAccessor;
 import org.apache.drill.exec.record.RawFragmentBatch;
 import org.apache.drill.exec.record.RawFragmentBatchProvider;
 import org.apache.drill.exec.record.RecordBatch;
 import org.apache.drill.exec.record.RecordBatchLoader;
+import org.apache.drill.exec.record.TypedFieldId;
+import org.apache.drill.exec.record.VectorWrapper;
 import org.apache.drill.exec.record.WritableBatch;
 import org.apache.drill.exec.record.selection.SelectionVector2;
 import org.apache.drill.exec.record.selection.SelectionVector4;
@@ -70,7 +71,7 @@ public class WireRecordBatch implements RecordBatch{
   }
   
   @Override
-  public Iterator<ValueVector> iterator() {
+  public Iterator<VectorWrapper<?>> iterator() {
     return batchLoader.iterator();
   }
 
@@ -86,14 +87,14 @@ public class WireRecordBatch implements RecordBatch{
 
   @Override
   public TypedFieldId getValueVectorId(SchemaPath path) {
-    return batchLoader.getValueVector(path);
+    return batchLoader.getValueVectorId(path);
   }
-
+  
   @Override
-  public <T extends ValueVector> T getValueVectorById(int fieldId, Class<?> clazz){
-    return batchLoader.getValueVector(fieldId, clazz);
+  public VectorWrapper<?> getValueAccessorById(int fieldId, Class<?> clazz) {
+    return batchLoader.getValueAccessorById(fieldId, clazz);
   }
-  
+
   @Override
   public IterOutcome next() {
     RawFragmentBatch batch = fragProvider.getNext();

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/db3afaa8/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/filter/FilterRecordBatch.java
----------------------------------------------------------------------
diff --git a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/filter/FilterRecordBatch.java b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/filter/FilterRecordBatch.java
index babc66e..806ead6 100644
--- a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/filter/FilterRecordBatch.java
+++ b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/filter/FilterRecordBatch.java
@@ -1,144 +1,68 @@
 package org.apache.drill.exec.physical.impl.filter;
 
 import java.io.IOException;
-import java.util.Iterator;
 import java.util.List;
 
 import org.apache.drill.common.expression.ErrorCollector;
 import org.apache.drill.common.expression.ErrorCollectorImpl;
 import org.apache.drill.common.expression.LogicalExpression;
-import org.apache.drill.common.expression.SchemaPath;
 import org.apache.drill.exec.exception.ClassTransformationException;
 import org.apache.drill.exec.exception.SchemaChangeException;
 import org.apache.drill.exec.expr.CodeGenerator;
 import org.apache.drill.exec.expr.ExpressionTreeMaterializer;
 import org.apache.drill.exec.ops.FragmentContext;
 import org.apache.drill.exec.physical.config.Filter;
-import org.apache.drill.exec.physical.impl.VectorHolder;
-import org.apache.drill.exec.record.BatchSchema;
 import org.apache.drill.exec.record.BatchSchema.SelectionVectorMode;
+import org.apache.drill.exec.record.AbstractSingleRecordBatch;
 import org.apache.drill.exec.record.RecordBatch;
-import org.apache.drill.exec.record.SchemaBuilder;
 import org.apache.drill.exec.record.TransferPair;
-import org.apache.drill.exec.record.WritableBatch;
+import org.apache.drill.exec.record.VectorWrapper;
 import org.apache.drill.exec.record.selection.SelectionVector2;
-import org.apache.drill.exec.record.selection.SelectionVector4;
 import org.apache.drill.exec.vector.ValueVector;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.Lists;
 
-public class FilterRecordBatch implements RecordBatch{
+public class FilterRecordBatch extends AbstractSingleRecordBatch<Filter>{
   static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(FilterRecordBatch.class);
 
-  private final Filter filterConfig;
-  private final RecordBatch incoming;
-  private final FragmentContext context;
   private final SelectionVector2 sv;
-  private BatchSchema outSchema;
   private Filterer filter;
-  private List<ValueVector> outputVectors;
-  private VectorHolder vh;
   
   public FilterRecordBatch(Filter pop, RecordBatch incoming, FragmentContext context){
-    this.filterConfig = pop;
-    this.incoming = incoming;
-    this.context = context;
+    super(pop, context, incoming);
     sv = new SelectionVector2(context.getAllocator());
   }
   
-  
   @Override
   public FragmentContext getContext() {
     return context;
   }
 
   @Override
-  public BatchSchema getSchema() {
-    Preconditions.checkNotNull(outSchema);
-    return outSchema;
-  }
-
-  @Override
   public int getRecordCount() {
     return sv.getCount();
   }
 
   @Override
-  public void kill() {
-    incoming.kill();
-  }
-
-  
-  @Override
-  public Iterator<ValueVector> iterator() {
-    return outputVectors.iterator();
-  }
-
-  @Override
   public SelectionVector2 getSelectionVector2() {
     return sv;
   }
 
   @Override
-  public SelectionVector4 getSelectionVector4() {
-    throw new UnsupportedOperationException();
-  }
-
-  @Override
-  public TypedFieldId getValueVectorId(SchemaPath path) {
-    return vh.getValueVector(path);
-  }
-
-  @Override
-  public <T extends ValueVector> T getValueVectorById(int fieldId, Class<?> clazz) {
-    return vh.getValueVector(fieldId, clazz);
-  }
-
-  @Override
-  public IterOutcome next() {
-    
-    IterOutcome upstream = incoming.next();
-    logger.debug("Upstream... {}", upstream);
-    switch(upstream){
-    case NONE:
-    case NOT_YET:
-    case STOP:
-      return upstream;
-    case OK_NEW_SCHEMA:
-      try{
-        filter = createNewFilterer();
-      }catch(SchemaChangeException ex){
-        incoming.kill();
-        logger.error("Failure during query", ex);
-        context.fail(ex);
-        return IterOutcome.STOP;
-      }
-      // fall through.
-    case OK:
-      int recordCount = incoming.getRecordCount();
-      sv.allocateNew(recordCount);
-      filter.filterBatch(recordCount);
-      for(ValueVector v : this.outputVectors){
-        ValueVector.Mutator m = v.getMutator();
-        m.setValueCount(recordCount);
-      }
-      return upstream; // change if upstream changed, otherwise normal.
-    default:
-      throw new UnsupportedOperationException();
+  protected void doWork() {
+    int recordCount = incoming.getRecordCount();
+    sv.allocateNew(recordCount);
+    filter.filterBatch(recordCount);
+    for(VectorWrapper<?> v : container){
+      ValueVector.Mutator m = v.getValueVector().getMutator();
+      m.setValueCount(recordCount);
     }
   }
   
-
-  private Filterer createNewFilterer() throws SchemaChangeException{
-    if(outputVectors != null){
-      for(ValueVector v : outputVectors){
-        v.close();
-      }
-    }
-    this.outputVectors = Lists.newArrayList();
-    this.vh = new VectorHolder(outputVectors);
-    LogicalExpression filterExpression = filterConfig.getExpr();
+  @Override
+  protected void setupNewSchema() throws SchemaChangeException {
+    container.clear();
+    LogicalExpression filterExpression = popConfig.getExpr();
     final ErrorCollector collector = new ErrorCollectorImpl();
     final List<TransferPair> transfers = Lists.newArrayList();
     final CodeGenerator<Filterer> cg = new CodeGenerator<Filterer>(Filterer.TEMPLATE_DEFINITION, context.getFunctionRegistry());
@@ -150,32 +74,21 @@ public class FilterRecordBatch implements RecordBatch{
     
     cg.addExpr(new ReturnValueExpression(expr));
     
-    for(ValueVector v : incoming){
-      TransferPair pair = v.getTransferPair();
-      outputVectors.add(pair.getTo());
+    for(VectorWrapper<?> v : incoming){
+      TransferPair pair = v.getValueVector().getTransferPair();
+      container.add(pair.getTo());
       transfers.add(pair);
     }
     
-    SchemaBuilder bldr = BatchSchema.newBuilder().setSelectionVectorMode(SelectionVectorMode.TWO_BYTE);
-    for(ValueVector v : outputVectors){
-      bldr.addField(v.getField());
-    }
-    this.outSchema = bldr.build();
+    container.buildSchema(SelectionVectorMode.TWO_BYTE);
     
     try {
       TransferPair[] tx = transfers.toArray(new TransferPair[transfers.size()]);
-      Filterer filterer = context.getImplementationClass(cg);
-      filterer.setup(context, incoming, this, tx);
-      return filterer;
+      this.filter = context.getImplementationClass(cg);
+      filter.setup(context, incoming, this, tx);
     } catch (ClassTransformationException | IOException e) {
       throw new SchemaChangeException("Failure while attempting to load generated class", e);
     }
   }
   
-  @Override
-  public WritableBatch getWritableBatch() {
-    return WritableBatch.get(this);
-  }
-  
-  
 }

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/db3afaa8/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/materialize/RecordMaterializer.java
----------------------------------------------------------------------
diff --git a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/materialize/RecordMaterializer.java b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/materialize/RecordMaterializer.java
index 17c65e9..b62e52b 100644
--- a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/materialize/RecordMaterializer.java
+++ b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/materialize/RecordMaterializer.java
@@ -17,12 +17,6 @@
  ******************************************************************************/
 package org.apache.drill.exec.physical.impl.materialize;
 
-import org.apache.drill.exec.ops.FragmentContext;
-import org.apache.drill.exec.proto.UserBitShared.QueryId;
-import org.apache.drill.exec.proto.UserProtos.QueryResult;
-import org.apache.drill.exec.record.MaterializedField;
-import org.apache.drill.exec.record.RecordBatch;
-import org.apache.drill.exec.record.WritableBatch;
 
 public interface RecordMaterializer {
   

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/db3afaa8/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/project/ProjectRecordBatch.java
----------------------------------------------------------------------
diff --git a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/project/ProjectRecordBatch.java b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/project/ProjectRecordBatch.java
index 29660cb..8f06290 100644
--- a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/project/ProjectRecordBatch.java
+++ b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/project/ProjectRecordBatch.java
@@ -1,7 +1,6 @@
 package org.apache.drill.exec.physical.impl.project;
 
 import java.io.IOException;
-import java.util.Iterator;
 import java.util.List;
 
 import org.apache.drill.common.expression.ErrorCollector;
@@ -20,19 +19,15 @@ import org.apache.drill.exec.expr.ValueVectorReadExpression;
 import org.apache.drill.exec.expr.ValueVectorWriteExpression;
 import org.apache.drill.exec.ops.FragmentContext;
 import org.apache.drill.exec.physical.config.Project;
-import org.apache.drill.exec.physical.impl.VectorHolder;
 import org.apache.drill.exec.proto.SchemaDefProtos.FieldDef;
 import org.apache.drill.exec.proto.SchemaDefProtos.NamePart;
 import org.apache.drill.exec.proto.SchemaDefProtos.NamePart.Type;
-import org.apache.drill.exec.record.BatchSchema;
 import org.apache.drill.exec.record.BatchSchema.SelectionVectorMode;
+import org.apache.drill.exec.record.AbstractSingleRecordBatch;
 import org.apache.drill.exec.record.MaterializedField;
 import org.apache.drill.exec.record.RecordBatch;
-import org.apache.drill.exec.record.SchemaBuilder;
 import org.apache.drill.exec.record.TransferPair;
-import org.apache.drill.exec.record.WritableBatch;
-import org.apache.drill.exec.record.selection.SelectionVector2;
-import org.apache.drill.exec.record.selection.SelectionVector4;
+import org.apache.drill.exec.record.VectorWrapper;
 import org.apache.drill.exec.vector.AllocationHelper;
 import org.apache.drill.exec.vector.TypeHelper;
 import org.apache.drill.exec.vector.ValueVector;
@@ -40,118 +35,39 @@ import org.apache.drill.exec.vector.ValueVector;
 import com.google.common.base.Preconditions;
 import com.google.common.collect.Lists;
 
-public class ProjectRecordBatch implements RecordBatch{
+public class ProjectRecordBatch extends AbstractSingleRecordBatch<Project>{
   static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ProjectRecordBatch.class);
 
-  private final Project pop;
-  private final RecordBatch incoming;
-  private final FragmentContext context;
-  private BatchSchema outSchema;
   private Projector projector;
   private List<ValueVector> allocationVectors;
-  private List<ValueVector> outputVectors;
-  private VectorHolder vh;
-  
   
   public ProjectRecordBatch(Project pop, RecordBatch incoming, FragmentContext context){
-    this.pop = pop;
-    this.incoming = incoming;
-    this.context = context;
+    super(pop, context, incoming);
   }
   
   @Override
-  public Iterator<ValueVector> iterator() {
-    return outputVectors.iterator();
-  }
-
-  @Override
-  public FragmentContext getContext() {
-    return context;
-  }
-
-  @Override
-  public BatchSchema getSchema() {
-    Preconditions.checkNotNull(outSchema);
-    return outSchema;
-  }
-
-  @Override
   public int getRecordCount() {
     return incoming.getRecordCount();
   }
 
   @Override
-  public void kill() {
-    incoming.kill();
-  }
-
-  @Override
-  public SelectionVector2 getSelectionVector2() {
-    throw new UnsupportedOperationException();
-  }
-
-  @Override
-  public SelectionVector4 getSelectionVector4() {
-    throw new UnsupportedOperationException();
-  }
-
-  @Override
-  public TypedFieldId getValueVectorId(SchemaPath path) {
-    return vh.getValueVector(path);
-  }
-
-  @Override
-  public <T extends ValueVector> T getValueVectorById(int fieldId, Class<?> clazz) {
-    return vh.getValueVector(fieldId, clazz);
-  }
-
-  @Override
-  public IterOutcome next() {
-    
-    IterOutcome upstream = incoming.next();
-    logger.debug("Upstream... {}", upstream);
-    switch(upstream){
-    case NONE:
-    case NOT_YET:
-    case STOP:
-      return upstream;
-    case OK_NEW_SCHEMA:
-      try{
-        projector = createNewProjector();
-      }catch(SchemaChangeException ex){
-        incoming.kill();
-        logger.error("Failure during query", ex);
-        context.fail(ex);
-        return IterOutcome.STOP;
-      }
-      // fall through.
-    case OK:
-      int recordCount = incoming.getRecordCount();
-      for(ValueVector v : this.allocationVectors){
-        AllocationHelper.allocate(v, recordCount, 50);
-      }
-      projector.projectRecords(recordCount, 0);
-      for(ValueVector v : this.outputVectors){
-        ValueVector.Mutator m = v.getMutator();
-        m.setValueCount(recordCount);
-      }
-      return upstream; // change if upstream changed, otherwise normal.
-    default:
-      throw new UnsupportedOperationException();
+  protected void doWork() {
+    int recordCount = incoming.getRecordCount();
+    for(ValueVector v : this.allocationVectors){
+      AllocationHelper.allocate(v, recordCount, 50);
+    }
+    projector.projectRecords(recordCount, 0);
+    for(VectorWrapper<?> v : container){
+      ValueVector.Mutator m = v.getValueVector().getMutator();
+      m.setValueCount(recordCount);
     }
   }
-  
 
-  private Projector createNewProjector() throws SchemaChangeException{
+  @Override
+  protected void setupNewSchema() throws SchemaChangeException{
     this.allocationVectors = Lists.newArrayList();
-    if(outputVectors != null){
-      for(ValueVector v : outputVectors){
-        v.close();
-      }
-    }
-    this.outputVectors = Lists.newArrayList();
-    this.vh = new VectorHolder(outputVectors);
-    final List<NamedExpression> exprs = pop.getExprs();
+    container.clear();
+    final List<NamedExpression> exprs = popConfig.getExprs();
     final ErrorCollector collector = new ErrorCollectorImpl();
     final List<TransferPair> transfers = Lists.newArrayList();
     
@@ -168,43 +84,34 @@ public class ProjectRecordBatch implements RecordBatch{
       // add value vector to transfer if direct reference and this is allowed, otherwise, add to evaluation stack.
       if(expr instanceof ValueVectorReadExpression && incoming.getSchema().getSelectionVectorMode() == SelectionVectorMode.NONE){
         ValueVectorReadExpression vectorRead = (ValueVectorReadExpression) expr;
-        ValueVector vvIn = incoming.getValueVectorById(vectorRead.getFieldId(), TypeHelper.getValueVectorClass(vectorRead.getMajorType().getMinorType(), vectorRead.getMajorType().getMode()));
+        ValueVector vvIn = incoming.getValueAccessorById(vectorRead.getFieldId().getFieldId(), TypeHelper.getValueVectorClass(vectorRead.getMajorType().getMinorType(), vectorRead.getMajorType().getMode())).getValueVector();
         Preconditions.checkNotNull(incoming);
 
         TransferPair tp = vvIn.getTransferPair();
         transfers.add(tp);
-        outputVectors.add(tp.getTo());
+        container.add(tp.getTo());
+        logger.debug("Added transfer.");
       }else{
         // need to do evaluation.
         ValueVector vector = TypeHelper.getNewVector(outputField, context.getAllocator());
         allocationVectors.add(vector);
-        outputVectors.add(vector);
-        ValueVectorWriteExpression write = new ValueVectorWriteExpression(outputVectors.size() - 1, expr);
+        ValueVectorWriteExpression write = new ValueVectorWriteExpression(container.add(vector), expr);
         cg.addExpr(write);
+        logger.debug("Added eval.");
       }
       
     }
     
-    SchemaBuilder bldr = BatchSchema.newBuilder().setSelectionVectorMode(incoming.getSchema().getSelectionVectorMode());
-    for(ValueVector v : outputVectors){
-      bldr.addField(v.getField());
-    }
-    this.outSchema = bldr.build();
+    container.buildSchema(incoming.getSchema().getSelectionVectorMode());
     
     try {
-      Projector projector = context.getImplementationClass(cg);
+      this.projector = context.getImplementationClass(cg);
       projector.setup(context, incoming, this, transfers);
-      return projector;
     } catch (ClassTransformationException | IOException e) {
       throw new SchemaChangeException("Failure while attempting to load generated class", e);
     }
   }
   
-  @Override
-  public WritableBatch getWritableBatch() {
-    return WritableBatch.get(this);
-  }
-  
   private MaterializedField getMaterializedField(FieldReference reference, LogicalExpression expr){
     return new MaterializedField(getFieldDef(reference, expr.getMajorType()));
   }

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/db3afaa8/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/sort/Comparator.java
----------------------------------------------------------------------
diff --git a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/sort/Comparator.java b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/sort/Comparator.java
new file mode 100644
index 0000000..86d0d61
--- /dev/null
+++ b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/sort/Comparator.java
@@ -0,0 +1,11 @@
+package org.apache.drill.exec.physical.impl.sort;
+
+import org.apache.drill.exec.exception.SchemaChangeException;
+import org.apache.drill.exec.ops.FragmentContext;
+import org.apache.drill.exec.record.RecordBatch;
+
+public interface Comparator {
+  
+  public abstract void doSetup(FragmentContext context, RecordBatch incoming, RecordBatch outgoing) throws SchemaChangeException;
+  public abstract int doEval(int inIndex, int outIndex);
+}

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/db3afaa8/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/sort/ReadIndexRewriter.java
----------------------------------------------------------------------
diff --git a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/sort/ReadIndexRewriter.java b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/sort/ReadIndexRewriter.java
new file mode 100644
index 0000000..83d43b2
--- /dev/null
+++ b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/sort/ReadIndexRewriter.java
@@ -0,0 +1,87 @@
+package org.apache.drill.exec.physical.impl.sort;
+
+import java.util.List;
+
+import org.apache.drill.common.expression.FunctionCall;
+import org.apache.drill.common.expression.IfExpression;
+import org.apache.drill.common.expression.LogicalExpression;
+import org.apache.drill.common.expression.SchemaPath;
+import org.apache.drill.common.expression.ValueExpressions.BooleanExpression;
+import org.apache.drill.common.expression.ValueExpressions.DoubleExpression;
+import org.apache.drill.common.expression.ValueExpressions.LongExpression;
+import org.apache.drill.common.expression.ValueExpressions.QuotedString;
+import org.apache.drill.common.expression.visitors.ExprVisitor;
+import org.apache.drill.exec.expr.ValueVectorReadExpression;
+
+import com.google.common.collect.Lists;
+
+public class ReadIndexRewriter implements ExprVisitor<LogicalExpression, String, RuntimeException> {
+  static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ReadIndexRewriter.class);
+
+  private String batchName;
+  
+  
+  @Override
+  public LogicalExpression visitUnknown(LogicalExpression e, String newIndexName) {
+    if (e instanceof ValueVectorReadExpression) {
+      ValueVectorReadExpression old = (ValueVectorReadExpression) e;
+      return new ValueVectorReadExpression(old.getTypedFieldId(), newIndexName);
+    } else {
+      throw new UnsupportedOperationException(String.format(
+          "ReadIndex rewriter doesn't know how to rewrite expression of type %s.", e.getClass().getName()));
+    }
+  }
+
+  @Override
+  public LogicalExpression visitFunctionCall(FunctionCall call, String newIndexName) {
+    List<LogicalExpression> args = Lists.newArrayList();
+    for (int i = 0; i < call.args.size(); ++i) {
+      LogicalExpression newExpr = call.args.get(i).accept(this, null);
+      args.add(newExpr);
+    }
+
+    return new FunctionCall(call.getDefinition(), args, call.getPosition());
+  }
+
+  @Override
+  public LogicalExpression visitIfExpression(IfExpression ifExpr, String newIndexName) {
+    List<IfExpression.IfCondition> conditions = Lists.newArrayList(ifExpr.iterator());
+    LogicalExpression newElseExpr = ifExpr.elseExpression.accept(this, null);
+
+    for (int i = 0; i < conditions.size(); ++i) {
+      IfExpression.IfCondition condition = conditions.get(i);
+
+      LogicalExpression newCondition = condition.condition.accept(this, null);
+      LogicalExpression newExpr = condition.expression.accept(this, null);
+      conditions.set(i, new IfExpression.IfCondition(newCondition, newExpr));
+    }
+
+    return IfExpression.newBuilder().setElse(newElseExpr).addConditions(conditions).build();
+  }
+
+  @Override
+  public LogicalExpression visitSchemaPath(SchemaPath path, String newIndexName) {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public LogicalExpression visitLongConstant(LongExpression intExpr, String value) throws RuntimeException {
+    return intExpr;
+  }
+
+  @Override
+  public LogicalExpression visitDoubleConstant(DoubleExpression dExpr, String value) throws RuntimeException {
+    return dExpr;
+  }
+
+  @Override
+  public LogicalExpression visitBooleanConstant(BooleanExpression e, String value) throws RuntimeException {
+    return e;
+  }
+
+  @Override
+  public LogicalExpression visitQuotedStringConstant(QuotedString e, String value) throws RuntimeException {
+    return e;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/db3afaa8/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/sort/RecordBatchData.java
----------------------------------------------------------------------
diff --git a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/sort/RecordBatchData.java b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/sort/RecordBatchData.java
new file mode 100644
index 0000000..a21af09
--- /dev/null
+++ b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/sort/RecordBatchData.java
@@ -0,0 +1,47 @@
+package org.apache.drill.exec.physical.impl.sort;
+
+import java.util.List;
+
+import org.apache.drill.exec.record.BatchSchema.SelectionVectorMode;
+import org.apache.drill.exec.record.RecordBatch;
+import org.apache.drill.exec.record.TransferPair;
+import org.apache.drill.exec.record.VectorWrapper;
+import org.apache.drill.exec.record.selection.SelectionVector2;
+import org.apache.drill.exec.vector.ValueVector;
+
+import com.google.common.collect.Lists;
+
+/**
+ * Holds the data for a particular record batch for later manipulation.
+ */
+class RecordBatchData {
+  static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(RecordBatchData.class);
+  
+  final List<ValueVector> vectors = Lists.newArrayList();
+  final SelectionVector2 sv2;
+  final int recordCount;
+  
+  public RecordBatchData(RecordBatch batch){
+    this.sv2 = batch.getSchema().getSelectionVectorMode() == SelectionVectorMode.TWO_BYTE ? batch.getSelectionVector2().clone() : null;
+    
+    for(VectorWrapper<?> v : batch){
+      if(v.isHyper()) throw new UnsupportedOperationException("Record batch data can't be created based on a hyper batch.");
+      TransferPair tp = v.getValueVector().getTransferPair();
+      tp.transfer();
+      vectors.add(tp.getTo());
+    }
+    
+    recordCount = batch.getRecordCount();
+  }
+  
+  public int getRecordCount(){
+    return recordCount;
+  }
+  public List<ValueVector> getVectors() {
+    return vectors;
+  }
+
+  public SelectionVector2 getSv2() {
+    return sv2;
+  }
+}

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/db3afaa8/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/sort/SortBatch.java
----------------------------------------------------------------------
diff --git a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/sort/SortBatch.java b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/sort/SortBatch.java
new file mode 100644
index 0000000..e361e38
--- /dev/null
+++ b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/sort/SortBatch.java
@@ -0,0 +1,171 @@
+package org.apache.drill.exec.physical.impl.sort;
+
+import java.io.IOException;
+
+import org.apache.drill.common.defs.OrderDef;
+import org.apache.drill.common.defs.OrderDef.Direction;
+import org.apache.drill.common.expression.ErrorCollector;
+import org.apache.drill.common.expression.ErrorCollectorImpl;
+import org.apache.drill.common.expression.ExpressionPosition;
+import org.apache.drill.common.expression.FunctionCall;
+import org.apache.drill.common.expression.LogicalExpression;
+import org.apache.drill.exec.exception.ClassTransformationException;
+import org.apache.drill.exec.exception.SchemaChangeException;
+import org.apache.drill.exec.expr.CodeGenerator;
+import org.apache.drill.exec.expr.CodeGenerator.HoldingContainer;
+import org.apache.drill.exec.expr.ExpressionTreeMaterializer;
+import org.apache.drill.exec.expr.fn.impl.ComparatorFunctions;
+import org.apache.drill.exec.ops.FragmentContext;
+import org.apache.drill.exec.physical.config.Sort;
+import org.apache.drill.exec.record.AbstractRecordBatch;
+import org.apache.drill.exec.record.BatchSchema;
+import org.apache.drill.exec.record.RecordBatch;
+import org.apache.drill.exec.record.WritableBatch;
+import org.apache.drill.exec.record.selection.SelectionVector2;
+import org.apache.drill.exec.record.selection.SelectionVector4;
+
+import com.google.common.collect.ImmutableList;
+import com.sun.codemodel.JConditional;
+import com.sun.codemodel.JExpr;
+
+public class SortBatch extends AbstractRecordBatch<Sort> {
+  static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SortBatch.class);
+
+  private static long MAX_SORT_BYTES = 8l * 1024 * 1024 * 1024;
+
+  private final RecordBatch incoming;
+  private SortRecordBatchBuilder builder;
+  private SelectionVector4 sv4;
+  private Sorter sorter;
+  private BatchSchema schema;
+  
+  public SortBatch(Sort popConfig, FragmentContext context, RecordBatch incoming) {
+    super(popConfig, context);
+    this.incoming = incoming;
+  }
+
+  @Override
+  public int getRecordCount() {
+    return sv4.getLength();
+  }
+
+  @Override
+  public void kill() {
+    incoming.kill();
+  }
+
+  @Override
+  public SelectionVector2 getSelectionVector2() {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public SelectionVector4 getSelectionVector4() {
+    return sv4;
+  }
+
+  @Override
+  public IterOutcome next() {
+    if(builder != null){
+      if(sv4.next()){
+        return IterOutcome.OK;
+      }else{
+        return IterOutcome.NONE;
+      }
+    }
+    
+    
+    try{
+      outer: while (true) {
+        IterOutcome upstream = incoming.next();
+        switch (upstream) {
+        case NONE:
+          break outer;
+        case NOT_YET:
+        case STOP:
+          container.clear();
+          return upstream;
+        case OK_NEW_SCHEMA:
+          // only change in the case that the schema truly changes.  Artificial schema changes are ignored.
+          if(!incoming.getSchema().equals(schema)){
+            if (builder != null) throw new UnsupportedOperationException("Sort doesn't currently support sorts with changing schemas.");
+            builder = new SortRecordBatchBuilder(context.getAllocator(), MAX_SORT_BYTES, container);
+            this.schema = incoming.getSchema();
+          }
+          // fall through.
+        case OK:
+          if(!builder.add(incoming)){
+            throw new UnsupportedOperationException("Sort doesn't currently support doing an external sort.");
+          };
+          break;
+        default:
+          throw new UnsupportedOperationException();
+        }
+      }
+      
+      builder.build(context);
+      sv4 = builder.getSv4();
+
+      sorter = createNewSorter();
+      sorter.setup(context, this);
+      long t1 = System.nanoTime();
+      sorter.sort(sv4, container);
+      logger.debug("Sorted {} records in {} micros.", sv4.getTotalCount(), (System.nanoTime() - t1)/1000);
+      
+      return IterOutcome.OK_NEW_SCHEMA;
+      
+    }catch(SchemaChangeException | ClassTransformationException | IOException ex){
+      kill();
+      logger.error("Failure during query", ex);
+      context.fail(ex);
+      return IterOutcome.STOP;
+    }
+  }
+
+  
+  private Sorter createNewSorter() throws ClassTransformationException, IOException, SchemaChangeException{
+    CodeGenerator<Sorter> g = new CodeGenerator<Sorter>(Sorter.TEMPLATE_DEFINITION, context.getFunctionRegistry());
+    
+    for(OrderDef od : popConfig.getOrderings()){
+      // first, we rewrite the evaluation stack for each side of the comparison.
+      ErrorCollector collector = new ErrorCollectorImpl(); 
+      final LogicalExpression expr = ExpressionTreeMaterializer.materialize(od.getExpr(), this, collector);
+      if(collector.hasErrors()) throw new SchemaChangeException("Failure while materializing expression. " + collector.toErrorString());
+      ReadIndexRewriter rewriter = new ReadIndexRewriter();
+      LogicalExpression left = expr.accept(rewriter, "inIndex");
+      LogicalExpression right = expr.accept(rewriter, "outIndex");
+      
+      // next we wrap the two comparison sides and add the expression block for the comparison.
+      FunctionCall f = new FunctionCall(ComparatorFunctions.COMPARE_TO, ImmutableList.of(left, right), ExpressionPosition.UNKNOWN);
+      HoldingContainer out = g.addExpr(f);
+      JConditional jc = g.getBlock()._if(out.getValue().ne(JExpr.lit(0)));
+      
+      //TODO: is this the right order...
+      if(od.getDirection() == Direction.ASC){
+        jc._then()._return(out.getValue());
+      }else{
+        jc._then()._return(out.getValue().minus());
+      }
+    }
+    
+    g.getBlock()._return(JExpr.lit(0));
+    
+    return context.getImplementationClass(g);
+
+
+  }
+  
+  @Override
+  public WritableBatch getWritableBatch() {
+    throw new UnsupportedOperationException("A sort batch is not writable.");
+  }
+
+  @Override
+  protected void killIncoming() {
+    incoming.kill();
+  }
+
+  
+  
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/db3afaa8/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/sort/SortBatchCreator.java
----------------------------------------------------------------------
diff --git a/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/sort/SortBatchCreator.java b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/sort/SortBatchCreator.java
new file mode 100644
index 0000000..0a671a8
--- /dev/null
+++ b/sandbox/prototype/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/sort/SortBatchCreator.java
@@ -0,0 +1,23 @@
+package org.apache.drill.exec.physical.impl.sort;
+
+import java.util.List;
+
+import org.apache.drill.common.exceptions.ExecutionSetupException;
+import org.apache.drill.exec.ops.FragmentContext;
+import org.apache.drill.exec.physical.config.Sort;
+import org.apache.drill.exec.physical.impl.BatchCreator;
+import org.apache.drill.exec.record.RecordBatch;
+
+import com.google.common.base.Preconditions;
+
+public class SortBatchCreator implements BatchCreator<Sort>{
+  static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SortBatchCreator.class);
+
+  @Override
+  public RecordBatch getBatch(FragmentContext context, Sort config, List<RecordBatch> children) throws ExecutionSetupException {
+    Preconditions.checkArgument(children.size() == 1);
+    return new SortBatch(config, context, children.iterator().next());
+  }
+  
+  
+}