You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@drill.apache.org by ja...@apache.org on 2015/11/13 03:38:05 UTC

[35/45] drill git commit: DRILL-3987: (MOVE) Move logical expressions and operators out of common. Move to new drill-logical model.

http://git-wip-us.apache.org/repos/asf/drill/blob/44dea433/logical/src/main/java/org/apache/drill/common/expression/ExpressionStringBuilder.java
----------------------------------------------------------------------
diff --git a/logical/src/main/java/org/apache/drill/common/expression/ExpressionStringBuilder.java b/logical/src/main/java/org/apache/drill/common/expression/ExpressionStringBuilder.java
new file mode 100644
index 0000000..c29b9b0
--- /dev/null
+++ b/logical/src/main/java/org/apache/drill/common/expression/ExpressionStringBuilder.java
@@ -0,0 +1,332 @@
+/**
+ * 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.common.expression;
+
+import java.math.BigDecimal;
+
+import org.apache.drill.common.expression.IfExpression.IfCondition;
+import org.apache.drill.common.expression.ValueExpressions.BooleanExpression;
+import org.apache.drill.common.expression.ValueExpressions.DateExpression;
+import org.apache.drill.common.expression.ValueExpressions.Decimal18Expression;
+import org.apache.drill.common.expression.ValueExpressions.Decimal28Expression;
+import org.apache.drill.common.expression.ValueExpressions.Decimal38Expression;
+import org.apache.drill.common.expression.ValueExpressions.Decimal9Expression;
+import org.apache.drill.common.expression.ValueExpressions.DoubleExpression;
+import org.apache.drill.common.expression.ValueExpressions.FloatExpression;
+import org.apache.drill.common.expression.ValueExpressions.IntExpression;
+import org.apache.drill.common.expression.ValueExpressions.IntervalDayExpression;
+import org.apache.drill.common.expression.ValueExpressions.IntervalYearExpression;
+import org.apache.drill.common.expression.ValueExpressions.LongExpression;
+import org.apache.drill.common.expression.ValueExpressions.QuotedString;
+import org.apache.drill.common.expression.ValueExpressions.TimeExpression;
+import org.apache.drill.common.expression.ValueExpressions.TimeStampExpression;
+import org.apache.drill.common.expression.visitors.AbstractExprVisitor;
+import org.apache.drill.common.types.TypeProtos.MajorType;
+import org.joda.time.Period;
+
+import com.google.common.collect.ImmutableList;
+
+public class ExpressionStringBuilder extends AbstractExprVisitor<Void, StringBuilder, RuntimeException>{
+  static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ExpressionStringBuilder.class);
+
+  static final ExpressionStringBuilder INSTANCE = new ExpressionStringBuilder();
+
+  public static String toString(LogicalExpression expr) {
+    StringBuilder sb = new StringBuilder();
+    expr.accept(INSTANCE, sb);
+    return sb.toString();
+  }
+
+  public static void toString(LogicalExpression expr, StringBuilder sb) {
+    expr.accept(INSTANCE, sb);
+  }
+
+
+  @Override
+  public Void visitFunctionCall(FunctionCall call, StringBuilder sb) throws RuntimeException {
+    ImmutableList<LogicalExpression> args = call.args;
+    sb.append(call.getName());
+    sb.append("(");
+    for (int i = 0; i < args.size(); i++) {
+      if (i != 0) {
+        sb.append(", ");
+      }
+      args.get(i).accept(this, sb);
+    }
+    sb.append(") ");
+    return null;
+  }
+
+  @Override
+  public Void visitBooleanOperator(BooleanOperator op, StringBuilder sb) throws RuntimeException {
+    return visitFunctionCall(op, sb);
+  }
+
+  @Override
+  public Void visitFunctionHolderExpression(FunctionHolderExpression holder, StringBuilder sb) throws RuntimeException {
+    ImmutableList<LogicalExpression> args = holder.args;
+    sb.append(holder.getName());
+    sb.append("(");
+    for (int i = 0; i < args.size(); i++) {
+      if (i != 0) {
+        sb.append(", ");
+      }
+      args.get(i).accept(this, sb);
+    }
+    sb.append(") ");
+    return null;
+  }
+
+  @Override
+  public Void visitIfExpression(IfExpression ifExpr, StringBuilder sb) throws RuntimeException {
+
+    // serialize the if expression
+    sb.append(" ( ");
+    IfCondition c = ifExpr.ifCondition;
+    sb.append("if (");
+    c.condition.accept(this, sb);
+    sb.append(" ) then (");
+    c.expression.accept(this, sb);
+    sb.append(" ) ");
+
+    sb.append(" else (");
+    ifExpr.elseExpression.accept(this, sb);
+    sb.append(" ) ");
+    sb.append(" end ");
+    sb.append(" ) ");
+    return null;
+  }
+
+  @Override
+  public Void visitSchemaPath(SchemaPath path, StringBuilder sb) throws RuntimeException {
+    PathSegment seg = path.getRootSegment();
+    if (seg.isArray()) {
+      throw new IllegalStateException("Drill doesn't currently support top level arrays");
+    }
+    sb.append('`');
+    sb.append(seg.getNameSegment().getPath());
+    sb.append('`');
+
+    while ( (seg = seg.getChild()) != null) {
+      if (seg.isNamed()) {
+        sb.append('.');
+        sb.append('`');
+        sb.append(seg.getNameSegment().getPath());
+        sb.append('`');
+      } else {
+        sb.append('[');
+        sb.append(seg.getArraySegment().getIndex());
+        sb.append(']');
+      }
+    }
+    return null;
+  }
+
+  @Override
+  public Void visitLongConstant(LongExpression lExpr, StringBuilder sb) throws RuntimeException {
+    sb.append(lExpr.getLong());
+    return null;
+  }
+
+  @Override
+  public Void visitDateConstant(DateExpression lExpr, StringBuilder sb) throws RuntimeException {
+    sb.append("cast( ");
+    sb.append(lExpr.getDate());
+    sb.append(" as DATE)");
+    return null;
+  }
+
+  @Override
+  public Void visitTimeConstant(TimeExpression lExpr, StringBuilder sb) throws RuntimeException {
+    sb.append("cast( ");
+    sb.append(lExpr.getTime());
+    sb.append(" as TIME)");
+    return null;
+  }
+
+  @Override
+  public Void visitTimeStampConstant(TimeStampExpression lExpr, StringBuilder sb) throws RuntimeException {
+    sb.append("cast( ");
+    sb.append(lExpr.getTimeStamp());
+    sb.append(" as TIMESTAMP)");
+    return null;
+  }
+
+  @Override
+  public Void visitIntervalYearConstant(IntervalYearExpression lExpr, StringBuilder sb) throws RuntimeException {
+    sb.append("cast( '");
+    sb.append(Period.months(lExpr.getIntervalYear()).toString());
+    sb.append("' as INTERVALYEAR)");
+    return null;
+  }
+
+  @Override
+  public Void visitIntervalDayConstant(IntervalDayExpression lExpr, StringBuilder sb) throws RuntimeException {
+    sb.append("cast( '");
+    sb.append(Period.days(lExpr.getIntervalDay()).plusMillis(lExpr.getIntervalMillis()).toString());
+    sb.append("' as INTERVALDAY)");
+    return null;
+  }
+
+  @Override
+  public Void visitDecimal9Constant(Decimal9Expression decExpr, StringBuilder sb) throws RuntimeException {
+    BigDecimal value = new BigDecimal(decExpr.getIntFromDecimal());
+    sb.append((value.setScale(decExpr.getScale())).toString());
+    return null;
+  }
+
+  @Override
+  public Void visitDecimal18Constant(Decimal18Expression decExpr, StringBuilder sb) throws RuntimeException {
+    BigDecimal value = new BigDecimal(decExpr.getLongFromDecimal());
+    sb.append((value.setScale(decExpr.getScale())).toString());
+    return null;
+  }
+
+  @Override
+  public Void visitDecimal28Constant(Decimal28Expression decExpr, StringBuilder sb) throws RuntimeException {
+    sb.append(decExpr.toString());
+    return null;
+  }
+
+  @Override
+  public Void visitDecimal38Constant(Decimal38Expression decExpr, StringBuilder sb) throws RuntimeException {
+    sb.append(decExpr.getBigDecimal().toString());
+    return null;
+  }
+
+  @Override
+  public Void visitDoubleConstant(DoubleExpression dExpr, StringBuilder sb) throws RuntimeException {
+    sb.append(dExpr.getDouble());
+    return null;
+  }
+
+  @Override
+  public Void visitBooleanConstant(BooleanExpression e, StringBuilder sb) throws RuntimeException {
+    sb.append(e.getBoolean());
+    return null;
+  }
+
+  @Override
+  public Void visitQuotedStringConstant(QuotedString e, StringBuilder sb) throws RuntimeException {
+    sb.append("'");
+    sb.append(e.value);
+    sb.append("'");
+    return null;
+  }
+
+  @Override
+  public Void visitConvertExpression(ConvertExpression e, StringBuilder sb) throws RuntimeException {
+    sb.append(e.getConvertFunction()).append("(");
+    e.getInput().accept(this, sb);
+    sb.append(", '").append(e.getEncodingType()).append("')");
+    return null;
+  }
+
+  @Override
+  public Void visitCastExpression(CastExpression e, StringBuilder sb) throws RuntimeException {
+    MajorType mt = e.getMajorType();
+
+    sb.append("cast( (");
+    e.getInput().accept(this, sb);
+    sb.append(" ) as ");
+    sb.append(mt.getMinorType().name());
+
+    switch(mt.getMinorType()) {
+    case FLOAT4:
+    case FLOAT8:
+    case BIT:
+    case INT:
+    case TINYINT:
+    case SMALLINT:
+    case BIGINT:
+    case UINT1:
+    case UINT2:
+    case UINT4:
+    case UINT8:
+    case DATE:
+    case TIMESTAMP:
+    case TIMESTAMPTZ:
+    case TIME:
+    case INTERVAL:
+    case INTERVALDAY:
+    case INTERVALYEAR:
+      // do nothing else.
+      break;
+    case VAR16CHAR:
+    case VARBINARY:
+    case VARCHAR:
+    case FIXED16CHAR:
+    case FIXEDBINARY:
+    case FIXEDCHAR:
+
+      // add size in parens
+      sb.append("(");
+      sb.append(mt.getWidth());
+      sb.append(")");
+      break;
+    case DECIMAL9:
+    case DECIMAL18:
+    case DECIMAL28DENSE:
+    case DECIMAL28SPARSE:
+    case DECIMAL38DENSE:
+    case DECIMAL38SPARSE:
+
+      // add scale and precision
+      sb.append("(");
+      sb.append(mt.getPrecision());
+      sb.append(", ");
+      sb.append(mt.getScale());
+      sb.append(")");
+      break;
+    default:
+      throw new UnsupportedOperationException(String.format("Unable to convert cast expression %s into string.", e));
+    }
+    sb.append(" )");
+    return null;
+  }
+
+  @Override
+  public Void visitFloatConstant(FloatExpression fExpr, StringBuilder sb) throws RuntimeException {
+    sb.append(fExpr.getFloat());
+    return null;
+  }
+
+  @Override
+  public Void visitIntConstant(IntExpression intExpr, StringBuilder sb) throws RuntimeException {
+    sb.append(intExpr.getInt());
+    return null;
+  }
+
+  @Override
+  public Void visitNullConstant(TypedNullConstant e, StringBuilder sb) throws RuntimeException {
+    sb.append("NULL");
+    return null;
+  }
+
+  @Override
+  public Void visitNullExpression(NullExpression e, StringBuilder sb) throws RuntimeException {
+    sb.append("NULL");
+    return null;
+  }
+
+  @Override
+  public Void visitUnknown(LogicalExpression e, StringBuilder sb) {
+    sb.append(e.toString());
+    return null;
+  }
+}

http://git-wip-us.apache.org/repos/asf/drill/blob/44dea433/logical/src/main/java/org/apache/drill/common/expression/FieldReference.java
----------------------------------------------------------------------
diff --git a/logical/src/main/java/org/apache/drill/common/expression/FieldReference.java b/logical/src/main/java/org/apache/drill/common/expression/FieldReference.java
new file mode 100644
index 0000000..7d0e86f
--- /dev/null
+++ b/logical/src/main/java/org/apache/drill/common/expression/FieldReference.java
@@ -0,0 +1,133 @@
+/**
+ * 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.common.expression;
+
+import java.io.IOException;
+
+import org.apache.drill.common.expression.FieldReference.De;
+import org.apache.drill.common.expression.FieldReference.Se;
+import org.apache.drill.common.expression.PathSegment.NameSegment;
+import org.apache.drill.common.types.TypeProtos.MajorType;
+
+import com.fasterxml.jackson.core.JsonGenerationException;
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.DeserializationContext;
+import com.fasterxml.jackson.databind.SerializerProvider;
+import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
+import com.fasterxml.jackson.databind.annotation.JsonSerialize;
+import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
+import com.fasterxml.jackson.databind.ser.std.StdSerializer;
+
+@JsonSerialize(using = Se.class)
+@JsonDeserialize(using = De.class)
+public class FieldReference extends SchemaPath {
+  MajorType overrideType;
+
+  public FieldReference(SchemaPath sp) {
+    super(sp);
+    checkData();
+  }
+
+  private void checkData() {
+    if (getRootSegment().getChild() != null) {
+      throw new UnsupportedOperationException("Field references must be singular names.");
+    }
+
+  }
+
+
+  private void checkSimpleString(CharSequence value) {
+    if (value.toString().contains(".")) {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Unhandled field reference \"%s\"; a field reference identifier"
+              + " must not have the form of a qualified name (i.e., with \".\").",
+              value));
+    }
+  }
+
+  public FieldReference(CharSequence value) {
+    this(value, ExpressionPosition.UNKNOWN);
+    checkSimpleString(value);
+  }
+
+  public static FieldReference getWithQuotedRef(CharSequence safeString) {
+    return new FieldReference(safeString, ExpressionPosition.UNKNOWN, false);
+  }
+
+
+  public FieldReference(CharSequence value, ExpressionPosition pos) {
+    this(value, pos, true);
+  }
+
+  public FieldReference(CharSequence value, ExpressionPosition pos, boolean check) {
+    super(new NameSegment(value), pos);
+    if (check) {
+      checkData();
+      checkSimpleString(value);
+    }
+
+  }
+
+  public FieldReference(String value, ExpressionPosition pos, MajorType dataType) {
+    this(value, pos);
+    this.overrideType = dataType;
+  }
+
+  @Override
+  public MajorType getMajorType() {
+    if (overrideType == null) {
+      return super.getMajorType();
+    } else {
+      return overrideType;
+    }
+  }
+
+  public static class De extends StdDeserializer<FieldReference> {
+
+    public De() {
+      super(FieldReference.class);
+    }
+
+    @Override
+    public FieldReference deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException,
+        JsonProcessingException {
+      String ref = this._parseString(jp, ctxt);
+      ref = ref.replace("`", "");
+      return new FieldReference(ref, ExpressionPosition.UNKNOWN, false);
+    }
+
+  }
+
+  public static class Se extends StdSerializer<FieldReference> {
+
+    public Se() {
+      super(FieldReference.class);
+    }
+
+    @Override
+    public void serialize(FieldReference value, JsonGenerator jgen, SerializerProvider provider) throws IOException,
+        JsonGenerationException {
+      jgen.writeString('`' + value.getRootSegment().getNameSegment().getPath() + '`');
+    }
+
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/drill/blob/44dea433/logical/src/main/java/org/apache/drill/common/expression/FunctionCall.java
----------------------------------------------------------------------
diff --git a/logical/src/main/java/org/apache/drill/common/expression/FunctionCall.java b/logical/src/main/java/org/apache/drill/common/expression/FunctionCall.java
new file mode 100644
index 0000000..938ab0a
--- /dev/null
+++ b/logical/src/main/java/org/apache/drill/common/expression/FunctionCall.java
@@ -0,0 +1,81 @@
+/**
+ * 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.common.expression;
+
+import java.util.Iterator;
+import java.util.List;
+
+import org.apache.drill.common.expression.visitors.ExprVisitor;
+import org.apache.drill.common.types.TypeProtos.MajorType;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+
+public class FunctionCall extends LogicalExpressionBase implements Iterable<LogicalExpression> {
+  private final String name;
+  public final ImmutableList<LogicalExpression> args;
+  private final ExpressionPosition pos;
+
+  public FunctionCall(String name, List<LogicalExpression> args, ExpressionPosition pos) {
+    super(pos);
+    this.name = name;
+
+    if (args == null) {
+      args = Lists.newArrayList();
+    }
+
+    if (!(args instanceof ImmutableList)) {
+      args = ImmutableList.copyOf(args);
+    }
+    this.args = (ImmutableList<LogicalExpression>) args;
+    this.pos = pos;
+  }
+
+  public String getName() {
+    return name;
+  }
+
+  @Override
+  public ExpressionPosition getPosition() {
+    return pos;
+  }
+
+  @Override
+  public <T, V, E extends Exception> T accept(ExprVisitor<T, V, E> visitor, V value) throws E{
+    return visitor.visitFunctionCall(this, value);
+  }
+
+  @Override
+  public Iterator<LogicalExpression> iterator() {
+    return args.iterator();
+  }
+
+  @Override
+  public MajorType getMajorType() {
+    throw new UnsupportedOperationException(
+      "No return type as FunctionCall is not a materialized expression");
+  }
+
+  @Override
+  public String toString() {
+    final int maxLen = 10;
+    return "FunctionCall [func=" + name + ", args="
+        + (args != null ? args.subList(0, Math.min(args.size(), maxLen)) : null) + ", pos=" + pos + "]";
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/drill/blob/44dea433/logical/src/main/java/org/apache/drill/common/expression/FunctionCallFactory.java
----------------------------------------------------------------------
diff --git a/logical/src/main/java/org/apache/drill/common/expression/FunctionCallFactory.java b/logical/src/main/java/org/apache/drill/common/expression/FunctionCallFactory.java
new file mode 100644
index 0000000..9128a78
--- /dev/null
+++ b/logical/src/main/java/org/apache/drill/common/expression/FunctionCallFactory.java
@@ -0,0 +1,132 @@
+/**
+ * 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.common.expression;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.drill.common.exceptions.DrillRuntimeException;
+import org.apache.drill.common.types.TypeProtos.MajorType;
+
+import com.google.common.collect.Lists;
+
+public class FunctionCallFactory {
+  static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(FunctionCallFactory.class);
+
+  private static Map<String, String> opToFuncTable = new HashMap<>();
+
+  static {
+    opToFuncTable.put("+", "add");
+    opToFuncTable.put("-", "subtract");
+    opToFuncTable.put("/", "divide");
+    opToFuncTable.put("*", "multiply");
+    opToFuncTable.put("%", "modulo");
+    opToFuncTable.put("^", "xor");
+    opToFuncTable.put("||", "concatOperator");
+    opToFuncTable.put("or", "booleanOr");
+    opToFuncTable.put("and", "booleanAnd");
+    opToFuncTable.put(">", "greater_than");
+    opToFuncTable.put("<", "less_than");
+    opToFuncTable.put("==", "equal");
+    opToFuncTable.put("=", "equal");
+    opToFuncTable.put("!=", "not_equal");
+    opToFuncTable.put("<>", "not_equal");
+    opToFuncTable.put(">=", "greater_than_or_equal_to");
+    opToFuncTable.put("<=", "less_than_or_equal_to");
+    opToFuncTable.put("is null", "isnull");
+    opToFuncTable.put("is not null", "isnotnull");
+    opToFuncTable.put("is true", "istrue");
+    opToFuncTable.put("is not true", "isnottrue");
+    opToFuncTable.put("is false", "isfalse");
+    opToFuncTable.put("is not false", "isnotfalse");
+    opToFuncTable.put("similar to", "similar_to");
+
+    opToFuncTable.put("!", "not");
+    opToFuncTable.put("u-", "negative");
+  }
+
+  private static String replaceOpWithFuncName(String op) {
+    return (opToFuncTable.containsKey(op)) ? (opToFuncTable.get(op)) : op;
+  }
+
+  public static boolean isBooleanOperator(String funcName) {
+    String opName  = replaceOpWithFuncName(funcName);
+    return opName.equals("booleanAnd") || opName.equals("booleanOr");
+  }
+
+  /*
+   * create a cast function.
+   * arguments : type -- targetType
+   *             ep   -- input expression position
+   *             expr -- input expression
+   */
+  public static LogicalExpression createCast(MajorType type, ExpressionPosition ep, LogicalExpression expr){
+    return new CastExpression(expr, type, ep);
+  }
+
+  public static LogicalExpression createConvert(String function, String conversionType, LogicalExpression expr, ExpressionPosition ep) {
+    return new ConvertExpression(function, conversionType, expr, ep);
+  }
+
+  public static LogicalExpression createExpression(String functionName, List<LogicalExpression> args){
+    return createExpression(functionName, ExpressionPosition.UNKNOWN, args);
+  }
+
+  public static LogicalExpression createExpression(String functionName, ExpressionPosition ep, List<LogicalExpression> args){
+    String name = replaceOpWithFuncName(functionName);
+    if (isBooleanOperator(name)) {
+      return new BooleanOperator(name, args, ep);
+    } else {
+      return new FunctionCall(name, args, ep);
+    }
+  }
+
+  public static LogicalExpression createExpression(String functionName, ExpressionPosition ep, LogicalExpression... e){
+    return createExpression(functionName, ep, Lists.newArrayList(e));
+  }
+
+  public static LogicalExpression createBooleanOperator(String functionName, List<LogicalExpression> args){
+    return createBooleanOperator(functionName, ExpressionPosition.UNKNOWN, args);
+  }
+
+  public static LogicalExpression createBooleanOperator(String functionName, ExpressionPosition ep, List<LogicalExpression> args){
+    return new BooleanOperator(replaceOpWithFuncName(functionName), args, ep);
+  }
+
+  public static LogicalExpression createByOp(List<LogicalExpression> args, ExpressionPosition ep, List<String> opTypes) {
+    if (args.size() == 1) {
+      return args.get(0);
+    }
+
+    if (args.size() - 1 != opTypes.size()) {
+      throw new DrillRuntimeException("Must receive one more expression then the provided number of operators.");
+    }
+
+    LogicalExpression first = args.get(0);
+    for (int i = 0; i < opTypes.size(); i++) {
+      List<LogicalExpression> l2 = new ArrayList<LogicalExpression>();
+      l2.add(first);
+      l2.add(args.get(i + 1));
+      first = createExpression(opTypes.get(i), ep, l2);
+    }
+    return first;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/drill/blob/44dea433/logical/src/main/java/org/apache/drill/common/expression/FunctionHolderExpression.java
----------------------------------------------------------------------
diff --git a/logical/src/main/java/org/apache/drill/common/expression/FunctionHolderExpression.java b/logical/src/main/java/org/apache/drill/common/expression/FunctionHolderExpression.java
new file mode 100644
index 0000000..d5497f7
--- /dev/null
+++ b/logical/src/main/java/org/apache/drill/common/expression/FunctionHolderExpression.java
@@ -0,0 +1,83 @@
+/**
+ * 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.common.expression;
+
+import java.util.List;
+
+import org.apache.drill.common.expression.fn.FuncHolder;
+import org.apache.drill.common.expression.visitors.ExprVisitor;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+
+public abstract class FunctionHolderExpression extends LogicalExpressionBase {
+  public final ImmutableList<LogicalExpression> args;
+  public final String nameUsed;
+
+  public FunctionHolderExpression(String nameUsed, ExpressionPosition pos, List<LogicalExpression> args) {
+    super(pos);
+    if (args == null) {
+      args = Lists.newArrayList();
+    }
+
+    if (!(args instanceof ImmutableList)) {
+      args = ImmutableList.copyOf(args);
+    }
+    this.args = (ImmutableList<LogicalExpression>) args;
+    this.nameUsed = nameUsed;
+  }
+
+  @Override
+  public <T, V, E extends Exception> T accept(ExprVisitor<T, V, E> visitor, V value) throws E {
+    return visitor.visitFunctionHolderExpression(this, value);
+  }
+
+  /**
+   * A function can have multiple names, it returns the function name used in the query
+   * @return
+   */
+  public String getName() {
+    return nameUsed;
+  }
+
+  /**
+   * constant input expected for i'th argument?
+   * @param i
+   * @return
+   */
+  public abstract boolean argConstantOnly(int i);
+
+  /**
+   * @return aggregating function or not
+   */
+  public abstract boolean isAggregating();
+
+  /**
+   * is the function output non-deterministic?
+   */
+  public abstract boolean isRandom();
+
+  /**
+   * @ return a copy of FunctionHolderExpression, with passed in argument list.
+   */
+  public abstract FunctionHolderExpression copy(List<LogicalExpression> args);
+
+  /** Return the underlying function implementation holder. */
+  public abstract FuncHolder getHolder();
+
+}

http://git-wip-us.apache.org/repos/asf/drill/blob/44dea433/logical/src/main/java/org/apache/drill/common/expression/FunctionName.java
----------------------------------------------------------------------
diff --git a/logical/src/main/java/org/apache/drill/common/expression/FunctionName.java b/logical/src/main/java/org/apache/drill/common/expression/FunctionName.java
new file mode 100644
index 0000000..2164cb2
--- /dev/null
+++ b/logical/src/main/java/org/apache/drill/common/expression/FunctionName.java
@@ -0,0 +1,29 @@
+/**
+ * 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.common.expression;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Retention(RetentionPolicy.RUNTIME)
+@Target({ElementType.TYPE})
+public @interface FunctionName {
+  String value();
+}

http://git-wip-us.apache.org/repos/asf/drill/blob/44dea433/logical/src/main/java/org/apache/drill/common/expression/IfExpression.java
----------------------------------------------------------------------
diff --git a/logical/src/main/java/org/apache/drill/common/expression/IfExpression.java b/logical/src/main/java/org/apache/drill/common/expression/IfExpression.java
new file mode 100644
index 0000000..e85caa0
--- /dev/null
+++ b/logical/src/main/java/org/apache/drill/common/expression/IfExpression.java
@@ -0,0 +1,163 @@
+/**
+ * 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.common.expression;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+
+import com.google.common.collect.Sets;
+import org.apache.drill.common.expression.visitors.ExprVisitor;
+import org.apache.drill.common.types.TypeProtos.DataMode;
+import org.apache.drill.common.types.TypeProtos.MajorType;
+import org.apache.drill.common.types.TypeProtos.MinorType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+
+public class IfExpression extends LogicalExpressionBase {
+  static final Logger logger = LoggerFactory.getLogger(IfExpression.class);
+
+  public final IfCondition ifCondition;
+  public final LogicalExpression elseExpression;
+  public final MajorType outputType;
+
+  private IfExpression(ExpressionPosition pos, IfCondition conditions, LogicalExpression elseExpression, MajorType outputType) {
+    super(pos);
+    this.ifCondition = conditions;
+    this.elseExpression = elseExpression;
+    this.outputType = outputType;
+  }
+
+  public static class IfCondition{
+    public final LogicalExpression condition;
+    public final LogicalExpression expression;
+
+    public IfCondition(LogicalExpression condition, LogicalExpression expression) {
+      //logger.debug("Generating IfCondition {}, {}", condition, expression);
+
+      this.condition = condition;
+      this.expression = expression;
+    }
+
+  }
+
+  @Override
+  public <T, V, E extends Exception> T accept(ExprVisitor<T, V, E> visitor, V value) throws E {
+    return visitor.visitIfExpression(this, value);
+  }
+
+  public static class Builder {
+    IfCondition conditions;
+    private LogicalExpression elseExpression;
+    private ExpressionPosition pos = ExpressionPosition.UNKNOWN;
+    private MajorType outputType;
+
+    public Builder setPosition(ExpressionPosition pos) {
+      this.pos = pos;
+      return this;
+    }
+
+    public Builder setElse(LogicalExpression elseExpression) {
+      this.elseExpression = elseExpression;
+            return this;
+    }
+
+    public Builder setIfCondition(IfCondition conditions) {
+      this.conditions = conditions;
+      return this;
+    }
+
+    public Builder setOutputType(MajorType outputType) {
+      this.outputType = outputType;
+      return this;
+    }
+
+    public IfExpression build(){
+      Preconditions.checkNotNull(pos);
+      Preconditions.checkNotNull(conditions);
+      return new IfExpression(pos, conditions, elseExpression, outputType);
+    }
+
+  }
+
+  @Override
+  public MajorType getMajorType() {
+    if (outputType != null) {
+      return outputType;
+    }
+
+    MajorType majorType = elseExpression.getMajorType();
+    if (majorType.getMinorType() == MinorType.UNION) {
+      Set<MinorType> subtypes = Sets.newHashSet();
+      for (MinorType subtype : majorType.getSubTypeList()) {
+        subtypes.add(subtype);
+      }
+      for (MinorType subtype : ifCondition.expression.getMajorType().getSubTypeList()) {
+        subtypes.add(subtype);
+      }
+      MajorType.Builder builder = MajorType.newBuilder().setMinorType(MinorType.UNION).setMode(DataMode.OPTIONAL);
+      for (MinorType subtype : subtypes) {
+        builder.addSubType(subtype);
+      }
+      return builder.build();
+    }
+    if (majorType.getMode() == DataMode.OPTIONAL) {
+      return majorType;
+    }
+
+    if (ifCondition.expression.getMajorType().getMode() == DataMode.OPTIONAL) {
+      assert ifCondition.expression.getMajorType().getMinorType() == majorType.getMinorType();
+
+      return ifCondition.expression.getMajorType();
+    }
+
+    return majorType;
+  }
+
+  public static Builder newBuilder() {
+    return new Builder();
+  }
+
+  @Override
+  public Iterator<LogicalExpression> iterator() {
+    List<LogicalExpression> children = Lists.newLinkedList();
+
+    children.add(ifCondition.condition);
+    children.add(ifCondition.expression);
+    children.add(this.elseExpression);
+    return children.iterator();
+  }
+
+  @Override
+  public int getCumulativeCost() {
+    // return the average cost of operands for a boolean "and" | "or"
+    int cost = this.getSelfCost();
+
+    int i = 0;
+    for (LogicalExpression e : this) {
+      cost += e.getCumulativeCost();
+      i++;
+    }
+
+    return (int) (cost / i) ;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/drill/blob/44dea433/logical/src/main/java/org/apache/drill/common/expression/LogicalExpression.java
----------------------------------------------------------------------
diff --git a/logical/src/main/java/org/apache/drill/common/expression/LogicalExpression.java b/logical/src/main/java/org/apache/drill/common/expression/LogicalExpression.java
new file mode 100644
index 0000000..a74ae29
--- /dev/null
+++ b/logical/src/main/java/org/apache/drill/common/expression/LogicalExpression.java
@@ -0,0 +1,110 @@
+/**
+ * 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.common.expression;
+
+import java.io.IOException;
+
+import org.antlr.runtime.ANTLRStringStream;
+import org.antlr.runtime.CommonTokenStream;
+import org.antlr.runtime.RecognitionException;
+import org.apache.drill.common.config.DrillConfig;
+import org.apache.drill.common.expression.parser.ExprLexer;
+import org.apache.drill.common.expression.parser.ExprParser;
+import org.apache.drill.common.expression.parser.ExprParser.parse_return;
+import org.apache.drill.common.expression.visitors.ExprVisitor;
+import org.apache.drill.common.types.TypeProtos.MajorType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.fasterxml.jackson.core.JsonGenerationException;
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.DeserializationContext;
+import com.fasterxml.jackson.databind.SerializerProvider;
+import com.fasterxml.jackson.databind.annotation.JsonSerialize;
+import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
+import com.fasterxml.jackson.databind.ser.std.StdSerializer;
+
+//@JsonDeserialize(using = LogicalExpression.De.class)  // Excluded as we need to register this with the DrillConfig.
+@JsonSerialize(using = LogicalExpression.Se.class)
+public interface LogicalExpression extends Iterable<LogicalExpression>{
+  static final Logger logger = LoggerFactory.getLogger(LogicalExpression.class);
+
+  public abstract MajorType getMajorType();
+
+  public <T, V, E extends Exception> T accept(ExprVisitor<T, V, E> visitor, V value) throws E;
+
+  public ExpressionPosition getPosition();
+
+  public int getSelfCost();
+  public int getCumulativeCost();
+
+  public static class De extends StdDeserializer<LogicalExpression> {
+    DrillConfig config;
+
+    public De(DrillConfig config) {
+      super(LogicalExpression.class);
+      this.config = config;
+    }
+
+    @Override
+    public LogicalExpression deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException,
+        JsonProcessingException {
+      String expr = jp.getText();
+
+      if (expr == null || expr.isEmpty()) {
+        return null;
+      }
+      try {
+        // logger.debug("Parsing expression string '{}'", expr);
+        ExprLexer lexer = new ExprLexer(new ANTLRStringStream(expr));
+        CommonTokenStream tokens = new CommonTokenStream(lexer);
+        ExprParser parser = new ExprParser(tokens);
+
+        //TODO: move functionregistry and error collector to injectables.
+        //ctxt.findInjectableValue(valueId, forProperty, beanInstance)
+        parse_return ret = parser.parse();
+
+        // ret.e.resolveAndValidate(expr, errorCollector);
+        return ret.e;
+      } catch (RecognitionException e) {
+        throw new RuntimeException(e);
+      }
+    }
+
+  }
+
+  public static class Se extends StdSerializer<LogicalExpression> {
+
+    protected Se() {
+      super(LogicalExpression.class);
+    }
+
+    @Override
+    public void serialize(LogicalExpression value, JsonGenerator jgen, SerializerProvider provider) throws IOException,
+        JsonGenerationException {
+      StringBuilder sb = new StringBuilder();
+      ExpressionStringBuilder esb = new ExpressionStringBuilder();
+      value.accept(esb, sb);
+      jgen.writeString(sb.toString());
+    }
+
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/drill/blob/44dea433/logical/src/main/java/org/apache/drill/common/expression/LogicalExpressionBase.java
----------------------------------------------------------------------
diff --git a/logical/src/main/java/org/apache/drill/common/expression/LogicalExpressionBase.java b/logical/src/main/java/org/apache/drill/common/expression/LogicalExpressionBase.java
new file mode 100644
index 0000000..7dfe4a2
--- /dev/null
+++ b/logical/src/main/java/org/apache/drill/common/expression/LogicalExpressionBase.java
@@ -0,0 +1,81 @@
+/**
+ * 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.common.expression;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.module.SimpleModule;
+import org.apache.drill.common.config.DrillConfig;
+import org.apache.drill.common.types.TypeProtos.MajorType;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+
+
+@JsonPropertyOrder({ "type" })
+public abstract class LogicalExpressionBase implements LogicalExpression {
+
+  private final ExpressionPosition pos;
+
+  protected LogicalExpressionBase(ExpressionPosition pos) {
+    super();
+    this.pos = pos;
+  }
+
+  @Override
+  public ExpressionPosition getPosition() {
+    return pos;
+  }
+
+  protected void i(StringBuilder sb, int indent) {
+    for (int i = 0; i < indent; i++){
+      sb.append("  ");
+    }
+  }
+
+  @Override
+  public MajorType getMajorType() {
+    throw new UnsupportedOperationException(String.format("The type of %s doesn't currently support LogicalExpression.getDataType().", this.getClass().getCanonicalName()));
+  }
+
+  @JsonProperty("type")
+  public String getDescription() {
+    return this.getClass().getSimpleName();
+  }
+
+  @JsonIgnore
+  public int getSelfCost() {
+    return 0;
+  }
+
+  @JsonIgnore
+  public int getCumulativeCost()  {
+    int cost = this.getSelfCost();
+
+    for (LogicalExpression e : this) {
+      cost += e.getCumulativeCost();
+    }
+
+    return cost;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/drill/blob/44dea433/logical/src/main/java/org/apache/drill/common/expression/NullExpression.java
----------------------------------------------------------------------
diff --git a/logical/src/main/java/org/apache/drill/common/expression/NullExpression.java b/logical/src/main/java/org/apache/drill/common/expression/NullExpression.java
new file mode 100644
index 0000000..e00399f
--- /dev/null
+++ b/logical/src/main/java/org/apache/drill/common/expression/NullExpression.java
@@ -0,0 +1,60 @@
+/**
+ * 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.common.expression;
+
+import java.util.Iterator;
+
+import org.apache.drill.common.expression.visitors.ExprVisitor;
+import org.apache.drill.common.types.TypeProtos.MajorType;
+import org.apache.drill.common.types.TypeProtos.MinorType;
+import org.apache.drill.common.types.Types;
+
+import com.google.common.collect.Iterators;
+
+public class NullExpression implements LogicalExpression{
+  static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(NullExpression.class);
+
+  public static final NullExpression INSTANCE = new NullExpression();
+
+  final MajorType t = Types.optional(MinorType.NULL);
+
+  @Override
+  public MajorType getMajorType() {
+    return t;
+  }
+
+  @Override
+  public <T, V, E extends Exception> T accept(ExprVisitor<T, V, E> visitor, V value) throws E {
+    return visitor.visitNullExpression(this, value);
+  }
+
+  @Override
+  public ExpressionPosition getPosition() {
+    return ExpressionPosition.UNKNOWN;
+  }
+
+  @Override
+  public Iterator<LogicalExpression> iterator() {
+    return Iterators.emptyIterator();
+  }
+
+  public int getSelfCost() { return 0 ; }
+
+  public int getCumulativeCost() { return 0; }
+
+}

http://git-wip-us.apache.org/repos/asf/drill/blob/44dea433/logical/src/main/java/org/apache/drill/common/expression/OutputTypeDeterminer.java
----------------------------------------------------------------------
diff --git a/logical/src/main/java/org/apache/drill/common/expression/OutputTypeDeterminer.java b/logical/src/main/java/org/apache/drill/common/expression/OutputTypeDeterminer.java
new file mode 100644
index 0000000..a03524c
--- /dev/null
+++ b/logical/src/main/java/org/apache/drill/common/expression/OutputTypeDeterminer.java
@@ -0,0 +1,97 @@
+/**
+ * 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.common.expression;
+
+import java.util.List;
+
+import org.apache.drill.common.types.TypeProtos.DataMode;
+import org.apache.drill.common.types.TypeProtos.MajorType;
+import org.apache.drill.common.types.TypeProtos.MinorType;
+import org.apache.drill.common.types.Types;
+
+public interface OutputTypeDeterminer {
+
+  public static OutputTypeDeterminer FIXED_BIT = new FixedType(Types.required(MinorType.BIT));
+  public static OutputTypeDeterminer FIXED_INT = new FixedType(Types.required(MinorType.INT));
+  public static OutputTypeDeterminer FIXED_BIGINT = new FixedType(Types.required(MinorType.BIGINT));
+  public static OutputTypeDeterminer FIXED_FLOAT4 = new FixedType(Types.required(MinorType.FLOAT4));
+  public static OutputTypeDeterminer FIXED_FLOAT8 = new FixedType(Types.required(MinorType.FLOAT8));
+  public static OutputTypeDeterminer FIXED_VARCHAR = new FixedType(Types.required(MinorType.VARCHAR));
+  public static OutputTypeDeterminer FIXED_VARBINARY = new FixedType(Types.required(MinorType.VARBINARY));
+  public static OutputTypeDeterminer FIXED_VAR16CHAR = new FixedType(Types.required(MinorType.VAR16CHAR));
+
+  public MajorType getOutputType(List<LogicalExpression> expressions);
+
+
+  public static class FixedType implements OutputTypeDeterminer{
+    public MajorType outputType;
+
+
+    public FixedType(MajorType outputType) {
+      super();
+      this.outputType = outputType;
+    }
+
+
+    @Override
+    public MajorType getOutputType(List<LogicalExpression> expressions) {
+      return outputType;
+    }
+
+  }
+
+  public static class SameAsFirstInput implements OutputTypeDeterminer{
+    @Override
+    public MajorType getOutputType(List<LogicalExpression> expressions) {
+      return expressions.get(0).getMajorType();
+    }
+  }
+
+  public static class SameAsAnySoft implements OutputTypeDeterminer{
+    @Override
+    public MajorType getOutputType(List<LogicalExpression> expressions) {
+      for(LogicalExpression e : expressions){
+        if(e.getMajorType().getMode() == DataMode.OPTIONAL){
+          return e.getMajorType();
+        }
+      }
+      return expressions.get(0).getMajorType();
+    }
+  }
+
+  public static class NullIfNullType implements OutputTypeDeterminer{
+    public MinorType outputMinorType;
+
+
+    public NullIfNullType(MinorType outputType) {
+      super();
+      this.outputMinorType = outputType;
+    }
+
+    @Override
+    public MajorType getOutputType(List<LogicalExpression> expressions) {
+      for(LogicalExpression e : expressions){
+        if(e.getMajorType().getMode() == DataMode.OPTIONAL){
+          return Types.optional(outputMinorType);
+        }
+      }
+      return Types.required(outputMinorType);
+    }
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/drill/blob/44dea433/logical/src/main/java/org/apache/drill/common/expression/PathSegment.java
----------------------------------------------------------------------
diff --git a/logical/src/main/java/org/apache/drill/common/expression/PathSegment.java b/logical/src/main/java/org/apache/drill/common/expression/PathSegment.java
new file mode 100644
index 0000000..744a07f
--- /dev/null
+++ b/logical/src/main/java/org/apache/drill/common/expression/PathSegment.java
@@ -0,0 +1,309 @@
+/**
+ * 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.common.expression;
+
+public abstract class PathSegment{
+
+  PathSegment child;
+
+  int hash;
+
+  public abstract PathSegment cloneWithNewChild(PathSegment segment);
+  @Override
+  public abstract PathSegment clone();
+
+  public static final class ArraySegment extends PathSegment {
+    private final int index;
+
+    public ArraySegment(String numberAsText, PathSegment child) {
+      this(Integer.parseInt(numberAsText), child);
+    }
+
+    public ArraySegment(int index, PathSegment child) {
+      this.child = child;
+      this.index = index;
+      assert index >=0;
+    }
+
+    public ArraySegment(PathSegment child) {
+      this.child = child;
+      this.index = -1;
+    }
+
+    public boolean hasIndex() {
+      return index != -1;
+    }
+
+    public ArraySegment(int index) {
+      if (index < 0 ) {
+        throw new IllegalArgumentException();
+      }
+      this.index = index;
+    }
+
+    public int getIndex() {
+      return index;
+    }
+
+    @Override
+    public boolean isArray() {
+      return true;
+    }
+
+    @Override
+    public boolean isNamed() {
+      return false;
+    }
+
+    @Override
+    public ArraySegment getArraySegment() {
+      return this;
+    }
+
+    @Override
+    public String toString() {
+      return "ArraySegment [index=" + index + ", getChild()=" + getChild() + "]";
+    }
+
+    @Override
+    public int segmentHashCode() {
+      return index;
+    }
+
+    @Override
+    public boolean segmentEquals(PathSegment obj) {
+      if (this == obj) {
+        return true;
+      } else if (obj == null) {
+        return false;
+      } else if (obj instanceof ArraySegment) {
+        return index == ((ArraySegment)obj).getIndex();
+      }
+      return false;
+    }
+
+    @Override
+    public PathSegment clone() {
+      PathSegment seg = index < 0 ? new ArraySegment(null) : new ArraySegment(index);
+      if (child != null) {
+        seg.setChild(child.clone());
+      }
+      return seg;
+    }
+
+    @Override
+    public ArraySegment cloneWithNewChild(PathSegment newChild) {
+      ArraySegment seg = index < 0 ? new ArraySegment(null) : new ArraySegment(index);
+      if (child != null) {
+        seg.setChild(child.cloneWithNewChild(newChild));
+      } else {
+        seg.setChild(newChild);
+      }
+      return seg;
+    }
+  }
+
+
+  public static final class NameSegment extends PathSegment {
+    private final String path;
+
+    public NameSegment(CharSequence n, PathSegment child) {
+      this.child = child;
+      this.path = n.toString();
+    }
+
+    public NameSegment(CharSequence n) {
+      this.path = n.toString();
+    }
+
+    public String getPath() {
+      return path;
+    }
+
+    @Override
+    public boolean isArray() {
+      return false;
+    }
+
+    @Override
+    public boolean isNamed() {
+      return true;
+    }
+
+    @Override
+    public NameSegment getNameSegment() {
+      return this;
+    }
+
+    @Override
+    public String toString() {
+      return "NameSegment [path=" + path + ", getChild()=" + getChild() + "]";
+    }
+
+    @Override
+    public int segmentHashCode() {
+      return ((path == null) ? 0 : path.toLowerCase().hashCode());
+    }
+
+    @Override
+    public boolean segmentEquals(PathSegment obj) {
+      if (this == obj) {
+        return true;
+      } else if (obj == null) {
+        return false;
+      } else if (getClass() != obj.getClass()) {
+        return false;
+      }
+
+      NameSegment other = (NameSegment) obj;
+      if (path == null) {
+        return other.path == null;
+      }
+      return path.equalsIgnoreCase(other.path);
+    }
+
+    @Override
+    public NameSegment clone() {
+      NameSegment s = new NameSegment(this.path);
+      if (child != null) {
+        s.setChild(child.clone());
+      }
+      return s;
+    }
+
+    @Override
+    public NameSegment cloneWithNewChild(PathSegment newChild) {
+      NameSegment s = new NameSegment(this.path);
+      if (child != null) {
+        s.setChild(child.cloneWithNewChild(newChild));
+      } else {
+        s.setChild(newChild);
+      }
+      return s;
+    }
+
+  }
+
+  public NameSegment getNameSegment() {
+    throw new UnsupportedOperationException();
+  }
+
+  public ArraySegment getArraySegment() {
+    throw new UnsupportedOperationException();
+  }
+
+  public abstract boolean isArray();
+  public abstract boolean isNamed();
+
+  public boolean isLastPath() {
+    return child == null;
+  }
+
+  public PathSegment getChild() {
+    return child;
+  }
+
+  void setChild(PathSegment child) {
+    this.child = child;
+  }
+
+  protected abstract int segmentHashCode();
+  protected abstract boolean segmentEquals(PathSegment other);
+
+  @Override
+  public int hashCode() {
+    int h = hash;
+    if (h == 0) {
+      h = segmentHashCode();
+      h = 31*h + ((child == null) ? 0 : child.hashCode());
+      hash = h;
+    }
+    return h;
+  }
+
+  @Override
+  public boolean equals(Object obj) {
+    if (this == obj) {
+      return true;
+    }
+    if (obj == null) {
+      return false;
+    }
+    if (getClass() != obj.getClass()) {
+      return false;
+    }
+
+    PathSegment other = (PathSegment) obj;
+    if (!segmentEquals(other)) {
+      return false;
+    } else if (child == null) {
+      return (other.child == null);
+    } else {
+      return child.equals(other.child);
+    }
+  }
+
+  /**
+   * Check if another path is contained in this one. This is useful for 2 cases. The first
+   * is checking if the other is lower down in the tree, below this path. The other is if
+   * a path is actually contained above the current one.
+   *
+   * Examples:
+   * [a] . contains( [a.b.c] ) returns true
+   * [a.b.c] . contains( [a] ) returns true
+   *
+   * This behavior is used for cases like scanning json in an event based fashion, when we arrive at
+   * a node in a complex type, we will know the complete path back to the root. This method can
+   * be used to determine if we need the data below. This is true in both the cases where the
+   * column requested from the user is below the current node (in which case we may ignore other nodes
+   * further down the tree, while keeping others). This is also the case if the requested path is further
+   * up the tree, if we know we are at position a.b.c and a.b was a requested column, we need to scan
+   * all of the data at and below the current a.b.c node.
+   *
+   * @param otherSeg - path segment to check if it is contained below this one.
+   * @return - is this a match
+   */
+  public boolean contains(PathSegment otherSeg) {
+    if (this == otherSeg) {
+      return true;
+    }
+    if (otherSeg == null) {
+      return false;
+    }
+    // TODO - fix this in the future to match array segments are part of the path
+    // the current behavior to always return true when we hit an array may be useful in some cases,
+    // but we can get better performance in the JSON reader if we avoid reading unwanted elements in arrays
+    if (otherSeg.isArray() || this.isArray()) {
+      return true;
+    }
+    if (getClass() != otherSeg.getClass()) {
+      return false;
+    }
+
+    if (!segmentEquals(otherSeg)) {
+      return false;
+    }
+    else if (child == null || otherSeg.child == null) {
+      return true;
+    } else {
+      return child.contains(otherSeg.child);
+    }
+
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/drill/blob/44dea433/logical/src/main/java/org/apache/drill/common/expression/SchemaPath.java
----------------------------------------------------------------------
diff --git a/logical/src/main/java/org/apache/drill/common/expression/SchemaPath.java b/logical/src/main/java/org/apache/drill/common/expression/SchemaPath.java
new file mode 100644
index 0000000..f5fc687
--- /dev/null
+++ b/logical/src/main/java/org/apache/drill/common/expression/SchemaPath.java
@@ -0,0 +1,290 @@
+/**
+ * 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.common.expression;
+
+import java.io.IOException;
+import java.util.Iterator;
+
+import org.antlr.runtime.ANTLRStringStream;
+import org.antlr.runtime.CommonTokenStream;
+import org.antlr.runtime.RecognitionException;
+import org.apache.drill.common.config.DrillConfig;
+import org.apache.drill.common.expression.PathSegment.ArraySegment;
+import org.apache.drill.common.expression.PathSegment.NameSegment;
+import org.apache.drill.common.expression.parser.ExprLexer;
+import org.apache.drill.common.expression.parser.ExprParser;
+import org.apache.drill.common.expression.parser.ExprParser.parse_return;
+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.proto.UserBitShared.NamePart;
+import org.apache.drill.exec.proto.UserBitShared.NamePart.Type;
+
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.databind.DeserializationContext;
+import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Iterators;
+
+public class SchemaPath extends LogicalExpressionBase {
+
+  private final NameSegment rootSegment;
+
+  public static SchemaPath getSimplePath(String name) {
+    return getCompoundPath(name);
+  }
+
+  public static SchemaPath getCompoundPath(String... strings) {
+    NameSegment s = null;
+    // loop through strings in reverse order
+    for (int i = strings.length - 1; i >= 0; i--) {
+      s = new NameSegment(strings[i], s);
+    }
+    return new SchemaPath(s);
+  }
+
+  @SuppressWarnings("unused")
+  public PathSegment getLastSegment() {
+    PathSegment s= rootSegment;
+    while (s.getChild() != null) {
+      s = s.getChild();
+    }
+    return s;
+  }
+
+  @Deprecated
+  public SchemaPath(String simpleName, ExpressionPosition pos) {
+    super(pos);
+    this.rootSegment = new NameSegment(simpleName);
+    if (simpleName.contains(".")) {
+      throw new IllegalStateException("This is deprecated and only supports simpe paths.");
+    }
+  }
+
+
+  public NamePart getAsNamePart() {
+    return getNamePart(rootSegment);
+  }
+
+  private static NamePart getNamePart(PathSegment s) {
+    if (s == null) {
+      return null;
+    }
+    NamePart.Builder b = NamePart.newBuilder();
+    if (s.getChild() != null) {
+      b.setChild(getNamePart(s.getChild()));
+    }
+
+    if (s.isArray()) {
+      if (s.getArraySegment().hasIndex()) {
+        throw new IllegalStateException("You cannot convert a indexed schema path to a NamePart.  NameParts can only reference Vectors, not individual records or values.");
+      }
+      b.setType(Type.ARRAY);
+    } else {
+      b.setType(Type.NAME);
+      b.setName(s.getNameSegment().getPath());
+    }
+    return b.build();
+  }
+
+  private static PathSegment getPathSegment(NamePart n) {
+    PathSegment child = n.hasChild() ? getPathSegment(n.getChild()) : null;
+    if (n.getType() == Type.ARRAY) {
+      return new ArraySegment(child);
+    } else {
+      return new NameSegment(n.getName(), child);
+    }
+  }
+
+  public static SchemaPath create(NamePart namePart) {
+    Preconditions.checkArgument(namePart.getType() == NamePart.Type.NAME);
+    return new SchemaPath((NameSegment) getPathSegment(namePart));
+  }
+
+  /**
+   * A simple is a path where there are no repeated elements outside the lowest level of the path.
+   * @return Whether this path is a simple path.
+   */
+  public boolean isSimplePath() {
+    PathSegment seg = rootSegment;
+    while (seg != null) {
+      if (seg.isArray() && !seg.isLastPath()) {
+        return false;
+      }
+      seg = seg.getChild();
+    }
+    return true;
+  }
+
+
+  public SchemaPath(SchemaPath path) {
+    super(path.getPosition());
+    this.rootSegment = path.rootSegment;
+  }
+
+  public SchemaPath(NameSegment rootSegment) {
+    super(ExpressionPosition.UNKNOWN);
+    this.rootSegment = rootSegment;
+  }
+
+  public SchemaPath(NameSegment rootSegment, ExpressionPosition pos) {
+    super(pos);
+    this.rootSegment = rootSegment;
+  }
+
+  @Override
+  public <T, V, E extends Exception> T accept(ExprVisitor<T, V, E> visitor, V value) throws E {
+    return visitor.visitSchemaPath(this, value);
+  }
+
+  public SchemaPath getChild(String childPath) {
+    NameSegment newRoot = rootSegment.cloneWithNewChild(new NameSegment(childPath));
+    return new SchemaPath(newRoot);
+  }
+
+  @SuppressWarnings("unused")
+  public SchemaPath getUnindexedArrayChild() {
+    NameSegment newRoot = rootSegment.cloneWithNewChild(new ArraySegment(null));
+    return new SchemaPath(newRoot);
+  }
+
+  public SchemaPath getChild(int index) {
+    NameSegment newRoot = rootSegment.cloneWithNewChild(new ArraySegment(index));
+    return new SchemaPath(newRoot);
+  }
+
+  public NameSegment getRootSegment() {
+    return rootSegment;
+  }
+
+  @Override
+  public MajorType getMajorType() {
+    return Types.LATE_BIND_TYPE;
+  }
+
+  @Override
+  public int hashCode() {
+    return ((rootSegment == null) ? 0 : rootSegment.hashCode());
+  }
+
+  @Override
+  public boolean equals(Object obj) {
+    if (this == obj) {
+      return true;
+    }
+    if (obj == null) {
+      return false;
+    }
+    if (!(obj instanceof SchemaPath)) {
+      return false;
+    }
+
+    SchemaPath other = (SchemaPath) obj;
+    if (rootSegment == null) {
+      return (other.rootSegment == null);
+    }
+    return rootSegment.equals(other.rootSegment);
+  }
+
+  public boolean contains(Object obj) {
+    if (this == obj) {
+      return true;
+    }
+    if (obj == null) {
+      return false;
+    }
+    if (!(obj instanceof SchemaPath)) {
+      return false;
+    }
+
+    SchemaPath other = (SchemaPath) obj;
+    return rootSegment == null || rootSegment.contains(other.rootSegment);
+  }
+
+  @Override
+  public Iterator<LogicalExpression> iterator() {
+    return Iterators.emptyIterator();
+  }
+
+  @Override
+  public String toString() {
+    return ExpressionStringBuilder.toString(this);
+  }
+
+  public String toExpr() {
+    return ExpressionStringBuilder.toString(this);
+  }
+
+  public String getAsUnescapedPath() {
+    StringBuilder sb = new StringBuilder();
+    PathSegment seg = getRootSegment();
+    if (seg.isArray()) {
+      throw new IllegalStateException("Drill doesn't currently support top level arrays");
+    }
+    sb.append(seg.getNameSegment().getPath());
+
+    while ( (seg = seg.getChild()) != null) {
+      if (seg.isNamed()) {
+        sb.append('.');
+        sb.append(seg.getNameSegment().getPath());
+      } else {
+        sb.append('[');
+        sb.append(seg.getArraySegment().getIndex());
+        sb.append(']');
+      }
+    }
+    return sb.toString();
+  }
+
+  public static class De extends StdDeserializer<SchemaPath> {
+
+    public De() {
+      super(LogicalExpression.class);
+    }
+
+    @Override
+    public SchemaPath deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
+      String expr = jp.getText();
+
+      if (expr == null || expr.isEmpty()) {
+        return null;
+      }
+      try {
+        // logger.debug("Parsing expression string '{}'", expr);
+        ExprLexer lexer = new ExprLexer(new ANTLRStringStream(expr));
+        CommonTokenStream tokens = new CommonTokenStream(lexer);
+        ExprParser parser = new ExprParser(tokens);
+
+        //TODO: move functionregistry and error collector to injectables.
+        //ctxt.findInjectableValue(valueId, forProperty, beanInstance)
+        parse_return ret = parser.parse();
+
+        // ret.e.resolveAndValidate(expr, errorCollector);
+        if (ret.e instanceof SchemaPath) {
+          return (SchemaPath) ret.e;
+        } else {
+          throw new IllegalStateException("Schema path is not a valid format.");
+        }
+      } catch (RecognitionException e) {
+        throw new RuntimeException(e);
+      }
+    }
+
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/drill/blob/44dea433/logical/src/main/java/org/apache/drill/common/expression/TypedNullConstant.java
----------------------------------------------------------------------
diff --git a/logical/src/main/java/org/apache/drill/common/expression/TypedNullConstant.java b/logical/src/main/java/org/apache/drill/common/expression/TypedNullConstant.java
new file mode 100644
index 0000000..bd129d6
--- /dev/null
+++ b/logical/src/main/java/org/apache/drill/common/expression/TypedNullConstant.java
@@ -0,0 +1,54 @@
+/**
+ * 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.common.expression;
+
+import java.util.Iterator;
+
+import org.apache.drill.common.expression.visitors.ExprVisitor;
+import org.apache.drill.common.types.TypeProtos;
+import org.apache.drill.common.types.TypeProtos.DataMode;
+import org.apache.drill.common.types.TypeProtos.MajorType;
+
+import com.google.common.collect.Iterators;
+
+public class TypedNullConstant extends LogicalExpressionBase {
+
+    private final MajorType type;
+
+    public TypedNullConstant(MajorType type) {
+      super(null);
+      this.type = TypeProtos.MajorType.newBuilder().mergeFrom(type).setMode(DataMode.OPTIONAL).build();
+    }
+
+    @Override
+    public MajorType getMajorType() {
+      return this.type;
+    }
+
+
+    @Override
+    public <T, V, E extends Exception> T accept(ExprVisitor<T, V, E> visitor, V value) throws E {
+      return visitor.visitNullConstant(this, value);
+    }
+
+    @Override
+    public Iterator<LogicalExpression> iterator() {
+      return Iterators.emptyIterator();
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/drill/blob/44dea433/logical/src/main/java/org/apache/drill/common/expression/ValidationError.java
----------------------------------------------------------------------
diff --git a/logical/src/main/java/org/apache/drill/common/expression/ValidationError.java b/logical/src/main/java/org/apache/drill/common/expression/ValidationError.java
new file mode 100644
index 0000000..195a6d8
--- /dev/null
+++ b/logical/src/main/java/org/apache/drill/common/expression/ValidationError.java
@@ -0,0 +1,22 @@
+/**
+ * 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.common.expression;
+
+public class ValidationError {
+
+}