Java Code Examples for org.apache.calcite.sql.SqlNode#getKind()

The following examples show how to use org.apache.calcite.sql.SqlNode#getKind() . 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: 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 2
Source File: SqlRollupOperator.java    From calcite with Apache License 2.0 6 votes vote down vote up
private void unparseCube(SqlWriter writer, SqlCall call) {
  writer.keyword(call.getOperator().getName());
  final SqlWriter.Frame frame =
      writer.startList(SqlWriter.FrameTypeEnum.FUN_CALL, "(", ")");
  for (SqlNode operand : call.getOperandList()) {
    writer.sep(",");
    if (operand.getKind() == SqlKind.ROW) {
      final SqlWriter.Frame frame2 =
          writer.startList(SqlWriter.FrameTypeEnum.SIMPLE, "(", ")");
      for (SqlNode operand2 : ((SqlCall) operand).getOperandList()) {
        writer.sep(",");
        operand2.unparse(writer, 0, 0);
      }
      writer.endList(frame2);
    } else if (operand instanceof SqlNodeList
        && ((SqlNodeList) operand).size() == 0) {
      writer.keyword("()");
    } else {
      operand.unparse(writer, 0, 0);
    }
  }
  writer.endList(frame);
}
 
Example 3
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
private SqlNode navigationInMeasure(SqlNode node, boolean allRows) {
	final Set<String> prefix = node.accept(new PatternValidator(true));
	Util.discard(prefix);
	final List<SqlNode> ops = ((SqlCall) node).getOperandList();

	final SqlOperator defaultOp =
		allRows ? SqlStdOperatorTable.RUNNING : SqlStdOperatorTable.FINAL;
	final SqlNode op0 = ops.get(0);
	if (!isRunningOrFinal(op0.getKind())
		|| !allRows && op0.getKind() == SqlKind.RUNNING) {
		SqlNode newNode = defaultOp.createCall(SqlParserPos.ZERO, op0);
		node = SqlStdOperatorTable.AS.createCall(SqlParserPos.ZERO, newNode, ops.get(1));
	}

	node = new NavigationExpander().go(node);
	return node;
}
 
Example 4
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 5 votes vote down vote up
private void lookupFromHints(
	SqlNode node,
	SqlValidatorScope scope,
	SqlParserPos pos,
	Collection<SqlMoniker> hintList) {
	if (node == null) {
		// This can happen in cases like "select * _suggest_", so from clause is absent
		return;
	}
	final SqlValidatorNamespace ns = getNamespace(node);
	if (ns.isWrapperFor(IdentifierNamespace.class)) {
		IdentifierNamespace idNs = ns.unwrap(IdentifierNamespace.class);
		final SqlIdentifier id = idNs.getId();
		for (int i = 0; i < id.names.size(); i++) {
			if (pos.toString().equals(
				id.getComponent(i).getParserPosition().toString())) {
				final List<SqlMoniker> objNames = new ArrayList<>();
				SqlValidatorUtil.getSchemaObjectMonikers(
					getCatalogReader(),
					id.names.subList(0, i + 1),
					objNames);
				for (SqlMoniker objName : objNames) {
					if (objName.getType() != SqlMonikerType.FUNCTION) {
						hintList.add(objName);
					}
				}
				return;
			}
		}
	}
	switch (node.getKind()) {
		case JOIN:
			lookupJoinHints((SqlJoin) node, scope, pos, hintList);
			break;
		default:
			lookupSelectHints(ns, pos, hintList);
			break;
	}
}
 
Example 5
Source File: HiveTableSqlFunction.java    From flink with Apache License 2.0 5 votes vote down vote up
private static Object getValue(SqlNode right) throws NonLiteralException {
	switch (right.getKind()) {
		case ARRAY_VALUE_CONSTRUCTOR:
			final List<Object> list = new ArrayList<>();
			for (SqlNode o : ((SqlCall) right).getOperandList()) {
				list.add(getValue(o));
			}
			return ImmutableNullableList.copyOf(list).toArray();
		case MAP_VALUE_CONSTRUCTOR:
			final Map<Object, Object> map = new HashMap<>();
			final List<SqlNode> operands = ((SqlCall) right).getOperandList();
			for (int i = 0; i < operands.size(); i += 2) {
				final SqlNode key = operands.get(i);
				final SqlNode value = operands.get(i + 1);
				map.put(getValue(key), getValue(value));
			}
			return map;
		default:
			if (SqlUtil.isNullLiteral(right, true)) {
				return null;
			}
			if (SqlUtil.isLiteral(right)) {
				return ((SqlLiteral) right).getValue();
			}
			if (right.getKind() == SqlKind.DEFAULT) {
				return null; // currently NULL is the only default value
			}
			throw new NonLiteralException();
	}
}
 
Example 6
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 5 votes vote down vote up
private static boolean isLateral(SqlNode node) {
	switch (node.getKind()) {
		case LATERAL:
		case UNNEST:
			// Per SQL std, UNNEST is implicitly LATERAL.
			return true;
		case AS:
			return isLateral(((SqlCall) node).operand(0));
		default:
			return false;
	}
}
 
Example 7
Source File: HiveTableSqlFunction.java    From flink with Apache License 2.0 5 votes vote down vote up
private static Object getValue(SqlNode right) throws NonLiteralException {
	switch (right.getKind()) {
		case ARRAY_VALUE_CONSTRUCTOR:
			final List<Object> list = new ArrayList<>();
			for (SqlNode o : ((SqlCall) right).getOperandList()) {
				list.add(getValue(o));
			}
			return ImmutableNullableList.copyOf(list).toArray();
		case MAP_VALUE_CONSTRUCTOR:
			final Map<Object, Object> map = new HashMap<>();
			final List<SqlNode> operands = ((SqlCall) right).getOperandList();
			for (int i = 0; i < operands.size(); i += 2) {
				final SqlNode key = operands.get(i);
				final SqlNode value = operands.get(i + 1);
				map.put(getValue(key), getValue(value));
			}
			return map;
		default:
			if (SqlUtil.isNullLiteral(right, true)) {
				return null;
			}
			if (SqlUtil.isLiteral(right)) {
				return ((SqlLiteral) right).getValue();
			}
			if (right.getKind() == SqlKind.DEFAULT) {
				return null; // currently NULL is the only default value
			}
			throw new NonLiteralException();
	}
}
 
Example 8
Source File: SqlParseUtil.java    From alchemy with Apache License 2.0 5 votes vote down vote up
public static List<String> findQuerySql(List<String> sqls)
    throws SqlParseException {
    List<String> newSqls = new ArrayList<>(sqls.size());
    for (String sql : sqls) {
        SqlParser sqlParser = SqlParser.create(sql, CONFIG);
        SqlNode sqlNode = sqlParser.parseStmt();
        if (sqlNode.getKind() != SqlKind.INSERT) {
            throw new IllegalArgumentException("It must be an insert SQL, sql:" + sql);
        }
        SqlInsert sqlInsert = (SqlInsert)sqlNode;
        newSqls.add(sqlInsert.getSource().toString());
    }
    return newSqls;
}
 
Example 9
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
private void lookupFromHints(
	SqlNode node,
	SqlValidatorScope scope,
	SqlParserPos pos,
	Collection<SqlMoniker> hintList) {
	final SqlValidatorNamespace ns = getNamespace(node);
	if (ns.isWrapperFor(IdentifierNamespace.class)) {
		IdentifierNamespace idNs = ns.unwrap(IdentifierNamespace.class);
		final SqlIdentifier id = idNs.getId();
		for (int i = 0; i < id.names.size(); i++) {
			if (pos.toString().equals(
				id.getComponent(i).getParserPosition().toString())) {
				final List<SqlMoniker> objNames = new ArrayList<>();
				SqlValidatorUtil.getSchemaObjectMonikers(
					getCatalogReader(),
					id.names.subList(0, i + 1),
					objNames);
				for (SqlMoniker objName : objNames) {
					if (objName.getType() != SqlMonikerType.FUNCTION) {
						hintList.add(objName);
					}
				}
				return;
			}
		}
	}
	switch (node.getKind()) {
		case JOIN:
			lookupJoinHints((SqlJoin) node, scope, pos, hintList);
			break;
		default:
			lookupSelectHints(ns, pos, hintList);
			break;
	}
}
 
Example 10
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
/** Returns whether a query uses {@code DEFAULT} to populate a given
 *  column. */
private boolean isValuesWithDefault(SqlNode source, int column) {
	switch (source.getKind()) {
		case VALUES:
			for (SqlNode operand : ((SqlCall) source).getOperandList()) {
				if (!isRowWithDefault(operand, column)) {
					return false;
				}
			}
			return true;
	}
	return false;
}
 
Example 11
Source File: SqlParseUtil.java    From alchemy with Apache License 2.0 5 votes vote down vote up
private static void parseFrom(SqlNode from, List<String> sources, List<String> udfs) throws SqlParseException {
    SqlKind sqlKind = from.getKind();
    switch (sqlKind) {
        case IDENTIFIER:
            SqlIdentifier identifier = (SqlIdentifier)from;
            addSource(sources, identifier.getSimple());
            break;
        case AS:
            SqlBasicCall sqlBasicCall = (SqlBasicCall)from;
            parseFrom(sqlBasicCall.operand(0), sources, udfs);
            break;
        case SELECT:
            parseSource((SqlSelect)from, sources, udfs);
            break;
        case JOIN:
            SqlJoin sqlJoin = (SqlJoin)from;
            SqlNode left = sqlJoin.getLeft();
            SqlNode right = sqlJoin.getRight();
            parseFrom(left, sources, udfs);
            parseFrom(right, sources, udfs);
            break;
        case LATERAL:
            SqlBasicCall basicCall = (SqlBasicCall)from;
            SqlNode childNode = basicCall.getOperands()[0];
            parseFunction(childNode, udfs);
        default:
    }
}
 
Example 12
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 5 votes vote down vote up
private boolean isRowWithDefault(SqlNode operand, int column) {
	switch (operand.getKind()) {
		case ROW:
			final SqlCall row = (SqlCall) operand;
			return row.getOperandList().size() >= column
				&& row.getOperandList().get(column).getKind() == SqlKind.DEFAULT;
	}
	return false;
}
 
Example 13
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 5 votes vote down vote up
private void registerSubQueries(
	SqlValidatorScope parentScope,
	SqlNode node) {
	if (node == null) {
		return;
	}
	if (node.getKind().belongsTo(SqlKind.QUERY)
		|| node.getKind() == SqlKind.MULTISET_QUERY_CONSTRUCTOR
		|| node.getKind() == SqlKind.MULTISET_VALUE_CONSTRUCTOR) {
		registerQuery(parentScope, null, node, node, null, false);
	} else if (node instanceof SqlCall) {
		validateNodeFeature(node);
		SqlCall call = (SqlCall) node;
		for (int i = 0; i < call.operandCount(); i++) {
			registerOperandSubQueries(parentScope, call, i);
		}
	} else if (node instanceof SqlNodeList) {
		SqlNodeList list = (SqlNodeList) node;
		for (int i = 0, count = list.size(); i < count; i++) {
			SqlNode listNode = list.get(i);
			if (listNode.getKind().belongsTo(SqlKind.QUERY)) {
				listNode =
					SqlStdOperatorTable.SCALAR_QUERY.createCall(
						listNode.getParserPosition(),
						listNode);
				list.set(i, listNode);
			}
			registerSubQueries(parentScope, listNode);
		}
	} else {
		// atomic node -- can be ignored
	}
}
 
Example 14
Source File: SideParser.java    From alchemy with 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 15
Source File: IdentifierNamespace.java    From Bats with Apache License 2.0 5 votes vote down vote up
protected static Pair<SqlIdentifier, SqlNodeList> split(SqlNode node) {
  switch (node.getKind()) {
  case EXTEND:
    final SqlCall call = (SqlCall) node;
    return Pair.of((SqlIdentifier) call.getOperandList().get(0),
        (SqlNodeList) call.getOperandList().get(1));
  default:
    return Pair.of((SqlIdentifier) node, null);
  }
}
 
Example 16
Source File: SqlImplementor.java    From calcite with Apache License 2.0 4 votes vote down vote up
/** Returns the row type of {@code rel}, adjusting the field names if
 * {@code node} is "(query) as tableAlias (fieldAlias, ...)". */
private RelDataType adjustedRowType(RelNode rel, SqlNode node) {
  final RelDataType rowType = rel.getRowType();
  final RelDataTypeFactory.Builder builder;
  switch (node.getKind()) {
  case UNION:
  case INTERSECT:
  case EXCEPT:
    return adjustedRowType(rel, ((SqlCall) node).getOperandList().get(0));

  case SELECT:
    final SqlNodeList selectList = ((SqlSelect) node).getSelectList();
    if (selectList == null) {
      return rowType;
    }
    builder = rel.getCluster().getTypeFactory().builder();
    Pair.forEach(selectList,
        rowType.getFieldList(),
        (selectItem, field) ->
            builder.add(
                Util.first(SqlValidatorUtil.getAlias(selectItem, -1),
                    field.getName()),
                field.getType()));
    return builder.build();

  case AS:
    final List<SqlNode> operandList = ((SqlCall) node).getOperandList();
    if (operandList.size() <= 2) {
      return rowType;
    }
    builder = rel.getCluster().getTypeFactory().builder();
    Pair.forEach(Util.skip(operandList, 2),
        rowType.getFieldList(),
        (operand, field) ->
            builder.add(operand.toString(), field.getType()));
    return builder.build();

  default:
    return rowType;
  }
}
 
Example 17
Source File: QuerySemantics.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
private static boolean isSimpleID(SqlNode node) {
  return node.getKind() == IDENTIFIER && ((SqlIdentifier)node).isSimple();
}
 
Example 18
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
private SqlNode stripDot(SqlNode node) {
	if (node != null && node.getKind() == SqlKind.DOT) {
		return stripDot(((SqlCall) node).operand(0));
	}
	return node;
}
 
Example 19
Source File: DremioRelToSqlConverter.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
private List<SqlNode> addJoinChildSelectNodes(SqlNode node, Set<String> usedNames) {
  final SqlNode childNode = (node.getKind() == SqlKind.AS) ? ((SqlBasicCall) node).getOperands()[0] : node;

  if (childNode.getKind() == SqlKind.JOIN) {
    final SqlJoin join = (SqlJoin)childNode;
    // Delegate to the children of the join to get the node list.
    final List<SqlNode> leftList = addJoinChildSelectNodes(join.getLeft(), usedNames);
    final List<SqlNode> rightList = addJoinChildSelectNodes(join.getRight(), usedNames);
    if (leftList == null || rightList == null) {
      // Not possible to get the nodes of one or the other child, abandon the effort.
      return null;
    }

    return ImmutableList.<SqlNode>builder().addAll(leftList).addAll(rightList).build();
  }

  if (childNode.getKind() != SqlKind.SELECT || ((SqlSelect)childNode).getSelectList() == null) {
    return null;
  }

  // Although we are expanding the * into a list of column references, don't do anything but the expansion as
  // the underlying references will have any necessary modifications (ie addition of explicit casts) done to them
  // already.
  final String tableAlias = SqlValidatorUtil.getAlias(node, -1);
  final List<SqlNode> selectList = new ArrayList<>();
  ((SqlSelect) childNode).getSelectList().getList().stream().forEach(n -> {
    String colAlias = SqlValidatorUtil.getAlias(n, -1);
    if (null == colAlias) {
      // Guard against possible null aliases being returned by generating a unique value.
      colAlias = SqlValidatorUtil.uniquify(colAlias, usedNames, SqlValidatorUtil.EXPR_SUGGESTER);
    } else if (colAlias.equals("\"*\"")) {
      // If * is used as an alias, it ends up getting double quoted when it should not be.
      colAlias = "*";
    }
    final List<String> names = (tableAlias != null) ? ImmutableList.of(tableAlias, colAlias) : ImmutableList.of(colAlias);

    if (n.getKind() == SqlKind.IDENTIFIER) {
      // Ensure we have unique names being used.
      final String alias = SqlValidatorUtil.uniquify(colAlias, usedNames, SqlValidatorUtil.EXPR_SUGGESTER);

      selectList.add(SqlStdOperatorTable.AS.createCall(
        POS,
        new SqlIdentifier(names, n.getParserPosition()),
        new SqlIdentifier(alias, POS)));
    } else if (n.getKind() == SqlKind.AS) {
      selectList.add(new SqlIdentifier(names, POS));
    } else {
      selectList.add(n);
    }

    usedNames.add(colAlias);
  });

  return selectList;
}
 
Example 20
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 4 votes vote down vote up
@Override public SqlNode visit(SqlCall call) {
	SqlKind kind = call.getKind();
	List<SqlNode> operands = call.getOperandList();
	List<SqlNode> newOperands = new ArrayList<>();

	// This code is a workaround for CALCITE-2707
	if (call.getFunctionQuantifier() != null
		&& call.getFunctionQuantifier().getValue() == SqlSelectKeyword.DISTINCT) {
		final SqlParserPos pos = call.getParserPosition();
		throw SqlUtil.newContextException(pos, Static.RESOURCE.functionQuantifierNotAllowed(call.toString()));
	}
	// This code is a workaround for CALCITE-2707

	if (isLogicalNavigation(kind) || isPhysicalNavigation(kind)) {
		SqlNode inner = operands.get(0);
		SqlNode offset = operands.get(1);

		// merge two straight prev/next, update offset
		if (isPhysicalNavigation(kind)) {
			SqlKind innerKind = inner.getKind();
			if (isPhysicalNavigation(innerKind)) {
				List<SqlNode> innerOperands = ((SqlCall) inner).getOperandList();
				SqlNode innerOffset = innerOperands.get(1);
				SqlOperator newOperator = innerKind == kind
					? SqlStdOperatorTable.PLUS : SqlStdOperatorTable.MINUS;
				offset = newOperator.createCall(SqlParserPos.ZERO,
					offset, innerOffset);
				inner = call.getOperator().createCall(SqlParserPos.ZERO,
					innerOperands.get(0), offset);
			}
		}
		SqlNode newInnerNode =
			inner.accept(new NavigationExpander(call.getOperator(), offset));
		if (op != null) {
			newInnerNode = op.createCall(SqlParserPos.ZERO, newInnerNode,
				this.offset);
		}
		return newInnerNode;
	}

	if (operands.size() > 0) {
		for (SqlNode node : operands) {
			if (node != null) {
				SqlNode newNode = node.accept(new NavigationExpander());
				if (op != null) {
					newNode = op.createCall(SqlParserPos.ZERO, newNode, offset);
				}
				newOperands.add(newNode);
			} else {
				newOperands.add(null);
			}
		}
		return call.getOperator().createCall(SqlParserPos.ZERO, newOperands);
	} else {
		if (op == null) {
			return call;
		} else {
			return op.createCall(SqlParserPos.ZERO, call, offset);
		}
	}
}