Java Code Examples for org.apache.calcite.sql.SqlBasicCall

The following examples show how to use org.apache.calcite.sql.SqlBasicCall. These examples are extracted from open source projects. 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 Project: Bats   Source File: SqlImplementor.java    License: 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 2
Source Project: Bats   Source File: RexSqlStandardConvertletTable.java    License: 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 3
Source Project: Bats   Source File: RexSqlStandardConvertletTable.java    License: 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 4
Source Project: Bats   Source File: DrillConvertletTable.java    License: 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 5
Source Project: flink   Source File: SqlValidatorImpl.java    License: 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 6
Source Project: flink   Source File: SqlValidatorImpl.java    License: 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 7
Source Project: alchemy   Source File: SideParser.java    License: 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 8
Source Project: alchemy   Source File: SideParser.java    License: 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 9
Source Project: alchemy   Source File: SideParser.java    License: 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 10
Source Project: alchemy   Source File: MysqlSideFunction.java    License: 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 11
Source Project: alchemy   Source File: SqlParseUtil.java    License: 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 12
Source Project: sylph   Source File: CalciteSqlParser.java    License: 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 13
Source Project: sylph   Source File: FlinkSqlParser.java    License: 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 14
Source Project: dremio-oss   Source File: SqlImplementor.java    License: 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 15
Source Project: samza   Source File: SamzaSqlQueryParser.java    License: 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 16
Source Project: calcite   Source File: SqlImplementor.java    License: 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 17
Source Project: calcite   Source File: RelToSqlConverter.java    License: 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 18
Source Project: calcite   Source File: RexSqlStandardConvertletTable.java    License: 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 Project: calcite   Source File: RexSqlStandardConvertletTable.java    License: 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 20
Source Project: incubator-pinot   Source File: CalciteSqlParser.java    License: 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 21
Source Project: incubator-pinot   Source File: CalciteSqlParser.java    License: 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 22
Source Project: Bats   Source File: HsqldbSqlDialect.java    License: 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 Project: Bats   Source File: MysqlSqlDialect.java    License: 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);
  // 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;
}
 
Example 24
Source Project: Bats   Source File: RexSqlStandardConvertletTable.java    License: 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 25
Source Project: Bats   Source File: DrillCompoundIdentifier.java    License: 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 26
Source Project: Flink-CEPplus   Source File: SqlValidatorImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override public SqlNode visit(SqlIdentifier id) {
	// First check for builtin functions which don't have
	// parentheses, like "LOCALTIME".
	SqlCall call =
		SqlUtil.makeCall(
			validator.getOperatorTable(),
			id);
	if (call != null) {
		return call.accept(this);
	}
	final SqlIdentifier fqId = getScope().fullyQualify(id).identifier;
	SqlNode expandedExpr = fqId;
	// Convert a column ref into ITEM(*, 'col_name').
	// select col_name from (select * from dynTable)
	// SqlIdentifier "col_name" would be resolved to a dynamic star field in dynTable's rowType.
	// Expand such SqlIdentifier to ITEM operator.
	if (DynamicRecordType.isDynamicStarColName(Util.last(fqId.names))
		&& !DynamicRecordType.isDynamicStarColName(Util.last(id.names))) {
		SqlNode[] inputs = new SqlNode[2];
		inputs[0] = fqId;
		inputs[1] = SqlLiteral.createCharString(
			Util.last(id.names),
			id.getParserPosition());
		SqlBasicCall item_call = new SqlBasicCall(
			SqlStdOperatorTable.ITEM,
			inputs,
			id.getParserPosition());
		expandedExpr = item_call;
	}
	validator.setOriginal(expandedExpr, id);
	return expandedExpr;
}
 
Example 27
Source Project: flink   Source File: SqlCreateTable.java    License: 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 Project: alchemy   Source File: SideParser.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *  select a.name , a.age , FUN(a.weight) as weight from test  -->  { name , age , weight}
 * @param selectList
 * @return
 */
public static List<String> findSelectField(SqlNodeList selectList){
    List<SqlNode> nodes = selectList.getList();
    List<String> fields = new ArrayList<>();
    for (SqlNode node : nodes){
        SqlKind kind = node.getKind();
        String field;
        switch (kind){
            case AS:
                SqlBasicCall call = (SqlBasicCall) node;
                field = findField(call.operand(0));
                break;
            case IDENTIFIER:
                field = findField(node);
                break;
            default:
                throw new UnsupportedOperationException("Don't supported findSelectField in" + node);
        }
        if (StringUtils.isEmpty(field)){
            // a.*
            return Collections.emptyList();
        }else{
            fields.add(field);
        }
    }
    return fields;
}
 
Example 29
Source Project: alchemy   Source File: SideParser.java    License: Apache License 2.0 5 votes vote down vote up
public static List<String> findConditionFields(SqlNode conditionNode, String specifyTableName){
    List<SqlNode> sqlNodeList = Lists.newArrayList();
    if(conditionNode.getKind() == SqlKind.AND){
        sqlNodeList.addAll(Lists.newArrayList(((SqlBasicCall)conditionNode).getOperands()));
    }else{
        sqlNodeList.add(conditionNode);
    }

    List<String> conditionFields = Lists.newArrayList();
    for(SqlNode sqlNode : sqlNodeList){
        if(sqlNode.getKind() != SqlKind.EQUALS){
            throw new RuntimeException("not equal operator.");
        }
        SqlIdentifier left = (SqlIdentifier)((SqlBasicCall)sqlNode).getOperands()[0];
        SqlIdentifier right = (SqlIdentifier)((SqlBasicCall)sqlNode).getOperands()[1];

        String leftTableName = left.names.get(0);
        String rightTableName = right.names.get(0);

        String tableCol;
        if(leftTableName.equalsIgnoreCase(specifyTableName)){
            tableCol = left.names.get(1);
        }else if(rightTableName.equalsIgnoreCase(specifyTableName)){
            tableCol = right.names.get(1);
        }else{
            throw new RuntimeException(String.format("side table:%s join condition is wrong", specifyTableName));
        }
        conditionFields.add(tableCol);
    }

    return conditionFields;
}
 
Example 30
Source Project: alchemy   Source File: MysqlSideFunction.java    License: Apache License 2.0 5 votes vote down vote up
private String modifySql(SideTable sideTable) throws SqlParseException {
    SqlParser.Config config = SqlParser.configBuilder().setLex(Lex.MYSQL).build();
    SqlParser sqlParser = SqlParser.create(sideTable.getSql(), config);
    SqlNode sqlNode = sqlParser.parseStmt();
    if (SqlKind.SELECT != sqlNode.getKind()) {
        throw new UnsupportedOperationException(
            "MysqlAsyncReqRow only support query sql, sql:" + sideTable.getSql());
    }
    SqlSelect sqlSelect = (SqlSelect)sqlNode;
    SqlNode whereNode = sqlSelect.getWhere();
    SqlBinaryOperator and = new SqlBinaryOperator("AND", SqlKind.AND, 24, true,
        ReturnTypes.BOOLEAN_NULLABLE_OPTIMIZED, InferTypes.BOOLEAN, OperandTypes.BOOLEAN_BOOLEAN);
    List<SqlBasicCall> conditionNodes = createConditionNodes(sideTable.getConditions(), sideTable.getSideAlias());
    List<SqlNode> nodes = new ArrayList<>();
    nodes.addAll(conditionNodes);
    if (whereNode != null) {
        nodes.add(whereNode);
    } else {
        SqlBinaryOperator equal = new SqlBinaryOperator("=", SqlKind.EQUALS, 30, true, ReturnTypes.BOOLEAN_NULLABLE,
            InferTypes.FIRST_KNOWN, OperandTypes.COMPARABLE_UNORDERED_COMPARABLE_UNORDERED);
        SqlBasicCall andEqual
            = new SqlBasicCall(equal, SideParser.createEqualNodes(SqlKind.AND), new SqlParserPos(0, 0));
        nodes.add(andEqual);
    }
    SqlBasicCall sqlBasicCall
        = new SqlBasicCall(and, nodes.toArray(new SqlNode[nodes.size()]), new SqlParserPos(0, 0));
    sqlSelect.setWhere(sqlBasicCall);
    return sqlSelect.toString();
}