org.apache.calcite.rex.RexInputRef - java examples

Here are the examples of the java api org.apache.calcite.rex.RexInputRef taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

88 Examples 7

19 View Complete Implementation : InstanceAccessByClassIdRule.java
Copyright Apache License 2.0
Author : vlsi
@Override
public void onMatch(RelOptRuleCall call) {
    InstanceByClreplacedTableScan 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));
    InstanceByClreplacedTable instanceByClreplacedTable = table.unwrap(InstanceByClreplacedTable.clreplaced);
    int snapshotId = SnapshotHolder.put(instanceByClreplacedTable.snapshot);
    RelOptCluster cluster = scan.getCluster();
    RexInputRef objectId = cluster.getRexBuilder().makeInputRef(ids, 0);
    RexBuilderContext rexContext = new ExecutionRexBuilderContext(cluster, snapshotId, objectId);
    List<Function<RexBuilderContext, RexNode>> resolvers = instanceByClreplacedTable.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));
}

19 View Complete Implementation : FieldsReWriterUtil.java
Copyright Apache License 2.0
Author : apache
/**
 * Checks if operator call is using item star field.
 * Will return field name if true. null otherwise.
 *
 * @param rexCall operator call
 * @param fieldNames list of field names
 * @return field name, null otherwise
 */
public static String getFieldNameFromItemStarField(RexCall rexCall, List<String> fieldNames) {
    if (!SqlStdOperatorTable.ITEM.equals(rexCall.getOperator())) {
        return null;
    }
    if (rexCall.getOperands().size() != 2) {
        return null;
    }
    if (!(rexCall.getOperands().get(0) instanceof RexInputRef && rexCall.getOperands().get(1) instanceof RexLiteral)) {
        return null;
    }
    // get parent field reference from the first operand (ITEM($0, 'col_name' -> $0)
    // and check if it corresponds to the dynamic star
    RexInputRef rexInputRef = (RexInputRef) rexCall.getOperands().get(0);
    String parentFieldName = fieldNames.get(rexInputRef.getIndex());
    if (!SchemaPath.DYNAMIC_STAR.equals(parentFieldName)) {
        return null;
    }
    // get field name from the second operand (ITEM($0, 'col_name') -> col_name)
    RexLiteral rexLiteral = (RexLiteral) rexCall.getOperands().get(1);
    if (SqlTypeName.CHAR.equals(rexLiteral.getType().getSqlTypeName())) {
        return RexLiteral.stringValue(rexLiteral);
    }
    return null;
}

19 View Complete Implementation : JdbcExpressionCheck.java
Copyright Apache License 2.0
Author : apache
@Override
public Boolean visitInputRef(RexInputRef paramRexInputRef) {
    return true;
}

19 View Complete Implementation : FindSimpleFilters.java
Copyright Apache License 2.0
Author : dremio
@Override
public StateHolder visitInputRef(RexInputRef inputRef) {
    return new StateHolder(Type.INPUT, inputRef);
}

19 View Complete Implementation : Strong.java
Copyright Apache License 2.0
Author : apache
/**
 * Returns whether a given input is definitely null.
 */
public boolean isNull(RexInputRef ref) {
    return false;
}

19 View Complete Implementation : RelMdUtil.java
Copyright Apache License 2.0
Author : apache
public static Boolean areColumnsUniqueWhenNullsFiltered(RelMetadataQuery mq, RelNode rel, List<RexInputRef> columnRefs) {
    ImmutableBitSet.Builder colMask = ImmutableBitSet.builder();
    for (RexInputRef columnRef : columnRefs) {
        colMask.set(columnRef.getIndex());
    }
    return mq.areColumnsUnique(rel, colMask.build(), true);
}

19 View Complete Implementation : RexVisitorComplexExprSplitter.java
Copyright Apache License 2.0
Author : apache
@Override
public RexNode visitInputRef(RexInputRef inputRef) {
    return inputRef;
}

19 View Complete Implementation : RelMdUtil.java
Copyright Apache License 2.0
Author : apache
public static Boolean areColumnsUnique(RelMetadataQuery mq, RelNode rel, List<RexInputRef> columnRefs) {
    ImmutableBitSet.Builder colMask = ImmutableBitSet.builder();
    for (RexInputRef columnRef : columnRefs) {
        colMask.set(columnRef.getIndex());
    }
    return mq.areColumnsUnique(rel, colMask.build());
}

18 View Complete Implementation : ORCFindRelevantFilters.java
Copyright Apache License 2.0
Author : dremio
@Override
public RexNode visitInputRef(RexInputRef inputRef) {
    return rexBuilder.copy(inputRef);
}

18 View Complete Implementation : MoreRelOptUtil.java
Copyright Apache License 2.0
Author : dremio
/**
 * Returns whether the leading edge of a given array of expressions is
 * wholly {@link RexInputRef} objects with types and names corresponding
 * to the underlying row type.
 */
public static boolean containIdenreplacedy(List<? extends RexNode> exps, RelDataType rowType, RelDataType childRowType) {
    List<RelDataTypeField> fields = rowType.getFieldList();
    List<RelDataTypeField> childFields = childRowType.getFieldList();
    int fieldCount = childFields.size();
    if (exps.size() != fieldCount) {
        return false;
    }
    for (int i = 0; i < exps.size(); i++) {
        RexNode exp = exps.get(i);
        if (!(exp instanceof RexInputRef)) {
            return false;
        }
        RexInputRef var = (RexInputRef) exp;
        if (var.getIndex() != i) {
            return false;
        }
        if (!fields.get(i).getName().equals(childFields.get(i).getName())) {
            return false;
        }
        if (!fields.get(i).getType().equals(childFields.get(i).getType())) {
            return false;
        }
    }
    return true;
}

18 View Complete Implementation : Lattice.java
Copyright Apache License 2.0
Author : apache
/**
 * Converts an expression into an (input, field) pair.
 */
private static int[] inputField(List<RelNode> leaves, RexNode rex) {
    if (!(rex instanceof RexInputRef)) {
        throw new RuntimeException("only equi-join of columns allowed: " + rex);
    }
    RexInputRef ref = (RexInputRef) rex;
    int start = 0;
    for (int i = 0; i < leaves.size(); i++) {
        final RelNode leaf = leaves.get(i);
        final int end = start + leaf.getRowType().getFieldCount();
        if (ref.getIndex() < end) {
            return new int[] { i, ref.getIndex() - start };
        }
        start = end;
    }
    throw new replacedertionError("input not found");
}

18 View Complete Implementation : ConvertHiveParquetScanToDrillParquetScan.java
Copyright Apache License 2.0
Author : apache
/**
 * Create a cast for parreplacedion column. Parreplacedion column is output as "VARCHAR" in native parquet reader. Cast it
 * appropriate type according the parreplacedion type in HiveScan.
 */
private RexNode createParreplacedionColumnCast(final DrillScanRel hiveScanRel, final DrillScanRel nativeScanRel, final String outputColName, final String dirColName, final RexBuilder rb) {
    final RelDataType outputType = hiveScanRel.getRowType().getField(outputColName, false, false).getType();
    final RelDataTypeField inputField = nativeScanRel.getRowType().getField(dirColName, false, false);
    final RexInputRef inputRef = rb.makeInputRef(rb.getTypeFactory().createSqlType(SqlTypeName.VARCHAR), inputField.getIndex());
    if (outputType.getSqlTypeName() == SqlTypeName.CHAR) {
        return rb.makeCall(RTRIM, inputRef);
    }
    return rb.makeCast(outputType, inputRef);
}

18 View Complete Implementation : DrillRelOptUtil.java
Copyright Apache License 2.0
Author : apache
/**
 * Returns whether the leading edge of a given array of expressions is
 * wholly {@link RexInputRef} objects with types and names corresponding
 * to the underlying row type.
 */
private static boolean containIdenreplacedy(List<? extends RexNode> exps, RelDataType rowType, RelDataType childRowType) {
    List<RelDataTypeField> fields = rowType.getFieldList();
    List<RelDataTypeField> childFields = childRowType.getFieldList();
    int fieldCount = childFields.size();
    if (exps.size() != fieldCount) {
        return false;
    }
    for (int i = 0; i < exps.size(); i++) {
        RexNode exp = exps.get(i);
        if (!(exp instanceof RexInputRef)) {
            return false;
        }
        RexInputRef var = (RexInputRef) exp;
        if (var.getIndex() != i) {
            return false;
        }
        if (!fields.get(i).getName().equals(childFields.get(i).getName())) {
            return false;
        }
        if (!fields.get(i).getType().equals(childFields.get(i).getType())) {
            return false;
        }
    }
    return true;
}

18 View Complete Implementation : TupleFilterVisitor.java
Copyright Apache License 2.0
Author : apache
@Override
public TupleFilter visitInputRef(RexInputRef inputRef) {
    TblColRef column = inputRowType.getColumnByIndex(inputRef.getIndex());
    ColumnTupleFilter filter = new ColumnTupleFilter(column);
    return filter;
}

18 View Complete Implementation : DrillRelOptUtil.java
Copyright Apache License 2.0
Author : apache
/**
 * Returns whether the join condition is a simple equi-join or not. A simple equi-join is
 * defined as an two-table equality join (no self-join)
 * @param join : input join
 * @param joinFieldOrdinals: join field ordinal w.r.t. the underlying inputs to the join
 * @return TRUE if the join is a simple equi-join (not a self-join), FALSE otherwise
 */
public static boolean replacedyzeSimpleEquiJoin(Join join, int[] joinFieldOrdinals) {
    RexNode joinExp = join.getCondition();
    if (joinExp.getKind() != SqlKind.EQUALS) {
        return false;
    } else {
        RexCall binaryExpression = (RexCall) joinExp;
        RexNode leftComparand = binaryExpression.operands.get(0);
        RexNode rightComparand = binaryExpression.operands.get(1);
        if (!(leftComparand instanceof RexInputRef)) {
            return false;
        } else if (!(rightComparand instanceof RexInputRef)) {
            return false;
        } else {
            int leftFieldCount = join.getLeft().getRowType().getFieldCount();
            int rightFieldCount = join.getRight().getRowType().getFieldCount();
            RexInputRef leftFieldAccess = (RexInputRef) leftComparand;
            RexInputRef rightFieldAccess = (RexInputRef) rightComparand;
            if (leftFieldAccess.getIndex() >= leftFieldCount + rightFieldCount || rightFieldAccess.getIndex() >= leftFieldCount + rightFieldCount) {
                return false;
            }
            /* Both columns reference same table */
            if ((leftFieldAccess.getIndex() >= leftFieldCount && rightFieldAccess.getIndex() >= leftFieldCount) || (leftFieldAccess.getIndex() < leftFieldCount && rightFieldAccess.getIndex() < leftFieldCount)) {
                return false;
            } else {
                if (leftFieldAccess.getIndex() < leftFieldCount) {
                    joinFieldOrdinals[0] = leftFieldAccess.getIndex();
                    joinFieldOrdinals[1] = rightFieldAccess.getIndex() - leftFieldCount;
                } else {
                    joinFieldOrdinals[0] = rightFieldAccess.getIndex();
                    joinFieldOrdinals[1] = leftFieldAccess.getIndex() - leftFieldCount;
                }
                return true;
            }
        }
    }
}

18 View Complete Implementation : FindFiltersForCollation.java
Copyright Apache License 2.0
Author : apache
@Override
public Boolean visitInputRef(RexInputRef inputRef) {
    if (inputRef.getIndex() == currentFieldIndex) {
        return true;
    }
    return false;
}

18 View Complete Implementation : IndexableExprMarker.java
Copyright Apache License 2.0
Author : apache
@Override
public Boolean visitInputRef(RexInputRef rexInputRef) {
    return directCompareOp;
}

18 View Complete Implementation : OLAPProjectRel.java
Copyright Apache License 2.0
Author : apache
private TblColRef translateRexNode(RexNode rexNode, ColumnRowType inputColumnRowType, TupleExpression tupleExpr, String fieldName) {
    if (tupleExpr instanceof ColumnTupleExpression) {
        return ((ColumnTupleExpression) tupleExpr).getColumn();
    } else if (tupleExpr instanceof NumberTupleExpression) {
        Object value = ((NumberTupleExpression) tupleExpr).getValue();
        return TblColRef.newInnerColumn(value == null ? "null" : value.toString(), InnerDataTypeEnum.LITERAL);
    } else if (tupleExpr instanceof StringTupleExpression) {
        Object value = ((StringTupleExpression) tupleExpr).getValue();
        return TblColRef.newInnerColumn(value == null ? "null" : value.toString(), InnerDataTypeEnum.LITERAL);
    } else if (tupleExpr instanceof RexCallTupleExpression && rexNode instanceof RexInputRef) {
        RexInputRef inputRef = (RexInputRef) rexNode;
        int index = inputRef.getIndex();
        if (index < inputColumnRowType.size()) {
            return inputColumnRowType.getColumnByIndex(index);
        }
    }
    return TblColRef.newInnerColumn(fieldName, InnerDataTypeEnum.LITERAL, tupleExpr.getDigest());
}

17 View Complete Implementation : RelMdColumnUniqueness.java
Copyright Apache License 2.0
Author : apache
private boolean simplyProjects(RelNode rel, ImmutableBitSet columns) {
    if (!(rel instanceof Project)) {
        return false;
    }
    Project project = (Project) rel;
    final List<RexNode> projects = project.getProjects();
    for (int column : columns) {
        if (column >= projects.size()) {
            return false;
        }
        if (!(projects.get(column) instanceof RexInputRef)) {
            return false;
        }
        final RexInputRef ref = (RexInputRef) projects.get(column);
        if (ref.getIndex() != column) {
            return false;
        }
    }
    return true;
}

17 View Complete Implementation : RelOptUtilTest.java
Copyright Apache License 2.0
Author : apache
/**
 * 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
public 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));
}

17 View Complete Implementation : PigToSqlAggregateRule.java
Copyright Apache License 2.0
Author : apache
private int getGroupRefIndex(RexNode rex) {
    if (rex instanceof RexFieldAccess) {
        final RexFieldAccess fieldAccess = (RexFieldAccess) rex;
        if (fieldAccess.getReferenceExpr() instanceof RexInputRef) {
            final RexInputRef inputRef = (RexInputRef) fieldAccess.getReferenceExpr();
            if (inputRef.getIndex() == 0) {
                // Project from 'group' column
                return fieldAccess.getField().getIndex();
            }
        }
    }
    return -1;
}

17 View Complete Implementation : ConvertHiveParquetScanToDrillParquetScan.java
Copyright Apache License 2.0
Author : apache
/**
 * Apply any data format conversion expressions.
 */
private RexNode createColumnFormatConversion(DrillScanRel hiveScanRel, DrillScanRel nativeScanRel, String colName, RexBuilder rb) {
    RelDataType outputType = hiveScanRel.getRowType().getField(colName, false, false).getType();
    RelDataTypeField inputField = nativeScanRel.getRowType().getField(colName, false, false);
    RexInputRef inputRef = rb.makeInputRef(inputField.getType(), inputField.getIndex());
    PlannerSettings settings = PrelUtil.getPlannerSettings(hiveScanRel.getCluster().getPlanner());
    boolean conversionToTimestampEnabled = settings.getOptions().getBoolean(ExecConstants.PARQUET_READER_INT96_AS_TIMESTAMP);
    if (outputType.getSqlTypeName() == SqlTypeName.TIMESTAMP && !conversionToTimestampEnabled) {
        // TIMESTAMP is stored as INT96 by Hive in ParquetFormat.
        // Used convert_fromTIMESTAMP_IMPALA UDF to convert INT96 format data to TIMESTAMP
        // only for the case when `store.parquet.reader.int96_as_timestamp` is
        // disabled to avoid double conversion after reading value from parquet and here.
        return rb.makeCall(INT96_TO_TIMESTAMP, inputRef);
    }
    return inputRef;
}

17 View Complete Implementation : FindPartitionConditions.java
Copyright Apache License 2.0
Author : apache
protected boolean inputRefToPush(RexInputRef inputRef) {
    return dirs.get(inputRef.getIndex());
}

17 View Complete Implementation : Expressions.java
Copyright Apache License 2.0
Author : apache
private static DruidExpression inputRefToDruidExpression(final RowSignature rowSignature, final RexNode rexNode) {
    // Translate field references.
    final RexInputRef ref = (RexInputRef) rexNode;
    final String columnName = rowSignature.getRowOrder().get(ref.getIndex());
    if (columnName == null) {
        throw new ISE("WTF?! Expression referred to nonexistent index[%d]", ref.getIndex());
    }
    return DruidExpression.fromColumn(columnName);
}

17 View Complete Implementation : JoinTranslator.java
Copyright Apache License 2.0
Author : apache
private void validateJoinKeys(RexInputRef ref) {
    SqlTypeName sqlTypeName = ref.getType().getSqlTypeName();
    // Primitive types and ANY (for the record key) are supported in the key
    if (sqlTypeName != SqlTypeName.BOOLEAN && sqlTypeName != SqlTypeName.TINYINT && sqlTypeName != SqlTypeName.SMALLINT && sqlTypeName != SqlTypeName.INTEGER && sqlTypeName != SqlTypeName.CHAR && sqlTypeName != SqlTypeName.BIGINT && sqlTypeName != SqlTypeName.VARCHAR && sqlTypeName != SqlTypeName.DOUBLE && sqlTypeName != SqlTypeName.FLOAT && sqlTypeName != SqlTypeName.ANY && sqlTypeName != SqlTypeName.OTHER) {
        log.error("Unsupported key type " + sqlTypeName + " used in join condition.");
        throw new SamzaException("Unsupported key type used in join condition.");
    }
}

17 View Complete Implementation : JoinTranslator.java
Copyright Apache License 2.0
Author : apache
// Fetch the stream and table key indices corresponding to the fields given in the join condition by parsing through
// the condition. Stream and table key indices are populated in streamKeyIds and tableKeyIds respectively.
private void populateStreamAndTableKeyIds(List<RexNode> operands, final LogicalJoin join, boolean isTablePosOnRight, List<Integer> streamKeyIds, List<Integer> tableKeyIds) {
    // All non-leaf operands in the join condition should be expressions.
    if (operands.get(0) instanceof RexCall) {
        operands.forEach(operand -> {
            validateJoinCondition(operand);
            populateStreamAndTableKeyIds(((RexCall) operand).getOperands(), join, isTablePosOnRight, streamKeyIds, tableKeyIds);
        });
        return;
    }
    // We are at the leaf of the join condition. Only binary operators are supported.
    Validate.isTrue(operands.size() == 2);
    // Only reference operands are supported in row expressions and not constants.
    // a.key = b.key is supported with a.key and b.key being reference operands.
    // a.key = "constant" is not yet supported.
    if (!(operands.get(0) instanceof RexInputRef) || !(operands.get(1) instanceof RexInputRef)) {
        throw new SamzaException("SQL query is not supported. Join condition " + join.getCondition() + " should have " + "reference operands but the types are " + operands.get(0).getClreplaced() + " and " + operands.get(1).getClreplaced());
    }
    // Join condition is commutative, meaning, a.key = b.key is equivalent to b.key = a.key.
    // Calcite replacedigns the indices to the fields based on the order a and b are specified in
    // the sql 'from' clause. Let's put the operand with smaller index in leftRef and larger
    // index in rightRef so that the order of operands in the join condition is in the order
    // the stream and table are specified in the 'from' clause.
    RexInputRef leftRef = (RexInputRef) operands.get(0);
    RexInputRef rightRef = (RexInputRef) operands.get(1);
    // Let's validate the key used in the join condition.
    validateJoinKeys(leftRef);
    validateJoinKeys(rightRef);
    if (leftRef.getIndex() > rightRef.getIndex()) {
        RexInputRef tmpRef = leftRef;
        leftRef = rightRef;
        rightRef = tmpRef;
    }
    // Get the table key index and stream key index
    int deltaKeyIdx = rightRef.getIndex() - join.getLeft().getRowType().getFieldCount();
    streamKeyIds.add(isTablePosOnRight ? leftRef.getIndex() : deltaKeyIdx);
    tableKeyIds.add(isTablePosOnRight ? deltaKeyIdx : leftRef.getIndex());
}

17 View Complete Implementation : ORCSearchArgumentGenerator.java
Copyright Apache License 2.0
Author : dremio
@Override
public Object visitInputRef(RexInputRef inputRef) {
    return columnNames.get(inputRef.getIndex());
}

17 View Complete Implementation : DrillRelOptUtil.java
Copyright Apache License 2.0
Author : lealone
/**
 * Returns whether the join condition is a simple equi-join or not. A simple equi-join is
 * defined as an two-table equality join (no self-join)
 * @param join : input join
 * @param joinFieldOrdinals: join field ordinal w.r.t. the underlying inputs to the join
 * @return TRUE if the join is a simple equi-join (not a self-join), FALSE otherwise
 */
public static boolean replacedyzeSimpleEquiJoin(Join join, int[] joinFieldOrdinals) {
    RexNode joinExp = join.getCondition();
    if (joinExp.getKind() != SqlKind.EQUALS) {
        return false;
    } else {
        RexCall binaryExpression = (RexCall) joinExp;
        RexNode leftComparand = binaryExpression.getOperands().get(0);
        RexNode rightComparand = binaryExpression.getOperands().get(1);
        if (!(leftComparand instanceof RexInputRef)) {
            return false;
        } else if (!(rightComparand instanceof RexInputRef)) {
            return false;
        } else {
            int leftFieldCount = join.getLeft().getRowType().getFieldCount();
            int rightFieldCount = join.getRight().getRowType().getFieldCount();
            RexInputRef leftFieldAccess = (RexInputRef) leftComparand;
            RexInputRef rightFieldAccess = (RexInputRef) rightComparand;
            if (leftFieldAccess.getIndex() >= leftFieldCount + rightFieldCount || rightFieldAccess.getIndex() >= leftFieldCount + rightFieldCount) {
                return false;
            }
            /* Both columns reference same table */
            if ((leftFieldAccess.getIndex() >= leftFieldCount && rightFieldAccess.getIndex() >= leftFieldCount) || (leftFieldAccess.getIndex() < leftFieldCount && rightFieldAccess.getIndex() < leftFieldCount)) {
                return false;
            } else {
                if (leftFieldAccess.getIndex() < leftFieldCount) {
                    joinFieldOrdinals[0] = leftFieldAccess.getIndex();
                    joinFieldOrdinals[1] = rightFieldAccess.getIndex() - leftFieldCount;
                } else {
                    joinFieldOrdinals[0] = rightFieldAccess.getIndex();
                    joinFieldOrdinals[1] = leftFieldAccess.getIndex() - leftFieldCount;
                }
                return true;
            }
        }
    }
}

16 View Complete Implementation : DrillRelMdSelectivity.java
Copyright Apache License 2.0
Author : apache
private SchemaPath getColumn(RexNode orPred, List<SchemaPath> fieldNames) {
    if (orPred instanceof RexCall) {
        int colIdx = -1;
        RexInputRef op = findRexInputRef(orPred);
        if (op != null) {
            colIdx = op.getIndex();
        }
        if (colIdx != -1 && colIdx < fieldNames.size()) {
            return fieldNames.get(colIdx);
        } else {
            if (logger.isDebugEnabled()) {
                logger.warn(String.format("No input reference $[%s] found for predicate [%s]", Integer.toString(colIdx), orPred.toString()));
            }
        }
    }
    return null;
}

16 View Complete Implementation : DrillProjectPushIntoLateralJoinRule.java
Copyright Apache License 2.0
Author : apache
public void onMatch(RelOptRuleCall call) {
    DrillProjectRel origProj = call.rel(0);
    final DrillLateralJoinRel corr = call.rel(1);
    if (StarColumnHelper.containsStarColumn(origProj.getRowType()) || StarColumnHelper.containsStarColumn(corr.getRowType()) || corr.excludeCorrelateColumn) {
        return;
    }
    DrillRelOptUtil.InputRefVisitor collectRefs = new DrillRelOptUtil.InputRefVisitor();
    for (RexNode exp : origProj.getChildExps()) {
        exp.accept(collectRefs);
    }
    int correlationIndex = corr.getRequiredColumns().nextSetBit(0);
    for (RexInputRef inputRef : collectRefs.getInputRefs()) {
        if (inputRef.getIndex() == correlationIndex) {
            return;
        }
    }
    final RelNode left = corr.getLeft();
    final RelNode right = corr.getRight();
    final RelNode convertedLeft = convert(left, left.getTraitSet().plus(DrillRel.DRILL_LOGICAL).simplify());
    final RelNode convertedRight = convert(right, right.getTraitSet().plus(DrillRel.DRILL_LOGICAL).simplify());
    final RelTraitSet traits = corr.getTraitSet().plus(DrillRel.DRILL_LOGICAL);
    boolean trivial = DrillRelOptUtil.isTrivialProject(origProj, true);
    RelNode relNode = new DrillLateralJoinRel(corr.getCluster(), traits, convertedLeft, convertedRight, true, corr.getCorrelationId(), corr.getRequiredColumns(), corr.getJoinType());
    if (!trivial) {
        Map<Integer, Integer> mapWithoutCorr = buildMapWithoutCorrColumn(corr, correlationIndex);
        List<RexNode> outputExprs = DrillRelOptUtil.transformExprs(origProj.getCluster().getRexBuilder(), origProj.getChildExps(), mapWithoutCorr);
        relNode = new DrillProjectRel(origProj.getCluster(), left.getTraitSet().plus(DrillRel.DRILL_LOGICAL), relNode, outputExprs, origProj.getRowType());
    }
    call.transformTo(relNode);
}

16 View Complete Implementation : OLAPJoinRel.java
Copyright Apache License 2.0
Author : apache
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);
    }
}

16 View Complete Implementation : MoreRelOptUtil.java
Copyright Apache License 2.0
Author : dremio
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;
}

16 View Complete Implementation : FindPartitionConditions.java
Copyright Apache License 2.0
Author : dremio
public Void visitInputRef(RexInputRef inputRef) {
    if (dirs.get(inputRef.getIndex())) {
        pushStatusStack.add(PushDirFilter.PUSH);
        addResult(inputRef);
    } else {
        pushStatusStack.add(PushDirFilter.NO_PUSH);
    }
    return null;
}

16 View Complete Implementation : DrillProjectPushIntoLateralJoinRule.java
Copyright Apache License 2.0
Author : lealone
public void onMatch(RelOptRuleCall call) {
    DrillProjectRel origProj = call.rel(0);
    final DrillLateralJoinRel corr = call.rel(1);
    if (StarColumnHelper.containsStarColumn(origProj.getRowType()) || StarColumnHelper.containsStarColumn(corr.getRowType()) || corr.excludeCorrelateColumn) {
        return;
    }
    DrillRelOptUtil.InputRefVisitor collectRefs = new DrillRelOptUtil.InputRefVisitor();
    for (RexNode exp : origProj.getChildExps()) {
        exp.accept(collectRefs);
    }
    int correlationIndex = corr.getRequiredColumns().nextSetBit(0);
    for (RexInputRef inputRef : collectRefs.getInputRefs()) {
        if (inputRef.getIndex() == correlationIndex) {
            return;
        }
    }
    final RelNode left = corr.getLeft();
    final RelNode right = corr.getRight();
    final RelNode convertedLeft = convert(left, left.getTraitSet().plus(DrillRel.DRILL_LOGICAL).simplify());
    final RelNode convertedRight = convert(right, right.getTraitSet().plus(DrillRel.DRILL_LOGICAL).simplify());
    final RelTraitSet traits = corr.getTraitSet().plus(DrillRel.DRILL_LOGICAL);
    RelNode relNode = new DrillLateralJoinRel(corr.getCluster(), traits, convertedLeft, convertedRight, true, corr.getCorrelationId(), corr.getRequiredColumns(), corr.getJoinType());
    if (!DrillRelOptUtil.isTrivialProject(origProj, true)) {
        Map<Integer, Integer> mapWithoutCorr = buildMapWithoutCorrColumn(corr, correlationIndex);
        List<RexNode> outputExprs = DrillRelOptUtil.transformExprs(origProj.getCluster().getRexBuilder(), origProj.getChildExps(), mapWithoutCorr);
        relNode = new DrillProjectRel(origProj.getCluster(), left.getTraitSet().plus(DrillRel.DRILL_LOGICAL), relNode, outputExprs, origProj.getRowType());
    }
    call.transformTo(relNode);
}

16 View Complete Implementation : RelMdExpressionLineage.java
Copyright Apache License 2.0
Author : apache
private static Set<RexNode> createAllPossibleExpressions(RexBuilder rexBuilder, RexNode expr, ImmutableBitSet predFieldsUsed, Map<RexInputRef, Set<RexNode>> mapping, Map<RexInputRef, RexNode> singleMapping) {
    final RexInputRef inputRef = mapping.keySet().iterator().next();
    final Set<RexNode> replacements = mapping.remove(inputRef);
    Set<RexNode> result = new HashSet<>();
    replacedert !replacements.isEmpty();
    if (predFieldsUsed.indexOf(inputRef.getIndex()) != -1) {
        for (RexNode replacement : replacements) {
            singleMapping.put(inputRef, replacement);
            createExpressions(rexBuilder, expr, predFieldsUsed, mapping, singleMapping, result);
            singleMapping.remove(inputRef);
        }
    } else {
        createExpressions(rexBuilder, expr, predFieldsUsed, mapping, singleMapping, result);
    }
    mapping.put(inputRef, replacements);
    return result;
}

16 View Complete Implementation : MutableRels.java
Copyright Apache License 2.0
Author : apache
/**
 * Construct expression list of Project by the given fields of the input.
 */
public static List<RexNode> createProjects(final MutableRel child, final List<RexNode> projs) {
    List<RexNode> rexNodeList = new ArrayList<>();
    for (int i = 0; i < projs.size(); i++) {
        if (projs.get(i) instanceof RexInputRef) {
            RexInputRef rexInputRef = (RexInputRef) projs.get(i);
            rexNodeList.add(RexInputRef.of(rexInputRef.getIndex(), child.rowType));
        } else {
            rexNodeList.add(projs.get(i));
        }
    }
    return rexNodeList;
}

16 View Complete Implementation : AggregateJoinTransposeRule.java
Copyright Apache License 2.0
Author : apache
private static void populateEquivalences(Map<Integer, BitSet> equivalence, RexNode predicate) {
    switch(predicate.getKind()) {
        case EQUALS:
            RexCall call = (RexCall) predicate;
            final List<RexNode> operands = call.getOperands();
            if (operands.get(0) instanceof RexInputRef) {
                final RexInputRef ref0 = (RexInputRef) operands.get(0);
                if (operands.get(1) instanceof RexInputRef) {
                    final RexInputRef ref1 = (RexInputRef) operands.get(1);
                    populateEquivalence(equivalence, ref0.getIndex(), ref1.getIndex());
                    populateEquivalence(equivalence, ref1.getIndex(), ref0.getIndex());
                }
            }
    }
}

15 View Complete Implementation : RelMdExpressionLineage.java
Copyright Apache License 2.0
Author : apache
/**
 * Expression lineage from Project.
 */
public Set<RexNode> getExpressionLineage(Project rel, final RelMetadataQuery mq, RexNode outputExpression) {
    final RelNode input = rel.getInput();
    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 inputExpr = rel.getChildExps().get(idx);
        final Set<RexNode> originalExprs = mq.getExpressionLineage(input, inputExpr);
        if (originalExprs == null) {
            // Bail out
            return null;
        }
        final RexInputRef ref = RexInputRef.of(idx, rel.getRowType().getFieldList());
        mapping.put(ref, originalExprs);
    }
    // Return result
    return createAllPossibleExpressions(rexBuilder, outputExpression, mapping);
}

15 View Complete Implementation : RelMdExpressionLineage.java
Copyright Apache License 2.0
Author : apache
/**
 * 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);
}

15 View Complete Implementation : RelOptUtilTest.java
Copyright Apache License 2.0
Author : apache
/**
 * 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
public void testSplitJoinConditionExpandedIsNotDistinctFromUsingCase2() {
    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 = relBuilder.call(SqlStdOperatorTable.CASE, relBuilder.call(SqlStdOperatorTable.IS_NULL, leftKeyInputRef), relBuilder.call(SqlStdOperatorTable.IS_NULL, rightKeyInputRef), relBuilder.call(SqlStdOperatorTable.IS_NULL, rightKeyInputRef), relBuilder.call(SqlStdOperatorTable.IS_NULL, leftKeyInputRef), relBuilder.call(SqlStdOperatorTable.EQUALS, leftKeyInputRef, rightKeyInputRef));
    splitJoinConditionHelper(joinCond, Collections.singletonList(leftJoinIndex), Collections.singletonList(rightJoinIndex), Collections.singletonList(false), relBuilder.literal(true));
}

15 View Complete Implementation : FindPartitionConditions.java
Copyright Apache License 2.0
Author : apache
public Void visitInputRef(RexInputRef inputRef) {
    if (inputRefToPush(inputRef)) {
        pushStatusStack.add(PushDirFilter.PUSH);
        addResult(inputRef);
        referencedDirs.set(inputRef.getIndex());
    } else {
        pushStatusStack.add(PushDirFilter.NO_PUSH);
    }
    return null;
}

15 View Complete Implementation : SplitUpComplexExpressions.java
Copyright Apache License 2.0
Author : apache
@Override
public Prel visitProject(final ProjectPrel project, Object unused) throws RelConversionException {
    final Prel oldInput = (Prel) project.getInput(0);
    RelNode newInput = oldInput.accept(this, unused);
    ProjectPrel newProject = (ProjectPrel) project.copy(project.getTraitSet(), Lists.newArrayList(newInput));
    final int lastColumnReferenced = PrelUtil.getLastUsedColumnReference(newProject.getProjects());
    if (lastColumnReferenced == -1) {
        return newProject;
    }
    List<RelDataTypeField> projectFields = newProject.getRowType().getFieldList();
    List<RelDataTypeField> origRelDataTypes = new ArrayList<>();
    List<RexNode> exprList = new ArrayList<>();
    final int lastRexInput = lastColumnReferenced + 1;
    RexVisitorComplexExprSplitter exprSplitter = new RexVisitorComplexExprSplitter(funcReg, rexBuilder, lastRexInput);
    int i = 0;
    for (RexNode rex : newProject.getChildExps()) {
        RelDataTypeField originField = projectFields.get(i++);
        RexNode splitRex = rex.accept(exprSplitter);
        origRelDataTypes.add(originField);
        exprList.add(splitRex);
    }
    final List<RexNode> complexExprs = exprSplitter.getComplexExprs();
    if (complexExprs.size() == 1 && findTopComplexFunc(newProject.getChildExps()).size() == 1) {
        return newProject;
    }
    // if the projection expressions contained complex outputs, split them into their own individual projects
    if (complexExprs.size() > 0) {
        List<RexNode> allExprs = new ArrayList<>();
        int exprIndex = 0;
        List<String> fieldNames = newInput.getRowType().getFieldNames();
        List<RelDataTypeField> relDataTypes = new ArrayList<>();
        for (int index = 0; index < lastRexInput; index++) {
            allExprs.add(rexBuilder.makeInputRef(new RelDataTypeDrillImpl(new RelDataTypeHolder(), factory), index));
            if (fieldNames.get(index).contains(SchemaPath.DYNAMIC_STAR)) {
                relDataTypes.add(new RelDataTypeFieldImpl(fieldNames.get(index), allExprs.size(), factory.createSqlType(SqlTypeName.ANY)));
            } else {
                relDataTypes.add(new RelDataTypeFieldImpl(getExprName(exprIndex), allExprs.size(), factory.createSqlType(SqlTypeName.ANY)));
                exprIndex++;
            }
        }
        RexNode currRexNode;
        int index = lastRexInput - 1;
        while (complexExprs.size() > 0) {
            if (index >= lastRexInput) {
                RexInputRef newLastRex = rexBuilder.makeInputRef(new RelDataTypeDrillImpl(new RelDataTypeHolder(), factory), index);
                // replace last rex with new one
                allExprs.set(allExprs.size() - 1, newLastRex);
            }
            index++;
            exprIndex++;
            currRexNode = complexExprs.remove(0);
            allExprs.add(currRexNode);
            relDataTypes.add(new RelDataTypeFieldImpl(getExprName(exprIndex), allExprs.size(), factory.createSqlType(SqlTypeName.ANY)));
            RelRecordType childProjectType = new RelRecordType(relDataTypes);
            ProjectPrel childProject = new ProjectPrel(newProject.getCluster(), newProject.getTraitSet(), newInput, ImmutableList.copyOf(allExprs), childProjectType);
            newInput = childProject;
        }
        allExprs.set(allExprs.size() - 1, rexBuilder.makeInputRef(new RelDataTypeDrillImpl(new RelDataTypeHolder(), factory), index));
        relDataTypes.add(new RelDataTypeFieldImpl(getExprName(exprIndex), allExprs.size(), factory.createSqlType(SqlTypeName.ANY)));
    }
    return (Prel) project.copy(project.getTraitSet(), newInput, exprList, new RelRecordType(origRelDataTypes));
}

15 View Complete Implementation : ElasticSourceNameFinder.java
Copyright Apache License 2.0
Author : dremio
@Override
public List<List<String>> visitInputRef(RexInputRef inputRef) {
    final int index = inputRef.getIndex();
    final RelDataTypeField field = rowType.getFieldList().get(index);
    return Lists.<List<String>>newArrayList(Lists.newArrayList(field.getName()));
}

15 View Complete Implementation : RelStructuredTypeFlattener.java
Copyright Apache License 2.0
Author : lealone
private RexNode restructure(RelDataType structuredType) {
    // Access null indicator for entire structure.
    RexInputRef nullIndicator = RexInputRef.of(iRestructureInput++, flattenedRootType.getFieldList());
    // Use NEW to put flattened data back together into a structure.
    List<RexNode> inputExprs = restructureFields(structuredType);
    RexNode newInvocation = rexBuilder.makeNewInvocation(structuredType, inputExprs);
    if (!structuredType.isNullable()) {
        // Optimize away the null test.
        return newInvocation;
    }
    // Construct a CASE expression to handle the structure-level null
    // indicator.
    RexNode[] caseOperands = new RexNode[3];
    // WHEN StructuredType.Indicator IS NULL
    caseOperands[0] = rexBuilder.makeCall(SqlStdOperatorTable.IS_NULL, nullIndicator);
    // THEN CAST(NULL AS StructuredType)
    caseOperands[1] = rexBuilder.makeCast(structuredType, rexBuilder.constantNull());
    // ELSE NEW StructuredType(inputs...) END
    caseOperands[2] = newInvocation;
    return rexBuilder.makeCall(SqlStdOperatorTable.CASE, caseOperands);
}

15 View Complete Implementation : RelToSqlConverter.java
Copyright Apache License 2.0
Author : qubole
/**
 * Convert {@link RexNode} condition into {@link SqlNode}
 *
 * @param node           condition Node
 * @param leftContext    LeftContext
 * @param rightContext   RightContext
 * @param leftFieldCount Number of field on left result
 * @return SqlJoin which represent the condition
 */
private SqlNode convertConditionToSqlNode(RexNode node, Context leftContext, Context rightContext, int leftFieldCount) {
    if (!(node instanceof RexCall)) {
        throw new replacedertionError(node);
    }
    final List<RexNode> operands;
    final SqlOperator op;
    switch(node.getKind()) {
        case AND:
        case OR:
            operands = ((RexCall) node).getOperands();
            op = ((RexCall) node).getOperator();
            SqlNode sqlCondition = null;
            for (RexNode operand : operands) {
                SqlNode x = convertConditionToSqlNode(operand, leftContext, rightContext, leftFieldCount);
                if (sqlCondition == null) {
                    sqlCondition = x;
                } else {
                    sqlCondition = op.createCall(POS, sqlCondition, x);
                }
            }
            return sqlCondition;
        case EQUALS:
        case IS_NOT_DISTINCT_FROM:
        case NOT_EQUALS:
        case GREATER_THAN:
        case GREATER_THAN_OR_EQUAL:
        case LESS_THAN:
        case LESS_THAN_OR_EQUAL:
            operands = ((RexCall) node).getOperands();
            op = ((RexCall) node).getOperator();
            if (operands.get(0) instanceof RexInputRef && operands.get(1) instanceof RexInputRef) {
                final RexInputRef op0 = (RexInputRef) operands.get(0);
                final RexInputRef op1 = (RexInputRef) operands.get(1);
                if (op0.getIndex() < leftFieldCount && op1.getIndex() >= leftFieldCount) {
                    // Arguments were of form 'op0 = op1'
                    return op.createCall(POS, leftContext.field(op0.getIndex()), rightContext.field(op1.getIndex() - leftFieldCount));
                }
                if (op1.getIndex() < leftFieldCount && op0.getIndex() >= leftFieldCount) {
                    // Arguments were of form 'op1 = op0'
                    return reverseOperatorDirection(op).createCall(POS, leftContext.field(op1.getIndex()), rightContext.field(op0.getIndex() - leftFieldCount));
                }
            }
    }
    throw new replacedertionError(node);
}

14 View Complete Implementation : RelOptUtilTest.java
Copyright Apache License 2.0
Author : apache
/**
 * Test {@link RelOptUtil#splitJoinCondition(RelNode, RelNode, RexNode, List, List, List)}
 * where the join condition contains an expanded version of IS NOT DISTINCT
 */
@Test
public void testSplitJoinConditionExpandedIsNotDistinctFrom() {
    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 = relBuilder.call(SqlStdOperatorTable.OR, relBuilder.call(SqlStdOperatorTable.EQUALS, leftKeyInputRef, rightKeyInputRef), relBuilder.call(SqlStdOperatorTable.AND, relBuilder.call(SqlStdOperatorTable.IS_NULL, leftKeyInputRef), relBuilder.call(SqlStdOperatorTable.IS_NULL, rightKeyInputRef)));
    splitJoinConditionHelper(joinCond, Collections.singletonList(leftJoinIndex), Collections.singletonList(rightJoinIndex), Collections.singletonList(false), relBuilder.literal(true));
}

14 View Complete Implementation : IndexPlanUtils.java
Copyright Apache License 2.0
Author : apache
/**
 * Build collation property for the 'upper' project, the one above the filter
 * @param projectRexs
 * @param inputCollation
 * @param indexInfo
 * @param collationFilterMap
 * @return the output RelCollation
 */
public static RelCollation buildCollationUpperProject(List<RexNode> projectRexs, RelCollation inputCollation, FunctionalIndexInfo indexInfo, Map<Integer, List<RexNode>> collationFilterMap) {
    List<RelFieldCollation> outputFieldCollations = Lists.newArrayList();
    if (inputCollation != null) {
        List<RelFieldCollation> inputFieldCollations = inputCollation.getFieldCollations();
        if (!indexInfo.hasFunctional()) {
            for (int projectExprIdx = 0; projectExprIdx < projectRexs.size(); projectExprIdx++) {
                RexNode n = projectRexs.get(projectExprIdx);
                if (n instanceof RexInputRef) {
                    RexInputRef ref = (RexInputRef) n;
                    boolean eligibleForCollation = true;
                    int maxIndex = getIndexFromCollation(ref.getIndex(), inputFieldCollations);
                    if (maxIndex < 0) {
                        eligibleForCollation = false;
                        continue;
                    }
                    // check if the prefix has equality conditions
                    for (int i = 0; i < maxIndex; i++) {
                        int fieldIdx = inputFieldCollations.get(i).getFieldIndex();
                        List<RexNode> conditions = collationFilterMap != null ? collationFilterMap.get(fieldIdx) : null;
                        if ((conditions == null || conditions.size() == 0) && i < maxIndex - 1) {
                            // if an intermediate column has no filter condition, it would select all values
                            // of that column, so a subsequent column cannot be eligible for collation
                            eligibleForCollation = false;
                            break;
                        } else {
                            for (RexNode r : conditions) {
                                if (!(r.getKind() == SqlKind.EQUALS)) {
                                    eligibleForCollation = false;
                                    break;
                                }
                            }
                        }
                    }
                    // for every projected expr, if it is eligible for collation, get the
                    // corresponding field collation from the input
                    if (eligibleForCollation) {
                        for (RelFieldCollation c : inputFieldCollations) {
                            if (ref.getIndex() == c.getFieldIndex()) {
                                RelFieldCollation outFieldCollation = new RelFieldCollation(projectExprIdx, c.getDirection(), c.nullDirection);
                                outputFieldCollations.add(outFieldCollation);
                            }
                        }
                    }
                }
            }
        } else {
        // TODO: handle functional index
        }
    }
    return RelCollations.of(outputFieldCollations);
}

14 View Complete Implementation : DrillFilterItemStarReWriterRule.java
Copyright Apache License 2.0
Author : apache
/**
 * Removes item star call from filter expression and propagates changes into project (if present) and scan.
 *
 * @param filterRel original filter expression
 * @param projectRel original project expression
 * @param scanRel original scan expression
 * @param call original rule call
 */
private static void transformFilterCall(DrillFilterRel filterRel, DrillProjectRel projectRel, DrillScanRel scanRel, RelOptRuleCall call) {
    List<String> fieldNames = projectRel == null ? scanRel.getRowType().getFieldNames() : projectRel.getRowType().getFieldNames();
    ItemStarFieldsVisitor itemStarFieldsVisitor = new ItemStarFieldsVisitor(fieldNames);
    filterRel.getCondition().accept(itemStarFieldsVisitor);
    // if there are no item fields, no need to proceed further
    if (itemStarFieldsVisitor.hasNoItemStarFields()) {
        return;
    }
    Map<String, DesiredField> itemStarFields = itemStarFieldsVisitor.gereplacedemStarFields();
    DrillScanRel newScan = createNewScan(scanRel, itemStarFields);
    // create new project if was present in call
    DrillProjectRel newProject = null;
    if (projectRel != null) {
        // add new projects to the already existing in original project
        int projectIndex = scanRel.getRowType().getFieldCount();
        List<RexNode> newProjects = new ArrayList<>(projectRel.getProjects());
        for (DesiredField desiredField : itemStarFields.values()) {
            newProjects.add(new RexInputRef(projectIndex, desiredField.getType()));
            projectIndex++;
        }
        RelDataType newProjectRowType = createNewRowType(projectRel.getCluster().getTypeFactory(), projectRel.getRowType().getFieldList(), itemStarFields.keySet());
        newProject = new DrillProjectRel(projectRel.getCluster(), projectRel.getTraitSet(), newScan, newProjects, newProjectRowType);
    }
    // transform filter condition
    Map<RexNode, Integer> fieldMapper = createFieldMapper(itemStarFields.values(), scanRel.getRowType().getFieldCount());
    FieldsReWriter fieldsReWriter = new FieldsReWriter(fieldMapper);
    RexNode newCondition = filterRel.getCondition().accept(fieldsReWriter);
    // create new filter
    DrillFilterRel newFilter = DrillFilterRel.create(newProject != null ? newProject : newScan, newCondition);
    // wrap with project to have the same row type as before
    List<RexNode> newProjects = new ArrayList<>();
    RelDataType rowType = filterRel.getRowType();
    List<RelDataTypeField> fieldList = rowType.getFieldList();
    for (RelDataTypeField field : fieldList) {
        RexInputRef inputRef = new RexInputRef(field.getIndex(), field.getType());
        newProjects.add(inputRef);
    }
    DrillProjectRel wrapper = new DrillProjectRel(filterRel.getCluster(), filterRel.getTraitSet(), newFilter, newProjects, filterRel.getRowType());
    call.transformTo(wrapper);
}

14 View Complete Implementation : OperatorConversions.java
Copyright Apache License 2.0
Author : apache
/**
 * Translate a Calcite {@code RexNode} to a Druid PostAggregator
 *
 * @param plannerContext SQL planner context
 * @param rowSignature   signature of the rows to be extracted from
 * @param rexNode        expression meant to be applied on top of the rows
 *
 * @param postAggregatorVisitor visitor that manages postagg names and tracks postaggs that were created
 *                              by the translation
 * @return rexNode referring to fields in rowOrder, or null if not possible
 */
@Nullable
public static PostAggregator toPostAggregator(final PlannerContext plannerContext, final RowSignature rowSignature, final RexNode rexNode, final PostAggregatorVisitor postAggregatorVisitor) {
    final SqlKind kind = rexNode.getKind();
    if (kind == SqlKind.INPUT_REF) {
        // Translate field references.
        final RexInputRef ref = (RexInputRef) rexNode;
        final String columnName = rowSignature.getRowOrder().get(ref.getIndex());
        if (columnName == null) {
            throw new ISE("WTF?! PostAgg referred to nonexistent index[%d]", ref.getIndex());
        }
        return new FieldAccessPostAggregator(postAggregatorVisitor.getOutputNamePrefix() + postAggregatorVisitor.getAndIncrementCounter(), columnName);
    } else if (rexNode instanceof RexCall) {
        final SqlOperator operator = ((RexCall) rexNode).getOperator();
        final SqlOperatorConversion conversion = plannerContext.getOperatorTable().lookupOperatorConversion(operator);
        if (conversion == null) {
            return null;
        } else {
            return conversion.toPostAggregator(plannerContext, rowSignature, rexNode, postAggregatorVisitor);
        }
    } else if (kind == SqlKind.LITERAL) {
        return null;
    } else {
        throw new IAE("Unknown rexnode kind: " + kind);
    }
}

14 View Complete Implementation : DruidQuery.java
Copyright Apache License 2.0
Author : apache
@Nonnull
private static Sorting computeSorting(final PartialDruidQuery partialQuery, final PlannerContext plannerContext, final RowSignature rowSignature, @Nullable final VirtualColumnRegistry virtualColumnRegistry) {
    final Sort sort = Preconditions.checkNotNull(partialQuery.getSort(), "sort");
    final Project sortProject = partialQuery.getSortProject();
    // Extract limit.
    final Long limit = sort.fetch != null ? ((Number) RexLiteral.value(sort.fetch)).longValue() : null;
    final List<OrderByColumnSpec> orderBys = new ArrayList<>(sort.getChildExps().size());
    if (sort.offset != null) {
        // Druid cannot currently handle LIMIT with OFFSET.
        throw new CannotBuildQueryException(sort);
    }
    // Extract orderBy column specs.
    for (int sortKey = 0; sortKey < sort.getChildExps().size(); sortKey++) {
        final RexNode sortExpression = sort.getChildExps().get(sortKey);
        final RelFieldCollation collation = sort.getCollation().getFieldCollations().get(sortKey);
        final OrderByColumnSpec.Direction direction;
        final StringComparator comparator;
        if (collation.getDirection() == RelFieldCollation.Direction.ASCENDING) {
            direction = OrderByColumnSpec.Direction.ASCENDING;
        } else if (collation.getDirection() == RelFieldCollation.Direction.DESCENDING) {
            direction = OrderByColumnSpec.Direction.DESCENDING;
        } else {
            throw new ISE("WTF?! Don't know what to do with direction[%s]", collation.getDirection());
        }
        final SqlTypeName sortExpressionType = sortExpression.getType().getSqlTypeName();
        if (SqlTypeName.NUMERIC_TYPES.contains(sortExpressionType) || SqlTypeName.TIMESTAMP == sortExpressionType || SqlTypeName.DATE == sortExpressionType) {
            comparator = StringComparators.NUMERIC;
        } else {
            comparator = StringComparators.LEXICOGRAPHIC;
        }
        if (sortExpression.isA(SqlKind.INPUT_REF)) {
            final RexInputRef ref = (RexInputRef) sortExpression;
            final String fieldName = rowSignature.getRowOrder().get(ref.getIndex());
            orderBys.add(new OrderByColumnSpec(fieldName, direction, comparator));
        } else {
            // We don't support sorting by anything other than refs which actually appear in the query result.
            throw new CannotBuildQueryException(sort, sortExpression);
        }
    }
    // Extract any post-sort Projection.
    final Projection projection;
    if (sortProject == null) {
        projection = null;
    } else if (partialQuery.getAggregate() == null) {
        if (virtualColumnRegistry == null) {
            throw new ISE("Must provide 'virtualColumnRegistry' for pre-aggregation Projection!");
        }
        projection = Projection.preAggregation(sortProject, plannerContext, rowSignature, virtualColumnRegistry);
    } else {
        projection = Projection.postAggregation(sortProject, plannerContext, rowSignature, "s");
    }
    return Sorting.create(orderBys, limit, projection);
}