use of com.facebook.presto.sql.tree.NodeRef in project presto by prestodb.
the class SimplifyExpressions method rewrite.
@VisibleForTesting
static Expression rewrite(Expression expression, Session session, PlanVariableAllocator variableAllocator, Metadata metadata, LiteralEncoder literalEncoder, SqlParser sqlParser) {
requireNonNull(metadata, "metadata is null");
requireNonNull(sqlParser, "sqlParser is null");
if (expression instanceof SymbolReference) {
return expression;
}
expression = pushDownNegations(expression);
expression = extractCommonPredicates(expression);
Map<NodeRef<Expression>, Type> expressionTypes = getExpressionTypes(session, metadata, sqlParser, variableAllocator.getTypes(), expression, emptyList(), WarningCollector.NOOP);
ExpressionInterpreter interpreter = ExpressionInterpreter.expressionOptimizer(expression, metadata, session, expressionTypes);
return literalEncoder.toExpression(interpreter.optimize(NoOpVariableResolver.INSTANCE), expressionTypes.get(NodeRef.of(expression)));
}
use of com.facebook.presto.sql.tree.NodeRef in project presto by prestodb.
the class FilterStatsCalculator method simplifyExpression.
private Expression simplifyExpression(Session session, Expression predicate, TypeProvider types) {
// TODO reuse com.facebook.presto.sql.planner.iterative.rule.SimplifyExpressions.rewrite
Map<NodeRef<Expression>, Type> expressionTypes = getExpressionTypes(session, predicate, types);
ExpressionInterpreter interpreter = ExpressionInterpreter.expressionOptimizer(predicate, metadata, session, expressionTypes);
Object value = interpreter.optimize(NoOpVariableResolver.INSTANCE);
if (value == null) {
// Expression evaluates to SQL null, which in Filter is equivalent to false. This assumes the expression is a top-level expression (eg. not in NOT).
value = false;
}
return literalEncoder.toExpression(value, BOOLEAN);
}
use of com.facebook.presto.sql.tree.NodeRef in project presto by prestodb.
the class FunctionAssertions method interpret.
private Object interpret(Expression expression, Type expectedType, Session session) {
Map<NodeRef<Expression>, Type> expressionTypes = getExpressionTypes(session, metadata, SQL_PARSER, SYMBOL_TYPES, expression, emptyList(), WarningCollector.NOOP);
ExpressionInterpreter evaluator = ExpressionInterpreter.expressionInterpreter(expression, metadata, session, expressionTypes);
Object result = evaluator.evaluate(variable -> {
Symbol symbol = new Symbol(variable.getName());
int position = 0;
int channel = INPUT_MAPPING.get(new VariableReferenceExpression(Optional.empty(), symbol.getName(), SYMBOL_TYPES.get(symbol.toSymbolReference())));
Type type = SYMBOL_TYPES.get(symbol.toSymbolReference());
Block block = SOURCE_PAGE.getBlock(channel);
if (block.isNull(position)) {
return null;
}
Class<?> javaType = type.getJavaType();
if (javaType == boolean.class) {
return type.getBoolean(block, position);
} else if (javaType == long.class) {
return type.getLong(block, position);
} else if (javaType == double.class) {
return type.getDouble(block, position);
} else if (javaType == Slice.class) {
return type.getSlice(block, position);
} else if (javaType == Block.class) {
return type.getObject(block, position);
} else {
throw new UnsupportedOperationException("not yet implemented");
}
});
// convert result from stack type to Type ObjectValue
Block block = Utils.nativeValueToBlock(expectedType, result);
return expectedType.getObjectValue(session.getSqlFunctionProperties(), block, 0);
}
use of com.facebook.presto.sql.tree.NodeRef in project presto by prestodb.
the class TestInlineSqlFunctions method assertInlined.
private void assertInlined(RuleTester tester, String inputSql, String expected, Map<String, Type> variableTypes) {
Session session = TestingSession.testSessionBuilder().setSystemProperty("inline_sql_functions", "true").build();
Metadata metadata = tester.getMetadata();
Expression inputSqlExpression = PlanBuilder.expression(inputSql);
Map<NodeRef<Expression>, Type> expressionTypes = getExpressionTypes(session, metadata, tester.getSqlParser(), viewOf(variableTypes), inputSqlExpression, ImmutableList.of(), WarningCollector.NOOP);
Expression inlinedExpression = InlineSqlFunctions.InlineSqlFunctionsRewriter.rewrite(inputSqlExpression, session, metadata, new PlanVariableAllocator(variableTypes.entrySet().stream().map(entry -> new VariableReferenceExpression(Optional.empty(), entry.getKey(), entry.getValue())).collect(toImmutableList())), expressionTypes);
inlinedExpression = ExpressionUtils.rewriteIdentifiersToSymbolReferences(inlinedExpression);
Expression expectedExpression = PlanBuilder.expression(expected);
assertEquals(inlinedExpression, expectedExpression);
}
use of com.facebook.presto.sql.tree.NodeRef in project presto by prestodb.
the class TranslateExpressions method createRewriter.
private static PlanRowExpressionRewriter createRewriter(Metadata metadata, SqlParser sqlParser) {
return new PlanRowExpressionRewriter() {
@Override
public RowExpression rewrite(RowExpression expression, Rule.Context context) {
// special treatment of the CallExpression in Aggregation
if (expression instanceof CallExpression && ((CallExpression) expression).getArguments().stream().anyMatch(OriginalExpressionUtils::isExpression)) {
return removeOriginalExpressionArguments((CallExpression) expression, context.getSession(), context.getVariableAllocator());
}
return removeOriginalExpression(expression, context);
}
private RowExpression removeOriginalExpressionArguments(CallExpression callExpression, Session session, PlanVariableAllocator variableAllocator) {
Map<NodeRef<Expression>, Type> types = analyzeCallExpressionTypes(callExpression, session, variableAllocator.getTypes());
return new CallExpression(callExpression.getSourceLocation(), callExpression.getDisplayName(), callExpression.getFunctionHandle(), callExpression.getType(), callExpression.getArguments().stream().map(expression -> removeOriginalExpression(expression, session, types)).collect(toImmutableList()));
}
private Map<NodeRef<Expression>, Type> analyzeCallExpressionTypes(CallExpression callExpression, Session session, TypeProvider typeProvider) {
List<LambdaExpression> lambdaExpressions = callExpression.getArguments().stream().filter(OriginalExpressionUtils::isExpression).map(OriginalExpressionUtils::castToExpression).filter(LambdaExpression.class::isInstance).map(LambdaExpression.class::cast).collect(toImmutableList());
ImmutableMap.Builder<NodeRef<Expression>, Type> builder = ImmutableMap.<NodeRef<Expression>, Type>builder();
if (!lambdaExpressions.isEmpty()) {
List<FunctionType> functionTypes = metadata.getFunctionAndTypeManager().getFunctionMetadata(callExpression.getFunctionHandle()).getArgumentTypes().stream().filter(typeSignature -> typeSignature.getBase().equals(FunctionType.NAME)).map(typeSignature -> (FunctionType) (metadata.getFunctionAndTypeManager().getType(typeSignature))).collect(toImmutableList());
InternalAggregationFunction internalAggregationFunction = metadata.getFunctionAndTypeManager().getAggregateFunctionImplementation(callExpression.getFunctionHandle());
List<Class> lambdaInterfaces = internalAggregationFunction.getLambdaInterfaces();
verify(lambdaExpressions.size() == functionTypes.size());
verify(lambdaExpressions.size() == lambdaInterfaces.size());
for (int i = 0; i < lambdaExpressions.size(); i++) {
LambdaExpression lambdaExpression = lambdaExpressions.get(i);
FunctionType functionType = functionTypes.get(i);
// To compile lambda, LambdaDefinitionExpression needs to be generated from LambdaExpression,
// which requires the types of all sub-expressions.
//
// In project and filter expression compilation, ExpressionAnalyzer.getExpressionTypesFromInput
// is used to generate the types of all sub-expressions. (see visitScanFilterAndProject and visitFilter)
//
// This does not work here since the function call representation in final aggregation node
// is currently a hack: it takes intermediate type as input, and may not be a valid
// function call in Presto.
//
// TODO: Once the final aggregation function call representation is fixed,
// the same mechanism in project and filter expression should be used here.
verify(lambdaExpression.getArguments().size() == functionType.getArgumentTypes().size());
Map<NodeRef<Expression>, Type> lambdaArgumentExpressionTypes = new HashMap<>();
Map<String, Type> lambdaArgumentSymbolTypes = new HashMap<>();
for (int j = 0; j < lambdaExpression.getArguments().size(); j++) {
LambdaArgumentDeclaration argument = lambdaExpression.getArguments().get(j);
Type type = functionType.getArgumentTypes().get(j);
lambdaArgumentExpressionTypes.put(NodeRef.of(argument), type);
lambdaArgumentSymbolTypes.put(argument.getName().getValue(), type);
}
// the lambda expression itself
builder.put(NodeRef.of(lambdaExpression), functionType).putAll(lambdaArgumentExpressionTypes).putAll(getExpressionTypes(session, metadata, sqlParser, TypeProvider.copyOf(lambdaArgumentSymbolTypes), lambdaExpression.getBody(), emptyList(), NOOP));
}
}
for (RowExpression argument : callExpression.getArguments()) {
if (!isExpression(argument) || castToExpression(argument) instanceof LambdaExpression) {
continue;
}
builder.putAll(analyze(castToExpression(argument), session, typeProvider));
}
return builder.build();
}
private Map<NodeRef<Expression>, Type> analyze(Expression expression, Session session, TypeProvider typeProvider) {
return getExpressionTypes(session, metadata, sqlParser, typeProvider, expression, emptyList(), NOOP);
}
private RowExpression toRowExpression(Expression expression, Session session, Map<NodeRef<Expression>, Type> types) {
return SqlToRowExpressionTranslator.translate(expression, types, ImmutableMap.of(), metadata.getFunctionAndTypeManager(), session);
}
private RowExpression removeOriginalExpression(RowExpression expression, Rule.Context context) {
if (isExpression(expression)) {
return toRowExpression(castToExpression(expression), context.getSession(), analyze(castToExpression(expression), context.getSession(), context.getVariableAllocator().getTypes()));
}
return expression;
}
private RowExpression removeOriginalExpression(RowExpression rowExpression, Session session, Map<NodeRef<Expression>, Type> types) {
if (isExpression(rowExpression)) {
Expression expression = castToExpression(rowExpression);
return toRowExpression(expression, session, types);
}
return rowExpression;
}
};
}
Aggregations