Search in sources :

Example 51 with SqlTypeName

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

the class SqlParameterizerShuttle method visit.

@Override
public SqlNode visit(SqlDynamicParam param) {
    try {
        if (plannerContext.getParameters().size() > param.getIndex()) {
            TypedValue paramBinding = plannerContext.getParameters().get(param.getIndex());
            if (paramBinding == null) {
                throw new IAE("Parameter at position[%s] is not bound", param.getIndex());
            }
            if (paramBinding.value == null) {
                return SqlLiteral.createNull(param.getParserPosition());
            }
            SqlTypeName typeName = SqlTypeName.getNameForJdbcType(paramBinding.type.typeId);
            if (SqlTypeName.APPROX_TYPES.contains(typeName)) {
                return SqlLiteral.createApproxNumeric(paramBinding.value.toString(), param.getParserPosition());
            }
            if (SqlTypeName.TIMESTAMP.equals(typeName) && paramBinding.value instanceof Long) {
                return SqlLiteral.createTimestamp(TimestampString.fromMillisSinceEpoch((Long) paramBinding.value), 0, param.getParserPosition());
            }
            return typeName.createLiteral(paramBinding.value, param.getParserPosition());
        } else {
            throw new IAE("Parameter at position[%s] is not bound", param.getIndex());
        }
    } catch (ClassCastException ignored) {
    // suppress
    }
    return param;
}
Also used : SqlTypeName(org.apache.calcite.sql.type.SqlTypeName) IAE(org.apache.druid.java.util.common.IAE) TypedValue(org.apache.calcite.avatica.remote.TypedValue)

Example 52 with SqlTypeName

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

the class Expressions method literalToDruidExpression.

@Nullable
private static DruidExpression literalToDruidExpression(final PlannerContext plannerContext, final RexNode rexNode) {
    final SqlTypeName sqlTypeName = rexNode.getType().getSqlTypeName();
    // Translate literal.
    final ColumnType columnType = Calcites.getColumnTypeForRelDataType(rexNode.getType());
    if (RexLiteral.isNullLiteral(rexNode)) {
        return DruidExpression.ofLiteral(columnType, DruidExpression.nullLiteral());
    } else if (SqlTypeName.NUMERIC_TYPES.contains(sqlTypeName)) {
        return DruidExpression.ofLiteral(columnType, DruidExpression.numberLiteral((Number) RexLiteral.value(rexNode)));
    } else if (SqlTypeFamily.INTERVAL_DAY_TIME == sqlTypeName.getFamily()) {
        // Calcite represents DAY-TIME intervals in milliseconds.
        final long milliseconds = ((Number) RexLiteral.value(rexNode)).longValue();
        return DruidExpression.ofLiteral(columnType, DruidExpression.numberLiteral(milliseconds));
    } else if (SqlTypeFamily.INTERVAL_YEAR_MONTH == sqlTypeName.getFamily()) {
        // Calcite represents YEAR-MONTH intervals in months.
        final long months = ((Number) RexLiteral.value(rexNode)).longValue();
        return DruidExpression.ofLiteral(columnType, DruidExpression.numberLiteral(months));
    } else if (SqlTypeName.STRING_TYPES.contains(sqlTypeName)) {
        return DruidExpression.ofStringLiteral(RexLiteral.stringValue(rexNode));
    } else if (SqlTypeName.TIMESTAMP == sqlTypeName || SqlTypeName.DATE == sqlTypeName) {
        if (RexLiteral.isNullLiteral(rexNode)) {
            return DruidExpression.ofLiteral(columnType, DruidExpression.nullLiteral());
        } else {
            return DruidExpression.ofLiteral(columnType, DruidExpression.numberLiteral(Calcites.calciteDateTimeLiteralToJoda(rexNode, plannerContext.getTimeZone()).getMillis()));
        }
    } else if (SqlTypeName.BOOLEAN == sqlTypeName) {
        return DruidExpression.ofLiteral(columnType, DruidExpression.numberLiteral(RexLiteral.booleanValue(rexNode) ? 1 : 0));
    } else {
        // Can't translate other literals.
        return null;
    }
}
Also used : ColumnType(org.apache.druid.segment.column.ColumnType) SqlTypeName(org.apache.calcite.sql.type.SqlTypeName) Nullable(javax.annotation.Nullable)

Example 53 with SqlTypeName

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

the class DruidRexExecutor method reduce.

@Override
public void reduce(final RexBuilder rexBuilder, final List<RexNode> constExps, final List<RexNode> reducedValues) {
    for (RexNode constExp : constExps) {
        final DruidExpression druidExpression = Expressions.toDruidExpression(plannerContext, EMPTY_ROW_SIGNATURE, constExp);
        if (druidExpression == null) {
            reducedValues.add(constExp);
        } else {
            final SqlTypeName sqlTypeName = constExp.getType().getSqlTypeName();
            final Expr expr = Parser.parse(druidExpression.getExpression(), plannerContext.getExprMacroTable());
            final ExprEval exprResult = expr.eval(InputBindings.forFunction(name -> {
                // Sanity check. Bindings should not be used for a constant expression.
                throw new UnsupportedOperationException();
            }));
            final RexNode literal;
            if (sqlTypeName == SqlTypeName.BOOLEAN) {
                literal = rexBuilder.makeLiteral(exprResult.asBoolean(), constExp.getType(), true);
            } else if (sqlTypeName == SqlTypeName.DATE) {
                // ExprEval.isNumericNull checks whether the parsed primitive value is null or not.
                if (!constExp.getType().isNullable() && exprResult.isNumericNull()) {
                    throw new UnsupportedSQLQueryException("Illegal DATE constant: %s", constExp);
                }
                literal = rexBuilder.makeDateLiteral(Calcites.jodaToCalciteDateString(DateTimes.utc(exprResult.asLong()), plannerContext.getTimeZone()));
            } else if (sqlTypeName == SqlTypeName.TIMESTAMP) {
                // ExprEval.isNumericNull checks whether the parsed primitive value is null or not.
                if (!constExp.getType().isNullable() && exprResult.isNumericNull()) {
                    throw new UnsupportedSQLQueryException("Illegal TIMESTAMP constant: %s", constExp);
                }
                literal = rexBuilder.makeTimestampLiteral(Calcites.jodaToCalciteTimestampString(DateTimes.utc(exprResult.asLong()), plannerContext.getTimeZone()), RelDataType.PRECISION_NOT_SPECIFIED);
            } else if (SqlTypeName.NUMERIC_TYPES.contains(sqlTypeName)) {
                final BigDecimal bigDecimal;
                if (exprResult.isNumericNull()) {
                    literal = rexBuilder.makeNullLiteral(constExp.getType());
                } else {
                    if (exprResult.type().is(ExprType.LONG)) {
                        bigDecimal = BigDecimal.valueOf(exprResult.asLong());
                    } else {
                        // if exprResult evaluates to Nan or infinity, this will throw a NumberFormatException.
                        // If you find yourself in such a position, consider casting the literal to a BIGINT so that
                        // the query can execute.
                        double exprResultDouble = exprResult.asDouble();
                        if (Double.isNaN(exprResultDouble) || Double.isInfinite(exprResultDouble)) {
                            String expression = druidExpression.getExpression();
                            throw new UnsupportedSQLQueryException("'%s' evaluates to '%s' that is not supported in SQL. You can either cast the expression as bigint ('cast(%s as bigint)') or char ('cast(%s as char)') or change the expression itself", expression, Double.toString(exprResultDouble), expression, expression);
                        }
                        bigDecimal = BigDecimal.valueOf(exprResult.asDouble());
                    }
                    literal = rexBuilder.makeLiteral(bigDecimal, constExp.getType(), true);
                }
            } else if (sqlTypeName == SqlTypeName.ARRAY) {
                assert exprResult.isArray();
                if (SqlTypeName.NUMERIC_TYPES.contains(constExp.getType().getComponentType().getSqlTypeName())) {
                    if (exprResult.type().getElementType().is(ExprType.LONG)) {
                        List<BigDecimal> resultAsBigDecimalList = Arrays.stream(exprResult.asLongArray()).map(BigDecimal::valueOf).collect(Collectors.toList());
                        literal = rexBuilder.makeLiteral(resultAsBigDecimalList, constExp.getType(), true);
                    } else {
                        List<BigDecimal> resultAsBigDecimalList = Arrays.stream(exprResult.asDoubleArray()).map(doubleVal -> {
                            if (Double.isNaN(doubleVal) || Double.isInfinite(doubleVal)) {
                                String expression = druidExpression.getExpression();
                                throw new UnsupportedSQLQueryException("'%s' contains an element that evaluates to '%s' which is not supported in SQL. You can either cast the element in the array to bigint or char or change the expression itself", expression, Double.toString(doubleVal));
                            }
                            return BigDecimal.valueOf(doubleVal);
                        }).collect(Collectors.toList());
                        literal = rexBuilder.makeLiteral(resultAsBigDecimalList, constExp.getType(), true);
                    }
                } else {
                    literal = rexBuilder.makeLiteral(Arrays.asList(exprResult.asArray()), constExp.getType(), true);
                }
            } else if (sqlTypeName == SqlTypeName.OTHER && constExp.getType() instanceof RowSignatures.ComplexSqlType) {
                // complex constant is not reducible, so just leave it as an expression
                literal = constExp;
            } else {
                if (exprResult.isArray()) {
                    // just leave array expressions on multi-value strings alone, we're going to push them down into a virtual
                    // column selector anyway
                    literal = constExp;
                } else {
                    literal = rexBuilder.makeLiteral(exprResult.value(), constExp.getType(), true);
                }
            }
            reducedValues.add(literal);
        }
    }
}
Also used : RelDataType(org.apache.calcite.rel.type.RelDataType) DateTimes(org.apache.druid.java.util.common.DateTimes) InputBindings(org.apache.druid.math.expr.InputBindings) Arrays(java.util.Arrays) SqlTypeName(org.apache.calcite.sql.type.SqlTypeName) RexBuilder(org.apache.calcite.rex.RexBuilder) Parser(org.apache.druid.math.expr.Parser) ExprType(org.apache.druid.math.expr.ExprType) RowSignatures(org.apache.druid.sql.calcite.table.RowSignatures) Collectors(java.util.stream.Collectors) ExprEval(org.apache.druid.math.expr.ExprEval) DruidExpression(org.apache.druid.sql.calcite.expression.DruidExpression) BigDecimal(java.math.BigDecimal) List(java.util.List) RexNode(org.apache.calcite.rex.RexNode) RowSignature(org.apache.druid.segment.column.RowSignature) Expr(org.apache.druid.math.expr.Expr) RexExecutor(org.apache.calcite.rex.RexExecutor) Expressions(org.apache.druid.sql.calcite.expression.Expressions) ExprEval(org.apache.druid.math.expr.ExprEval) DruidExpression(org.apache.druid.sql.calcite.expression.DruidExpression) SqlTypeName(org.apache.calcite.sql.type.SqlTypeName) Expr(org.apache.druid.math.expr.Expr) BigDecimal(java.math.BigDecimal) RexNode(org.apache.calcite.rex.RexNode)

Example 54 with SqlTypeName

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.sql.type.SqlTypeName in project hazelcast by hazelcast.

the class HazelcastRexBuilder method makeLiteral.

@Override
public RexNode makeLiteral(Object value, RelDataType type, boolean allowCast) {
    if (type.getSqlTypeName() == ANY && value instanceof Number) {
        Converter converter = Converters.getConverter(value.getClass());
        if (converter != null) {
            QueryDataTypeFamily typeFamily = converter.getTypeFamily();
            if (typeFamily.isNumericInteger()) {
                int bitWidth = HazelcastIntegerType.bitWidthOf(((Number) value).longValue());
                type = HazelcastIntegerType.create(bitWidth, false);
            } else {
                SqlTypeName typeName = HazelcastTypeUtils.toCalciteType(typeFamily);
                type = HazelcastTypeFactory.INSTANCE.createSqlType(typeName);
            }
        }
    }
    return super.makeLiteral(value, type, allowCast);
}
Also used : QueryDataTypeFamily(com.hazelcast.sql.impl.type.QueryDataTypeFamily) SqlTypeName(org.apache.calcite.sql.type.SqlTypeName) Converter(com.hazelcast.sql.impl.type.converter.Converter)

Example 55 with SqlTypeName

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.sql.type.SqlTypeName in project hazelcast by hazelcast.

the class WindowOperandMetadata method checkOperandTypes.

private boolean checkOperandTypes(HazelcastCallBinding binding, boolean throwOnFailure, int columnIndex) {
    SqlNode lag = binding.operand(columnIndex);
    HazelcastSqlValidator validator = binding.getValidator();
    SqlTypeName orderingColumnType = getOrderingColumnType(binding, 1).getSqlTypeName();
    boolean result;
    SqlTypeName lagType = ((SqlValidator) validator).getValidatedNodeType(lag).getSqlTypeName();
    if (SqlTypeName.INT_TYPES.contains(orderingColumnType)) {
        result = SqlTypeName.INT_TYPES.contains(lagType);
    } else if (SqlTypeName.DATETIME_TYPES.contains(orderingColumnType)) {
        result = lagType.getFamily() == SqlTypeFamily.INTERVAL_DAY_TIME;
    } else {
        result = false;
    }
    if (!result && throwOnFailure) {
        QueryDataTypeFamily hzOrderingColumnType = toHazelcastTypeFromSqlTypeName(orderingColumnType).getTypeFamily();
        QueryDataTypeFamily hzLagType = toHazelcastTypeFromSqlTypeName(lagType).getTypeFamily();
        throw validator.newValidationError(binding.getCall(), RESOURCES.windowFunctionTypeMismatch(hzOrderingColumnType.toString(), hzLagType.toString()));
    }
    return result;
}
Also used : QueryDataTypeFamily(com.hazelcast.sql.impl.type.QueryDataTypeFamily) HazelcastTypeUtils.toHazelcastTypeFromSqlTypeName(com.hazelcast.jet.sql.impl.validate.types.HazelcastTypeUtils.toHazelcastTypeFromSqlTypeName) SqlTypeName(org.apache.calcite.sql.type.SqlTypeName) HazelcastSqlValidator(com.hazelcast.jet.sql.impl.validate.HazelcastSqlValidator) SqlNode(org.apache.calcite.sql.SqlNode)

Aggregations

SqlTypeName (org.apache.calcite.sql.type.SqlTypeName)117 Test (org.junit.Test)38 RelDataType (org.apache.calcite.rel.type.RelDataType)28 RexNode (org.apache.calcite.rex.RexNode)18 BigDecimal (java.math.BigDecimal)13 ArrayList (java.util.ArrayList)13 List (java.util.List)11 RelDataTypeField (org.apache.calcite.rel.type.RelDataTypeField)9 RelDataTypeFactory (org.apache.calcite.rel.type.RelDataTypeFactory)8 ImmutableList (com.google.common.collect.ImmutableList)7 Map (java.util.Map)7 DateString (org.apache.calcite.util.DateString)7 TimeString (org.apache.calcite.util.TimeString)7 TimestampString (org.apache.calcite.util.TimestampString)7 ISE (io.druid.java.util.common.ISE)6 SqlKind (org.apache.calcite.sql.SqlKind)6 NlsString (org.apache.calcite.util.NlsString)6 Calendar (java.util.Calendar)5 Nullable (javax.annotation.Nullable)5 RexBuilder (org.apache.calcite.rex.RexBuilder)5