org.apache.calcite.rel.core.Calc Java Examples

The following examples show how to use org.apache.calcite.rel.core.Calc. 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: RelMdColumnOrigins.java    From calcite with Apache License 2.0 6 votes vote down vote up
public Set<RelColumnOrigin> getColumnOrigins(Calc rel,
    final RelMetadataQuery mq, int iOutputColumn) {
  final RelNode input = rel.getInput();
  final RexShuttle rexShuttle = new RexShuttle() {
    @Override public RexNode visitLocalRef(RexLocalRef localRef) {
      return rel.getProgram().expandLocalRef(localRef);
    }
  };
  final List<RexNode> projects = new ArrayList<>();
  for (RexNode rex: rexShuttle.apply(rel.getProgram().getProjectList())) {
    projects.add(rex);
  }
  final RexNode rexNode = projects.get(iOutputColumn);
  if (rexNode instanceof RexInputRef) {
    // Direct reference:  no derivation added.
    RexInputRef inputRef = (RexInputRef) rexNode;
    return mq.getColumnOrigins(input, inputRef.getIndex());
  }
  // Anything else is a derivation, possibly from multiple columns.
  final Set<RelColumnOrigin> set = getMultipleColumns(rexNode, input, mq);
  return createDerivedColumnOrigins(set);
}
 
Example #2
Source File: CalcRelSplitter.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs a CalcRelSplitter.
 *
 * @param calc     Calc to split
 * @param relTypes Array of rel types, e.g. {Java, Fennel}. Must be
 *                 distinct.
 */
CalcRelSplitter(Calc calc, RelBuilder relBuilder, RelType[] relTypes) {
    this.relBuilder = relBuilder;
    for (int i = 0; i < relTypes.length; i++) {
        assert relTypes[i] != null;
        for (int j = 0; j < i; j++) {
            assert relTypes[i] != relTypes[j] : "Rel types must be distinct";
        }
    }
    this.program = calc.getProgram();
    this.cluster = calc.getCluster();
    this.traits = calc.getTraitSet();
    this.typeFactory = calc.getCluster().getTypeFactory();
    this.child = calc.getInput();
    this.relTypes = relTypes;
}
 
Example #3
Source File: RelToSqlConverter.java    From quark with Apache License 2.0 6 votes vote down vote up
public Result visitCalc(Calc e) {
  Result x = visitChild(0, e.getInput());
  final RexProgram program = e.getProgram();
  Builder builder =
      program.getCondition() != null
          ? x.builder(e, Clause.WHERE)
          : x.builder(e);
  if (!isStar(program)) {
    final List<SqlNode> selectList = new ArrayList<>();
    for (RexLocalRef ref : program.getProjectList()) {
      SqlNode sqlExpr = builder.context.toSql(program, ref);
      addSelect(selectList, sqlExpr, e.getRowType());
    }
    builder.setSelect(new SqlNodeList(selectList, POS));
  }

  if (program.getCondition() != null) {
    builder.setWhere(
        builder.context.toSql(program, program.getCondition()));
  }
  return builder.result();
}
 
Example #4
Source File: RelToSqlConverter.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** @see #dispatch */
public Result visit(Calc e) {
  Result x = visitChild(0, e.getInput());
  parseCorrelTable(e, x);
  final RexProgram program = e.getProgram();
  Builder builder =
      program.getCondition() != null
          ? x.builder(e, Clause.WHERE)
          : x.builder(e);
  if (!isStar(program)) {
    final List<SqlNode> selectList = new ArrayList<>(program.getProjectList().size());
    for (RexLocalRef ref : program.getProjectList()) {
      SqlNode sqlExpr = builder.context.toSql(program, ref);
      addSelect(selectList, sqlExpr, e.getRowType());
    }
    builder.setSelect(new SqlNodeList(selectList, POS));
  }

  if (program.getCondition() != null) {
    builder.setWhere(
        builder.context.toSql(program, program.getCondition()));
  }
  return builder.result();
}
 
Example #5
Source File: RelToSqlConverter.java    From Bats with Apache License 2.0 6 votes vote down vote up
/** @see #dispatch */
public Result visit(Calc e) {
  Result x = visitChild(0, e.getInput());
  parseCorrelTable(e, x);
  final RexProgram program = e.getProgram();
  Builder builder =
      program.getCondition() != null
          ? x.builder(e, Clause.WHERE)
          : x.builder(e);
  if (!isStar(program)) {
    final List<SqlNode> selectList = new ArrayList<>();
    for (RexLocalRef ref : program.getProjectList()) {
      SqlNode sqlExpr = builder.context.toSql(program, ref);
      addSelect(selectList, sqlExpr, e.getRowType());
    }
    builder.setSelect(new SqlNodeList(selectList, POS));
  }

  if (program.getCondition() != null) {
    builder.setWhere(
        builder.context.toSql(program, program.getCondition()));
  }
  return builder.result();
}
 
Example #6
Source File: CalcRelSplitter.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs a CalcRelSplitter.
 *
 * @param calc     Calc to split
 * @param relTypes Array of rel types, e.g. {Java, Fennel}. Must be
 *                 distinct.
 */
CalcRelSplitter(Calc calc, RelBuilder relBuilder, RelType[] relTypes) {
  this.relBuilder = relBuilder;
  for (int i = 0; i < relTypes.length; i++) {
    assert relTypes[i] != null;
    for (int j = 0; j < i; j++) {
      assert relTypes[i] != relTypes[j]
          : "Rel types must be distinct";
    }
  }
  this.program = calc.getProgram();
  this.cluster = calc.getCluster();
  this.traits = calc.getTraitSet();
  this.typeFactory = calc.getCluster().getTypeFactory();
  this.child = calc.getInput();
  this.relTypes = relTypes;
}
 
Example #7
Source File: RelToSqlConverter.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
/**
 * @see #dispatch
 */
public Result visit(Calc e) {
  Result x = visitChild(0, e.getInput());
  parseCorrelTable(e, x);
  final RexProgram program = e.getProgram();
  Builder builder =
    program.getCondition() != null
      ? x.builder(e, Clause.WHERE)
      : x.builder(e);
  if (!isStar(program)) {
    final List<SqlNode> selectList = new ArrayList<>();
    for (RexLocalRef ref : program.getProjectList()) {
      SqlNode sqlExpr = builder.context.toSql(program, ref);
      addSelect(selectList, sqlExpr, e.getRowType());
    }
    builder.setSelect(new SqlNodeList(selectList, POS));
  }

  if (program.getCondition() != null) {
    builder.setWhere(
      builder.context.toSql(program, program.getCondition()));
  }
  return builder.result();
}
 
Example #8
Source File: CalcSplitRule.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public void onMatch(RelOptRuleCall call) {
  final Calc calc = call.rel(0);
  final Pair<ImmutableList<RexNode>, ImmutableList<RexNode>> projectFilter =
      calc.getProgram().split();
  final RelBuilder relBuilder = call.builder();
  relBuilder.push(calc.getInput());
  relBuilder.filter(projectFilter.right);
  relBuilder.project(projectFilter.left, calc.getRowType().getFieldNames());
  call.transformTo(relBuilder.build());
}
 
Example #9
Source File: RelMdMinRowCount.java    From calcite with Apache License 2.0 5 votes vote down vote up
public Double getMinRowCount(Calc rel, RelMetadataQuery mq) {
  if (rel.getProgram().getCondition() != null) {
    // no lower bound
    return 0d;
  } else {
    return mq.getMinRowCount(rel.getInput());
  }
}
 
Example #10
Source File: RelMdColumnUniqueness.java    From calcite with Apache License 2.0 5 votes vote down vote up
public Boolean areColumnsUnique(Calc rel, RelMetadataQuery mq,
    ImmutableBitSet columns, boolean ignoreNulls) {
  columns = decorateWithConstantColumnsFromPredicates(columns, rel, mq);
  RexProgram program = rel.getProgram();

  return areProjectColumnsUnique(rel, mq, columns, ignoreNulls,
      Lists.transform(program.getProjectList(), program::expandLocalRef));
}
 
Example #11
Source File: RelMdSelectivity.java    From calcite with Apache License 2.0 5 votes vote down vote up
public Double getSelectivity(Calc rel, RelMetadataQuery mq, RexNode predicate) {
  final RexProgram rexProgram = rel.getProgram();
  final RexLocalRef programCondition = rexProgram.getCondition();
  if (programCondition == null) {
    return getSelectivity(rel.getInput(), mq, predicate);
  } else {
    return mq.getSelectivity(rel.getInput(),
        RelMdUtil.minusPreds(
            rel.getCluster().getRexBuilder(),
            predicate,
            rexProgram.expandLocalRef(programCondition)));
  }
}
 
Example #12
Source File: RelMdUniqueKeys.java    From calcite with Apache License 2.0 5 votes vote down vote up
public Set<ImmutableBitSet> getUniqueKeys(Calc rel, RelMetadataQuery mq,
    boolean ignoreNulls) {
  RexProgram program = rel.getProgram();
  Permutation permutation = program.getPermutation();
  return getProjectUniqueKeys(rel, mq, ignoreNulls,
      Lists.transform(program.getProjectList(), program::expandLocalRef));
}
 
Example #13
Source File: RelMdSize.java    From calcite with Apache License 2.0 5 votes vote down vote up
public List<Double> averageColumnSizes(Calc rel, RelMetadataQuery mq) {
  final List<Double> inputColumnSizes =
      mq.getAverageColumnSizesNotNull(rel.getInput());
  final ImmutableNullableList.Builder<Double> sizes =
      ImmutableNullableList.builder();
  rel.getProgram().split().left.forEach(
      exp -> sizes.add(averageRexSize(exp, inputColumnSizes)));
  return sizes.build();
}
 
Example #14
Source File: RelToSqlConverter.java    From quark with Apache License 2.0 5 votes vote down vote up
public Result visitChild(int i, RelNode e) {
  if (e instanceof Union) {
    return visitUnion((Union) e);
  } else if (e instanceof Join) {
    return visitJoin((Join) e);
  } else if (e instanceof Filter) {
    return visitFilter((Filter) e);
  } else if (e instanceof Project) {
    return visitProject((Project) e);
  } else if (e instanceof Aggregate) {
    return visitAggregate((Aggregate) e);
  } else if (e instanceof TableScan) {
    return visitTableScan((TableScan) e);
  } else if (e instanceof Intersect) {
    return visitIntersect((Intersect) e);
  } else if (e instanceof Minus) {
    return visitMinus((Minus) e);
  } else if (e instanceof Calc) {
    return visitCalc((Calc) e);
  } else if (e instanceof Sort) {
    return visitSort((Sort) e);
  } else if (e instanceof TableModify) {
    return visitTableModify((TableModify) e);
  } else if (e instanceof Limit) {
    return visitLimit((Limit) e);
  } else {
    throw new AssertionError("Need to Implement for " + e.getClass().getName()); // TODO:
  }
}
 
Example #15
Source File: CalcMergeRule.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a CalcMergeRule.
 *
 * @param relBuilderFactory Builder for relational expressions
 */
public CalcMergeRule(RelBuilderFactory relBuilderFactory) {
  super(
      operand(
          Calc.class,
          operand(Calc.class, any())),
      relBuilderFactory, null);
}
 
Example #16
Source File: PostOrderRelNodeVisitor.java    From streamline with Apache License 2.0 5 votes vote down vote up
public final T traverse(RelNode n) throws Exception {
  List<T> inputStreams = new ArrayList<>();
  for (RelNode input : n.getInputs()) {
    inputStreams.add(traverse(input));
  }

  if (n instanceof Aggregate) {
    return visitAggregate((Aggregate) n, inputStreams);
  } else if (n instanceof Calc) {
    return visitCalc((Calc) n, inputStreams);
  } else if (n instanceof Collect) {
    return visitCollect((Collect) n, inputStreams);
  } else if (n instanceof Correlate) {
    return visitCorrelate((Correlate) n, inputStreams);
  } else if (n instanceof Delta) {
    return visitDelta((Delta) n, inputStreams);
  } else if (n instanceof Exchange) {
    return visitExchange((Exchange) n, inputStreams);
  } else if (n instanceof Project) {
    return visitProject((Project) n, inputStreams);
  } else if (n instanceof Filter) {
    return visitFilter((Filter) n, inputStreams);
  } else if (n instanceof Sample) {
    return visitSample((Sample) n, inputStreams);
  } else if (n instanceof Sort) {
    return visitSort((Sort) n, inputStreams);
  } else if (n instanceof TableModify) {
    return visitTableModify((TableModify) n, inputStreams);
  } else if (n instanceof TableScan) {
    return visitTableScan((TableScan) n, inputStreams);
  } else if (n instanceof Uncollect) {
    return visitUncollect((Uncollect) n, inputStreams);
  } else if (n instanceof Window) {
    return visitWindow((Window) n, inputStreams);
  } else if (n instanceof Join) {
    return visitJoin((Join) n, inputStreams);
  } else {
    return defaultValue(n, inputStreams);
  }
}
 
Example #17
Source File: ProjectToWindowRule.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a CalcToWindowRule.
 *
 * @param relBuilderFactory Builder for relational expressions
 */
public CalcToWindowRule(RelBuilderFactory relBuilderFactory) {
  super(
      operandJ(Calc.class, null,
          calc -> RexOver.containsOver(calc.getProgram()), any()),
      relBuilderFactory, "ProjectToWindowRule");
}
 
Example #18
Source File: ProjectToWindowRule.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a CalcToWindowRule.
 *
 * @param relBuilderFactory Builder for relational expressions
 */
public CalcToWindowRule(RelBuilderFactory relBuilderFactory) {
  super(
      operandJ(Calc.class, null,
          calc -> RexOver.containsOver(calc.getProgram()), any()),
      relBuilderFactory, "ProjectToWindowRule");
}
 
Example #19
Source File: CalcSplitRule.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override public void onMatch(RelOptRuleCall call) {
  final Calc calc = call.rel(0);
  final Pair<ImmutableList<RexNode>, ImmutableList<RexNode>> projectFilter =
      calc.getProgram().split();
  final RelBuilder relBuilder = call.builder();
  relBuilder.push(calc.getInput());
  relBuilder.filter(projectFilter.right);
  relBuilder.project(projectFilter.left, calc.getRowType().getFieldNames());
  call.transformTo(relBuilder.build());
}
 
Example #20
Source File: CalcMergeRule.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a CalcMergeRule.
 *
 * @param relBuilderFactory Builder for relational expressions
 */
public CalcMergeRule(RelBuilderFactory relBuilderFactory) {
  super(
      operand(
          Calc.class,
          operand(Calc.class, any())),
      relBuilderFactory, null);
}
 
Example #21
Source File: JdbcRules.java    From calcite with Apache License 2.0 5 votes vote down vote up
public RelNode convert(RelNode rel) {
  final Calc calc = (Calc) rel;

  // If there's a multiset, let FarragoMultisetSplitter work on it
  // first.
  if (RexMultisetUtil.containsMultiset(calc.getProgram())) {
    return null;
  }

  return new JdbcCalc(rel.getCluster(), rel.getTraitSet().replace(out),
      convert(calc.getInput(), calc.getTraitSet().replace(out)),
      calc.getProgram());
}
 
Example #22
Source File: EnumerableCalcRule.java    From calcite with Apache License 2.0 5 votes vote down vote up
EnumerableCalcRule() {
  // The predicate ensures that if there's a multiset, FarragoMultisetSplitter
  // will work on it first.
  super(LogicalCalc.class,
      (Predicate<Calc>) RelOptUtil::notContainsWindowedAgg,
      Convention.NONE, EnumerableConvention.INSTANCE,
      RelFactories.LOGICAL_BUILDER, "EnumerableCalcRule");
}
 
Example #23
Source File: SqlHintsConverterTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testHintsForCalc() {
  final String sql = "select /*+ resource(mem='1024MB')*/ ename, sal, deptno from emp";
  final RelNode rel = tester.convertSqlToRel(sql).rel;
  final RelHint hint = RelHint.builder("RESOURCE")
      .hintOption("MEM", "1024MB")
      .build();
  // planner rule to convert Project to Calc.
  HepProgram program = new HepProgramBuilder()
      .addRuleInstance(ProjectToCalcRule.INSTANCE)
      .build();
  HepPlanner planner = new HepPlanner(program);
  planner.setRoot(rel);
  RelNode newRel = planner.findBestExp();
  new ValidateHintVisitor(hint, Calc.class).go(newRel);
}
 
Example #24
Source File: RelMdNodeTypes.java    From calcite with Apache License 2.0 4 votes vote down vote up
public Multimap<Class<? extends RelNode>, RelNode> getNodeTypes(Calc rel,
    RelMetadataQuery mq) {
  return getNodeTypes(rel, Calc.class, mq);
}
 
Example #25
Source File: ProjectToWindowRule.java    From calcite with Apache License 2.0 4 votes vote down vote up
WindowedAggRelSplitter(Calc calc, RelBuilder relBuilder) {
  super(calc, relBuilder, REL_TYPES);
}
 
Example #26
Source File: JdbcRules.java    From calcite with Apache License 2.0 4 votes vote down vote up
/** Creates a JdbcCalcRule. */
private JdbcCalcRule(JdbcConvention out,
    RelBuilderFactory relBuilderFactory) {
  super(Calc.class, (Predicate<RelNode>) r -> true, Convention.NONE,
      out, relBuilderFactory, "JdbcCalcRule");
}
 
Example #27
Source File: ReduceExpressionsRule.java    From calcite with Apache License 2.0 4 votes vote down vote up
public CalcReduceExpressionsRule(Class<? extends Calc> calcClass,
    boolean matchNullability, RelBuilderFactory relBuilderFactory) {
  super(calcClass, matchNullability, relBuilderFactory,
      "ReduceExpressionsRule(Calc)");
}
 
Example #28
Source File: ReduceExpressionsRule.java    From calcite with Apache License 2.0 4 votes vote down vote up
@Deprecated // to be removed before 2.0
public CalcReduceExpressionsRule(Class<? extends Calc> calcClass,
    RelBuilderFactory relBuilderFactory) {
  this(calcClass, true, relBuilderFactory);
}
 
Example #29
Source File: RelMdRowCount.java    From calcite with Apache License 2.0 4 votes vote down vote up
public Double getRowCount(Calc rel, RelMetadataQuery mq) {
  return RelMdUtil.estimateFilteredRows(rel.getInput(), rel.getProgram(), mq);
}
 
Example #30
Source File: RelFieldTrimmer.java    From calcite with Apache License 2.0 4 votes vote down vote up
/**
 * Variant of {@link #trimFields(RelNode, ImmutableBitSet, Set)} for
 * {@link org.apache.calcite.rel.logical.LogicalCalc}.
 */
public TrimResult trimFields(
    Calc calc,
    ImmutableBitSet fieldsUsed,
    Set<RelDataTypeField> extraFields) {
  final RexProgram rexProgram = calc.getProgram();
  final List<RexNode> projs = Lists.transform(rexProgram.getProjectList(),
      rexProgram::expandLocalRef);

  final RelDataType rowType = calc.getRowType();
  final int fieldCount = rowType.getFieldCount();
  final RelNode input = calc.getInput();

  final Set<RelDataTypeField> inputExtraFields =
      new HashSet<>(extraFields);
  RelOptUtil.InputFinder inputFinder =
      new RelOptUtil.InputFinder(inputExtraFields);
  for (Ord<RexNode> ord : Ord.zip(projs)) {
    if (fieldsUsed.get(ord.i)) {
      ord.e.accept(inputFinder);
    }
  }
  ImmutableBitSet inputFieldsUsed = inputFinder.build();

  // Create input with trimmed columns.
  TrimResult trimResult =
      trimChild(calc, input, inputFieldsUsed, inputExtraFields);
  RelNode newInput = trimResult.left;
  final Mapping inputMapping = trimResult.right;

  // If the input is unchanged, and we need to project all columns,
  // there's nothing we can do.
  if (newInput == input
      && fieldsUsed.cardinality() == fieldCount) {
    return result(calc, Mappings.createIdentity(fieldCount));
  }

  // Some parts of the system can't handle rows with zero fields, so
  // pretend that one field is used.
  if (fieldsUsed.cardinality() == 0) {
    return dummyProject(fieldCount, newInput);
  }

  // Build new project expressions, and populate the mapping.
  final List<RexNode> newProjects = new ArrayList<>();
  final RexVisitor<RexNode> shuttle =
      new RexPermuteInputsShuttle(
          inputMapping, newInput);
  final Mapping mapping =
      Mappings.create(
          MappingType.INVERSE_SURJECTION,
          fieldCount,
          fieldsUsed.cardinality());
  for (Ord<RexNode> ord : Ord.zip(projs)) {
    if (fieldsUsed.get(ord.i)) {
      mapping.set(ord.i, newProjects.size());
      RexNode newProjectExpr = ord.e.accept(shuttle);
      newProjects.add(newProjectExpr);
    }
  }

  final RelDataType newRowType =
      RelOptUtil.permute(calc.getCluster().getTypeFactory(), rowType,
          mapping);

  final RelNode newInputRelNode = relBuilder.push(newInput).build();
  RexNode newConditionExpr = null;
  if (rexProgram.getCondition() != null) {
    final List<RexNode> filter = Lists.transform(
        ImmutableList.of(
            rexProgram.getCondition()), rexProgram::expandLocalRef);
    assert filter.size() == 1;
    final RexNode conditionExpr = filter.get(0);
    newConditionExpr = conditionExpr.accept(shuttle);
  }
  final RexProgram newRexProgram = RexProgram.create(newInputRelNode.getRowType(),
      newProjects, newConditionExpr, newRowType.getFieldNames(),
      newInputRelNode.getCluster().getRexBuilder());
  final Calc newCalc = calc.copy(calc.getTraitSet(), newInputRelNode, newRexProgram);
  return result(newCalc, mapping);
}