org.apache.calcite.util.ImmutableIntList Java Examples

The following examples show how to use org.apache.calcite.util.ImmutableIntList. 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: TableScanNode.java    From calcite with Apache License 2.0 6 votes vote down vote up
private static TableScanNode createFilterable(Compiler compiler,
    TableScan rel, ImmutableList<RexNode> filters, ImmutableIntList projects,
    FilterableTable filterableTable) {
  final DataContext root = compiler.getDataContext();
  final List<RexNode> mutableFilters = Lists.newArrayList(filters);
  final Enumerable<Object[]> enumerable =
      filterableTable.scan(root, mutableFilters);
  for (RexNode filter : mutableFilters) {
    if (!filters.contains(filter)) {
      throw RESOURCE.filterableTableInventedFilter(filter.toString()).ex();
    }
  }
  final Enumerable<Row> rowEnumerable = Enumerables.toRow(enumerable);
  return createEnumerable(compiler, rel, rowEnumerable, null,
      mutableFilters, projects);
}
 
Example #2
Source File: FilterTableScanRule.java    From calcite with Apache License 2.0 6 votes vote down vote up
protected void apply(RelOptRuleCall call, Filter filter, TableScan scan) {
  final ImmutableIntList projects;
  final ImmutableList.Builder<RexNode> filters = ImmutableList.builder();
  if (scan instanceof Bindables.BindableTableScan) {
    final Bindables.BindableTableScan bindableScan =
        (Bindables.BindableTableScan) scan;
    filters.addAll(bindableScan.filters);
    projects = bindableScan.projects;
  } else {
    projects = scan.identity();
  }

  final Mapping mapping = Mappings.target(projects,
      scan.getTable().getRowType().getFieldCount());
  filters.add(
      RexUtil.apply(mapping.inverse(), filter.getCondition()));

  call.transformTo(
      Bindables.BindableTableScan.create(scan.getCluster(), scan.getTable(),
          filters.build(), projects));
}
 
Example #3
Source File: FlinkRelMdCollation.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Helper method to determine a {@link Join}'s collation assuming that it
 * uses a merge-join algorithm.
 *
 * <p>If the inputs are sorted on other keys <em>in addition to</em> the join
 * key, the result preserves those collations too.
 */
public static List<RelCollation> mergeJoin(
		RelMetadataQuery mq,
		RelNode left, RelNode right,
		ImmutableIntList leftKeys,
		ImmutableIntList rightKeys) {
	final com.google.common.collect.ImmutableList.Builder<RelCollation> builder =
			com.google.common.collect.ImmutableList.builder();

	final com.google.common.collect.ImmutableList<RelCollation> leftCollations = mq.collations(left);
	assert RelCollations.contains(leftCollations, leftKeys)
			: "cannot merge join: left input is not sorted on left keys";
	builder.addAll(leftCollations);

	final com.google.common.collect.ImmutableList<RelCollation> rightCollations = mq.collations(right);
	assert RelCollations.contains(rightCollations, rightKeys)
			: "cannot merge join: right input is not sorted on right keys";
	final int leftFieldCount = left.getRowType().getFieldCount();
	for (RelCollation collation : rightCollations) {
		builder.add(RelCollations.shift(collation, leftFieldCount));
	}
	return builder.build();
}
 
Example #4
Source File: AggregateReduceFunctionsRule.java    From calcite with Apache License 2.0 6 votes vote down vote up
private RexNode getRegrCountRexNode(Aggregate oldAggRel,
    AggregateCall oldCall,
    List<AggregateCall> newCalls,
    Map<AggregateCall, RexNode> aggCallMapping,
    ImmutableIntList argOrdinals,
    ImmutableList<RelDataType> operandTypes,
    int filterArg) {
  final AggregateCall countArgAggCall =
      AggregateCall.create(SqlStdOperatorTable.REGR_COUNT,
          oldCall.isDistinct(),
          oldCall.isApproximate(),
          oldCall.ignoreNulls(),
          argOrdinals,
          filterArg,
          oldCall.collation,
          oldAggRel.getGroupCount(),
          oldAggRel,
          null,
          null);

  return oldAggRel.getCluster().getRexBuilder().addAggCall(countArgAggCall,
      oldAggRel.getGroupCount(),
      newCalls,
      aggCallMapping,
      operandTypes);
}
 
Example #5
Source File: AggregateReduceFunctionsRule.java    From calcite with Apache License 2.0 6 votes vote down vote up
private AggregateCall createAggregateCallWithBinding(
    RelDataTypeFactory typeFactory,
    SqlAggFunction aggFunction,
    RelDataType operandType,
    Aggregate oldAggRel,
    AggregateCall oldCall,
    int argOrdinal,
    int filter) {
  final Aggregate.AggCallBinding binding =
      new Aggregate.AggCallBinding(typeFactory, aggFunction,
          ImmutableList.of(operandType), oldAggRel.getGroupCount(),
          filter >= 0);
  return AggregateCall.create(aggFunction,
      oldCall.isDistinct(),
      oldCall.isApproximate(),
      oldCall.ignoreNulls(),
      ImmutableIntList.of(argOrdinal),
      filter,
      oldCall.collation,
      aggFunction.inferReturnType(binding),
      null);
}
 
Example #6
Source File: AggregateReduceFunctionsRule.java    From Bats with Apache License 2.0 6 votes vote down vote up
private AggregateCall createAggregateCallWithBinding(
    RelDataTypeFactory typeFactory,
    SqlAggFunction aggFunction,
    RelDataType operandType,
    Aggregate oldAggRel,
    AggregateCall oldCall,
    int argOrdinal,
    int filter) {
  final Aggregate.AggCallBinding binding =
      new Aggregate.AggCallBinding(typeFactory, aggFunction,
          ImmutableList.of(operandType), oldAggRel.getGroupCount(),
          filter >= 0);
  return AggregateCall.create(aggFunction,
      oldCall.isDistinct(),
      oldCall.isApproximate(),
      ImmutableIntList.of(argOrdinal),
      filter,
      oldCall.collation,
      aggFunction.inferReturnType(binding),
      null);
}
 
Example #7
Source File: EnumerableSortedAggregateRule.java    From calcite with Apache License 2.0 6 votes vote down vote up
public RelNode convert(RelNode rel) {
  final LogicalAggregate agg = (LogicalAggregate) rel;
  if (!Aggregate.isSimple(agg)) {
    return null;
  }
  final RelTraitSet inputTraits = rel.getCluster()
      .traitSet().replace(EnumerableConvention.INSTANCE)
      .replace(
          RelCollations.of(
              ImmutableIntList.copyOf(
          agg.getGroupSet().asList())));
  final RelTraitSet selfTraits = inputTraits.replace(
      RelCollations.of(
      ImmutableIntList.identity(agg.getGroupSet().cardinality())));
  return new EnumerableSortedAggregate(
      rel.getCluster(),
      selfTraits,
      convert(agg.getInput(), inputTraits),
      agg.getGroupSet(),
      agg.getGroupSets(),
      agg.getAggCallList());
}
 
Example #8
Source File: AggregateReduceFunctionsRule.java    From Bats with Apache License 2.0 6 votes vote down vote up
private RexNode getRegrCountRexNode(Aggregate oldAggRel,
    AggregateCall oldCall,
    List<AggregateCall> newCalls,
    Map<AggregateCall, RexNode> aggCallMapping,
    ImmutableIntList argOrdinals,
    ImmutableList<RelDataType> operandTypes,
    int filterArg) {
  final AggregateCall countArgAggCall =
      AggregateCall.create(SqlStdOperatorTable.REGR_COUNT,
          oldCall.isDistinct(),
          oldCall.isApproximate(),
          argOrdinals,
          filterArg,
          oldCall.collation,
          oldAggRel.getGroupCount(),
          oldAggRel,
          null,
          null);

  return oldAggRel.getCluster().getRexBuilder().addAggCall(countArgAggCall,
      oldAggRel.getGroupCount(),
      oldAggRel.indicator,
      newCalls,
      aggCallMapping,
      operandTypes);
}
 
Example #9
Source File: RelMdCollation.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Helper method to determine a {@link Join}'s collation assuming that it
 * uses a merge-join algorithm.
 *
 * <p>If the inputs are sorted on other keys <em>in addition to</em> the join
 * key, the result preserves those collations too. */
public static List<RelCollation> mergeJoin(RelMetadataQuery mq,
    RelNode left, RelNode right,
    ImmutableIntList leftKeys, ImmutableIntList rightKeys, JoinRelType joinType) {
  assert EnumerableMergeJoin.isMergeJoinSupported(joinType)
      : "EnumerableMergeJoin unsupported for join type " + joinType;

  final ImmutableList<RelCollation> leftCollations = mq.collations(left);
  if (!joinType.projectsRight()) {
    return leftCollations;
  }

  final ImmutableList.Builder<RelCollation> builder = ImmutableList.builder();
  builder.addAll(leftCollations);

  final ImmutableList<RelCollation> rightCollations = mq.collations(right);
  final int leftFieldCount = left.getRowType().getFieldCount();
  for (RelCollation collation : rightCollations) {
    builder.add(RelCollations.shift(collation, leftFieldCount));
  }
  return builder.build();
}
 
Example #10
Source File: ModifiableViewTable.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a mapping from the view index to the index in the underlying table.
 */
private static ImmutableIntList getNewColumnMapping(Table underlying,
    ImmutableIntList oldColumnMapping, List<RelDataTypeField> extendedColumns,
    RelDataTypeFactory typeFactory) {
  final List<RelDataTypeField> baseColumns =
      underlying.getRowType(typeFactory).getFieldList();
  final Map<String, Integer> nameToIndex = mapNameToIndex(baseColumns);

  final ImmutableList.Builder<Integer> newMapping = ImmutableList.builder();
  newMapping.addAll(oldColumnMapping);
  int newMappedIndex = baseColumns.size();
  for (RelDataTypeField extendedColumn : extendedColumns) {
    if (nameToIndex.containsKey(extendedColumn.getName())) {
      // The extended column duplicates a column in the underlying table.
      // Map to the index in the underlying table.
      newMapping.add(nameToIndex.get(extendedColumn.getName()));
    } else {
      // The extended column is not in the underlying table.
      newMapping.add(newMappedIndex++);
    }
  }
  return ImmutableIntList.copyOf(newMapping.build());
}
 
Example #11
Source File: ModifiableViewTable.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a mapping from the view index to the index in the underlying table.
 */
private static ImmutableIntList getNewColumnMapping(Table underlying,
    ImmutableIntList oldColumnMapping, List<RelDataTypeField> extendedColumns,
    RelDataTypeFactory typeFactory) {
  final List<RelDataTypeField> baseColumns =
      underlying.getRowType(typeFactory).getFieldList();
  final Map<String, Integer> nameToIndex = mapNameToIndex(baseColumns);

  final ImmutableList.Builder<Integer> newMapping = ImmutableList.builder();
  newMapping.addAll(oldColumnMapping);
  int newMappedIndex = baseColumns.size();
  for (RelDataTypeField extendedColumn : extendedColumns) {
    if (nameToIndex.containsKey(extendedColumn.getName())) {
      // The extended column duplicates a column in the underlying table.
      // Map to the index in the underlying table.
      newMapping.add(nameToIndex.get(extendedColumn.getName()));
    } else {
      // The extended column is not in the underlying table.
      newMapping.add(newMappedIndex++);
    }
  }
  return ImmutableIntList.copyOf(newMapping.build());
}
 
Example #12
Source File: RelCollation.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the ordinals of the key columns.
 */
default @Nonnull ImmutableIntList getKeys() {
  final List<RelFieldCollation> collations = getFieldCollations();
  final int size = collations.size();
  final int[] keys = new int[size];
  for (int i = 0; i < size; i++) {
    keys[i] = collations.get(i).getFieldIndex();
  }
  return ImmutableIntList.of(keys);
}
 
Example #13
Source File: StarTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
public RelDataType getRowType(RelDataTypeFactory typeFactory) {
  final List<RelDataType> typeList = new ArrayList<>();
  final List<Integer> fieldCounts = new ArrayList<>();
  for (Table table : tables) {
    final RelDataType rowType = table.getRowType(typeFactory);
    typeList.addAll(RelOptUtil.getFieldTypeList(rowType));
    fieldCounts.add(rowType.getFieldCount());
  }
  // Compute fieldCounts the first time this method is called. Safe to assume
  // that the field counts will be the same whichever type factory is used.
  if (this.fieldCounts == null) {
    this.fieldCounts = ImmutableIntList.copyOf(fieldCounts);
  }
  return typeFactory.createStructType(typeList, lattice.uniqueColumnNames());
}
 
Example #14
Source File: RelCollations.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Returns whether one of a list of collations indicates that the collection
 * is sorted on the given list of keys. */
public static boolean contains(List<RelCollation> collations,
    ImmutableIntList keys) {
  final List<Integer> distinctKeys = Util.distinctList(keys);
  for (RelCollation collation : collations) {
    if (contains(collation, distinctKeys)) {
      return true;
    }
  }
  return false;
}
 
Example #15
Source File: ProjectToWindowRule.java    From calcite with Apache License 2.0 5 votes vote down vote up
private List<Integer> getRank(DirectedGraph<Integer, DefaultEdge> graph) {
  final int[] rankArr = new int[graph.vertexSet().size()];
  int rank = 0;
  for (int i : TopologicalOrderIterator.of(graph)) {
    rankArr[i] = rank++;
  }
  return ImmutableIntList.of(rankArr);
}
 
Example #16
Source File: EnumerableMergeJoin.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Deprecated // to be removed before 2.0
EnumerableMergeJoin(RelOptCluster cluster, RelTraitSet traits, RelNode left,
    RelNode right, RexNode condition, ImmutableIntList leftKeys,
    ImmutableIntList rightKeys, Set<CorrelationId> variablesSet,
    JoinRelType joinType) {
  this(cluster, traits, left, right, condition, variablesSet, joinType);
}
 
Example #17
Source File: AggregateExpandDistinctAggregatesRule.java    From calcite with Apache License 2.0 5 votes vote down vote up
private static List<Integer> remap(ImmutableBitSet groupSet,
    List<Integer> argList) {
  ImmutableIntList list = ImmutableIntList.of();
  for (int arg : argList) {
    list = list.append(remap(groupSet, arg));
  }
  return list;
}
 
Example #18
Source File: RelMdCollation.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Helper method to determine a {@link Join}'s collation assuming that it
 * uses a merge-join algorithm.
 *
 * <p>If the inputs are sorted on other keys <em>in addition to</em> the join
 * key, the result preserves those collations too.
 * @deprecated Use {@link #mergeJoin(RelMetadataQuery, RelNode, RelNode, ImmutableIntList, ImmutableIntList, JoinRelType)} */
@Deprecated // to be removed before 2.0
public static List<RelCollation> mergeJoin(RelMetadataQuery mq,
    RelNode left, RelNode right,
    ImmutableIntList leftKeys, ImmutableIntList rightKeys) {
  return mergeJoin(mq, left, right, leftKeys, rightKeys, JoinRelType.INNER);
}
 
Example #19
Source File: RelRoot.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Creates a simple RelRoot. */
public static RelRoot of(RelNode rel, RelDataType rowType, SqlKind kind) {
  final ImmutableIntList refs =
      ImmutableIntList.identity(rowType.getFieldCount());
  final List<String> names = rowType.getFieldNames();
  return new RelRoot(rel, rowType, kind, Pair.zip(refs, names),
      RelCollations.EMPTY, new ArrayList<>());
}
 
Example #20
Source File: MockCatalogReader.java    From calcite with Apache License 2.0 5 votes vote down vote up
MockModifiableViewTable(Type elementType, RelProtoDataType rowType,
    String viewSql, List<String> schemaPath, List<String> viewPath,
    Table table, Path tablePath, RexNode constraint,
    ImmutableIntList columnMapping) {
  super(elementType, rowType, viewSql, schemaPath, viewPath, table,
      tablePath, constraint, columnMapping);
  this.constraint = constraint;
}
 
Example #21
Source File: EnumerableMergeJoin.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Deprecated // to be removed before 2.0
EnumerableMergeJoin(RelOptCluster cluster, RelTraitSet traits, RelNode left,
    RelNode right, RexNode condition, ImmutableIntList leftKeys,
    ImmutableIntList rightKeys, JoinRelType joinType,
    Set<String> variablesStopped) {
  this(cluster, traits, left, right, condition, leftKeys, rightKeys,
      CorrelationId.setOf(variablesStopped), joinType);
}
 
Example #22
Source File: EquiJoin.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Deprecated // to be removed before 2.0
public EquiJoin(RelOptCluster cluster, RelTraitSet traits, RelNode left,
    RelNode right, RexNode condition, ImmutableIntList leftKeys,
    ImmutableIntList rightKeys, JoinRelType joinType,
    Set<String> variablesStopped) {
  this(cluster, traits, left, right, condition, leftKeys, rightKeys,
      CorrelationId.setOf(variablesStopped), joinType);
}
 
Example #23
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
/** Moves fields according to the permutation. */
public void permute(List<SqlNode> selectItems,
	List<Map.Entry<String, RelDataType>> fields) {
	if (trivial) {
		return;
	}

	final List<SqlNode> oldSelectItems = ImmutableList.copyOf(selectItems);
	selectItems.clear();
	final List<Map.Entry<String, RelDataType>> oldFields =
		ImmutableList.copyOf(fields);
	fields.clear();
	for (ImmutableIntList source : sources) {
		final int p0 = source.get(0);
		Map.Entry<String, RelDataType> field = oldFields.get(p0);
		final String name = field.getKey();
		RelDataType type = field.getValue();
		SqlNode selectItem = oldSelectItems.get(p0);
		for (int p1 : Util.skip(source)) {
			final Map.Entry<String, RelDataType> field1 = oldFields.get(p1);
			final SqlNode selectItem1 = oldSelectItems.get(p1);
			final RelDataType type1 = field1.getValue();
			// output is nullable only if both inputs are
			final boolean nullable = type.isNullable() && type1.isNullable();
			final RelDataType type2 =
				SqlTypeUtil.leastRestrictiveForComparison(typeFactory, type,
					type1);
			selectItem =
				SqlStdOperatorTable.AS.createCall(SqlParserPos.ZERO,
					SqlStdOperatorTable.COALESCE.createCall(SqlParserPos.ZERO,
						maybeCast(selectItem, type, type2),
						maybeCast(selectItem1, type1, type2)),
					new SqlIdentifier(name, SqlParserPos.ZERO));
			type = typeFactory.createTypeWithNullability(type2, nullable);
		}
		fields.add(Pair.of(name, type));
		selectItems.add(selectItem);
	}
}
 
Example #24
Source File: Window.java    From calcite with Apache License 2.0 5 votes vote down vote up
public static ImmutableIntList getProjectOrdinals(final List<RexNode> exprs) {
  return ImmutableIntList.copyOf(
      new AbstractList<Integer>() {
        public Integer get(int index) {
          return ((RexSlot) exprs.get(index)).getIndex();
        }

        public int size() {
          return exprs.size();
        }
      });
}
 
Example #25
Source File: RelDistributions.java    From calcite with Apache License 2.0 5 votes vote down vote up
private RelDistributionImpl(Type type, ImmutableIntList keys) {
  this.type = Objects.requireNonNull(type);
  this.keys = ImmutableIntList.copyOf(keys);
  assert type != Type.HASH_DISTRIBUTED
      || keys.size() < 2
      || Ordering.natural().isOrdered(keys)
      : "key columns of hash distribution must be in order";
  assert type == Type.HASH_DISTRIBUTED
      || type == Type.RANDOM_DISTRIBUTED
      || keys.isEmpty();
}
 
Example #26
Source File: CalciteResult.java    From Bats with Apache License 2.0 5 votes vote down vote up
public AnalyzeViewResult(SqlValidator validator, String sql, SqlNode sqlNode, RelDataType rowType, RelRoot root,
        Table table, ImmutableList<String> tablePath, RexNode constraint, ImmutableIntList columnMapping,
        boolean modifiable) {
    super(validator, sql, sqlNode, rowType, root);
    this.table = table;
    this.tablePath = tablePath;
    this.constraint = constraint;
    this.columnMapping = columnMapping;
    this.modifiable = modifiable;
    Preconditions.checkArgument(modifiable == (table != null));
}
 
Example #27
Source File: StarTable.java    From Bats with Apache License 2.0 5 votes vote down vote up
public RelDataType getRowType(RelDataTypeFactory typeFactory) {
  final List<RelDataType> typeList = new ArrayList<>();
  final List<Integer> fieldCounts = new ArrayList<>();
  for (Table table : tables) {
    final RelDataType rowType = table.getRowType(typeFactory);
    typeList.addAll(RelOptUtil.getFieldTypeList(rowType));
    fieldCounts.add(rowType.getFieldCount());
  }
  // Compute fieldCounts the first time this method is called. Safe to assume
  // that the field counts will be the same whichever type factory is used.
  if (this.fieldCounts == null) {
    this.fieldCounts = ImmutableIntList.copyOf(fieldCounts);
  }
  return typeFactory.createStructType(typeList, lattice.uniqueColumnNames());
}
 
Example #28
Source File: ModifiableViewTable.java    From Bats with Apache License 2.0 5 votes vote down vote up
/** Creates a ModifiableViewTable. */
public ModifiableViewTable(Type elementType, RelProtoDataType rowType,
    String viewSql, List<String> schemaPath, List<String> viewPath,
    Table table, Path tablePath, RexNode constraint,
    ImmutableIntList columnMapping) {
  super(elementType, rowType, viewSql, schemaPath, viewPath);
  this.table = table;
  this.tablePath = tablePath;
  this.constraint = constraint;
  this.columnMapping = columnMapping;
  this.initializerExpressionFactory = new ModifiableViewTableInitializerExpressionFactory();
}
 
Example #29
Source File: RelBuilder.java    From Bats with Apache License 2.0 5 votes vote down vote up
private GroupKey groupKey_(ImmutableBitSet groupSet, boolean indicator, ImmutableList<ImmutableBitSet> groupSets) {
    if (groupSet.length() > peek().getRowType().getFieldCount()) {
        throw new IllegalArgumentException("out of bounds: " + groupSet);
    }
    Objects.requireNonNull(groupSets);
    final ImmutableList<RexNode> nodes = fields(ImmutableIntList.of(groupSet.toArray()));
    final List<ImmutableList<RexNode>> nodeLists = Util.transform(groupSets,
            bitSet -> fields(ImmutableIntList.of(bitSet.toArray())));
    return groupKey_(nodes, indicator, nodeLists);
}
 
Example #30
Source File: EnumerableMergeJoin.java    From calcite with Apache License 2.0 5 votes vote down vote up
private Mappings.TargetMapping buildMapping(boolean left2Right) {
  ImmutableIntList sourceKeys = left2Right ? joinInfo.leftKeys : joinInfo.rightKeys;
  ImmutableIntList targetKeys = left2Right ? joinInfo.rightKeys : joinInfo.leftKeys;
  Map<Integer, Integer> keyMap = new HashMap<>();
  for (int i = 0; i < joinInfo.leftKeys.size(); i++) {
    keyMap.put(sourceKeys.get(i), targetKeys.get(i));
  }

  Mappings.TargetMapping mapping = Mappings.target(keyMap,
      (left2Right ? left : right).getRowType().getFieldCount(),
      (left2Right ? right : left).getRowType().getFieldCount());
  return mapping;
}