Search in sources :

Example 26 with Expression

use of com.facebook.presto.sql.tree.Expression in project presto by prestodb.

the class AstBuilder method visitFunctionCall.

@Override
public Node visitFunctionCall(SqlBaseParser.FunctionCallContext context) {
    Optional<Expression> filter = visitIfPresent(context.filter(), Expression.class);
    Optional<Window> window = visitIfPresent(context.over(), Window.class);
    QualifiedName name = getQualifiedName(context.qualifiedName());
    boolean distinct = isDistinct(context.setQuantifier());
    if (name.toString().equalsIgnoreCase("if")) {
        check(context.expression().size() == 2 || context.expression().size() == 3, "Invalid number of arguments for 'if' function", context);
        check(!window.isPresent(), "OVER clause not valid for 'if' function", context);
        check(!distinct, "DISTINCT not valid for 'if' function", context);
        Expression elseExpression = null;
        if (context.expression().size() == 3) {
            elseExpression = (Expression) visit(context.expression(2));
        }
        return new IfExpression(getLocation(context), (Expression) visit(context.expression(0)), (Expression) visit(context.expression(1)), elseExpression);
    }
    if (name.toString().equalsIgnoreCase("nullif")) {
        check(context.expression().size() == 2, "Invalid number of arguments for 'nullif' function", context);
        check(!window.isPresent(), "OVER clause not valid for 'nullif' function", context);
        check(!distinct, "DISTINCT not valid for 'nullif' function", context);
        return new NullIfExpression(getLocation(context), (Expression) visit(context.expression(0)), (Expression) visit(context.expression(1)));
    }
    if (name.toString().equalsIgnoreCase("coalesce")) {
        check(!window.isPresent(), "OVER clause not valid for 'coalesce' function", context);
        check(!distinct, "DISTINCT not valid for 'coalesce' function", context);
        return new CoalesceExpression(getLocation(context), visit(context.expression(), Expression.class));
    }
    if (name.toString().equalsIgnoreCase("try")) {
        check(context.expression().size() == 1, "The 'try' function must have exactly one argument", context);
        check(!window.isPresent(), "OVER clause not valid for 'try' function", context);
        check(!distinct, "DISTINCT not valid for 'try' function", context);
        return new TryExpression(getLocation(context), (Expression) visit(getOnlyElement(context.expression())));
    }
    return new FunctionCall(getLocation(context), getQualifiedName(context.qualifiedName()), window, filter, distinct, visit(context.expression(), Expression.class));
}
Also used : Window(com.facebook.presto.sql.tree.Window) IfExpression(com.facebook.presto.sql.tree.IfExpression) NullIfExpression(com.facebook.presto.sql.tree.NullIfExpression) SubqueryExpression(com.facebook.presto.sql.tree.SubqueryExpression) SubscriptExpression(com.facebook.presto.sql.tree.SubscriptExpression) LogicalBinaryExpression(com.facebook.presto.sql.tree.LogicalBinaryExpression) SearchedCaseExpression(com.facebook.presto.sql.tree.SearchedCaseExpression) CoalesceExpression(com.facebook.presto.sql.tree.CoalesceExpression) SimpleCaseExpression(com.facebook.presto.sql.tree.SimpleCaseExpression) NotExpression(com.facebook.presto.sql.tree.NotExpression) LambdaExpression(com.facebook.presto.sql.tree.LambdaExpression) IfExpression(com.facebook.presto.sql.tree.IfExpression) QuantifiedComparisonExpression(com.facebook.presto.sql.tree.QuantifiedComparisonExpression) InListExpression(com.facebook.presto.sql.tree.InListExpression) TryExpression(com.facebook.presto.sql.tree.TryExpression) ArithmeticUnaryExpression(com.facebook.presto.sql.tree.ArithmeticUnaryExpression) DereferenceExpression(com.facebook.presto.sql.tree.DereferenceExpression) NullIfExpression(com.facebook.presto.sql.tree.NullIfExpression) ComparisonExpression(com.facebook.presto.sql.tree.ComparisonExpression) Expression(com.facebook.presto.sql.tree.Expression) ArithmeticBinaryExpression(com.facebook.presto.sql.tree.ArithmeticBinaryExpression) QualifiedName(com.facebook.presto.sql.tree.QualifiedName) NullIfExpression(com.facebook.presto.sql.tree.NullIfExpression) FunctionCall(com.facebook.presto.sql.tree.FunctionCall) TryExpression(com.facebook.presto.sql.tree.TryExpression) CoalesceExpression(com.facebook.presto.sql.tree.CoalesceExpression)

Example 27 with Expression

use of com.facebook.presto.sql.tree.Expression in project presto by prestodb.

the class TestSqlParser method testCreateTableAsSelect.

@Test
public void testCreateTableAsSelect() throws Exception {
    Query query = simpleQuery(selectList(new AllColumns()), table(QualifiedName.of("t")));
    QualifiedName table = QualifiedName.of("foo");
    assertStatement("CREATE TABLE foo AS SELECT * FROM t", new CreateTableAsSelect(table, query, false, ImmutableMap.of(), true));
    assertStatement("CREATE TABLE IF NOT EXISTS foo AS SELECT * FROM t", new CreateTableAsSelect(table, query, true, ImmutableMap.of(), true));
    assertStatement("CREATE TABLE foo AS SELECT * FROM t WITH NO DATA", new CreateTableAsSelect(table, query, false, ImmutableMap.of(), false));
    ImmutableMap<String, Expression> properties = ImmutableMap.<String, Expression>builder().put("string", new StringLiteral("bar")).put("long", new LongLiteral("42")).put("computed", new FunctionCall(QualifiedName.of("concat"), ImmutableList.of(new StringLiteral("ban"), new StringLiteral("ana")))).put("a", new ArrayConstructor(ImmutableList.of(new StringLiteral("v1"), new StringLiteral("v2")))).build();
    assertStatement("CREATE TABLE foo " + "WITH ( string = 'bar', long = 42, computed = 'ban' || 'ana', a  = ARRAY[ 'v1', 'v2' ] ) " + "AS " + "SELECT * FROM t", new CreateTableAsSelect(table, query, false, properties, true));
    assertStatement("CREATE TABLE foo " + "WITH ( string = 'bar', long = 42, computed = 'ban' || 'ana', a  = ARRAY[ 'v1', 'v2' ] ) " + "AS " + "SELECT * FROM t " + "WITH NO DATA", new CreateTableAsSelect(table, query, false, properties, false));
}
Also used : Query(com.facebook.presto.sql.tree.Query) QueryUtil.simpleQuery(com.facebook.presto.sql.QueryUtil.simpleQuery) WithQuery(com.facebook.presto.sql.tree.WithQuery) StringLiteral(com.facebook.presto.sql.tree.StringLiteral) LongLiteral(com.facebook.presto.sql.tree.LongLiteral) SubqueryExpression(com.facebook.presto.sql.tree.SubqueryExpression) SubscriptExpression(com.facebook.presto.sql.tree.SubscriptExpression) LogicalBinaryExpression(com.facebook.presto.sql.tree.LogicalBinaryExpression) NotExpression(com.facebook.presto.sql.tree.NotExpression) LambdaExpression(com.facebook.presto.sql.tree.LambdaExpression) QuantifiedComparisonExpression(com.facebook.presto.sql.tree.QuantifiedComparisonExpression) DereferenceExpression(com.facebook.presto.sql.tree.DereferenceExpression) ComparisonExpression(com.facebook.presto.sql.tree.ComparisonExpression) Expression(com.facebook.presto.sql.tree.Expression) ArithmeticBinaryExpression(com.facebook.presto.sql.tree.ArithmeticBinaryExpression) QualifiedName(com.facebook.presto.sql.tree.QualifiedName) CreateTableAsSelect(com.facebook.presto.sql.tree.CreateTableAsSelect) ArrayConstructor(com.facebook.presto.sql.tree.ArrayConstructor) AllColumns(com.facebook.presto.sql.tree.AllColumns) FunctionCall(com.facebook.presto.sql.tree.FunctionCall) Test(org.testng.annotations.Test)

Example 28 with Expression

use of com.facebook.presto.sql.tree.Expression in project presto by prestodb.

the class AbstractPropertyManager method getProperties.

public final Map<String, Object> getProperties(ConnectorId connectorId, // only use this for error messages
String catalog, Map<String, Expression> sqlPropertyValues, Session session, Metadata metadata, List<Expression> parameters) {
    Map<String, PropertyMetadata<?>> supportedProperties = connectorProperties.get(connectorId);
    if (supportedProperties == null) {
        throw new PrestoException(NOT_FOUND, "Catalog not found: " + catalog);
    }
    ImmutableMap.Builder<String, Object> properties = ImmutableMap.builder();
    // Fill in user-specified properties
    for (Map.Entry<String, Expression> sqlProperty : sqlPropertyValues.entrySet()) {
        String propertyName = sqlProperty.getKey().toLowerCase(ENGLISH);
        PropertyMetadata<?> property = supportedProperties.get(propertyName);
        if (property == null) {
            throw new PrestoException(propertyError, format("Catalog '%s' does not support %s property '%s'", catalog, propertyType, propertyName));
        }
        Object sqlObjectValue;
        try {
            sqlObjectValue = evaluatePropertyValue(sqlProperty.getValue(), property.getSqlType(), session, metadata, parameters);
        } catch (SemanticException e) {
            throw new PrestoException(propertyError, format("Invalid value for %s property '%s': Cannot convert '%s' to %s", propertyType, property.getName(), sqlProperty.getValue(), property.getSqlType()), e);
        }
        Object value;
        try {
            value = property.decode(sqlObjectValue);
        } catch (Exception e) {
            throw new PrestoException(propertyError, format("Unable to set %s property '%s' to '%s': %s", propertyType, property.getName(), sqlProperty.getValue(), e.getMessage()), e);
        }
        properties.put(property.getName(), value);
    }
    Map<String, Object> userSpecifiedProperties = properties.build();
    // Fill in the remaining properties with non-null defaults
    for (PropertyMetadata<?> propertyMetadata : supportedProperties.values()) {
        if (!userSpecifiedProperties.containsKey(propertyMetadata.getName())) {
            Object value = propertyMetadata.getDefaultValue();
            if (value != null) {
                properties.put(propertyMetadata.getName(), value);
            }
        }
    }
    return properties.build();
}
Also used : PrestoException(com.facebook.presto.spi.PrestoException) ImmutableMap(com.google.common.collect.ImmutableMap) PrestoException(com.facebook.presto.spi.PrestoException) SemanticException(com.facebook.presto.sql.analyzer.SemanticException) ExpressionInterpreter.evaluateConstantExpression(com.facebook.presto.sql.planner.ExpressionInterpreter.evaluateConstantExpression) Expression(com.facebook.presto.sql.tree.Expression) PropertyMetadata(com.facebook.presto.spi.session.PropertyMetadata) ConcurrentMap(java.util.concurrent.ConcurrentMap) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) SemanticException(com.facebook.presto.sql.analyzer.SemanticException)

Example 29 with Expression

use of com.facebook.presto.sql.tree.Expression in project presto by prestodb.

the class ExpressionUtils method binaryExpression.

public static Expression binaryExpression(LogicalBinaryExpression.Type type, Collection<Expression> expressions) {
    requireNonNull(type, "type is null");
    requireNonNull(expressions, "expressions is null");
    Preconditions.checkArgument(!expressions.isEmpty(), "expressions is empty");
    // Build balanced tree for efficient recursive processing that
    // preserves the evaluation order of the input expressions.
    //
    // The tree is built bottom up by combining pairs of elements into
    // binary AND expressions.
    //
    // Example:
    //
    // Initial state:
    //  a b c d e
    //
    // First iteration:
    //
    //  /\    /\   e
    // a  b  c  d
    //
    // Second iteration:
    //
    //    / \    e
    //  /\   /\
    // a  b c  d
    //
    //
    // Last iteration:
    //
    //      / \
    //    / \  e
    //  /\   /\
    // a  b c  d
    Queue<Expression> queue = new ArrayDeque<>(expressions);
    while (queue.size() > 1) {
        Queue<Expression> buffer = new ArrayDeque<>();
        // combine pairs of elements
        while (queue.size() >= 2) {
            buffer.add(new LogicalBinaryExpression(type, queue.remove(), queue.remove()));
        }
        // if there's and odd number of elements, just append the last one
        if (!queue.isEmpty()) {
            buffer.add(queue.remove());
        }
        // continue processing the pairs that were just built
        queue = buffer;
    }
    return queue.remove();
}
Also used : LogicalBinaryExpression(com.facebook.presto.sql.tree.LogicalBinaryExpression) NotExpression(com.facebook.presto.sql.tree.NotExpression) LambdaExpression(com.facebook.presto.sql.tree.LambdaExpression) ComparisonExpression(com.facebook.presto.sql.tree.ComparisonExpression) LogicalBinaryExpression(com.facebook.presto.sql.tree.LogicalBinaryExpression) Expression(com.facebook.presto.sql.tree.Expression) ArrayDeque(java.util.ArrayDeque)

Example 30 with Expression

use of com.facebook.presto.sql.tree.Expression in project presto by prestodb.

the class ExpressionAnalyzer method analyzeExpressions.

private static ExpressionAnalysis analyzeExpressions(Session session, Metadata metadata, SqlParser sqlParser, RelationType tupleDescriptor, Map<Symbol, Type> types, Iterable<? extends Expression> expressions, List<Expression> parameters, boolean isDescribe) {
    // expressions at this point can not have sub queries so deny all access checks
    // in the future, we will need a full access controller here to verify access to functions
    Analysis analysis = new Analysis(null, parameters, isDescribe);
    ExpressionAnalyzer analyzer = create(analysis, session, metadata, sqlParser, new DenyAllAccessControl(), types);
    for (Expression expression : expressions) {
        analyzer.analyze(expression, Scope.builder().withRelationType(tupleDescriptor).build());
    }
    return new ExpressionAnalysis(analyzer.getExpressionTypes(), analyzer.getExpressionCoercions(), analyzer.getSubqueryInPredicates(), analyzer.getScalarSubqueries(), analyzer.getExistsSubqueries(), analyzer.getColumnReferences(), analyzer.getTypeOnlyCoercions(), analyzer.getQuantifiedComparisons(), analyzer.getLambdaArgumentReferences());
}
Also used : DenyAllAccessControl(com.facebook.presto.security.DenyAllAccessControl) SubqueryExpression(com.facebook.presto.sql.tree.SubqueryExpression) SubscriptExpression(com.facebook.presto.sql.tree.SubscriptExpression) LogicalBinaryExpression(com.facebook.presto.sql.tree.LogicalBinaryExpression) SearchedCaseExpression(com.facebook.presto.sql.tree.SearchedCaseExpression) CoalesceExpression(com.facebook.presto.sql.tree.CoalesceExpression) SimpleCaseExpression(com.facebook.presto.sql.tree.SimpleCaseExpression) NotExpression(com.facebook.presto.sql.tree.NotExpression) LambdaExpression(com.facebook.presto.sql.tree.LambdaExpression) IfExpression(com.facebook.presto.sql.tree.IfExpression) QuantifiedComparisonExpression(com.facebook.presto.sql.tree.QuantifiedComparisonExpression) InListExpression(com.facebook.presto.sql.tree.InListExpression) TryExpression(com.facebook.presto.sql.tree.TryExpression) ArithmeticUnaryExpression(com.facebook.presto.sql.tree.ArithmeticUnaryExpression) DereferenceExpression(com.facebook.presto.sql.tree.DereferenceExpression) NullIfExpression(com.facebook.presto.sql.tree.NullIfExpression) ComparisonExpression(com.facebook.presto.sql.tree.ComparisonExpression) Expression(com.facebook.presto.sql.tree.Expression) ArithmeticBinaryExpression(com.facebook.presto.sql.tree.ArithmeticBinaryExpression)

Aggregations

Expression (com.facebook.presto.sql.tree.Expression)137 ComparisonExpression (com.facebook.presto.sql.tree.ComparisonExpression)74 Test (org.testng.annotations.Test)46 NotExpression (com.facebook.presto.sql.tree.NotExpression)42 InListExpression (com.facebook.presto.sql.tree.InListExpression)40 DereferenceExpression (com.facebook.presto.sql.tree.DereferenceExpression)33 Type (com.facebook.presto.spi.type.Type)26 PlanNode (com.facebook.presto.sql.planner.plan.PlanNode)26 LiteralInterpreter.toExpression (com.facebook.presto.sql.planner.LiteralInterpreter.toExpression)25 LogicalBinaryExpression (com.facebook.presto.sql.tree.LogicalBinaryExpression)22 ImmutableList (com.google.common.collect.ImmutableList)22 LambdaExpression (com.facebook.presto.sql.tree.LambdaExpression)19 ArithmeticBinaryExpression (com.facebook.presto.sql.tree.ArithmeticBinaryExpression)18 Cast (com.facebook.presto.sql.tree.Cast)17 ArrayList (java.util.ArrayList)17 ExtractionResult (com.facebook.presto.sql.planner.DomainTranslator.ExtractionResult)16 CoalesceExpression (com.facebook.presto.sql.tree.CoalesceExpression)16 SubqueryExpression (com.facebook.presto.sql.tree.SubqueryExpression)16 SubscriptExpression (com.facebook.presto.sql.tree.SubscriptExpression)16 QuantifiedComparisonExpression (com.facebook.presto.sql.tree.QuantifiedComparisonExpression)15