Search in sources :

Example 1 with ExprType

use of org.apache.druid.math.expr.ExprType in project druid by druid-io.

the class CastOperatorConversion method toDruidExpression.

@Override
public DruidExpression toDruidExpression(final PlannerContext plannerContext, final RowSignature rowSignature, final RexNode rexNode) {
    final RexNode operand = ((RexCall) rexNode).getOperands().get(0);
    final DruidExpression operandExpression = Expressions.toDruidExpression(plannerContext, rowSignature, operand);
    if (operandExpression == null) {
        return null;
    }
    final SqlTypeName fromType = operand.getType().getSqlTypeName();
    final SqlTypeName toType = rexNode.getType().getSqlTypeName();
    if (SqlTypeName.CHAR_TYPES.contains(fromType) && SqlTypeName.DATETIME_TYPES.contains(toType)) {
        return castCharToDateTime(plannerContext, operandExpression, toType, Calcites.getColumnTypeForRelDataType(rexNode.getType()));
    } else if (SqlTypeName.DATETIME_TYPES.contains(fromType) && SqlTypeName.CHAR_TYPES.contains(toType)) {
        return castDateTimeToChar(plannerContext, operandExpression, fromType, Calcites.getColumnTypeForRelDataType(rexNode.getType()));
    } else {
        // Handle other casts.
        final ExprType fromExprType = EXPRESSION_TYPES.get(fromType);
        final ExprType toExprType = EXPRESSION_TYPES.get(toType);
        if (fromExprType == null || toExprType == null) {
            // We have no runtime type for these SQL types.
            return null;
        }
        final DruidExpression typeCastExpression;
        if (fromExprType != toExprType) {
            // Ignore casts for simple extractions (use Function.identity) since it is ok in many cases.
            typeCastExpression = operandExpression.map(Function.identity(), expression -> StringUtils.format("CAST(%s, '%s')", expression, toExprType.toString()));
        } else {
            typeCastExpression = operandExpression;
        }
        if (toType == SqlTypeName.DATE) {
            // Floor to day when casting to DATE.
            return TimeFloorOperatorConversion.applyTimestampFloor(typeCastExpression, new PeriodGranularity(Period.days(1), null, plannerContext.getTimeZone()), plannerContext.getExprMacroTable());
        } else {
            return typeCastExpression;
        }
    }
}
Also used : DruidExpression(org.apache.druid.sql.calcite.expression.DruidExpression) SqlTypeName(org.apache.calcite.sql.type.SqlTypeName) ExprType(org.apache.druid.math.expr.ExprType) PeriodGranularity(org.apache.druid.java.util.common.granularity.PeriodGranularity) RexNode(org.apache.calcite.rex.RexNode)

Aggregations

RexNode (org.apache.calcite.rex.RexNode)1 SqlTypeName (org.apache.calcite.sql.type.SqlTypeName)1 PeriodGranularity (org.apache.druid.java.util.common.granularity.PeriodGranularity)1 ExprType (org.apache.druid.math.expr.ExprType)1 DruidExpression (org.apache.druid.sql.calcite.expression.DruidExpression)1