Java Code Examples for org.apache.calcite.rel.type.RelDataTypeField

The following examples show how to use org.apache.calcite.rel.type.RelDataTypeField. 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: calcite   Source File: RexProgramBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a program-builder.
 */
private RexProgramBuilder(RelDataType inputRowType, RexBuilder rexBuilder,
    RexSimplify simplify) {
  this.inputRowType = Objects.requireNonNull(inputRowType);
  this.rexBuilder = Objects.requireNonNull(rexBuilder);
  this.simplify = simplify; // may be null
  this.validating = assertionsAreEnabled();

  // Pre-create an expression for each input field.
  if (inputRowType.isStruct()) {
    final List<RelDataTypeField> fields = inputRowType.getFieldList();
    for (int i = 0; i < fields.size(); i++) {
      registerInternal(RexInputRef.of(i, fields), false);
    }
  }
}
 
Example 2
Source Project: Bats   Source File: MaterializedViewSubstitutionVisitor.java    License: Apache License 2.0 6 votes vote down vote up
private static List<RexNode> transformRex(List<RexNode> nodes, final List<RelDataTypeField> oldFields,
        final List<RelDataTypeField> newFields) {
    RexShuttle shuttle = new RexShuttle() {
        @Override
        public RexNode visitInputRef(RexInputRef ref) {
            RelDataTypeField f = oldFields.get(ref.getIndex());
            for (int index = 0; index < newFields.size(); index++) {
                RelDataTypeField newf = newFields.get(index);
                if (f.getKey().equals(newf.getKey()) && f.getValue() == newf.getValue()) {
                    return RexBuilder.getRexFactory().makeInputRef(index, f.getValue());
                }
            }
            throw MatchFailed.INSTANCE;
        }
    };
    return shuttle.apply(nodes);
}
 
Example 3
Source Project: dremio-oss   Source File: CopyWithCluster.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public RelNode visit(LogicalJoin join) {
  // to the best of my knowledge join.systemFieldList is always empty
  Preconditions.checkState(join.getSystemFieldList().isEmpty(), "join.systemFieldList is not empty!");

  final RelNode left = join.getLeft().accept(this);
  final RelNode right = join.getRight().accept(this);

  return new LogicalJoin(
    cluster,
    copyOf(join.getTraitSet()),
    left,
    right,
    copyOf(join.getCondition()),
    join.getVariablesSet(),
    join.getJoinType(),
    join.isSemiJoinDone(),
    ImmutableList.<RelDataTypeField>of()
  );
}
 
Example 4
Source Project: dremio-oss   Source File: DremioRelToSqlConverter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public SqlImplementor.Result visit(Window e) {
  SqlImplementor.Result x = visitChild(0, e.getInput());
  SqlImplementor.Builder builder = x.builder(e);
  RelNode input = e.getInput();
  List<RexOver> rexOvers = WindowUtil.getOver(e);

  final List<SqlNode> selectList = new ArrayList<>();
  final Set<String> fields = ImmutableSet.copyOf(e.getRowType().getFieldNames());
  for (RelDataTypeField field : input.getRowType().getFieldList()) {
    if (fields.contains(field.getName())) {
      addSelect(selectList, builder.context.field(field.getIndex()), e.getRowType());
    }
  }

  for (RexOver rexOver : rexOvers) {
    addSelect(selectList, builder.context.toSql(null, rexOver), e.getRowType());
  }
  builder.setSelect(new SqlNodeList(selectList, POS));
  return builder.result();
}
 
Example 5
Source Project: calcite   Source File: PushProjector.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new projection based on the original projection, adjusting all
 * input refs using an adjustment array passed in. If there was no original
 * projection, create a new one that selects every field from the underlying
 * rel.
 *
 * <p>If the resulting projection would be trivial, return the child.
 *
 * @param projChild   child of the new project
 * @param adjustments array indicating how much each input reference should
 *                    be adjusted by
 * @return the created projection
 */
public RelNode createNewProject(RelNode projChild, int[] adjustments) {
  final List<Pair<RexNode, String>> projects = new ArrayList<>();

  if (origProj != null) {
    for (Pair<RexNode, String> p : origProj.getNamedProjects()) {
      projects.add(
          Pair.of(
              convertRefsAndExprs(
                  p.left,
                  projChild.getRowType().getFieldList(),
                  adjustments),
              p.right));
    }
  } else {
    for (Ord<RelDataTypeField> field : Ord.zip(childFields)) {
      projects.add(
          Pair.of(
              rexBuilder.makeInputRef(
                  field.e.getType(), field.i), field.e.getName()));
    }
  }
  return relBuilder.push(projChild)
      .project(Pair.left(projects), Pair.right(projects))
      .build();
}
 
Example 6
Source Project: calcite   Source File: RelOptTableImpl.java    License: Apache License 2.0 6 votes vote down vote up
/** Returns the row type of a table after any {@link ColumnStrategy#VIRTUAL}
 * columns have been removed. This is the type of the records that are
 * actually stored. */
public static RelDataType realRowType(RelOptTable table) {
  final RelDataType rowType = table.getRowType();
  final List<ColumnStrategy> strategies = columnStrategies(table);
  if (!strategies.contains(ColumnStrategy.VIRTUAL)) {
    return rowType;
  }
  final RelDataTypeFactory.Builder builder =
      table.getRelOptSchema().getTypeFactory().builder();
  for (RelDataTypeField field : rowType.getFieldList()) {
    if (strategies.get(field.getIndex()) != ColumnStrategy.VIRTUAL) {
      builder.add(field);
    }
  }
  return builder.build();
}
 
Example 7
Source Project: calcite   Source File: DruidQuery.java    License: Apache License 2.0 6 votes vote down vote up
private ColumnMetaData.Rep getPrimitive(RelDataTypeField field) {
  switch (field.getType().getSqlTypeName()) {
  case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
  case TIMESTAMP:
    return ColumnMetaData.Rep.JAVA_SQL_TIMESTAMP;
  case BIGINT:
    return ColumnMetaData.Rep.LONG;
  case INTEGER:
    return ColumnMetaData.Rep.INTEGER;
  case SMALLINT:
    return ColumnMetaData.Rep.SHORT;
  case TINYINT:
    return ColumnMetaData.Rep.BYTE;
  case REAL:
    return ColumnMetaData.Rep.FLOAT;
  case DOUBLE:
  case FLOAT:
    return ColumnMetaData.Rep.DOUBLE;
  default:
    return null;
  }
}
 
Example 8
Source Project: calcite   Source File: ExplicitOperandTypeChecker.java    License: Apache License 2.0 6 votes vote down vote up
public boolean checkOperandTypes(
    SqlCallBinding callBinding,
    boolean throwOnFailure) {
  List<SqlTypeFamily> families = new ArrayList<>();

  List<RelDataTypeField> fieldList = type.getFieldList();
  for (int i = 0; i < fieldList.size(); i++) {
    RelDataTypeField field = fieldList.get(i);
    SqlTypeName sqlTypeName = field.getType().getSqlTypeName();
    if (sqlTypeName == SqlTypeName.ROW) {
      if (field.getType().equals(callBinding.getOperandType(i))) {
        families.add(SqlTypeFamily.ANY);
      }
    } else {
      families.add(field.getType().getSqlTypeName().getFamily());
    }
  }
  return OperandTypes.family(families).checkOperandTypes(callBinding, throwOnFailure);
}
 
Example 9
Source Project: Bats   Source File: RuntimeFilterVisitor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Find a join condition's left input source scan Prel. If we can't find a target scan Prel then this
 * RuntimeFilter can not pushed down to a probe side scan Prel.
 *
 * @param fieldName   left join condition field Name
 * @param leftRelNode left RelNode of a BiRel or the SingleRel
 * @return a left scan Prel which contains the left join condition name or null
 */
private ScanPrel findLeftScanPrel(String fieldName, RelNode leftRelNode) {
  if (leftRelNode instanceof ScanPrel) {
    RelDataType scanRowType = leftRelNode.getRowType();
    RelDataTypeField field = scanRowType.getField(fieldName, true, true);
    if (field != null) {
      //found
      return (ScanPrel) leftRelNode;
    } else {
      return null;
    }
  } else if (leftRelNode instanceof RelSubset) {
    RelNode bestNode = ((RelSubset) leftRelNode).getBest();
    if (bestNode != null) {
      return findLeftScanPrel(fieldName, bestNode);
    } else {
      return null;
    }
  } else {
    List<RelNode> relNodes = leftRelNode.getInputs();
    RelNode leftNode = relNodes.get(0);
    return findLeftScanPrel(fieldName, leftNode);
  }
}
 
Example 10
Source Project: quark   Source File: PlanExecutor.java    License: Apache License 2.0 6 votes vote down vote up
private RelDataType getDataSourceRowType() throws SQLException {

    List<RelDataTypeField> relDataTypeFields =
        ImmutableList.<RelDataTypeField>of(
            new RelDataTypeFieldImpl("id", 1, getIntegerJavaType()),
            new RelDataTypeFieldImpl("type", 2, getStringJavaType()),
            new RelDataTypeFieldImpl("url", 3, getStringJavaType()),
            new RelDataTypeFieldImpl("name", 4, getStringJavaType()),
            new RelDataTypeFieldImpl("ds_set_id", 5, getIntegerJavaType()),
            new RelDataTypeFieldImpl("datasource_type", 6, getStringJavaType()),
            new RelDataTypeFieldImpl("auth_token", 7, getStringJavaType()),
            new RelDataTypeFieldImpl("dbtap_id", 8, getIntegerJavaType()),
            new RelDataTypeFieldImpl("username", 9, getStringJavaType()),
            new RelDataTypeFieldImpl("password", 10, getStringJavaType()));

    return new RelRecordType(relDataTypeFields);
  }
 
Example 11
Source Project: calcite   Source File: RelOptUtil.java    License: Apache License 2.0 6 votes vote down vote up
private static RexNode shiftFilter(
    int start,
    int end,
    int offset,
    RexBuilder rexBuilder,
    List<RelDataTypeField> joinFields,
    int nTotalFields,
    List<RelDataTypeField> rightFields,
    RexNode filter) {
  int[] adjustments = new int[nTotalFields];
  for (int i = start; i < end; i++) {
    adjustments[i] = offset;
  }
  return filter.accept(
      new RexInputConverter(
          rexBuilder,
          joinFields,
          rightFields,
          adjustments));
}
 
Example 12
Source Project: calcite   Source File: SqlTypeUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns whether two types are scalar types of the same family, or struct types whose fields
 * are pairwise of the same family.
 *
 * @param type1 First type
 * @param type2 Second type
 * @return Whether types have the same family
 */
private static boolean isSameFamily(RelDataType type1, RelDataType type2) {
  if (type1.isStruct() != type2.isStruct()) {
    return false;
  }

  if (type1.isStruct()) {
    int n = type1.getFieldCount();
    if (n != type2.getFieldCount()) {
      return false;
    }
    for (Pair<RelDataTypeField, RelDataTypeField> pair
        : Pair.zip(type1.getFieldList(), type2.getFieldList())) {
      if (!isSameFamily(pair.left.getType(), pair.right.getType())) {
        return false;
      }
    }
    return true;
  }

  final RelDataTypeFamily family1 = family(type1);
  final RelDataTypeFamily family2 = family(type2);
  return family1 == family2;
}
 
Example 13
Source Project: Bats   Source File: WithItemNamespace.java    License: Apache License 2.0 6 votes vote down vote up
@Override protected RelDataType validateImpl(RelDataType targetRowType) {
  final SqlValidatorNamespace childNs =
      validator.getNamespace(withItem.query);
  final RelDataType rowType = childNs.getRowTypeSansSystemColumns();
  if (withItem.columnList == null) {
    return rowType;
  }
  final RelDataTypeFactory.Builder builder =
      validator.getTypeFactory().builder();
  for (Pair<SqlNode, RelDataTypeField> pair
      : Pair.zip(withItem.columnList, rowType.getFieldList())) {
    builder.add(((SqlIdentifier) pair.left).getSimple(),
        pair.right.getType());
  }
  return builder.build();
}
 
Example 14
Source Project: calcite   Source File: RexTransformerTest.java    License: Apache License 2.0 6 votes vote down vote up
/** Test case for
 * <a href="https://issues.apache.org/jira/browse/CALCITE-833">[CALCITE-833]
 * RelOptUtil.splitJoinCondition attempts to split a Join-Condition which
 * has a remaining condition</a>. */
@Test void testSplitJoinCondition() {
  final String sql = "select *\n"
      + "from emp a\n"
      + "INNER JOIN dept b\n"
      + "ON CAST(a.empno AS int) <> b.deptno";

  final RelNode relNode = toRel(sql);
  final LogicalProject project = (LogicalProject) relNode;
  final LogicalJoin join = (LogicalJoin) project.getInput(0);
  final List<RexNode> leftJoinKeys = new ArrayList<>();
  final List<RexNode> rightJoinKeys = new ArrayList<>();
  final ArrayList<RelDataTypeField> sysFieldList = new ArrayList<>();
  final RexNode remaining = RelOptUtil.splitJoinCondition(sysFieldList,
      join.getInputs().get(0),
      join.getInputs().get(1),
      join.getCondition(),
      leftJoinKeys,
      rightJoinKeys,
      null,
      null);

  assertThat(remaining.toString(), is("<>($0, $9)"));
  assertThat(leftJoinKeys.isEmpty(), is(true));
  assertThat(rightJoinKeys.isEmpty(), is(true));
}
 
Example 15
Source Project: calcite   Source File: PushProjector.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Clones an expression tree and walks through it, adjusting each
 * RexInputRef index by some amount, and converting expressions that need to
 * be preserved to field references.
 *
 * @param rex         the expression
 * @param destFields  fields that the new expressions will be referencing
 * @param adjustments the amount each input reference index needs to be
 *                    adjusted by
 * @return modified expression tree
 */
public RexNode convertRefsAndExprs(
    RexNode rex,
    List<RelDataTypeField> destFields,
    int[] adjustments) {
  return rex.accept(
      new RefAndExprConverter(
          rexBuilder,
          childFields,
          destFields,
          adjustments,
          childPreserveExprs,
          nProject,
          rightPreserveExprs,
          nProject + childPreserveExprs.size() + nRightProject));
}
 
Example 16
Source Project: calcite   Source File: RelFieldTrimmer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Invokes {@link #trimFields}, or the appropriate method for the type
 * of the rel parameter, using multi-method dispatch.
 *
 * @param rel        Relational expression
 * @param fieldsUsed Bitmap of fields needed by the consumer
 * @return New relational expression and its field mapping
 */
protected final TrimResult dispatchTrimFields(
    RelNode rel,
    ImmutableBitSet fieldsUsed,
    Set<RelDataTypeField> extraFields) {
  final TrimResult trimResult =
      trimFieldsDispatcher.invoke(rel, fieldsUsed, extraFields);
  final RelNode newRel = trimResult.left;
  final Mapping mapping = trimResult.right;
  final int fieldCount = rel.getRowType().getFieldCount();
  assert mapping.getSourceCount() == fieldCount
      : "source: " + mapping.getSourceCount() + " != " + fieldCount;
  final int newFieldCount = newRel.getRowType().getFieldCount();
  assert mapping.getTargetCount() + extraFields.size() == newFieldCount
      || Bug.TODO_FIXED
      : "target: " + mapping.getTargetCount()
      + " + " + extraFields.size()
      + " != " + newFieldCount;
  if (Bug.TODO_FIXED) {
    assert newFieldCount > 0 : "rel has no fields after trim: " + rel;
  }
  if (newRel.equals(rel)) {
    return result(rel, mapping);
  }
  return trimResult;
}
 
Example 17
Source Project: calcite   Source File: RexProgram.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a program that projects its input fields but with possibly
 * different names for the output fields.
 */
public static RexProgram createIdentity(
    RelDataType rowType,
    RelDataType outputRowType) {
  if (rowType != outputRowType
      && !Pair.right(rowType.getFieldList()).equals(
          Pair.right(outputRowType.getFieldList()))) {
    throw new IllegalArgumentException(
        "field type mismatch: " + rowType + " vs. " + outputRowType);
  }
  final List<RelDataTypeField> fields = rowType.getFieldList();
  final List<RexLocalRef> projectRefs = new ArrayList<>();
  final List<RexInputRef> refs = new ArrayList<>();
  for (int i = 0; i < fields.size(); i++) {
    final RexInputRef ref = RexInputRef.of(i, fields);
    refs.add(ref);
    projectRefs.add(new RexLocalRef(i, ref.getType()));
  }
  return new RexProgram(rowType, refs, projectRefs, null, outputRowType);
}
 
Example 18
Source Project: flink   Source File: RelDecorrelator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Pulls a {@link Project} above a {@link Correlate} from its RHS input.
 * Enforces nullability for join output.
 *
 * @param correlate  Correlate
 * @param project the original project as the RHS input of the join
 * @param isCount Positions which are calls to the <code>COUNT</code>
 *                aggregation function
 * @return the subtree with the new Project at the root
 */
private RelNode aggregateCorrelatorOutput(
    Correlate correlate,
    LogicalProject project,
    Set<Integer> isCount) {
  final RelNode left = correlate.getLeft();
  final JoinRelType joinType = correlate.getJoinType();

  // now create the new project
  final List<Pair<RexNode, String>> newProjects = new ArrayList<>();

  // Project everything from the LHS and then those from the original
  // project
  final List<RelDataTypeField> leftInputFields =
      left.getRowType().getFieldList();

  for (int i = 0; i < leftInputFields.size(); i++) {
    newProjects.add(RexInputRef.of2(i, leftInputFields));
  }

  // Marked where the projected expr is coming from so that the types will
  // become nullable for the original projections which are now coming out
  // of the nullable side of the OJ.
  boolean projectPulledAboveLeftCorrelator =
      joinType.generatesNullsOnRight();

  for (Pair<RexNode, String> pair : project.getNamedProjects()) {
    RexNode newProjExpr =
        removeCorrelationExpr(
            pair.left,
            projectPulledAboveLeftCorrelator,
            isCount);
    newProjects.add(Pair.of(newProjExpr, pair.right));
  }

  return relBuilder.push(correlate)
      .projectNamed(Pair.left(newProjects), Pair.right(newProjects), true)
      .build();
}
 
Example 19
Source Project: calcite   Source File: PigRelBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Builds the projection expressions for a data type on top of an input data type.
 * For any field in output type, if there is no matching input field, we build
 * the literal null expression with the corresponding output field type.
 *
 * @param inputType The input data type
 * @param outputType The output data type that defines the types of projection expressions
 * @return List of projection expressions
 */
private List<RexNode> projects(RelDataType inputType, RelDataType outputType) {
  final List<RelDataTypeField> outputFields = outputType.getFieldList();
  final List<RelDataTypeField> inputFields = inputType.getFieldList();
  final List<RexNode> projectionExprs = new ArrayList<>();

  for (RelDataTypeField outputField : outputFields) {
    RelDataTypeField matchInputField = null;
    // First find the matching input field
    for (RelDataTypeField inputField : inputFields) {
      if (inputField.getName().equals(outputField.getName())) {
        // Matched if same name
        matchInputField = inputField;
        break;
      }
    }
    if (matchInputField != null) {
      RexNode fieldProject = field(matchInputField.getIndex());
      if (matchInputField.getType().equals(outputField.getType())) {
        // If found and on same type, just project the field
        projectionExprs.add(fieldProject);
      } else {
        // Different types, CAST is required
        projectionExprs.add(getRexBuilder().makeCast(outputField.getType(), fieldProject));
      }
    } else {
      final RelDataType columnType = outputField.getType();
      if (!columnType.isStruct() && columnType.getComponentType() == null) {
        // If not, project the null Literal with the same basic type
        projectionExprs.add(getRexBuilder().makeNullLiteral(outputField.getType()));
      } else {
        // If Record or Multiset just project a constant null
        projectionExprs.add(literal(null));
      }
    }
  }
  return projectionExprs;
}
 
Example 20
Source Project: calcite   Source File: CalcitePrepareImpl.java    License: Apache License 2.0 5 votes vote down vote up
private List<ColumnMetaData> getColumnMetaDataList(
    JavaTypeFactory typeFactory, RelDataType x, RelDataType jdbcType,
    List<List<String>> originList) {
  final List<ColumnMetaData> columns = new ArrayList<>();
  for (Ord<RelDataTypeField> pair : Ord.zip(jdbcType.getFieldList())) {
    final RelDataTypeField field = pair.e;
    final RelDataType type = field.getType();
    final RelDataType fieldType =
        x.isStruct() ? x.getFieldList().get(pair.i).getType() : type;
    columns.add(
        metaData(typeFactory, columns.size(), field.getName(), type,
            fieldType, originList.get(pair.i)));
  }
  return columns;
}
 
Example 21
Source Project: Bats   Source File: LogicalJoin.java    License: Apache License 2.0 5 votes vote down vote up
@Deprecated // to be removed before 2.0
public static LogicalJoin create(RelNode left, RelNode right,
    RexNode condition, JoinRelType joinType, Set<String> variablesStopped,
    boolean semiJoinDone, ImmutableList<RelDataTypeField> systemFieldList) {
  return create(left, right, condition, CorrelationId.setOf(variablesStopped),
      joinType, semiJoinDone, systemFieldList);
}
 
Example 22
Source Project: calcite   Source File: RelStructuredTypeFlattener.java    License: Apache License 2.0 5 votes vote down vote up
private void flattenNullLiteral(
    RelDataType type,
    List<Pair<RexNode, String>> flattenedExps) {
  RelDataType flattenedType =
      SqlTypeUtil.flattenRecordType(rexBuilder.getTypeFactory(), type, null);
  for (RelDataTypeField field : flattenedType.getFieldList()) {
    flattenedExps.add(
        Pair.of(
            rexBuilder.makeNullLiteral(field.getType()),
            field.getName()));
  }
}
 
Example 23
Source Project: dremio-oss   Source File: PrelWithDictionaryInfo.java    License: Apache License 2.0 5 votes vote down vote up
static RelDataType toRowDataType(Collection<RelDataTypeField> fields, RelDataTypeFactory factory) {
  final RelDataTypeFactory.FieldInfoBuilder builder = new RelDataTypeFactory.FieldInfoBuilder(factory);
  for (RelDataTypeField field: fields) {
    builder.add(field);
  }
  return builder.build();
}
 
Example 24
Source Project: calcite   Source File: AliasNamespace.java    License: Apache License 2.0 5 votes vote down vote up
public String translate(String name) {
  final RelDataType underlyingRowType =
      validator.getValidatedNodeType(call.operand(0));
  int i = 0;
  for (RelDataTypeField field : rowType.getFieldList()) {
    if (field.getName().equals(name)) {
      return underlyingRowType.getFieldList().get(i).getName();
    }
    ++i;
  }
  throw new AssertionError("unknown field '" + name
      + "' in rowtype " + underlyingRowType);
}
 
Example 25
Source Project: calcite   Source File: GeodeAggregate.java    License: Apache License 2.0 5 votes vote down vote up
private List<String> fieldNames(RelDataType relDataType) {
  ArrayList<String> names = new ArrayList<>();

  for (RelDataTypeField rdtf : relDataType.getFieldList()) {
    names.add(rdtf.getName());
  }
  return names;
}
 
Example 26
Source Project: dremio-oss   Source File: PrelTransformer.java    License: Apache License 2.0 5 votes vote down vote up
public static Rel addRenamedProject(SqlHandlerConfig config, Rel 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.F_SUGGESTER,
          rel.getCluster().getTypeFactory().getTypeSystem().isSchemaCaseSensitive());

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

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

  final boolean hasAnyType = Iterables.find(
      validatedRowType.getFieldList(),
      new Predicate<RelDataTypeField>() {
        @Override
        public boolean apply(@Nullable RelDataTypeField input) {
          return input.getType().getSqlTypeName() == SqlTypeName.ANY;
        }
      },
      null
  ) != null;

  // Add a final non-trivial Project to get the validatedRowType, if child is not project or the input row type
  // contains at least one field of type ANY
  if (rel instanceof Project && MoreRelOptUtil.isTrivialProject(topProj, true) && !hasAnyType) {
    return rel;
  }

  return topProj;
}
 
Example 27
Source Project: calcite   Source File: RelFieldTrimmer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Trims the fields of an input relational expression.
 *
 * @param rel        Relational expression
 * @param input      Input relational expression, whose fields to trim
 * @param fieldsUsed Bitmap of fields needed by the consumer
 * @return New relational expression and its field mapping
 */
protected TrimResult trimChild(
    RelNode rel,
    RelNode input,
    final ImmutableBitSet fieldsUsed,
    Set<RelDataTypeField> extraFields) {
  final ImmutableBitSet.Builder fieldsUsedBuilder = fieldsUsed.rebuild();

  // Fields that define the collation cannot be discarded.
  final RelMetadataQuery mq = rel.getCluster().getMetadataQuery();
  final ImmutableList<RelCollation> collations = mq.collations(input);
  for (RelCollation collation : collations) {
    for (RelFieldCollation fieldCollation : collation.getFieldCollations()) {
      fieldsUsedBuilder.set(fieldCollation.getFieldIndex());
    }
  }

  // Correlating variables are a means for other relational expressions to use
  // fields.
  for (final CorrelationId correlation : rel.getVariablesSet()) {
    rel.accept(
        new CorrelationReferenceFinder() {
          protected RexNode handle(RexFieldAccess fieldAccess) {
            final RexCorrelVariable v =
                (RexCorrelVariable) fieldAccess.getReferenceExpr();
            if (v.id.equals(correlation)) {
              fieldsUsedBuilder.set(fieldAccess.getField().getIndex());
            }
            return fieldAccess;
          }
        });
  }

  return dispatchTrimFields(input, fieldsUsedBuilder.build(), extraFields);
}
 
Example 28
Source Project: Bats   Source File: RelOptTableImpl.java    License: Apache License 2.0 5 votes vote down vote up
/** Returns the row type of a table after any {@link ColumnStrategy#VIRTUAL}
 * columns have been removed. This is the type of the records that are
 * actually stored. */
public static RelDataType realRowType(RelOptTable table) {
    final RelDataType rowType = table.getRowType();
    final List<ColumnStrategy> strategies = columnStrategies(table);
    if (!strategies.contains(ColumnStrategy.VIRTUAL)) {
        return rowType;
    }
    final RelDataTypeFactory.Builder builder = table.getRelOptSchema().getTypeFactory().builder();
    for (RelDataTypeField field : rowType.getFieldList()) {
        if (strategies.get(field.getIndex()) != ColumnStrategy.VIRTUAL) {
            builder.add(field);
        }
    }
    return builder.build();
}
 
Example 29
Source Project: dremio-oss   Source File: ReflectionAnalyzer.java    License: Apache License 2.0 5 votes vote down vote up
protected Iterable<StatColumn> getStatColumnsPerField(final RelDataTypeField field) {
  final RelDataTypeFamily family = field.getType().getFamily();
  Collection<StatType> dims = DIMENSIONS.get(family);
  if (dims.isEmpty()) {
    dims = DIMENSIONS.get(SqlTypeFamily.ANY);
  }

  return FluentIterable.from(dims)
    .transform(new Function<StatType, StatColumn>() {
      @Override
      public StatColumn apply(final StatType type) {
        return new StatColumn(type, field);
      }
    });
}
 
Example 30
Source Project: Bats   Source File: LoptMultiJoin.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the fields corresponding to a join between a left and right
 * tree
 *
 * @param left left hand side of the join
 * @param right right hand side of the join
 *
 * @return fields of the join
 */
public List<RelDataTypeField> getJoinFields(
    LoptJoinTree left,
    LoptJoinTree right) {
  RelDataType rowType =
      factory.createJoinType(
          left.getJoinTree().getRowType(),
          right.getJoinTree().getRowType());
  return rowType.getFieldList();
}