Search in sources :

Example 76 with PrestoException

use of com.facebook.presto.spi.PrestoException in project presto by prestodb.

the class FunctionRegistry method resolveFunction.

public Signature resolveFunction(QualifiedName name, List<TypeSignatureProvider> parameterTypes) {
    Collection<SqlFunction> allCandidates = functions.get(name);
    List<SqlFunction> exactCandidates = allCandidates.stream().filter(function -> function.getSignature().getTypeVariableConstraints().isEmpty()).collect(Collectors.toList());
    Optional<Signature> match = matchFunctionExact(exactCandidates, parameterTypes);
    if (match.isPresent()) {
        return match.get();
    }
    List<SqlFunction> genericCandidates = allCandidates.stream().filter(function -> !function.getSignature().getTypeVariableConstraints().isEmpty()).collect(Collectors.toList());
    match = matchFunctionExact(genericCandidates, parameterTypes);
    if (match.isPresent()) {
        return match.get();
    }
    match = matchFunctionWithCoercion(allCandidates, parameterTypes);
    if (match.isPresent()) {
        return match.get();
    }
    List<String> expectedParameters = new ArrayList<>();
    for (SqlFunction function : allCandidates) {
        expectedParameters.add(format("%s(%s) %s", name, Joiner.on(", ").join(function.getSignature().getArgumentTypes()), Joiner.on(", ").join(function.getSignature().getTypeVariableConstraints())));
    }
    String parameters = Joiner.on(", ").join(parameterTypes);
    String message = format("Function %s not registered", name);
    if (!expectedParameters.isEmpty()) {
        String expected = Joiner.on(", ").join(expectedParameters);
        message = format("Unexpected parameters (%s) for function %s. Expected: %s", parameters, name, expected);
    }
    if (name.getSuffix().startsWith(MAGIC_LITERAL_FUNCTION_PREFIX)) {
        // extract type from function name
        String typeName = name.getSuffix().substring(MAGIC_LITERAL_FUNCTION_PREFIX.length());
        // lookup the type
        Type type = typeManager.getType(parseTypeSignature(typeName));
        requireNonNull(type, format("Type %s not registered", typeName));
        // verify we have one parameter of the proper type
        checkArgument(parameterTypes.size() == 1, "Expected one argument to literal function, but got %s", parameterTypes);
        Type parameterType = typeManager.getType(parameterTypes.get(0).getTypeSignature());
        requireNonNull(parameterType, format("Type %s not found", parameterTypes.get(0)));
        return getMagicLiteralFunctionSignature(type);
    }
    throw new PrestoException(FUNCTION_NOT_FOUND, message);
}
Also used : INTEGER_TO_DECIMAL_CAST(com.facebook.presto.type.DecimalCasts.INTEGER_TO_DECIMAL_CAST) ApproximateDoublePercentileArrayAggregations(com.facebook.presto.operator.aggregation.ApproximateDoublePercentileArrayAggregations) DECIMAL_TO_SMALLINT_SATURATED_FLOOR_CAST(com.facebook.presto.type.DecimalSaturatedFloorCasts.DECIMAL_TO_SMALLINT_SATURATED_FLOOR_CAST) MapEqualOperator(com.facebook.presto.operator.scalar.MapEqualOperator) DECIMAL_SUBTRACT_OPERATOR(com.facebook.presto.type.DecimalOperators.DECIMAL_SUBTRACT_OPERATOR) TimeOperators(com.facebook.presto.type.TimeOperators) JsonFunctions(com.facebook.presto.operator.scalar.JsonFunctions) NTileFunction(com.facebook.presto.operator.window.NTileFunction) TimestampWithTimeZoneOperators(com.facebook.presto.type.TimestampWithTimeZoneOperators) ArrayContains(com.facebook.presto.operator.scalar.ArrayContains) DECIMAL_LESS_THAN_OR_EQUAL_OPERATOR(com.facebook.presto.type.DecimalInequalityOperators.DECIMAL_LESS_THAN_OR_EQUAL_OPERATOR) BOOLEAN(com.facebook.presto.spi.type.BooleanType.BOOLEAN) AverageAggregations(com.facebook.presto.operator.aggregation.AverageAggregations) Map(java.util.Map) MathFunctions(com.facebook.presto.operator.scalar.MathFunctions) ImmutableCollectors.toImmutableList(com.facebook.presto.util.ImmutableCollectors.toImmutableList) MAP_FILTER_FUNCTION(com.facebook.presto.operator.scalar.MapFilterFunction.MAP_FILTER_FUNCTION) CONCAT(com.facebook.presto.operator.scalar.ConcatFunction.CONCAT) SignatureBinder.applyBoundVariables(com.facebook.presto.metadata.SignatureBinder.applyBoundVariables) HyperLogLogOperators(com.facebook.presto.type.HyperLogLogOperators) WINDOW(com.facebook.presto.metadata.FunctionKind.WINDOW) InternalAggregationFunction(com.facebook.presto.operator.aggregation.InternalAggregationFunction) MAP_ELEMENT_AT(com.facebook.presto.operator.scalar.MapElementAtFunction.MAP_ELEMENT_AT) OperatorType(com.facebook.presto.spi.function.OperatorType) ArrayFunctions(com.facebook.presto.operator.scalar.ArrayFunctions) PercentRankFunction(com.facebook.presto.operator.window.PercentRankFunction) DECIMAL_MULTIPLY_OPERATOR(com.facebook.presto.type.DecimalOperators.DECIMAL_MULTIPLY_OPERATOR) Joiner(com.google.common.base.Joiner) MethodHandle(java.lang.invoke.MethodHandle) LagFunction(com.facebook.presto.operator.window.LagFunction) ApproximateCountDistinctAggregations(com.facebook.presto.operator.aggregation.ApproximateCountDistinctAggregations) ColorFunctions(com.facebook.presto.operator.scalar.ColorFunctions) DECIMAL_SUM_AGGREGATION(com.facebook.presto.operator.aggregation.DecimalSumAggregation.DECIMAL_SUM_AGGREGATION) VarbinaryOperators(com.facebook.presto.type.VarbinaryOperators) MAP_UNION(com.facebook.presto.operator.aggregation.MapUnionAggregation.MAP_UNION) ARRAY_TO_ARRAY_CAST(com.facebook.presto.operator.scalar.ArrayToArrayCast.ARRAY_TO_ARRAY_CAST) TimestampOperators(com.facebook.presto.type.TimestampOperators) ArrayPositionFunction(com.facebook.presto.operator.scalar.ArrayPositionFunction) CHECKSUM_AGGREGATION(com.facebook.presto.operator.aggregation.ChecksumAggregationFunction.CHECKSUM_AGGREGATION) DecimalOperators(com.facebook.presto.type.DecimalOperators) Type(com.facebook.presto.spi.type.Type) ARRAY_FLATTEN_FUNCTION(com.facebook.presto.operator.scalar.ArrayFlattenFunction.ARRAY_FLATTEN_FUNCTION) TRY_CAST(com.facebook.presto.operator.scalar.TryCastFunction.TRY_CAST) ArrayEqualOperator(com.facebook.presto.operator.scalar.ArrayEqualOperator) JoniRegexpFunctions(com.facebook.presto.operator.scalar.JoniRegexpFunctions) BitwiseAndAggregation(com.facebook.presto.operator.aggregation.BitwiseAndAggregation) ELEMENT_TO_ARRAY_CONCAT_FUNCTION(com.facebook.presto.operator.scalar.ElementToArrayConcatFunction.ELEMENT_TO_ARRAY_CONCAT_FUNCTION) AMBIGUOUS_FUNCTION_CALL(com.facebook.presto.spi.StandardErrorCode.AMBIGUOUS_FUNCTION_CALL) DECIMAL_GREATER_THAN_OPERATOR(com.facebook.presto.type.DecimalInequalityOperators.DECIMAL_GREATER_THAN_OPERATOR) ApproximateRealPercentileAggregations(com.facebook.presto.operator.aggregation.ApproximateRealPercentileAggregations) DECIMAL_TO_BIGINT_SATURATED_FLOOR_CAST(com.facebook.presto.type.DecimalSaturatedFloorCasts.DECIMAL_TO_BIGINT_SATURATED_FLOOR_CAST) BIGINT_TO_DECIMAL_CAST(com.facebook.presto.type.DecimalCasts.BIGINT_TO_DECIMAL_CAST) Throwables(com.google.common.base.Throwables) MAP_AGG(com.facebook.presto.operator.aggregation.MapAggregationFunction.MAP_AGG) GREATEST(com.facebook.presto.operator.scalar.Greatest.GREATEST) IDENTITY_CAST(com.facebook.presto.operator.scalar.IdentityCast.IDENTITY_CAST) Iterables.getOnlyElement(com.google.common.collect.Iterables.getOnlyElement) ColorOperators(com.facebook.presto.type.ColorOperators) HISTOGRAM(com.facebook.presto.operator.aggregation.Histogram.HISTOGRAM) ArrayExceptFunction(com.facebook.presto.operator.scalar.ArrayExceptFunction) ARRAY_TO_ELEMENT_CONCAT_FUNCTION(com.facebook.presto.operator.scalar.ArrayToElementConcatFunction.ARRAY_TO_ELEMENT_CONCAT_FUNCTION) TINYINT_TO_DECIMAL_SATURATED_FLOOR_CAST(com.facebook.presto.type.DecimalSaturatedFloorCasts.TINYINT_TO_DECIMAL_SATURATED_FLOOR_CAST) DoubleCovarianceAggregation(com.facebook.presto.operator.aggregation.DoubleCovarianceAggregation) CountIfAggregation(com.facebook.presto.operator.aggregation.CountIfAggregation) JSON_TO_DECIMAL_CAST(com.facebook.presto.type.DecimalCasts.JSON_TO_DECIMAL_CAST) VarcharType(com.facebook.presto.spi.type.VarcharType) DECIMAL_DISTINCT_FROM_OPERATOR(com.facebook.presto.type.DecimalInequalityOperators.DECIMAL_DISTINCT_FROM_OPERATOR) TypeSignature.parseTypeSignature(com.facebook.presto.spi.type.TypeSignature.parseTypeSignature) DoubleRegressionAggregation(com.facebook.presto.operator.aggregation.DoubleRegressionAggregation) MAX_BY(com.facebook.presto.operator.aggregation.MaxBy.MAX_BY) DoubleSumAggregation(com.facebook.presto.operator.aggregation.DoubleSumAggregation) DECIMAL_NOT_EQUAL_OPERATOR(com.facebook.presto.type.DecimalInequalityOperators.DECIMAL_NOT_EQUAL_OPERATOR) IntegerOperators(com.facebook.presto.type.IntegerOperators) ArrayReverseFunction(com.facebook.presto.operator.scalar.ArrayReverseFunction) LastValueFunction(com.facebook.presto.operator.window.LastValueFunction) Block(com.facebook.presto.spi.block.Block) MAP_HASH_CODE(com.facebook.presto.operator.scalar.MapHashCodeOperator.MAP_HASH_CODE) RealGeometricMeanAggregations(com.facebook.presto.operator.aggregation.RealGeometricMeanAggregations) FUNCTION_NOT_FOUND(com.facebook.presto.spi.StandardErrorCode.FUNCTION_NOT_FOUND) ARBITRARY_AGGREGATION(com.facebook.presto.operator.aggregation.ArbitraryAggregationFunction.ARBITRARY_AGGREGATION) JSON_TO_ARRAY(com.facebook.presto.operator.scalar.JsonToArrayCast.JSON_TO_ARRAY) ARRAY_CONCAT_FUNCTION(com.facebook.presto.operator.scalar.ArrayConcatFunction.ARRAY_CONCAT_FUNCTION) Re2JCastToRegexpFunction.castCharToRe2JRegexp(com.facebook.presto.operator.scalar.Re2JCastToRegexpFunction.castCharToRe2JRegexp) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) BooleanAndAggregation(com.facebook.presto.operator.aggregation.BooleanAndAggregation) DateTimeOperators(com.facebook.presto.type.DateTimeOperators) MIN_BY(com.facebook.presto.operator.aggregation.MinBy.MIN_BY) ARRAY_TO_JSON(com.facebook.presto.operator.scalar.ArrayToJsonCast.ARRAY_TO_JSON) UNKNOWN(com.facebook.presto.type.UnknownType.UNKNOWN) RankFunction(com.facebook.presto.operator.window.RankFunction) MAP_TRANSFORM_VALUE_FUNCTION(com.facebook.presto.operator.scalar.MapTransformValueFunction.MAP_TRANSFORM_VALUE_FUNCTION) ArrayDistinctFunction(com.facebook.presto.operator.scalar.ArrayDistinctFunction) DECIMAL_MOD_FUNCTION(com.facebook.presto.operator.scalar.MathFunctions.DECIMAL_MOD_FUNCTION) NthValueFunction(com.facebook.presto.operator.window.NthValueFunction) MAX_BY_N_AGGREGATION(com.facebook.presto.operator.aggregation.MaxByNAggregationFunction.MAX_BY_N_AGGREGATION) ImmutableSet(com.google.common.collect.ImmutableSet) DECIMAL_LESS_THAN_OPERATOR(com.facebook.presto.type.DecimalInequalityOperators.DECIMAL_LESS_THAN_OPERATOR) Collection(java.util.Collection) CountAggregation(com.facebook.presto.operator.aggregation.CountAggregation) Collectors(java.util.stream.Collectors) ARRAY_REDUCE_FUNCTION(com.facebook.presto.operator.scalar.ArrayReduceFunction.ARRAY_REDUCE_FUNCTION) CacheLoader(com.google.common.cache.CacheLoader) DECIMAL_TO_BIGINT_CAST(com.facebook.presto.type.DecimalCasts.DECIMAL_TO_BIGINT_CAST) Re2JCastToRegexpFunction.castVarcharToRe2JRegexp(com.facebook.presto.operator.scalar.Re2JCastToRegexpFunction.castVarcharToRe2JRegexp) DECIMAL_TO_DECIMAL_CAST(com.facebook.presto.type.DecimalToDecimalCasts.DECIMAL_TO_DECIMAL_CAST) WindowFunctionSupplier(com.facebook.presto.operator.window.WindowFunctionSupplier) AggregateWindowFunction.supplier(com.facebook.presto.operator.window.AggregateWindowFunction.supplier) QualifiedName(com.facebook.presto.sql.tree.QualifiedName) DECIMAL_ADD_OPERATOR(com.facebook.presto.type.DecimalOperators.DECIMAL_ADD_OPERATOR) DoubleHistogramAggregation(com.facebook.presto.operator.aggregation.DoubleHistogramAggregation) ROW_HASH_CODE(com.facebook.presto.operator.scalar.RowHashCodeOperator.ROW_HASH_CODE) JoniRegexpCasts(com.facebook.presto.operator.scalar.JoniRegexpCasts) UnknownOperators(com.facebook.presto.type.UnknownOperators) ArrayDistinctFromOperator(com.facebook.presto.operator.scalar.ArrayDistinctFromOperator) BooleanOperators(com.facebook.presto.type.BooleanOperators) BlockEncodingSerde(com.facebook.presto.spi.block.BlockEncodingSerde) Re2JRegexpFunctions(com.facebook.presto.operator.scalar.Re2JRegexpFunctions) ImmutableList(com.google.common.collect.ImmutableList) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) INTEGER_TO_DECIMAL_SATURATED_FLOOR_CAST(com.facebook.presto.type.DecimalSaturatedFloorCasts.INTEGER_TO_DECIMAL_SATURATED_FLOOR_CAST) ArrayLessThanOperator(com.facebook.presto.operator.scalar.ArrayLessThanOperator) JsonOperators(com.facebook.presto.operator.scalar.JsonOperators) VARBINARY(com.facebook.presto.spi.type.VarbinaryType.VARBINARY) ArrayGreaterThanOrEqualOperator(com.facebook.presto.operator.scalar.ArrayGreaterThanOrEqualOperator) MAX_N_AGGREGATION(com.facebook.presto.operator.aggregation.MaxNAggregationFunction.MAX_N_AGGREGATION) DECIMAL_TO_INTEGER_SATURATED_FLOOR_CAST(com.facebook.presto.type.DecimalSaturatedFloorCasts.DECIMAL_TO_INTEGER_SATURATED_FLOOR_CAST) RealCorrelationAggregation(com.facebook.presto.operator.aggregation.RealCorrelationAggregation) ArraySortFunction(com.facebook.presto.operator.scalar.ArraySortFunction) ArraySliceFunction(com.facebook.presto.operator.scalar.ArraySliceFunction) MAP_TO_JSON(com.facebook.presto.operator.scalar.MapToJsonCast.MAP_TO_JSON) HyperLogLogFunctions(com.facebook.presto.operator.scalar.HyperLogLogFunctions) RowNumberFunction(com.facebook.presto.operator.window.RowNumberFunction) JSON_TO_MAP(com.facebook.presto.operator.scalar.JsonToMapCast.JSON_TO_MAP) MAP_TRANSFORM_KEY_FUNCTION(com.facebook.presto.operator.scalar.MapTransformKeyFunction.MAP_TRANSFORM_KEY_FUNCTION) Ordering(com.google.common.collect.Ordering) ARRAY_SUBSCRIPT(com.facebook.presto.operator.scalar.ArraySubscriptOperator.ARRAY_SUBSCRIPT) BitwiseOrAggregation(com.facebook.presto.operator.aggregation.BitwiseOrAggregation) DECIMAL_TO_JSON_CAST(com.facebook.presto.type.DecimalCasts.DECIMAL_TO_JSON_CAST) EmptyMapConstructor(com.facebook.presto.operator.scalar.EmptyMapConstructor) ARRAY_JOIN(com.facebook.presto.operator.scalar.ArrayJoin.ARRAY_JOIN) DECIMAL_TO_VARCHAR_CAST(com.facebook.presto.type.DecimalCasts.DECIMAL_TO_VARCHAR_CAST) Arrays(java.util.Arrays) DECIMAL_TO_BOOLEAN_CAST(com.facebook.presto.type.DecimalCasts.DECIMAL_TO_BOOLEAN_CAST) LoadingCache(com.google.common.cache.LoadingCache) TypeManager(com.facebook.presto.spi.type.TypeManager) MapKeys(com.facebook.presto.operator.scalar.MapKeys) BIGINT_TO_DECIMAL_SATURATED_FLOOR_CAST(com.facebook.presto.type.DecimalSaturatedFloorCasts.BIGINT_TO_DECIMAL_SATURATED_FLOOR_CAST) AGGREGATE(com.facebook.presto.metadata.FunctionKind.AGGREGATE) REAL_TO_DECIMAL_SATURATED_FLOOR_CAST(com.facebook.presto.type.DecimalSaturatedFloorCasts.REAL_TO_DECIMAL_SATURATED_FLOOR_CAST) ROW_NOT_EQUAL(com.facebook.presto.operator.scalar.RowNotEqualOperator.ROW_NOT_EQUAL) BIGINT(com.facebook.presto.spi.type.BigintType.BIGINT) SmallintOperators(com.facebook.presto.type.SmallintOperators) ApproximateRealPercentileArrayAggregations(com.facebook.presto.operator.aggregation.ApproximateRealPercentileArrayAggregations) SqlWindowFunction(com.facebook.presto.operator.window.SqlWindowFunction) CharOperators(com.facebook.presto.type.CharOperators) MAP_CONSTRUCTOR(com.facebook.presto.operator.scalar.MapConstructor.MAP_CONSTRUCTOR) ArrayAggregationFunction(com.facebook.presto.operator.aggregation.ArrayAggregationFunction) MapCardinalityFunction(com.facebook.presto.operator.scalar.MapCardinalityFunction) LongSumAggregation(com.facebook.presto.operator.aggregation.LongSumAggregation) MapNotEqualOperator(com.facebook.presto.operator.scalar.MapNotEqualOperator) ROW_GREATER_THAN_OR_EQUAL(com.facebook.presto.operator.scalar.RowGreaterThanOrEqualOperator.ROW_GREATER_THAN_OR_EQUAL) LikeFunctions(com.facebook.presto.type.LikeFunctions) MethodHandles(java.lang.invoke.MethodHandles) TypeOfFunction(com.facebook.presto.operator.scalar.TypeOfFunction) Set(java.util.Set) RealSumAggregation(com.facebook.presto.operator.aggregation.RealSumAggregation) ThreadSafe(javax.annotation.concurrent.ThreadSafe) DECIMAL_TO_DOUBLE_CAST(com.facebook.presto.type.DecimalCasts.DECIMAL_TO_DOUBLE_CAST) ArrayGreaterThanOperator(com.facebook.presto.operator.scalar.ArrayGreaterThanOperator) FeaturesConfig(com.facebook.presto.sql.analyzer.FeaturesConfig) MIN_AGGREGATION(com.facebook.presto.operator.aggregation.MinAggregationFunction.MIN_AGGREGATION) LEAST(com.facebook.presto.operator.scalar.Least.LEAST) DECIMAL_TO_INTEGER_CAST(com.facebook.presto.type.DecimalCasts.DECIMAL_TO_INTEGER_CAST) ApproximateLongPercentileArrayAggregations(com.facebook.presto.operator.aggregation.ApproximateLongPercentileArrayAggregations) DECIMAL_TO_TINYINT_CAST(com.facebook.presto.type.DecimalCasts.DECIMAL_TO_TINYINT_CAST) MergeHyperLogLogAggregation(com.facebook.presto.operator.aggregation.MergeHyperLogLogAggregation) IntervalYearMonthOperators(com.facebook.presto.type.IntervalYearMonthOperators) FUNCTION_IMPLEMENTATION_MISSING(com.facebook.presto.spi.StandardErrorCode.FUNCTION_IMPLEMENTATION_MISSING) ImmutableListMultimap(com.google.common.collect.ImmutableListMultimap) ArrayElementAtFunction(com.facebook.presto.operator.scalar.ArrayElementAtFunction) ROW_EQUAL(com.facebook.presto.operator.scalar.RowEqualOperator.ROW_EQUAL) BitwiseFunctions(com.facebook.presto.operator.scalar.BitwiseFunctions) RealOperators(com.facebook.presto.type.RealOperators) VarcharOperators(com.facebook.presto.type.VarcharOperators) MoreObjects.toStringHelper(com.google.common.base.MoreObjects.toStringHelper) SMALLINT_TO_DECIMAL_SATURATED_FLOOR_CAST(com.facebook.presto.type.DecimalSaturatedFloorCasts.SMALLINT_TO_DECIMAL_SATURATED_FLOOR_CAST) Iterables(com.google.common.collect.Iterables) DOUBLE(com.facebook.presto.spi.type.DoubleType.DOUBLE) Slice(io.airlift.slice.Slice) ApproximateSetAggregation(com.facebook.presto.operator.aggregation.ApproximateSetAggregation) DoubleOperators(com.facebook.presto.type.DoubleOperators) MAX_AGGREGATION(com.facebook.presto.operator.aggregation.MaxAggregationFunction.MAX_AGGREGATION) DECIMAL_MODULUS_OPERATOR(com.facebook.presto.type.DecimalOperators.DECIMAL_MODULUS_OPERATOR) TypeSignatureProvider.fromTypes(com.facebook.presto.sql.analyzer.TypeSignatureProvider.fromTypes) DECIMAL_AVERAGE_AGGREGATION(com.facebook.presto.operator.aggregation.DecimalAverageAggregation.DECIMAL_AVERAGE_AGGREGATION) Multimaps(com.google.common.collect.Multimaps) ArrayList(java.util.ArrayList) MIN_N_AGGREGATION(com.facebook.presto.operator.aggregation.MinNAggregationFunction.MIN_N_AGGREGATION) REAL_TO_DECIMAL_CAST(com.facebook.presto.type.DecimalCasts.REAL_TO_DECIMAL_CAST) RealAverageAggregation(com.facebook.presto.operator.aggregation.RealAverageAggregation) ArrayNotEqualOperator(com.facebook.presto.operator.scalar.ArrayNotEqualOperator) TimeWithTimeZoneOperators(com.facebook.presto.type.TimeWithTimeZoneOperators) DECIMAL_EQUAL_OPERATOR(com.facebook.presto.type.DecimalInequalityOperators.DECIMAL_EQUAL_OPERATOR) DECIMAL_DIVIDE_OPERATOR(com.facebook.presto.type.DecimalOperators.DECIMAL_DIVIDE_OPERATOR) ApproximateDoublePercentileAggregations(com.facebook.presto.operator.aggregation.ApproximateDoublePercentileAggregations) MIN_BY_N_AGGREGATION(com.facebook.presto.operator.aggregation.MinByNAggregationFunction.MIN_BY_N_AGGREGATION) DECIMAL_GREATER_THAN_OR_EQUAL_OPERATOR(com.facebook.presto.type.DecimalInequalityOperators.DECIMAL_GREATER_THAN_OR_EQUAL_OPERATOR) CAST_FROM_UNKNOWN(com.facebook.presto.operator.scalar.CastFromUnknownOperator.CAST_FROM_UNKNOWN) DenseRankFunction(com.facebook.presto.operator.window.DenseRankFunction) DECIMAL_TO_DECIMAL_SATURATED_FLOOR_CAST(com.facebook.presto.type.DecimalSaturatedFloorCasts.DECIMAL_TO_DECIMAL_SATURATED_FLOOR_CAST) ArrayMaxFunction(com.facebook.presto.operator.scalar.ArrayMaxFunction) RealCovarianceAggregation(com.facebook.presto.operator.aggregation.RealCovarianceAggregation) ArrayLessThanOrEqualOperator(com.facebook.presto.operator.scalar.ArrayLessThanOrEqualOperator) BlockSerdeUtil(com.facebook.presto.block.BlockSerdeUtil) ArrayUnionFunction(com.facebook.presto.operator.scalar.ArrayUnionFunction) CumulativeDistributionFunction(com.facebook.presto.operator.window.CumulativeDistributionFunction) ARRAY_TRANSFORM_FUNCTION(com.facebook.presto.operator.scalar.ArrayTransformFunction.ARRAY_TRANSFORM_FUNCTION) SequenceFunction(com.facebook.presto.operator.scalar.SequenceFunction) RealRegressionAggregation(com.facebook.presto.operator.aggregation.RealRegressionAggregation) FailureFunction(com.facebook.presto.operator.scalar.FailureFunction) MapSubscriptOperator(com.facebook.presto.operator.scalar.MapSubscriptOperator) MULTIMAP_AGG(com.facebook.presto.operator.aggregation.MultimapAggregationFunction.MULTIMAP_AGG) BigintOperators(com.facebook.presto.type.BigintOperators) ARRAY_CONSTRUCTOR(com.facebook.presto.operator.scalar.ArrayConstructor.ARRAY_CONSTRUCTOR) ArraysOverlapFunction(com.facebook.presto.operator.scalar.ArraysOverlapFunction) ROW_GREATER_THAN(com.facebook.presto.operator.scalar.RowGreaterThanOperator.ROW_GREATER_THAN) GeometricMeanAggregations(com.facebook.presto.operator.aggregation.GeometricMeanAggregations) RealHistogramAggregation(com.facebook.presto.operator.aggregation.RealHistogramAggregation) BOOLEAN_TO_DECIMAL_CAST(com.facebook.presto.type.DecimalCasts.BOOLEAN_TO_DECIMAL_CAST) ImmutableCollectors.toImmutableSet(com.facebook.presto.util.ImmutableCollectors.toImmutableSet) DECIMAL_BETWEEN_OPERATOR(com.facebook.presto.type.DecimalInequalityOperators.DECIMAL_BETWEEN_OPERATOR) DateTimeFunctions(com.facebook.presto.operator.scalar.DateTimeFunctions) BooleanOrAggregation(com.facebook.presto.operator.aggregation.BooleanOrAggregation) DOUBLE_TO_DECIMAL_SATURATED_FLOOR_CAST(com.facebook.presto.type.DecimalSaturatedFloorCasts.DOUBLE_TO_DECIMAL_SATURATED_FLOOR_CAST) CharacterStringCasts(com.facebook.presto.operator.scalar.CharacterStringCasts) ZIP_FUNCTIONS(com.facebook.presto.operator.scalar.ZipFunction.ZIP_FUNCTIONS) IntervalDayTimeOperators(com.facebook.presto.type.IntervalDayTimeOperators) ApproximateLongPercentileAggregations(com.facebook.presto.operator.aggregation.ApproximateLongPercentileAggregations) MapDistinctFromOperator(com.facebook.presto.operator.scalar.MapDistinctFromOperator) FirstValueFunction(com.facebook.presto.operator.window.FirstValueFunction) String.format(java.lang.String.format) TypeUtils.resolveTypes(com.facebook.presto.type.TypeUtils.resolveTypes) Preconditions.checkState(com.google.common.base.Preconditions.checkState) TINYINT_TO_DECIMAL_CAST(com.facebook.presto.type.DecimalCasts.TINYINT_TO_DECIMAL_CAST) List(java.util.List) ArrayShuffleFunction(com.facebook.presto.operator.scalar.ArrayShuffleFunction) ArrayIntersectFunction(com.facebook.presto.operator.scalar.ArrayIntersectFunction) ROW_TO_JSON(com.facebook.presto.operator.scalar.RowToJsonCast.ROW_TO_JSON) TypeSignatureProvider(com.facebook.presto.sql.analyzer.TypeSignatureProvider) Optional(java.util.Optional) MapToMapCast(com.facebook.presto.operator.scalar.MapToMapCast) CacheBuilder(com.google.common.cache.CacheBuilder) TypeSignature(com.facebook.presto.spi.type.TypeSignature) DOUBLE_TO_DECIMAL_CAST(com.facebook.presto.type.DecimalCasts.DOUBLE_TO_DECIMAL_CAST) SMALLINT_TO_DECIMAL_CAST(com.facebook.presto.type.DecimalCasts.SMALLINT_TO_DECIMAL_CAST) ScalarFunctionImplementation(com.facebook.presto.operator.scalar.ScalarFunctionImplementation) DateOperators(com.facebook.presto.type.DateOperators) PrestoException(com.facebook.presto.spi.PrestoException) Multimap(com.google.common.collect.Multimap) ZIP_WITH_FUNCTION(com.facebook.presto.operator.scalar.ZipWithFunction.ZIP_WITH_FUNCTION) StringFunctions(com.facebook.presto.operator.scalar.StringFunctions) DECIMAL_TO_TINYINT_SATURATED_FLOOR_CAST(com.facebook.presto.type.DecimalSaturatedFloorCasts.DECIMAL_TO_TINYINT_SATURATED_FLOOR_CAST) SCALAR(com.facebook.presto.metadata.FunctionKind.SCALAR) ROW_TO_ROW_CAST(com.facebook.presto.operator.scalar.RowToRowCast.ROW_TO_ROW_CAST) CombineHashFunction(com.facebook.presto.operator.scalar.CombineHashFunction) Objects.requireNonNull(java.util.Objects.requireNonNull) TypeSignatureProvider.fromTypeSignatures(com.facebook.presto.sql.analyzer.TypeSignatureProvider.fromTypeSignatures) COUNT_COLUMN(com.facebook.presto.operator.aggregation.CountColumn.COUNT_COLUMN) LeadFunction(com.facebook.presto.operator.window.LeadFunction) DoubleCorrelationAggregation(com.facebook.presto.operator.aggregation.DoubleCorrelationAggregation) DECIMAL_TO_REAL_CAST(com.facebook.presto.type.DecimalCasts.DECIMAL_TO_REAL_CAST) ArrayFilterFunction(com.facebook.presto.operator.scalar.ArrayFilterFunction) MapValues(com.facebook.presto.operator.scalar.MapValues) TinyintOperators(com.facebook.presto.type.TinyintOperators) Signature.internalOperator(com.facebook.presto.metadata.Signature.internalOperator) ArrayCardinalityFunction(com.facebook.presto.operator.scalar.ArrayCardinalityFunction) VarbinaryFunctions(com.facebook.presto.operator.scalar.VarbinaryFunctions) UrlFunctions(com.facebook.presto.operator.scalar.UrlFunctions) ARRAY_JOIN_WITH_NULL_REPLACEMENT(com.facebook.presto.operator.scalar.ArrayJoin.ARRAY_JOIN_WITH_NULL_REPLACEMENT) DECIMAL_TO_SMALLINT_CAST(com.facebook.presto.type.DecimalCasts.DECIMAL_TO_SMALLINT_CAST) VARCHAR_TO_DECIMAL_CAST(com.facebook.presto.type.DecimalCasts.VARCHAR_TO_DECIMAL_CAST) Primitives(com.google.common.primitives.Primitives) VarianceAggregation(com.facebook.presto.operator.aggregation.VarianceAggregation) ArrayRemoveFunction(com.facebook.presto.operator.scalar.ArrayRemoveFunction) MAP_CONCAT_FUNCTION(com.facebook.presto.operator.scalar.MapConcatFunction.MAP_CONCAT_FUNCTION) ROW_LESS_THAN_OR_EQUAL(com.facebook.presto.operator.scalar.RowLessThanOrEqualOperator.ROW_LESS_THAN_OR_EQUAL) ArrayHashCodeOperator(com.facebook.presto.operator.scalar.ArrayHashCodeOperator) ArrayMinFunction(com.facebook.presto.operator.scalar.ArrayMinFunction) VisibleForTesting(com.google.common.annotations.VisibleForTesting) ROW_DISTINCT_FROM(com.facebook.presto.operator.scalar.RowDistinctFromOperator.ROW_DISTINCT_FROM) ROW_LESS_THAN(com.facebook.presto.operator.scalar.RowLessThanOperator.ROW_LESS_THAN) OperatorType(com.facebook.presto.spi.function.OperatorType) Type(com.facebook.presto.spi.type.Type) VarcharType(com.facebook.presto.spi.type.VarcharType) TypeSignature.parseTypeSignature(com.facebook.presto.spi.type.TypeSignature.parseTypeSignature) TypeSignature(com.facebook.presto.spi.type.TypeSignature) ArrayList(java.util.ArrayList) PrestoException(com.facebook.presto.spi.PrestoException)

Example 77 with PrestoException

use of com.facebook.presto.spi.PrestoException in project presto by prestodb.

the class SimpleNodeSelector method computeAssignments.

@Override
public SplitPlacementResult computeAssignments(Set<Split> splits, List<RemoteTask> existingTasks) {
    Multimap<Node, Split> assignment = HashMultimap.create();
    NodeMap nodeMap = this.nodeMap.get().get();
    NodeAssignmentStats assignmentStats = new NodeAssignmentStats(nodeTaskMap, nodeMap, existingTasks);
    ResettableRandomizedIterator<Node> randomCandidates = randomizedNodes(nodeMap, includeCoordinator);
    Set<Node> blockedExactNodes = new HashSet<>();
    boolean splitWaitingForAnyNode = false;
    for (Split split : splits) {
        randomCandidates.reset();
        List<Node> candidateNodes;
        if (!split.isRemotelyAccessible()) {
            candidateNodes = selectExactNodes(nodeMap, split.getAddresses(), includeCoordinator);
        } else {
            candidateNodes = selectNodes(minCandidates, randomCandidates);
        }
        if (candidateNodes.isEmpty()) {
            log.debug("No nodes available to schedule %s. Available nodes %s", split, nodeMap.getNodesByHost().keys());
            throw new PrestoException(NO_NODES_AVAILABLE, "No nodes available to run query");
        }
        Node chosenNode = null;
        int min = Integer.MAX_VALUE;
        for (Node node : candidateNodes) {
            int totalSplitCount = assignmentStats.getTotalSplitCount(node);
            if (totalSplitCount < min && totalSplitCount < maxSplitsPerNode) {
                chosenNode = node;
                min = totalSplitCount;
            }
        }
        if (chosenNode == null) {
            // min is guaranteed to be MAX_VALUE at this line
            for (Node node : candidateNodes) {
                int totalSplitCount = assignmentStats.getQueuedSplitCountForStage(node);
                if (totalSplitCount < min && totalSplitCount < maxPendingSplitsPerTask) {
                    chosenNode = node;
                    min = totalSplitCount;
                }
            }
        }
        if (chosenNode != null) {
            assignment.put(chosenNode, split);
            assignmentStats.addAssignedSplit(chosenNode);
        } else {
            if (split.isRemotelyAccessible()) {
                splitWaitingForAnyNode = true;
            } else // Exact node set won't matter, if a split is waiting for any node
            if (!splitWaitingForAnyNode) {
                blockedExactNodes.addAll(candidateNodes);
            }
        }
    }
    ListenableFuture<?> blocked;
    if (splitWaitingForAnyNode) {
        blocked = toWhenHasSplitQueueSpaceFuture(existingTasks, calculateLowWatermark(maxPendingSplitsPerTask));
    } else {
        blocked = toWhenHasSplitQueueSpaceFuture(blockedExactNodes, existingTasks, calculateLowWatermark(maxPendingSplitsPerTask));
    }
    return new SplitPlacementResult(blocked, assignment);
}
Also used : Node(com.facebook.presto.spi.Node) PrestoException(com.facebook.presto.spi.PrestoException) Split(com.facebook.presto.metadata.Split) HashSet(java.util.HashSet)

Example 78 with PrestoException

use of com.facebook.presto.spi.PrestoException in project presto by prestodb.

the class SqlQueryScheduler method schedule.

private void schedule() {
    try (SetThreadName ignored = new SetThreadName("Query-%s", queryStateMachine.getQueryId())) {
        Set<StageId> completedStages = new HashSet<>();
        ExecutionSchedule executionSchedule = executionPolicy.createExecutionSchedule(stages.values());
        while (!executionSchedule.isFinished()) {
            List<ListenableFuture<?>> blockedStages = new ArrayList<>();
            for (SqlStageExecution stage : executionSchedule.getStagesToSchedule()) {
                stage.beginScheduling();
                // perform some scheduling work
                ScheduleResult result = stageSchedulers.get(stage.getStageId()).schedule();
                // modify parent and children based on the results of the scheduling
                if (result.isFinished()) {
                    stage.schedulingComplete();
                } else if (!result.getBlocked().isDone()) {
                    blockedStages.add(result.getBlocked());
                }
                stageLinkages.get(stage.getStageId()).processScheduleResults(stage.getState(), result.getNewTasks());
                schedulerStats.getSplitsScheduledPerIteration().add(result.getSplitsScheduled());
                if (result.getBlockedReason().isPresent()) {
                    switch(result.getBlockedReason().get()) {
                        case WAITING_FOR_SOURCE:
                            schedulerStats.getWaitingForSource().update(1);
                            break;
                        case SPLIT_QUEUES_FULL:
                            schedulerStats.getSplitQueuesFull().update(1);
                            break;
                        default:
                            throw new UnsupportedOperationException("Unknown blocked reason: " + result.getBlockedReason().get());
                    }
                }
            }
            // make sure to update stage linkage at least once per loop to catch async state changes (e.g., partial cancel)
            for (SqlStageExecution stage : stages.values()) {
                if (!completedStages.contains(stage.getStageId()) && stage.getState().isDone()) {
                    stageLinkages.get(stage.getStageId()).processScheduleResults(stage.getState(), ImmutableSet.of());
                    completedStages.add(stage.getStageId());
                }
            }
            // wait for a state change and then schedule again
            if (!blockedStages.isEmpty()) {
                try (TimeStat.BlockTimer timer = schedulerStats.getSleepTime().time()) {
                    tryGetFutureValue(whenAnyComplete(blockedStages), 1, SECONDS);
                }
                for (ListenableFuture<?> blockedStage : blockedStages) {
                    blockedStage.cancel(true);
                }
            }
        }
        for (SqlStageExecution stage : stages.values()) {
            StageState state = stage.getState();
            if (state != SCHEDULED && state != RUNNING && !state.isDone()) {
                throw new PrestoException(GENERIC_INTERNAL_ERROR, format("Scheduling is complete, but stage %s is in state %s", stage.getStageId(), state));
            }
        }
    } catch (Throwable t) {
        queryStateMachine.transitionToFailed(t);
        throw Throwables.propagate(t);
    } finally {
        RuntimeException closeError = new RuntimeException();
        for (StageScheduler scheduler : stageSchedulers.values()) {
            try {
                scheduler.close();
            } catch (Throwable t) {
                queryStateMachine.transitionToFailed(t);
                // Self-suppression not permitted
                if (closeError != t) {
                    closeError.addSuppressed(t);
                }
            }
        }
        if (closeError.getSuppressed().length > 0) {
            throw closeError;
        }
    }
}
Also used : StageId(com.facebook.presto.execution.StageId) ArrayList(java.util.ArrayList) TimeStat(io.airlift.stats.TimeStat) PrestoException(com.facebook.presto.spi.PrestoException) SqlStageExecution(com.facebook.presto.execution.SqlStageExecution) StageState(com.facebook.presto.execution.StageState) SetThreadName(io.airlift.concurrent.SetThreadName) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) HashSet(java.util.HashSet)

Example 79 with PrestoException

use of com.facebook.presto.spi.PrestoException in project presto by prestodb.

the class ClusterMemoryManager method process.

public synchronized void process(Iterable<QueryExecution> queries) {
    if (!enabled) {
        return;
    }
    boolean outOfMemory = isClusterOutOfMemory();
    if (!outOfMemory) {
        lastTimeNotOutOfMemory = System.nanoTime();
    }
    boolean queryKilled = false;
    long totalBytes = 0;
    for (QueryExecution query : queries) {
        long bytes = query.getTotalMemoryReservation();
        DataSize sessionMaxQueryMemory = getQueryMaxMemory(query.getSession());
        long queryMemoryLimit = Math.min(maxQueryMemory.toBytes(), sessionMaxQueryMemory.toBytes());
        totalBytes += bytes;
        if (resourceOvercommit(query.getSession()) && outOfMemory) {
            // If a query has requested resource overcommit, only kill it if the cluster has run out of memory
            DataSize memory = succinctBytes(bytes);
            query.fail(new PrestoException(CLUSTER_OUT_OF_MEMORY, format("The cluster is out of memory and %s=true, so this query was killed. It was using %s of memory", RESOURCE_OVERCOMMIT, memory)));
            queryKilled = true;
        }
        if (!resourceOvercommit(query.getSession()) && bytes > queryMemoryLimit) {
            DataSize maxMemory = succinctBytes(queryMemoryLimit);
            query.fail(exceededGlobalLimit(maxMemory));
            queryKilled = true;
        }
    }
    clusterMemoryUsageBytes.set(totalBytes);
    if (killOnOutOfMemory) {
        boolean shouldKillQuery = nanosSince(lastTimeNotOutOfMemory).compareTo(killOnOutOfMemoryDelay) > 0 && outOfMemory;
        boolean lastKilledQueryIsGone = (lastKilledQuery == null);
        if (!lastKilledQueryIsGone) {
            ClusterMemoryPool generalPool = pools.get(GENERAL_POOL);
            if (generalPool != null) {
                lastKilledQueryIsGone = generalPool.getQueryMemoryReservations().containsKey(lastKilledQuery);
            }
        }
        if (shouldKillQuery && lastKilledQueryIsGone && !queryKilled) {
            // Kill the biggest query in the general pool
            QueryExecution biggestQuery = null;
            long maxMemory = -1;
            for (QueryExecution query : queries) {
                long bytesUsed = query.getTotalMemoryReservation();
                if (bytesUsed > maxMemory && query.getMemoryPool().getId().equals(GENERAL_POOL)) {
                    biggestQuery = query;
                    maxMemory = bytesUsed;
                }
            }
            if (biggestQuery != null) {
                biggestQuery.fail(new PrestoException(CLUSTER_OUT_OF_MEMORY, "The cluster is out of memory, and your query was killed. Please try again in a few minutes."));
                queriesKilledDueToOutOfMemory.incrementAndGet();
                lastKilledQuery = biggestQuery.getQueryId();
            }
        }
    }
    Map<MemoryPoolId, Integer> countByPool = new HashMap<>();
    for (QueryExecution query : queries) {
        MemoryPoolId id = query.getMemoryPool().getId();
        countByPool.put(id, countByPool.getOrDefault(id, 0) + 1);
    }
    updatePools(countByPool);
    updateNodes(updateAssignments(queries));
    // check if CPU usage is over limit
    for (QueryExecution query : queries) {
        Duration cpuTime = query.getTotalCpuTime();
        Duration sessionLimit = getQueryMaxCpuTime(query.getSession());
        Duration limit = maxQueryCpuTime.compareTo(sessionLimit) < 0 ? maxQueryCpuTime : sessionLimit;
        if (cpuTime.compareTo(limit) > 0) {
            query.fail(new ExceededCpuLimitException(limit));
        }
    }
}
Also used : HashMap(java.util.HashMap) DataSize(io.airlift.units.DataSize) PrestoException(com.facebook.presto.spi.PrestoException) Duration(io.airlift.units.Duration) ExceededCpuLimitException(com.facebook.presto.ExceededCpuLimitException) QueryExecution(com.facebook.presto.execution.QueryExecution) MemoryPoolId(com.facebook.presto.spi.memory.MemoryPoolId)

Example 80 with PrestoException

use of com.facebook.presto.spi.PrestoException in project presto by prestodb.

the class SqlTaskManager method failAbandonedTasks.

public void failAbandonedTasks() {
    DateTime now = DateTime.now();
    DateTime oldestAllowedHeartbeat = now.minus(clientTimeout.toMillis());
    for (SqlTask sqlTask : tasks.asMap().values()) {
        try {
            TaskInfo taskInfo = sqlTask.getTaskInfo();
            TaskStatus taskStatus = taskInfo.getTaskStatus();
            if (taskStatus.getState().isDone()) {
                continue;
            }
            DateTime lastHeartbeat = taskInfo.getLastHeartbeat();
            if (lastHeartbeat != null && lastHeartbeat.isBefore(oldestAllowedHeartbeat)) {
                log.info("Failing abandoned task %s", taskStatus.getTaskId());
                sqlTask.failed(new PrestoException(ABANDONED_TASK, format("Task %s has not been accessed since %s: currentTime %s", taskStatus.getTaskId(), lastHeartbeat, now)));
            }
        } catch (RuntimeException e) {
            log.warn(e, "Error while inspecting age of task %s", sqlTask.getTaskId());
        }
    }
}
Also used : PrestoException(com.facebook.presto.spi.PrestoException) DateTime(org.joda.time.DateTime)

Aggregations

PrestoException (com.facebook.presto.spi.PrestoException)273 IOException (java.io.IOException)58 Type (com.facebook.presto.spi.type.Type)48 ImmutableList (com.google.common.collect.ImmutableList)40 SchemaTableName (com.facebook.presto.spi.SchemaTableName)32 ArrayList (java.util.ArrayList)32 List (java.util.List)28 Path (org.apache.hadoop.fs.Path)28 Map (java.util.Map)24 Slice (io.airlift.slice.Slice)23 TableNotFoundException (com.facebook.presto.spi.TableNotFoundException)22 SqlType (com.facebook.presto.spi.function.SqlType)22 ImmutableMap (com.google.common.collect.ImmutableMap)22 Optional (java.util.Optional)20 ColumnMetadata (com.facebook.presto.spi.ColumnMetadata)19 Block (com.facebook.presto.spi.block.Block)19 Test (org.testng.annotations.Test)19 ConnectorSession (com.facebook.presto.spi.ConnectorSession)17 Table (com.facebook.presto.hive.metastore.Table)15 Session (com.facebook.presto.Session)14