Java Code Examples for org.apache.calcite.sql.SqlKind#AS

The following examples show how to use org.apache.calcite.sql.SqlKind#AS . 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: 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 2
Source File: QuerySemantics.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
private static ASNode extractAS(SqlCall call) {
  if (call.getOperator().getKind() == SqlKind.AS) {
    List<SqlNode> operandList = call.getOperandList();
    if (operandList.size() == 2) {
      SqlNode exp = operandList.get(0);
      SqlNode colID = operandList.get(1);
      if (isSimpleID(colID)) {
        return new ASNode((SqlIdentifier)colID, exp);
      } else {
        throw new UnsupportedOperationException("Unexpected AS " + colID + "\n" + SqlNodes.toTreeString(call));
      }
    } else {
      throw new UnsupportedOperationException("Unexpected AS operands in field: \n" + SqlNodes.toTreeString(call));
    }
  }
  throw new UnsupportedOperationException("AS not understood: " + SqlNodes.toSQLString(call));
}
 
Example 3
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 4
Source File: SqlImplementor.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Returns a node that can be included in the FROM clause or a JOIN. It has
 * an alias that is unique within the query. The alias is implicit if it
 * can be derived using the usual rules (For example, "SELECT * FROM emp" is
 * equivalent to "SELECT * FROM emp AS emp".) */
public SqlNode asFrom() {
  if (neededAlias != null) {
    if (node.getKind() == SqlKind.AS) {
      // If we already have an AS node, we need to replace the alias
      // This is especially relevant for the VALUES clause rendering
      SqlCall sqlCall = (SqlCall) node;
      SqlNode[] operands = sqlCall.getOperandList().toArray(SqlNode.EMPTY_ARRAY);
      operands[1] = new SqlIdentifier(neededAlias, POS);
      return SqlStdOperatorTable.AS.createCall(POS, operands);
    } else {
      return SqlStdOperatorTable.AS.createCall(POS, node,
          new SqlIdentifier(neededAlias, POS));
    }
  }
  return node;
}
 
Example 5
Source File: RelToSqlConverter.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public SqlNode visit(SqlIdentifier id) {
  if (tableAlias.equals(id.names.get(0))) {
    int index = tableType.getField(
        id.names.get(1), false, false).getIndex();
    SqlNode selectItem = replaceSource.get(index);
    if (selectItem.getKind() == SqlKind.AS) {
      selectItem = ((SqlCall) selectItem).operand(0);
    }
    return selectItem.clone(id.getParserPosition());
  }
  return id;
}
 
Example 6
Source File: DremioRelToSqlConverter.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Process the Result from visiting a Project node's child.
 *
 * @param project     The project node.
 * @param childResult The Result from calling visit() on the child of project.
 * @return The Result of visiting the Project node itself.
 */
protected DremioRelToSqlConverter.Result processProjectChild(Project project, DremioRelToSqlConverter.Result childResult) {
  // unlike the super impl #visit(Project), this expands star ("*") if additional push downs are enabled

  Pointer<Boolean> isPartial = new Pointer<>(false);
  project.accept(new StatelessRelShuttleImpl() {
    @Override
    public RelNode visit(TableScan scan) {
      if (scan instanceof ScanRelBase) {
        ScanRelBase tableScan = (ScanRelBase) scan;
        if (tableScan.getTableMetadata().getSchema().getFieldCount() != tableScan.getProjectedColumns().size()) {
          isPartial.value = true;
        }
      }
      return scan;
    }
  });

  PlannerSettings plannerSettings = PrelUtil.getPlannerSettings(project.getCluster());
  if (plannerSettings != null &&
    !plannerSettings.getOptions().getOption(PlannerSettings.JDBC_PUSH_DOWN_PLUS) &&
    !isPartial.value &&
    isStar(project.getChildExps(), project.getInput().getRowType(), project.getRowType())) {
    return childResult;
  }

  final DremioRelToSqlConverter.Builder builder =
    childResult.builder(project, SqlImplementor.Clause.SELECT);
  final List<SqlNode> selectList = new ArrayList<>();
  for (RexNode ref : project.getChildExps()) {
    SqlNode sqlExpr = builder.context.toSql(null, simplifyDatetimePlus(ref, project.getCluster().getRexBuilder()));
    if ((getDialect().shouldInjectNumericCastToProject() && isDecimal(ref.getType())) ||
        (getDialect().shouldInjectApproxNumericCastToProject() && isApproximateNumeric(ref.getType()))) {
      if (!((sqlExpr.getKind() == SqlKind.CAST) || (sqlExpr.getKind() == SqlKind.AS && ((SqlBasicCall) sqlExpr).operand(0).getKind() == SqlKind.CAST))) {
        // Add an explicit cast around this projection.
        sqlExpr = SqlStdOperatorTable.CAST.createCall(POS, sqlExpr, getDialect().getCastSpec(ref.getType()));
      }
    }

    addSelect(selectList, sqlExpr, project.getRowType());
  }

  builder.setSelect(new SqlNodeList(selectList, POS));
  return builder.result();
}
 
Example 7
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 8
Source File: AbstractTypeCoercion.java    From calcite with Apache License 2.0 4 votes vote down vote up
/**
 * Cast column at index {@code index} to target type.
 *
 * @param scope      Validator scope for the node list
 * @param nodeList   Column node list
 * @param index      Index of column
 * @param targetType Target type to cast to
 */
protected boolean coerceColumnType(
    SqlValidatorScope scope,
    SqlNodeList nodeList,
    int index,
    RelDataType targetType) {
  // Transform the JavaType to SQL type because the SqlDataTypeSpec
  // does not support deriving JavaType yet.
  if (RelDataTypeFactoryImpl.isJavaType(targetType)) {
    targetType = ((JavaTypeFactory) factory).toSql(targetType);
  }

  // This will happen when there is a star/dynamic-star column in the select list,
  // and the source is values expression, i.e. `select * from (values(1, 2, 3))`.
  // There is no need to coerce the column type, only remark
  // the inferred row type has changed, we will then add in type coercion
  // when expanding star/dynamic-star.

  // See SqlToRelConverter#convertSelectList for details.
  if (index >= nodeList.getList().size()) {
    // Can only happen when there is a star(*) in the column,
    // just return true.
    return true;
  }

  final SqlNode node = nodeList.get(index);
  if (node instanceof SqlDynamicParam) {
    // Do not support implicit type coercion for dynamic param.
    return false;
  }
  if (node instanceof SqlIdentifier) {
    // Do not expand a star/dynamic table col.
    SqlIdentifier node1 = (SqlIdentifier) node;
    if (node1.isStar()) {
      return true;
    } else if (DynamicRecordType.isDynamicStarColName(Util.last(node1.names))) {
      // Should support implicit cast for dynamic table.
      return false;
    }
  }

  if (node instanceof SqlCall) {
    SqlCall node2 = (SqlCall) node;
    if (node2.getOperator().kind == SqlKind.AS) {
      final SqlNode operand = node2.operand(0);
      if (!needToCast(scope, operand, targetType)) {
        return false;
      }
      RelDataType targetType2 = syncAttributes(validator.deriveType(scope, operand), targetType);
      final SqlNode casted = castTo(operand, targetType2);
      node2.setOperand(0, casted);
      updateInferredType(casted, targetType2);
      return true;
    }
  }
  if (!needToCast(scope, node, targetType)) {
    return false;
  }
  RelDataType targetType3 = syncAttributes(validator.deriveType(scope, node), targetType);
  final SqlNode node3 = castTo(node, targetType3);
  nodeList.set(index, node3);
  updateInferredType(node3, targetType3);
  return true;
}