Java Code Examples for org.apache.calcite.util.Pair#of()

The following examples show how to use org.apache.calcite.util.Pair#of() . 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: IdentifierNamespace.java    From calcite with Apache License 2.0 6 votes vote down vote up
protected static Pair<SqlIdentifier, SqlNodeList> split(SqlNode node) {
  switch (node.getKind()) {
  case EXTEND:
    final SqlCall call = (SqlCall) node;
    final SqlNode operand0 = call.operand(0);
    final SqlIdentifier identifier = operand0.getKind() == SqlKind.TABLE_REF
        ? ((SqlCall) operand0).operand(0)
        : (SqlIdentifier) operand0;
    return Pair.of(identifier, call.operand(1));
  case TABLE_REF:
    final SqlCall tableRef = (SqlCall) node;
    return Pair.of(tableRef.operand(0), null);
  default:
    return Pair.of((SqlIdentifier) node, null);
  }
}
 
Example 2
Source File: MaterializedViewRule.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Classifies each of the predicates in the list into one of these two
 * categories:
 *
 * <ul>
 * <li> 1-l) column equality predicates, or
 * <li> 2-r) residual predicates, all the rest
 * </ul>
 *
 * <p>For each category, it creates the conjunction of the predicates. The
 * result is an pair of RexNode objects corresponding to each category.
 */
protected Pair<RexNode, RexNode> splitPredicates(
    RexBuilder rexBuilder, RexNode pred) {
  List<RexNode> equiColumnsPreds = new ArrayList<>();
  List<RexNode> residualPreds = new ArrayList<>();
  for (RexNode e : RelOptUtil.conjunctions(pred)) {
    switch (e.getKind()) {
    case EQUALS:
      RexCall eqCall = (RexCall) e;
      if (RexUtil.isReferenceOrAccess(eqCall.getOperands().get(0), false)
              && RexUtil.isReferenceOrAccess(eqCall.getOperands().get(1), false)) {
        equiColumnsPreds.add(e);
      } else {
        residualPreds.add(e);
      }
      break;
    default:
      residualPreds.add(e);
    }
  }
  return Pair.of(
      RexUtil.composeConjunction(rexBuilder, equiColumnsPreds),
      RexUtil.composeConjunction(rexBuilder, residualPreds));
}
 
Example 3
Source File: EnumerableTraitsUtils.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * This function can be reused when a Join's traits pass-down shall only
 * pass through collation to left input.
 *
 * @param required required trait set for the join
 * @param joinType the join type
 * @param leftInputFieldCount number of field count of left join input
 * @param joinTraitSet trait set of the join
 */
static Pair<RelTraitSet, List<RelTraitSet>> passThroughTraitsForJoin(
    RelTraitSet required, JoinRelType joinType,
    int leftInputFieldCount, RelTraitSet joinTraitSet) {
  RelCollation collation = required.getCollation();
  if (collation == null
      || collation == RelCollations.EMPTY
      || joinType == JoinRelType.FULL
      || joinType == JoinRelType.RIGHT) {
    return null;
  }

  for (RelFieldCollation fc : collation.getFieldCollations()) {
    // If field collation belongs to right input: cannot push down collation.
    if (fc.getFieldIndex() >= leftInputFieldCount) {
      return null;
    }
  }

  RelTraitSet passthroughTraitSet = joinTraitSet.replace(collation);
  return Pair.of(passthroughTraitSet,
      ImmutableList.of(
          passthroughTraitSet,
          passthroughTraitSet.replace(RelCollations.EMPTY)));
}
 
Example 4
Source File: MongoProject.java    From calcite with Apache License 2.0 6 votes vote down vote up
public void implement(Implementor implementor) {
  implementor.visitChild(0, getInput());

  final MongoRules.RexToMongoTranslator translator =
      new MongoRules.RexToMongoTranslator(
          (JavaTypeFactory) getCluster().getTypeFactory(),
          MongoRules.mongoFieldNames(getInput().getRowType()));
  final List<String> items = new ArrayList<>();
  for (Pair<RexNode, String> pair : getNamedProjects()) {
    final String name = pair.right;
    final String expr = pair.left.accept(translator);
    items.add(expr.equals("'$" + name + "'")
        ? MongoRules.maybeQuote(name) + ": 1"
        : MongoRules.maybeQuote(name) + ": " + expr);
  }
  final String findString = Util.toString(items, "{", ", ", "}");
  final String aggregateString = "{$project: " + findString + "}";
  final Pair<String, String> op = Pair.of(findString, aggregateString);
  implementor.add(op.left, op.right);
}
 
Example 5
Source File: StandardConvertletTable.java    From calcite with Apache License 2.0 6 votes vote down vote up
private Pair<RexNode, RexNode> convertOverlapsOperand(SqlRexContext cx,
    SqlParserPos pos, SqlNode operand) {
  final SqlNode a0;
  final SqlNode a1;
  switch (operand.getKind()) {
  case ROW:
    a0 = ((SqlCall) operand).operand(0);
    final SqlNode a10 = ((SqlCall) operand).operand(1);
    final RelDataType t1 = cx.getValidator().getValidatedNodeType(a10);
    if (SqlTypeUtil.isInterval(t1)) {
      // make t1 = t0 + t1 when t1 is an interval.
      a1 = plus(pos, a0, a10);
    } else {
      a1 = a10;
    }
    break;
  default:
    a0 = operand;
    a1 = operand;
  }

  final RexNode r0 = cx.convertExpression(a0);
  final RexNode r1 = cx.convertExpression(a1);
  return Pair.of(r0, r1);
}
 
Example 6
Source File: ListScope.java    From Bats with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Override public Pair<String, SqlValidatorNamespace>
findQualifyingTableName(final String columnName, SqlNode ctx) {
  final SqlNameMatcher nameMatcher = validator.catalogReader.nameMatcher();
  final Map<String, ScopeChild> map =
      findQualifyingTableNames(columnName, ctx, nameMatcher);
  switch (map.size()) {
  case 0:
    throw validator.newValidationError(ctx,
        RESOURCE.columnNotFound(columnName));
  case 1:
    final Map.Entry<String, ScopeChild> entry =
        map.entrySet().iterator().next();
    return Pair.of(entry.getKey(), entry.getValue().namespace);
  default:
    throw validator.newValidationError(ctx,
        RESOURCE.columnAmbiguous(columnName));
  }
}
 
Example 7
Source File: AvroSchema.java    From kareldb with Apache License 2.0 5 votes vote down vote up
public static Pair<LinkedHashMap<String, ColumnDef>, List<String>> toColumnDefs(org.apache.avro.Schema schema) {
    int size = schema.getFields().size();
    final LinkedHashMap<String, ColumnDef> columnDefs = new LinkedHashMap<>();
    String[] keyNames = new String[size];
    for (org.apache.avro.Schema.Field field : schema.getFields()) {
        org.apache.avro.Schema fieldSchema = field.schema();
        Integer keyIndex = (Integer) field.getObjectProp(SQL_KEY_INDEX_PROP);
        if (keyIndex != null) {
            keyNames[keyIndex] = field.name();
        }
        ColumnDef columnDef = toColumnDef(fieldSchema);
        if (columnDef == null) {
            throw new IllegalArgumentException("Unsupported type " + fieldSchema.getType());
        }
        if (field.hasDefaultValue()) {
            Object defaultVal = field.defaultVal();
            // Already handled null strategy
            if (defaultVal != JsonProperties.NULL_VALUE) {
                columnDef = new ColumnDef(columnDef.getColumnType(),
                    new ColumnStrategy.DefaultStrategy(defaultVal),
                    columnDef.getPrecision(), columnDef.getScale());
            }
        }
        columnDefs.put(field.name(), columnDef);
    }
    List<String> keyFields = new ArrayList<>(size);
    for (String keyName : keyNames) {
        if (keyName == null) {
            break;
        }
        keyFields.add(keyName);
    }
    return Pair.of(columnDefs, keyFields);
}
 
Example 8
Source File: SubstitutionVisitor.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Explain filtering condition and projections from MutableCalc. */
private static Pair<RexNode, List<RexNode>> explainCalc(MutableCalc calc) {
  final RexShuttle shuttle = getExpandShuttle(calc.program);
  final RexNode condition = shuttle.apply(calc.program.getCondition());
  final List<RexNode> projects = new ArrayList<>();
  for (RexNode rex: shuttle.apply(calc.program.getProjectList())) {
    projects.add(rex);
  }
  if (condition == null) {
    return Pair.of(calc.cluster.getRexBuilder().makeLiteral(true), projects);
  } else {
    return Pair.of(condition, projects);
  }
}
 
Example 9
Source File: RexProgram.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a list of project expressions and their field names.
 */
public List<Pair<RexLocalRef, String>> getNamedProjects() {
    return new AbstractList<Pair<RexLocalRef, String>>() {
        @Override
        public int size() {
            return projects.size();
        }

        @Override
        public Pair<RexLocalRef, String> get(int index) {
            return Pair.of(projects.get(index), outputRowType.getFieldList().get(index).getName());
        }
    };
}
 
Example 10
Source File: MaterializedViewAggregateRule.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public Pair<RelNode, RelNode> pushFilterToOriginalViewPlan(RelBuilder builder,
    RelNode topViewProject, RelNode viewNode, RexNode cond) {
  // We add (and push) the filter to the view plan before triggering the rewriting.
  // This is useful in case some of the columns can be folded to same value after
  // filter is added.
  HepProgramBuilder pushFiltersProgram = new HepProgramBuilder();
  if (topViewProject != null) {
    pushFiltersProgram.addRuleInstance(filterProjectTransposeRule);
  }
  pushFiltersProgram
      .addRuleInstance(this.filterAggregateTransposeRule)
      .addRuleInstance(this.aggregateProjectPullUpConstantsRule)
      .addRuleInstance(this.projectMergeRule);
  final HepPlanner tmpPlanner = new HepPlanner(pushFiltersProgram.build());
  // Now that the planner is created, push the node
  RelNode topNode = builder
      .push(topViewProject != null ? topViewProject : viewNode)
      .filter(cond).build();
  tmpPlanner.setRoot(topNode);
  topNode = tmpPlanner.findBestExp();
  RelNode resultTopViewProject = null;
  RelNode resultViewNode = null;
  while (topNode != null) {
    if (topNode instanceof Project) {
      if (resultTopViewProject != null) {
        // Both projects could not be merged, we will bail out
        return Pair.of(topViewProject, viewNode);
      }
      resultTopViewProject = topNode;
      topNode = topNode.getInput(0);
    } else if (topNode instanceof Aggregate) {
      resultViewNode = topNode;
      topNode = null;
    } else {
      // We move to the child
      topNode = topNode.getInput(0);
    }
  }
  return Pair.of(resultTopViewProject, resultViewNode);
}
 
Example 11
Source File: RelOptUtil.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
public Pair<RexNode, String> get(int index) {
    if (index < rightCount) {
        RelDataTypeField field = fields.get(index);
        return Pair.of(RexBuilder.getRexFactory().makeInputRef(index, field.getType()),
                field.getName());
    } else {
        return Pair.of(RexUtil.shift(extraRightExprs.get(index - rightCount), -newLeftCount), null);
    }
}
 
Example 12
Source File: PlannerImpl.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
public Pair<SqlNode, RelDataType> validateAndGetType(SqlNode sqlNode)
        throws ValidationException {
    final SqlNode validatedNode = this.validate(sqlNode);
    final RelDataType type =
            this.validator.getValidatedNodeType(validatedNode);
    return Pair.of(validatedNode, type);
}
 
Example 13
Source File: RexImplicationChecker.java    From calcite with Apache License 2.0 5 votes vote down vote up
private void updateUsage(SqlOperator op, RexInputRef inputRef,
    RexNode literal) {
  final InputRefUsage<SqlOperator, RexNode> inputRefUse =
      getUsageMap(inputRef);
  Pair<SqlOperator, RexNode> use = Pair.of(op, literal);
  inputRefUse.usageList.add(use);
}
 
Example 14
Source File: SqlMapValueConstructor.java    From calcite with Apache License 2.0 5 votes vote down vote up
private Pair<RelDataType, RelDataType> getComponentTypes(
    RelDataTypeFactory typeFactory,
    List<RelDataType> argTypes) {
  return Pair.of(
      typeFactory.leastRestrictive(Util.quotientList(argTypes, 2, 0)),
      typeFactory.leastRestrictive(Util.quotientList(argTypes, 2, 1)));
}
 
Example 15
Source File: AbstractMaterializedViewRule.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
public Pair<RelNode, RelNode> pushFilterToOriginalViewPlan(RelBuilder builder, RelNode topViewProject,
        RelNode viewNode, RexNode cond) {
    // We add (and push) the filter to the view plan before triggering the rewriting.
    // This is useful in case some of the columns can be folded to same value after
    // filter is added.
    HepProgramBuilder pushFiltersProgram = new HepProgramBuilder();
    if (topViewProject != null) {
        pushFiltersProgram.addRuleInstance(filterProjectTransposeRule);
    }
    pushFiltersProgram.addRuleInstance(this.filterAggregateTransposeRule)
            .addRuleInstance(this.aggregateProjectPullUpConstantsRule).addRuleInstance(this.projectMergeRule);
    final HepPlanner tmpPlanner = new HepPlanner(pushFiltersProgram.build());
    // Now that the planner is created, push the node
    RelNode topNode = builder.push(topViewProject != null ? topViewProject : viewNode).filter(cond).build();
    tmpPlanner.setRoot(topNode);
    topNode = tmpPlanner.findBestExp();
    RelNode resultTopViewProject = null;
    RelNode resultViewNode = null;
    while (topNode != null) {
        if (topNode instanceof Project) {
            if (resultTopViewProject != null) {
                // Both projects could not be merged, we will bail out
                return Pair.of(topViewProject, viewNode);
            }
            resultTopViewProject = topNode;
            topNode = topNode.getInput(0);
        } else if (topNode instanceof Aggregate) {
            resultViewNode = topNode;
            topNode = null;
        } else {
            // We move to the child
            topNode = topNode.getInput(0);
        }
    }
    return Pair.of(resultTopViewProject, resultViewNode);
}
 
Example 16
Source File: PlannerImpl.java    From calcite with Apache License 2.0 5 votes vote down vote up
public Pair<SqlNode, RelDataType> validateAndGetType(SqlNode sqlNode)
    throws ValidationException {
  final SqlNode validatedNode = this.validate(sqlNode);
  final RelDataType type =
      this.validator.getValidatedNodeType(validatedNode);
  return Pair.of(validatedNode, type);
}
 
Example 17
Source File: MetadataFactoryImpl.java    From Bats with Apache License 2.0 5 votes vote down vote up
public <M extends Metadata> M query(RelNode rel, RelMetadataQuery mq,
    Class<M> metadataClazz) {
  try {
    //noinspection unchecked
    final Pair<Class<RelNode>, Class<Metadata>> key =
        (Pair) Pair.of(rel.getClass(), metadataClazz);
    final Metadata apply = cache.get(key).bind(rel, mq);
    return metadataClazz.cast(apply);
  } catch (UncheckedExecutionException | ExecutionException e) {
    Util.throwIfUnchecked(e.getCause());
    throw new RuntimeException(e.getCause());
  }
}
 
Example 18
Source File: DrillJoinRel.java    From Bats with Apache License 2.0 4 votes vote down vote up
protected static Pair<RelNode, RelNode> getJoinInputs(Join join, ConversionContext context) throws InvalidRelException {
  RelNode left = context.toRel(join.getLeft());
  RelNode right = context.toRel(join.getRight());
  return Pair.of(left, right);
}
 
Example 19
Source File: RexUtil.java    From calcite with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a key for {@link RexNode} which is the same as another key of
 * another RexNode only if the two have both the same type and textual
 * representation. For example, "10" integer and "10" bigint result in
 * different keys.
 */
public static Pair<RexNode, String> makeKey(RexNode expr) {
  return Pair.of(expr, expr.getType().getFullTypeString());
}
 
Example 20
Source File: RexUtil.java    From Bats with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a key for {@link RexNode} which is the same as another key of
 * another RexNode only if the two have both the same type and textual
 * representation. For example, "10" integer and "10" bigint result in
 * different keys.
 */
public static Pair<RexNode, String> makeKey(RexNode expr) {
    return Pair.of(expr, expr.getType().getFullTypeString());
}