weidong3630 commented on a change in pull request #1338: [CALCITE-3210] Fix the 
bug that RelToSqlConverter converts "cast(null as $type)" just as null
URL: https://github.com/apache/calcite/pull/1338#discussion_r308111279
 
 

 ##########
 File path: 
core/src/main/java/org/apache/calcite/rel/rel2sql/RelToSqlConverter.java
 ##########
 @@ -195,15 +198,57 @@ public Result visit(Project e) {
     final Builder builder =
         x.builder(e, Clause.SELECT);
     final List<SqlNode> selectList = new ArrayList<>();
+
+    boolean checkNull = isNeedCastNull(stack);
     for (RexNode ref : e.getChildExps()) {
       SqlNode sqlExpr = builder.context.toSql(null, ref);
+      if (checkNull && SqlUtil.isNullLiteral(sqlExpr, false)) {
+        sqlExpr = castNullType(sqlExpr, 
e.getRowType().getFieldList().get(selectList.size()));
+      }
       addSelect(selectList, sqlExpr, e.getRowType());
     }
 
     builder.setSelect(new SqlNodeList(selectList, POS));
     return builder.result();
   }
 
+  /**
+   * Check whether null item in select need to be casted
+   * @param stack stack of visit
+   * @return If null need to be casted then return true, otherwise return 
false.
+   */
+  private static boolean isNeedCastNull(Deque<Frame> stack) {
+    final int stackSize = stack.size();
+    if (stackSize > 1) {
+      int i = 1;
+      for (; i < stackSize; i++) {
+        RelNode currentNode = Iterables.get(stack, i).r;
+        if (!(currentNode instanceof SingleRel)) {
+          break;
+        } else if (currentNode instanceof Project) {
+          //direct or indirect input of Project need to cast null type
+          break;
+        } else if (currentNode instanceof TableModify) {
+          //direct or indirect input of TableModify do not need to cast null 
type
+          return false;
+        }
+      }
+    }
+
+    return true;
+  }
+
+  /**
+   * cast null with type
+   * @param sqlNodeNull null SqlNode
+   * @param field field description of sqlNodeNull
+   * @return SqlNode with cast to type.
+   */
+  private SqlNode  castNullType(SqlNode sqlNodeNull, RelDataTypeField field) {
 
 Review comment:
   Thanks, I will fix it.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
[email protected]


With regards,
Apache Git Services

Reply via email to