You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@flink.apache.org by fh...@apache.org on 2016/05/17 22:49:26 UTC

[1/5] flink git commit: [FLINK-3754] [tableAPI] Add validation phase to Table API before construction of RelNodes.

Repository: flink
Updated Branches:
  refs/heads/master 1e9fff4ab -> f0d543f8c


http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/JoinITCase.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/JoinITCase.scala b/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/JoinITCase.scala
index 3a89de2..1a9be93 100644
--- a/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/JoinITCase.scala
+++ b/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/JoinITCase.scala
@@ -22,7 +22,7 @@ import org.apache.flink.api.scala._
 import org.apache.flink.api.scala.table._
 import org.apache.flink.api.scala.util.CollectionDataSets
 import org.apache.flink.api.table.expressions.Literal
-import org.apache.flink.api.table.{Row, TableEnvironment, TableException}
+import org.apache.flink.api.table.{Row, TableEnvironment, TableException, ValidationException}
 import org.apache.flink.test.util.MultipleProgramsTestBase.TestExecutionMode
 import org.apache.flink.test.util.{MultipleProgramsTestBase, TestBaseUtils}
 import org.junit._
@@ -97,7 +97,7 @@ class JoinITCase(mode: TestExecutionMode) extends MultipleProgramsTestBase(mode)
     TestBaseUtils.compareResultAsText(results.asJava, expected)
   }
 
-  @Test(expected = classOf[IllegalArgumentException])
+  @Test(expected = classOf[ValidationException])
   def testJoinNonExistingKey(): Unit = {
     val env: ExecutionEnvironment = ExecutionEnvironment.getExecutionEnvironment
     val tEnv = TableEnvironment.getTableEnvironment(env)
@@ -111,7 +111,7 @@ class JoinITCase(mode: TestExecutionMode) extends MultipleProgramsTestBase(mode)
       .select('c, 'g)
   }
 
-  @Test(expected = classOf[TableException])
+  @Test(expected = classOf[ValidationException])
   def testJoinWithNonMatchingKeyTypes(): Unit = {
     val env: ExecutionEnvironment = ExecutionEnvironment.getExecutionEnvironment
     val tEnv = TableEnvironment.getTableEnvironment(env)
@@ -125,7 +125,7 @@ class JoinITCase(mode: TestExecutionMode) extends MultipleProgramsTestBase(mode)
       .select('c, 'g).collect()
   }
 
-  @Test(expected = classOf[IllegalArgumentException])
+  @Test(expected = classOf[ValidationException])
   def testJoinWithAmbiguousFields(): Unit = {
     val env: ExecutionEnvironment = ExecutionEnvironment.getExecutionEnvironment
     val tEnv = TableEnvironment.getTableEnvironment(env)
@@ -258,7 +258,7 @@ class JoinITCase(mode: TestExecutionMode) extends MultipleProgramsTestBase(mode)
     TestBaseUtils.compareResultAsText(results.asJava, expected)
   }
 
-  @Test(expected = classOf[TableException])
+  @Test(expected = classOf[ValidationException])
   def testJoinTablesFromDifferentEnvs(): Unit = {
     val env: ExecutionEnvironment = ExecutionEnvironment.getExecutionEnvironment
     val tEnv1 = TableEnvironment.getTableEnvironment(env)

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/SelectITCase.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/SelectITCase.scala b/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/SelectITCase.scala
index c6a6122..9aed5a7 100644
--- a/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/SelectITCase.scala
+++ b/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/SelectITCase.scala
@@ -23,7 +23,7 @@ import org.apache.flink.api.scala.batch.utils.TableProgramsTestBase
 import org.apache.flink.api.scala.batch.utils.TableProgramsTestBase.TableConfigMode
 import org.apache.flink.api.scala.table._
 import org.apache.flink.api.scala.util.CollectionDataSets
-import org.apache.flink.api.table.{Row, TableEnvironment}
+import org.apache.flink.api.table.{Row, TableEnvironment, ValidationException}
 import org.apache.flink.test.util.MultipleProgramsTestBase.TestExecutionMode
 import org.apache.flink.test.util.TestBaseUtils
 import org.junit._
@@ -104,7 +104,7 @@ class SelectITCase(
     TestBaseUtils.compareResultAsText(results.asJava, expected)
   }
 
-  @Test(expected = classOf[IllegalArgumentException])
+  @Test(expected = classOf[ValidationException])
   def testSelectInvalidFieldFields(): Unit = {
     val env = ExecutionEnvironment.getExecutionEnvironment
     val tEnv = TableEnvironment.getTableEnvironment(env, config)
@@ -114,7 +114,7 @@ class SelectITCase(
       .select('a, 'foo)
   }
 
-  @Test(expected = classOf[IllegalArgumentException])
+  @Test(expected = classOf[ValidationException])
   def testSelectAmbiguousRenaming(): Unit = {
     val env = ExecutionEnvironment.getExecutionEnvironment
     val tEnv = TableEnvironment.getTableEnvironment(env, config)
@@ -124,7 +124,7 @@ class SelectITCase(
       .select('a + 1 as 'foo, 'b + 2 as 'foo).toDataSet[Row].print()
   }
 
-  @Test(expected = classOf[IllegalArgumentException])
+  @Test(expected = classOf[ValidationException])
   def testSelectAmbiguousRenaming2(): Unit = {
     val env = ExecutionEnvironment.getExecutionEnvironment
     val tEnv = TableEnvironment.getTableEnvironment(env, config)

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/StringExpressionsITCase.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/StringExpressionsITCase.scala b/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/StringExpressionsITCase.scala
index e428306..f7d998b 100644
--- a/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/StringExpressionsITCase.scala
+++ b/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/StringExpressionsITCase.scala
@@ -20,8 +20,7 @@ package org.apache.flink.api.scala.batch.table
 
 import org.apache.flink.api.scala._
 import org.apache.flink.api.scala.table._
-import org.apache.flink.api.table.codegen.CodeGenException
-import org.apache.flink.api.table.{Row, TableEnvironment}
+import org.apache.flink.api.table.{Row, TableEnvironment, ValidationException}
 import org.apache.flink.test.util.MultipleProgramsTestBase.TestExecutionMode
 import org.apache.flink.test.util.{MultipleProgramsTestBase, TestBaseUtils}
 import org.junit._
@@ -59,7 +58,7 @@ class StringExpressionsITCase(mode: TestExecutionMode) extends MultipleProgramsT
     TestBaseUtils.compareResultAsText(results.asJava, expected)
   }
 
-  @Test(expected = classOf[CodeGenException])
+  @Test(expected = classOf[ValidationException])
   def testNonWorkingSubstring1(): Unit = {
     val env = ExecutionEnvironment.getExecutionEnvironment
     val tEnv = TableEnvironment.getTableEnvironment(env)
@@ -71,7 +70,7 @@ class StringExpressionsITCase(mode: TestExecutionMode) extends MultipleProgramsT
     t.toDataSet[Row].collect()
   }
 
-  @Test(expected = classOf[CodeGenException])
+  @Test(expected = classOf[ValidationException])
   def testNonWorkingSubstring2(): Unit = {
     val env = ExecutionEnvironment.getExecutionEnvironment
     val tEnv = TableEnvironment.getTableEnvironment(env)

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/UnionITCase.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/UnionITCase.scala b/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/UnionITCase.scala
index 7c109a3..29427a5 100644
--- a/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/UnionITCase.scala
+++ b/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/UnionITCase.scala
@@ -23,7 +23,7 @@ import org.apache.flink.api.scala.batch.utils.TableProgramsTestBase
 import org.apache.flink.api.scala.batch.utils.TableProgramsTestBase.TableConfigMode
 import org.apache.flink.api.scala.table._
 import org.apache.flink.api.scala.util.CollectionDataSets
-import org.apache.flink.api.table.{Row, TableEnvironment, TableException}
+import org.apache.flink.api.table.{Row, TableEnvironment, TableException, ValidationException}
 import org.apache.flink.test.util.MultipleProgramsTestBase.TestExecutionMode
 import org.apache.flink.test.util.TestBaseUtils
 import org.junit._
@@ -90,7 +90,7 @@ class UnionITCase(
     TestBaseUtils.compareResultAsText(results.asJava, expected)
   }
 
-  @Test(expected = classOf[IllegalArgumentException])
+  @Test(expected = classOf[ValidationException])
   def testUnionDifferentFieldNames(): Unit = {
     val env: ExecutionEnvironment = ExecutionEnvironment.getExecutionEnvironment
     val tEnv = TableEnvironment.getTableEnvironment(env, config)
@@ -102,7 +102,7 @@ class UnionITCase(
     ds1.unionAll(ds2)
   }
 
-  @Test(expected = classOf[IllegalArgumentException])
+  @Test(expected = classOf[ValidationException])
   def testUnionDifferentFieldTypes(): Unit = {
     val env: ExecutionEnvironment = ExecutionEnvironment.getExecutionEnvironment
     val tEnv = TableEnvironment.getTableEnvironment(env, config)
@@ -159,7 +159,7 @@ class UnionITCase(
     TestBaseUtils.compareResultAsText(results.asJava, expected)
   }
 
-  @Test(expected = classOf[TableException])
+  @Test(expected = classOf[ValidationException])
   def testUnionTablesFromDifferentEnvs(): Unit = {
     val env: ExecutionEnvironment = ExecutionEnvironment.getExecutionEnvironment
     val tEnv1 = TableEnvironment.getTableEnvironment(env, config)

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/expression/utils/ExpressionEvaluator.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/expression/utils/ExpressionEvaluator.scala b/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/expression/utils/ExpressionEvaluator.scala
index 56daa6b..fe606e0 100644
--- a/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/expression/utils/ExpressionEvaluator.scala
+++ b/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/expression/utils/ExpressionEvaluator.scala
@@ -30,7 +30,7 @@ import org.apache.flink.api.scala.{DataSet, ExecutionEnvironment}
 import org.apache.flink.api.table.codegen.{CodeGenerator, GeneratedFunction}
 import org.apache.flink.api.table.expressions.Expression
 import org.apache.flink.api.table.runtime.FunctionCompiler
-import org.apache.flink.api.table.{TableConfig, TableEnvironment}
+import org.apache.flink.api.table.{BatchTableEnvironment, TableConfig, TableEnvironment}
 import org.mockito.Mockito._
 
 /**
@@ -82,8 +82,12 @@ object ExpressionEvaluator {
   }
 
   def evaluate(data: Any, typeInfo: TypeInformation[Any], expr: Expression): String = {
-    val relBuilder = prepareTable(typeInfo)._2
-    evaluate(data, typeInfo, relBuilder, expr.toRexNode(relBuilder))
+    val table = prepareTable(typeInfo)
+    val env = table._3
+    val resolvedExpr =
+      env.asInstanceOf[BatchTableEnvironment].scan("myTable").select(expr).
+        getRelNode.asInstanceOf[LogicalProject].getChildExps.get(0)
+    evaluate(data, typeInfo, table._2, resolvedExpr)
   }
 
   def evaluate(

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/stream/table/UnionITCase.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/stream/table/UnionITCase.scala b/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/stream/table/UnionITCase.scala
index ff0e961..feda75f 100644
--- a/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/stream/table/UnionITCase.scala
+++ b/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/stream/table/UnionITCase.scala
@@ -19,9 +19,9 @@
 package org.apache.flink.api.scala.stream.table
 
 import org.apache.flink.api.scala._
-import org.apache.flink.api.scala.stream.utils.{StreamTestData, StreamITCase}
+import org.apache.flink.api.scala.stream.utils.{StreamITCase, StreamTestData}
 import org.apache.flink.api.scala.table._
-import org.apache.flink.api.table.{Row, TableEnvironment, TableException}
+import org.apache.flink.api.table.{Row, TableEnvironment, ValidationException}
 import org.apache.flink.streaming.api.scala.StreamExecutionEnvironment
 import org.apache.flink.streaming.util.StreamingMultipleProgramsTestBase
 import org.junit.Assert._
@@ -70,7 +70,7 @@ class UnionITCase extends StreamingMultipleProgramsTestBase {
     assertEquals(expected.sorted, StreamITCase.testResults.sorted)
   }
 
-  @Test(expected = classOf[IllegalArgumentException])
+  @Test(expected = classOf[ValidationException])
   def testUnionFieldsNameNotOverlap1(): Unit = {
     val env = StreamExecutionEnvironment.getExecutionEnvironment
     val tEnv = TableEnvironment.getTableEnvironment(env)
@@ -88,7 +88,7 @@ class UnionITCase extends StreamingMultipleProgramsTestBase {
     assertEquals(true, StreamITCase.testResults.isEmpty)
   }
 
-  @Test(expected = classOf[IllegalArgumentException])
+  @Test(expected = classOf[ValidationException])
   def testUnionFieldsNameNotOverlap2(): Unit = {
     val env = StreamExecutionEnvironment.getExecutionEnvironment
     val tEnv = TableEnvironment.getTableEnvironment(env)
@@ -108,7 +108,7 @@ class UnionITCase extends StreamingMultipleProgramsTestBase {
     assertEquals(true, StreamITCase.testResults.isEmpty)
   }
 
-  @Test(expected = classOf[TableException])
+  @Test(expected = classOf[ValidationException])
   def testUnionTablesFromDifferentEnvs(): Unit = {
     val env = StreamExecutionEnvironment.getExecutionEnvironment
     val tEnv1 = TableEnvironment.getTableEnvironment(env)

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/stream/table/UnsupportedOpsTest.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/stream/table/UnsupportedOpsTest.scala b/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/stream/table/UnsupportedOpsTest.scala
index e6309a2..a382447 100644
--- a/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/stream/table/UnsupportedOpsTest.scala
+++ b/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/stream/table/UnsupportedOpsTest.scala
@@ -50,6 +50,13 @@ class UnsupportedOpsTest extends StreamingMultipleProgramsTestBase {
   }
 
   @Test(expected = classOf[TableException])
+  def testSort(): Unit = {
+    val env = StreamExecutionEnvironment.getExecutionEnvironment
+    val tEnv = TableEnvironment.getTableEnvironment(env)
+    StreamTestData.getSmall3TupleDataStream(env).toTable(tEnv).orderBy('_1.desc)
+  }
+
+  @Test(expected = classOf[TableException])
   def testJoin(): Unit = {
     val env = StreamExecutionEnvironment.getExecutionEnvironment
     val tEnv = TableEnvironment.getTableEnvironment(env)


[4/5] flink git commit: [FLINK-3900] [tableAPI] Set nullCheck=true as default in TableConfig.

Posted by fh...@apache.org.
[FLINK-3900] [tableAPI] Set nullCheck=true as default in TableConfig.

This closes #1994


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

Branch: refs/heads/master
Commit: f2e605759f77061e76fc7da6a55faeb44c67fc6f
Parents: 4fbd8eb
Author: Joshi <re...@gmail.com>
Authored: Mon May 16 14:25:12 2016 -0700
Committer: Fabian Hueske <fh...@apache.org>
Committed: Wed May 18 00:12:22 2016 +0200

----------------------------------------------------------------------
 docs/apis/table.md                                                 | 2 +-
 .../src/main/scala/org/apache/flink/api/table/TableConfig.scala    | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/flink/blob/f2e60575/docs/apis/table.md
----------------------------------------------------------------------
diff --git a/docs/apis/table.md b/docs/apis/table.md
index eae4ebd..276341d 100644
--- a/docs/apis/table.md
+++ b/docs/apis/table.md
@@ -737,5 +737,5 @@ Runtime Configuration
 The Table API provides a configuration (the so-called `TableConfig`) to modify runtime behavior. It can be accessed either through `TableEnvironment` or passed to the `toDataSet`/`toDataStream` method when using Scala implicit conversion.
 
 ### Null Handling
-By default, the Table API does not support `null` values at runtime for efficiency purposes. Null handling can be enabled by setting the `nullCheck` property in the `TableConfig` to `true`.
+By default, the Table API supports `null` values. Null handling can be disabled by setting the `nullCheck` property in the `TableConfig` to `false`.
 

http://git-wip-us.apache.org/repos/asf/flink/blob/f2e60575/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/TableConfig.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/TableConfig.scala b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/TableConfig.scala
index e93d37d..c92451d 100644
--- a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/TableConfig.scala
+++ b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/TableConfig.scala
@@ -32,7 +32,7 @@ class TableConfig extends Serializable {
   /**
    * Defines if all fields need to be checked for NULL first.
    */
-  private var nullCheck: Boolean = false
+  private var nullCheck: Boolean = true
 
   /**
     * Defines if efficient types (such as Tuple types or Atomic types)


[2/5] flink git commit: [FLINK-3754] [tableAPI] Add validation phase to Table API before construction of RelNodes.

Posted by fh...@apache.org.
http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/plan/RexNodeTranslator.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/plan/RexNodeTranslator.scala b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/plan/RexNodeTranslator.scala
index f946ed9..095cf04 100644
--- a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/plan/RexNodeTranslator.scala
+++ b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/plan/RexNodeTranslator.scala
@@ -18,57 +18,49 @@
 
 package org.apache.flink.api.table.plan
 
-import org.apache.calcite.tools.RelBuilder.AggCall
 import org.apache.flink.api.table.TableEnvironment
-
 import org.apache.flink.api.table.expressions._
 
 object RexNodeTranslator {
 
   /**
-    * Extracts all aggregation expressions (zero, one, or more) from an expression, translates
-    * these aggregation expressions into Calcite AggCalls, and replaces the original aggregation
-    * expressions by field accesses expressions.
+    * Extracts all aggregation expressions (zero, one, or more) from an expression,
+    * and replaces the original aggregation expressions by field accesses expressions.
     */
-  def extractAggCalls(
+  def extractAggregations(
     exp: Expression,
-    tableEnv: TableEnvironment): Pair[Expression, List[AggCall]] = {
-
-    val relBuilder = tableEnv.getRelBuilder
+    tableEnv: TableEnvironment): Pair[Expression, List[NamedExpression]] = {
 
     exp match {
       case agg: Aggregation =>
         val name = tableEnv.createUniqueAttributeName()
-        val aggCall = agg.toAggCall(name)(relBuilder)
+        val aggCall = Alias(agg, name)
         val fieldExp = new UnresolvedFieldReference(name)
         (fieldExp, List(aggCall))
-      case n@Naming(agg: Aggregation, name) =>
-        val aggCall = agg.toAggCall(name)(relBuilder)
+      case n @ Alias(agg: Aggregation, name) =>
         val fieldExp = new UnresolvedFieldReference(name)
-        (fieldExp, List(aggCall))
+        (fieldExp, List(n))
       case l: LeafExpression =>
         (l, Nil)
       case u: UnaryExpression =>
-        val c = extractAggCalls(u.child, tableEnv)
-        (u.makeCopy(List(c._1)), c._2)
+        val c = extractAggregations(u.child, tableEnv)
+        (u.makeCopy(Array(c._1)), c._2)
       case b: BinaryExpression =>
-        val l = extractAggCalls(b.left, tableEnv)
-        val r = extractAggCalls(b.right, tableEnv)
-        (b.makeCopy(List(l._1, r._1)), l._2 ::: r._2)
-      case e: Eval =>
-        val c = extractAggCalls(e.condition, tableEnv)
-        val t = extractAggCalls(e.ifTrue, tableEnv)
-        val f = extractAggCalls(e.ifFalse, tableEnv)
-        (e.makeCopy(List(c._1, t._1, f._1)), c._2 ::: t._2 ::: f._2)
+        val l = extractAggregations(b.left, tableEnv)
+        val r = extractAggregations(b.right, tableEnv)
+        (b.makeCopy(Array(l._1, r._1)), l._2 ::: r._2)
 
       // Scalar functions
-      case c@Call(name, args@_*) =>
-        val newArgs = args.map(extractAggCalls(_, tableEnv)).toList
-        (c.makeCopy(name :: newArgs.map(_._1)), newArgs.flatMap(_._2))
+      case c @ Call(name, args) =>
+        val newArgs = args.map(extractAggregations(_, tableEnv))
+        (c.makeCopy((name :: newArgs.map(_._1) :: Nil).toArray), newArgs.flatMap(_._2).toList)
 
-      case e@AnyRef =>
-        throw new IllegalArgumentException(
-          s"Expression $e of type ${e.getClass} not supported yet")
+      case e: Expression =>
+        val newArgs = e.productIterator.map {
+          case arg: Expression =>
+            extractAggregations(arg, tableEnv)
+        }
+        (e.makeCopy(newArgs.map(_._1).toArray), newArgs.flatMap(_._2).toList)
     }
   }
 }

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/plan/logical/LogicalNode.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/plan/logical/LogicalNode.scala b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/plan/logical/LogicalNode.scala
new file mode 100644
index 0000000..dae02bd
--- /dev/null
+++ b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/plan/logical/LogicalNode.scala
@@ -0,0 +1,162 @@
+/*
+ * 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.flink.api.table.plan.logical
+
+import org.apache.calcite.rel.RelNode
+import org.apache.calcite.tools.RelBuilder
+
+import org.apache.flink.api.table.{TableEnvironment, ValidationException}
+import org.apache.flink.api.table.expressions._
+import org.apache.flink.api.table.trees.TreeNode
+import org.apache.flink.api.table.typeutils.TypeCoercion
+import org.apache.flink.api.table.validate._
+
+/**
+  * LogicalNode is created and validated as we construct query plan using Table API.
+  *
+  * The main validation procedure is separated into two phases:
+  *
+  * Expressions' resolution and transformation ([[resolveExpressions]]):
+  *
+  * - translate [[UnresolvedFieldReference]] into [[ResolvedFieldReference]]
+  *     using child operator's output
+  * - translate [[Call]](UnresolvedFunction) into solid Expression
+  * - generate alias names for query output
+  * - ....
+  *
+  * LogicalNode validation ([[validate]]):
+  *
+  * - check no [[UnresolvedFieldReference]] exists any more
+  * - check if all expressions have children of needed type
+  * - check each logical operator have desired input
+  *
+  * Once we pass the validation phase, we can safely convert LogicalNode into Calcite's RelNode.
+  */
+abstract class LogicalNode extends TreeNode[LogicalNode] {
+  def output: Seq[Attribute]
+
+  def resolveExpressions(tableEnv: TableEnvironment): LogicalNode = {
+    // resolve references and function calls
+    val exprResolved = expressionPostOrderTransform {
+      case u @ UnresolvedFieldReference(name) =>
+        resolveReference(name).getOrElse(u)
+      case c @ Call(name, children) if c.childrenValid =>
+        tableEnv.getFunctionCatalog.lookupFunction(name, children)
+    }
+
+    exprResolved.expressionPostOrderTransform {
+      case ips: InputTypeSpec if ips.childrenValid =>
+        var changed: Boolean = false
+        val newChildren = ips.expectedTypes.zip(ips.children).map { case (tpe, child) =>
+          val childType = child.resultType
+          if (childType != tpe && TypeCoercion.canSafelyCast(childType, tpe)) {
+            changed = true
+            Cast(child, tpe)
+          } else {
+            child
+          }
+        }.toArray[AnyRef]
+        if (changed) ips.makeCopy(newChildren) else ips
+    }
+  }
+
+  final def toRelNode(relBuilder: RelBuilder): RelNode = construct(relBuilder).build()
+
+  protected[logical] def construct(relBuilder: RelBuilder): RelBuilder
+
+  def validate(tableEnv: TableEnvironment): LogicalNode = {
+    val resolvedNode = resolveExpressions(tableEnv)
+    resolvedNode.expressionPostOrderTransform {
+      case a: Attribute if !a.valid =>
+        val from = children.flatMap(_.output).map(_.name).mkString(", ")
+        failValidation(s"cannot resolve [${a.name}] given input [$from]")
+
+      case e: Expression if e.validateInput().isFailure =>
+        failValidation(s"Expression $e failed on input check: " +
+          s"${e.validateInput().asInstanceOf[ValidationFailure].message}")
+    }
+  }
+
+  /**
+    * Resolves the given strings to a [[NamedExpression]] using the input from all child
+    * nodes of this LogicalPlan.
+    */
+  def resolveReference(name: String): Option[NamedExpression] = {
+    val childrenOutput = children.flatMap(_.output)
+    val candidates = childrenOutput.filter(_.name.equalsIgnoreCase(name))
+    if (candidates.length > 1) {
+      failValidation(s"Reference $name is ambiguous")
+    } else if (candidates.length == 0) {
+      None
+    } else {
+      Some(candidates.head.withName(name))
+    }
+  }
+
+  /**
+    * Runs [[postOrderTransform]] with `rule` on all expressions present in this logical node.
+    *
+    * @param rule the rule to be applied to every expression in this logical node.
+    */
+  def expressionPostOrderTransform(rule: PartialFunction[Expression, Expression]): LogicalNode = {
+    var changed = false
+
+    def expressionPostOrderTransform(e: Expression): Expression = {
+      val newExpr = e.postOrderTransform(rule)
+      if (newExpr.fastEquals(e)) {
+        e
+      } else {
+        changed = true
+        newExpr
+      }
+    }
+
+    val newArgs = productIterator.map {
+      case e: Expression => expressionPostOrderTransform(e)
+      case Some(e: Expression) => Some(expressionPostOrderTransform(e))
+      case seq: Traversable[_] => seq.map {
+        case e: Expression => expressionPostOrderTransform(e)
+        case other => other
+      }
+      case other: AnyRef => other
+    }.toArray
+
+    if (changed) makeCopy(newArgs) else this
+  }
+
+  protected def failValidation(msg: String): Nothing = {
+    throw new ValidationException(msg)
+  }
+}
+
+abstract class LeafNode extends LogicalNode {
+  override def children: Seq[LogicalNode] = Nil
+}
+
+abstract class UnaryNode extends LogicalNode {
+  def child: LogicalNode
+
+  override def children: Seq[LogicalNode] = child :: Nil
+}
+
+abstract class BinaryNode extends LogicalNode {
+  def left: LogicalNode
+  def right: LogicalNode
+
+  override def children: Seq[LogicalNode] = left :: right :: Nil
+}

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/plan/logical/operators.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/plan/logical/operators.scala b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/plan/logical/operators.scala
new file mode 100644
index 0000000..d347651
--- /dev/null
+++ b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/plan/logical/operators.scala
@@ -0,0 +1,339 @@
+/*
+ * 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.flink.api.table.plan.logical
+
+import scala.collection.JavaConverters._
+import scala.collection.mutable
+
+import org.apache.calcite.rel.RelNode
+import org.apache.calcite.rel.`type`.RelDataType
+import org.apache.calcite.rel.core.JoinRelType
+import org.apache.calcite.rel.logical.LogicalProject
+import org.apache.calcite.tools.RelBuilder
+
+import org.apache.flink.api.common.typeinfo.BasicTypeInfo._
+import org.apache.flink.api.java.operators.join.JoinType
+import org.apache.flink.api.table._
+import org.apache.flink.api.table.expressions._
+import org.apache.flink.api.table.typeutils.TypeConverter
+
+case class Project(projectList: Seq[NamedExpression], child: LogicalNode) extends UnaryNode {
+  override def output: Seq[Attribute] = projectList.map(_.toAttribute)
+
+  override def resolveExpressions(tableEnv: TableEnvironment): LogicalNode = {
+    val afterResolve = super.resolveExpressions(tableEnv).asInstanceOf[Project]
+    val newProjectList =
+      afterResolve.projectList.zipWithIndex.map { case (e, i) =>
+        e match {
+          case u @ UnresolvedAlias(child) => child match {
+            case ne: NamedExpression => ne
+            case e if !e.valid => u
+            case c @ Cast(ne: NamedExpression, tp) => Alias(c, s"${ne.name}-$tp")
+            case other => Alias(other, s"_c$i")
+          }
+          case _ => throw new IllegalArgumentException
+        }
+    }
+    Project(newProjectList, child)
+  }
+
+  override def validate(tableEnv: TableEnvironment): LogicalNode = {
+    val resolvedProject = super.validate(tableEnv).asInstanceOf[Project]
+
+    def checkUniqueNames(exprs: Seq[Expression]): Unit = {
+      val names: mutable.Set[String] = mutable.Set()
+      exprs.foreach {
+        case n: Alias =>
+          // explicit name
+          if (names.contains(n.name)) {
+            throw new ValidationException(s"Duplicate field name $n.name.")
+          } else {
+            names.add(n.name)
+          }
+        case r: ResolvedFieldReference =>
+          // simple field forwarding
+          if (names.contains(r.name)) {
+            throw new ValidationException(s"Duplicate field name $r.name.")
+          } else {
+            names.add(r.name)
+          }
+        case _ => // Do nothing
+      }
+    }
+    checkUniqueNames(resolvedProject.projectList)
+    resolvedProject
+  }
+
+  override protected[logical] def construct(relBuilder: RelBuilder): RelBuilder = {
+    val allAlias = projectList.forall(_.isInstanceOf[Alias])
+    child.construct(relBuilder)
+    if (allAlias) {
+      // Calcite's RelBuilder does not translate identity projects even if they rename fields.
+      //   Add a projection ourselves (will be automatically removed by translation rules).
+      relBuilder.push(
+        LogicalProject.create(relBuilder.peek(),
+          projectList.map(_.toRexNode(relBuilder)).asJava,
+          projectList.map(_.name).asJava))
+    } else {
+      relBuilder.project(projectList.map(_.toRexNode(relBuilder)): _*)
+    }
+  }
+}
+
+case class AliasNode(aliasList: Seq[Expression], child: LogicalNode) extends UnaryNode {
+  override def output: Seq[Attribute] =
+    throw new UnresolvedException("Invalid call to output on AliasNode")
+
+  override protected[logical] def construct(relBuilder: RelBuilder): RelBuilder =
+    throw new UnresolvedException("Invalid call to toRelNode on AliasNode")
+
+  override def resolveExpressions(tableEnv: TableEnvironment): LogicalNode = {
+    if (aliasList.length > child.output.length) {
+      failValidation("Aliasing more fields than we actually have")
+    } else if (!aliasList.forall(_.isInstanceOf[UnresolvedFieldReference])) {
+      failValidation("Alias only accept name expressions as arguments")
+    } else {
+      val names = aliasList.map(_.asInstanceOf[UnresolvedFieldReference].name)
+      val input = child.output
+      Project(
+        names.zip(input).map { case (name, attr) =>
+          Alias(attr, name)} ++ input.drop(names.length), child)
+    }
+  }
+}
+
+case class Distinct(child: LogicalNode) extends UnaryNode {
+  override def output: Seq[Attribute] = child.output
+
+  override protected[logical] def construct(relBuilder: RelBuilder): RelBuilder = {
+    child.construct(relBuilder)
+    relBuilder.distinct()
+  }
+
+  override def validate(tableEnv: TableEnvironment): LogicalNode = {
+    if (tableEnv.isInstanceOf[StreamTableEnvironment]) {
+      throw new TableException(s"Distinct on stream tables is currently not supported.")
+    }
+    this
+  }
+}
+
+case class Sort(order: Seq[Ordering], child: LogicalNode) extends UnaryNode {
+  override def output: Seq[Attribute] = child.output
+
+  override protected[logical] def construct(relBuilder: RelBuilder): RelBuilder = {
+    child.construct(relBuilder)
+    relBuilder.sort(order.map(_.toRexNode(relBuilder)).asJava)
+  }
+
+  override def validate(tableEnv: TableEnvironment): LogicalNode = {
+    if (tableEnv.isInstanceOf[StreamTableEnvironment]) {
+      throw new TableException(s"Distinct on stream tables is currently not supported.")
+    }
+    super.validate(tableEnv)
+  }
+}
+
+case class Filter(condition: Expression, child: LogicalNode) extends UnaryNode {
+  override def output: Seq[Attribute] = child.output
+
+  override protected[logical] def construct(relBuilder: RelBuilder): RelBuilder = {
+    child.construct(relBuilder)
+    relBuilder.filter(condition.toRexNode(relBuilder))
+  }
+
+  override def validate(tableEnv: TableEnvironment): LogicalNode = {
+    val resolvedFilter = super.validate(tableEnv).asInstanceOf[Filter]
+    if (resolvedFilter.condition.resultType != BOOLEAN_TYPE_INFO) {
+      failValidation(s"filter expression ${resolvedFilter.condition} of" +
+        s" ${resolvedFilter.condition.resultType} is not a boolean")
+    }
+    resolvedFilter
+  }
+}
+
+case class Aggregate(
+    groupingExpressions: Seq[Expression],
+    aggregateExpressions: Seq[NamedExpression],
+    child: LogicalNode) extends UnaryNode {
+
+  override def output: Seq[Attribute] = {
+    (groupingExpressions ++ aggregateExpressions) map { agg =>
+      agg match {
+        case ne: NamedExpression => ne.toAttribute
+        case e => Alias(e, e.toString).toAttribute
+      }
+    }
+  }
+
+  override protected[logical] def construct(relBuilder: RelBuilder): RelBuilder = {
+    child.construct(relBuilder)
+    relBuilder.aggregate(
+      relBuilder.groupKey(groupingExpressions.map(_.toRexNode(relBuilder)).asJava),
+      aggregateExpressions.map { e =>
+        e match {
+          case Alias(agg: Aggregation, name) => agg.toAggCall(name)(relBuilder)
+          case _ => throw new RuntimeException("This should never happen.")
+        }
+      }.asJava)
+  }
+
+  override def validate(tableEnv: TableEnvironment): LogicalNode = {
+    if (tableEnv.isInstanceOf[StreamTableEnvironment]) {
+      throw new TableException(s"Aggregate on stream tables is currently not supported.")
+    }
+
+    val resolvedAggregate = super.validate(tableEnv).asInstanceOf[Aggregate]
+    val groupingExprs = resolvedAggregate.groupingExpressions
+    val aggregateExprs = resolvedAggregate.aggregateExpressions
+    aggregateExprs.foreach(validateAggregateExpression)
+    groupingExprs.foreach(validateGroupingExpression)
+
+    def validateAggregateExpression(expr: Expression): Unit = expr match {
+      // check no nested aggregation exists.
+      case aggExpr: Aggregation =>
+        aggExpr.children.foreach { child =>
+          child.preOrderVisit {
+            case agg: Aggregation =>
+              failValidation(
+                "It's not allowed to use an aggregate function as " +
+                  "input of another aggregate function")
+            case _ => // OK
+          }
+        }
+      case a: Attribute if !groupingExprs.exists(_.checkEquals(a)) =>
+        failValidation(
+          s"expression '$a' is invalid because it is neither" +
+            " present in group by nor an aggregate function")
+      case e if groupingExprs.exists(_.checkEquals(e)) => // OK
+      case e => e.children.foreach(validateAggregateExpression)
+    }
+
+    def validateGroupingExpression(expr: Expression): Unit = {
+      if (!expr.resultType.isKeyType) {
+        failValidation(
+          s"expression $expr cannot be used as a grouping expression " +
+            "because it's not a valid key type")
+      }
+    }
+    resolvedAggregate
+  }
+}
+
+case class Union(left: LogicalNode, right: LogicalNode) extends BinaryNode {
+  override def output: Seq[Attribute] = left.output
+
+  override protected[logical] def construct(relBuilder: RelBuilder): RelBuilder = {
+    left.construct(relBuilder)
+    right.construct(relBuilder)
+    relBuilder.union(true)
+  }
+
+  override def validate(tableEnv: TableEnvironment): LogicalNode = {
+    val resolvedUnion = super.validate(tableEnv).asInstanceOf[Union]
+    if (left.output.length != right.output.length) {
+      failValidation(s"Union two table of different column sizes:" +
+        s" ${left.output.size} and ${right.output.size}")
+    }
+    val sameSchema = left.output.zip(right.output).forall { case (l, r) =>
+      l.resultType == r.resultType && l.name == r.name }
+    if (!sameSchema) {
+      failValidation(s"Union two table of different schema:" +
+        s" [${left.output.map(a => (a.name, a.resultType)).mkString(", ")}] and" +
+        s" [${right.output.map(a => (a.name, a.resultType)).mkString(", ")}]")
+    }
+    resolvedUnion
+  }
+}
+
+case class Join(
+    left: LogicalNode,
+    right: LogicalNode,
+    joinType: JoinType,
+    condition: Option[Expression]) extends BinaryNode {
+
+  override def output: Seq[Attribute] = {
+    joinType match {
+      case JoinType.INNER => left.output ++ right.output
+      case j => throw new ValidationException(s"Unsupported JoinType: $j")
+    }
+  }
+
+  override protected[logical] def construct(relBuilder: RelBuilder): RelBuilder = {
+    joinType match {
+      case JoinType.INNER =>
+        left.construct(relBuilder)
+        right.construct(relBuilder)
+        relBuilder.join(JoinRelType.INNER,
+          condition.map(_.toRexNode(relBuilder)).getOrElse(relBuilder.literal(true)))
+      case _ =>
+        throw new ValidationException(s"Unsupported JoinType: $joinType")
+    }
+  }
+
+  private def ambiguousName: Set[String] =
+    left.output.map(_.name).toSet.intersect(right.output.map(_.name).toSet)
+
+  override def validate(tableEnv: TableEnvironment): LogicalNode = {
+    if (tableEnv.isInstanceOf[StreamTableEnvironment]) {
+      throw new TableException(s"Join on stream tables is currently not supported.")
+    }
+
+    val resolvedJoin = super.validate(tableEnv).asInstanceOf[Join]
+    if (!resolvedJoin.condition.forall(_.resultType == BOOLEAN_TYPE_INFO)) {
+      failValidation(s"filter expression ${resolvedJoin.condition} is not a boolean")
+    } else if (!ambiguousName.isEmpty) {
+      failValidation(s"join relations with ambiguous names: ${ambiguousName.mkString(", ")}")
+    }
+    resolvedJoin
+  }
+}
+
+case class CatalogNode(
+    tableName: String,
+    rowType: RelDataType) extends LeafNode {
+
+  val output: Seq[Attribute] = rowType.getFieldList.asScala.map { field =>
+    ResolvedFieldReference(
+      field.getName, TypeConverter.sqlTypeToTypeInfo(field.getType.getSqlTypeName))
+  }
+
+  override protected[logical] def construct(relBuilder: RelBuilder): RelBuilder = {
+    relBuilder.scan(tableName)
+  }
+
+  override def validate(tableEnv: TableEnvironment): LogicalNode = this
+}
+
+/**
+  * Wrapper for valid logical plans generated from SQL String.
+  */
+case class LogicalRelNode(
+    relNode: RelNode) extends LeafNode {
+
+  val output: Seq[Attribute] = relNode.getRowType.getFieldList.asScala.map { field =>
+    ResolvedFieldReference(
+      field.getName, TypeConverter.sqlTypeToTypeInfo(field.getType.getSqlTypeName))
+  }
+
+  override protected[logical] def construct(relBuilder: RelBuilder): RelBuilder = {
+    relBuilder.push(relNode)
+  }
+
+  override def validate(tableEnv: TableEnvironment): LogicalNode = this
+}

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/table.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/table.scala b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/table.scala
index 5356a9d..4f111c9 100644
--- a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/table.scala
+++ b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/table.scala
@@ -17,28 +17,18 @@
  */
 package org.apache.flink.api.table
 
+import scala.collection.JavaConverters._
+
 import org.apache.calcite.rel.RelNode
-import org.apache.calcite.rel.`type`.RelDataTypeField
-import org.apache.calcite.rel.core.JoinRelType
-import org.apache.calcite.rel.logical.LogicalProject
-import org.apache.calcite.rex.{RexCall, RexInputRef, RexLiteral, RexNode}
-import org.apache.calcite.sql.SqlKind
-import org.apache.calcite.tools.RelBuilder.{AggCall, GroupKey}
-import org.apache.calcite.util.NlsString
+
 import org.apache.flink.api.common.typeinfo.TypeInformation
-import org.apache.flink.api.table.plan.PlanGenException
-import org.apache.flink.api.table.plan.RexNodeTranslator.extractAggCalls
+import org.apache.flink.api.java.operators.join.JoinType
+import org.apache.flink.api.table.plan.RexNodeTranslator.extractAggregations
 import org.apache.flink.api.table.expressions._
+import org.apache.flink.api.table.plan.logical._
 import org.apache.flink.api.table.sinks.TableSink
 import org.apache.flink.api.table.typeutils.TypeConverter
 
-import scala.collection.mutable
-import scala.collection.JavaConverters._
-
-case class BaseTable(
-  private[flink] val relNode: RelNode,
-  private[flink] val tableEnv: TableEnvironment)
-
 /**
   * A Table is the core component of the Table API.
   * Similar to how the batch and streaming APIs have DataSet and DataStream,
@@ -66,18 +56,16 @@ case class BaseTable(
   * in a Scala DSL or as an expression String. Please refer to the documentation for the expression
   * syntax.
   *
-  * @param relNode The root node of the relational Calcite [[RelNode]] tree.
   * @param tableEnv The [[TableEnvironment]] to which the table is bound.
+  * @param logicalPlan
   */
 class Table(
-  private[flink] override val relNode: RelNode,
-  private[flink] override val tableEnv: TableEnvironment)
-  extends BaseTable(relNode, tableEnv)
-{
+    private[flink] val tableEnv: TableEnvironment,
+    private[flink] val logicalPlan: LogicalNode) {
 
   def relBuilder = tableEnv.getRelBuilder
 
-  def getRelNode: RelNode = relNode
+  def getRelNode: RelNode = logicalPlan.toRelNode(relBuilder)
 
   /**
     * Performs a selection operation. Similar to an SQL SELECT statement. The field expressions
@@ -90,44 +78,17 @@ class Table(
     * }}}
     */
   def select(fields: Expression*): Table = {
-
-    checkUniqueNames(fields)
-
-    relBuilder.push(relNode)
-
-    // separate aggregations and selection expressions
-    val extractedAggCalls: List[(Expression, List[AggCall])] = fields
-      .map(extractAggCalls(_, tableEnv)).toList
-
-    // get aggregation calls
-    val aggCalls: List[AggCall] = extractedAggCalls.flatMap(_._2)
-
-    // apply aggregations
-    if (aggCalls.nonEmpty) {
-      // aggregation on stream table is not currently supported
-      tableEnv match {
-        case _: StreamTableEnvironment =>
-          throw new TableException("Aggregation on stream tables is currently not supported.")
-        case _ =>
-          val emptyKey: GroupKey = relBuilder.groupKey()
-          relBuilder.aggregate(emptyKey, aggCalls.toIterable.asJava)
-      }
-    }
-
-    // get selection expressions
-    val exprs: List[RexNode] = extractedAggCalls.map(_._1.toRexNode(relBuilder))
-
-    relBuilder.project(exprs.toIterable.asJava)
-    val projected = relBuilder.build()
-
-    if(relNode == projected) {
-      // Calcite's RelBuilder does not translate identity projects even if they rename fields.
-      //   Add a projection ourselves (will be automatically removed by translation rules).
-      new Table(createRenamingProject(exprs), tableEnv)
+    val projectionOnAggregates = fields.map(extractAggregations(_, tableEnv))
+    val aggregations = projectionOnAggregates.flatMap(_._2)
+    if (aggregations.nonEmpty) {
+      new Table(tableEnv,
+        Project(projectionOnAggregates.map(e => UnresolvedAlias(e._1)),
+          Aggregate(Nil, aggregations, logicalPlan).validate(tableEnv)).validate(tableEnv))
     } else {
-      new Table(projected, tableEnv)
+      new Table(tableEnv,
+        Project(
+          projectionOnAggregates.map(e => UnresolvedAlias(e._1)), logicalPlan).validate(tableEnv))
     }
-
   }
 
   /**
@@ -156,30 +117,7 @@ class Table(
     * }}}
     */
   def as(fields: Expression*): Table = {
-
-    val curNames = relNode.getRowType.getFieldNames.asScala
-
-    // validate that AS has only field references
-    if (! fields.forall( _.isInstanceOf[UnresolvedFieldReference] )) {
-      throw new IllegalArgumentException("All expressions must be field references.")
-    }
-    // validate that we have not more field references than fields
-    if ( fields.length > curNames.size) {
-      throw new IllegalArgumentException("More field references than fields.")
-    }
-
-    val curFields = curNames.map(new UnresolvedFieldReference(_))
-
-    val renamings = fields.zip(curFields).map {
-      case (newName, oldName) => new Naming(oldName, newName.name)
-    }
-    val remaining = curFields.drop(fields.size)
-
-    relBuilder.push(relNode)
-
-    val exprs = (renamings ++ remaining).map(_.toRexNode(relBuilder))
-
-    new Table(createRenamingProject(exprs), tableEnv)
+    new Table(tableEnv, AliasNode(fields, logicalPlan).validate(tableEnv))
   }
 
   /**
@@ -208,11 +146,7 @@ class Table(
     * }}}
     */
   def filter(predicate: Expression): Table = {
-
-    relBuilder.push(relNode)
-    relBuilder.filter(predicate.toRexNode(relBuilder))
-
-    new Table(relBuilder.build(), tableEnv)
+    new Table(tableEnv, Filter(predicate, logicalPlan).validate(tableEnv))
   }
 
   /**
@@ -269,19 +203,10 @@ class Table(
     * }}}
     */
   def groupBy(fields: Expression*): GroupedTable = {
-
-    // group by on stream tables is currently not supported
-    tableEnv match {
-      case _: StreamTableEnvironment =>
-        throw new TableException("Group by on stream tables is currently not supported.")
-      case _ => {
-        relBuilder.push(relNode)
-        val groupExpr = fields.map(_.toRexNode(relBuilder)).toIterable.asJava
-        val groupKey = relBuilder.groupKey(groupExpr)
-
-        new GroupedTable(relBuilder.build(), tableEnv, groupKey)
-      }
+    if (tableEnv.isInstanceOf[StreamTableEnvironment]) {
+      throw new TableException(s"Group by on stream tables is currently not supported.")
     }
+    new GroupedTable(this, fields)
   }
 
   /**
@@ -309,15 +234,7 @@ class Table(
     * }}}
     */
   def distinct(): Table = {
-    // distinct on stream table is not currently supported
-    tableEnv match {
-      case _: StreamTableEnvironment =>
-        throw new TableException("Distinct on stream tables is currently not supported.")
-      case _ =>
-        relBuilder.push(relNode)
-        relBuilder.distinct()
-        new Table(relBuilder.build(), tableEnv)
-    }
+    new Table(tableEnv, Distinct(logicalPlan).validate(tableEnv))
   }
 
   /**
@@ -334,32 +251,12 @@ class Table(
     * }}}
     */
   def join(right: Table): Table = {
-
-    // join on stream tables is currently not supported
-    tableEnv match {
-      case _: StreamTableEnvironment =>
-        throw new TableException("Join on stream tables is currently not supported.")
-      case _ => {
-        // check that right table belongs to the same TableEnvironment
-        if (right.tableEnv != this.tableEnv) {
-          throw new TableException("Only tables from the same TableEnvironment can be joined.")
-        }
-
-        // check that join inputs do not have overlapping field names
-        val leftFields = relNode.getRowType.getFieldNames.asScala.toSet
-        val rightFields = right.relNode.getRowType.getFieldNames.asScala.toSet
-        if (leftFields.intersect(rightFields).nonEmpty) {
-          throw new IllegalArgumentException("Overlapping fields names on join input.")
-        }
-
-        relBuilder.push(relNode)
-        relBuilder.push(right.relNode)
-
-        relBuilder.join(JoinRelType.INNER, relBuilder.literal(true))
-        val join = relBuilder.build()
-        new Table(join, tableEnv)
-      }
+    // check that right table belongs to the same TableEnvironment
+    if (right.tableEnv != this.tableEnv) {
+      throw new ValidationException("Only tables from the same TableEnvironment can be joined.")
     }
+    new Table(tableEnv,
+      Join(this.logicalPlan, right.logicalPlan, JoinType.INNER, None).validate(tableEnv))
   }
 
   /**
@@ -375,32 +272,11 @@ class Table(
     * }}}
     */
   def unionAll(right: Table): Table = {
-
     // check that right table belongs to the same TableEnvironment
     if (right.tableEnv != this.tableEnv) {
-      throw new TableException("Only tables from the same TableEnvironment can be unioned.")
-    }
-
-    val leftRowType: List[RelDataTypeField] = relNode.getRowType.getFieldList.asScala.toList
-    val rightRowType: List[RelDataTypeField] = right.relNode.getRowType.getFieldList.asScala.toList
-
-    if (leftRowType.length != rightRowType.length) {
-      throw new IllegalArgumentException("Unioned tables have varying row schema.")
+      throw new ValidationException("Only tables from the same TableEnvironment can be unioned.")
     }
-    else {
-      val zipped: List[(RelDataTypeField, RelDataTypeField)] = leftRowType.zip(rightRowType)
-      zipped.foreach { case (x, y) =>
-        if (!x.getName.equals(y.getName) || x.getType != y.getType) {
-          throw new IllegalArgumentException("Unioned tables have varying row schema.")
-        }
-      }
-    }
-
-    relBuilder.push(relNode)
-    relBuilder.push(right.relNode)
-
-    relBuilder.union(true)
-    new Table(relBuilder.build(), tableEnv)
+    new Table(tableEnv, Union(logicalPlan, right.logicalPlan).validate(tableEnv))
   }
 
   /**
@@ -414,22 +290,13 @@ class Table(
     * }}}
     */
   def orderBy(fields: Expression*): Table = {
-    relBuilder.push(relNode)
-
-    if (! fields.forall {
-      case x : UnresolvedFieldReference => true
-      case x : Ordering => x.child.isInstanceOf[UnresolvedFieldReference]
-      case _ => false
-    }) {
-      throw new IllegalArgumentException("All expressions must be field references " +
-        "or asc/desc expressions.")
+    val order: Seq[Ordering] = fields.map { case e =>
+      e match {
+        case o: Ordering => o
+        case _ => Asc(e)
+      }
     }
-
-    val exprs = fields.map(_.toRexNode(relBuilder))
-
-    relBuilder.sort(exprs.asJava)
-    new Table(relBuilder.build(), tableEnv)
-
+    new Table(tableEnv, Sort(order, logicalPlan).validate(tableEnv))
   }
 
   /**
@@ -460,7 +327,7 @@ class Table(
   def toSink[T](sink: TableSink[T]): Unit = {
 
     // get schema information of table
-    val rowType = relNode.getRowType
+    val rowType = getRelNode.getRowType
     val fieldNames: Array[String] = rowType.getFieldNames.asScala.toArray
     val fieldTypes: Array[TypeInformation[_]] = rowType.getFieldList.asScala
       .map(f => TypeConverter.sqlTypeToTypeInfo(f.getType.getSqlTypeName)).toArray
@@ -471,62 +338,14 @@ class Table(
     // emit the table to the configured table sink
     tableEnv.emitToSink(this, configuredSink)
   }
-
-  private def createRenamingProject(exprs: Seq[RexNode]): LogicalProject = {
-
-    val names = exprs.map{ e =>
-      e.getKind match {
-        case SqlKind.AS =>
-          e.asInstanceOf[RexCall].getOperands.get(1)
-            .asInstanceOf[RexLiteral].getValue
-            .asInstanceOf[NlsString].getValue
-        case SqlKind.INPUT_REF =>
-          relNode.getRowType.getFieldNames.get(e.asInstanceOf[RexInputRef].getIndex)
-        case _ =>
-          throw new PlanGenException("Unexpected expression type encountered.")
-      }
-
-    }
-    LogicalProject.create(relNode, exprs.toList.asJava, names.toList.asJava)
-  }
-
-  private def checkUniqueNames(exprs: Seq[Expression]): Unit = {
-    val names: mutable.Set[String] = mutable.Set()
-
-    exprs.foreach {
-      case n: Naming =>
-        // explicit name
-        if (names.contains(n.name)) {
-          throw new IllegalArgumentException(s"Duplicate field name $n.name.")
-        } else {
-          names.add(n.name)
-        }
-      case u: UnresolvedFieldReference =>
-        // simple field forwarding
-        if (names.contains(u.name)) {
-          throw new IllegalArgumentException(s"Duplicate field name $u.name.")
-        } else {
-          names.add(u.name)
-        }
-      case _ => // Do nothing
-    }
-  }
-
 }
 
 /**
   * A table that has been grouped on a set of grouping keys.
-  *
-  * @param relNode The root node of the relational Calcite [[RelNode]] tree.
-  * @param tableEnv The [[TableEnvironment]] to which the table is bound.
-  * @param groupKey The Calcite [[GroupKey]] of this table.
   */
 class GroupedTable(
-  private[flink] override val relNode: RelNode,
-  private[flink] override val tableEnv: TableEnvironment,
-  private[flink] val groupKey: GroupKey) extends BaseTable(relNode, tableEnv) {
-
-  def relBuilder = tableEnv.getRelBuilder
+  private[flink] val table: Table,
+  private[flink] val groupKey: Seq[Expression]) {
 
   /**
     * Performs a selection operation on a grouped table. Similar to an SQL SELECT statement.
@@ -540,31 +359,19 @@ class GroupedTable(
     */
   def select(fields: Expression*): Table = {
 
-    relBuilder.push(relNode)
-
-    // separate aggregations and selection expressions
-    val extractedAggCalls: List[(Expression, List[AggCall])] = fields
-      .map(extractAggCalls(_, tableEnv)).toList
-
-    // get aggregation calls
-    val aggCalls: List[AggCall] = extractedAggCalls.flatMap(_._2)
+    val projectionOnAggregates = fields.map(extractAggregations(_, table.tableEnv))
+    val aggregations = projectionOnAggregates.flatMap(_._2)
 
-    // apply aggregations
-    relBuilder.aggregate(groupKey, aggCalls.toIterable.asJava)
-
-    // get selection expressions
-    val exprs: List[RexNode] = try {
-      extractedAggCalls.map(_._1.toRexNode(relBuilder))
-    } catch {
-      case iae: IllegalArgumentException  =>
-        throw new IllegalArgumentException(
-          "Only grouping fields and aggregations allowed after groupBy.", iae)
-      case e: Exception => throw e
+    val logical = if (aggregations.nonEmpty) {
+      Project(projectionOnAggregates.map(e => UnresolvedAlias(e._1)),
+        Aggregate(groupKey, aggregations, table.logicalPlan).validate(table.tableEnv)
+      )
+    } else {
+      Project(projectionOnAggregates.map(e => UnresolvedAlias(e._1)),
+        Aggregate(groupKey, Nil, table.logicalPlan).validate(table.tableEnv))
     }
 
-    relBuilder.project(exprs.toIterable.asJava)
-
-    new Table(relBuilder.build(), tableEnv)
+    new Table(table.tableEnv, logical.validate(table.tableEnv))
   }
 
   /**
@@ -581,5 +388,4 @@ class GroupedTable(
     val fieldExprs = ExpressionParser.parseExpressionList(fields)
     select(fieldExprs: _*)
   }
-
 }

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/trees/TreeNode.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/trees/TreeNode.scala b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/trees/TreeNode.scala
new file mode 100644
index 0000000..63c7013
--- /dev/null
+++ b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/trees/TreeNode.scala
@@ -0,0 +1,114 @@
+/*
+ * 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.flink.api.table.trees
+
+import org.apache.commons.lang.ClassUtils
+
+/**
+ * Generic base class for trees that can be transformed and traversed.
+ */
+abstract class TreeNode[A <: TreeNode[A]] extends Product { self: A =>
+
+  /**
+   * List of child nodes that should be considered when doing transformations. Other values
+   * in the Product will not be transformed, only handed through.
+   */
+  def children: Seq[A]
+
+  /**
+   * Tests for equality by first testing for reference equality.
+   */
+  def fastEquals(other: TreeNode[_]): Boolean = this.eq(other) || this == other
+
+  /**
+    * Do tree transformation in post order.
+    */
+  def postOrderTransform(rule: PartialFunction[A, A]): A = {
+    def childrenTransform(rule: PartialFunction[A, A]): A = {
+      var changed = false
+      val newArgs = productIterator.map {
+        case arg: TreeNode[_] if children.contains(arg) =>
+          val newChild = arg.asInstanceOf[A].postOrderTransform(rule)
+          if (!(newChild fastEquals arg)) {
+            changed = true
+            newChild
+          } else {
+            arg
+          }
+        case args: Traversable[_] => args.map {
+          case arg: TreeNode[_] if children.contains(arg) =>
+            val newChild = arg.asInstanceOf[A].postOrderTransform(rule)
+            if (!(newChild fastEquals arg)) {
+              changed = true
+              newChild
+            } else {
+              arg
+            }
+          case other => other
+        }
+        case nonChild: AnyRef => nonChild
+        case null => null
+      }.toArray
+      if (changed) makeCopy(newArgs) else this
+    }
+
+    val afterChildren = childrenTransform(rule)
+    if (afterChildren fastEquals this) {
+      rule.applyOrElse(this, identity[A])
+    } else {
+      rule.applyOrElse(afterChildren, identity[A])
+    }
+  }
+
+  /**
+    * Runs the given function first on the node and then recursively on all its children.
+    */
+  def preOrderVisit(f: A => Unit): Unit = {
+    f(this)
+    children.foreach(_.preOrderVisit(f))
+  }
+
+  /**
+   * Creates a new copy of this expression with new children. This is used during transformation
+   * if children change.
+   */
+  def makeCopy(newArgs: Array[AnyRef]): A = {
+    val ctors = getClass.getConstructors.filter(_.getParameterTypes.size > 0)
+    if (ctors.isEmpty) {
+      throw new RuntimeException(s"No valid constructor for ${getClass.getSimpleName}")
+    }
+
+    val defaultCtor = ctors.find { ctor =>
+      if (ctor.getParameterTypes.size != newArgs.length) {
+        false
+      } else if (newArgs.contains(null)) {
+        false
+      } else {
+        val argsClasses: Array[Class[_]] = newArgs.map(_.getClass)
+        ClassUtils.isAssignable(argsClasses, ctor.getParameterTypes)
+      }
+    }.getOrElse(ctors.maxBy(_.getParameterTypes.size))
+
+    try {
+      defaultCtor.newInstance(newArgs: _*).asInstanceOf[A]
+    } catch {
+      case e: java.lang.IllegalArgumentException =>
+        throw new IllegalArgumentException(s"Fail to copy treeNode ${getClass.getName}")
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/typeutils/TypeCheckUtils.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/typeutils/TypeCheckUtils.scala b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/typeutils/TypeCheckUtils.scala
new file mode 100644
index 0000000..1da1d2c
--- /dev/null
+++ b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/typeutils/TypeCheckUtils.scala
@@ -0,0 +1,40 @@
+/*
+ * 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.flink.api.table.typeutils
+
+import org.apache.flink.api.common.typeinfo.{NumericTypeInfo, TypeInformation}
+import org.apache.flink.api.table.validate._
+
+object TypeCheckUtils {
+
+  def assertNumericExpr(dataType: TypeInformation[_], caller: String): ExprValidationResult = {
+    if (dataType.isInstanceOf[NumericTypeInfo[_]]) {
+      ValidationSuccess
+    } else {
+      ValidationFailure(s"$caller requires numeric types, get $dataType here")
+    }
+  }
+
+  def assertOrderableExpr(dataType: TypeInformation[_], caller: String): ExprValidationResult = {
+    if (dataType.isSortKeyType) {
+      ValidationSuccess
+    } else {
+      ValidationFailure(s"$caller requires orderable types, get $dataType here")
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/typeutils/TypeCoercion.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/typeutils/TypeCoercion.scala b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/typeutils/TypeCoercion.scala
new file mode 100644
index 0000000..218996d
--- /dev/null
+++ b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/typeutils/TypeCoercion.scala
@@ -0,0 +1,92 @@
+/*
+ * 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.flink.api.table.typeutils
+
+import org.apache.flink.api.common.typeinfo.BasicTypeInfo._
+import org.apache.flink.api.common.typeinfo.{NumericTypeInfo, TypeInformation}
+
+/**
+  * Utilities for type conversions.
+  */
+object TypeCoercion {
+
+  val numericWideningPrecedence: IndexedSeq[TypeInformation[_]] =
+    IndexedSeq(
+      BYTE_TYPE_INFO,
+      SHORT_TYPE_INFO,
+      INT_TYPE_INFO,
+      LONG_TYPE_INFO,
+      FLOAT_TYPE_INFO,
+      DOUBLE_TYPE_INFO)
+
+  def widerTypeOf(tp1: TypeInformation[_], tp2: TypeInformation[_]): Option[TypeInformation[_]] = {
+    (tp1, tp2) match {
+      case (tp1, tp2) if tp1 == tp2 => Some(tp1)
+
+      case (_, STRING_TYPE_INFO) => Some(STRING_TYPE_INFO)
+      case (STRING_TYPE_INFO, _) => Some(STRING_TYPE_INFO)
+
+      case tuple if tuple.productIterator.forall(numericWideningPrecedence.contains) =>
+        val higherIndex = numericWideningPrecedence.lastIndexWhere(t => t == tp1 || t == tp2)
+        Some(numericWideningPrecedence(higherIndex))
+
+      case _ => None
+    }
+  }
+
+  /**
+    * Test if we can do cast safely without lose of information.
+    */
+  def canSafelyCast(from: TypeInformation[_], to: TypeInformation[_]): Boolean = (from, to) match {
+    case (_, STRING_TYPE_INFO) => true
+
+    case tuple if tuple.productIterator.forall(numericWideningPrecedence.contains) =>
+      if (numericWideningPrecedence.indexOf(from) < numericWideningPrecedence.indexOf(to)) {
+        true
+      } else {
+        false
+      }
+
+    case _ => false
+  }
+
+  /**
+    * All the supported cast types in flink-table.
+    * Note: This may lose information during the cast.
+    */
+  def canCast(from: TypeInformation[_], to: TypeInformation[_]): Boolean = (from, to) match {
+    case (from, to) if from == to => true
+
+    case (_, STRING_TYPE_INFO) => true
+
+    case (_, DATE_TYPE_INFO) => false // Date type not supported yet.
+    case (_, VOID_TYPE_INFO) => false // Void type not supported
+    case (_, CHAR_TYPE_INFO) => false // Character type not supported.
+
+    case (STRING_TYPE_INFO, _: NumericTypeInfo[_]) => true
+    case (STRING_TYPE_INFO, BOOLEAN_TYPE_INFO) => true
+
+    case (BOOLEAN_TYPE_INFO, _: NumericTypeInfo[_]) => true
+    case (_: NumericTypeInfo[_], BOOLEAN_TYPE_INFO) => true
+
+    case (_: NumericTypeInfo[_], _: NumericTypeInfo[_]) => true
+
+    case _ => false
+  }
+}

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/validate/ExprValidationResult.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/validate/ExprValidationResult.scala b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/validate/ExprValidationResult.scala
new file mode 100644
index 0000000..8571051
--- /dev/null
+++ b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/validate/ExprValidationResult.scala
@@ -0,0 +1,41 @@
+/*
+ * 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.flink.api.table.validate
+
+/**
+  * Represents the result of `Expression.validateInput`.
+  */
+sealed trait ExprValidationResult {
+  def isFailure: Boolean = !isSuccess
+  def isSuccess: Boolean
+}
+
+/**
+  * Represents the successful result of `Expression.checkInputDataTypes`.
+  */
+object ValidationSuccess extends ExprValidationResult {
+  val isSuccess: Boolean = true
+}
+
+/**
+  * Represents the failing result of `Expression.checkInputDataTypes`,
+  * with a error message to show the reason of failure.
+  */
+case class ValidationFailure(message: String) extends ExprValidationResult {
+  val isSuccess: Boolean = false
+}

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/validate/FunctionCatalog.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/validate/FunctionCatalog.scala b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/validate/FunctionCatalog.scala
new file mode 100644
index 0000000..726917e
--- /dev/null
+++ b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/validate/FunctionCatalog.scala
@@ -0,0 +1,124 @@
+/*
+ * 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.flink.api.table.validate
+
+import scala.collection.mutable
+import scala.util.{Failure, Success, Try}
+
+import org.apache.flink.api.table.expressions._
+import org.apache.flink.api.table.ValidationException
+
+/**
+  * A catalog for looking up user defined functions, used during validation phase.
+  */
+class FunctionCatalog {
+
+  private val functionBuilders = mutable.HashMap.empty[String, Class[_]]
+
+  def registerFunction(name: String, builder: Class[_]): Unit =
+    functionBuilders.put(name.toLowerCase, builder)
+
+  /**
+    * Lookup and create an expression if we find a match.
+    */
+  def lookupFunction(name: String, children: Seq[Expression]): Expression = {
+    val funcClass = functionBuilders.get(name.toLowerCase).getOrElse {
+      throw new ValidationException(s"undefined function $name")
+    }
+    withChildren(funcClass, children)
+  }
+
+  /**
+    * Instantiate a function using the provided `children`.
+    */
+  private def withChildren(func: Class[_], children: Seq[Expression]): Expression = {
+    // Try to find a constructor accepts `Seq[Expression]`
+    Try(func.getDeclaredConstructor(classOf[Seq[_]])) match {
+      case Success(seqCtor) =>
+        Try(seqCtor.newInstance(children).asInstanceOf[Expression]) match {
+          case Success(expr) => expr
+          case Failure(e) => throw new ValidationException(e.getMessage)
+        }
+      case Failure(e) =>
+        val childrenClass = Seq.fill(children.length)(classOf[Expression])
+        // Try to find a constructor matching the exact number of children
+        Try(func.getDeclaredConstructor(childrenClass: _*)) match {
+          case Success(ctor) =>
+            Try(ctor.newInstance(children: _*).asInstanceOf[Expression]) match {
+              case Success(expr) => expr
+              case Failure(e) => throw new ValidationException(e.getMessage)
+            }
+          case Failure(e) =>
+            throw new ValidationException(s"Invalid number of arguments for function $func")
+        }
+    }
+  }
+
+  /**
+    * Drop a function and return if the function existed.
+    */
+  def dropFunction(name: String): Boolean =
+    functionBuilders.remove(name.toLowerCase).isDefined
+
+  /**
+    * Drop all registered functions.
+    */
+  def clear(): Unit = functionBuilders.clear()
+}
+
+object FunctionCatalog {
+
+  val buildInFunctions: Map[String, Class[_]] = Map(
+    // aggregate functions
+    "avg" -> classOf[Avg],
+    "count" -> classOf[Count],
+    "max" -> classOf[Max],
+    "min" -> classOf[Min],
+    "sum" -> classOf[Sum],
+
+    // string functions
+    "charLength" -> classOf[CharLength],
+    "initCap" -> classOf[InitCap],
+    "like" -> classOf[Like],
+    "lowerCase" -> classOf[Lower],
+    "similar" -> classOf[Similar],
+    "subString" -> classOf[SubString],
+    "trim" -> classOf[Trim],
+    "upperCase" -> classOf[Upper],
+
+    // math functions
+    "abs" -> classOf[Abs],
+    "ceil" -> classOf[Ceil],
+    "exp" -> classOf[Exp],
+    "floor" -> classOf[Floor],
+    "log10" -> classOf[Log10],
+    "ln" -> classOf[Ln],
+    "power" -> classOf[Power],
+    "mod" -> classOf[Mod]
+  )
+
+  /**
+    * Create a new function catalog with build-in functions.
+    */
+  def withBuildIns: FunctionCatalog = {
+    val catalog = new FunctionCatalog()
+    buildInFunctions.foreach { case (n, c) => catalog.registerFunction(n, c) }
+    catalog
+  }
+}

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/TableEnvironmentITCase.java
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/TableEnvironmentITCase.java b/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/TableEnvironmentITCase.java
index 0a2cf57..8fdb2da 100644
--- a/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/TableEnvironmentITCase.java
+++ b/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/TableEnvironmentITCase.java
@@ -24,10 +24,7 @@ import org.apache.flink.api.java.table.BatchTableEnvironment;
 import org.apache.flink.api.java.tuple.Tuple3;
 import org.apache.flink.api.java.tuple.Tuple5;
 import org.apache.flink.api.scala.batch.utils.TableProgramsTestBase;
-import org.apache.flink.api.table.Row;
-import org.apache.flink.api.table.Table;
-import org.apache.flink.api.table.TableEnvironment;
-import org.apache.flink.api.table.TableException;
+import org.apache.flink.api.table.*;
 import org.apache.flink.test.javaApiOperators.util.CollectionDataSets;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -99,7 +96,7 @@ public class TableEnvironmentITCase extends TableProgramsTestBase {
 		tableEnv.registerDataSet("MyTable", ds2);
 	}
 
-	@Test(expected = TableException.class)
+	@Test(expected = ValidationException.class)
 	public void testScanUnregisteredTable() throws Exception {
 		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
 		BatchTableEnvironment tableEnv = TableEnvironment.getTableEnvironment(env, config());
@@ -127,7 +124,7 @@ public class TableEnvironmentITCase extends TableProgramsTestBase {
 		compareResultAsText(results, expected);
 	}
 
-	@Test(expected = TableException.class)
+	@Test(expected = ValidationException.class)
 	public void testIllegalName() throws Exception {
 		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
 		BatchTableEnvironment tableEnv = TableEnvironment.getTableEnvironment(env, config());
@@ -138,7 +135,7 @@ public class TableEnvironmentITCase extends TableProgramsTestBase {
 		tableEnv.registerTable("_DataSetTable_42", t);
 	}
 
-	@Test(expected = TableException.class)
+	@Test(expected = ValidationException.class)
 	public void testRegisterTableFromOtherEnv() throws Exception {
 		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
 		BatchTableEnvironment tableEnv1 = TableEnvironment.getTableEnvironment(env, config());

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/AggregationsITCase.java
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/AggregationsITCase.java b/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/AggregationsITCase.java
index d4af08d..ddf5884 100644
--- a/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/AggregationsITCase.java
+++ b/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/AggregationsITCase.java
@@ -27,7 +27,7 @@ import org.apache.flink.api.java.operators.DataSource;
 import org.apache.flink.api.java.tuple.Tuple2;
 import org.apache.flink.api.java.tuple.Tuple7;
 import org.apache.flink.api.table.TableEnvironment;
-import org.apache.flink.api.table.plan.PlanGenException;
+import org.apache.flink.api.table.ValidationException;
 import org.apache.flink.test.javaApiOperators.util.CollectionDataSets;
 import org.apache.flink.test.util.MultipleProgramsTestBase;
 import org.junit.Test;
@@ -59,7 +59,7 @@ public class AggregationsITCase extends MultipleProgramsTestBase {
 		compareResultAsText(results, expected);
 	}
 
-	@Test(expected = IllegalArgumentException.class)
+	@Test(expected = ValidationException.class)
 	public void testAggregationOnNonExistingField() throws Exception {
 		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
 		BatchTableEnvironment tableEnv = TableEnvironment.getTableEnvironment(env);
@@ -141,7 +141,7 @@ public class AggregationsITCase extends MultipleProgramsTestBase {
 		compareResultAsText(results, expected);
 	}
 
-	@Test(expected = PlanGenException.class)
+	@Test(expected = ValidationException.class)
 	public void testNonWorkingDataTypes() throws Exception {
 		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
 		BatchTableEnvironment tableEnv = TableEnvironment.getTableEnvironment(env);
@@ -161,7 +161,7 @@ public class AggregationsITCase extends MultipleProgramsTestBase {
 		compareResultAsText(results, expected);
 	}
 
-	@Test(expected = UnsupportedOperationException.class)
+	@Test(expected = ValidationException.class)
 	public void testNoNestedAggregation() throws Exception {
 		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
 		BatchTableEnvironment tableEnv = TableEnvironment.getTableEnvironment(env);

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/ExpressionsITCase.java
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/ExpressionsITCase.java b/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/ExpressionsITCase.java
index 0246904..83c7cfd 100644
--- a/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/ExpressionsITCase.java
+++ b/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/ExpressionsITCase.java
@@ -30,6 +30,8 @@ import org.apache.flink.api.java.tuple.Tuple3;
 import org.apache.flink.api.table.TableEnvironment;
 import org.apache.flink.api.table.codegen.CodeGenException;
 import static org.junit.Assert.fail;
+
+import org.apache.flink.api.table.ValidationException;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.junit.runners.Parameterized;
@@ -154,7 +156,7 @@ public class ExpressionsITCase extends TableProgramsTestBase {
 		compareResultAsText(results, expected);
 	}
 
-	@Test(expected = IllegalArgumentException.class)
+	@Test(expected = ValidationException.class)
 	public void testEvalInvalidTypes() throws Exception {
 		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
 		BatchTableEnvironment tableEnv = TableEnvironment.getTableEnvironment(env, config());

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/FilterITCase.java
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/FilterITCase.java b/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/FilterITCase.java
index 2848347..7a2bedf 100644
--- a/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/FilterITCase.java
+++ b/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/FilterITCase.java
@@ -26,6 +26,7 @@ import org.apache.flink.api.java.ExecutionEnvironment;
 import org.apache.flink.api.java.table.BatchTableEnvironment;
 import org.apache.flink.api.java.tuple.Tuple3;
 import org.apache.flink.api.table.TableEnvironment;
+import org.apache.flink.api.table.ValidationException;
 import org.apache.flink.test.javaApiOperators.util.CollectionDataSets;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -152,7 +153,7 @@ public class FilterITCase extends TableProgramsTestBase {
 		compareResultAsText(results, expected);
 	}
 
-	@Test(expected = IllegalArgumentException.class)
+	@Test(expected = ValidationException.class)
 	public void testFilterInvalidField() throws Exception {
 		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
 		BatchTableEnvironment tableEnv = TableEnvironment.getTableEnvironment(env, config());

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/GroupedAggregationsITCase.java
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/GroupedAggregationsITCase.java b/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/GroupedAggregationsITCase.java
index 70dd793..1906040 100644
--- a/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/GroupedAggregationsITCase.java
+++ b/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/GroupedAggregationsITCase.java
@@ -25,6 +25,7 @@ import org.apache.flink.api.java.ExecutionEnvironment;
 import org.apache.flink.api.java.table.BatchTableEnvironment;
 import org.apache.flink.api.java.tuple.Tuple3;
 import org.apache.flink.api.table.TableEnvironment;
+import org.apache.flink.api.table.ValidationException;
 import org.apache.flink.test.javaApiOperators.util.CollectionDataSets;
 import org.apache.flink.test.util.MultipleProgramsTestBase;
 import org.junit.Test;
@@ -40,7 +41,7 @@ public class GroupedAggregationsITCase extends MultipleProgramsTestBase {
 		super(mode);
 	}
 
-	@Test(expected = IllegalArgumentException.class)
+	@Test(expected = ValidationException.class)
 	public void testGroupingOnNonExistentField() throws Exception {
 		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
 		BatchTableEnvironment tableEnv = TableEnvironment.getTableEnvironment(env);
@@ -54,7 +55,7 @@ public class GroupedAggregationsITCase extends MultipleProgramsTestBase {
 			.select("a.avg");
 	}
 
-	@Test(expected = IllegalArgumentException.class)
+	@Test(expected = ValidationException.class)
 	public void testGroupingInvalidSelection() throws Exception {
 		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
 		BatchTableEnvironment tableEnv = TableEnvironment.getTableEnvironment(env);

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/JoinITCase.java
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/JoinITCase.java b/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/JoinITCase.java
index 4c40596..e6db3b0 100644
--- a/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/JoinITCase.java
+++ b/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/JoinITCase.java
@@ -26,7 +26,7 @@ import org.apache.flink.api.java.table.BatchTableEnvironment;
 import org.apache.flink.api.java.tuple.Tuple3;
 import org.apache.flink.api.java.tuple.Tuple5;
 import org.apache.flink.api.table.TableEnvironment;
-import org.apache.flink.api.table.TableException;
+import org.apache.flink.api.table.ValidationException;
 import org.apache.flink.test.javaApiOperators.util.CollectionDataSets;
 import org.apache.flink.test.util.MultipleProgramsTestBase;
 import org.junit.Test;
@@ -121,7 +121,7 @@ public class JoinITCase extends MultipleProgramsTestBase {
 		compareResultAsText(results, expected);
 	}
 
-	@Test(expected = IllegalArgumentException.class)
+	@Test(expected = ValidationException.class)
 	public void testJoinNonExistingKey() throws Exception {
 		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
 		BatchTableEnvironment tableEnv = TableEnvironment.getTableEnvironment(env);
@@ -136,7 +136,7 @@ public class JoinITCase extends MultipleProgramsTestBase {
 		in1.join(in2).where("foo === e").select("c, g");
 	}
 
-	@Test(expected = TableException.class)
+	@Test(expected = ValidationException.class)
 	public void testJoinWithNonMatchingKeyTypes() throws Exception {
 		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
 		BatchTableEnvironment tableEnv = TableEnvironment.getTableEnvironment(env);
@@ -154,7 +154,7 @@ public class JoinITCase extends MultipleProgramsTestBase {
 		tableEnv.toDataSet(result, Row.class).collect();
 	}
 
-	@Test(expected = IllegalArgumentException.class)
+	@Test(expected = ValidationException.class)
 	public void testJoinWithAmbiguousFields() throws Exception {
 		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
 		BatchTableEnvironment tableEnv = TableEnvironment.getTableEnvironment(env);
@@ -189,7 +189,7 @@ public class JoinITCase extends MultipleProgramsTestBase {
 		compareResultAsText(results, expected);
 	}
 
-	@Test(expected = TableException.class)
+	@Test(expected = ValidationException.class)
 	public void testJoinTablesFromDifferentEnvs() {
 		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
 		BatchTableEnvironment tEnv1 = TableEnvironment.getTableEnvironment(env);

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/SelectITCase.java
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/SelectITCase.java b/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/SelectITCase.java
index 7c9478a..e48914c 100644
--- a/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/SelectITCase.java
+++ b/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/SelectITCase.java
@@ -26,6 +26,7 @@ import org.apache.flink.api.java.ExecutionEnvironment;
 import org.apache.flink.api.java.table.BatchTableEnvironment;
 import org.apache.flink.api.java.tuple.Tuple3;
 import org.apache.flink.api.table.TableEnvironment;
+import org.apache.flink.api.table.ValidationException;
 import org.apache.flink.test.javaApiOperators.util.CollectionDataSets;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -103,7 +104,7 @@ public class SelectITCase extends TableProgramsTestBase {
 		compareResultAsText(results, expected);
 	}
 
-	@Test(expected = IllegalArgumentException.class)
+	@Test(expected = ValidationException.class)
 	public void testSelectInvalidField() throws Exception {
 		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
 		BatchTableEnvironment tableEnv = TableEnvironment.getTableEnvironment(env, config());
@@ -115,7 +116,7 @@ public class SelectITCase extends TableProgramsTestBase {
 			.select("a + 1, foo + 2");
 	}
 
-	@Test(expected = IllegalArgumentException.class)
+	@Test(expected = ValidationException.class)
 	public void testSelectAmbiguousFieldNames() throws Exception {
 		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
 		BatchTableEnvironment tableEnv = TableEnvironment.getTableEnvironment(env, config());

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/StringExpressionsITCase.java
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/StringExpressionsITCase.java b/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/StringExpressionsITCase.java
index e55bd22..db5eac9 100644
--- a/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/StringExpressionsITCase.java
+++ b/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/StringExpressionsITCase.java
@@ -21,10 +21,10 @@ package org.apache.flink.api.java.batch.table;
 
 import org.apache.flink.api.java.tuple.Tuple3;
 import org.apache.flink.api.table.TableEnvironment;
+import org.apache.flink.api.table.ValidationException;
 import org.apache.flink.test.javaApiOperators.util.CollectionDataSets;
 import org.apache.flink.api.table.Row;
 import org.apache.flink.api.table.Table;
-import org.apache.flink.api.table.codegen.CodeGenException;
 import org.apache.flink.api.java.DataSet;
 import org.apache.flink.api.java.ExecutionEnvironment;
 import org.apache.flink.api.java.table.BatchTableEnvironment;
@@ -64,6 +64,26 @@ public class StringExpressionsITCase extends MultipleProgramsTestBase {
 	}
 
 	@Test
+	public void testSubstringWithByteStart() throws Exception {
+		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
+		BatchTableEnvironment tableEnv = TableEnvironment.getTableEnvironment(env);
+
+		DataSet<Tuple2<String, Byte>> ds = env.fromElements(
+			new Tuple2<>("AAAA", (byte) 2),
+			new Tuple2<>("BBBB", (byte) 1));
+
+		Table in = tableEnv.fromDataSet(ds, "a, b");
+
+		Table result = in
+			.select("a.substring(1, b)");
+
+		DataSet<Row> resultSet = tableEnv.toDataSet(result, Row.class);
+		List<Row> results = resultSet.collect();
+		String expected = "AA\nB";
+		compareResultAsText(results, expected);
+	}
+
+	@Test
 	public void testSubstringWithMaxEnd() throws Exception {
 		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
 		BatchTableEnvironment tableEnv = TableEnvironment.getTableEnvironment(env);
@@ -83,7 +103,7 @@ public class StringExpressionsITCase extends MultipleProgramsTestBase {
 		compareResultAsText(results, expected);
 	}
 
-	@Test(expected = CodeGenException.class)
+	@Test(expected = ValidationException.class)
 	public void testNonWorkingSubstring1() throws Exception {
 		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
 		BatchTableEnvironment tableEnv = TableEnvironment.getTableEnvironment(env);
@@ -102,7 +122,7 @@ public class StringExpressionsITCase extends MultipleProgramsTestBase {
 		resultSet.collect();
 	}
 
-	@Test(expected = CodeGenException.class)
+	@Test(expected = ValidationException.class)
 	public void testNonWorkingSubstring2() throws Exception {
 		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
 		BatchTableEnvironment tableEnv = TableEnvironment.getTableEnvironment(env);
@@ -121,7 +141,7 @@ public class StringExpressionsITCase extends MultipleProgramsTestBase {
 		resultSet.collect();
 	}
 
-	@Test(expected = CodeGenException.class)
+	@Test(expected = ValidationException.class)
 	public void testGeneratedCodeForStringComparison() throws Exception {
 		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
 		BatchTableEnvironment tableEnv = TableEnvironment.getTableEnvironment(env);
@@ -132,7 +152,7 @@ public class StringExpressionsITCase extends MultipleProgramsTestBase {
 		DataSet<Row> resultSet = tableEnv.toDataSet(res, Row.class);
 	}
 
-	@Test(expected = CodeGenException.class)
+	@Test(expected = ValidationException.class)
 	public void testGeneratedCodeForIntegerEqualsComparison() throws Exception {
 		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
 		BatchTableEnvironment tableEnv = TableEnvironment.getTableEnvironment(env);
@@ -143,7 +163,7 @@ public class StringExpressionsITCase extends MultipleProgramsTestBase {
 		DataSet<Row> resultSet = tableEnv.toDataSet(res, Row.class);
 	}
 
-	@Test(expected = CodeGenException.class)
+	@Test(expected = ValidationException.class)
 	public void testGeneratedCodeForIntegerGreaterComparison() throws Exception {
 		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
 		BatchTableEnvironment tableEnv = TableEnvironment.getTableEnvironment(env);

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/UnionITCase.java
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/UnionITCase.java b/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/UnionITCase.java
index a7805f8..853cd7f 100644
--- a/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/UnionITCase.java
+++ b/flink-libraries/flink-table/src/test/java/org/apache/flink/api/java/batch/table/UnionITCase.java
@@ -26,7 +26,7 @@ import org.apache.flink.api.java.tuple.Tuple5;
 import org.apache.flink.api.table.Row;
 import org.apache.flink.api.table.Table;
 import org.apache.flink.api.table.TableEnvironment;
-import org.apache.flink.api.table.TableException;
+import org.apache.flink.api.table.ValidationException;
 import org.apache.flink.test.javaApiOperators.util.CollectionDataSets;
 import org.apache.flink.test.util.MultipleProgramsTestBase;
 import org.junit.Test;
@@ -80,7 +80,7 @@ public class UnionITCase extends MultipleProgramsTestBase {
 		compareResultAsText(results, expected);
 	}
 
-	@Test(expected = IllegalArgumentException.class)
+	@Test(expected = ValidationException.class)
 	public void testUnionIncompatibleNumberOfFields() throws Exception {
 		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
 		BatchTableEnvironment tableEnv = TableEnvironment.getTableEnvironment(env);
@@ -95,7 +95,7 @@ public class UnionITCase extends MultipleProgramsTestBase {
 		in1.unionAll(in2);
 	}
 
-	@Test(expected = IllegalArgumentException.class)
+	@Test(expected = ValidationException.class)
 	public void testUnionIncompatibleFieldsName() throws Exception {
 		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
 		BatchTableEnvironment tableEnv = TableEnvironment.getTableEnvironment(env);
@@ -110,7 +110,7 @@ public class UnionITCase extends MultipleProgramsTestBase {
 		in1.unionAll(in2);
 	}
 
-	@Test(expected = IllegalArgumentException.class)
+	@Test(expected = ValidationException.class)
 	public void testUnionIncompatibleFieldTypes() throws Exception {
 		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
 		BatchTableEnvironment tableEnv = TableEnvironment.getTableEnvironment(env);
@@ -168,7 +168,7 @@ public class UnionITCase extends MultipleProgramsTestBase {
 	    compareResultAsText(results, expected);
 	}
 
-	@Test(expected = TableException.class)
+	@Test(expected = ValidationException.class)
 	public void testUnionTablesFromDifferentEnvs() throws Exception {
 		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
 		BatchTableEnvironment tEnv1 = TableEnvironment.getTableEnvironment(env);

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/TableEnvironmentITCase.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/TableEnvironmentITCase.scala b/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/TableEnvironmentITCase.scala
index 80a491b..c33e1ef 100644
--- a/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/TableEnvironmentITCase.scala
+++ b/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/TableEnvironmentITCase.scala
@@ -23,7 +23,7 @@ import org.apache.flink.api.scala.batch.utils.TableProgramsTestBase
 import org.apache.flink.api.scala.batch.utils.TableProgramsTestBase.TableConfigMode
 import org.apache.flink.api.scala.table._
 import org.apache.flink.api.scala.util.CollectionDataSets
-import org.apache.flink.api.table.{Row, TableEnvironment, TableException}
+import org.apache.flink.api.table.{Row, TableEnvironment, TableException, ValidationException}
 import org.apache.flink.test.util.MultipleProgramsTestBase.TestExecutionMode
 import org.apache.flink.test.util.TestBaseUtils
 import org.junit._
@@ -89,7 +89,7 @@ class TableEnvironmentITCase(
     tEnv.registerDataSet("MyTable", ds2)
   }
 
-  @Test(expected = classOf[TableException])
+  @Test(expected = classOf[ValidationException])
   def testScanUnregisteredTable(): Unit = {
     val env = ExecutionEnvironment.getExecutionEnvironment
     val tEnv = TableEnvironment.getTableEnvironment(env, config)
@@ -130,7 +130,7 @@ class TableEnvironmentITCase(
     tEnv.registerDataSet("MyTable", t2)
   }
 
-  @Test(expected = classOf[TableException])
+  @Test(expected = classOf[ValidationException])
   def testRegisterTableFromOtherEnv(): Unit = {
     val env = ExecutionEnvironment.getExecutionEnvironment
     val tEnv1 = TableEnvironment.getTableEnvironment(env, config)

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/AggregationsITCase.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/AggregationsITCase.scala b/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/AggregationsITCase.scala
index c34edbc..6c413e5 100644
--- a/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/AggregationsITCase.scala
+++ b/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/AggregationsITCase.scala
@@ -21,8 +21,7 @@ package org.apache.flink.api.scala.batch.table
 import org.apache.flink.api.scala._
 import org.apache.flink.api.scala.table._
 import org.apache.flink.api.scala.util.CollectionDataSets
-import org.apache.flink.api.table.plan.PlanGenException
-import org.apache.flink.api.table.{Row, TableEnvironment}
+import org.apache.flink.api.table.{Row, TableEnvironment, ValidationException}
 import org.apache.flink.examples.scala.WordCountTable.{WC => MyWC}
 import org.apache.flink.test.util.MultipleProgramsTestBase.TestExecutionMode
 import org.apache.flink.test.util.{MultipleProgramsTestBase, TestBaseUtils}
@@ -49,7 +48,7 @@ class AggregationsITCase(mode: TestExecutionMode) extends MultipleProgramsTestBa
     TestBaseUtils.compareResultAsText(results.asJava, expected)
   }
 
-  @Test(expected = classOf[IllegalArgumentException])
+  @Test(expected = classOf[ValidationException])
   def testAggregationOnNonExistingField(): Unit = {
 
     val env = ExecutionEnvironment.getExecutionEnvironment
@@ -137,7 +136,7 @@ class AggregationsITCase(mode: TestExecutionMode) extends MultipleProgramsTestBa
     TestBaseUtils.compareResultAsText(result.asJava, expected)
   }
 
-  @Test(expected = classOf[PlanGenException])
+  @Test(expected = classOf[ValidationException])
   def testNonWorkingAggregationDataTypes(): Unit = {
 
     val env = ExecutionEnvironment.getExecutionEnvironment
@@ -150,7 +149,7 @@ class AggregationsITCase(mode: TestExecutionMode) extends MultipleProgramsTestBa
     t.collect()
   }
 
-  @Test(expected = classOf[UnsupportedOperationException])
+  @Test(expected = classOf[ValidationException])
   def testNoNestedAggregations(): Unit = {
 
     val env = ExecutionEnvironment.getExecutionEnvironment

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/ExpressionsITCase.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/ExpressionsITCase.scala b/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/ExpressionsITCase.scala
index fdbe3c9..9a0a035 100644
--- a/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/ExpressionsITCase.scala
+++ b/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/ExpressionsITCase.scala
@@ -27,7 +27,7 @@ import org.apache.flink.api.scala.batch.utils.TableProgramsTestBase.TableConfigM
 import org.apache.flink.api.scala.table._
 import org.apache.flink.api.table.codegen.CodeGenException
 import org.apache.flink.api.table.expressions.{Literal, Null}
-import org.apache.flink.api.table.{Row, TableEnvironment}
+import org.apache.flink.api.table.{Row, TableEnvironment, ValidationException}
 import org.apache.flink.test.util.MultipleProgramsTestBase.TestExecutionMode
 import org.apache.flink.test.util.TestBaseUtils
 import org.junit.Assert._
@@ -144,7 +144,7 @@ class ExpressionsITCase(
     TestBaseUtils.compareResultAsText(results.asJava, expected)
   }
 
-  @Test(expected = classOf[IllegalArgumentException])
+  @Test(expected = classOf[ValidationException])
   def testEvalInvalidTypes(): Unit = {
     val env = ExecutionEnvironment.getExecutionEnvironment
     val tEnv = TableEnvironment.getTableEnvironment(env, config)

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/FilterITCase.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/FilterITCase.scala b/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/FilterITCase.scala
index 5deff9e..ee0356f 100644
--- a/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/FilterITCase.scala
+++ b/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/FilterITCase.scala
@@ -24,7 +24,7 @@ import org.apache.flink.api.scala.batch.utils.TableProgramsTestBase.TableConfigM
 import org.apache.flink.api.scala.table._
 import org.apache.flink.api.scala.util.CollectionDataSets
 import org.apache.flink.api.table.expressions.Literal
-import org.apache.flink.api.table.{Row, TableEnvironment}
+import org.apache.flink.api.table.{Row, TableEnvironment, ValidationException}
 import org.apache.flink.test.util.MultipleProgramsTestBase.TestExecutionMode
 import org.apache.flink.test.util.TestBaseUtils
 import org.junit._
@@ -174,7 +174,7 @@ class FilterITCase(
     TestBaseUtils.compareResultAsText(results.asJava, expected)
   }
 
-  @Test(expected = classOf[IllegalArgumentException])
+  @Test(expected = classOf[ValidationException])
   def testFilterInvalidFieldName(): Unit = {
     val env = ExecutionEnvironment.getExecutionEnvironment
     val tEnv = TableEnvironment.getTableEnvironment(env, config)

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/GroupedAggregationsITCase.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/GroupedAggregationsITCase.scala b/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/GroupedAggregationsITCase.scala
index cbd42b2..8889b37 100644
--- a/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/GroupedAggregationsITCase.scala
+++ b/flink-libraries/flink-table/src/test/scala/org/apache/flink/api/scala/batch/table/GroupedAggregationsITCase.scala
@@ -21,7 +21,7 @@ package org.apache.flink.api.scala.batch.table
 import org.apache.flink.api.scala._
 import org.apache.flink.api.scala.table._
 import org.apache.flink.api.scala.util.CollectionDataSets
-import org.apache.flink.api.table.{Row, TableEnvironment}
+import org.apache.flink.api.table.{Row, TableEnvironment, ValidationException}
 import org.apache.flink.test.util.MultipleProgramsTestBase.TestExecutionMode
 import org.apache.flink.test.util.{MultipleProgramsTestBase, TestBaseUtils}
 import org.junit._
@@ -33,7 +33,7 @@ import scala.collection.JavaConverters._
 @RunWith(classOf[Parameterized])
 class GroupedAggregationsITCase(mode: TestExecutionMode) extends MultipleProgramsTestBase(mode) {
 
-  @Test(expected = classOf[IllegalArgumentException])
+  @Test(expected = classOf[ValidationException])
   def testGroupingOnNonExistentField(): Unit = {
 
     val env = ExecutionEnvironment.getExecutionEnvironment
@@ -45,7 +45,7 @@ class GroupedAggregationsITCase(mode: TestExecutionMode) extends MultipleProgram
       .select('a.avg)
   }
 
-  @Test(expected = classOf[IllegalArgumentException])
+  @Test(expected = classOf[ValidationException])
   def testGroupingInvalidSelection(): Unit = {
 
     val env = ExecutionEnvironment.getExecutionEnvironment


[5/5] flink git commit: [FLINK-3913] [docs] Clean up spelling mistakes.

Posted by fh...@apache.org.
[FLINK-3913] [docs] Clean up spelling mistakes.

This closes #1992


Project: http://git-wip-us.apache.org/repos/asf/flink/repo
Commit: http://git-wip-us.apache.org/repos/asf/flink/commit/4fbd8eb9
Tree: http://git-wip-us.apache.org/repos/asf/flink/tree/4fbd8eb9
Diff: http://git-wip-us.apache.org/repos/asf/flink/diff/4fbd8eb9

Branch: refs/heads/master
Commit: 4fbd8eb938cf0f1deee550161cc54f27757411e8
Parents: 1e9fff4
Author: Mark Reddy <ma...@gmail.com>
Authored: Mon May 16 00:52:53 2016 +0100
Committer: Fabian Hueske <fh...@apache.org>
Committed: Wed May 18 00:12:22 2016 +0200

----------------------------------------------------------------------
 docs/apis/batch/dataset_transformations.md      |  4 ++--
 docs/apis/batch/examples.md                     |  6 +++---
 docs/apis/batch/index.md                        | 16 ++++++++--------
 docs/apis/batch/iterations.md                   |  2 +-
 docs/apis/batch/libs/gelly.md                   |  4 ++--
 .../batch/libs/ml/multiple_linear_regression.md |  2 +-
 docs/apis/batch/libs/ml/pipelines.md            |  2 +-
 docs/apis/batch/python.md                       |  2 +-
 docs/apis/best_practices.md                     |  2 +-
 docs/apis/common/index.md                       |  4 ++--
 docs/apis/scala_shell.md                        |  2 +-
 docs/apis/streaming/connectors/rabbitmq.md      |  2 +-
 docs/apis/streaming/event_time.md               |  2 +-
 .../streaming/event_timestamps_watermarks.md    |  2 +-
 docs/apis/streaming/fault_tolerance.md          |  2 +-
 docs/apis/streaming/index.md                    | 20 ++++++++++----------
 docs/apis/streaming/storm_compatibility.md      |  4 ++--
 docs/apis/table.md                              |  6 +++---
 docs/internals/back_pressure_monitoring.md      |  2 +-
 docs/internals/general_arch.md                  |  2 +-
 docs/internals/job_scheduling.md                |  4 ++--
 docs/internals/monitoring_rest_api.md           |  6 +++---
 docs/setup/config.md                            |  8 ++++----
 docs/setup/local_setup.md                       |  2 +-
 docs/setup/yarn_setup.md                        |  8 ++++----
 25 files changed, 58 insertions(+), 58 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/flink/blob/4fbd8eb9/docs/apis/batch/dataset_transformations.md
----------------------------------------------------------------------
diff --git a/docs/apis/batch/dataset_transformations.md b/docs/apis/batch/dataset_transformations.md
index 2d72817..0de771a 100644
--- a/docs/apis/batch/dataset_transformations.md
+++ b/docs/apis/batch/dataset_transformations.md
@@ -1514,7 +1514,7 @@ The following hints are available:
   partitioned) and builds a hash table from the first input. This strategy is good if the first
   input is smaller than the second, but both inputs are still large.
   *Note:* This is the default fallback strategy that the system uses if no size estimates can be made
-  and no pre-existing partitiongs and sort-orders can be re-used.
+  and no pre-existing partitions and sort-orders can be re-used.
 
 * `REPARTITION_HASH_SECOND`: The system partitions (shuffles) each input (unless the input is already
   partitioned) and builds a hash table from the second input. This strategy is good if the second
@@ -1528,7 +1528,7 @@ The following hints are available:
 
 ### OuterJoin
 
-The OuterJoin transformation performs a left, right, or full outer join on two data sets. Outer joins are similar to regular (inner) joins and create all pairs of elements that are equal on their keys. In addition, records of the "outer" side (left, right, or both in case of full) are preserved if no matching key is found in the other side. Matching pair of elements (or one element and a `null` value for the other input) are given to a `JoinFunction` to turn the pair of elements into a single element, or to a `FlatJoinFunction` to turn the pair of elements into arbitararily many (including none) elements.
+The OuterJoin transformation performs a left, right, or full outer join on two data sets. Outer joins are similar to regular (inner) joins and create all pairs of elements that are equal on their keys. In addition, records of the "outer" side (left, right, or both in case of full) are preserved if no matching key is found in the other side. Matching pair of elements (or one element and a `null` value for the other input) are given to a `JoinFunction` to turn the pair of elements into a single element, or to a `FlatJoinFunction` to turn the pair of elements into arbitrarily many (including none) elements.
 
 The elements of both DataSets are joined on one or more keys which can be specified using
 

http://git-wip-us.apache.org/repos/asf/flink/blob/4fbd8eb9/docs/apis/batch/examples.md
----------------------------------------------------------------------
diff --git a/docs/apis/batch/examples.md b/docs/apis/batch/examples.md
index 3b6ccd4..3523185 100644
--- a/docs/apis/batch/examples.md
+++ b/docs/apis/batch/examples.md
@@ -118,7 +118,7 @@ val counts = text.flatMap { _.toLowerCase.split("\\W+") filter { _.nonEmpty } }
 counts.writeAsCsv(outputPath, "\n", " ")
 ~~~
 
-The {% gh_link /flink-examples/flink-exampls-batch/src/main/scala/org/apache/flink/examples/scala/wordcount/WordCount.scala  "WordCount example" %} implements the above described algorithm with input parameters: `--input <path> --output <path>`. As test data, any text file will do.
+The {% gh_link /flink-examples/flink-examples-batch/src/main/scala/org/apache/flink/examples/scala/wordcount/WordCount.scala  "WordCount example" %} implements the above described algorithm with input parameters: `--input <path> --output <path>`. As test data, any text file will do.
 
 
 </div>
@@ -171,11 +171,11 @@ public static final class JoinVertexWithEdgesMatch
     @Override
     public void join(<Tuple2<Long, Double> page, Tuple2<Long, Long[]> adj,
                         Collector<Tuple2<Long, Double>> out) {
-        Long[] neigbors = adj.f1;
+        Long[] neighbors = adj.f1;
         double rank = page.f1;
         double rankToDistribute = rank / ((double) neigbors.length);
 
-        for (int i = 0; i < neigbors.length; i++) {
+        for (int i = 0; i < neighbors.length; i++) {
             out.collect(new Tuple2<Long, Double>(neighbors[i], rankToDistribute));
         }
     }

http://git-wip-us.apache.org/repos/asf/flink/blob/4fbd8eb9/docs/apis/batch/index.md
----------------------------------------------------------------------
diff --git a/docs/apis/batch/index.md b/docs/apis/batch/index.md
index 653e5d7..4c0aea8 100644
--- a/docs/apis/batch/index.md
+++ b/docs/apis/batch/index.md
@@ -348,7 +348,7 @@ DataSet<Integer> data1 = // [...]
 DataSet<String> data2 = // [...]
 DataSet<Tuple2<Integer, String>> result = data1.cross(data2);
 {% endhighlight %}
-      <p>Note: Cross is potentially a <b>very</b> compute-intensive operation which can challenge even large compute clusters! It is adviced to hint the system with the DataSet sizes by using <i>crossWithTiny()</i> and <i>crossWithHuge()</i>.</p>
+      <p>Note: Cross is potentially a <b>very</b> compute-intensive operation which can challenge even large compute clusters! It is advised to hint the system with the DataSet sizes by using <i>crossWithTiny()</i> and <i>crossWithHuge()</i>.</p>
       </td>
     </tr>
     <tr>
@@ -560,7 +560,7 @@ val output: DataSet[(Int, String, Doublr)] = input.aggregate(SUM, 0).aggregate(M
   <p>You can also use short-hand syntax for minimum, maximum, and sum aggregations.</p>
 {% highlight scala %}
 val input: DataSet[(Int, String, Double)] = // [...]
-val output: DataSet[(Int, String, Doublr)] = input.sum(0).min(2)
+val output: DataSet[(Int, String, Double)] = input.sum(0).min(2)
 {% endhighlight %}
       </td>
     </tr>
@@ -1100,7 +1100,7 @@ DataSet:
 - `writeAsCsv(...)` / `CsvOutputFormat` - Writes tuples as comma-separated value files. Row and field
   delimiters are configurable. The value for each field comes from the *toString()* method of the objects.
 - `print()` / `printToErr()` / `print(String msg)` / `printToErr(String msg)` - Prints the *toString()* value
-of each element on the standard out / strandard error stream. Optionally, a prefix (msg) can be provided which is
+of each element on the standard out / standard error stream. Optionally, a prefix (msg) can be provided which is
 prepended to the output. This can help to distinguish between different calls to *print*. If the parallelism is
 greater than 1, the output will also be prepended with the identifier of the task which produced the output.
 - `write()` / `FileOutputFormat` - Method and base class for custom file outputs. Supports
@@ -1135,7 +1135,7 @@ values.writeAsCsv("file:///path/to/the/result/file", "\n", "|");
 // this writes tuples in the text formatting "(a, b, c)", rather than as CSV lines
 values.writeAsText("file:///path/to/the/result/file");
 
-// this wites values as strings using a user-defined TextFormatter object
+// this writes values as strings using a user-defined TextFormatter object
 values.writeAsFormattedText("file:///path/to/the/result/file",
     new TextFormatter<Tuple2<Integer, Integer>>() {
         public String format (Tuple2<Integer, Integer> value) {
@@ -1199,12 +1199,12 @@ using an
 Flink comes with a variety of built-in output formats that are encapsulated behind operations on the
 DataSet:
 
-- `writeAsText()` / `TextOuputFormat` - Writes elements line-wise as Strings. The Strings are
+- `writeAsText()` / `TextOutputFormat` - Writes elements line-wise as Strings. The Strings are
   obtained by calling the *toString()* method of each element.
 - `writeAsCsv(...)` / `CsvOutputFormat` - Writes tuples as comma-separated value files. Row and field
   delimiters are configurable. The value for each field comes from the *toString()* method of the objects.
 - `print()` / `printToErr()` - Prints the *toString()* value of each element on the
-  standard out / strandard error stream.
+  standard out / standard error stream.
 - `write()` / `FileOutputFormat` - Method and base class for custom file outputs. Supports
   custom object-to-bytes conversion.
 - `output()`/ `OutputFormat` - Most generic output method, for data sinks that are not file based
@@ -1237,7 +1237,7 @@ values.writeAsCsv("file:///path/to/the/result/file", "\n", "|")
 // this writes tuples in the text formatting "(a, b, c)", rather than as CSV lines
 values.writeAsText("file:///path/to/the/result/file");
 
-// this wites values as strings using a user-defined formatting
+// this writes values as strings using a user-defined formatting
 values map { tuple => tuple._1 + " - " + tuple._2 }
   .writeAsText("file:///path/to/the/result/file")
 {% endhighlight %}
@@ -1616,7 +1616,7 @@ result data. This section give some hints how to ease the development of Flink p
 ### Local Execution Environment
 
 A `LocalEnvironment` starts a Flink system within the same JVM process it was created in. If you
-start the LocalEnvironement from an IDE, you can set breakpoints in your code and easily debug your
+start the LocalEnvironment from an IDE, you can set breakpoints in your code and easily debug your
 program.
 
 A LocalEnvironment is created and used as follows:

http://git-wip-us.apache.org/repos/asf/flink/blob/4fbd8eb9/docs/apis/batch/iterations.md
----------------------------------------------------------------------
diff --git a/docs/apis/batch/iterations.md b/docs/apis/batch/iterations.md
index 912f378..bad058f 100644
--- a/docs/apis/batch/iterations.md
+++ b/docs/apis/batch/iterations.md
@@ -191,7 +191,7 @@ In the following example, every vertex has an **ID** and a **coloring**. Each ve
     <img alt="Delta Iterate Operator Example" width="100%" src="fig/iterations_delta_iterate_operator_example.png" />
 </p>
 
-The **intial input** is set as **both workset and solution set.** In the above figure, the colors visualize the **evolution of the solution set**. With each iteration, the color of the minimum ID is spreading in the respective subgraph. At the same time, the amount of work (exchanged and compared vertex IDs) decreases with each iteration. This corresponds to the **decreasing size of the workset**, which goes from all seven vertices to zero after three iterations, at which time the iteration terminates. The **important observation** is that *the lower subgraph converges before the upper half* does and the delta iteration is able to capture this with the workset abstraction.
+The **initial input** is set as **both workset and solution set.** In the above figure, the colors visualize the **evolution of the solution set**. With each iteration, the color of the minimum ID is spreading in the respective subgraph. At the same time, the amount of work (exchanged and compared vertex IDs) decreases with each iteration. This corresponds to the **decreasing size of the workset**, which goes from all seven vertices to zero after three iterations, at which time the iteration terminates. The **important observation** is that *the lower subgraph converges before the upper half* does and the delta iteration is able to capture this with the workset abstraction.
 
 In the upper subgraph **ID 1** (*orange*) is the **minimum ID**. In the **first iteration**, it will get propagated to vertex 2, which will subsequently change its color to orange. Vertices 3 and 4 will receive **ID 2** (in *yellow*) as their current minimum ID and change to yellow. Because the color of *vertex 1* didn't change in the first iteration, it can be skipped it in the next workset.
 

http://git-wip-us.apache.org/repos/asf/flink/blob/4fbd8eb9/docs/apis/batch/libs/gelly.md
----------------------------------------------------------------------
diff --git a/docs/apis/batch/libs/gelly.md b/docs/apis/batch/libs/gelly.md
index dd0b4c1..5d9bfd6 100644
--- a/docs/apis/batch/libs/gelly.md
+++ b/docs/apis/batch/libs/gelly.md
@@ -1957,7 +1957,7 @@ PageRank is an algorithm that was first used to rank web search engine results.
 
 #### Details
 The algorithm operates in iterations, where pages distribute their scores to their neighbors (pages they have links to) and subsequently update their scores based on the partial values they receive. The implementation assumes that each page has at least one incoming and one outgoing link.
-In order to consider the importance of a link from one page to another, scores are divided by the total number of out-links of the source page. Thus, a page with 10 links will distribute 1/10 of its score to each neighbor, while a page with 100 links, will distribute 1/100 of its score to each neighboring page. This process computes what is often called the transition probablities, i.e. the probability that some page will lead to other page while surfing the web. To correctly compute the transition probabilities, this implementation expectes the edge values to be initialiez to 1.0.
+In order to consider the importance of a link from one page to another, scores are divided by the total number of out-links of the source page. Thus, a page with 10 links will distribute 1/10 of its score to each neighbor, while a page with 100 links, will distribute 1/100 of its score to each neighboring page. This process computes what is often called the transition probablities, i.e. the probability that some page will lead to other page while surfing the web. To correctly compute the transition probabilities, this implementation expects the edge values to be initialised to 1.0.
 
 #### Usage
 The algorithm takes as input a `Graph` with any vertex type, `Double` vertex values, and `Double` edge values. Edges values should be initialized to 1.0, in order to correctly compute the transition probabilities. Otherwise, the transition probability for an Edge `(u, v)` will be set to the edge value divided by `u`'s out-degree. The algorithm returns a `DataSet` of vertices, where the vertex value corresponds to assigned rank after convergence (or maximum iterations).
@@ -2679,7 +2679,7 @@ A directed or undirected power-law graph generated using the
 [Recursive Matrix (R-Mat)](http://www.cs.cmu.edu/~christos/PUBLICATIONS/siam04.pdf) model.
 
 RMat is a stochastic generator configured with a source of randomness implementing the
-`RandomGenerableFactory` interface. Provided implemenations are `JDKRandomGeneratorFactory`
+`RandomGenerableFactory` interface. Provided implementations are `JDKRandomGeneratorFactory`
 and `MersenneTwisterFactory`. These generate an initial sequence of random values which are
 then used as seeds for generating the edges.
 

http://git-wip-us.apache.org/repos/asf/flink/blob/4fbd8eb9/docs/apis/batch/libs/ml/multiple_linear_regression.md
----------------------------------------------------------------------
diff --git a/docs/apis/batch/libs/ml/multiple_linear_regression.md b/docs/apis/batch/libs/ml/multiple_linear_regression.md
index 436f95b..b427eac 100644
--- a/docs/apis/batch/libs/ml/multiple_linear_regression.md
+++ b/docs/apis/batch/libs/ml/multiple_linear_regression.md
@@ -135,7 +135,7 @@ the algorithm's performance.
         <td>
             <p>
                 Learning rate method used to calculate the effective learning rate for each iteration.
-                See the list of supported <a href="optimization.html">learing rate methods</a>.
+                See the list of supported <a href="optimization.html">learning rate methods</a>.
                 (Default value: <strong>LearningRateMethod.Default</strong>)
             </p>
         </td>

http://git-wip-us.apache.org/repos/asf/flink/blob/4fbd8eb9/docs/apis/batch/libs/ml/pipelines.md
----------------------------------------------------------------------
diff --git a/docs/apis/batch/libs/ml/pipelines.md b/docs/apis/batch/libs/ml/pipelines.md
index a6cce45..f86476c 100644
--- a/docs/apis/batch/libs/ml/pipelines.md
+++ b/docs/apis/batch/libs/ml/pipelines.md
@@ -403,7 +403,7 @@ Furthermore, we can now use this transformer as part of an analysis pipeline whe
 val trainingData: DataSet[DenseVector] = ...
 
 val mean = MeanTransformer.setMean(1.0)
-val polyFeaturs = PolynomialFeatures().setDegree(3)
+val polyFeatures = PolynomialFeatures().setDegree(3)
 
 val pipeline = mean.chainTransformer(polyFeatures)
 

http://git-wip-us.apache.org/repos/asf/flink/blob/4fbd8eb9/docs/apis/batch/python.md
----------------------------------------------------------------------
diff --git a/docs/apis/batch/python.md b/docs/apis/batch/python.md
index 646683d..8771cb5 100644
--- a/docs/apis/batch/python.md
+++ b/docs/apis/batch/python.md
@@ -563,7 +563,7 @@ The degree of parallelism of a task can be specified in Flink on different level
 
 ### Execution Environment Level
 
-Flink programs are executed in the context of an [execution environmentt](#program-skeleton). An
+Flink programs are executed in the context of an [execution environment](#program-skeleton). An
 execution environment defines a default parallelism for all operators, data sources, and data sinks
 it executes. Execution environment parallelism can be overwritten by explicitly configuring the
 parallelism of an operator.

http://git-wip-us.apache.org/repos/asf/flink/blob/4fbd8eb9/docs/apis/best_practices.md
----------------------------------------------------------------------
diff --git a/docs/apis/best_practices.md b/docs/apis/best_practices.md
index 4d911dd..62e0ebf 100644
--- a/docs/apis/best_practices.md
+++ b/docs/apis/best_practices.md
@@ -214,7 +214,7 @@ final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
 env.getConfig().registerTypeWithKryoSerializer(MyCustomType.class, ProtobufSerializer.class);
 
 // register the serializer included with Apache Thrift as the standard serializer
-// TBaseSerializer states it should be initalized as a default Kryo serializer
+// TBaseSerializer states it should be initialized as a default Kryo serializer
 env.getConfig().addDefaultKryoSerializer(MyCustomType.class, TBaseSerializer.class);
 
 {% endhighlight %}

http://git-wip-us.apache.org/repos/asf/flink/blob/4fbd8eb9/docs/apis/common/index.md
----------------------------------------------------------------------
diff --git a/docs/apis/common/index.md b/docs/apis/common/index.md
index cb2c78d..022f961 100644
--- a/docs/apis/common/index.md
+++ b/docs/apis/common/index.md
@@ -336,7 +336,7 @@ print()
 </div>
 
 Once you specified the complete program you need to **trigger the program execution** by calling
-`execute()` on the `StreamExecutionEnviroment`.
+`execute()` on the `StreamExecutionEnvironment`.
 Depending on the type of the `ExecutionEnvironment` the execution will be triggered on your local
 machine or submit your program for execution on a cluster.
 
@@ -1236,7 +1236,7 @@ Client can either be a Java or a Scala program. One example of such a Client is
 Flink's Command-line Interface (CLI).
 
 For the CLI client, the parallelism parameter can be specified with `-p`. For
-exampple:
+example:
 
     ./bin/flink run -p 10 ../examples/*WordCount-java*.jar
 

http://git-wip-us.apache.org/repos/asf/flink/blob/4fbd8eb9/docs/apis/scala_shell.md
----------------------------------------------------------------------
diff --git a/docs/apis/scala_shell.md b/docs/apis/scala_shell.md
index 0377f5a..ad36ca0 100644
--- a/docs/apis/scala_shell.md
+++ b/docs/apis/scala_shell.md
@@ -62,7 +62,7 @@ Scala-Flink> counts.print()
 
 The print() command will automatically send the specified tasks to the JobManager for execution and will show the result of the computation in the terminal.
 
-It is possbile to write results to a file. However, in this case you need to call `execute`, to run your program:
+It is possible to write results to a file. However, in this case you need to call `execute`, to run your program:
 
 ~~~scala
 Scala-Flink> benv.execute("MyProgram")

http://git-wip-us.apache.org/repos/asf/flink/blob/4fbd8eb9/docs/apis/streaming/connectors/rabbitmq.md
----------------------------------------------------------------------
diff --git a/docs/apis/streaming/connectors/rabbitmq.md b/docs/apis/streaming/connectors/rabbitmq.md
index f5ea702..b48608d 100644
--- a/docs/apis/streaming/connectors/rabbitmq.md
+++ b/docs/apis/streaming/connectors/rabbitmq.md
@@ -50,7 +50,7 @@ The followings have to be provided for the `RMQSource(\u2026)` constructor in order
 - hostName: The RabbitMQ broker hostname.
 - queueName: The RabbitMQ queue name.
 - usesCorrelationId: `true` when correlation ids should be used, `false` otherwise (default is `false`).
-- deserializationScehma: Deserialization schema to turn messages into Java objects.
+- deserializationSchema: Deserialization schema to turn messages into Java objects.
 
 This source can be operated in three different modes:
 

http://git-wip-us.apache.org/repos/asf/flink/blob/4fbd8eb9/docs/apis/streaming/event_time.md
----------------------------------------------------------------------
diff --git a/docs/apis/streaming/event_time.md b/docs/apis/streaming/event_time.md
index 0b4da03..7bc53e7 100644
--- a/docs/apis/streaming/event_time.md
+++ b/docs/apis/streaming/event_time.md
@@ -84,7 +84,7 @@ Flink supports different notions of *time* in streaming programs.
 
 The first part of a Flink DataStream program is usually to set the base *time characteristic*. That setting
 defines how data stream sources behave (for example whether to assign timestamps), and what notion of
-time the window operations like `KeyedStream.timeWindow(Time.secondss(30))` refer to.
+time the window operations like `KeyedStream.timeWindow(Time.seconds(30))` refer to.
 
 The following example shows a Flink program that aggregates events in hourly time windows. The behavior of the
 windows adapts with the time characteristic.

http://git-wip-us.apache.org/repos/asf/flink/blob/4fbd8eb9/docs/apis/streaming/event_timestamps_watermarks.md
----------------------------------------------------------------------
diff --git a/docs/apis/streaming/event_timestamps_watermarks.md b/docs/apis/streaming/event_timestamps_watermarks.md
index 11c97a7..0ec2810 100644
--- a/docs/apis/streaming/event_timestamps_watermarks.md
+++ b/docs/apis/streaming/event_timestamps_watermarks.md
@@ -69,7 +69,7 @@ There are two ways to assign timestamps and generate Watermarks:
 Stream sources can also directly assign timestamps to the elements they produce and emit Watermarks. In that case,
 no Timestamp Assigner is needed.
 
-To assign a timestamp to an element in the soruce directly, the source must use the `collectWithTimestamp(...)`
+To assign a timestamp to an element in the source directly, the source must use the `collectWithTimestamp(...)`
 method on the `SourceContext`. To generate Watermarks, the source must call the `emitWatermark(Watermark)` function.
 
 Below is a simple example of a source *(non-checkpointed)* that assigns timestamps and generates Watermarks

http://git-wip-us.apache.org/repos/asf/flink/blob/4fbd8eb9/docs/apis/streaming/fault_tolerance.md
----------------------------------------------------------------------
diff --git a/docs/apis/streaming/fault_tolerance.md b/docs/apis/streaming/fault_tolerance.md
index d85038b..f6e90a4 100644
--- a/docs/apis/streaming/fault_tolerance.md
+++ b/docs/apis/streaming/fault_tolerance.md
@@ -36,7 +36,7 @@ transient program failures, etc.
 Streaming Fault Tolerance
 -------------------------
 
-Flink has a checkpointing mechanism that recovers streaming jobs after failues. The checkpointing mechanism requires a *persistent* (or *durable*) source that
+Flink has a checkpointing mechanism that recovers streaming jobs after failures. The checkpointing mechanism requires a *persistent* (or *durable*) source that
 can be asked for prior records again (Apache Kafka is a good example of such a source).
 
 The checkpointing mechanism stores the progress in the data sources and data sinks, the state of windows, as well as the user-defined state (see [Working with State](state.html)) consistently to provide *exactly once* processing semantics. Where the checkpoints are stored (e.g., JobManager memory, file system, database) depends on the configured [state backend](state_backends.html).

http://git-wip-us.apache.org/repos/asf/flink/blob/4fbd8eb9/docs/apis/streaming/index.md
----------------------------------------------------------------------
diff --git a/docs/apis/streaming/index.md b/docs/apis/streaming/index.md
index 17d8b56..8a825dd 100644
--- a/docs/apis/streaming/index.md
+++ b/docs/apis/streaming/index.md
@@ -270,7 +270,7 @@ DataStream<String> result =
           <td><strong>Aggregations</strong><br>KeyedStream &rarr; DataStream</td>
           <td>
             <p>Rolling aggregations on a keyed data stream. The difference between min
-	    and minBy is that min returns the minimun value, whereas minBy returns
+	    and minBy is that min returns the minimum value, whereas minBy returns
 	    the element that has the minimum value in this field (same for max and maxBy).</p>
     {% highlight java %}
 keyedStream.sum(0);
@@ -726,7 +726,7 @@ val result: DataStream[String] =
           <td><strong>Aggregations on windows</strong><br>WindowedStream &rarr; DataStream</td>
           <td>
             <p>Aggregates the contents of a window. The difference between min
-	    and minBy is that min returns the minimun value, whereas minBy returns
+	    and minBy is that min returns the minimum value, whereas minBy returns
 	    the element that has the minimum value in this field (same for max and maxBy).</p>
     {% highlight scala %}
 windowedStream.sum(0)
@@ -1415,14 +1415,14 @@ Data sinks consume DataStreams and forward them to files, sockets, external syst
 Flink comes with a variety of built-in output formats that are encapsulated behind operations on the
 DataStreams:
 
-- `writeAsText()` / `TextOuputFormat` - Writes elements line-wise as Strings. The Strings are
+- `writeAsText()` / `TextOutputFormat` - Writes elements line-wise as Strings. The Strings are
   obtained by calling the *toString()* method of each element.
 
 - `writeAsCsv(...)` / `CsvOutputFormat` - Writes tuples as comma-separated value files. Row and field
   delimiters are configurable. The value for each field comes from the *toString()* method of the objects.
 
 - `print()` / `printToErr()`  - Prints the *toString()* value
-of each element on the standard out / strandard error stream. Optionally, a prefix (msg) can be provided which is
+of each element on the standard out / standard error stream. Optionally, a prefix (msg) can be provided which is
 prepended to the output. This can help to distinguish between different calls to *print*. If the parallelism is
 greater than 1, the output will also be prepended with the identifier of the task which produced the output.
 
@@ -1443,14 +1443,14 @@ Data sinks consume DataStreams and forward them to files, sockets, external syst
 Flink comes with a variety of built-in output formats that are encapsulated behind operations on the
 DataStreams:
 
-- `writeAsText()` / `TextOuputFormat` - Writes elements line-wise as Strings. The Strings are
+- `writeAsText()` / `TextOutputFormat` - Writes elements line-wise as Strings. The Strings are
   obtained by calling the *toString()* method of each element.
 
 - `writeAsCsv(...)` / `CsvOutputFormat` - Writes tuples as comma-separated value files. Row and field
   delimiters are configurable. The value for each field comes from the *toString()* method of the objects.
 
 - `print()` / `printToErr()`  - Prints the *toString()* value
-of each element on the standard out / strandard error stream. Optionally, a prefix (msg) can be provided which is
+of each element on the standard out / standard error stream. Optionally, a prefix (msg) can be provided which is
 prepended to the output. This can help to distinguish between different calls to *print*. If the parallelism is
 greater than 1, the output will also be prepended with the identifier of the task which produced the output.
 
@@ -1472,7 +1472,7 @@ OutputFormat. This means that not all elements send to the OutputFormat are imme
 in the target system. Also, in failure cases, those records might be lost.
 
 For reliable, exactly-once delivery of a stream into a file system, use the `flink-connector-filesystem`.
-Also, custom implementations through the `.addSink(...)` method can partiticpate in Flink's checkpointing
+Also, custom implementations through the `.addSink(...)` method can participate in Flink's checkpointing
 for exactly-once semantics.
 
 {% top %}
@@ -1494,7 +1494,7 @@ or a `filter`. Here, we show an example using filters. First, we define an `Iter
 IterativeStream<Integer> iteration = input.iterate();
 {% endhighlight %}
 
-Then, we specify the logic that will be executed inside the loop using a series of trasformations (here
+Then, we specify the logic that will be executed inside the loop using a series of transformations (here
 a simple `map` transformation)
 
 {% highlight java %}
@@ -1627,7 +1627,7 @@ Usage:
 LocalStreamEnvironment env = StreamExecutionEnvironment.createLocalEnvironment();
 env.setBufferTimeout(timeoutMillis);
 
-env.genereateSequence(1,10).map(new MyMapper()).setBufferTimeout(timeoutMillis);
+env.generateSequence(1,10).map(new MyMapper()).setBufferTimeout(timeoutMillis);
 {% endhighlight %}
 </div>
 <div data-lang="scala" markdown="1">
@@ -1660,7 +1660,7 @@ result data. This section give some hints how to ease the development of Flink p
 ### Local Execution Environment
 
 A `LocalStreamEnvironment` starts a Flink system within the same JVM process it was created in. If you
-start the LocalEnvironement from an IDE, you can set breakpoints in your code and easily debug your
+start the LocalEnvironment from an IDE, you can set breakpoints in your code and easily debug your
 program.
 
 A LocalEnvironment is created and used as follows:

http://git-wip-us.apache.org/repos/asf/flink/blob/4fbd8eb9/docs/apis/streaming/storm_compatibility.md
----------------------------------------------------------------------
diff --git a/docs/apis/streaming/storm_compatibility.md b/docs/apis/streaming/storm_compatibility.md
index 6c8c018..94e0042 100644
--- a/docs/apis/streaming/storm_compatibility.md
+++ b/docs/apis/streaming/storm_compatibility.md
@@ -166,7 +166,7 @@ Bolts can accesses input tuple fields via name (additionally to access via index
 To use this feature with embedded Bolts, you need to have either a
 
  1. [POJO]({{site.baseurl}}/apis/batch/index.html#pojos) type input stream or
- 2. [Tuple]({{site.baseurl}}/apis/batch/index.html#tuples-and-case-classes) type input stream and spedify the input schema (ie, name-to-index-mapping)
+ 2. [Tuple]({{site.baseurl}}/apis/batch/index.html#tuples-and-case-classes) type input stream and specify the input schema (i.e. name-to-index-mapping)
 
 For POJO input types, Flink accesses the fields via reflection.
 For this case, Flink expects either a corresponding public member variable or public getter method.
@@ -261,7 +261,7 @@ An example of a finite Spout that emits records for 10 seconds only:
 <div data-lang="java" markdown="1">
 ~~~java
 public class TimedFiniteSpout extends BaseRichSpout implements FiniteSpout {
-	[...] // implemente open(), nextTuple(), ...
+	[...] // implement open(), nextTuple(), ...
 
 	private long starttime = System.currentTimeMillis();
 

http://git-wip-us.apache.org/repos/asf/flink/blob/4fbd8eb9/docs/apis/table.md
----------------------------------------------------------------------
diff --git a/docs/apis/table.md b/docs/apis/table.md
index 3defdbb..eae4ebd 100644
--- a/docs/apis/table.md
+++ b/docs/apis/table.md
@@ -29,7 +29,7 @@ under the License.
 **Table API and SQL are experimental features**
 
 The Table API is a SQL-like expression language for relational stream and batch processing that can be easily embedded in Flink's DataSet and DataStream APIs (Java and Scala).
-The Table API and SQL insterface operate on a relational `Table` abstraction, which can be created from external data sources, or existing DataSets and DataStreams. With the Table API, you can apply relational operators such as selection, aggregation, and joins on `Table`s.
+The Table API and SQL interface operate on a relational `Table` abstraction, which can be created from external data sources, or existing DataSets and DataStreams. With the Table API, you can apply relational operators such as selection, aggregation, and joins on `Table`s.
 
 `Table`s can also be queried with regular SQL, as long as they are registered (see [Registering and Accessing Tables](#registering-and-accessing-tables)). The Table API and SQL offer equivalent functionality and can be mixed in the same program. When a `Table` is converted back into a `DataSet` or `DataStream`, the logical plan, which was defined by relational operators and SQL queries, is optimized using [Apache Calcite](https://calcite.apache.org/) and transformed into a `DataSet` or `DataStream` execution plan.
 
@@ -130,7 +130,7 @@ tableEnv.registerDataStream("Orders", ord, 'user, 'product, 'amount)
 
 ### Register a Table
 
-A `Table` that originates from a Table API operation or a SQL query is registered in a `TableEnvironemnt` as follows:
+A `Table` that originates from a Table API operation or a SQL query is registered in a `TableEnvironment` as follows:
 
 <div class="codetabs" markdown="1">
 <div data-lang="java" markdown="1">
@@ -688,7 +688,7 @@ SQL queries can be executed on DataStream Tables by adding the `STREAM` SQL keyw
 Emit a Table to external sinks
 ----
 
-A `Table` can be emitted to a `TableSink`, which is a generic interface to support a wide variaty of file formats (e.g., CSV, Apache Parquet, Apache Avro), storage systems (e.g., JDBC, Apache HBase, Apache Cassandra, Elasticsearch), or messaging systems (e.g., Apache Kafka, RabbitMQ), and others. A batch `Table` can only be emitted by a `BatchTableSink`, a streaming table requires a `StreamTableSink` (a `TableSink` can implement both interfaces). 
+A `Table` can be emitted to a `TableSink`, which is a generic interface to support a wide variety of file formats (e.g. CSV, Apache Parquet, Apache Avro), storage systems (e.g., JDBC, Apache HBase, Apache Cassandra, Elasticsearch), or messaging systems (e.g., Apache Kafka, RabbitMQ), and others. A batch `Table` can only be emitted by a `BatchTableSink`, a streaming table requires a `StreamTableSink` (a `TableSink` can implement both interfaces). 
 
 Currently, Flink only provides a `CsvTableSink` that writes a batch or streaming `Table` to CSV-formatted files. A custom `TableSource` can be defined by implementing the `BatchTableSink` and/or `StreamTableSink` interface. 
 

http://git-wip-us.apache.org/repos/asf/flink/blob/4fbd8eb9/docs/internals/back_pressure_monitoring.md
----------------------------------------------------------------------
diff --git a/docs/internals/back_pressure_monitoring.md b/docs/internals/back_pressure_monitoring.md
index d272eaf..ee25e3b 100644
--- a/docs/internals/back_pressure_monitoring.md
+++ b/docs/internals/back_pressure_monitoring.md
@@ -54,7 +54,7 @@ In order to not overload the task managers with stack trace samples, the web int
 
 ## Configuration
 
-You can configure the number of samples for the job manager with the following confiugration keys:
+You can configure the number of samples for the job manager with the following configuration keys:
 
 - `jobmanager.web.backpressure.refresh-interval`: Time after which available stats are deprecated and need to be refreshed (DEFAULT: 60000, 1 min).
 - `jobmanager.web.backpressure.num-samples`: Number of stack trace samples to take to determine back pressure (DEFAULT: 100).

http://git-wip-us.apache.org/repos/asf/flink/blob/4fbd8eb9/docs/internals/general_arch.md
----------------------------------------------------------------------
diff --git a/docs/internals/general_arch.md b/docs/internals/general_arch.md
index c599a01..612fb6b 100644
--- a/docs/internals/general_arch.md
+++ b/docs/internals/general_arch.md
@@ -83,7 +83,7 @@ You can click on the components in the figure to learn more.
 ## Projects and Dependencies
 
 The Flink system code is divided into multiple sub-projects. The goal is to reduce the number of
-dependencies that a project implementing a Flink progam needs, as well as to faciltate easier testing
+dependencies that a project implementing a Flink program needs, as well as to faciltate easier testing
 of smaller sub-modules.
 
 The individual projects and their dependencies are shown in the figure below.

http://git-wip-us.apache.org/repos/asf/flink/blob/4fbd8eb9/docs/internals/job_scheduling.md
----------------------------------------------------------------------
diff --git a/docs/internals/job_scheduling.md b/docs/internals/job_scheduling.md
index cce78d9..1e1da97 100644
--- a/docs/internals/job_scheduling.md
+++ b/docs/internals/job_scheduling.md
@@ -60,8 +60,8 @@ and reacts to finished tasks or execution failures.
 The JobManager receives the {% gh_link /flink-runtime/src/main/java/org/apache/flink/runtime/jobgraph/ "JobGraph" %},
 which is a representation of the data flow consisting of operators ({% gh_link /flink-runtime/src/main/java/org/apache/flink/runtime/jobgraph/JobVertex.java "JobVertex" %})
 and intermediate results ({% gh_link /flink-runtime/src/main/java/org/apache/flink/runtime/jobgraph/IntermediateDataSet.java "IntermediateDataSet" %}).
-Each operator has properies, like the parallelism and the code that it executes.
-In addition, the JobGraph has a set of attached libraries, that are neccessary to execute the code of the operators.
+Each operator has properties, like the parallelism and the code that it executes.
+In addition, the JobGraph has a set of attached libraries, that are necessary to execute the code of the operators.
 
 The JobManager transforms the JobGraph into an {% gh_link /flink-runtime/src/main/java/org/apache/flink/runtime/executiongraph/ "ExecutionGraph" %}.
 The ExecutionGraph is a parallel version of the JobGraph: For each JobVertex, it contains an {% gh_link /flink-runtime/src/main/java/org/apache/flink/runtime/executiongraph/ExecutionVertex.java "ExecutionVertex" %} per parallel subtask. An operator with a parallelism of 100 will have one JobVertex and 100 ExecutionVertices.

http://git-wip-us.apache.org/repos/asf/flink/blob/4fbd8eb9/docs/internals/monitoring_rest_api.md
----------------------------------------------------------------------
diff --git a/docs/internals/monitoring_rest_api.md b/docs/internals/monitoring_rest_api.md
index 97a5c51..ca1cf13 100644
--- a/docs/internals/monitoring_rest_api.md
+++ b/docs/internals/monitoring_rest_api.md
@@ -39,7 +39,7 @@ The monitoring API is backed by a web server that runs as part of the *JobManage
 
 In the case of multiple JobManagers (for high availability), each JobManager will run its own instance of the monitoring API, which offers information about completed and running job while that JobManager was elected the cluster leader.
 
-**NOTE:** Currently, the monitoring API is started together with the new web dashboard. To enable it, one need to add the following entry to the `flink-conf.yaml` in order to activate the new dashboard instread of the old dashboard: `jobmanager.new-web-frontend: true`
+**NOTE:** Currently, the monitoring API is started together with the new web dashboard. To enable it, one need to add the following entry to the `flink-conf.yaml` in order to activate the new dashboard instead of the old dashboard: `jobmanager.new-web-frontend: true`
 
 
 ## Developing
@@ -169,11 +169,11 @@ Sample Result:
 
 **`/joboverview/running`**
 
-Jobs, groupes by status, each with a small summary of its status. The same as `/joboverview`, but containing only currently running jobs.
+Jobs, grouped by status, each with a small summary of its status. The same as `/joboverview`, but containing only currently running jobs.
 
 **`/joboverview/completed`**
 
-Jobs, groupes by status, each with a small summary of its status. The same as `/joboverview`, but containing only completed (finished, canceled, or failed) jobs.
+Jobs, grouped by status, each with a small summary of its status. The same as `/joboverview`, but containing only completed (finished, canceled, or failed) jobs.
 
 
 ### Details of a Running or Completed Job

http://git-wip-us.apache.org/repos/asf/flink/blob/4fbd8eb9/docs/setup/config.md
----------------------------------------------------------------------
diff --git a/docs/setup/config.md b/docs/setup/config.md
index db189a0..14e9d21 100644
--- a/docs/setup/config.md
+++ b/docs/setup/config.md
@@ -83,7 +83,7 @@ The default fraction for managed memory can be adjusted using the `taskmanager.m
 
 ### Memory and Performance Debugging
 
-These options are useful for debugging a Flink application for memory and garbage collection related isues, such as performance and out-of-memory process kills or exceptions.
+These options are useful for debugging a Flink application for memory and garbage collection related issues, such as performance and out-of-memory process kills or exceptions.
 
 - `taskmanager.debug.memory.startLogThread`: Causes the TaskManagers to periodically log memory and Garbage collection statistics. The statistics include current heap-, off-heap, and other memory pool utilization, as well as the time spent on garbage collection, by heap memory pool.
 
@@ -97,7 +97,7 @@ Flink supports Kerberos authentication of Hadoop services such as HDFS, YARN, or
   other versions have critical bugs which might fail the Flink job
   unexpectedly.**
 
-While Hadoop uses Kerberos tickets to authenticate users with services initially, the authentication process continues differently afterwards. Instead of saving the ticket to authenticate on a later access, Hadoop creates its own security tockens (DelegationToken) that it passes around. These are authenticated to Kerberos periodically but are independent of the token renewal time. The tokens have a maximum life span identical to the Kerberos ticket maximum life span.
+While Hadoop uses Kerberos tickets to authenticate users with services initially, the authentication process continues differently afterwards. Instead of saving the ticket to authenticate on a later access, Hadoop creates its own security tokens (DelegationToken) that it passes around. These are authenticated to Kerberos periodically but are independent of the token renewal time. The tokens have a maximum life span identical to the Kerberos ticket maximum life span.
 
 Please make sure to set the maximum ticket life span high long running jobs. The renewal time of the ticket, on the other hand, is not important because Hadoop abstracts this away using its own security tocken renewal system. Hadoop makes sure that tickets are renewed in time and you can be sure to be authenticated until the end of the ticket life time.
 
@@ -220,7 +220,7 @@ definition. This scheme is used **ONLY** if no other scheme is specified (explic
 
 ### Runtime Algorithms
 
-- `taskmanager.runtime.hashjoin-bloom-filters`: Flag to activate/deactivate bloomfilters in the hybrid hash join implementation. In cases where the hash join needs to spill to disk (datasets larger than the reserved fraction of memory), these bloom filters can greatly reduce the number of spilled records, at the cost some CPU cycles. (DEFAULT: false)
+- `taskmanager.runtime.hashjoin-bloom-filters`: Flag to activate/deactivate bloom filters in the hybrid hash join implementation. In cases where the hash join needs to spill to disk (datasets larger than the reserved fraction of memory), these bloom filters can greatly reduce the number of spilled records, at the cost some CPU cycles. (DEFAULT: false)
 - `taskmanager.runtime.max-fan`: The maximal fan-in for external merge joins and fan-out for spilling hash tables. Limits the number of file handles per operator, but may cause intermediate merging/partitioning, if set too small (DEFAULT: 128).
 - `taskmanager.runtime.sort-spilling-threshold`: A sort operation starts spilling when this fraction of its memory budget is full (DEFAULT: 0.8).
 
@@ -237,7 +237,7 @@ definition. This scheme is used **ONLY** if no other scheme is specified (explic
 
 - `yarn.heartbeat-delay` (Default: 5 seconds). Time between heartbeats with the ResourceManager.
 
-- `yarn.properties-file.location` (Default: temp directory). When a Flink job is submitted to YARN, the JobManager's host and the number of available processing slots is written into a properties file, so that the Flink clientis able to pick those details up. This configuration parameter allows changing the default location of that file (for example for environments sharing a Flink installation between users)
+- `yarn.properties-file.location` (Default: temp directory). When a Flink job is submitted to YARN, the JobManager's host and the number of available processing slots is written into a properties file, so that the Flink client is able to pick those details up. This configuration parameter allows changing the default location of that file (for example for environments sharing a Flink installation between users)
 
 - `yarn.application-master.env.`*ENV_VAR1=value* Configuration values prefixed with `yarn.application-master.env.` will be passed as environment variables to the ApplicationMaster/JobManager process. For example for passing `LD_LIBRARY_PATH` as an env variable to the ApplicationMaster, set:
 

http://git-wip-us.apache.org/repos/asf/flink/blob/4fbd8eb9/docs/setup/local_setup.md
----------------------------------------------------------------------
diff --git a/docs/setup/local_setup.md b/docs/setup/local_setup.md
index 54864f0..43a9b79 100644
--- a/docs/setup/local_setup.md
+++ b/docs/setup/local_setup.md
@@ -102,7 +102,7 @@ Note: The ``bin`` folder of your Java Runtime Environment must be included in Wi
 $ cd flink
 $ cd bin
 $ start-local.bat
-Starting Flink job manager. Webinterface by default on http://localhost:8081/.
+Starting Flink job manager. Web interface by default on http://localhost:8081/.
 Do not close this batch window. Stop job manager by pressing Ctrl+C.
 ~~~
 

http://git-wip-us.apache.org/repos/asf/flink/blob/4fbd8eb9/docs/setup/yarn_setup.md
----------------------------------------------------------------------
diff --git a/docs/setup/yarn_setup.md b/docs/setup/yarn_setup.md
index f24f451..aa0f7a4 100644
--- a/docs/setup/yarn_setup.md
+++ b/docs/setup/yarn_setup.md
@@ -221,7 +221,7 @@ Note: It is possible to combine `-m yarn-cluster` with a detached YARN submissio
 Flink's YARN client has the following configuration parameters to control how to behave in case of container failures. These parameters can be set either from the `conf/flink-conf.yaml` or when starting the YARN session, using `-D` parameters.
 
 - `yarn.reallocate-failed`: This parameter controls whether Flink should reallocate failed TaskManager containers. Default: true
-- `yarn.maximum-failed-containers`: The maximum number of failed containers the ApplicationMaster accepts until it fails the YARN session. Default: The number of initally requested TaskManagers (`-n`).
+- `yarn.maximum-failed-containers`: The maximum number of failed containers the ApplicationMaster accepts until it fails the YARN session. Default: The number of initially requested TaskManagers (`-n`).
 - `yarn.application-attempts`: The number of ApplicationMaster (+ its TaskManager containers) attempts. If this value is set to 1 (default), the entire YARN session will fail when the Application master fails. Higher values specify the number of restarts of the ApplicationMaster by YARN.
 
 ## Debugging a failed YARN session
@@ -240,11 +240,11 @@ yarn logs -applicationId <application ID>
 
 Note that it takes a few seconds after the session has finished until the logs show up.
 
-### YARN Client console & Webinterfaces
+### YARN Client console & Web interfaces
 
 The Flink YARN client also prints error messages in the terminal if errors occur during runtime (for example if a TaskManager stops working after some time).
 
-In addition to that, there is the YARN Resource Manager webinterface (by default on port 8088). The port of the Resource Manager web interface is determined by the `yarn.resourcemanager.webapp.address` configuration value.
+In addition to that, there is the YARN Resource Manager web interface (by default on port 8088). The port of the Resource Manager web interface is determined by the `yarn.resourcemanager.webapp.address` configuration value.
 
 It allows to access log files for running YARN applications and shows diagnostics for failed apps.
 
@@ -261,7 +261,7 @@ ranges configured, users can also submit jobs to Flink crossing the firewall.
 
 Currently, two services are needed to submit a job:
 
- * The JobManager (ApplicatonMaster in YARN)
+ * The JobManager (ApplicationMaster in YARN)
  * The BlobServer running within the JobManager.
 
 When submitting a job to Flink, the BlobServer will distribute the jars with the user code to all worker nodes (TaskManagers).


[3/5] flink git commit: [FLINK-3754] [tableAPI] Add validation phase to Table API before construction of RelNodes.

Posted by fh...@apache.org.
[FLINK-3754] [tableAPI] Add validation phase to Table API before construction of RelNodes.

This closes #1958


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

Branch: refs/heads/master
Commit: f0d543f8cf95efecef88c77155456104a6d742b9
Parents: f2e6057
Author: Yijie Shen <he...@gmail.com>
Authored: Wed Apr 13 16:46:58 2016 +0800
Committer: Fabian Hueske <fh...@apache.org>
Committed: Wed May 18 00:12:22 2016 +0200

----------------------------------------------------------------------
 .../flink/api/scala/table/expressionDsl.scala   |  74 ++--
 .../flink/api/table/BatchTableEnvironment.scala |  34 +-
 .../api/table/ExpressionParserException.scala   |  23 --
 .../flink/api/table/FlinkPlannerImpl.scala      |   4 +-
 .../api/table/StreamTableEnvironment.scala      |  17 +-
 .../flink/api/table/TableEnvironment.scala      |  43 ++-
 .../apache/flink/api/table/TableException.scala |  23 --
 .../org/apache/flink/api/table/exceptions.scala |  39 +++
 .../api/table/expressions/Expression.scala      |  64 ++--
 .../table/expressions/ExpressionParser.scala    |  42 +--
 .../api/table/expressions/InputTypeSpec.scala   |  55 +++
 .../flink/api/table/expressions/TreeNode.scala  | 120 -------
 .../api/table/expressions/aggregations.scala    |  33 +-
 .../api/table/expressions/arithmetic.scala      |  44 ++-
 .../flink/api/table/expressions/call.scala      |  75 +---
 .../flink/api/table/expressions/cast.scala      |  21 +-
 .../api/table/expressions/comparison.scala      |  41 ++-
 .../api/table/expressions/fieldExpression.scala |  73 +++-
 .../flink/api/table/expressions/literals.scala  |  14 +-
 .../flink/api/table/expressions/logic.scala     |  50 ++-
 .../api/table/expressions/mathExpressions.scala | 115 +++++++
 .../flink/api/table/expressions/ordering.scala  |  21 +-
 .../table/expressions/stringExpressions.scala   | 220 ++++++++++++
 .../api/table/plan/RexNodeTranslator.scala      |  50 ++-
 .../api/table/plan/logical/LogicalNode.scala    | 162 +++++++++
 .../api/table/plan/logical/operators.scala      | 339 +++++++++++++++++++
 .../org/apache/flink/api/table/table.scala      | 296 +++-------------
 .../apache/flink/api/table/trees/TreeNode.scala | 114 +++++++
 .../api/table/typeutils/TypeCheckUtils.scala    |  40 +++
 .../api/table/typeutils/TypeCoercion.scala      |  92 +++++
 .../table/validate/ExprValidationResult.scala   |  41 +++
 .../api/table/validate/FunctionCatalog.scala    | 124 +++++++
 .../api/java/batch/TableEnvironmentITCase.java  |  11 +-
 .../java/batch/table/AggregationsITCase.java    |   8 +-
 .../api/java/batch/table/ExpressionsITCase.java |   4 +-
 .../api/java/batch/table/FilterITCase.java      |   3 +-
 .../batch/table/GroupedAggregationsITCase.java  |   5 +-
 .../flink/api/java/batch/table/JoinITCase.java  |  10 +-
 .../api/java/batch/table/SelectITCase.java      |   5 +-
 .../batch/table/StringExpressionsITCase.java    |  32 +-
 .../flink/api/java/batch/table/UnionITCase.java |  10 +-
 .../scala/batch/TableEnvironmentITCase.scala    |   6 +-
 .../scala/batch/table/AggregationsITCase.scala  |   9 +-
 .../scala/batch/table/ExpressionsITCase.scala   |   4 +-
 .../api/scala/batch/table/FilterITCase.scala    |   4 +-
 .../batch/table/GroupedAggregationsITCase.scala |   6 +-
 .../api/scala/batch/table/JoinITCase.scala      |  10 +-
 .../api/scala/batch/table/SelectITCase.scala    |   8 +-
 .../batch/table/StringExpressionsITCase.scala   |   7 +-
 .../api/scala/batch/table/UnionITCase.scala     |   8 +-
 .../expression/utils/ExpressionEvaluator.scala  |  10 +-
 .../api/scala/stream/table/UnionITCase.scala    |  10 +-
 .../scala/stream/table/UnsupportedOpsTest.scala |   7 +
 53 files changed, 1915 insertions(+), 765 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/scala/table/expressionDsl.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/scala/table/expressionDsl.scala b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/scala/table/expressionDsl.scala
index 0f0b93c..11fb64a 100644
--- a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/scala/table/expressionDsl.scala
+++ b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/scala/table/expressionDsl.scala
@@ -17,11 +17,11 @@
  */
 package org.apache.flink.api.scala.table
 
+import scala.language.implicitConversions
+
 import org.apache.flink.api.common.typeinfo.TypeInformation
 import org.apache.flink.api.table.expressions._
 
-import scala.language.implicitConversions
-
 /**
  * These are all the operations that can be used to construct an [[Expression]] AST for expression
  * operations.
@@ -63,7 +63,7 @@ trait ImplicitExpressionOperations {
 
   def cast(toType: TypeInformation[_]) = Cast(expr, toType)
 
-  def as(name: Symbol) = Naming(expr, name.name)
+  def as(name: Symbol) = Alias(expr, name.name)
 
   def asc = Asc(expr)
   def desc = Desc(expr)
@@ -91,37 +91,37 @@ trait ImplicitExpressionOperations {
   /**
     * Calculates the Euler's number raised to the given power.
     */
-  def exp() = Call(BuiltInFunctionNames.EXP, expr)
+  def exp() = Exp(expr)
 
   /**
     * Calculates the base 10 logarithm of given value.
     */
-  def log10() = Call(BuiltInFunctionNames.LOG10, expr)
+  def log10() = Log10(expr)
 
   /**
     * Calculates the natural logarithm of given value.
     */
-  def ln() = Call(BuiltInFunctionNames.LN, expr)
+  def ln() = Ln(expr)
 
   /**
     * Calculates the given number raised to the power of the other value.
     */
-  def power(other: Expression) = Call(BuiltInFunctionNames.POWER, expr, other)
+  def power(other: Expression) = Power(expr, other)
 
   /**
     * Calculates the absolute value of given one.
     */
-  def abs() = Call(BuiltInFunctionNames.ABS, expr)
+  def abs() = Abs(expr)
 
   /**
     * Calculates the largest integer less than or equal to a given number.
     */
-  def floor() = Call(BuiltInFunctionNames.FLOOR, expr)
+  def floor() = Floor(expr)
 
   /**
     * Calculates the smallest integer greater than or equal to a given number.
     */
-  def ceil() = Call(BuiltInFunctionNames.CEIL, expr)
+  def ceil() = Ceil(expr)
 
   /**
     * Creates a substring of the given string between the given indices.
@@ -130,9 +130,8 @@ trait ImplicitExpressionOperations {
     * @param endIndex last character of the substring (starting at 1, inclusive)
     * @return substring
     */
-  def substring(beginIndex: Expression, endIndex: Expression) = {
-    Call(BuiltInFunctionNames.SUBSTRING, expr, beginIndex, endIndex)
-  }
+  def substring(beginIndex: Expression, endIndex: Expression) =
+    SubString(expr, beginIndex, endIndex)
 
   /**
     * Creates a substring of the given string beginning at the given index to the end.
@@ -140,9 +139,8 @@ trait ImplicitExpressionOperations {
     * @param beginIndex first character of the substring (starting at 1, inclusive)
     * @return substring
     */
-  def substring(beginIndex: Expression) = {
-    Call(BuiltInFunctionNames.SUBSTRING, expr, beginIndex)
-  }
+  def substring(beginIndex: Expression) =
+    new SubString(expr, beginIndex)
 
   /**
     * Removes leading and/or trailing characters from the given string.
@@ -155,25 +153,13 @@ trait ImplicitExpressionOperations {
   def trim(
       removeLeading: Boolean = true,
       removeTrailing: Boolean = true,
-      character: Expression = BuiltInFunctionConstants.TRIM_DEFAULT_CHAR) = {
+      character: Expression = TrimConstants.TRIM_DEFAULT_CHAR) = {
     if (removeLeading && removeTrailing) {
-      Call(
-        BuiltInFunctionNames.TRIM,
-        BuiltInFunctionConstants.TRIM_BOTH,
-        character,
-        expr)
+      Trim(TrimConstants.TRIM_BOTH, character, expr)
     } else if (removeLeading) {
-      Call(
-        BuiltInFunctionNames.TRIM,
-        BuiltInFunctionConstants.TRIM_LEADING,
-        character,
-        expr)
+      Trim(TrimConstants.TRIM_LEADING, character, expr)
     } else if (removeTrailing) {
-      Call(
-        BuiltInFunctionNames.TRIM,
-        BuiltInFunctionConstants.TRIM_TRAILING,
-        character,
-        expr)
+      Trim(TrimConstants.TRIM_TRAILING, character, expr)
     } else {
       expr
     }
@@ -182,51 +168,39 @@ trait ImplicitExpressionOperations {
   /**
     * Returns the length of a String.
     */
-  def charLength() = {
-    Call(BuiltInFunctionNames.CHAR_LENGTH, expr)
-  }
+  def charLength() = CharLength(expr)
 
   /**
     * Returns all of the characters in a String in upper case using the rules of
     * the default locale.
     */
-  def upperCase() = {
-    Call(BuiltInFunctionNames.UPPER_CASE, expr)
-  }
+  def upperCase() = Upper(expr)
 
   /**
     * Returns all of the characters in a String in lower case using the rules of
     * the default locale.
     */
-  def lowerCase() = {
-    Call(BuiltInFunctionNames.LOWER_CASE, expr)
-  }
+  def lowerCase() = Lower(expr)
 
   /**
     * Converts the initial letter of each word in a String to uppercase.
     * Assumes a String containing only [A-Za-z0-9], everything else is treated as whitespace.
     */
-  def initCap() = {
-    Call(BuiltInFunctionNames.INIT_CAP, expr)
-  }
+  def initCap() = InitCap(expr)
 
   /**
     * Returns true, if a String matches the specified LIKE pattern.
     *
     * e.g. "Jo_n%" matches all Strings that start with "Jo(arbitrary letter)n"
     */
-  def like(pattern: Expression) = {
-    Call(BuiltInFunctionNames.LIKE, expr, pattern)
-  }
+  def like(pattern: Expression) = Like(expr, pattern)
 
   /**
     * Returns true, if a String matches the specified SQL regex pattern.
     *
     * e.g. "A+" matches all Strings that consist of at least one A
     */
-  def similar(pattern: Expression) = {
-    Call(BuiltInFunctionNames.SIMILAR, expr, pattern)
-  }
+  def similar(pattern: Expression) = Similar(expr, pattern)
 }
 
 /**

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/BatchTableEnvironment.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/BatchTableEnvironment.scala b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/BatchTableEnvironment.scala
index 39e3105..207500a 100644
--- a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/BatchTableEnvironment.scala
+++ b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/BatchTableEnvironment.scala
@@ -24,6 +24,7 @@ import org.apache.calcite.plan.RelOptPlanner.CannotPlanException
 import org.apache.calcite.plan.RelOptUtil
 import org.apache.calcite.sql2rel.RelDecorrelator
 import org.apache.calcite.tools.Programs
+
 import org.apache.flink.api.common.typeinfo.TypeInformation
 import org.apache.flink.api.java.{ExecutionEnvironment, DataSet}
 import org.apache.flink.api.java.io.DiscardingOutputFormat
@@ -31,7 +32,8 @@ import org.apache.flink.api.java.typeutils.TypeExtractor
 import org.apache.flink.api.table.explain.PlanJsonParser
 import org.apache.flink.api.table.expressions.Expression
 import org.apache.flink.api.table.plan.PlanGenException
-import org.apache.flink.api.table.plan.nodes.dataset.{DataSetRel, DataSetConvention}
+import org.apache.flink.api.table.plan.logical.{CatalogNode, LogicalRelNode}
+import org.apache.flink.api.table.plan.nodes.dataset.{DataSetConvention, DataSetRel}
 import org.apache.flink.api.table.plan.rules.FlinkRuleSets
 import org.apache.flink.api.table.plan.schema.{TableSourceTable, DataSetTable}
 import org.apache.flink.api.table.sinks.{BatchTableSink, TableSink}
@@ -72,7 +74,7 @@ abstract class BatchTableEnvironment(
     val m = internalNamePattern.findFirstIn(name)
     m match {
       case Some(_) =>
-        throw new TableException(s"Illegal Table name. " +
+        throw new ValidationException(s"Illegal Table name. " +
           s"Please choose a name that does not contain the pattern $internalNamePattern")
       case None =>
     }
@@ -87,18 +89,15 @@ abstract class BatchTableEnvironment(
     * The table to scan must be registered in the [[TableEnvironment]]'s catalog.
     *
     * @param tableName The name of the table to scan.
-    * @throws TableException if no table is registered under the given name.
+    * @throws ValidationException if no table is registered under the given name.
     * @return The scanned table.
     */
-  @throws[TableException]
+  @throws[ValidationException]
   def scan(tableName: String): Table = {
-
     if (isRegistered(tableName)) {
-      relBuilder.scan(tableName)
-      new Table(relBuilder.build(), this)
-    }
-    else {
-      throw new TableException(s"Table \'$tableName\' was not found in the registry.")
+      new Table(this, CatalogNode(tableName, getRowType(tableName)))
+    } else {
+      throw new ValidationException(s"Table \'$tableName\' was not found in the registry.")
     }
   }
 
@@ -133,7 +132,7 @@ abstract class BatchTableEnvironment(
     // transform to a relational tree
     val relational = planner.rel(validated)
 
-    new Table(relational.rel, this)
+    new Table(this, LogicalRelNode(relational.rel))
   }
 
   /**
@@ -169,7 +168,7 @@ abstract class BatchTableEnvironment(
     */
   private[flink] def explain(table: Table, extended: Boolean): String = {
 
-    val ast = RelOptUtil.toString(table.relNode)
+    val ast = RelOptUtil.toString(table.getRelNode)
     val dataSet = translate[Row](table)(TypeExtractor.createTypeInfo(classOf[Row]))
     dataSet.output(new DiscardingOutputFormat[Row])
     val env = dataSet.getExecutionEnvironment
@@ -219,15 +218,10 @@ abstract class BatchTableEnvironment(
     * @tparam T The type of the [[DataSet]].
     */
   protected def registerDataSetInternal[T](
-    name: String, dataSet: DataSet[T],
-    fields: Array[Expression]): Unit = {
+      name: String, dataSet: DataSet[T], fields: Array[Expression]): Unit = {
 
-    val (fieldNames, fieldIndexes) = getFieldInfo[T](dataSet.getType, fields.toArray)
-    val dataSetTable = new DataSetTable[T](
-      dataSet,
-      fieldIndexes.toArray,
-      fieldNames.toArray
-    )
+    val (fieldNames, fieldIndexes) = getFieldInfo[T](dataSet.getType, fields)
+    val dataSetTable = new DataSetTable[T](dataSet, fieldIndexes, fieldNames)
     registerTableInternal(name, dataSetTable)
   }
 

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/ExpressionParserException.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/ExpressionParserException.scala b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/ExpressionParserException.scala
deleted file mode 100644
index 2d6fae6..0000000
--- a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/ExpressionParserException.scala
+++ /dev/null
@@ -1,23 +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.flink.api.table
-
-/**
- * Exception for all errors occurring during expression evaluation.
- */
-class ExpressionParserException(msg: String) extends RuntimeException(msg)

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/FlinkPlannerImpl.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/FlinkPlannerImpl.scala b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/FlinkPlannerImpl.scala
index 5a1b3fe..9d0a146 100644
--- a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/FlinkPlannerImpl.scala
+++ b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/FlinkPlannerImpl.scala
@@ -34,7 +34,7 @@ import org.apache.calcite.sql.parser.{SqlParser, SqlParseException}
 import org.apache.calcite.sql.validate.SqlValidator
 import org.apache.calcite.sql.{SqlNode, SqlOperatorTable}
 import org.apache.calcite.sql2rel.{RelDecorrelator, SqlToRelConverter, SqlRexConvertletTable}
-import org.apache.calcite.tools.{RelConversionException, ValidationException, Frameworks, FrameworkConfig}
+import org.apache.calcite.tools.{RelConversionException, ValidationException => CValidationException, Frameworks, FrameworkConfig}
 import org.apache.calcite.util.Util
 import scala.collection.JavaConversions._
 
@@ -96,7 +96,7 @@ class FlinkPlannerImpl(config: FrameworkConfig, var planner: RelOptPlanner) {
     }
     catch {
       case e: RuntimeException => {
-        throw new ValidationException(e)
+        throw new CValidationException(e)
       }
     }
     validatedSqlNode

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/StreamTableEnvironment.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/StreamTableEnvironment.scala b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/StreamTableEnvironment.scala
index be1c005..8ba3000 100644
--- a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/StreamTableEnvironment.scala
+++ b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/StreamTableEnvironment.scala
@@ -24,10 +24,12 @@ import org.apache.calcite.plan.RelOptPlanner.CannotPlanException
 import org.apache.calcite.plan.RelOptUtil
 import org.apache.calcite.sql2rel.RelDecorrelator
 import org.apache.calcite.tools.Programs
+
 import org.apache.flink.api.common.typeinfo.TypeInformation
 import org.apache.flink.api.table.expressions.Expression
 import org.apache.flink.api.table.plan.PlanGenException
-import org.apache.flink.api.table.plan.nodes.datastream.{DataStreamRel, DataStreamConvention}
+import org.apache.flink.api.table.plan.logical.{CatalogNode, LogicalRelNode}
+import org.apache.flink.api.table.plan.nodes.datastream.{DataStreamConvention, DataStreamRel}
 import org.apache.flink.api.table.plan.rules.FlinkRuleSets
 import org.apache.flink.api.table.sinks.{StreamTableSink, TableSink}
 import org.apache.flink.api.table.plan.schema.
@@ -86,18 +88,17 @@ abstract class StreamTableEnvironment(
     * The table to ingest must be registered in the [[TableEnvironment]]'s catalog.
     *
     * @param tableName The name of the table to ingest.
-    * @throws TableException if no table is registered under the given name.
+    * @throws ValidationException if no table is registered under the given name.
     * @return The ingested table.
     */
-  @throws[TableException]
+  @throws[ValidationException]
   def ingest(tableName: String): Table = {
 
     if (isRegistered(tableName)) {
-      relBuilder.scan(tableName)
-      new Table(relBuilder.build(), this)
+      new Table(this, CatalogNode(tableName, getRowType(tableName)))
     }
     else {
-      throw new TableException(s"Table \'$tableName\' was not found in the registry.")
+      throw new ValidationException(s"Table \'$tableName\' was not found in the registry.")
     }
   }
 
@@ -132,7 +133,7 @@ abstract class StreamTableEnvironment(
     // transform to a relational tree
     val relational = planner.rel(validated)
 
-    new Table(relational.rel, this)
+    new Table(this, LogicalRelNode(relational.rel))
   }
 
   /**
@@ -240,7 +241,7 @@ abstract class StreamTableEnvironment(
     */
   protected def translate[A](table: Table)(implicit tpe: TypeInformation[A]): DataStream[A] = {
 
-    val relNode = table.relNode
+    val relNode = table.getRelNode
 
     // decorrelate
     val decorPlan = RelDecorrelator.decorrelateQuery(relNode)

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/TableEnvironment.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/TableEnvironment.scala b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/TableEnvironment.scala
index 6ccde47..8aa9e10 100644
--- a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/TableEnvironment.scala
+++ b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/TableEnvironment.scala
@@ -21,11 +21,13 @@ package org.apache.flink.api.table
 import java.util.concurrent.atomic.AtomicInteger
 
 import org.apache.calcite.config.Lex
-import org.apache.calcite.plan.RelOptPlanner
+import org.apache.calcite.plan.{RelOptCluster, RelOptPlanner}
+import org.apache.calcite.rel.`type`.{RelDataType, RelDataTypeFactory}
 import org.apache.calcite.schema.SchemaPlus
 import org.apache.calcite.schema.impl.AbstractTable
 import org.apache.calcite.sql.parser.SqlParser
-import org.apache.calcite.tools.{Frameworks, FrameworkConfig, RelBuilder}
+import org.apache.calcite.tools.{FrameworkConfig, Frameworks, RelBuilder}
+
 import org.apache.flink.api.common.typeinfo.{AtomicType, TypeInformation}
 import org.apache.flink.api.java.{ExecutionEnvironment => JavaBatchExecEnv}
 import org.apache.flink.api.java.table.{BatchTableEnvironment => JavaBatchTableEnv}
@@ -35,11 +37,11 @@ import org.apache.flink.api.scala.{ExecutionEnvironment => ScalaBatchExecEnv}
 import org.apache.flink.api.scala.table.{BatchTableEnvironment => ScalaBatchTableEnv}
 import org.apache.flink.api.scala.table.{StreamTableEnvironment => ScalaStreamTableEnv}
 import org.apache.flink.api.scala.typeutils.CaseClassTypeInfo
-import org.apache.flink.api.table.expressions.{Naming, UnresolvedFieldReference, Expression}
+import org.apache.flink.api.table.expressions.{Alias, Expression, UnresolvedFieldReference}
 import org.apache.flink.api.table.plan.cost.DataSetCostFactory
-import org.apache.flink.api.table.plan.schema.{TransStreamTable, RelTable}
 import org.apache.flink.api.table.sinks.TableSink
-import org.apache.flink.streaming.api.datastream.DataStream
+import org.apache.flink.api.table.plan.schema.{RelTable, TransStreamTable}
+import org.apache.flink.api.table.validate.FunctionCatalog
 import org.apache.flink.streaming.api.environment.{StreamExecutionEnvironment => JavaStreamExecEnv}
 import org.apache.flink.streaming.api.scala.{StreamExecutionEnvironment => ScalaStreamExecEnv}
 
@@ -72,10 +74,16 @@ abstract class TableEnvironment(val config: TableConfig) {
   // the builder for Calcite RelNodes, Calcite's representation of a relational expression tree.
   protected val relBuilder: RelBuilder = RelBuilder.create(frameworkConfig)
 
-  // the planner instance used to optimize queries of this TableEnvironment
-  private val planner: RelOptPlanner = relBuilder
+  private val cluster: RelOptCluster = relBuilder
     .values(Array("dummy"), new Integer(1))
-    .build().getCluster.getPlanner
+    .build().getCluster
+
+  // the planner instance used to optimize queries of this TableEnvironment
+  private val planner: RelOptPlanner = cluster.getPlanner
+
+  private val typeFactory: RelDataTypeFactory = cluster.getTypeFactory
+
+  private val functionCatalog: FunctionCatalog = FunctionCatalog.withBuildIns
 
   // a counter for unique attribute names
   private val attrNameCntr: AtomicInteger = new AtomicInteger(0)
@@ -94,7 +102,7 @@ abstract class TableEnvironment(val config: TableConfig) {
 
     // check that table belongs to this table environment
     if (table.tableEnv != this) {
-      throw new TableException(
+      throw new ValidationException(
         "Only tables that belong to this TableEnvironment can be registered.")
     }
 
@@ -152,7 +160,7 @@ abstract class TableEnvironment(val config: TableConfig) {
     *
     * @param name The name under which the table is registered.
     * @param table The table to register in the catalog
-    * @throws TableException if another table is registered under the provided name.
+    * @throws ValidationException if another table is registered under the provided name.
     */
   @throws[TableException]
   protected def registerTableInternal(name: String, table: AbstractTable): Unit = {
@@ -182,6 +190,10 @@ abstract class TableEnvironment(val config: TableConfig) {
     tables.getTableNames.contains(name)
   }
 
+  protected def getRowType(name: String): RelDataType = {
+    tables.getTable(name).getRowType(typeFactory)
+  }
+
   /** Returns a unique temporary attribute name. */
   private[flink] def createUniqueAttributeName(): String = {
     "TMP_" + attrNameCntr.getAndIncrement()
@@ -197,6 +209,10 @@ abstract class TableEnvironment(val config: TableConfig) {
     planner
   }
 
+  private[flink] def getFunctionCatalog: FunctionCatalog = {
+    functionCatalog
+  }
+
   /** Returns the Calcite [[FrameworkConfig]] of this TableEnvironment. */
   private[flink] def getFrameworkConfig: FrameworkConfig = {
     frameworkConfig
@@ -253,7 +269,7 @@ abstract class TableEnvironment(val config: TableConfig) {
       case t: TupleTypeInfo[A] =>
         exprs.zipWithIndex.map {
           case (UnresolvedFieldReference(name), idx) => (idx, name)
-          case (Naming(UnresolvedFieldReference(origName), name), _) =>
+          case (Alias(UnresolvedFieldReference(origName), name), _) =>
             val idx = t.getFieldIndex(origName)
             if (idx < 0) {
               throw new IllegalArgumentException(s"$origName is not a field of type $t")
@@ -265,7 +281,7 @@ abstract class TableEnvironment(val config: TableConfig) {
       case c: CaseClassTypeInfo[A] =>
         exprs.zipWithIndex.map {
           case (UnresolvedFieldReference(name), idx) => (idx, name)
-          case (Naming(UnresolvedFieldReference(origName), name), _) =>
+          case (Alias(UnresolvedFieldReference(origName), name), _) =>
             val idx = c.getFieldIndex(origName)
             if (idx < 0) {
               throw new IllegalArgumentException(s"$origName is not a field of type $c")
@@ -276,7 +292,7 @@ abstract class TableEnvironment(val config: TableConfig) {
         }
       case p: PojoTypeInfo[A] =>
         exprs.map {
-          case Naming(UnresolvedFieldReference(origName), name) =>
+          case Alias(UnresolvedFieldReference(origName), name) =>
             val idx = p.getFieldIndex(origName)
             if (idx < 0) {
               throw new IllegalArgumentException(s"$origName is not a field of type $p")
@@ -389,5 +405,4 @@ object TableEnvironment {
 
     new ScalaStreamTableEnv(executionEnvironment, tableConfig)
   }
-
 }

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/TableException.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/TableException.scala b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/TableException.scala
deleted file mode 100644
index 3e298a4..0000000
--- a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/TableException.scala
+++ /dev/null
@@ -1,23 +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.flink.api.table
-
-/**
- * General Exception for all errors during table handling.
- */
-class TableException(msg: String) extends RuntimeException(msg)

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/exceptions.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/exceptions.scala b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/exceptions.scala
new file mode 100644
index 0000000..a3ab6fd
--- /dev/null
+++ b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/exceptions.scala
@@ -0,0 +1,39 @@
+/*
+ * 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.flink.api.table
+
+/**
+  * Exception for all errors occurring during expression parsing.
+  */
+case class ExpressionParserException(msg: String) extends RuntimeException(msg)
+
+/**
+  * General Exception for all errors during table handling.
+  */
+case class TableException(msg: String) extends RuntimeException(msg)
+
+/**
+  * Exception for all errors occurring during validation phase.
+  */
+case class ValidationException(msg: String) extends RuntimeException(msg)
+
+/**
+  * Exception for unwanted method calling on unresolved expression.
+  */
+case class UnresolvedException(msg: String) extends RuntimeException(msg)

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/Expression.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/Expression.scala b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/Expression.scala
index 6960a9f..14e464e 100644
--- a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/Expression.scala
+++ b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/Expression.scala
@@ -17,13 +17,34 @@
  */
 package org.apache.flink.api.table.expressions
 
-import java.util.concurrent.atomic.AtomicInteger
-
 import org.apache.calcite.rex.RexNode
 import org.apache.calcite.tools.RelBuilder
 
-abstract class Expression extends TreeNode[Expression] { self: Product =>
-  def name: String = Expression.freshName("expression")
+import org.apache.flink.api.common.typeinfo.TypeInformation
+import org.apache.flink.api.table.trees.TreeNode
+import org.apache.flink.api.table.validate.{ExprValidationResult, ValidationSuccess}
+
+abstract class Expression extends TreeNode[Expression] {
+  /**
+    * Returns the [[TypeInformation]] for evaluating this expression.
+    * It is sometimes not available until the expression is valid.
+    */
+  def resultType: TypeInformation[_]
+
+  /**
+    * One pass validation of the expression tree in post order.
+    */
+  lazy val valid: Boolean = childrenValid && validateInput().isSuccess
+
+  def childrenValid: Boolean = children.forall(_.valid)
+
+  /**
+    * Check input data types, inputs number or other properties specified by this expression.
+    * Return `ValidationSuccess` if it pass the check,
+    * or `ValidationFailure` with supplement message explaining the error.
+    * Note: we should only call this method until `childrenValid == true`
+    */
+  def validateInput(): ExprValidationResult = ValidationSuccess
 
   /**
     * Convert Expression to its counterpart in Calcite, i.e. RexNode
@@ -32,31 +53,36 @@ abstract class Expression extends TreeNode[Expression] { self: Product =>
     throw new UnsupportedOperationException(
       s"${this.getClass.getName} cannot be transformed to RexNode"
     )
+
+  def checkEquals(other: Expression): Boolean = {
+    if (this.getClass != other.getClass) {
+      false
+    } else {
+      def checkEquality(elements1: Seq[Any], elements2: Seq[Any]): Boolean = {
+        elements1.length == elements2.length && elements1.zip(elements2).forall {
+          case (e1: Expression, e2: Expression) => e1.checkEquals(e2)
+          case (t1: Seq[_], t2: Seq[_]) => checkEquality(t1, t2)
+          case (i1, i2) => i1 == i2
+        }
+      }
+      val elements1 = this.productIterator.toSeq
+      val elements2 = other.productIterator.toSeq
+      checkEquality(elements1, elements2)
+    }
+  }
 }
 
-abstract class BinaryExpression extends Expression { self: Product =>
+abstract class BinaryExpression extends Expression {
   def left: Expression
   def right: Expression
   def children = Seq(left, right)
 }
 
-abstract class UnaryExpression extends Expression { self: Product =>
+abstract class UnaryExpression extends Expression {
   def child: Expression
   def children = Seq(child)
 }
 
-abstract class LeafExpression extends Expression { self: Product =>
+abstract class LeafExpression extends Expression {
   val children = Nil
 }
-
-case class NopExpression() extends LeafExpression {
-  override val name = Expression.freshName("nop")
-}
-
-object Expression {
-  def freshName(prefix: String): String = {
-    s"$prefix-${freshNameCounter.getAndIncrement}"
-  }
-
-  val freshNameCounter = new AtomicInteger
-}

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/ExpressionParser.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/ExpressionParser.scala b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/ExpressionParser.scala
index ffadca5..db3d187 100644
--- a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/ExpressionParser.scala
+++ b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/ExpressionParser.scala
@@ -111,8 +111,8 @@ object ExpressionParser extends JavaTokenParsers with PackratParsers {
       stringLiteralFlink | singleQuoteStringLiteral |
       boolLiteral | nullLiteral
 
-  lazy val fieldReference: PackratParser[Expression] = ident ^^ {
-    case sym => UnresolvedFieldReference(sym)
+  lazy val fieldReference: PackratParser[NamedExpression] = ident ^^ {
+    sym => UnresolvedFieldReference(sym)
   }
 
   lazy val atom: PackratParser[Expression] =
@@ -155,7 +155,7 @@ object ExpressionParser extends JavaTokenParsers with PackratParsers {
 
   lazy val suffixAs: PackratParser[Expression] =
     composite ~ "." ~ AS ~ "(" ~ fieldReference ~ ")" ^^ {
-    case e ~ _ ~ _ ~ _ ~ target ~ _ => Naming(e, target.name)
+    case e ~ _ ~ _ ~ _ ~ target ~ _ => Alias(e, target.name)
   }
 
   lazy val suffixEval: PackratParser[Expression] =
@@ -165,27 +165,23 @@ object ExpressionParser extends JavaTokenParsers with PackratParsers {
 
   lazy val suffixFunctionCall =
     composite ~ "." ~ functionIdent ~ "(" ~ repsep(expression, ",") ~ ")" ^^ {
-    case operand ~ _ ~ name ~ _ ~ args ~ _ => Call(name.toUpperCase, operand :: args : _*)
+    case operand ~ _ ~ name ~ _ ~ args ~ _ => Call(name.toUpperCase, operand :: args)
   }
 
   lazy val suffixTrim = composite ~ ".trim(" ~ ("BOTH" | "LEADING" | "TRAILING") ~ "," ~
       expression ~ ")" ^^ {
     case operand ~ _ ~ trimType ~ _ ~ trimCharacter ~ _ =>
       val flag = trimType match {
-        case "BOTH" => BuiltInFunctionConstants.TRIM_BOTH
-        case "LEADING" => BuiltInFunctionConstants.TRIM_LEADING
-        case "TRAILING" => BuiltInFunctionConstants.TRIM_TRAILING
+        case "BOTH" => TrimConstants.TRIM_BOTH
+        case "LEADING" => TrimConstants.TRIM_LEADING
+        case "TRAILING" => TrimConstants.TRIM_TRAILING
       }
-      Call(BuiltInFunctionNames.TRIM, flag, trimCharacter, operand)
+      Trim(flag, trimCharacter, operand)
   }
 
   lazy val suffixTrimWithoutArgs = composite <~ ".trim" ~ opt("()") ^^ {
     case e =>
-      Call(
-        BuiltInFunctionNames.TRIM,
-        BuiltInFunctionConstants.TRIM_BOTH,
-        BuiltInFunctionConstants.TRIM_DEFAULT_CHAR,
-        e)
+      Trim(TrimConstants.TRIM_BOTH, TrimConstants.TRIM_DEFAULT_CHAR, e)
   }
 
   lazy val suffixed: PackratParser[Expression] =
@@ -223,7 +219,7 @@ object ExpressionParser extends JavaTokenParsers with PackratParsers {
 
   lazy val prefixAs: PackratParser[Expression] =
     AS ~ "(" ~ expression ~ "," ~ fieldReference ~ ")" ^^ {
-    case _ ~ _ ~ e ~ _ ~ target ~ _ => Naming(e, target.name)
+    case _ ~ _ ~ e ~ _ ~ target ~ _ => Alias(e, target.name)
   }
 
   lazy val prefixEval: PackratParser[Expression] = composite ~
@@ -232,27 +228,23 @@ object ExpressionParser extends JavaTokenParsers with PackratParsers {
   }
 
   lazy val prefixFunctionCall = functionIdent ~ "(" ~ repsep(expression, ",") ~ ")" ^^ {
-    case name ~ _ ~ args ~ _ => Call(name.toUpperCase, args: _*)
+    case name ~ _ ~ args ~ _ => Call(name.toUpperCase, args)
   }
 
   lazy val prefixTrim = "trim(" ~ ("BOTH" | "LEADING" | "TRAILING") ~ "," ~ expression ~
       "," ~ expression ~ ")" ^^ {
     case _ ~ trimType ~ _ ~ trimCharacter ~ _ ~ operand ~ _ =>
       val flag = trimType match {
-        case "BOTH" => BuiltInFunctionConstants.TRIM_BOTH
-        case "LEADING" => BuiltInFunctionConstants.TRIM_LEADING
-        case "TRAILING" => BuiltInFunctionConstants.TRIM_TRAILING
+        case "BOTH" => TrimConstants.TRIM_BOTH
+        case "LEADING" => TrimConstants.TRIM_LEADING
+        case "TRAILING" => TrimConstants.TRIM_TRAILING
       }
-      Call(BuiltInFunctionNames.TRIM, flag, trimCharacter, operand)
+      Trim(flag, trimCharacter, operand)
   }
 
   lazy val prefixTrimWithoutArgs = "trim(" ~ expression ~ ")" ^^ {
     case _ ~ operand ~ _ =>
-      Call(
-        BuiltInFunctionNames.TRIM,
-        BuiltInFunctionConstants.TRIM_BOTH,
-        BuiltInFunctionConstants.TRIM_DEFAULT_CHAR,
-        operand)
+      Trim(TrimConstants.TRIM_BOTH, TrimConstants.TRIM_DEFAULT_CHAR, operand)
   }
 
   lazy val prefixed: PackratParser[Expression] =
@@ -322,7 +314,7 @@ object ExpressionParser extends JavaTokenParsers with PackratParsers {
   // alias
 
   lazy val alias: PackratParser[Expression] = logic ~ AS ~ fieldReference ^^ {
-    case e ~ _ ~ name => Naming(e, name.name)
+    case e ~ _ ~ name => Alias(e, name.name)
   } | logic
 
   lazy val expression: PackratParser[Expression] = alias

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/InputTypeSpec.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/InputTypeSpec.scala b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/InputTypeSpec.scala
new file mode 100644
index 0000000..9cb52d5
--- /dev/null
+++ b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/InputTypeSpec.scala
@@ -0,0 +1,55 @@
+/*
+ * 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.flink.api.table.expressions
+
+import scala.collection.mutable
+
+import org.apache.flink.api.common.typeinfo.TypeInformation
+import org.apache.flink.api.table.validate._
+
+/**
+  * Expressions that have specification on its inputs.
+  */
+trait InputTypeSpec extends Expression {
+
+  /**
+    * Input type specification for each child.
+    *
+    * For example, [[Power]] expecting both of the children be of Double Type should use:
+    * {{{
+    *   def expectedTypes: Seq[TypeInformation[_]] = DOUBLE_TYPE_INFO :: DOUBLE_TYPE_INFO :: Nil
+    * }}}
+    */
+  def expectedTypes: Seq[TypeInformation[_]]
+
+  override def validateInput(): ExprValidationResult = {
+    val typeMismatches = mutable.ArrayBuffer.empty[String]
+    children.zip(expectedTypes).zipWithIndex.foreach { case ((e, tpe), i) =>
+      if (e.resultType != tpe) {
+        typeMismatches += s"expecting $tpe on ${i}th input, get ${e.resultType}"
+      }
+    }
+    if (typeMismatches.isEmpty) {
+      ValidationSuccess
+    } else {
+      ValidationFailure(
+        s"$this fails on input type checking: ${typeMismatches.mkString("[", ", ", "]")}")
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/TreeNode.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/TreeNode.scala b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/TreeNode.scala
deleted file mode 100644
index 9d4ca80..0000000
--- a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/TreeNode.scala
+++ /dev/null
@@ -1,120 +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.flink.api.table.expressions
-
-/**
- * Generic base class for trees that can be transformed and traversed.
- */
-abstract class TreeNode[A <: TreeNode[A]] { self: A with Product =>
-
-  /**
-   * List of child nodes that should be considered when doing transformations. Other values
-   * in the Product will not be transformed, only handed through.
-   */
-  def children: Seq[A]
-
-  /**
-   * Tests for equality by first testing for reference equality.
-   */
-  def fastEquals(other: TreeNode[_]): Boolean = this.eq(other) || this == other
-
-  def transformPre(rule: PartialFunction[A, A]): A = {
-    val afterTransform = rule.applyOrElse(this, identity[A])
-
-    if (afterTransform fastEquals this) {
-      this.transformChildrenPre(rule)
-    } else {
-      afterTransform.transformChildrenPre(rule)
-    }
-  }
-
-  def transformChildrenPre(rule: PartialFunction[A, A]): A = {
-    var changed = false
-    val newArgs = productIterator map {
-      case child: A if children.contains(child) =>
-        val newChild = child.transformPre(rule)
-        if (newChild fastEquals child) {
-          child
-        } else {
-          changed = true
-          newChild
-        }
-      case other: AnyRef => other
-      case null => null
-    } toArray
-
-    if (changed) makeCopy(newArgs) else this
-  }
-
-  def transformPost(rule: PartialFunction[A, A]): A = {
-    val afterChildren = transformChildrenPost(rule)
-    if (afterChildren fastEquals this) {
-      rule.applyOrElse(this, identity[A])
-    } else {
-      rule.applyOrElse(afterChildren, identity[A])
-    }
-  }
-
-  def transformChildrenPost(rule: PartialFunction[A, A]): A = {
-    var changed = false
-    val newArgs = productIterator map {
-      case child: A if children.contains(child) =>
-        val newChild = child.transformPost(rule)
-        if (newChild fastEquals child) {
-          child
-        } else {
-          changed = true
-          newChild
-        }
-      case other: AnyRef => other
-      case null => null
-    } toArray
-    // toArray forces evaluation, toSeq does not seem to work here
-
-    if (changed) makeCopy(newArgs) else this
-  }
-
-  def exists(predicate: A => Boolean): Boolean = {
-    var exists = false
-    this.transformPre {
-      case e: A => if (predicate(e)) {
-        exists = true
-      }
-        e
-    }
-    exists
-  }
-
-  /**
-   * Creates a new copy of this expression with new children. This is used during transformation
-   * if children change. This must be overridden by tree nodes that don't have the Constructor
-   * arguments in the same order as the `children`.
-   */
-  def makeCopy(newArgs: Seq[AnyRef]): this.type = {
-    val defaultCtor =
-      this.getClass.getConstructors.find { _.getParameterTypes.size > 0}.head
-    try {
-      defaultCtor.newInstance(newArgs.toArray: _*).asInstanceOf[this.type]
-    } catch {
-      case iae: IllegalArgumentException =>
-        println("IAE " + this)
-        throw new RuntimeException("Should never happen.")
-    }
-  }
-}
-

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/aggregations.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/aggregations.scala b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/aggregations.scala
index 8cd9dc3..24ce85f 100644
--- a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/aggregations.scala
+++ b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/aggregations.scala
@@ -22,7 +22,10 @@ import org.apache.calcite.sql.fun.SqlStdOperatorTable
 import org.apache.calcite.tools.RelBuilder
 import org.apache.calcite.tools.RelBuilder.AggCall
 
-abstract sealed class Aggregation extends UnaryExpression { self: Product =>
+import org.apache.flink.api.common.typeinfo.BasicTypeInfo
+import org.apache.flink.api.table.typeutils.TypeCheckUtils
+
+abstract sealed class Aggregation extends UnaryExpression {
 
   override def toString = s"Aggregate($child)"
 
@@ -36,41 +39,59 @@ abstract sealed class Aggregation extends UnaryExpression { self: Product =>
 }
 
 case class Sum(child: Expression) extends Aggregation {
-  override def toString = s"($child).sum"
+  override def toString = s"sum($child)"
 
   override def toAggCall(name: String)(implicit relBuilder: RelBuilder): AggCall = {
     relBuilder.aggregateCall(SqlStdOperatorTable.SUM, false, null, name, child.toRexNode)
   }
+
+  override def resultType = child.resultType
+
+  override def validateInput = TypeCheckUtils.assertNumericExpr(child.resultType, "sum")
 }
 
 case class Min(child: Expression) extends Aggregation {
-  override def toString = s"($child).min"
+  override def toString = s"min($child)"
 
   override def toAggCall(name: String)(implicit relBuilder: RelBuilder): AggCall = {
     relBuilder.aggregateCall(SqlStdOperatorTable.MIN, false, null, name, child.toRexNode)
   }
+
+  override def resultType = child.resultType
+
+  override def validateInput = TypeCheckUtils.assertOrderableExpr(child.resultType, "min")
 }
 
 case class Max(child: Expression) extends Aggregation {
-  override def toString = s"($child).max"
+  override def toString = s"max($child)"
 
   override def toAggCall(name: String)(implicit relBuilder: RelBuilder): AggCall = {
     relBuilder.aggregateCall(SqlStdOperatorTable.MAX, false, null, name, child.toRexNode)
   }
+
+  override def resultType = child.resultType
+
+  override def validateInput = TypeCheckUtils.assertOrderableExpr(child.resultType, "max")
 }
 
 case class Count(child: Expression) extends Aggregation {
-  override def toString = s"($child).count"
+  override def toString = s"count($child)"
 
   override def toAggCall(name: String)(implicit relBuilder: RelBuilder): AggCall = {
     relBuilder.aggregateCall(SqlStdOperatorTable.COUNT, false, null, name, child.toRexNode)
   }
+
+  override def resultType = BasicTypeInfo.LONG_TYPE_INFO
 }
 
 case class Avg(child: Expression) extends Aggregation {
-  override def toString = s"($child).avg"
+  override def toString = s"avg($child)"
 
   override def toAggCall(name: String)(implicit relBuilder: RelBuilder): AggCall = {
     relBuilder.aggregateCall(SqlStdOperatorTable.AVG, false, null, name, child.toRexNode)
   }
+
+  override def resultType = child.resultType
+
+  override def validateInput = TypeCheckUtils.assertNumericExpr(child.resultType, "avg")
 }

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/arithmetic.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/arithmetic.scala b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/arithmetic.scala
index ca67697..0ce4685 100644
--- a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/arithmetic.scala
+++ b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/arithmetic.scala
@@ -25,15 +25,34 @@ import org.apache.calcite.sql.SqlOperator
 import org.apache.calcite.sql.fun.SqlStdOperatorTable
 import org.apache.calcite.tools.RelBuilder
 
-import org.apache.flink.api.common.typeinfo.BasicTypeInfo
-import org.apache.flink.api.table.typeutils.TypeConverter
+import org.apache.flink.api.common.typeinfo.{BasicTypeInfo, NumericTypeInfo, TypeInformation}
+import org.apache.flink.api.table.typeutils.{TypeCheckUtils, TypeCoercion, TypeConverter}
+import org.apache.flink.api.table.validate._
 
-abstract class BinaryArithmetic extends BinaryExpression { self: Product =>
+abstract class BinaryArithmetic extends BinaryExpression {
   def sqlOperator: SqlOperator
 
   override def toRexNode(implicit relBuilder: RelBuilder): RexNode = {
     relBuilder.call(sqlOperator, children.map(_.toRexNode))
   }
+
+  override def resultType: TypeInformation[_] =
+    TypeCoercion.widerTypeOf(left.resultType, right.resultType) match {
+      case Some(t) => t
+      case None =>
+        throw new RuntimeException("This should never happen.")
+    }
+
+  // TODO: tighten this rule once we implemented type coercion rules during validation
+  override def validateInput(): ExprValidationResult = {
+    if (!left.resultType.isInstanceOf[NumericTypeInfo[_]] ||
+      !right.resultType.isInstanceOf[NumericTypeInfo[_]]) {
+      ValidationFailure(s"$this requires both operands Numeric, get" +
+        s"${left.resultType} and ${right.resultType}")
+    } else {
+      ValidationSuccess
+    }
+  }
 }
 
 case class Plus(left: Expression, right: Expression) extends BinaryArithmetic {
@@ -56,6 +75,20 @@ case class Plus(left: Expression, right: Expression) extends BinaryArithmetic {
       relBuilder.call(SqlStdOperatorTable.PLUS, l, r)
     }
   }
+
+  // TODO: tighten this rule once we implemented type coercion rules during validation
+  override def validateInput(): ExprValidationResult = {
+    if (left.resultType == BasicTypeInfo.STRING_TYPE_INFO ||
+        right.resultType == BasicTypeInfo.STRING_TYPE_INFO) {
+      ValidationSuccess
+    } else if (!left.resultType.isInstanceOf[NumericTypeInfo[_]] ||
+        !right.resultType.isInstanceOf[NumericTypeInfo[_]]) {
+      ValidationFailure(s"$this requires Numeric or String input," +
+        s" get ${left.resultType} and ${right.resultType}")
+    } else {
+      ValidationSuccess
+    }
+  }
 }
 
 case class UnaryMinus(child: Expression) extends UnaryExpression {
@@ -64,6 +97,11 @@ case class UnaryMinus(child: Expression) extends UnaryExpression {
   override def toRexNode(implicit relBuilder: RelBuilder): RexNode = {
     relBuilder.call(SqlStdOperatorTable.UNARY_MINUS, child.toRexNode)
   }
+
+  override def resultType = child.resultType
+
+  override def validateInput(): ExprValidationResult =
+    TypeCheckUtils.assertNumericExpr(child.resultType, "unary minus")
 }
 
 case class Minus(left: Expression, right: Expression) extends BinaryArithmetic {

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/call.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/call.scala b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/call.scala
index e36a784..bf2e6ba 100644
--- a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/call.scala
+++ b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/call.scala
@@ -18,85 +18,28 @@
 package org.apache.flink.api.table.expressions
 
 import org.apache.calcite.rex.RexNode
-import org.apache.calcite.sql.SqlOperator
-import org.apache.calcite.sql.fun.SqlStdOperatorTable
 import org.apache.calcite.tools.RelBuilder
 
+import org.apache.flink.api.table.UnresolvedException
+import org.apache.flink.api.table.validate.{ExprValidationResult, ValidationFailure}
+
 /**
   * General expression for unresolved function calls. The function can be a built-in
   * scalar function or a user-defined scalar function.
   */
-case class Call(functionName: String, args: Expression*) extends Expression {
+case class Call(functionName: String, args: Seq[Expression]) extends Expression {
 
   override def children: Seq[Expression] = args
 
   override def toRexNode(implicit relBuilder: RelBuilder): RexNode = {
-    relBuilder.call(
-      BuiltInFunctionNames.toSqlOperator(functionName),
-      args.map(_.toRexNode): _*)
+    throw new UnresolvedException(s"trying to convert UnresolvedFunction $functionName to RexNode")
   }
 
   override def toString = s"\\$functionName(${args.mkString(", ")})"
 
-  override def makeCopy(newArgs: Seq[AnyRef]): this.type = {
-    val copy = Call(
-      newArgs.head.asInstanceOf[String],
-      newArgs.drop(1).asInstanceOf[Seq[Expression]]: _*)
-
-    copy.asInstanceOf[this.type]
-  }
-}
-
-/**
-  * Enumeration of common function names.
-  */
-object BuiltInFunctionNames {
-  val SUBSTRING = "SUBSTRING"
-  val TRIM = "TRIM"
-  val CHAR_LENGTH = "CHARLENGTH"
-  val UPPER_CASE = "UPPERCASE"
-  val LOWER_CASE = "LOWERCASE"
-  val INIT_CAP = "INITCAP"
-  val LIKE = "LIKE"
-  val SIMILAR = "SIMILAR"
-  val MOD = "MOD"
-  val EXP = "EXP"
-  val LOG10 = "LOG10"
-  val POWER = "POWER"
-  val LN = "LN"
-  val ABS = "ABS"
-  val FLOOR = "FLOOR"
-  val CEIL = "CEIL"
-
-  def toSqlOperator(name: String): SqlOperator = {
-    name match {
-      case BuiltInFunctionNames.SUBSTRING => SqlStdOperatorTable.SUBSTRING
-      case BuiltInFunctionNames.TRIM => SqlStdOperatorTable.TRIM
-      case BuiltInFunctionNames.CHAR_LENGTH => SqlStdOperatorTable.CHAR_LENGTH
-      case BuiltInFunctionNames.UPPER_CASE => SqlStdOperatorTable.UPPER
-      case BuiltInFunctionNames.LOWER_CASE => SqlStdOperatorTable.LOWER
-      case BuiltInFunctionNames.INIT_CAP => SqlStdOperatorTable.INITCAP
-      case BuiltInFunctionNames.LIKE => SqlStdOperatorTable.LIKE
-      case BuiltInFunctionNames.SIMILAR => SqlStdOperatorTable.SIMILAR_TO
-      case BuiltInFunctionNames.EXP => SqlStdOperatorTable.EXP
-      case BuiltInFunctionNames.LOG10 => SqlStdOperatorTable.LOG10
-      case BuiltInFunctionNames.POWER => SqlStdOperatorTable.POWER
-      case BuiltInFunctionNames.LN => SqlStdOperatorTable.LN
-      case BuiltInFunctionNames.ABS => SqlStdOperatorTable.ABS
-      case BuiltInFunctionNames.MOD => SqlStdOperatorTable.MOD
-      case BuiltInFunctionNames.FLOOR => SqlStdOperatorTable.FLOOR
-      case BuiltInFunctionNames.CEIL => SqlStdOperatorTable.CEIL
-      case _ => ???
-    }
-  }
-}
+  override def resultType =
+    throw new UnresolvedException(s"calling resultType on UnresolvedFunction $functionName")
 
-/**
-  * Enumeration of common function flags.
-  */
-object BuiltInFunctionConstants {
-  val TRIM_BOTH = Literal(0)
-  val TRIM_LEADING = Literal(1)
-  val TRIM_TRAILING = Literal(2)
-  val TRIM_DEFAULT_CHAR = Literal(" ")
+  override def validateInput(): ExprValidationResult =
+    ValidationFailure(s"Unresolved function call: $functionName")
 }

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/cast.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/cast.scala b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/cast.scala
index fdad1f6..3b8b0e7 100644
--- a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/cast.scala
+++ b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/cast.scala
@@ -21,18 +21,27 @@ import org.apache.calcite.rex.RexNode
 import org.apache.calcite.tools.RelBuilder
 
 import org.apache.flink.api.common.typeinfo.TypeInformation
-import org.apache.flink.api.table.typeutils.TypeConverter
+import org.apache.flink.api.table.typeutils.{TypeCoercion, TypeConverter}
+import org.apache.flink.api.table.validate._
 
-case class Cast(child: Expression, tpe: TypeInformation[_]) extends UnaryExpression {
+case class Cast(child: Expression, resultType: TypeInformation[_]) extends UnaryExpression {
 
-  override def toString = s"$child.cast($tpe)"
+  override def toString = s"$child.cast($resultType)"
 
   override def toRexNode(implicit relBuilder: RelBuilder): RexNode = {
-    relBuilder.cast(child.toRexNode, TypeConverter.typeInfoToSqlType(tpe))
+    relBuilder.cast(child.toRexNode, TypeConverter.typeInfoToSqlType(resultType))
   }
 
-  override def makeCopy(anyRefs: Seq[AnyRef]): this.type = {
+  override def makeCopy(anyRefs: Array[AnyRef]): this.type = {
     val child: Expression = anyRefs.head.asInstanceOf[Expression]
-    copy(child, tpe).asInstanceOf[this.type]
+    copy(child, resultType).asInstanceOf[this.type]
+  }
+
+  override def validateInput(): ExprValidationResult = {
+    if (TypeCoercion.canCast(child.resultType, resultType)) {
+      ValidationSuccess
+    } else {
+      ValidationFailure(s"Unsupported cast from ${child.resultType} to $resultType")
+    }
   }
 }

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/comparison.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/comparison.scala b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/comparison.scala
index 124393c..63caeaa 100644
--- a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/comparison.scala
+++ b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/comparison.scala
@@ -24,24 +24,59 @@ import org.apache.calcite.sql.SqlOperator
 import org.apache.calcite.sql.fun.SqlStdOperatorTable
 import org.apache.calcite.tools.RelBuilder
 
-abstract class BinaryComparison extends BinaryExpression { self: Product =>
+import org.apache.flink.api.common.typeinfo.BasicTypeInfo._
+import org.apache.flink.api.common.typeinfo.NumericTypeInfo
+import org.apache.flink.api.table.validate._
+
+abstract class BinaryComparison extends BinaryExpression {
   def sqlOperator: SqlOperator
 
   override def toRexNode(implicit relBuilder: RelBuilder): RexNode = {
     relBuilder.call(sqlOperator, children.map(_.toRexNode))
   }
+
+  override def resultType = BOOLEAN_TYPE_INFO
+
+  // TODO: tighten this rule once we implemented type coercion rules during validation
+  override def validateInput(): ExprValidationResult = (left.resultType, right.resultType) match {
+    case (STRING_TYPE_INFO, STRING_TYPE_INFO) => ValidationSuccess
+    case (_: NumericTypeInfo[_], _: NumericTypeInfo[_]) => ValidationSuccess
+    case (lType, rType) =>
+      ValidationFailure(
+        s"Comparison is only supported for Strings and numeric types, get $lType and $rType")
+  }
 }
 
 case class EqualTo(left: Expression, right: Expression) extends BinaryComparison {
   override def toString = s"$left === $right"
 
   val sqlOperator: SqlOperator = SqlStdOperatorTable.EQUALS
+
+  override def validateInput(): ExprValidationResult = (left.resultType, right.resultType) match {
+    case (_: NumericTypeInfo[_], _: NumericTypeInfo[_]) => ValidationSuccess
+    case (lType, rType) =>
+      if (lType != rType) {
+        ValidationFailure(s"Equality predicate on incompatible types: $lType and $rType")
+      } else {
+        ValidationSuccess
+      }
+  }
 }
 
 case class NotEqualTo(left: Expression, right: Expression) extends BinaryComparison {
   override def toString = s"$left !== $right"
 
   val sqlOperator: SqlOperator = SqlStdOperatorTable.NOT_EQUALS
+
+  override def validateInput(): ExprValidationResult = (left.resultType, right.resultType) match {
+    case (_: NumericTypeInfo[_], _: NumericTypeInfo[_]) => ValidationSuccess
+    case (lType, rType) =>
+      if (lType != rType) {
+        ValidationFailure(s"Equality predicate on incompatible types: $lType and $rType")
+      } else {
+        ValidationSuccess
+      }
+  }
 }
 
 case class GreaterThan(left: Expression, right: Expression) extends BinaryComparison {
@@ -74,6 +109,8 @@ case class IsNull(child: Expression) extends UnaryExpression {
   override def toRexNode(implicit relBuilder: RelBuilder): RexNode = {
     relBuilder.isNull(child.toRexNode)
   }
+
+  override def resultType = BOOLEAN_TYPE_INFO
 }
 
 case class IsNotNull(child: Expression) extends UnaryExpression {
@@ -82,4 +119,6 @@ case class IsNotNull(child: Expression) extends UnaryExpression {
   override def toRexNode(implicit relBuilder: RelBuilder): RexNode = {
     relBuilder.isNotNull(child.toRexNode)
   }
+
+  override def resultType = BOOLEAN_TYPE_INFO
 }

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/fieldExpression.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/fieldExpression.scala b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/fieldExpression.scala
index 82f7653..24283d0 100644
--- a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/fieldExpression.scala
+++ b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/fieldExpression.scala
@@ -20,27 +20,88 @@ package org.apache.flink.api.table.expressions
 import org.apache.calcite.rex.RexNode
 import org.apache.calcite.tools.RelBuilder
 
-case class UnresolvedFieldReference(override val name: String) extends LeafExpression {
+import org.apache.flink.api.common.typeinfo.TypeInformation
+import org.apache.flink.api.table.UnresolvedException
+import org.apache.flink.api.table.validate.{ExprValidationResult, ValidationFailure}
+
+trait NamedExpression extends Expression {
+  def name: String
+  def toAttribute: Attribute
+}
+
+abstract class Attribute extends LeafExpression with NamedExpression {
+  override def toAttribute: Attribute = this
+
+  def withName(newName: String): Attribute
+}
+
+case class UnresolvedFieldReference(name: String) extends Attribute {
+
   override def toString = "\"" + name
 
+  override def withName(newName: String): Attribute = UnresolvedFieldReference(newName)
+
+  override def resultType: TypeInformation[_] =
+    throw new UnresolvedException(s"calling resultType on ${this.getClass}")
+
+  override def validateInput(): ExprValidationResult =
+    ValidationFailure(s"Unresolved reference $name")
+}
+
+case class ResolvedFieldReference(
+    name: String,
+    resultType: TypeInformation[_]) extends Attribute {
+
+  override def toString = s"'$name"
+
   override def toRexNode(implicit relBuilder: RelBuilder): RexNode = {
     relBuilder.field(name)
   }
-}
 
-case class ResolvedFieldReference(override val name: String) extends LeafExpression {
-  override def toString = s"'$name"
+  override def withName(newName: String): Attribute = {
+    if (newName == name) {
+      this
+    } else {
+      ResolvedFieldReference(newName, resultType)
+    }
+  }
 }
 
-case class Naming(child: Expression, override val name: String) extends UnaryExpression {
+case class Alias(child: Expression, name: String)
+    extends UnaryExpression with NamedExpression {
+
   override def toString = s"$child as '$name"
 
   override def toRexNode(implicit relBuilder: RelBuilder): RexNode = {
     relBuilder.alias(child.toRexNode, name)
   }
 
-  override def makeCopy(anyRefs: Seq[AnyRef]): this.type = {
+  override def resultType: TypeInformation[_] = child.resultType
+
+  override def makeCopy(anyRefs: Array[AnyRef]): this.type = {
     val child: Expression = anyRefs.head.asInstanceOf[Expression]
     copy(child, name).asInstanceOf[this.type]
   }
+
+  override def toAttribute: Attribute = {
+    if (valid) {
+      ResolvedFieldReference(name, child.resultType)
+    } else {
+      UnresolvedFieldReference(name)
+    }
+  }
+}
+
+case class UnresolvedAlias(child: Expression) extends UnaryExpression with NamedExpression {
+
+  override def name: String =
+    throw new UnresolvedException("Invalid call to name on UnresolvedAlias")
+
+  override def toAttribute: Attribute =
+    throw new UnresolvedException("Invalid call to toAttribute on UnresolvedAlias")
+
+  override def resultType: TypeInformation[_] =
+    throw new UnresolvedException("Invalid call to resultType on UnresolvedAlias")
+
+  override lazy val valid = false
 }

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/literals.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/literals.scala b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/literals.scala
index 1fbe5a3..9caec26 100644
--- a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/literals.scala
+++ b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/literals.scala
@@ -22,7 +22,6 @@ import java.util.Date
 import org.apache.calcite.rex.RexNode
 import org.apache.calcite.tools.RelBuilder
 import org.apache.flink.api.common.typeinfo.{BasicTypeInfo, TypeInformation}
-import org.apache.flink.api.scala.table.ImplicitExpressionOperations
 import org.apache.flink.api.table.typeutils.TypeConverter
 
 object Literal {
@@ -39,11 +38,7 @@ object Literal {
   }
 }
 
-case class Literal(value: Any, tpe: TypeInformation[_])
-  extends LeafExpression with ImplicitExpressionOperations {
-  def expr = this
-  def typeInfo = tpe
-
+case class Literal(value: Any, resultType: TypeInformation[_]) extends LeafExpression {
   override def toString = s"$value"
 
   override def toRexNode(implicit relBuilder: RelBuilder): RexNode = {
@@ -51,13 +46,10 @@ case class Literal(value: Any, tpe: TypeInformation[_])
   }
 }
 
-case class Null(tpe: TypeInformation[_]) extends LeafExpression {
-  def expr = this
-  def typeInfo = tpe
-
+case class Null(resultType: TypeInformation[_]) extends LeafExpression {
   override def toString = s"null"
 
   override def toRexNode(implicit relBuilder: RelBuilder): RexNode = {
-    relBuilder.getRexBuilder.makeNullLiteral(TypeConverter.typeInfoToSqlType(tpe))
+    relBuilder.getRexBuilder.makeNullLiteral(TypeConverter.typeInfoToSqlType(resultType))
   }
 }

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/logic.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/logic.scala b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/logic.scala
index 37a6597..90d3dbc 100644
--- a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/logic.scala
+++ b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/logic.scala
@@ -21,25 +21,47 @@ import org.apache.calcite.rex.RexNode
 import org.apache.calcite.sql.fun.SqlStdOperatorTable
 import org.apache.calcite.tools.RelBuilder
 
-abstract class BinaryPredicate extends BinaryExpression { self: Product => }
+import org.apache.flink.api.common.typeinfo.BasicTypeInfo
+import org.apache.flink.api.table.validate._
+
+abstract class BinaryPredicate extends BinaryExpression {
+  override def resultType = BasicTypeInfo.BOOLEAN_TYPE_INFO
+
+  override def validateInput(): ExprValidationResult = {
+    if (left.resultType == BasicTypeInfo.BOOLEAN_TYPE_INFO &&
+        right.resultType == BasicTypeInfo.BOOLEAN_TYPE_INFO) {
+      ValidationSuccess
+    } else {
+      ValidationFailure(s"$this only accepts children of Boolean Type, " +
+        s"get ${left.resultType} and ${right.resultType}")
+    }
+  }
+}
 
 case class Not(child: Expression) extends UnaryExpression {
 
-  override val name = Expression.freshName("not-" + child.name)
-
   override def toString = s"!($child)"
 
   override def toRexNode(implicit relBuilder: RelBuilder): RexNode = {
     relBuilder.not(child.toRexNode)
   }
+
+  override def resultType = BasicTypeInfo.BOOLEAN_TYPE_INFO
+
+  override def validateInput(): ExprValidationResult = {
+    if (child.resultType == BasicTypeInfo.BOOLEAN_TYPE_INFO) {
+      ValidationSuccess
+    } else {
+      ValidationFailure(s"Not only accepts child of Boolean Type, " +
+        s"get ${child.resultType}")
+    }
+  }
 }
 
 case class And(left: Expression, right: Expression) extends BinaryPredicate {
 
   override def toString = s"$left && $right"
 
-  override val name = Expression.freshName(left.name + "-and-" + right.name)
-
   override def toRexNode(implicit relBuilder: RelBuilder): RexNode = {
     relBuilder.and(left.toRexNode, right.toRexNode)
   }
@@ -49,8 +71,6 @@ case class Or(left: Expression, right: Expression) extends BinaryPredicate {
 
   override def toString = s"$left || $right"
 
-  override val name = Expression.freshName(left.name + "-or-" + right.name)
-
   override def toRexNode(implicit relBuilder: RelBuilder): RexNode = {
     relBuilder.or(left.toRexNode, right.toRexNode)
   }
@@ -63,10 +83,9 @@ case class Eval(
   extends Expression {
   def children = Seq(condition, ifTrue, ifFalse)
 
-  override def toString = s"($condition)? $ifTrue : $ifFalse"
+  override def resultType = ifTrue.resultType
 
-  override val name = Expression.freshName("if-" + condition.name +
-    "-then-" + ifTrue.name + "-else-" + ifFalse.name)
+  override def toString = s"($condition)? $ifTrue : $ifFalse"
 
   override def toRexNode(implicit relBuilder: RelBuilder): RexNode = {
     val c = condition.toRexNode
@@ -74,4 +93,15 @@ case class Eval(
     val f = ifFalse.toRexNode
     relBuilder.call(SqlStdOperatorTable.CASE, c, t, f)
   }
+
+  override def validateInput(): ExprValidationResult = {
+    if (condition.resultType == BasicTypeInfo.BOOLEAN_TYPE_INFO &&
+        ifTrue.resultType == ifFalse.resultType) {
+      ValidationSuccess
+    } else {
+      ValidationFailure(
+        s"Eval should have boolean condition and same type of ifTrue and ifFalse, get " +
+          s"(${condition.resultType}, ${ifTrue.resultType}, ${ifFalse.resultType})")
+    }
+  }
 }

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/mathExpressions.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/mathExpressions.scala b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/mathExpressions.scala
new file mode 100644
index 0000000..cf734f0
--- /dev/null
+++ b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/mathExpressions.scala
@@ -0,0 +1,115 @@
+/*
+ * 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.flink.api.table.expressions
+
+import org.apache.calcite.rex.RexNode
+import org.apache.calcite.sql.fun.SqlStdOperatorTable
+import org.apache.calcite.tools.RelBuilder
+
+import org.apache.flink.api.common.typeinfo.BasicTypeInfo._
+import org.apache.flink.api.common.typeinfo.TypeInformation
+import org.apache.flink.api.table.typeutils.TypeCheckUtils
+import org.apache.flink.api.table.validate._
+
+case class Abs(child: Expression) extends UnaryExpression {
+  override def resultType: TypeInformation[_] = child.resultType
+
+  override def validateInput(): ExprValidationResult =
+    TypeCheckUtils.assertNumericExpr(child.resultType, "Abs")
+
+  override def toString(): String = s"abs($child)"
+
+  override def toRexNode(implicit relBuilder: RelBuilder): RexNode = {
+    relBuilder.call(SqlStdOperatorTable.ABS, child.toRexNode)
+  }
+}
+
+case class Ceil(child: Expression) extends UnaryExpression {
+  override def resultType: TypeInformation[_] = LONG_TYPE_INFO
+
+  override def validateInput(): ExprValidationResult =
+    TypeCheckUtils.assertNumericExpr(child.resultType, "Ceil")
+
+  override def toString(): String = s"ceil($child)"
+
+  override def toRexNode(implicit relBuilder: RelBuilder): RexNode = {
+    relBuilder.call(SqlStdOperatorTable.CEIL, child.toRexNode)
+  }
+}
+
+case class Exp(child: Expression) extends UnaryExpression with InputTypeSpec {
+  override def resultType: TypeInformation[_] = DOUBLE_TYPE_INFO
+
+  override def expectedTypes: Seq[TypeInformation[_]] = DOUBLE_TYPE_INFO :: Nil
+
+  override def toString(): String = s"exp($child)"
+
+  override def toRexNode(implicit relBuilder: RelBuilder): RexNode = {
+    relBuilder.call(SqlStdOperatorTable.EXP, child.toRexNode)
+  }
+}
+
+
+case class Floor(child: Expression) extends UnaryExpression {
+  override def resultType: TypeInformation[_] = LONG_TYPE_INFO
+
+  override def validateInput(): ExprValidationResult =
+    TypeCheckUtils.assertNumericExpr(child.resultType, "Floor")
+
+  override def toString(): String = s"floor($child)"
+
+  override def toRexNode(implicit relBuilder: RelBuilder): RexNode = {
+    relBuilder.call(SqlStdOperatorTable.FLOOR, child.toRexNode)
+  }
+}
+
+case class Log10(child: Expression) extends UnaryExpression with InputTypeSpec {
+  override def resultType: TypeInformation[_] = DOUBLE_TYPE_INFO
+
+  override def expectedTypes: Seq[TypeInformation[_]] = DOUBLE_TYPE_INFO :: Nil
+
+  override def toString(): String = s"log10($child)"
+
+  override def toRexNode(implicit relBuilder: RelBuilder): RexNode = {
+    relBuilder.call(SqlStdOperatorTable.LOG10, child.toRexNode)
+  }
+}
+
+case class Ln(child: Expression) extends UnaryExpression with InputTypeSpec {
+  override def resultType: TypeInformation[_] = DOUBLE_TYPE_INFO
+
+  override def expectedTypes: Seq[TypeInformation[_]] = DOUBLE_TYPE_INFO :: Nil
+
+  override def toString(): String = s"ln($child)"
+
+  override def toRexNode(implicit relBuilder: RelBuilder): RexNode = {
+    relBuilder.call(SqlStdOperatorTable.LN, child.toRexNode)
+  }
+}
+
+case class Power(left: Expression, right: Expression) extends BinaryExpression with InputTypeSpec {
+  override def resultType: TypeInformation[_] = DOUBLE_TYPE_INFO
+
+  override def expectedTypes: Seq[TypeInformation[_]] = DOUBLE_TYPE_INFO :: DOUBLE_TYPE_INFO :: Nil
+
+  override def toString(): String = s"pow($left, $right)"
+
+  override def toRexNode(implicit relBuilder: RelBuilder): RexNode = {
+    relBuilder.call(SqlStdOperatorTable.POWER, left.toRexNode, right.toRexNode)
+  }
+}

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/ordering.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/ordering.scala b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/ordering.scala
index 75fa078..887cf60 100644
--- a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/ordering.scala
+++ b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/ordering.scala
@@ -16,28 +16,39 @@
  * limitations under the License.
  */
 package org.apache.flink.api.table.expressions
+
 import org.apache.calcite.rex.RexNode
 import org.apache.calcite.tools.RelBuilder
 
-abstract class Ordering extends UnaryExpression { self: Product =>
+import org.apache.flink.api.common.typeinfo.TypeInformation
+import org.apache.flink.api.table.validate._
+
+abstract class Ordering extends UnaryExpression {
+  override def validateInput(): ExprValidationResult = {
+    if (!child.isInstanceOf[NamedExpression]) {
+      ValidationFailure(s"Sort should only based on field reference")
+    } else {
+      ValidationSuccess
+    }
+  }
 }
 
 case class Asc(child: Expression) extends Ordering {
   override def toString: String = s"($child).asc"
 
-  override def name: String = child.name + "-asc"
-
   override def toRexNode(implicit relBuilder: RelBuilder): RexNode = {
     child.toRexNode
   }
+
+  override def resultType: TypeInformation[_] = child.resultType
 }
 
 case class Desc(child: Expression) extends Ordering {
   override def toString: String = s"($child).desc"
 
-  override def name: String = child.name + "-desc"
-
   override def toRexNode(implicit relBuilder: RelBuilder): RexNode = {
     relBuilder.desc(child.toRexNode)
   }
+
+  override def resultType: TypeInformation[_] = child.resultType
 }

http://git-wip-us.apache.org/repos/asf/flink/blob/f0d543f8/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/stringExpressions.scala
----------------------------------------------------------------------
diff --git a/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/stringExpressions.scala b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/stringExpressions.scala
new file mode 100644
index 0000000..11825f7
--- /dev/null
+++ b/flink-libraries/flink-table/src/main/scala/org/apache/flink/api/table/expressions/stringExpressions.scala
@@ -0,0 +1,220 @@
+/*
+ * 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.flink.api.table.expressions
+
+import scala.collection.JavaConversions._
+
+import org.apache.calcite.rex.RexNode
+import org.apache.calcite.sql.fun.SqlStdOperatorTable
+import org.apache.calcite.tools.RelBuilder
+
+import org.apache.flink.api.common.typeinfo.BasicTypeInfo._
+import org.apache.flink.api.common.typeinfo.TypeInformation
+import org.apache.flink.api.table.validate._
+
+/**
+  * Returns the length of this `str`.
+  */
+case class CharLength(child: Expression) extends UnaryExpression {
+  override def resultType: TypeInformation[_] = INT_TYPE_INFO
+
+  override def validateInput(): ExprValidationResult = {
+    if (child.resultType == STRING_TYPE_INFO) {
+      ValidationSuccess
+    } else {
+      ValidationFailure(s"CharLength only accepts String input, get ${child.resultType}")
+    }
+  }
+
+  override def toString(): String = s"($child).charLength()"
+
+  override def toRexNode(implicit relBuilder: RelBuilder): RexNode = {
+    relBuilder.call(SqlStdOperatorTable.CHAR_LENGTH, child.toRexNode)
+  }
+}
+
+/**
+  * Returns str with the first letter of each word in uppercase.
+  * All other letters are in lowercase. Words are delimited by white space.
+  */
+case class InitCap(child: Expression) extends UnaryExpression {
+  override def resultType: TypeInformation[_] = STRING_TYPE_INFO
+
+  override def validateInput(): ExprValidationResult = {
+    if (child.resultType == STRING_TYPE_INFO) {
+      ValidationSuccess
+    } else {
+      ValidationFailure(s"InitCap only accepts String input, get ${child.resultType}")
+    }
+  }
+
+  override def toString(): String = s"($child).initCap()"
+
+  override def toRexNode(implicit relBuilder: RelBuilder): RexNode = {
+    relBuilder.call(SqlStdOperatorTable.INITCAP, child.toRexNode)
+  }
+}
+
+/**
+  * Returns true if `str` matches `pattern`.
+  */
+case class Like(str: Expression, pattern: Expression) extends BinaryExpression {
+  def left: Expression = str
+  def right: Expression = pattern
+
+  override def resultType: TypeInformation[_] = BOOLEAN_TYPE_INFO
+
+  override def validateInput(): ExprValidationResult = {
+    if (str.resultType == STRING_TYPE_INFO && pattern.resultType == STRING_TYPE_INFO) {
+      ValidationSuccess
+    } else {
+      ValidationFailure(s"Like only accepts (String, String) input, " +
+        s"get (${str.resultType}, ${pattern.resultType})")
+    }
+  }
+
+  override def toString(): String = s"($str).like($pattern)"
+
+  override def toRexNode(implicit relBuilder: RelBuilder): RexNode = {
+    relBuilder.call(SqlStdOperatorTable.LIKE, children.map(_.toRexNode))
+  }
+}
+
+/**
+  * Returns str with all characters changed to lowercase.
+  */
+case class Lower(child: Expression) extends UnaryExpression {
+  override def resultType: TypeInformation[_] = STRING_TYPE_INFO
+
+  override def validateInput(): ExprValidationResult = {
+    if (child.resultType == STRING_TYPE_INFO) {
+      ValidationSuccess
+    } else {
+      ValidationFailure(s"Lower only accepts String input, get ${child.resultType}")
+    }
+  }
+
+  override def toString(): String = s"($child).toLowerCase()"
+
+  override def toRexNode(implicit relBuilder: RelBuilder): RexNode = {
+    relBuilder.call(SqlStdOperatorTable.LOWER, child.toRexNode)
+  }
+}
+
+/**
+  * Returns true if `str` is similar to `pattern`.
+  */
+case class Similar(str: Expression, pattern: Expression) extends BinaryExpression {
+  def left: Expression = str
+  def right: Expression = pattern
+
+  override def resultType: TypeInformation[_] = BOOLEAN_TYPE_INFO
+
+  override def validateInput(): ExprValidationResult = {
+    if (str.resultType == STRING_TYPE_INFO && pattern.resultType == STRING_TYPE_INFO) {
+      ValidationSuccess
+    } else {
+      ValidationFailure(s"Similar only accepts (String, String) input, " +
+        s"get (${str.resultType}, ${pattern.resultType})")
+    }
+  }
+
+  override def toString(): String = s"($str).similarTo($pattern)"
+
+  override def toRexNode(implicit relBuilder: RelBuilder): RexNode = {
+    relBuilder.call(SqlStdOperatorTable.SIMILAR_TO, children.map(_.toRexNode))
+  }
+}
+
+/**
+  * Returns subString of `str` from `begin`(inclusive) to `end`(not inclusive).
+  */
+case class SubString(
+    str: Expression,
+    begin: Expression,
+    end: Expression) extends Expression with InputTypeSpec {
+
+  def this(str: Expression, begin: Expression) = this(str, begin, CharLength(str))
+
+  override def children: Seq[Expression] = str :: begin :: end :: Nil
+
+  override def resultType: TypeInformation[_] = STRING_TYPE_INFO
+
+  override def expectedTypes: Seq[TypeInformation[_]] =
+    Seq(STRING_TYPE_INFO, INT_TYPE_INFO, INT_TYPE_INFO)
+
+  override def toString(): String = s"$str.subString($begin, $end)"
+
+  override def toRexNode(implicit relBuilder: RelBuilder): RexNode = {
+    relBuilder.call(SqlStdOperatorTable.SUBSTRING, children.map(_.toRexNode))
+  }
+}
+
+/**
+  * Trim `trimString` from `str` according to `trimFlag`:
+  * 0 for TRIM_BOTH, 1 for TRIM_LEADING and 2 for TRIM_TRAILING.
+  */
+case class Trim(
+    trimFlag: Expression,
+    trimString: Expression,
+    str: Expression) extends Expression with InputTypeSpec {
+
+  override def children: Seq[Expression] = trimFlag :: trimString :: str :: Nil
+
+  override def resultType: TypeInformation[_] = STRING_TYPE_INFO
+
+  override def expectedTypes: Seq[TypeInformation[_]] =
+    Seq(INT_TYPE_INFO, STRING_TYPE_INFO, STRING_TYPE_INFO)
+
+  override def toString(): String = s"trim($trimFlag, $trimString, $str)"
+
+  override def toRexNode(implicit relBuilder: RelBuilder): RexNode = {
+    relBuilder.call(SqlStdOperatorTable.TRIM, children.map(_.toRexNode))
+  }
+}
+
+/**
+  * Enumeration of trim flags.
+  */
+object TrimConstants {
+  val TRIM_BOTH = Literal(0)
+  val TRIM_LEADING = Literal(1)
+  val TRIM_TRAILING = Literal(2)
+  val TRIM_DEFAULT_CHAR = Literal(" ")
+}
+
+/**
+  * Returns str with all characters changed to uppercase.
+  */
+case class Upper(child: Expression) extends UnaryExpression {
+  override def resultType: TypeInformation[_] = STRING_TYPE_INFO
+
+  override def validateInput(): ExprValidationResult = {
+    if (child.resultType == STRING_TYPE_INFO) {
+      ValidationSuccess
+    } else {
+      ValidationFailure(s"Upper only accepts String input, get ${child.resultType}")
+    }
+  }
+
+  override def toString(): String = s"($child).toUpperCase()"
+
+  override def toRexNode(implicit relBuilder: RelBuilder): RexNode = {
+    relBuilder.call(SqlStdOperatorTable.UPPER, child.toRexNode)
+  }
+}