org.apache.calcite.rex.RexInputRef Java Examples

The following examples show how to use org.apache.calcite.rex.RexInputRef. 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   Author: apache   File: GeodeFilter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 *  Get the field name for the left node to use for IN SET query
 */
private String getLeftNodeFieldName(RexNode left) {
  switch (left.getKind()) {
  case INPUT_REF:
    final RexInputRef left1 = (RexInputRef) left;
    return fieldNames.get(left1.getIndex());
  case CAST:
    // FIXME This will not work in all cases (for example, we ignore string encoding)
    return getLeftNodeFieldName(((RexCall) left).operands.get(0));
  case ITEM:
  case OTHER_FUNCTION:
    return left.accept(new GeodeRules.RexToGeodeTranslator(this.fieldNames));
  default:
    return null;
  }
}
 
Example #2
Source Project: mat-calcite-plugin   Author: vlsi   File: InstanceAccessByClassIdRule.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onMatch(RelOptRuleCall call) {
    InstanceByClassTableScan scan = call.rel(0);
    RelOptTable table = scan.getTable();
    RelOptSchema schema = table.getRelOptSchema();
    List<String> indexName = new ArrayList<String>(table.getQualifiedName());
    indexName.set(indexName.size() - 1, "$ids$:" + indexName.get(indexName.size() - 1));
    LogicalTableScan ids = LogicalTableScan.create(scan.getCluster(), schema.getTableForMember(indexName));

    InstanceByClassTable instanceByClassTable = table.unwrap(InstanceByClassTable.class);
    int snapshotId = SnapshotHolder.put(instanceByClassTable.snapshot);

    RelOptCluster cluster = scan.getCluster();
    RexInputRef objectId = cluster.getRexBuilder().makeInputRef(ids, 0);
    RexBuilderContext rexContext = new ExecutionRexBuilderContext(cluster, snapshotId, objectId);

    List<Function<RexBuilderContext, RexNode>> resolvers = instanceByClassTable.getResolvers();
    List<RexNode> exprs = new ArrayList<RexNode>(resolvers.size());
    for (Function<RexBuilderContext, RexNode> resolver : resolvers) {
        exprs.add(resolver.apply(rexContext));
    }
    call.transformTo(RelOptUtil.createProject(ids, exprs, table.getRowType().getFieldNames(), true));
}
 
Example #3
Source Project: dremio-oss   Author: dremio   File: MoreRelOptUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static boolean isSimpleColumnSelection(Project project) {
  HashSet<Integer> inputRefReferenced = new HashSet<>();
  for (Pair<RexNode, String> proj : project.getNamedProjects()) {
    if (proj.getKey().getKind() != SqlKind.INPUT_REF) {
      return false;
    }
    RexInputRef inputRef = (RexInputRef) proj.getKey();
    // If the input reference is again referenced, then it is not a simple column selection (since it is not a permutation).
    if (inputRefReferenced.contains(inputRef.getIndex())) {
      return false;
    }
    final String nameOfProjectField = proj.getValue();
    final String nameOfInput = project.getInput().getRowType().getFieldNames().get(inputRef.getIndex());
    // Renaming a column is not a simple column selection
    if (nameOfProjectField == null || !nameOfProjectField.equals(nameOfInput)) {
      return false;
    }
    inputRefReferenced.add(inputRef.getIndex());
  }
  return true;
}
 
Example #4
Source Project: calcite   Author: apache   File: RelMdExpressionLineage.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Expression lineage from {@link TableScan}.
 *
 * <p>We extract the fields referenced by the expression and we express them
 * using {@link RexTableInputRef}.
 */
public Set<RexNode> getExpressionLineage(TableScan rel,
    RelMetadataQuery mq, RexNode outputExpression) {
  final RexBuilder rexBuilder = rel.getCluster().getRexBuilder();

  // Extract input fields referenced by expression
  final ImmutableBitSet inputFieldsUsed = extractInputRefs(outputExpression);

  // Infer column origin expressions for given references
  final Map<RexInputRef, Set<RexNode>> mapping = new LinkedHashMap<>();
  for (int idx : inputFieldsUsed) {
    final RexNode inputRef = RexTableInputRef.of(
        RelTableRef.of(rel.getTable(), 0),
        RexInputRef.of(idx, rel.getRowType().getFieldList()));
    final RexInputRef ref = RexInputRef.of(idx, rel.getRowType().getFieldList());
    mapping.put(ref, ImmutableSet.of(inputRef));
  }

  // Return result
  return createAllPossibleExpressions(rexBuilder, outputExpression, mapping);
}
 
Example #5
Source Project: calcite   Author: apache   File: SubstitutionVisitor.java    License: Apache License 2.0 6 votes vote down vote up
/** Check if join condition only references RexInputRef. */
private static boolean referenceByMapping(
    RexNode joinCondition, List<RexNode>... projectsOfInputs) {
  List<RexNode> projects = new ArrayList<>();
  for (List<RexNode> projectsOfInput: projectsOfInputs) {
    projects.addAll(projectsOfInput);
  }

  try {
    RexVisitor rexVisitor = new RexVisitorImpl<Void>(true) {
      @Override public Void visitInputRef(RexInputRef inputRef) {
        if (!(projects.get(inputRef.getIndex()) instanceof RexInputRef)) {
          throw Util.FoundOne.NULL;
        }
        return super.visitInputRef(inputRef);
      }
    };
    joinCondition.accept(rexVisitor);
  } catch (Util.FoundOne e) {
    return false;
  }
  return true;
}
 
Example #6
Source Project: lucene-solr   Author: apache   File: SolrFilter.java    License: Apache License 2.0 6 votes vote down vote up
/**
     * Translates a call to a binary operator. Returns whether successful.
     */
    private Pair<String, RexLiteral> translateBinary2(RexNode left, RexNode right) {
      switch (right.getKind()) {
        case LITERAL:
          break;
        default:
          return null;
      }

      final RexLiteral rightLiteral = (RexLiteral) right;
      switch (left.getKind()) {
        case INPUT_REF:
          final RexInputRef left1 = (RexInputRef) left;
          String name = fieldNames.get(left1.getIndex());
          return new Pair<>(name, rightLiteral);
        case CAST:
          return translateBinary2(((RexCall) left).operands.get(0), right);
//        case OTHER_FUNCTION:
//          String itemName = SolrRules.isItem((RexCall) left);
//          if (itemName != null) {
//            return translateOp2(op, itemName, rightLiteral);
//          }
        default:
          return null;
      }
    }
 
Example #7
Source Project: Bats   Author: lealone   File: RelOptUtil.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public RexNode visitInputRef(RexInputRef var) {
    int srcIndex = var.getIndex();
    int destIndex = srcIndex + adjustments[srcIndex];

    RelDataType type;
    if (destFields != null) {
        type = destFields.get(destIndex).getType();
    } else if (leftDestFields != null) {
        if (destIndex < nLeftDestFields) {
            type = leftDestFields.get(destIndex).getType();
        } else {
            type = rightDestFields.get(destIndex - nLeftDestFields).getType();
        }
    } else {
        type = srcFields.get(srcIndex).getType();
    }
    if ((adjustments[srcIndex] != 0) || (srcFields == null) || (type != srcFields.get(srcIndex).getType())) {
        return rexBuilder.makeInputRef(type, destIndex);
    } else {
        return var;
    }
}
 
Example #8
Source Project: calcite   Author: apache   File: RelMdSize.java    License: Apache License 2.0 6 votes vote down vote up
public Double averageRexSize(RexNode node, List<Double> inputColumnSizes) {
  switch (node.getKind()) {
  case INPUT_REF:
    return inputColumnSizes.get(((RexInputRef) node).getIndex());
  case LITERAL:
    return typeValueSize(node.getType(),
        ((RexLiteral) node).getValueAs(Comparable.class));
  default:
    if (node instanceof RexCall) {
      RexCall call = (RexCall) node;
      for (RexNode operand : call.getOperands()) {
        // It's a reasonable assumption that a function's result will have
        // similar size to its argument of a similar type. For example,
        // UPPER(c) has the same average size as c.
        if (operand.getType().getSqlTypeName()
            == node.getType().getSqlTypeName()) {
          return averageRexSize(operand, inputColumnSizes);
        }
      }
    }
    return averageTypeValueSize(node.getType());
  }
}
 
Example #9
Source Project: calcite   Author: apache   File: MockCatalogReader.java    License: Apache License 2.0 6 votes vote down vote up
@Override public RelNode toRel(ToRelContext context) {
  RelNode rel = LogicalTableScan.create(context.getCluster(), fromTable,
      context.getTableHints());
  final RexBuilder rexBuilder = context.getCluster().getRexBuilder();
  rel = LogicalFilter.create(
      rel, getConstraint(rexBuilder, rel.getRowType()));
  final List<RelDataTypeField> fieldList =
      rel.getRowType().getFieldList();
  final List<Pair<RexNode, String>> projects =
      new AbstractList<Pair<RexNode, String>>() {
        @Override public Pair<RexNode, String> get(int index) {
          return RexInputRef.of2(mapping.get(index), fieldList);
        }

        @Override public int size() {
          return mapping.size();
        }
      };
  return LogicalProject.create(rel,
      ImmutableList.of(),
      Pair.left(projects),
      Pair.right(projects));
}
 
Example #10
Source Project: calcite   Author: apache   File: RelMetadataTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test void testExpressionLineageTwoColumnsSwapped() {
  // deptno is column 7 in catalog.sales.emp
  // mgr is column 3 in catalog.sales.emp
  final RelNode rel = convertSql("select deptno, mgr from emp");
  final RelMetadataQuery mq = rel.getCluster().getMetadataQuery();

  final RexNode ref1 = RexInputRef.of(0, rel.getRowType().getFieldList());
  final Set<RexNode> r1 = mq.getExpressionLineage(rel, ref1);
  assertThat(r1.size(), is(1));
  final RexTableInputRef result1 = (RexTableInputRef) r1.iterator().next();
  assertThat(result1.getQualifiedName(), is(EMP_QNAME));
  assertThat(result1.getIndex(), is(7));

  final RexNode ref2 = RexInputRef.of(1, rel.getRowType().getFieldList());
  final Set<RexNode> r2 = mq.getExpressionLineage(rel, ref2);
  assertThat(r2.size(), is(1));
  final RexTableInputRef result2 = (RexTableInputRef) r2.iterator().next();
  assertThat(result2.getQualifiedName(), is(EMP_QNAME));
  assertThat(result2.getIndex(), is(3));

  assertThat(result1.getIdentifier(), is(result2.getIdentifier()));
}
 
Example #11
Source Project: calcite   Author: apache   File: GeodeRules.java    License: Apache License 2.0 6 votes vote down vote up
private boolean isBooleanColumnReference(RexNode node, List<String> fieldNames) {
  // FIXME Ignore casts for rel and assume they aren't really necessary
  if (node.isA(SqlKind.CAST)) {
    node = ((RexCall) node).getOperands().get(0);
  }
  if (node.isA(SqlKind.NOT)) {
    node = ((RexCall) node).getOperands().get(0);
  }
  if (node.isA(SqlKind.INPUT_REF)) {
    if (node.getType().getSqlTypeName() == SqlTypeName.BOOLEAN) {
      final RexInputRef left1 = (RexInputRef) node;
      String name = fieldNames.get(left1.getIndex());
      return name != null;
    }
  }
  return false;
}
 
Example #12
Source Project: Bats   Author: lealone   File: VisitorDataContext.java    License: Apache License 2.0 6 votes vote down vote up
public static DataContext of(RelDataType rowType,
    List<Pair<RexInputRef, RexNode>> usageList) {
  final int size = rowType.getFieldList().size();
  final Object[] values = new Object[size];
  for (Pair<RexInputRef, RexNode> elem : usageList) {
    Pair<Integer, ?> value = getValue(elem.getKey(), elem.getValue());
    if (value == null) {
      LOGGER.warn("{} is not handled for {} for checking implication",
          elem.getKey(), elem.getValue());
      return null;
    }
    int index = value.getKey();
    values[index] = value.getValue();
  }
  return new VisitorDataContext(values);
}
 
Example #13
Source Project: kylin   Author: apache   File: OLAPJoinRel.java    License: Apache License 2.0 6 votes vote down vote up
void translateJoinColumn(RexCall condition, Multimap<TblColRef, TblColRef> joinColumns) {
    SqlKind kind = condition.getOperator().getKind();
    if (kind == SqlKind.AND) {
        for (RexNode operand : condition.getOperands()) {
            RexCall subCond = (RexCall) operand;
            translateJoinColumn(subCond, joinColumns);
        }
    } else if (kind == SqlKind.EQUALS) {
        List<RexNode> operands = condition.getOperands();
        RexInputRef op0 = (RexInputRef) operands.get(0);
        TblColRef col0 = columnRowType.getColumnByIndex(op0.getIndex());
        RexInputRef op1 = (RexInputRef) operands.get(1);
        TblColRef col1 = columnRowType.getColumnByIndex(op1.getIndex());
        // map left => right
        if (op0.getIndex() < columnRowTypeLeftRightCut)
            joinColumns.put(col0, col1);
        else
            joinColumns.put(col1, col0);
    }
}
 
Example #14
Source Project: calcite   Author: apache   File: RelDecorrelator.java    License: Apache License 2.0 6 votes vote down vote up
@Override public RexNode visitFieldAccess(RexFieldAccess fieldAccess) {
  if (cm.mapFieldAccessToCorRef.containsKey(fieldAccess)) {
    // if it is a corVar, change it to be input ref.
    CorRef corVar = cm.mapFieldAccessToCorRef.get(fieldAccess);

    // corVar offset should point to the leftInput of currentRel,
    // which is the Correlate.
    RexNode newRexNode =
        new RexInputRef(corVar.field, fieldAccess.getType());

    if (projectPulledAboveLeftCorrelator
        && (nullIndicator != null)) {
      // need to enforce nullability by applying an additional
      // cast operator over the transformed expression.
      newRexNode =
          createCaseExpression(nullIndicator, null, newRexNode);
    }
    return newRexNode;
  }
  return fieldAccess;
}
 
Example #15
Source Project: calcite   Author: apache   File: RelBuilder.java    License: 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 #16
Source Project: flink   Author: apache   File: FlinkSemiAntiJoinProjectTransposeRule.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean matches(RelOptRuleCall call) {
	LogicalJoin join = call.rel(0);
	LogicalProject project = call.rel(1);

	// only accept SEMI/ANTI join
	JoinRelType joinType = join.getJoinType();
	if (joinType != JoinRelType.SEMI && joinType != JoinRelType.ANTI) {
		return false;
	}
	// all expressions in Project should be RexInputRef
	for (RexNode p : project.getProjects()) {
		if (!(p instanceof RexInputRef)) {
			return false;
		}
	}
	return true;
}
 
Example #17
Source Project: calcite   Author: apache   File: RelStructuredTypeFlattener.java    License: Apache License 2.0 6 votes vote down vote up
@Override public RexNode visitInputRef(RexInputRef input) {
  final int oldIndex = input.getIndex();
  final Ord<RelDataType> field = getNewFieldForOldInput(oldIndex);
  RelDataTypeField inputFieldByOldIndex = currentRel.getInputs().stream()
      .flatMap(relInput -> relInput.getRowType().getFieldList().stream())
      .skip(oldIndex)
      .findFirst()
      .orElseThrow(() ->
          new AssertionError("Found input ref with index not found in old inputs"));
  if (inputFieldByOldIndex.getType().isStruct()) {
    iRestructureInput = field.i;
    List<RexNode> rexNodes = restructureFields(inputFieldByOldIndex.getType());
    return rexBuilder.makeCall(
        inputFieldByOldIndex.getType(),
        SqlStdOperatorTable.ROW,
        rexNodes);
  }

  // Use the actual flattened type, which may be different from the current
  // type.
  RelDataType fieldType = removeDistinct(field.e);
  return new RexInputRef(field.i, fieldType);
}
 
Example #18
Source Project: calcite   Author: apache   File: RelOptUtilTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test {@link RelOptUtil#splitJoinCondition(RelNode, RelNode, RexNode, List, List, List)}
 * where the join condition contains an expanded version of IS NOT DISTINCT using CASE
 */
@Test void testSplitJoinConditionExpandedIsNotDistinctFromUsingCase() {
  int leftJoinIndex = empScan.getRowType().getFieldNames().indexOf("DEPTNO");
  int rightJoinIndex = deptRow.getFieldNames().indexOf("DEPTNO");

  RexInputRef leftKeyInputRef = RexInputRef.of(leftJoinIndex, empDeptJoinRelFields);
  RexInputRef rightKeyInputRef =
      RexInputRef.of(empRow.getFieldCount() + rightJoinIndex, empDeptJoinRelFields);
  RexNode joinCond = RelOptUtil.isDistinctFrom(
      relBuilder.getRexBuilder(),
      leftKeyInputRef,
      rightKeyInputRef,
      true);


  splitJoinConditionHelper(
      joinCond,
      Collections.singletonList(leftJoinIndex),
      Collections.singletonList(rightJoinIndex),
      Collections.singletonList(false),
      relBuilder.literal(true));
}
 
Example #19
Source Project: Bats   Author: lealone   File: DrillRelMdSelectivity.java    License: Apache License 2.0 6 votes vote down vote up
private static RexInputRef findRexInputRef(final RexNode node) {
  try {
    RexVisitor<Void> visitor =
        new RexVisitorImpl<Void>(true) {
          public Void visitCall(RexCall call) {
            for (RexNode child : call.getOperands()) {
              child.accept(this);
            }
            return super.visitCall(call);
          }

          public Void visitInputRef(RexInputRef inputRef) {
            throw new Util.FoundOne(inputRef);
          }
        };
    node.accept(visitor);
    return null;
  } catch (Util.FoundOne e) {
    Util.swallow(e, null);
    return (RexInputRef) e.getNode();
  }
}
 
Example #20
Source Project: Bats   Author: lealone   File: CountToDirectScanUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * For each field creates row expression.
 *
 * @param rowType row type
 * @return list of row expressions
 */
public static List<RexNode> prepareFieldExpressions(RelDataType rowType) {
  List<RexNode> expressions = new ArrayList<>();
  for (int i = 0; i < rowType.getFieldCount(); i++) {
    expressions.add(RexInputRef.of(i, rowType));
  }
  return expressions;
}
 
Example #21
Source Project: Bats   Author: lealone   File: ProjectPrule.java    License: Apache License 2.0 5 votes vote down vote up
private Map<Integer, Integer> getCollationMap(DrillProjectRel project) {
  Map<Integer, Integer> m = new HashMap<>();

  for (Ord<RexNode> node : Ord.zip(project.getProjects())) {
    // For collation, only $0 will keep the sort-ness after projection.
    if (node.e instanceof RexInputRef) {
      m.put( ((RexInputRef) node.e).getIndex(), node.i);
    }
  }
  return m;

}
 
Example #22
Source Project: calcite   Author: apache   File: RexToLixTranslator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Visit {@code RexInputRef}. If it has never been visited
 * under current storage type before, {@code RexToLixTranslator}
 * generally produces three lines of code.
 * For example, when visiting a column (named commission) in
 * table Employee, the generated code snippet is:
 * {@code
 *   final Employee current =(Employee) inputEnumerator.current();
     final Integer input_value = current.commission;
     final boolean input_isNull = input_value == null;
 * }
 */
@Override public Result visitInputRef(RexInputRef inputRef) {
  final Pair<RexNode, Type> key = Pair.of(inputRef, currentStorageType);
  // If the RexInputRef has been visited under current storage type already,
  // it is not necessary to visit it again, just return the result.
  if (rexWithStorageTypeResultMap.containsKey(key)) {
    return rexWithStorageTypeResultMap.get(key);
  }
  // Generate one line of code to get the input, e.g.,
  // "final Employee current =(Employee) inputEnumerator.current();"
  final Expression valueExpression = inputGetter.field(
      list, inputRef.getIndex(), currentStorageType);

  // Generate one line of code for the value of RexInputRef, e.g.,
  // "final Integer input_value = current.commission;"
  final ParameterExpression valueVariable =
      Expressions.parameter(
          valueExpression.getType(), list.newName("input_value"));
  list.add(Expressions.declare(Modifier.FINAL, valueVariable, valueExpression));

  // Generate one line of code to check whether RexInputRef is null, e.g.,
  // "final boolean input_isNull = input_value == null;"
  final Expression isNullExpression = checkNull(valueVariable);
  final ParameterExpression isNullVariable =
      Expressions.parameter(
          Boolean.TYPE, list.newName("input_isNull"));
  list.add(Expressions.declare(Modifier.FINAL, isNullVariable, isNullExpression));

  final Result result = new Result(isNullVariable, valueVariable);

  // Cache <RexInputRef, currentStorageType>'s result
  // Note: EnumerableMatch's PrevInputGetter changes index each time,
  // it is not right to reuse the result under such case.
  if (!(inputGetter instanceof EnumerableMatch.PrevInputGetter)) {
    rexWithStorageTypeResultMap.put(key, result);
  }
  return new Result(isNullVariable, valueVariable);
}
 
Example #23
Source Project: nifi   Author: apache   File: JvmMetricsProjectTableScanRule.java    License: Apache License 2.0 5 votes vote down vote up
private int[] getProjectFields(List<RexNode> exps) {
    final int[] fields = new int[exps.size()];

    for (int i = 0; i < exps.size(); i++) {
        final RexNode exp = exps.get(i);

        if (exp instanceof RexInputRef) {
            fields[i] = ((RexInputRef) exp).getIndex();
        } else {
            return null; // not a simple projection
        }
    }

    return fields;
}
 
Example #24
Source Project: calcite   Author: apache   File: RelMetadataTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test void testExpressionLineageValues() {
  // lineage cannot be determined
  final RelNode rel = convertSql("select * from (values (1), (2)) as t(c)");
  final RelMetadataQuery mq = rel.getCluster().getMetadataQuery();

  final RexNode ref = RexInputRef.of(0, rel.getRowType().getFieldList());
  final Set<RexNode> r = mq.getExpressionLineage(rel, ref);
  assertNull(r);
}
 
Example #25
Source Project: calcite   Author: apache   File: RelOptUtil.java    License: Apache License 2.0 5 votes vote down vote up
/** Decomposes the WHERE clause of a view into predicates that constraint
 * a column to a particular value.
 *
 * <p>This method is key to the validation of a modifiable view. Columns that
 * are constrained to a single value can be omitted from the
 * SELECT clause of a modifiable view.
 *
 * @param projectMap Mapping from column ordinal to the expression that
 * populate that column, to be populated by this method
 * @param filters List of remaining filters, to be populated by this method
 * @param constraint Constraint to be analyzed
 */
public static void inferViewPredicates(Map<Integer, RexNode> projectMap,
    List<RexNode> filters, RexNode constraint) {
  for (RexNode node : conjunctions(constraint)) {
    switch (node.getKind()) {
    case EQUALS:
      final List<RexNode> operands = ((RexCall) node).getOperands();
      RexNode o0 = operands.get(0);
      RexNode o1 = operands.get(1);
      if (o0 instanceof RexLiteral) {
        o0 = operands.get(1);
        o1 = operands.get(0);
      }
      if (o0.getKind() == SqlKind.CAST) {
        o0 = ((RexCall) o0).getOperands().get(0);
      }
      if (o0 instanceof RexInputRef && o1 instanceof RexLiteral) {
        final int index = ((RexInputRef) o0).getIndex();
        if (projectMap.get(index) == null) {
          projectMap.put(index, o1);
          continue;
        }
      }
    }
    filters.add(node);
  }
}
 
Example #26
Source Project: calcite   Author: apache   File: RelMetadataTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test void testExpressionLineageStar() {
  // All columns in output
  final RelNode tableRel = convertSql("select * from emp");
  final RelMetadataQuery mq = tableRel.getCluster().getMetadataQuery();

  final RexNode ref = RexInputRef.of(4, tableRel.getRowType().getFieldList());
  final Set<RexNode> r = mq.getExpressionLineage(tableRel, ref);
  final String inputRef = RexInputRef.of(4, tableRel.getRowType().getFieldList()).toString();
  assertThat(r.size(), is(1));
  final String resultString = r.iterator().next().toString();
  assertThat(resultString, startsWith(EMP_QNAME.toString()));
  assertThat(resultString, endsWith(inputRef));
}
 
Example #27
Source Project: dremio-oss   Author: dremio   File: FindPartitionConditions.java    License: Apache License 2.0 5 votes vote down vote up
public Void visitInputRef(RexInputRef inputRef) {
  if(dirs.get(inputRef.getIndex())){
    pushStatusStack.add(PushDirFilter.PUSH);
    addResult(inputRef);
  }else{
    pushStatusStack.add(PushDirFilter.NO_PUSH);
  }
  return null;
}
 
Example #28
Source Project: Bats   Author: lealone   File: SubQueryRemoveRule.java    License: Apache License 2.0 5 votes vote down vote up
/** Returns a reference to a particular field, by offset, across several
 * inputs on a {@link RelBuilder}'s stack. */
private RexInputRef field(RelBuilder builder, int inputCount, int offset) {
    for (int inputOrdinal = 0;;) {
        final RelNode r = builder.peek(inputCount, inputOrdinal);
        if (offset < r.getRowType().getFieldCount()) {
            return builder.field(inputCount, inputOrdinal, offset);
        }
        ++inputOrdinal;
        offset -= r.getRowType().getFieldCount();
    }
}
 
Example #29
Source Project: calcite   Author: apache   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,
    Project 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 #30
Source Project: nifi   Author: apache   File: ProcessGroupStatusProjectTableScanRule.java    License: Apache License 2.0 5 votes vote down vote up
private int[] getProjectFields(List<RexNode> exps) {
    final int[] fields = new int[exps.size()];

    for (int i = 0; i < exps.size(); i++) {
        final RexNode exp = exps.get(i);

        if (exp instanceof RexInputRef) {
            fields[i] = ((RexInputRef) exp).getIndex();
        } else {
            return null; // not a simple projection
        }
    }

    return fields;
}