org.apache.calcite.sql.SqlJoin Java Examples

The following examples show how to use org.apache.calcite.sql.SqlJoin. 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: RelToSqlConverter.java    From quark with Apache License 2.0 6 votes vote down vote up
public Result visitJoin(Join e) {
  final Result leftResult = visitChild(0, e.getLeft());
  final Result rightResult = visitChild(1, e.getRight());
  final Context leftContext = leftResult.qualifiedContext();
  final Context rightContext =
      rightResult.qualifiedContext();
  SqlNode sqlCondition = convertConditionToSqlNode(e.getCondition(),
      leftContext,
      rightContext,
      e.getLeft().getRowType().getFieldCount());
  SqlNode join =
      new SqlJoin(POS,
          leftResult.asFrom(),
          SqlLiteral.createBoolean(false, POS),
          joinType(e.getJoinType()).symbol(POS),
          rightResult.asFrom(),
          JoinConditionType.ON.symbol(POS),
          sqlCondition);
  return result(join, leftResult, rightResult);
}
 
Example #2
Source File: DremioSqlDialect.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public void unparseCall(SqlWriter writer, SqlCall call, int leftPrec, int rightPrec) {
  // Translate the PI function call to PI()
  if (call.getOperator() == SqlStdOperatorTable.PI) {
    super.unparseCall(
      writer,
      PI_FUNCTION.createCall(new SqlNodeList(call.getOperandList(), SqlParserPos.ZERO)),
      leftPrec, rightPrec);
  } else if (call.getOperator().equals(FunctionRegistry.E_FUNCTION)) {
    // Translate the E() function call to EXP(1)
    final SqlCall newCall = SqlStdOperatorTable.EXP.createCall(
      SqlParserPos.ZERO, SqlLiteral.createExactNumeric("1", SqlParserPos.ZERO));
    super.unparseCall(writer, newCall, leftPrec, rightPrec);
  } else if (call.getKind() == SqlKind.JOIN) {
    this.unparseJoin(writer, (SqlJoin) call, leftPrec, rightPrec);
  } else {
    super.unparseCall(writer, call, leftPrec, rightPrec);
  }
}
 
Example #3
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 #4
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 #5
Source File: SideParser.java    From alchemy with Apache License 2.0 6 votes vote down vote up
public static SqlSelect newSelect(SqlSelect selectSelf, String table, String alias, boolean left, boolean newTable) {
    List<SqlNode> operand = selectSelf.getOperandList();
    SqlNodeList keywordList = (SqlNodeList)operand.get(0);
    SqlNodeList selectList = (SqlNodeList)operand.get(1);
    SqlNode from = operand.get(2);
    SqlNode where = operand.get(3);
    SqlNodeList groupBy = (SqlNodeList)operand.get(4);
    SqlNode having = operand.get(5);
    SqlNodeList windowDecls = (SqlNodeList)operand.get(6);
    SqlNodeList orderBy = (SqlNodeList)operand.get(7);
    SqlNode offset = operand.get(8);
    SqlNode fetch = operand.get(9);
    if (left) {
        return newSelect(selectSelf.getParserPosition(), keywordList, selectList, ((SqlJoin)from).getLeft(), where,
            groupBy, having, windowDecls, orderBy, offset, fetch, alias, newTable);
    }
    if (newTable) {
        return newSelect(selectSelf.getParserPosition(), null,  creatFullNewSelectList(alias, selectList), createNewFrom(table, alias, from),
            where, groupBy, having, windowDecls, orderBy, offset, fetch, alias, newTable);
    } else {
        return newSelect(selectSelf.getParserPosition(), null, selectList, ((SqlJoin)from).getRight(), where,
            groupBy, having, windowDecls, orderBy, offset, fetch, alias, newTable);
    }

}
 
Example #6
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 #7
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 6 votes vote down vote up
/** Returns the set of field names in the join condition specified by USING
 * or implicitly by NATURAL, de-duplicated and in order. */
private List<String> usingNames(SqlJoin join) {
	switch (join.getConditionType()) {
		case USING:
			final ImmutableList.Builder<String> list = ImmutableList.builder();
			final Set<String> names = catalogReader.nameMatcher().createSet();
			for (SqlNode node : (SqlNodeList) join.getCondition()) {
				final String name = ((SqlIdentifier) node).getSimple();
				if (names.add(name)) {
					list.add(name);
				}
			}
			return list.build();
		case NONE:
			if (join.isNatural()) {
				final RelDataType t0 = getValidatedNodeType(join.getLeft());
				final RelDataType t1 = getValidatedNodeType(join.getRight());
				return SqlValidatorUtil.deriveNaturalJoinColumnList(
					catalogReader.nameMatcher(), t0, t1);
			}
	}
	return null;
}
 
Example #8
Source File: FlinkCalciteSqlValidator.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
protected void validateJoin(SqlJoin join, SqlValidatorScope scope) {
	// Due to the improper translation of lateral table left outer join in Calcite, we need to
	// temporarily forbid the common predicates until the problem is fixed (see FLINK-7865).
	if (join.getJoinType() == JoinType.LEFT &&
			SqlUtil.stripAs(join.getRight()).getKind() == SqlKind.COLLECTION_TABLE) {
		final SqlNode condition = join.getCondition();
		if (condition != null &&
				(!SqlUtil.isLiteral(condition) || ((SqlLiteral) condition).getValueAs(Boolean.class) != Boolean.TRUE)) {
			throw new ValidationException(
				String.format(
					"Left outer joins with a table function do not accept a predicate such as %s. " +
					"Only literal TRUE is accepted.",
					condition));
		}
	}
	super.validateJoin(join, scope);
}
 
Example #9
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/** Returns the set of field names in the join condition specified by USING
 * or implicitly by NATURAL, de-duplicated and in order. */
private List<String> usingNames(SqlJoin join) {
	switch (join.getConditionType()) {
		case USING:
			final ImmutableList.Builder<String> list = ImmutableList.builder();
			final Set<String> names = catalogReader.nameMatcher().createSet();
			for (SqlNode node : (SqlNodeList) join.getCondition()) {
				final String name = ((SqlIdentifier) node).getSimple();
				if (names.add(name)) {
					list.add(name);
				}
			}
			return list.build();
		case NONE:
			if (join.isNatural()) {
				final RelDataType t0 = getValidatedNodeType(join.getLeft());
				final RelDataType t1 = getValidatedNodeType(join.getRight());
				return SqlValidatorUtil.deriveNaturalJoinColumnList(
					catalogReader.nameMatcher(), t0, t1);
			}
	}
	return null;
}
 
Example #10
Source File: FlinkCalciteSqlValidator.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
protected void validateJoin(SqlJoin join, SqlValidatorScope scope) {
	// Due to the improper translation of lateral table left outer join in Calcite, we need to
	// temporarily forbid the common predicates until the problem is fixed (see FLINK-7865).
	if (join.getJoinType() == JoinType.LEFT &&
			SqlUtil.stripAs(join.getRight()).getKind() == SqlKind.COLLECTION_TABLE) {
		final SqlNode condition = join.getCondition();
		if (condition != null &&
				(!SqlUtil.isLiteral(condition) || ((SqlLiteral) condition).getValueAs(Boolean.class) != Boolean.TRUE)) {
			throw new ValidationException(
				String.format(
					"Left outer joins with a table function do not accept a predicate such as %s. " +
					"Only literal TRUE is accepted.",
					condition));
		}
	}
	super.validateJoin(join, scope);
}
 
Example #11
Source File: Lattice.java    From calcite with Apache License 2.0 6 votes vote down vote up
private static void populateAliases(SqlNode from, List<String> aliases,
    @Nullable String current) {
  if (from instanceof SqlJoin) {
    SqlJoin join = (SqlJoin) from;
    populateAliases(join.getLeft(), aliases, null);
    populateAliases(join.getRight(), aliases, null);
  } else if (from.getKind() == SqlKind.AS) {
    populateAliases(SqlUtil.stripAs(from), aliases,
        SqlValidatorUtil.getAlias(from, -1));
  } else {
    if (current == null) {
      current = SqlValidatorUtil.getAlias(from, -1);
    }
    aliases.add(current);
  }
}
 
Example #12
Source File: RelToSqlConverter.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** @see #dispatch */
public Result visit(Correlate e) {
  final Result leftResult =
      visitChild(0, e.getLeft())
          .resetAlias(e.getCorrelVariable(), e.getRowType());
  parseCorrelTable(e, leftResult);
  final Result rightResult = visitChild(1, e.getRight());
  final SqlNode rightLateral =
      SqlStdOperatorTable.LATERAL.createCall(POS, rightResult.node);
  final SqlNode rightLateralAs =
      SqlStdOperatorTable.AS.createCall(POS, rightLateral,
          new SqlIdentifier(rightResult.neededAlias, POS));

  final SqlNode join =
      new SqlJoin(POS,
          leftResult.asFrom(),
          SqlLiteral.createBoolean(false, POS),
          JoinType.COMMA.symbol(POS),
          rightLateralAs,
          JoinConditionType.NONE.symbol(POS),
          null);
  return result(join, leftResult, rightResult);
}
 
Example #13
Source File: Lattice.java    From Bats with Apache License 2.0 6 votes vote down vote up
private static void populateAliases(SqlNode from, List<String> aliases,
    String current) {
  if (from instanceof SqlJoin) {
    SqlJoin join = (SqlJoin) from;
    populateAliases(join.getLeft(), aliases, null);
    populateAliases(join.getRight(), aliases, null);
  } else if (from.getKind() == SqlKind.AS) {
    populateAliases(SqlUtil.stripAs(from), aliases,
        SqlValidatorUtil.getAlias(from, -1));
  } else {
    if (current == null) {
      current = SqlValidatorUtil.getAlias(from, -1);
    }
    aliases.add(current);
  }
}
 
Example #14
Source File: RelToSqlConverter.java    From Bats with Apache License 2.0 5 votes vote down vote up
/** @see #dispatch */
public Result visit(Join e) {
  final Result leftResult = visitChild(0, e.getLeft()).resetAlias();
  final Result rightResult = visitChild(1, e.getRight()).resetAlias();
  final Context leftContext = leftResult.qualifiedContext();
  final Context rightContext = rightResult.qualifiedContext();
  SqlNode sqlCondition = null;
  SqlLiteral condType = JoinConditionType.ON.symbol(POS);
  JoinType joinType = joinType(e.getJoinType());
  if (isCrossJoin(e)) {
    joinType = dialect.emulateJoinTypeForCrossJoin();
    condType = JoinConditionType.NONE.symbol(POS);
  } else {
    sqlCondition = convertConditionToSqlNode(e.getCondition(),
        leftContext,
        rightContext,
        e.getLeft().getRowType().getFieldCount());
  }
  SqlNode join =
      new SqlJoin(POS,
          leftResult.asFrom(),
          SqlLiteral.createBoolean(false, POS),
          joinType.symbol(POS),
          rightResult.asFrom(),
          condType,
          sqlCondition);
  return result(join, leftResult, rightResult);
}
 
Example #15
Source File: RuleParser.java    From streamline with Apache License 2.0 5 votes vote down vote up
private List<Stream> parseStreams(SqlSelect sqlSelect) throws Exception {
    List<Stream> streams = new ArrayList<>();
    SqlNode sqlFrom = sqlSelect.getFrom();
    LOG.debug("from = {}", sqlFrom);
    if (sqlFrom instanceof SqlJoin) {
        throw new IllegalArgumentException("Sql join is not yet supported");
    } else if (sqlFrom instanceof SqlIdentifier) {
        streams.add(getStream(((SqlIdentifier) sqlFrom).getSimple()));
    }
    LOG.debug("Streams {}", streams);
    return streams;
}
 
Example #16
Source File: RelToSqlConverter.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** @see #dispatch */
public Result visit(Join e) {
  if (e.getJoinType() == JoinRelType.ANTI || e.getJoinType() == JoinRelType.SEMI) {
    return visitAntiOrSemiJoin(e);
  }
  final Result leftResult = visitChild(0, e.getLeft()).resetAlias();
  final Result rightResult = visitChild(1, e.getRight()).resetAlias();
  final Context leftContext = leftResult.qualifiedContext();
  final Context rightContext = rightResult.qualifiedContext();
  SqlNode sqlCondition = null;
  SqlLiteral condType = JoinConditionType.ON.symbol(POS);
  JoinType joinType = joinType(e.getJoinType());
  if (isCrossJoin(e)) {
    joinType = dialect.emulateJoinTypeForCrossJoin();
    condType = JoinConditionType.NONE.symbol(POS);
  } else {
    sqlCondition = convertConditionToSqlNode(e.getCondition(),
        leftContext,
        rightContext,
        e.getLeft().getRowType().getFieldCount(),
        dialect);
  }
  SqlNode join =
      new SqlJoin(POS,
          leftResult.asFrom(),
          SqlLiteral.createBoolean(false, POS),
          joinType.symbol(POS),
          rightResult.asFrom(),
          condType,
          sqlCondition);
  return result(join, leftResult, rightResult);
}
 
Example #17
Source File: DremioRelToSqlConverter.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
/**
 * @see #dispatch
 */
@Override
public SqlImplementor.Result visit(Join e) {
  final DremioRelToSqlConverter.Result leftResult = (DremioRelToSqlConverter.Result) visitChild(0, e.getLeft()).resetAlias();
  final DremioRelToSqlConverter.Result rightResult = (DremioRelToSqlConverter.Result) visitChild(1, e.getRight()).resetAlias();

  SqlNode sqlCondition = null;
  SqlLiteral condType = JoinConditionType.ON.symbol(POS);
  JoinType joinType = joinType(e.getJoinType());
  final Context leftContext = leftResult.qualifiedContext();
  final Context rightContext = rightResult.qualifiedContext();
  final Context joinContext = leftContext.implementor().joinContext(leftContext, rightContext);
  final RexNode condition = e.getCondition() == null ?
    null :
    this.simplifyDatetimePlus(e.getCondition(), e.getCluster().getRexBuilder());
  sqlCondition = joinContext.toSql(null, condition);

  final SqlNode join =
    new SqlJoin(POS,
      leftResult.asFrom(),
      SqlLiteral.createBoolean(false, POS),
      joinType.symbol(POS),
      rightResult.asFrom(),
      condType,
      sqlCondition);
  return result(join, leftResult, rightResult);
}
 
Example #18
Source File: RelToSqlConverter.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
/**
 * @see #dispatch
 */
public Result visit(Join e) {
  final Result leftResult = visitChild(0, e.getLeft()).resetAlias();
  final Result rightResult = visitChild(1, e.getRight()).resetAlias();
  final Context leftContext = leftResult.qualifiedContext();
  final Context rightContext = rightResult.qualifiedContext();
  SqlNode sqlCondition = null;
  SqlLiteral condType = JoinConditionType.ON.symbol(POS);
  JoinType joinType = joinType(e.getJoinType());
  if (e.getJoinType() == JoinRelType.INNER && e.getCondition().isAlwaysTrue()) {
    joinType = JoinType.COMMA;
    condType = JoinConditionType.NONE.symbol(POS);
  } else {
    final RexNode condition = e.getCondition() != null
      ? simplifyDatetimePlus(e.getCondition(), e.getCluster().getRexBuilder())
      : null;
    sqlCondition = convertConditionToSqlNode(
      condition,
      leftContext,
      rightContext,
      e.getLeft().getRowType().getFieldCount());
  }
  SqlNode join =
    new SqlJoin(POS,
      leftResult.asFrom(),
      SqlLiteral.createBoolean(false, POS),
      joinType.symbol(POS),
      rightResult.asFrom(),
      condType,
      sqlCondition);
  return result(join, leftResult, rightResult);
}
 
Example #19
Source File: JoinScope.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a <code>JoinScope</code>.
 *
 * @param parent     Parent scope
 * @param usingScope Scope for resolving USING clause
 * @param join       Call to JOIN operator
 */
JoinScope(
    SqlValidatorScope parent,
    SqlValidatorScope usingScope,
    SqlJoin join) {
  super(parent);
  this.usingScope = usingScope;
  this.join = join;
}
 
Example #20
Source File: JoinInfo.java    From sylph with Apache License 2.0 5 votes vote down vote up
JoinInfo(SqlJoin sqlJoin, TableName leftTable, TableName rightTable, boolean leftIsBatch, boolean rightIsBatch)
{
    this.sqlJoin = sqlJoin;
    this.leftIsBatch = leftIsBatch;
    this.rightIsBatch = rightIsBatch;
    this.joinType = sqlJoin.getJoinType();
    this.leftTable = leftTable;
    this.rightTable = rightTable;
}
 
Example #21
Source File: JoinScope.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a <code>JoinScope</code>.
 *
 * @param parent     Parent scope
 * @param usingScope Scope for resolving USING clause
 * @param join       Call to JOIN operator
 */
JoinScope(
    SqlValidatorScope parent,
    SqlValidatorScope usingScope,
    SqlJoin join) {
  super(parent);
  this.usingScope = usingScope;
  this.join = join;
}
 
Example #22
Source File: SideStream.java    From alchemy with Apache License 2.0 5 votes vote down vote up
public static DataStream<Row> buildStream(StreamTableEnvironment env, SqlSelect sqlSelect, Alias leftAlias,
    Alias sideAlias, SourceDescriptor sideSource) throws Exception {
    SqlSelect leftSelect = SideParser.newSelect(sqlSelect, leftAlias.getTable(), leftAlias.getAlias(), true, false);
    // register leftTable
    Table leftTable = env.sqlQuery(leftSelect.toString());
    DataStream<Row> leftStream = env.toAppendStream(leftTable, Row.class);
    SqlSelect rightSelect
        = SideParser.newSelect(sqlSelect, sideAlias.getTable(), sideAlias.getAlias(), false, false);
    SqlJoin sqlJoin = (SqlJoin)sqlSelect.getFrom();
    List<String> equalFields = SideParser.findConditionFields(sqlJoin.getCondition(), leftAlias.getAlias());
    if (sideSource.getSide().isPartition()) {
        leftStream = leftStream.keyBy(equalFields.toArray(new String[equalFields.size()]));
    }
    RowTypeInfo sideType = createSideType(rightSelect.getSelectList(), sideSource.getSchema());
    RowTypeInfo returnType = createReturnType(leftTable.getSchema(), sideType);
    SideTable sideTable = createSideTable(leftTable.getSchema(), sideType, sqlJoin.getJoinType(), rightSelect,
        equalFields, sideAlias, sideSource.getSide());
    DataStream<Row> returnStream;
    if (sideSource.getSide().isAsync()) {
        AbstractAsyncSideFunction reqRow = sideSource.transform(sideTable);
        returnStream = AsyncDataStream.orderedWait(leftStream, reqRow, sideSource.getSide().getTimeout(),
            TimeUnit.MILLISECONDS, sideSource.getSide().getCapacity());
    } else {
        AbstractSyncSideFunction syncReqRow = sideSource.transform(sideTable);
        returnStream = leftStream.flatMap(syncReqRow);
    }
    returnStream.getTransformation().setOutputType(returnType);
    return returnStream;
}
 
Example #23
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 #24
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
private void lookupJoinHints(
	SqlJoin join,
	SqlValidatorScope scope,
	SqlParserPos pos,
	Collection<SqlMoniker> hintList) {
	SqlNode left = join.getLeft();
	SqlNode right = join.getRight();
	SqlNode condition = join.getCondition();
	lookupFromHints(left, scope, pos, hintList);
	if (hintList.size() > 0) {
		return;
	}
	lookupFromHints(right, scope, pos, hintList);
	if (hintList.size() > 0) {
		return;
	}
	final JoinConditionType conditionType = join.getConditionType();
	final SqlValidatorScope joinScope = scopes.get(join);
	switch (conditionType) {
		case ON:
			condition.findValidOptions(this, joinScope, pos, hintList);
			return;
		default:

			// No suggestions.
			// Not supporting hints for other types such as 'Using' yet.
			return;
	}
}
 
Example #25
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 #26
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Validates the FROM clause of a query, or (recursively) a child node of
 * the FROM clause: AS, OVER, JOIN, VALUES, or sub-query.
 *
 * @param node          Node in FROM clause, typically a table or derived
 *                      table
 * @param targetRowType Desired row type of this expression, or
 *                      {@link #unknownType} if not fussy. Must not be null.
 * @param scope         Scope
 */
protected void validateFrom(
	SqlNode node,
	RelDataType targetRowType,
	SqlValidatorScope scope) {
	Objects.requireNonNull(targetRowType);
	switch (node.getKind()) {
		case AS:
			validateFrom(
				((SqlCall) node).operand(0),
				targetRowType,
				scope);
			break;
		case VALUES:
			validateValues((SqlCall) node, targetRowType, scope);
			break;
		case JOIN:
			validateJoin((SqlJoin) node, scope);
			break;
		case OVER:
			validateOver((SqlCall) node, scope);
			break;
		case UNNEST:
			validateUnnest((SqlCall) node, scope, targetRowType);
			break;
		default:
			validateQuery(node, scope, targetRowType);
			break;
	}

	// Validate the namespace representation of the node, just in case the
	// validation did not occur implicitly.
	getNamespace(node, scope).validate(targetRowType);
}
 
Example #27
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 5 votes vote down vote up
private void lookupJoinHints(
	SqlJoin join,
	SqlValidatorScope scope,
	SqlParserPos pos,
	Collection<SqlMoniker> hintList) {
	SqlNode left = join.getLeft();
	SqlNode right = join.getRight();
	SqlNode condition = join.getCondition();
	lookupFromHints(left, scope, pos, hintList);
	if (hintList.size() > 0) {
		return;
	}
	lookupFromHints(right, scope, pos, hintList);
	if (hintList.size() > 0) {
		return;
	}
	final JoinConditionType conditionType = join.getConditionType();
	final SqlValidatorScope joinScope = scopes.get(join);
	switch (conditionType) {
		case ON:
			condition.findValidOptions(this, joinScope, pos, hintList);
			return;
		default:

			// No suggestions.
			// Not supporting hints for other types such as 'Using' yet.
			return;
	}
}
 
Example #28
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 #29
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
/**
 * Validates the FROM clause of a query, or (recursively) a child node of
 * the FROM clause: AS, OVER, JOIN, VALUES, or sub-query.
 *
 * @param node          Node in FROM clause, typically a table or derived
 *                      table
 * @param targetRowType Desired row type of this expression, or
 *                      {@link #unknownType} if not fussy. Must not be null.
 * @param scope         Scope
 */
protected void validateFrom(
	SqlNode node,
	RelDataType targetRowType,
	SqlValidatorScope scope) {
	Objects.requireNonNull(targetRowType);
	switch (node.getKind()) {
		case AS:
			validateFrom(
				((SqlCall) node).operand(0),
				targetRowType,
				scope);
			break;
		case VALUES:
			validateValues((SqlCall) node, targetRowType, scope);
			break;
		case JOIN:
			validateJoin((SqlJoin) node, scope);
			break;
		case OVER:
			validateOver((SqlCall) node, scope);
			break;
		default:
			validateQuery(node, scope, targetRowType);
			break;
	}

	// Validate the namespace representation of the node, just in case the
	// validation did not occur implicitly.
	getNamespace(node, scope).validate(targetRowType);
}
 
Example #30
Source File: JoinNamespace.java    From calcite with Apache License 2.0 4 votes vote down vote up
JoinNamespace(SqlValidatorImpl validator, SqlJoin join) {
  super(validator, null);
  this.join = join;
}