Search in sources :

Example 6 with SqlTypeName

use of org.apache.calcite.sql.type.SqlTypeName in project druid by druid-io.

the class Expressions method toMathExpression.

/**
   * Translate a row-expression to a Druid math expression. One day, when possible, this could be folded into
   * {@link #toRowExtraction(DruidOperatorTable, PlannerContext, List, RexNode)}.
   *
   * @param rowOrder   order of fields in the Druid rows to be extracted from
   * @param expression expression meant to be applied on top of the rows
   *
   * @return expression referring to fields in rowOrder, or null if not possible
   */
public static String toMathExpression(final List<String> rowOrder, final RexNode expression) {
    final SqlKind kind = expression.getKind();
    final SqlTypeName sqlTypeName = expression.getType().getSqlTypeName();
    if (kind == SqlKind.INPUT_REF) {
        // Translate field references.
        final RexInputRef ref = (RexInputRef) expression;
        final String columnName = rowOrder.get(ref.getIndex());
        if (columnName == null) {
            throw new ISE("WTF?! Expression referred to nonexistent index[%d]", ref.getIndex());
        }
        return String.format("\"%s\"", escape(columnName));
    } else if (kind == SqlKind.CAST || kind == SqlKind.REINTERPRET) {
        // Translate casts.
        final RexNode operand = ((RexCall) expression).getOperands().get(0);
        final String operandExpression = toMathExpression(rowOrder, operand);
        if (operandExpression == null) {
            return null;
        }
        final ExprType fromType = MATH_TYPES.get(operand.getType().getSqlTypeName());
        final ExprType toType = MATH_TYPES.get(sqlTypeName);
        if (fromType != toType) {
            return String.format("CAST(%s, '%s')", operandExpression, toType.toString());
        } else {
            return operandExpression;
        }
    } else if (kind == SqlKind.TIMES || kind == SqlKind.DIVIDE || kind == SqlKind.PLUS || kind == SqlKind.MINUS) {
        // Translate simple arithmetic.
        final List<RexNode> operands = ((RexCall) expression).getOperands();
        final String lhsExpression = toMathExpression(rowOrder, operands.get(0));
        final String rhsExpression = toMathExpression(rowOrder, operands.get(1));
        if (lhsExpression == null || rhsExpression == null) {
            return null;
        }
        final String op = ImmutableMap.of(SqlKind.TIMES, "*", SqlKind.DIVIDE, "/", SqlKind.PLUS, "+", SqlKind.MINUS, "-").get(kind);
        return String.format("(%s %s %s)", lhsExpression, op, rhsExpression);
    } else if (kind == SqlKind.OTHER_FUNCTION) {
        final String calciteFunction = ((RexCall) expression).getOperator().getName();
        final String druidFunction = MATH_FUNCTIONS.get(calciteFunction);
        final List<String> functionArgs = Lists.newArrayList();
        for (final RexNode operand : ((RexCall) expression).getOperands()) {
            final String operandExpression = toMathExpression(rowOrder, operand);
            if (operandExpression == null) {
                return null;
            }
            functionArgs.add(operandExpression);
        }
        if ("MOD".equals(calciteFunction)) {
            // Special handling for MOD, which is a function in Calcite but a binary operator in Druid.
            Preconditions.checkState(functionArgs.size() == 2, "WTF?! Expected 2 args for MOD.");
            return String.format("(%s %s %s)", functionArgs.get(0), "%", functionArgs.get(1));
        }
        if (druidFunction == null) {
            return null;
        }
        return String.format("%s(%s)", druidFunction, Joiner.on(", ").join(functionArgs));
    } else if (kind == SqlKind.LITERAL) {
        // Translate literal.
        if (SqlTypeName.NUMERIC_TYPES.contains(sqlTypeName)) {
            // Include literal numbers as-is.
            return String.valueOf(RexLiteral.value(expression));
        } else if (SqlTypeName.STRING_TYPES.contains(sqlTypeName)) {
            // Quote literal strings.
            return "\'" + escape(RexLiteral.stringValue(expression)) + "\'";
        } else {
            // Can't translate other literals.
            return null;
        }
    } else {
        // Can't translate other kinds of expressions.
        return null;
    }
}
Also used : RexCall(org.apache.calcite.rex.RexCall) SqlTypeName(org.apache.calcite.sql.type.SqlTypeName) ExprType(io.druid.math.expr.ExprType) RexInputRef(org.apache.calcite.rex.RexInputRef) ISE(io.druid.java.util.common.ISE) List(java.util.List) SqlKind(org.apache.calcite.sql.SqlKind) RexNode(org.apache.calcite.rex.RexNode)

Example 7 with SqlTypeName

use of org.apache.calcite.sql.type.SqlTypeName in project druid by druid-io.

the class Expressions method toMillisLiteral.

/**
   * Translates "literal" (a TIMESTAMP or DATE literal) to milliseconds since the epoch using the provided
   * session time zone.
   *
   * @param literal  TIMESTAMP or DATE literal
   * @param timeZone session time zone
   *
   * @return milliseconds time
   */
public static long toMillisLiteral(final RexNode literal, final DateTimeZone timeZone) {
    final SqlTypeName typeName = literal.getType().getSqlTypeName();
    if (literal.getKind() != SqlKind.LITERAL || (typeName != SqlTypeName.TIMESTAMP && typeName != SqlTypeName.DATE)) {
        throw new IAE("Expected TIMESTAMP or DATE literal but got[%s:%s]", literal.getKind(), typeName);
    }
    final Calendar calendar = (Calendar) RexLiteral.value(literal);
    return Calcites.calciteTimestampToJoda(calendar.getTimeInMillis(), timeZone).getMillis();
}
Also used : SqlTypeName(org.apache.calcite.sql.type.SqlTypeName) Calendar(java.util.Calendar) IAE(io.druid.java.util.common.IAE)

Example 8 with SqlTypeName

use of org.apache.calcite.sql.type.SqlTypeName in project drill by apache.

the class DrillConstExecutor method reduce.

@Override
public void reduce(final RexBuilder rexBuilder, List<RexNode> constExps, final List<RexNode> reducedValues) {
    for (final RexNode newCall : constExps) {
        LogicalExpression logEx = DrillOptiq.toDrill(new DrillParseContext(plannerSettings), (RelNode) null, /* input rel */
        newCall);
        ErrorCollectorImpl errors = new ErrorCollectorImpl();
        final LogicalExpression materializedExpr = ExpressionTreeMaterializer.materialize(logEx, null, errors, funcImplReg);
        if (errors.getErrorCount() != 0) {
            String message = String.format("Failure while materializing expression in constant expression evaluator [%s].  Errors: %s", newCall.toString(), errors.toString());
            throw UserException.planError().message(message).build(logger);
        }
        if (NON_REDUCIBLE_TYPES.contains(materializedExpr.getMajorType().getMinorType())) {
            logger.debug("Constant expression not folded due to return type {}, complete expression: {}", materializedExpr.getMajorType(), ExpressionStringBuilder.toString(materializedExpr));
            reducedValues.add(newCall);
            continue;
        }
        ValueHolder output = InterpreterEvaluator.evaluateConstantExpr(udfUtilities, materializedExpr);
        final RelDataTypeFactory typeFactory = rexBuilder.getTypeFactory();
        if (materializedExpr.getMajorType().getMode() == TypeProtos.DataMode.OPTIONAL && TypeHelper.isNull(output)) {
            SqlTypeName sqlTypeName = TypeInferenceUtils.getCalciteTypeFromDrillType(materializedExpr.getMajorType().getMinorType());
            if (sqlTypeName == null) {
                String message = String.format("Error reducing constant expression, unsupported type: %s.", materializedExpr.getMajorType().getMinorType());
                throw UserException.unsupportedError().message(message).build(logger);
            }
            reducedValues.add(rexBuilder.makeNullLiteral(sqlTypeName));
            continue;
        }
        Function<ValueHolder, RexNode> literator = new Function<ValueHolder, RexNode>() {

            @Override
            public RexNode apply(ValueHolder output) {
                switch(materializedExpr.getMajorType().getMinorType()) {
                    case INT:
                        {
                            int value = (materializedExpr.getMajorType().getMode() == TypeProtos.DataMode.OPTIONAL) ? ((NullableIntHolder) output).value : ((IntHolder) output).value;
                            return rexBuilder.makeLiteral(new BigDecimal(value), TypeInferenceUtils.createCalciteTypeWithNullability(typeFactory, SqlTypeName.INTEGER, newCall.getType().isNullable()), false);
                        }
                    case BIGINT:
                        {
                            long value = (materializedExpr.getMajorType().getMode() == TypeProtos.DataMode.OPTIONAL) ? ((NullableBigIntHolder) output).value : ((BigIntHolder) output).value;
                            return rexBuilder.makeLiteral(new BigDecimal(value), TypeInferenceUtils.createCalciteTypeWithNullability(typeFactory, SqlTypeName.BIGINT, newCall.getType().isNullable()), false);
                        }
                    case FLOAT4:
                        {
                            float value = (materializedExpr.getMajorType().getMode() == TypeProtos.DataMode.OPTIONAL) ? ((NullableFloat4Holder) output).value : ((Float4Holder) output).value;
                            return rexBuilder.makeLiteral(new BigDecimal(value), TypeInferenceUtils.createCalciteTypeWithNullability(typeFactory, SqlTypeName.FLOAT, newCall.getType().isNullable()), false);
                        }
                    case FLOAT8:
                        {
                            double value = (materializedExpr.getMajorType().getMode() == TypeProtos.DataMode.OPTIONAL) ? ((NullableFloat8Holder) output).value : ((Float8Holder) output).value;
                            return rexBuilder.makeLiteral(new BigDecimal(value), TypeInferenceUtils.createCalciteTypeWithNullability(typeFactory, SqlTypeName.DOUBLE, newCall.getType().isNullable()), false);
                        }
                    case VARCHAR:
                        {
                            String value = (materializedExpr.getMajorType().getMode() == TypeProtos.DataMode.OPTIONAL) ? StringFunctionHelpers.getStringFromVarCharHolder((NullableVarCharHolder) output) : StringFunctionHelpers.getStringFromVarCharHolder((VarCharHolder) output);
                            return rexBuilder.makeLiteral(value, TypeInferenceUtils.createCalciteTypeWithNullability(typeFactory, SqlTypeName.VARCHAR, newCall.getType().isNullable()), false);
                        }
                    case BIT:
                        {
                            boolean value = (materializedExpr.getMajorType().getMode() == TypeProtos.DataMode.OPTIONAL) ? ((NullableBitHolder) output).value == 1 : ((BitHolder) output).value == 1;
                            return rexBuilder.makeLiteral(value, TypeInferenceUtils.createCalciteTypeWithNullability(typeFactory, SqlTypeName.BOOLEAN, newCall.getType().isNullable()), false);
                        }
                    case DATE:
                        {
                            Calendar value = (materializedExpr.getMajorType().getMode() == TypeProtos.DataMode.OPTIONAL) ? new DateTime(((NullableDateHolder) output).value, DateTimeZone.UTC).toCalendar(null) : new DateTime(((DateHolder) output).value, DateTimeZone.UTC).toCalendar(null);
                            return rexBuilder.makeLiteral(value, TypeInferenceUtils.createCalciteTypeWithNullability(typeFactory, SqlTypeName.DATE, newCall.getType().isNullable()), false);
                        }
                    case DECIMAL9:
                        {
                            long value;
                            int scale;
                            if (materializedExpr.getMajorType().getMode() == TypeProtos.DataMode.OPTIONAL) {
                                NullableDecimal9Holder decimal9Out = (NullableDecimal9Holder) output;
                                value = decimal9Out.value;
                                scale = decimal9Out.scale;
                            } else {
                                Decimal9Holder decimal9Out = (Decimal9Holder) output;
                                value = decimal9Out.value;
                                scale = decimal9Out.scale;
                            }
                            return rexBuilder.makeLiteral(new BigDecimal(BigInteger.valueOf(value), scale), TypeInferenceUtils.createCalciteTypeWithNullability(typeFactory, SqlTypeName.DECIMAL, newCall.getType().isNullable()), false);
                        }
                    case DECIMAL18:
                        {
                            long value;
                            int scale;
                            if (materializedExpr.getMajorType().getMode() == TypeProtos.DataMode.OPTIONAL) {
                                NullableDecimal18Holder decimal18Out = (NullableDecimal18Holder) output;
                                value = decimal18Out.value;
                                scale = decimal18Out.scale;
                            } else {
                                Decimal18Holder decimal18Out = (Decimal18Holder) output;
                                value = decimal18Out.value;
                                scale = decimal18Out.scale;
                            }
                            return rexBuilder.makeLiteral(new BigDecimal(BigInteger.valueOf(value), scale), TypeInferenceUtils.createCalciteTypeWithNullability(typeFactory, SqlTypeName.DECIMAL, newCall.getType().isNullable()), false);
                        }
                    case DECIMAL28SPARSE:
                        {
                            DrillBuf buffer;
                            int start;
                            int scale;
                            if (materializedExpr.getMajorType().getMode() == TypeProtos.DataMode.OPTIONAL) {
                                NullableDecimal28SparseHolder decimal28Out = (NullableDecimal28SparseHolder) output;
                                buffer = decimal28Out.buffer;
                                start = decimal28Out.start;
                                scale = decimal28Out.scale;
                            } else {
                                Decimal28SparseHolder decimal28Out = (Decimal28SparseHolder) output;
                                buffer = decimal28Out.buffer;
                                start = decimal28Out.start;
                                scale = decimal28Out.scale;
                            }
                            return rexBuilder.makeLiteral(org.apache.drill.exec.util.DecimalUtility.getBigDecimalFromSparse(buffer, start * 20, 5, scale), TypeInferenceUtils.createCalciteTypeWithNullability(typeFactory, SqlTypeName.DECIMAL, newCall.getType().isNullable()), false);
                        }
                    case DECIMAL38SPARSE:
                        {
                            DrillBuf buffer;
                            int start;
                            int scale;
                            if (materializedExpr.getMajorType().getMode() == TypeProtos.DataMode.OPTIONAL) {
                                NullableDecimal38SparseHolder decimal38Out = (NullableDecimal38SparseHolder) output;
                                buffer = decimal38Out.buffer;
                                start = decimal38Out.start;
                                scale = decimal38Out.scale;
                            } else {
                                Decimal38SparseHolder decimal38Out = (Decimal38SparseHolder) output;
                                buffer = decimal38Out.buffer;
                                start = decimal38Out.start;
                                scale = decimal38Out.scale;
                            }
                            return rexBuilder.makeLiteral(org.apache.drill.exec.util.DecimalUtility.getBigDecimalFromSparse(buffer, start * 24, 6, scale), TypeInferenceUtils.createCalciteTypeWithNullability(typeFactory, SqlTypeName.DECIMAL, newCall.getType().isNullable()), false);
                        }
                    case TIME:
                        {
                            Calendar value = (materializedExpr.getMajorType().getMode() == TypeProtos.DataMode.OPTIONAL) ? new DateTime(((NullableTimeHolder) output).value, DateTimeZone.UTC).toCalendar(null) : new DateTime(((TimeHolder) output).value, DateTimeZone.UTC).toCalendar(null);
                            return rexBuilder.makeLiteral(value, TypeInferenceUtils.createCalciteTypeWithNullability(typeFactory, SqlTypeName.TIME, newCall.getType().isNullable()), false);
                        }
                    case TIMESTAMP:
                        {
                            Calendar value = (materializedExpr.getMajorType().getMode() == TypeProtos.DataMode.OPTIONAL) ? new DateTime(((NullableTimeStampHolder) output).value, DateTimeZone.UTC).toCalendar(null) : new DateTime(((TimeStampHolder) output).value, DateTimeZone.UTC).toCalendar(null);
                            return rexBuilder.makeLiteral(value, TypeInferenceUtils.createCalciteTypeWithNullability(typeFactory, SqlTypeName.TIMESTAMP, newCall.getType().isNullable()), false);
                        }
                    case INTERVALYEAR:
                        {
                            BigDecimal value = (materializedExpr.getMajorType().getMode() == TypeProtos.DataMode.OPTIONAL) ? new BigDecimal(((NullableIntervalYearHolder) output).value) : new BigDecimal(((IntervalYearHolder) output).value);
                            return rexBuilder.makeLiteral(value, TypeInferenceUtils.createCalciteTypeWithNullability(typeFactory, SqlTypeName.INTERVAL_YEAR_MONTH, newCall.getType().isNullable()), false);
                        }
                    case INTERVALDAY:
                        {
                            int days;
                            int milliseconds;
                            if (materializedExpr.getMajorType().getMode() == TypeProtos.DataMode.OPTIONAL) {
                                NullableIntervalDayHolder intervalDayOut = (NullableIntervalDayHolder) output;
                                days = intervalDayOut.days;
                                milliseconds = intervalDayOut.milliseconds;
                            } else {
                                IntervalDayHolder intervalDayOut = (IntervalDayHolder) output;
                                days = intervalDayOut.days;
                                milliseconds = intervalDayOut.milliseconds;
                            }
                            return rexBuilder.makeLiteral(new BigDecimal(days * DateUtility.daysToStandardMillis + milliseconds), TypeInferenceUtils.createCalciteTypeWithNullability(typeFactory, SqlTypeName.INTERVAL_DAY_TIME, newCall.getType().isNullable()), false);
                        }
                    // as new types may be added in the future.
                    default:
                        logger.debug("Constant expression not folded due to return type {}, complete expression: {}", materializedExpr.getMajorType(), ExpressionStringBuilder.toString(materializedExpr));
                        return newCall;
                }
            }
        };
        reducedValues.add(literator.apply(output));
    }
}
Also used : SqlTypeName(org.apache.calcite.sql.type.SqlTypeName) NullableFloat8Holder(org.apache.drill.exec.expr.holders.NullableFloat8Holder) NullableDecimal9Holder(org.apache.drill.exec.expr.holders.NullableDecimal9Holder) NullableFloat4Holder(org.apache.drill.exec.expr.holders.NullableFloat4Holder) Float4Holder(org.apache.drill.exec.expr.holders.Float4Holder) Decimal9Holder(org.apache.drill.exec.expr.holders.Decimal9Holder) NullableDecimal9Holder(org.apache.drill.exec.expr.holders.NullableDecimal9Holder) DateTime(org.joda.time.DateTime) ErrorCollectorImpl(org.apache.drill.common.expression.ErrorCollectorImpl) LogicalExpression(org.apache.drill.common.expression.LogicalExpression) Function(com.google.common.base.Function) BigIntHolder(org.apache.drill.exec.expr.holders.BigIntHolder) NullableBigIntHolder(org.apache.drill.exec.expr.holders.NullableBigIntHolder) NullableTimeStampHolder(org.apache.drill.exec.expr.holders.NullableTimeStampHolder) TimeStampHolder(org.apache.drill.exec.expr.holders.TimeStampHolder) NullableIntHolder(org.apache.drill.exec.expr.holders.NullableIntHolder) RelDataTypeFactory(org.apache.calcite.rel.type.RelDataTypeFactory) BigIntHolder(org.apache.drill.exec.expr.holders.BigIntHolder) NullableBigIntHolder(org.apache.drill.exec.expr.holders.NullableBigIntHolder) IntHolder(org.apache.drill.exec.expr.holders.IntHolder) NullableIntHolder(org.apache.drill.exec.expr.holders.NullableIntHolder) NullableDateHolder(org.apache.drill.exec.expr.holders.NullableDateHolder) DrillBuf(io.netty.buffer.DrillBuf) NullableTimeStampHolder(org.apache.drill.exec.expr.holders.NullableTimeStampHolder) NullableIntervalDayHolder(org.apache.drill.exec.expr.holders.NullableIntervalDayHolder) Decimal18Holder(org.apache.drill.exec.expr.holders.Decimal18Holder) NullableDecimal18Holder(org.apache.drill.exec.expr.holders.NullableDecimal18Holder) DateHolder(org.apache.drill.exec.expr.holders.DateHolder) NullableDateHolder(org.apache.drill.exec.expr.holders.NullableDateHolder) NullableTimeHolder(org.apache.drill.exec.expr.holders.NullableTimeHolder) NullableIntervalDayHolder(org.apache.drill.exec.expr.holders.NullableIntervalDayHolder) IntervalDayHolder(org.apache.drill.exec.expr.holders.IntervalDayHolder) Calendar(java.util.Calendar) NullableDecimal38SparseHolder(org.apache.drill.exec.expr.holders.NullableDecimal38SparseHolder) ValueHolder(org.apache.drill.exec.expr.holders.ValueHolder) NullableFloat8Holder(org.apache.drill.exec.expr.holders.NullableFloat8Holder) Float8Holder(org.apache.drill.exec.expr.holders.Float8Holder) BigDecimal(java.math.BigDecimal) NullableDecimal28SparseHolder(org.apache.drill.exec.expr.holders.NullableDecimal28SparseHolder) NullableBigIntHolder(org.apache.drill.exec.expr.holders.NullableBigIntHolder) NullableDecimal18Holder(org.apache.drill.exec.expr.holders.NullableDecimal18Holder) Decimal38SparseHolder(org.apache.drill.exec.expr.holders.Decimal38SparseHolder) NullableDecimal38SparseHolder(org.apache.drill.exec.expr.holders.NullableDecimal38SparseHolder) TimeHolder(org.apache.drill.exec.expr.holders.TimeHolder) NullableTimeHolder(org.apache.drill.exec.expr.holders.NullableTimeHolder) NullableFloat4Holder(org.apache.drill.exec.expr.holders.NullableFloat4Holder) Decimal28SparseHolder(org.apache.drill.exec.expr.holders.Decimal28SparseHolder) NullableDecimal28SparseHolder(org.apache.drill.exec.expr.holders.NullableDecimal28SparseHolder) RexNode(org.apache.calcite.rex.RexNode)

Example 9 with SqlTypeName

use of org.apache.calcite.sql.type.SqlTypeName in project druid by druid-io.

the class GroupByRules method toLimitSpec.

public static DefaultLimitSpec toLimitSpec(final List<String> rowOrder, final Sort sort) {
    final Integer limit = sort.fetch != null ? RexLiteral.intValue(sort.fetch) : null;
    final List<OrderByColumnSpec> orderBys = Lists.newArrayListWithCapacity(sort.getChildExps().size());
    if (sort.offset != null) {
        // LimitSpecs don't accept offsets.
        return null;
    }
    // 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 = rowOrder.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.
            return null;
        }
    }
    return new DefaultLimitSpec(orderBys, limit);
}
Also used : SqlTypeName(org.apache.calcite.sql.type.SqlTypeName) DefaultLimitSpec(io.druid.query.groupby.orderby.DefaultLimitSpec) StringComparator(io.druid.query.ordering.StringComparator) OrderByColumnSpec(io.druid.query.groupby.orderby.OrderByColumnSpec) RelFieldCollation(org.apache.calcite.rel.RelFieldCollation) RexInputRef(org.apache.calcite.rex.RexInputRef) ISE(io.druid.java.util.common.ISE) RexNode(org.apache.calcite.rex.RexNode)

Example 10 with SqlTypeName

use of org.apache.calcite.sql.type.SqlTypeName in project druid by druid-io.

the class GroupByRules method applyAggregate.

/**
   * Applies a filter -> project -> aggregate chain to a druidRel. Do not call this method unless
   * {@link #canApplyAggregate(DruidRel, Filter, Project, Aggregate)} returns true.
   *
   * @return new rel, or null if the chain cannot be applied
   */
private static DruidRel applyAggregate(final DruidRel druidRel, final Filter filter0, final Project project0, final Aggregate aggregate, final DruidOperatorTable operatorTable, final boolean approximateCountDistinct) {
    Preconditions.checkState(canApplyAggregate(druidRel, filter0, project0, aggregate), "Cannot applyAggregate.");
    final RowSignature sourceRowSignature;
    final boolean isNestedQuery = druidRel.getQueryBuilder().getGrouping() != null;
    if (isNestedQuery) {
        // Nested groupBy; source row signature is the output signature of druidRel.
        sourceRowSignature = druidRel.getOutputRowSignature();
    } else {
        sourceRowSignature = druidRel.getSourceRowSignature();
    }
    // Filter that should be applied before aggregating.
    final DimFilter filter;
    if (filter0 != null) {
        filter = Expressions.toFilter(operatorTable, druidRel.getPlannerContext(), sourceRowSignature, filter0.getCondition());
        if (filter == null) {
            // Can't plan this filter.
            return null;
        }
    } else if (druidRel.getQueryBuilder().getFilter() != null && !isNestedQuery) {
        // We're going to replace the existing druidRel, so inherit its filter.
        filter = druidRel.getQueryBuilder().getFilter();
    } else {
        filter = null;
    }
    // Projection that should be applied before aggregating.
    final Project project;
    if (project0 != null) {
        project = project0;
    } else if (druidRel.getQueryBuilder().getSelectProjection() != null && !isNestedQuery) {
        // We're going to replace the existing druidRel, so inherit its projection.
        project = druidRel.getQueryBuilder().getSelectProjection().getProject();
    } else {
        project = null;
    }
    final List<DimensionSpec> dimensions = Lists.newArrayList();
    final List<Aggregation> aggregations = Lists.newArrayList();
    final List<String> rowOrder = Lists.newArrayList();
    // Translate groupSet.
    final ImmutableBitSet groupSet = aggregate.getGroupSet();
    int dimOutputNameCounter = 0;
    for (int i : groupSet) {
        if (project != null && project.getChildExps().get(i) instanceof RexLiteral) {
            // Ignore literals in GROUP BY, so a user can write e.g. "GROUP BY 'dummy'" to group everything into a single
            // row. Add dummy rowOrder entry so NULLs come out. This is not strictly correct but it works as long as
            // nobody actually expects to see the literal.
            rowOrder.add(dimOutputName(dimOutputNameCounter++));
        } else {
            final RexNode rexNode = Expressions.fromFieldAccess(sourceRowSignature, project, i);
            final RowExtraction rex = Expressions.toRowExtraction(operatorTable, druidRel.getPlannerContext(), sourceRowSignature.getRowOrder(), rexNode);
            if (rex == null) {
                return null;
            }
            final SqlTypeName sqlTypeName = rexNode.getType().getSqlTypeName();
            final ValueType outputType = Calcites.getValueTypeForSqlTypeName(sqlTypeName);
            if (outputType == null) {
                throw new ISE("Cannot translate sqlTypeName[%s] to Druid type for field[%s]", sqlTypeName, rowOrder.get(i));
            }
            final DimensionSpec dimensionSpec = rex.toDimensionSpec(sourceRowSignature, dimOutputName(dimOutputNameCounter++), outputType);
            if (dimensionSpec == null) {
                return null;
            }
            dimensions.add(dimensionSpec);
            rowOrder.add(dimensionSpec.getOutputName());
        }
    }
    // Translate aggregates.
    for (int i = 0; i < aggregate.getAggCallList().size(); i++) {
        final AggregateCall aggCall = aggregate.getAggCallList().get(i);
        final Aggregation aggregation = translateAggregateCall(druidRel.getPlannerContext(), sourceRowSignature, project, aggCall, operatorTable, aggregations, i, approximateCountDistinct);
        if (aggregation == null) {
            return null;
        }
        aggregations.add(aggregation);
        rowOrder.add(aggregation.getOutputName());
    }
    if (isNestedQuery) {
        // Nested groupBy.
        return DruidNestedGroupBy.from(druidRel, filter, Grouping.create(dimensions, aggregations), aggregate.getRowType(), rowOrder);
    } else {
        // groupBy on a base dataSource.
        return druidRel.withQueryBuilder(druidRel.getQueryBuilder().withFilter(filter).withGrouping(Grouping.create(dimensions, aggregations), aggregate.getRowType(), rowOrder));
    }
}
Also used : DimensionSpec(io.druid.query.dimension.DimensionSpec) RexLiteral(org.apache.calcite.rex.RexLiteral) ImmutableBitSet(org.apache.calcite.util.ImmutableBitSet) SqlTypeName(org.apache.calcite.sql.type.SqlTypeName) ValueType(io.druid.segment.column.ValueType) RowExtraction(io.druid.sql.calcite.expression.RowExtraction) Aggregation(io.druid.sql.calcite.aggregation.Aggregation) AggregateCall(org.apache.calcite.rel.core.AggregateCall) Project(org.apache.calcite.rel.core.Project) ISE(io.druid.java.util.common.ISE) RowSignature(io.druid.sql.calcite.table.RowSignature) DimFilter(io.druid.query.filter.DimFilter) NotDimFilter(io.druid.query.filter.NotDimFilter) AndDimFilter(io.druid.query.filter.AndDimFilter) RexNode(org.apache.calcite.rex.RexNode)

Aggregations

SqlTypeName (org.apache.calcite.sql.type.SqlTypeName)13 ISE (io.druid.java.util.common.ISE)6 RexNode (org.apache.calcite.rex.RexNode)6 BigDecimal (java.math.BigDecimal)3 AggregatorFactory (io.druid.query.aggregation.AggregatorFactory)2 DimensionSpec (io.druid.query.dimension.DimensionSpec)2 AndDimFilter (io.druid.query.filter.AndDimFilter)2 DimFilter (io.druid.query.filter.DimFilter)2 NotDimFilter (io.druid.query.filter.NotDimFilter)2 ValueType (io.druid.segment.column.ValueType)2 Aggregation (io.druid.sql.calcite.aggregation.Aggregation)2 RowExtraction (io.druid.sql.calcite.expression.RowExtraction)2 Calendar (java.util.Calendar)2 RexCall (org.apache.calcite.rex.RexCall)2 SqlKind (org.apache.calcite.sql.SqlKind)2 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)1 Function (com.google.common.base.Function)1 IAE (io.druid.java.util.common.IAE)1 ExprType (io.druid.math.expr.ExprType)1 QueryInterruptedException (io.druid.query.QueryInterruptedException)1