Java Code Examples for org.apache.calcite.util.Util#first()

The following examples show how to use org.apache.calcite.util.Util#first() . 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: RelMdPredicates.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** @see RelMetadataQuery#getPulledUpPredicates(RelNode) */
public RelOptPredicateList getPredicates(RelSubset r,
    RelMetadataQuery mq) {
  if (!Bug.CALCITE_1048_FIXED) {
    return RelOptPredicateList.EMPTY;
  }
  final RexBuilder rexBuilder = r.getCluster().getRexBuilder();
  RelOptPredicateList list = null;
  for (RelNode r2 : r.getRels()) {
    RelOptPredicateList list2 = mq.getPulledUpPredicates(r2);
    if (list2 != null) {
      list = list == null ? list2 : list.union(rexBuilder, list2);
    }
  }
  return Util.first(list, RelOptPredicateList.EMPTY);
}
 
Example 2
Source File: RelMdPredicates.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * Infers predicates for a {@link org.apache.calcite.rel.core.Join} (including
 * {@link org.apache.calcite.rel.core.SemiJoin}).
 */
public RelOptPredicateList getPredicates(Join join, RelMetadataQuery mq) {
  RelOptCluster cluster = join.getCluster();
  RexBuilder rexBuilder = cluster.getRexBuilder();
  final RexExecutor executor =
      Util.first(cluster.getPlanner().getExecutor(), RexUtil.EXECUTOR);
  final RelNode left = join.getInput(0);
  final RelNode right = join.getInput(1);

  final RelOptPredicateList leftInfo = mq.getPulledUpPredicates(left);
  final RelOptPredicateList rightInfo = mq.getPulledUpPredicates(right);

  JoinConditionBasedPredicateInference joinInference =
      new JoinConditionBasedPredicateInference(join,
          RexUtil.composeConjunction(rexBuilder, leftInfo.pulledUpPredicates),
          RexUtil.composeConjunction(rexBuilder, rightInfo.pulledUpPredicates),
          new RexSimplify(rexBuilder, RelOptPredicateList.EMPTY, executor));

  return joinInference.inferPredicates(false);
}
 
Example 3
Source File: RelBuilder.java    From calcite with Apache License 2.0 6 votes vote down vote up
private static RelFieldCollation collation(RexNode node,
    RelFieldCollation.Direction direction,
    RelFieldCollation.NullDirection nullDirection, List<RexNode> extraNodes) {
  switch (node.getKind()) {
  case INPUT_REF:
    return new RelFieldCollation(((RexInputRef) node).getIndex(), direction,
        Util.first(nullDirection, direction.defaultNullDirection()));
  case DESCENDING:
    return collation(((RexCall) node).getOperands().get(0),
        RelFieldCollation.Direction.DESCENDING,
        nullDirection, extraNodes);
  case NULLS_FIRST:
    return collation(((RexCall) node).getOperands().get(0), direction,
        RelFieldCollation.NullDirection.FIRST, extraNodes);
  case NULLS_LAST:
    return collation(((RexCall) node).getOperands().get(0), direction,
        RelFieldCollation.NullDirection.LAST, extraNodes);
  default:
    final int fieldIndex = extraNodes.size();
    extraNodes.add(node);
    return new RelFieldCollation(fieldIndex, direction,
        Util.first(nullDirection, direction.defaultNullDirection()));
  }
}
 
Example 4
Source File: TpchSchemaFactory.java    From calcite with Apache License 2.0 5 votes vote down vote up
public Schema create(SchemaPlus parentSchema, String name,
    Map<String, Object> operand) {
  Map map = (Map) operand;
  double scale = Util.first((Double) map.get("scale"), 1D);
  int part = Util.first((Integer) map.get("part"), 1);
  int partCount = Util.first((Integer) map.get("partCount"), 1);
  boolean columnPrefix = Util.first((Boolean) map.get("columnPrefix"), true);
  return new TpchSchema(scale, part, partCount, columnPrefix);
}
 
Example 5
Source File: RelBuilder.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Derives the Config to be used for this RelBuilder.
 *
 * <p>Overrides {@link RelBuilder.Config#simplify} if
 * {@link Hook#REL_BUILDER_SIMPLIFY} is set.
 */
private Config getConfig(Context context) {
  final Config config =
      Util.first(context.unwrap(Config.class), Config.DEFAULT);
  boolean simplify = Hook.REL_BUILDER_SIMPLIFY.get(config.simplify());
  return config.withSimplify(simplify);
}
 
Example 6
Source File: ModelHandler.java    From calcite with Apache License 2.0 5 votes vote down vote up
public void visit(JsonFunction jsonFunction) {
  // "name" is not required - a class can have several functions
  checkRequiredAttributes(jsonFunction, "className");
  try {
    final SchemaPlus schema = currentMutableSchema("function");
    final List<String> path =
        Util.first(jsonFunction.path, currentSchemaPath());
    addFunctions(schema, jsonFunction.name, path, jsonFunction.className,
        jsonFunction.methodName, false);
  } catch (Exception e) {
    throw new RuntimeException("Error instantiating " + jsonFunction, e);
  }
}
 
Example 7
Source File: QuidemTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
protected static Collection<Object[]> data(String first) {
  // inUrl = "file:/home/fred/calcite/core/target/test-classes/sql/agg.iq"
  final URL inUrl = JdbcTest.class.getResource("/" + n2u(first));
  final File firstFile = Sources.of(inUrl).file();
  final int commonPrefixLength = firstFile.getAbsolutePath().length() - first.length();
  final File dir = firstFile.getParentFile();
  final List<String> paths = new ArrayList<>();
  final FilenameFilter filter = new PatternFilenameFilter(".*\\.iq$");
  for (File f : Util.first(dir.listFiles(filter), new File[0])) {
    paths.add(f.getAbsolutePath().substring(commonPrefixLength));
  }
  return Lists.transform(paths, path -> new Object[] {path});
}
 
Example 8
Source File: Join.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** @deprecated Use {@link RelMdUtil#getJoinRowCount(RelMetadataQuery, Join, RexNode)}. */
@Deprecated // to be removed before 2.0
public static double estimateJoinedRows(
    Join joinRel,
    RexNode condition) {
  final RelMetadataQuery mq = joinRel.getCluster().getMetadataQuery();
  return Util.first(RelMdUtil.getJoinRowCount(mq, joinRel, condition), 1D);
}
 
Example 9
Source File: RelBuilder.java    From Bats with Apache License 2.0 5 votes vote down vote up
protected RelBuilder(Context context, RelOptCluster cluster, RelOptSchema relOptSchema) {
    this.cluster = cluster;
    this.relOptSchema = relOptSchema;
    if (context == null) {
        context = Contexts.EMPTY_CONTEXT;
    }
    this.simplify = Hook.REL_BUILDER_SIMPLIFY.get(true);
    this.aggregateFactory = Util.first(context.unwrap(RelFactories.AggregateFactory.class),
            RelFactories.DEFAULT_AGGREGATE_FACTORY);
    this.filterFactory = Util.first(context.unwrap(RelFactories.FilterFactory.class),
            RelFactories.DEFAULT_FILTER_FACTORY);
    this.projectFactory = Util.first(context.unwrap(RelFactories.ProjectFactory.class),
            RelFactories.DEFAULT_PROJECT_FACTORY);
    this.sortFactory = Util.first(context.unwrap(RelFactories.SortFactory.class),
            RelFactories.DEFAULT_SORT_FACTORY);
    this.exchangeFactory = Util.first(context.unwrap(RelFactories.ExchangeFactory.class),
            RelFactories.DEFAULT_EXCHANGE_FACTORY);
    this.sortExchangeFactory = Util.first(context.unwrap(RelFactories.SortExchangeFactory.class),
            RelFactories.DEFAULT_SORT_EXCHANGE_FACTORY);
    this.setOpFactory = Util.first(context.unwrap(RelFactories.SetOpFactory.class),
            RelFactories.DEFAULT_SET_OP_FACTORY);
    this.joinFactory = Util.first(context.unwrap(RelFactories.JoinFactory.class),
            RelFactories.DEFAULT_JOIN_FACTORY);
    this.semiJoinFactory = Util.first(context.unwrap(RelFactories.SemiJoinFactory.class),
            RelFactories.DEFAULT_SEMI_JOIN_FACTORY);
    this.correlateFactory = Util.first(context.unwrap(RelFactories.CorrelateFactory.class),
            RelFactories.DEFAULT_CORRELATE_FACTORY);
    this.valuesFactory = Util.first(context.unwrap(RelFactories.ValuesFactory.class),
            RelFactories.DEFAULT_VALUES_FACTORY);
    this.scanFactory = Util.first(context.unwrap(RelFactories.TableScanFactory.class),
            RelFactories.DEFAULT_TABLE_SCAN_FACTORY);
    this.snapshotFactory = Util.first(context.unwrap(RelFactories.SnapshotFactory.class),
            RelFactories.DEFAULT_SNAPSHOT_FACTORY);
    this.matchFactory = Util.first(context.unwrap(RelFactories.MatchFactory.class),
            RelFactories.DEFAULT_MATCH_FACTORY);
    final RexExecutor executor = Util.first(context.unwrap(RexExecutor.class),
            Util.first(cluster.getPlanner().getExecutor(), RexUtil.EXECUTOR));
    final RelOptPredicateList predicates = RelOptPredicateList.EMPTY;
    this.simplifier = new RexSimplify(cluster.getRexBuilder(), predicates, executor);
}
 
Example 10
Source File: HepPlanner.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new HepPlanner with the option to keep the graph a
 * tree (noDag = true) or allow DAG (noDag = false).
 *
 * @param noDag      If false, create shared nodes if expressions are
 *                   identical
 * @param program    Program controlling rule application
 * @param onCopyHook Function to call when a node is copied
 */
public HepPlanner(
    HepProgram program,
    Context context,
    boolean noDag,
    Function2<RelNode, RelNode, Void> onCopyHook,
    RelOptCostFactory costFactory) {
  super(costFactory, context);
  this.mainProgram = program;
  this.onCopyHook = Util.first(onCopyHook, Functions.ignore2());
  this.noDag = noDag;
}
 
Example 11
Source File: RelMdPredicates.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Infers predicates for a Intersect.
 */
public RelOptPredicateList getPredicates(Intersect intersect, RelMetadataQuery mq) {
  final RexBuilder rexBuilder = intersect.getCluster().getRexBuilder();

  final RexExecutor executor =
      Util.first(intersect.getCluster().getPlanner().getExecutor(), RexUtil.EXECUTOR);

  final RexImplicationChecker rexImplicationChecker =
      new RexImplicationChecker(rexBuilder, executor, intersect.getRowType());

  Set<RexNode> finalPredicates = new HashSet<>();

  for (Ord<RelNode> input : Ord.zip(intersect.getInputs())) {
    RelOptPredicateList info = mq.getPulledUpPredicates(input.e);
    if (info == null || info.pulledUpPredicates.isEmpty()) {
      continue;
    }

    for (RexNode pred: info.pulledUpPredicates) {
      if (finalPredicates.stream().anyMatch(
          finalPred -> rexImplicationChecker.implies(finalPred, pred))) {
        // There's already a stricter predicate in finalPredicates,
        // thus no need to count this one.
        continue;
      }
      // Remove looser predicate and add this one into finalPredicates
      finalPredicates = finalPredicates.stream()
          .filter(finalPred -> !rexImplicationChecker.implies(pred, finalPred))
          .collect(Collectors.toSet());
      finalPredicates.add(pred);
    }
  }

  return RelOptPredicateList.of(rexBuilder, finalPredicates);
}
 
Example 12
Source File: ModelHandler.java    From calcite with Apache License 2.0 5 votes vote down vote up
public void visit(JsonView jsonView) {
  try {
    checkRequiredAttributes(jsonView, "name");
    final SchemaPlus schema = currentMutableSchema("view");
    final List<String> path = Util.first(jsonView.path, currentSchemaPath());
    final List<String> viewPath = ImmutableList.<String>builder().addAll(path)
        .add(jsonView.name).build();
    schema.add(jsonView.name,
        ViewTable.viewMacro(schema, jsonView.getSql(), path, viewPath,
            jsonView.modifiable));
  } catch (Exception e) {
    throw new RuntimeException("Error instantiating " + jsonView, e);
  }
}
 
Example 13
Source File: FilterProjectTransposeRule.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Simplifies the filter condition using a simplifier created by the
 * information in the current call.
 *
 * <p>This method is an attempt to replicate the simplification behavior of
 * {@link RelBuilder#filter(RexNode...)} which cannot be used in the case of
 * copying nodes. The main difference with the behavior of that method is that
 * it does not drop entirely the filter if the condition is always false.
 */
private RexNode simplifyFilterCondition(RexNode condition, RelOptRuleCall call) {
  final RexBuilder xBuilder = call.builder().getRexBuilder();
  final RexExecutor executor =
      Util.first(call.getPlanner().getContext().unwrap(RexExecutor.class),
          Util.first(call.getPlanner().getExecutor(), RexUtil.EXECUTOR));
  // unknownAsFalse => true since in the WHERE clause:
  // 1>null evaluates to unknown and WHERE unknown behaves exactly like WHERE false
  RexSimplify simplifier =
      new RexSimplify(xBuilder, RelOptPredicateList.EMPTY, executor);
  return RexUtil.removeNullabilityCast(
      xBuilder.getTypeFactory(), simplifier.simplifyUnknownAsFalse(condition));
}
 
Example 14
Source File: SemiJoin.java    From Bats with Apache License 2.0 4 votes vote down vote up
@Override public double estimateRowCount(RelMetadataQuery mq) {
  return Util.first(
      RelMdUtil.getSemiJoinRowCount(mq, left, right, joinType, condition),
      1D);
}
 
Example 15
Source File: Join.java    From calcite with Apache License 2.0 4 votes vote down vote up
@Override public double estimateRowCount(RelMetadataQuery mq) {
  return Util.first(RelMdUtil.getJoinRowCount(mq, this, condition), 1D);
}
 
Example 16
Source File: RexInterpreter.java    From calcite with Apache License 2.0 4 votes vote down vote up
public Comparable visitLiteral(RexLiteral literal) {
  return Util.first(literal.getValue4(), N);
}
 
Example 17
Source File: SqlIntervalQualifier.java    From calcite with Apache License 2.0 4 votes vote down vote up
/** Returns {@code SECOND} for both {@code HOUR TO SECOND} and
 * {@code SECOND}. */
public TimeUnit getUnit() {
  return Util.first(timeUnitRange.endUnit, timeUnitRange.startUnit);
}
 
Example 18
Source File: RexInterpreter.java    From Bats with Apache License 2.0 4 votes vote down vote up
@Override
public Comparable visitLiteral(RexLiteral literal) {
    return Util.first(literal.getValue4(), N);
}
 
Example 19
Source File: TpcdsSchemaFactory.java    From calcite with Apache License 2.0 4 votes vote down vote up
public Schema create(SchemaPlus parentSchema, String name,
    Map<String, Object> operand) {
  @SuppressWarnings("RawTypeCanBeGeneric") final Map map = operand;
  double scale = Util.first((Double) map.get("scale"), 1D);
  return new TpcdsSchema(scale);
}
 
Example 20
Source File: ReduceExpressionsRule.java    From Bats with Apache License 2.0 3 votes vote down vote up
/**
 * Reduces a list of expressions.
 *
 * <p>The {@code matchNullability} flag comes into play when reducing a
 * expression whose type is nullable. Suppose we are reducing an expression
 * {@code CASE WHEN 'a' = 'a' THEN 1 ELSE NULL END}. Before reduction the
 * type is {@code INTEGER} (nullable), but after reduction the literal 1 has
 * type {@code INTEGER NOT NULL}.
 *
 * <p>In some situations it is more important to preserve types; in this
 * case you should use {@code matchNullability = true} (which used to be
 * the default behavior of this method), and it will cast the literal to
 * {@code INTEGER} (nullable).
 *
 * <p>In other situations, you would rather propagate the new stronger type,
 * because it may allow further optimizations later; pass
 * {@code matchNullability = false} and no cast will be added, but you may
 * need to adjust types elsewhere in the expression tree.
 *
 * @param rel     Relational expression
 * @param expList List of expressions, modified in place
 * @param predicates Constraints known to hold on input expressions
 * @param unknownAsFalse Whether UNKNOWN will be treated as FALSE
 * @param matchNullability Whether Calcite should add a CAST to a literal
 *                         resulting from simplification and expression if the
 *                         expression had nullable type and the literal is
 *                         NOT NULL
 *
 * @return whether reduction found something to change, and succeeded
 */
protected static boolean reduceExpressions(RelNode rel, List<RexNode> expList,
    RelOptPredicateList predicates, boolean unknownAsFalse,
    boolean matchNullability) {
  final RelOptCluster cluster = rel.getCluster();
  final RexBuilder rexBuilder = cluster.getRexBuilder();
  final RexExecutor executor =
      Util.first(cluster.getPlanner().getExecutor(), RexUtil.EXECUTOR);
  final RexSimplify simplify =
      new RexSimplify(rexBuilder, predicates, executor);

  // Simplify predicates in place
  final RexUnknownAs unknownAs = RexUnknownAs.falseIf(unknownAsFalse);
  final boolean reduced = reduceExpressionsInternal(rel, simplify, unknownAs,
      expList, predicates);

  boolean simplified = false;
  for (int i = 0; i < expList.size(); i++) {
    final RexNode expr2 =
        simplify.simplifyPreservingType(expList.get(i), unknownAs,
            matchNullability);
    if (!expr2.equals(expList.get(i))) {
      expList.set(i, expr2);
      simplified = true;
    }
  }

  return reduced || simplified;
}