org.apache.calcite.sql.SqlBasicCall Java Examples

The following examples show how to use org.apache.calcite.sql.SqlBasicCall. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CalciteSqlParser.java    From sylph with Apache License 2.0 6 votes vote down vote up
private JoinInfo parserJoin(SqlJoin sqlJoin)
{
    final Function<SqlNode, TableName> func = (node) -> {
        TableName tableName;
        if (node.getKind() == IDENTIFIER) {
            String leftTableName = node.toString();
            tableName = new TableName(leftTableName, Optional.empty());
        }
        else if (node.getKind() == JOIN) {
            JoinInfo nodeJoinInfo = parserJoin((SqlJoin) node);
            throw new UnsupportedOperationException("this have't support!");
        }
        else if (node.getKind() == AS) {
            tableName = parserAs((SqlBasicCall) node);
        }
        else {
            throw new UnsupportedOperationException("this have't support! " + node);
        }
        return tableName;
    };

    TableName leftTable = func.apply(sqlJoin.getLeft());
    TableName rightTable = func.apply(sqlJoin.getRight());

    return new JoinInfo(sqlJoin, leftTable, rightTable, batchTables.contains(leftTable.getName()), batchTables.contains(rightTable.getName()));
}
 
Example #2
Source File: CalciteSqlParser.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
private static Expression compileFunctionExpression(SqlBasicCall funcSqlNode) {
  String funcName = extractFunctionName(funcSqlNode);
  Expression funcExpr = RequestUtils.getFunctionExpression(funcName);
  for (SqlNode child : funcSqlNode.getOperands()) {
    if (child instanceof SqlNodeList) {
      final Iterator<SqlNode> iterator = ((SqlNodeList) child).iterator();
      while (iterator.hasNext()) {
        final SqlNode next = iterator.next();
        funcExpr.getFunctionCall().addToOperands(toExpression(next));
      }
    } else {
      funcExpr.getFunctionCall().addToOperands(toExpression(child));
    }
  }
  return funcExpr;
}
 
Example #3
Source File: CalciteSqlParser.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
private static Expression convertOrderBy(SqlNode node) {
  final SqlKind kind = node.getKind();
  Expression expression;
  switch (kind) {
    case DESCENDING:
      SqlBasicCall basicCall = (SqlBasicCall) node;
      expression = RequestUtils.getFunctionExpression("DESC");
      expression.getFunctionCall().addToOperands(toExpression(basicCall.getOperands()[0]));
      break;
    case IDENTIFIER:
    default:
      expression = RequestUtils.getFunctionExpression("ASC");
      expression.getFunctionCall().addToOperands(toExpression(node));
      break;
  }
  return expression;
}
 
Example #4
Source File: RexSqlStandardConvertletTable.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Creates and registers a convertlet for an operator in which
 * the SQL representation needs the result type appended
 * as an extra argument (e.g. CAST).
 *
 * @param op operator instance
 */
private void registerTypeAppendOp(final SqlOperator op) {
  registerOp(
      op, (converter, call) -> {
        SqlNode[] operands =
            convertExpressionList(converter, call.operands);
        if (operands == null) {
          return null;
        }
        List<SqlNode> operandList =
            new ArrayList<>(Arrays.asList(operands));
        SqlDataTypeSpec typeSpec =
            SqlTypeUtil.convertTypeToSpec(call.getType());
        operandList.add(typeSpec);
        return new SqlBasicCall(
            op,
            operandList.toArray(new SqlNode[0]),
            SqlParserPos.ZERO);
      });
}
 
Example #5
Source File: RexSqlStandardConvertletTable.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Converts a call to an operator into a {@link SqlCall} to the same
 * operator.
 *
 * <p>Called automatically via reflection.
 *
 * @param converter Converter
 * @param call      Call
 * @return Sql call
 */
public SqlNode convertCall(
    RexToSqlNodeConverter converter,
    RexCall call) {
  if (get(call) == null) {
    return null;
  }

  final SqlOperator op = call.getOperator();
  final List<RexNode> operands = call.getOperands();

  final SqlNode[] exprs = convertExpressionList(converter, operands);
  if (exprs == null) {
    return null;
  }
  return new SqlBasicCall(
      op,
      exprs,
      SqlParserPos.ZERO);
}
 
Example #6
Source File: RelToSqlConverter.java    From calcite with Apache License 2.0 6 votes vote down vote up
public Result visit(TableFunctionScan e) {
  final List<SqlNode> inputSqlNodes = new ArrayList<>();
  final int inputSize = e.getInputs().size();
  for (int i = 0; i < inputSize; i++) {
    Result child = visitChild(i, e.getInput(i));
    inputSqlNodes.add(child.asStatement());
  }
  final Context context = tableFunctionScanContext(inputSqlNodes);
  SqlNode callNode = context.toSql(null, e.getCall());
  // Convert to table function call, "TABLE($function_name(xxx))"
  SqlNode tableCall = new SqlBasicCall(
      SqlStdOperatorTable.COLLECTION_TABLE,
      new SqlNode[]{callNode},
      SqlParserPos.ZERO);
  SqlNode select = new SqlSelect(
      SqlParserPos.ZERO, null, null, tableCall,
      null, null, null, null, null, null, null, SqlNodeList.EMPTY);
  return result(select, ImmutableList.of(Clause.SELECT), e, null);
}
 
Example #7
Source File: SqlImplementor.java    From calcite with Apache License 2.0 6 votes vote down vote up
private boolean hasNestedAggregations(Aggregate rel) {
  if (node instanceof SqlSelect) {
    final SqlNodeList selectList = ((SqlSelect) node).getSelectList();
    if (selectList != null) {
      final Set<Integer> aggregatesArgs = new HashSet<>();
      for (AggregateCall aggregateCall : rel.getAggCallList()) {
        aggregatesArgs.addAll(aggregateCall.getArgList());
      }
      for (int aggregatesArg : aggregatesArgs) {
        if (selectList.get(aggregatesArg) instanceof SqlBasicCall) {
          final SqlBasicCall call =
              (SqlBasicCall) selectList.get(aggregatesArg);
          for (SqlNode operand : call.getOperands()) {
            if (operand instanceof SqlCall
                && ((SqlCall) operand).getOperator() instanceof SqlAggFunction) {
              return true;
            }
          }
        }
      }
    }
  }
  return false;
}
 
Example #8
Source File: SamzaSqlQueryParser.java    From samza with Apache License 2.0 6 votes vote down vote up
private static void getSource(SqlNode node, ArrayList<String> sourceList) {
  if (node instanceof SqlJoin) {
    SqlJoin joinNode = (SqlJoin) node;
    ArrayList<String> sourcesLeft = new ArrayList<>();
    ArrayList<String> sourcesRight = new ArrayList<>();
    getSource(joinNode.getLeft(), sourcesLeft);
    getSource(joinNode.getRight(), sourcesRight);

    sourceList.addAll(sourcesLeft);
    sourceList.addAll(sourcesRight);
  } else if (node instanceof SqlIdentifier) {
    sourceList.add(node.toString());
  } else if (node instanceof SqlBasicCall) {
    SqlBasicCall basicCall = (SqlBasicCall) node;
    if (basicCall.getOperator() instanceof SqlAsOperator) {
      getSource(basicCall.operand(0), sourceList);
    } else if (basicCall.getOperator() instanceof SqlUnnestOperator && basicCall.operand(0) instanceof SqlSelect) {
      sourceList.addAll(getSourcesFromSelectQuery(basicCall.operand(0)));
    }
  } else if (node instanceof SqlSelect) {
    getSource(((SqlSelect) node).getFrom(), sourceList);
  }
}
 
Example #9
Source File: SqlImplementor.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
protected boolean hasNestedAggregations(LogicalAggregate rel) {
  List<AggregateCall> aggCallList = rel.getAggCallList();
  HashSet<Integer> aggregatesArgs = new HashSet<>();
  for (AggregateCall aggregateCall : aggCallList) {
    aggregatesArgs.addAll(aggregateCall.getArgList());
  }
  for (Integer aggregatesArg : aggregatesArgs) {
    SqlNode selectNode = ((SqlSelect) node).getSelectList().get(aggregatesArg);
    if (!(selectNode instanceof SqlBasicCall)) {
      continue;
    }
    for (SqlNode operand : ((SqlBasicCall) selectNode).getOperands()) {
      if (operand instanceof SqlCall) {
        final SqlOperator operator = ((SqlCall) operand).getOperator();
        if (operator instanceof SqlAggFunction) {
          return true;
        }
      }
    }
  }
  return false;
}
 
Example #10
Source File: FlinkSqlParser.java    From sylph with Apache License 2.0 6 votes vote down vote up
/**
 * update having
 */
private static SqlNode updateOnlyOneFilter(SqlNode filterNode, String joinOutTableName)
{
    if (filterNode.getKind() == IDENTIFIER) {
        SqlIdentifier field = ((SqlIdentifier) filterNode);
        checkState(!field.isStar(), "filter field must not Star(*)");
        if (field.names.size() > 1) {
            field.setName(0, field.getComponent(0).getSimple());
            field.setName(1, joinOutTableName);
        }
        return field;
    }
    else if (filterNode instanceof SqlBasicCall) {  //demo: `user_id` = 'uid_1'
        SqlBasicCall sqlBasicCall = (SqlBasicCall) filterNode;
        for (int i = 0; i < sqlBasicCall.getOperandList().size(); i++) {
            SqlNode sqlNode = sqlBasicCall.getOperandList().get(i);
            SqlNode upNode = updateOnlyOneFilter(sqlNode, joinOutTableName);
            sqlBasicCall.getOperands()[i] = upNode;
        }
        return sqlBasicCall;
    }
    else {
        return filterNode;
    }
}
 
Example #11
Source File: SqlImplementor.java    From Bats with Apache License 2.0 6 votes vote down vote up
private boolean hasNestedAggregations(LogicalAggregate rel) {
    if (node instanceof SqlSelect) {
        final SqlNodeList selectList = ((SqlSelect) node).getSelectList();
        if (selectList != null) {
            final Set<Integer> aggregatesArgs = new HashSet<>();
            for (AggregateCall aggregateCall : rel.getAggCallList()) {
                aggregatesArgs.addAll(aggregateCall.getArgList());
            }
            for (int aggregatesArg : aggregatesArgs) {
                if (selectList.get(aggregatesArg) instanceof SqlBasicCall) {
                    final SqlBasicCall call = (SqlBasicCall) selectList.get(aggregatesArg);
                    for (SqlNode operand : call.getOperands()) {
                        if (operand instanceof SqlCall
                                && ((SqlCall) operand).getOperator() instanceof SqlAggFunction) {
                            return true;
                        }
                    }
                }
            }
        }
    }
    return false;
}
 
Example #12
Source File: SqlParseUtil.java    From alchemy with Apache License 2.0 6 votes vote down vote up
private static void parseSelect(SqlNode sqlNode, List<String> sources, List<String> udfs) throws SqlParseException {
    SqlKind sqlKind = sqlNode.getKind();
    switch (sqlKind) {
        case IDENTIFIER:
            break;
        case AS:
            SqlNode firstNode = ((SqlBasicCall)sqlNode).operand(0);
            parseSelect(firstNode, sources, udfs);
            break;
        case SELECT:
            parseSource((SqlSelect)sqlNode, sources, udfs);
            break;
        default:
            parseFunction(sqlNode, udfs);

    }
}
 
Example #13
Source File: MysqlSideFunction.java    From alchemy with Apache License 2.0 6 votes vote down vote up
private List<SqlBasicCall> createConditionNodes(List<String> conditions, Alias alias) {
    SqlBinaryOperator equal = new SqlBinaryOperator("=", SqlKind.EQUALS, 30, true, ReturnTypes.BOOLEAN_NULLABLE,
        InferTypes.FIRST_KNOWN, OperandTypes.COMPARABLE_UNORDERED_COMPARABLE_UNORDERED);
    List<SqlBasicCall> nodes = new ArrayList<>(conditions.size());
    int num = 0;
    for (String condition : conditions) {
        List<String> fields = new ArrayList<>(2);
        fields.add(alias.getAlias());
        fields.add(condition);
        SqlIdentifier leftIdentifier = new SqlIdentifier(fields, new SqlParserPos(0, 0));
        SqlDynamicParam sqlDynamicParam = new SqlDynamicParam(num++, new SqlParserPos(0, 0));
        SqlNode[] sqlNodes = new SqlNode[2];
        sqlNodes[0] = leftIdentifier;
        sqlNodes[1] = sqlDynamicParam;
        SqlBasicCall andEqual = new SqlBasicCall(equal, sqlNodes, new SqlParserPos(0, 0));
        nodes.add(andEqual);
    }
    return nodes;
}
 
Example #14
Source File: SideParser.java    From alchemy with Apache License 2.0 6 votes vote down vote up
public static void rewrite(SqlNode sqlNode, SqlSelect sqlSelect) {
    SqlKind sqlKind = sqlNode.getKind();
    switch (sqlKind) {
        case INSERT:
            SqlInsert sqlInsert = ((SqlInsert)sqlNode);
            sqlInsert.setSource(sqlSelect);
            break;
        case SELECT:
            SqlSelect select = (SqlSelect)sqlNode;
            select.setFrom(sqlSelect);
            break;
        case AS:
            SqlBasicCall basicCall = (SqlBasicCall)sqlNode;
            basicCall.setOperand(0, sqlSelect);
            break;
        default:
            throw new UnsupportedOperationException(sqlKind + "目前不支持维表操作");
    }
}
 
Example #15
Source File: SideParser.java    From alchemy with Apache License 2.0 6 votes vote down vote up
public static Alias getTableName(SqlNode sqlNode) {
    SqlKind sqlKind = sqlNode.getKind();
    Alias alias;
    switch (sqlKind) {
        case IDENTIFIER:
            SqlIdentifier sqlIdentifier = (SqlIdentifier)sqlNode;
            alias = new Alias(sqlIdentifier.names.get(0), sqlIdentifier.names.get(0));
            break;
        case AS:
            SqlBasicCall sqlBasicCall = (SqlBasicCall)sqlNode;
            SqlNode first = sqlBasicCall.getOperands()[0];
            SqlNode second = sqlBasicCall.getOperands()[1];
            if (first.getKind() == SqlKind.IDENTIFIER) {
                alias = new Alias(((SqlIdentifier)first).names.get(0), ((SqlIdentifier)second).names.get(0));
            } else {
                alias = new Alias(((SqlIdentifier)second).names.get(0), ((SqlIdentifier)second).names.get(0));
            }
            break;
        default:
            throw new UnsupportedOperationException("暂时不支持" + sqlKind);
    }
    return alias;
}
 
Example #16
Source File: SideParser.java    From alchemy with Apache License 2.0 6 votes vote down vote up
public static void parse(SqlNode sqlNode, Deque<SqlNode> deque) {
    deque.offer(sqlNode);
    SqlKind sqlKind = sqlNode.getKind();
    switch (sqlKind) {
        case INSERT:
            SqlNode sqlSource = ((SqlInsert)sqlNode).getSource();
            parse(sqlSource, deque);
            break;
        case SELECT:
            SqlNode sqlFrom = ((SqlSelect)sqlNode).getFrom();
            parse(sqlFrom, deque);
            break;
        case JOIN:
            SqlNode sqlLeft = ((SqlJoin)sqlNode).getLeft();
            SqlNode sqlRight = ((SqlJoin)sqlNode).getRight();
            parse(sqlLeft, deque);
            parse(sqlRight, deque);
            break;
        case AS:
            SqlNode sqlAs = ((SqlBasicCall)sqlNode).getOperands()[0];
            parse(sqlAs, deque);
            break;
        default:
            return;
    }
}
 
Example #17
Source File: DrillConvertletTable.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override
public SqlRexConvertlet get(SqlCall call) {
  SqlRexConvertlet convertlet;
  if(call.getOperator() instanceof DrillCalciteSqlWrapper) {
    final SqlOperator wrapper = call.getOperator();
    final SqlOperator wrapped = DrillCalciteWrapperUtility.extractSqlOperatorFromWrapper(call.getOperator());
    if ((convertlet = map.get(wrapped)) != null) {
      return convertlet;
    }

    ((SqlBasicCall) call).setOperator(wrapped);
    SqlRexConvertlet sqlRexConvertlet = StandardConvertletTable.INSTANCE.get(call);
    ((SqlBasicCall) call).setOperator(wrapper);
    return sqlRexConvertlet;
  }

  if ((convertlet = map.get(call.getOperator())) != null) {
    return convertlet;
  }

  return StandardConvertletTable.INSTANCE.get(call);
}
 
Example #18
Source File: RexSqlStandardConvertletTable.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * Converts a call to an operator into a {@link SqlCall} to the same
 * operator.
 *
 * <p>Called automatically via reflection.
 *
 * @param converter Converter
 * @param call      Call
 * @return Sql call
 */
public SqlNode convertCall(
    RexToSqlNodeConverter converter,
    RexCall call) {
  if (get(call) == null) {
    return null;
  }

  final SqlOperator op = call.getOperator();
  final List<RexNode> operands = call.getOperands();

  final SqlNode[] exprs = convertExpressionList(converter, operands);
  if (exprs == null) {
    return null;
  }
  return new SqlBasicCall(
      op,
      exprs,
      SqlParserPos.ZERO);
}
 
Example #19
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 6 votes vote down vote up
protected SqlNode expandDynamicStar(SqlIdentifier id, SqlIdentifier fqId) {
	if (DynamicRecordType.isDynamicStarColName(Util.last(fqId.names))
		&& !DynamicRecordType.isDynamicStarColName(Util.last(id.names))) {
		// Convert a column ref into ITEM(*, 'col_name')
		// for a dynamic star field in dynTable's rowType.
		SqlNode[] inputs = new SqlNode[2];
		inputs[0] = fqId;
		inputs[1] = SqlLiteral.createCharString(
			Util.last(id.names),
			id.getParserPosition());
		return new SqlBasicCall(
			SqlStdOperatorTable.ITEM,
			inputs,
			id.getParserPosition());
	}
	return fqId;
}
 
Example #20
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 6 votes vote down vote up
@Nullable public SqlCall makeNullaryCall(SqlIdentifier id) {
	if (id.names.size() == 1 && !id.isComponentQuoted(0)) {
		final List<SqlOperator> list = new ArrayList<>();
		opTab.lookupOperatorOverloads(id, null, SqlSyntax.FUNCTION, list,
				catalogReader.nameMatcher());
		for (SqlOperator operator : list) {
			if (operator.getSyntax() == SqlSyntax.FUNCTION_ID) {
				// Even though this looks like an identifier, it is a
				// actually a call to a function. Construct a fake
				// call to this function, so we can use the regular
				// operator validation.
				return new SqlBasicCall(operator, SqlNode.EMPTY_ARRAY,
						id.getParserPosition(), true, null);
			}
		}
	}
	return null;
}
 
Example #21
Source File: RexSqlStandardConvertletTable.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * Creates and registers a convertlet for an operator in which
 * the SQL representation needs the result type appended
 * as an extra argument (e.g. CAST).
 *
 * @param op operator instance
 */
private void registerTypeAppendOp(final SqlOperator op) {
  registerOp(
      op, (converter, call) -> {
        SqlNode[] operands =
            convertExpressionList(converter, call.getOperands());
        if (operands == null) {
          return null;
        }
        List<SqlNode> operandList =
            new ArrayList<>(Arrays.asList(operands));
        SqlDataTypeSpec typeSpec =
            SqlTypeUtil.convertTypeToSpec(call.getType());
        operandList.add(typeSpec);
        return new SqlBasicCall(
            op,
            operandList.toArray(new SqlNode[0]),
            SqlParserPos.ZERO);
      });
}
 
Example #22
Source File: HsqldbSqlDialect.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public SqlNode rewriteSingleValueExpr(SqlNode aggCall) {
  final SqlNode operand = ((SqlBasicCall) aggCall).operand(0);
  final SqlLiteral nullLiteral = SqlLiteral.createNull(SqlParserPos.ZERO);
  final SqlNode unionOperand = SqlStdOperatorTable.VALUES.createCall(SqlParserPos.ZERO,
      SqlLiteral.createApproxNumeric("0", SqlParserPos.ZERO));
  // For hsqldb, generate
  //   CASE COUNT(*)
  //   WHEN 0 THEN NULL
  //   WHEN 1 THEN MIN(<result>)
  //   ELSE (VALUES 1 UNION ALL VALUES 1)
  //   END
  final SqlNode caseExpr =
      new SqlCase(SqlParserPos.ZERO,
          SqlStdOperatorTable.COUNT.createCall(SqlParserPos.ZERO, operand),
          SqlNodeList.of(
              SqlLiteral.createExactNumeric("0", SqlParserPos.ZERO),
              SqlLiteral.createExactNumeric("1", SqlParserPos.ZERO)),
          SqlNodeList.of(
              nullLiteral,
              SqlStdOperatorTable.MIN.createCall(SqlParserPos.ZERO, operand)),
          SqlStdOperatorTable.SCALAR_QUERY.createCall(SqlParserPos.ZERO,
              SqlStdOperatorTable.UNION_ALL
                  .createCall(SqlParserPos.ZERO, unionOperand, unionOperand)));

  LOGGER.debug("SINGLE_VALUE rewritten into [{}]", caseExpr);

  return caseExpr;
}
 
Example #23
Source File: SqlCreateTable.java    From flink with Apache License 2.0 5 votes vote down vote up
public boolean containsComputedColumn() {
	for (SqlNode column : columnList) {
		if (column instanceof SqlBasicCall) {
			return true;
		}
	}
	return false;
}
 
Example #24
Source File: MergeTableLikeUtilTest.java    From flink with Apache License 2.0 5 votes vote down vote up
private SqlNode tableColumn(String name, SqlNode expression) {
	return new SqlBasicCall(
		new SqlAsOperator(),
		new SqlNode[]{expression, identifier(name)},
		SqlParserPos.ZERO
	);
}
 
Example #25
Source File: MergeTableLikeUtilTest.java    From flink with Apache License 2.0 5 votes vote down vote up
private SqlNode plus(String column, String value) {
	return new SqlBasicCall(
		SqlStdOperatorTable.PLUS,
		new SqlNode[]{
			identifier(column), SqlLiteral.createExactNumeric(value, SqlParserPos.ZERO)},
		SqlParserPos.ZERO
	);
}
 
Example #26
Source File: MergeTableLikeUtilTest.java    From flink with Apache License 2.0 5 votes vote down vote up
private SqlNode boundedStrategy(String rowtimeColumn, String delay) {
	return new SqlBasicCall(
		SqlStdOperatorTable.MINUS,
		new SqlNode[]{
			identifier(rowtimeColumn),
			SqlLiteral.createInterval(
				1,
				delay,
				new SqlIntervalQualifier(TimeUnit.SECOND, TimeUnit.SECOND, SqlParserPos.ZERO),
				SqlParserPos.ZERO)
		},
		SqlParserPos.ZERO
	);
}
 
Example #27
Source File: SqlCreateTable.java    From flink with Apache License 2.0 5 votes vote down vote up
public boolean containsComputedColumn() {
	for (SqlNode column : columnList) {
		if (column instanceof SqlBasicCall) {
			return true;
		}
	}
	return false;
}
 
Example #28
Source File: RexSqlStandardConvertletTable.java    From Bats with Apache License 2.0 5 votes vote down vote up
public SqlNode convertCall(RexToSqlNodeConverter converter, RexCall call) {
  SqlNode[] operands = convertExpressionList(converter, call.getOperands());
  if (operands == null) {
    return null;
  }
  return new SqlBasicCall(op, operands, SqlParserPos.ZERO);
}
 
Example #29
Source File: DrillCompoundIdentifier.java    From Bats with Apache License 2.0 5 votes vote down vote up
public SqlNode getNode(SqlNode node) {
  SqlLiteral literal;
  if (isArray) {
    literal = SqlLiteral.createExactNumeric(value, parserPos);
  } else {
    literal = SqlLiteral.createCharString(value, parserPos);
  }
  return new SqlBasicCall(SqlStdOperatorTable.ITEM, new SqlNode[]{node, literal}, parserPos);
}
 
Example #30
Source File: MysqlSqlDialect.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public SqlNode rewriteSingleValueExpr(SqlNode aggCall) {
  final SqlNode operand = ((SqlBasicCall) aggCall).operand(0);
  final SqlLiteral nullLiteral = SqlLiteral.createNull(SqlParserPos.ZERO);
  final SqlNode unionOperand = new SqlSelect(SqlParserPos.ZERO, SqlNodeList.EMPTY,
      SqlNodeList.of(nullLiteral), null, null, null, null,
      SqlNodeList.EMPTY, null, null, null, SqlNodeList.EMPTY);
  // For MySQL, generate
  //   CASE COUNT(*)
  //   WHEN 0 THEN NULL
  //   WHEN 1 THEN <result>
  //   ELSE (SELECT NULL UNION ALL SELECT NULL)
  //   END
  final SqlNode caseExpr =
      new SqlCase(SqlParserPos.ZERO,
          SqlStdOperatorTable.COUNT.createCall(SqlParserPos.ZERO, operand),
          SqlNodeList.of(
              SqlLiteral.createExactNumeric("0", SqlParserPos.ZERO),
              SqlLiteral.createExactNumeric("1", SqlParserPos.ZERO)),
          SqlNodeList.of(
              nullLiteral,
              operand),
          SqlStdOperatorTable.SCALAR_QUERY.createCall(SqlParserPos.ZERO,
              SqlStdOperatorTable.UNION_ALL
                  .createCall(SqlParserPos.ZERO, unionOperand, unionOperand)));

  LOGGER.debug("SINGLE_VALUE rewritten into [{}]", caseExpr);

  return caseExpr;
}