Java Code Examples for org.apache.calcite.sql.validate.SqlValidatorUtil

The following examples show how to use org.apache.calcite.sql.validate.SqlValidatorUtil. 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: Lattice.java    License: 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 Project: Bats   Source File: SqlCallBinding.java    License: Apache License 2.0 6 votes vote down vote up
@Override public int getGroupCount() {
  final SelectScope selectScope =
      SqlValidatorUtil.getEnclosingSelectScope(scope);
  if (selectScope == null) {
    // Probably "VALUES expr". Treat same as "SELECT expr GROUP BY ()"
    return 0;
  }
  final SqlSelect select = selectScope.getNode();
  final SqlNodeList group = select.getGroup();
  if (group != null) {
    int n = 0;
    for (SqlNode groupItem : group) {
      if (!(groupItem instanceof SqlNodeList)
          || ((SqlNodeList) groupItem).size() != 0) {
        ++n;
      }
    }
    return n;
  }
  return validator.isAggregate(select) ? 0 : -1;
}
 
Example 3
Source Project: Bats   Source File: SqlTypeUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Adds collation and charset to a character type, returns other types
 * unchanged.
 *
 * @param type        Type
 * @param typeFactory Type factory
 * @return Type with added charset and collation, or unchanged type if it is
 * not a char type.
 */
public static RelDataType addCharsetAndCollation(
    RelDataType type,
    RelDataTypeFactory typeFactory) {
  if (!inCharFamily(type)) {
    return type;
  }
  Charset charset = type.getCharset();
  if (charset == null) {
    charset = typeFactory.getDefaultCharset();
  }
  SqlCollation collation = type.getCollation();
  if (collation == null) {
    collation = SqlCollation.IMPLICIT;
  }

  // todo: should get the implicit collation from repository
  //   instead of null
  type =
      typeFactory.createTypeWithCharsetAndCollation(
          type,
          charset,
          collation);
  SqlValidatorUtil.checkCharsetAndCollateConsistentIfCharType(type);
  return type;
}
 
Example 4
Source Project: Bats   Source File: RelBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/** Creates a {@link Project} of the given
 * expressions and field names, and optionally optimizing.
 *
 * <p>If {@code fieldNames} is null, or if a particular entry in
 * {@code fieldNames} is null, derives field names from the input
 * expressions.
 *
 * <p>If {@code force} is false,
 * and the input is a {@code Project},
 * and the expressions  make the trivial projection ($0, $1, ...),
 * modifies the input.
 *
 * @param nodes       Expressions
 * @param fieldNames  Suggested field names, or null to generate
 * @param force       Whether to create a renaming Project if the
 *                    projections are trivial
 */
public RelBuilder projectNamed(Iterable<? extends RexNode> nodes, Iterable<String> fieldNames, boolean force) {
    @SuppressWarnings({ "unchecked", "rawtypes" })
    final List<? extends RexNode> nodeList = nodes instanceof List ? (List) nodes : ImmutableList.copyOf(nodes);
    final List<String> fieldNameList = fieldNames == null ? null
            : fieldNames instanceof List ? (List<String>) fieldNames : ImmutableNullableList.copyOf(fieldNames);
    final RelNode input = peek();
    final RelDataType rowType = RexUtil.createStructType(cluster.getTypeFactory(), nodeList, fieldNameList,
            SqlValidatorUtil.F_SUGGESTER);
    if (!force && RexUtil.isIdentity(nodeList, input.getRowType())) {
        if (input instanceof Project && fieldNames != null) {
            // Rename columns of child projection if desired field names are given.
            final Frame frame = stack.pop();
            final Project childProject = (Project) frame.rel;
            final Project newInput = childProject.copy(childProject.getTraitSet(), childProject.getInput(),
                    childProject.getProjects(), rowType);
            stack.push(new Frame(newInput, frame.fields));
        }
    } else {
        project(nodeList, rowType.getFieldNames(), force);
    }
    return this;
}
 
Example 5
Source Project: Bats   Source File: CalciteCatalogReader.java    License: Apache License 2.0 6 votes vote down vote up
public PreparingTable getTable(final List<String> names) {
  // First look in the default schema, if any.
  // If not found, look in the root schema.
  CalciteSchema.TableEntry entry = SqlValidatorUtil.getTableEntry(this, names);
  if (entry != null) {
    final Table table = entry.getTable();
    if (table instanceof Wrapper) {
      final PreparingTable relOptTable =
          ((Wrapper) table).unwrap(PreparingTable.class);
      if (relOptTable != null) {
        return relOptTable;
      }
    }
    return RelOptTableImpl.create(this,
        table.getRowType(typeFactory), entry, null);
  }
  return null;
}
 
Example 6
Source Project: Bats   Source File: RexUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a record type with specified field names.
 *
 * <p>The array of field names may be null, or any of the names within it
 * can be null. We recommend using explicit names where possible, because it
 * makes it much easier to figure out the intent of fields when looking at
 * planner output.
 *
 * @param typeFactory Type factory
 * @param exprs       Expressions
 * @param names       Field names, may be null, or elements may be null
 * @param suggester   Generates alternative names if {@code names} is not
 *                    null and its elements are not unique
 * @return Record type
 */
public static RelDataType createStructType(RelDataTypeFactory typeFactory, final List<? extends RexNode> exprs,
        List<String> names, SqlValidatorUtil.Suggester suggester) {
    if (names != null && suggester != null) {
        names = SqlValidatorUtil.uniquify(names, suggester, typeFactory.getTypeSystem().isSchemaCaseSensitive());
    }
    final RelDataTypeFactory.Builder builder = typeFactory.builder();
    for (int i = 0; i < exprs.size(); i++) {
        String name;
        if (names == null || (name = names.get(i)) == null) {
            name = "$f" + i;
        }
        builder.add(name, exprs.get(i).getType());
    }
    return builder.build();
}
 
Example 7
Source Project: Bats   Source File: DrillLateralJoinRelBase.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected RelDataType deriveRowType() {
  switch (joinType) {
    case LEFT:
    case INNER:
      return constructRowType(SqlValidatorUtil.deriveJoinRowType(left.getRowType(),
        removeImplicitField(right.getRowType()), joinType.toJoinType(),
        getCluster().getTypeFactory(), null,
        ImmutableList.of()));
    case ANTI:
    case SEMI:
      return constructRowType(left.getRowType());
    default:
      throw new IllegalStateException("Unknown join type " + joinType);
  }
}
 
Example 8
Source Project: calcite   Source File: RexUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a record type with specified field names.
 *
 * <p>The array of field names may be null, or any of the names within it
 * can be null. We recommend using explicit names where possible, because it
 * makes it much easier to figure out the intent of fields when looking at
 * planner output.
 *
 * @param typeFactory Type factory
 * @param exprs       Expressions
 * @param names       Field names, may be null, or elements may be null
 * @param suggester   Generates alternative names if {@code names} is not
 *                    null and its elements are not unique
 * @return Record type
 */
public static RelDataType createStructType(
    RelDataTypeFactory typeFactory,
    final List<? extends RexNode> exprs,
    List<String> names,
    SqlValidatorUtil.Suggester suggester) {
  if (names != null && suggester != null) {
    names = SqlValidatorUtil.uniquify(names, suggester,
        typeFactory.getTypeSystem().isSchemaCaseSensitive());
  }
  final RelDataTypeFactory.Builder builder = typeFactory.builder();
  for (int i = 0; i < exprs.size(); i++) {
    String name;
    if (names == null || (name = names.get(i)) == null) {
      name = "$f" + i;
    }
    builder.add(name, exprs.get(i).getType());
  }
  return builder.build();
}
 
Example 9
Source Project: calcite   Source File: Lattice.java    License: 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 10
Source Project: calcite   Source File: CalciteCatalogReader.java    License: Apache License 2.0 6 votes vote down vote up
public Prepare.PreparingTable getTable(final List<String> names) {
  // First look in the default schema, if any.
  // If not found, look in the root schema.
  CalciteSchema.TableEntry entry = SqlValidatorUtil.getTableEntry(this, names);
  if (entry != null) {
    final Table table = entry.getTable();
    if (table instanceof Wrapper) {
      final Prepare.PreparingTable relOptTable =
          ((Wrapper) table).unwrap(Prepare.PreparingTable.class);
      if (relOptTable != null) {
        return relOptTable;
      }
    }
    return RelOptTableImpl.create(this,
        table.getRowType(typeFactory), entry, null);
  }
  return null;
}
 
Example 11
Source Project: calcite   Source File: SqlCallBinding.java    License: Apache License 2.0 6 votes vote down vote up
@Override public int getGroupCount() {
  final SelectScope selectScope =
      SqlValidatorUtil.getEnclosingSelectScope(scope);
  if (selectScope == null) {
    // Probably "VALUES expr". Treat same as "SELECT expr GROUP BY ()"
    return 0;
  }
  final SqlSelect select = selectScope.getNode();
  final SqlNodeList group = select.getGroup();
  if (group != null) {
    int n = 0;
    for (SqlNode groupItem : group) {
      if (!(groupItem instanceof SqlNodeList)
          || ((SqlNodeList) groupItem).size() != 0) {
        ++n;
      }
    }
    return n;
  }
  return validator.isAggregate(select) ? 0 : -1;
}
 
Example 12
Source Project: calcite   Source File: SqlTypeUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Adds collation and charset to a character type, returns other types
 * unchanged.
 *
 * @param type        Type
 * @param typeFactory Type factory
 * @return Type with added charset and collation, or unchanged type if it is
 * not a char type.
 */
public static RelDataType addCharsetAndCollation(
    RelDataType type,
    RelDataTypeFactory typeFactory) {
  if (!inCharFamily(type)) {
    return type;
  }
  Charset charset = type.getCharset();
  if (charset == null) {
    charset = typeFactory.getDefaultCharset();
  }
  SqlCollation collation = type.getCollation();
  if (collation == null) {
    collation = SqlCollation.IMPLICIT;
  }

  // todo: should get the implicit collation from repository
  //   instead of null
  type =
      typeFactory.createTypeWithCharsetAndCollation(
          type,
          charset,
          collation);
  SqlValidatorUtil.checkCharsetAndCollateConsistentIfCharType(type);
  return type;
}
 
Example 13
Source Project: Bats   Source File: BatsOptimizerTest.java    License: Apache License 2.0 5 votes vote down vote up
static Pair<SqlNode, SqlValidator> testSqlValidator() throws Exception {
    String sql = "select * from my_schema.test where f1=1 or f2=2 order by f3 limit 2";
    sql = "select * from test";
    sql = "select * from my_schema2.test2";
    sql = "select sum(f1),max(f2) from test";

    sql = "select t1.f1,sum(Distinct f1) as sumf1 from test as t1 "
            + "where f2>20 group by f1 having f1>10 order by f1 limit 2";
    // sql = "insert into test(f1,f2,f3) values(1,2,3)";
    // sql = "update test set f1=100 where f2>10";
    // sql = "delete from test where f2>10";
    SqlNode sqlNode = parse(sql);

    SqlOperatorTable opTab = SqlStdOperatorTable.instance();
    RelDataTypeFactory typeFactory = createJavaTypeFactory();
    SqlValidatorCatalogReader catalogReader = createCalciteCatalogReader(typeFactory);
    SqlConformance conformance = SqlConformanceEnum.DEFAULT;

    List<String> names = new ArrayList<>();
    names.add("my_schema");
    names.add("test");
    catalogReader.getTable(names);

    SqlValidator sqlValidator = SqlValidatorUtil.newValidator(opTab, catalogReader, typeFactory, conformance);
    sqlNode = sqlValidator.validate(sqlNode);
    // System.out.println(sqlNode);

    sql = "insert into test(f1,f2,f3) values(1,2,3)";
    // sqlNode = parse(sql);
    // sqlNode = sqlValidator.validate(sqlNode);

    return new Pair<>(sqlNode, sqlValidator);
}
 
Example 14
Source Project: Bats   Source File: MutableProject.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a MutableProject.
 *
 * @param input         Input relational expression
 * @param exprList      List of expressions for the input columns
 * @param fieldNameList Aliases of the expressions, or null to generate
 */
public static MutableRel of(MutableRel input, List<RexNode> exprList,
    List<String> fieldNameList) {
  final RelDataType rowType =
      RexUtil.createStructType(input.cluster.getTypeFactory(), exprList,
          fieldNameList, SqlValidatorUtil.F_SUGGESTER);
  return of(rowType, input, exprList);
}
 
Example 15
Source Project: Bats   Source File: LogicalProject.java    License: Apache License 2.0 5 votes vote down vote up
/** Creates a LogicalProject. */
public static LogicalProject create(final RelNode input,
    final List<? extends RexNode> projects, List<String> fieldNames) {
  final RelOptCluster cluster = input.getCluster();
  final RelDataType rowType =
      RexUtil.createStructType(cluster.getTypeFactory(), projects,
          fieldNames, SqlValidatorUtil.F_SUGGESTER);
  return create(input, projects, rowType);
}
 
Example 16
Source Project: Bats   Source File: SqlImplementor.java    License: Apache License 2.0 5 votes vote down vote up
public void addSelect(List<SqlNode> selectList, SqlNode node, RelDataType rowType) {
    String name = rowType.getFieldNames().get(selectList.size());
    String alias = SqlValidatorUtil.getAlias(node, -1);
    if (alias == null || !alias.equals(name)) {
        node = SqlStdOperatorTable.AS.createCall(POS, node, new SqlIdentifier(name, POS));
    }
    selectList.add(node);
}
 
Example 17
Source Project: Bats   Source File: RelToSqlConverter.java    License: Apache License 2.0 5 votes vote down vote up
@Override public void addSelect(List<SqlNode> selectList, SqlNode node,
    RelDataType rowType) {
  String name = rowType.getFieldNames().get(selectList.size());
  String alias = SqlValidatorUtil.getAlias(node, -1);
  final String lowerName = name.toLowerCase(Locale.ROOT);
  if (lowerName.startsWith("expr$")) {
    // Put it in ordinalMap
    ordinalMap.put(lowerName, node);
  } else if (alias == null || !alias.equals(name)) {
    node = as(node, name);
  }
  selectList.add(node);
}
 
Example 18
Source Project: Bats   Source File: RelDataTypeFactory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Makes sure that field names are unique.
 */
public Builder uniquify() {
  final List<String> uniqueNames = SqlValidatorUtil.uniquify(names,
      typeFactory.getTypeSystem().isSchemaCaseSensitive());
  if (uniqueNames != names) {
    names.clear();
    names.addAll(uniqueNames);
  }
  return this;
}
 
Example 19
Source Project: Bats   Source File: Join.java    License: Apache License 2.0 5 votes vote down vote up
@Deprecated // to be removed before 2.0
public static RelDataType deriveJoinRowType(
    RelDataType leftType,
    RelDataType rightType,
    JoinRelType joinType,
    RelDataTypeFactory typeFactory,
    List<String> fieldNameList,
    List<RelDataTypeField> systemFieldList) {
  return SqlValidatorUtil.deriveJoinRowType(leftType, rightType, joinType,
      typeFactory, fieldNameList, systemFieldList);
}
 
Example 20
Source Project: Bats   Source File: Join.java    License: Apache License 2.0 5 votes vote down vote up
@Deprecated // to be removed before 2.0
public static RelDataType createJoinType(
    RelDataTypeFactory typeFactory,
    RelDataType leftType,
    RelDataType rightType,
    List<String> fieldNameList,
    List<RelDataTypeField> systemFieldList) {
  return SqlValidatorUtil.createJoinType(typeFactory, leftType, rightType,
      fieldNameList, systemFieldList);
}
 
Example 21
Source Project: calcite   Source File: RelBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/** Creates a {@link Project} of the given
 * expressions and field names, and optionally optimizing.
 *
 * <p>If {@code fieldNames} is null, or if a particular entry in
 * {@code fieldNames} is null, derives field names from the input
 * expressions.
 *
 * <p>If {@code force} is false,
 * and the input is a {@code Project},
 * and the expressions  make the trivial projection ($0, $1, ...),
 * modifies the input.
 *
 * @param nodes       Expressions
 * @param fieldNames  Suggested field names, or null to generate
 * @param force       Whether to create a renaming Project if the
 *                    projections are trivial
 */
public RelBuilder projectNamed(Iterable<? extends RexNode> nodes,
    Iterable<String> fieldNames, boolean force) {
  @SuppressWarnings("unchecked") final List<? extends RexNode> nodeList =
      nodes instanceof List ? (List) nodes : ImmutableList.copyOf(nodes);
  final List<String> fieldNameList =
      fieldNames == null ? null
        : fieldNames instanceof List ? (List<String>) fieldNames
        : ImmutableNullableList.copyOf(fieldNames);
  final RelNode input = peek();
  final RelDataType rowType =
      RexUtil.createStructType(cluster.getTypeFactory(), nodeList,
          fieldNameList, SqlValidatorUtil.F_SUGGESTER);
  if (!force
      && RexUtil.isIdentity(nodeList, input.getRowType())) {
    if (input instanceof Project && fieldNames != null) {
      // Rename columns of child projection if desired field names are given.
      final Frame frame = stack.pop();
      final Project childProject = (Project) frame.rel;
      final Project newInput = childProject.copy(childProject.getTraitSet(),
          childProject.getInput(), childProject.getProjects(), rowType);
      stack.push(new Frame(newInput.attachHints(childProject.getHints()), frame.fields));
    }
  } else {
    project(nodeList, rowType.getFieldNames(), force);
  }
  return this;
}
 
Example 22
Source Project: Bats   Source File: Correlate.java    License: Apache License 2.0 5 votes vote down vote up
@Override protected RelDataType deriveRowType() {
  switch (joinType) {
  case LEFT:
  case INNER:
    return SqlValidatorUtil.deriveJoinRowType(left.getRowType(),
        right.getRowType(), joinType.toJoinType(),
        getCluster().getTypeFactory(), null,
        ImmutableList.of());
  case ANTI:
  case SEMI:
    return left.getRowType();
  default:
    throw new IllegalStateException("Unknown join type " + joinType);
  }
}
 
Example 23
Source Project: Bats   Source File: CalciteCatalogReader.java    License: Apache License 2.0 5 votes vote down vote up
public RelDataType getNamedType(SqlIdentifier typeName) {
  CalciteSchema.TypeEntry typeEntry = SqlValidatorUtil.getTypeEntry(getRootSchema(), typeName);
  if (typeEntry != null) {
    return typeEntry.getType().apply(typeFactory);
  } else {
    return null;
  }
}
 
Example 24
Source Project: Bats   Source File: CalciteCatalogReader.java    License: Apache License 2.0 5 votes vote down vote up
public List<SqlMoniker> getAllSchemaObjectNames(List<String> names) {
  final CalciteSchema schema =
      SqlValidatorUtil.getSchema(rootSchema, names, nameMatcher);
  if (schema == null) {
    return ImmutableList.of();
  }
  final List<SqlMoniker> result = new ArrayList<>();

  // Add root schema if not anonymous
  if (!schema.name.equals("")) {
    result.add(moniker(schema, null, SqlMonikerType.SCHEMA));
  }

  final Map<String, CalciteSchema> schemaMap = schema.getSubSchemaMap();

  for (String subSchema : schemaMap.keySet()) {
    result.add(moniker(schema, subSchema, SqlMonikerType.SCHEMA));
  }

  for (String table : schema.getTableNames()) {
    result.add(moniker(schema, table, SqlMonikerType.TABLE));
  }

  final NavigableSet<String> functions = schema.getFunctionNames();
  for (String function : functions) { // views are here as well
    result.add(moniker(schema, function, SqlMonikerType.FUNCTION));
  }
  return result;
}
 
Example 25
Source Project: Bats   Source File: RowKeyJoinRel.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public RelDataType deriveRowType() {
  return SqlValidatorUtil.deriveJoinRowType(
          left.getRowType(),
          isSemiJoin() ? null : right.getRowType(),
          JoinRelType.INNER,
          getCluster().getTypeFactory(),
          null,
          ImmutableList.of());
}
 
Example 26
Source Project: Bats   Source File: JoinPrel.java    License: Apache License 2.0 5 votes vote down vote up
@Override public RelDataType deriveRowType() {
  if (isSemiJoin) {
    return SqlValidatorUtil.deriveJoinRowType(
            left.getRowType(),
            null,
            this.joinType,
            getCluster().getTypeFactory(),
            null,
            new ArrayList<>());
  } else {
    return super.deriveRowType();
  }
}
 
Example 27
Source Project: Bats   Source File: TopProjectVisitor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Adds top project to ensure final output field names are preserved.
 * In case of duplicated column names, will rename duplicates.
 * Top project will be added only if top project is non-trivial and
 * child physical relational node is not project.
 *
 * @param prel physical relational node
 * @param validatedRowType final output row type
 * @return physical relational node with top project if necessary
 */
private Prel addTopProjectPrel(Prel prel, RelDataType validatedRowType) {
  RelDataType rowType = prel.getRowType();
  if (rowType.getFieldCount() != validatedRowType.getFieldCount()) {
    return prel;
  }

  RexBuilder rexBuilder = prel.getCluster().getRexBuilder();
  List<RexNode> projections = new ArrayList<>();
  int projectCount = rowType.getFieldList().size();

  for (int i = 0; i < projectCount; i++) {
    projections.add(rexBuilder.makeInputRef(prel, i));
  }

  List<String> fieldNames = SqlValidatorUtil.uniquify(
      validatedRowType.getFieldNames(),
      SqlValidatorUtil.EXPR_SUGGESTER,
      prel.getCluster().getTypeFactory().getTypeSystem().isSchemaCaseSensitive());

  RelDataType newRowType = RexUtil.createStructType(prel.getCluster().getTypeFactory(), projections, fieldNames, null);
  ProjectPrel topProject = new ProjectPrel(prel.getCluster(),
      prel.getTraitSet(),
      prel,
      projections,
      newRowType,
      true);  //outputProj = true : NONE -> OK_NEW_SCHEMA, also handle expression with NULL type.

  if (prel instanceof Project && DrillRelOptUtil.isTrivialProject(topProject, true)) {
    return new ProjectPrel(prel.getCluster(),
        prel.getTraitSet(),
        ((Project) prel).getInput(),
        ((Project) prel).getProjects(),
        prel.getRowType(),
        true); //outputProj = true : NONE -> OK_NEW_SCHEMA, also handle expression with NULL type.
  } else {
    return topProject;
  }
}
 
Example 28
Source Project: Bats   Source File: DefaultSqlHandler.java    License: Apache License 2.0 5 votes vote down vote up
protected DrillRel addRenamedProject(DrillRel rel, RelDataType validatedRowType) {
  RelDataType t = rel.getRowType();

  RexBuilder b = rel.getCluster().getRexBuilder();
  List<RexNode> projections = Lists.newArrayList();
  int projectCount = t.getFieldList().size();

  for (int i =0; i < projectCount; i++) {
    projections.add(b.makeInputRef(rel, i));
  }

  final List<String> fieldNames2 = SqlValidatorUtil.uniquify(
      validatedRowType.getFieldNames(),
      SqlValidatorUtil.EXPR_SUGGESTER,
      rel.getCluster().getTypeFactory().getTypeSystem().isSchemaCaseSensitive());

  RelDataType newRowType = RexUtil.createStructType(rel.getCluster().getTypeFactory(),
      projections, fieldNames2, null);

  DrillProjectRel topProj = DrillProjectRel.create(rel.getCluster(), rel.getTraitSet(), rel, projections, newRowType);

  // Add a final non-trivial Project to get the validatedRowType, if child is not project.
  if (rel instanceof Project && DrillRelOptUtil.isTrivialProject(topProj, true)) {
    return rel;
  } else{
    return topProj;
  }
}
 
Example 29
Source Project: Bats   Source File: SqlConverter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String deriveAlias(
    SqlNode node,
    int ordinal) {
  if (node instanceof SqlIdentifier) {
    SqlIdentifier tempNode = ((SqlIdentifier) node);
    changeNamesIfTableIsTemporary(tempNode);
  }
  return SqlValidatorUtil.getAlias(node, ordinal);
}
 
Example 30
Source Project: Bats   Source File: SqlConverter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Checks that specified expression is not implicit column and
 * adds it to a select list, ensuring that its alias does not
 * clash with any existing expressions on the list.
 * <p>
 * This method may be used when {@link RelDataType#isDynamicStruct}
 * method returns false. Each column from table row type except
 * the implicit is added into specified list, aliases and fieldList.
 * In the opposite case when {@link RelDataType#isDynamicStruct}
 * returns true, only dynamic star is added into specified
 * list, aliases and fieldList.
 */
@Override
protected void addToSelectList(
    List<SqlNode> list,
    Set<String> aliases,
    List<Map.Entry<String, RelDataType>> fieldList,
    SqlNode exp,
    SqlValidatorScope scope,
    final boolean includeSystemVars) {
  if (!ColumnExplorer.initImplicitFileColumns(session.getOptions())
      .containsKey(SqlValidatorUtil.getAlias(exp, -1))) {
    super.addToSelectList(list, aliases, fieldList, exp, scope, includeSystemVars);
  }
}