Search in sources :

Example 1 with BooleanLiteral

use of io.trino.sql.tree.BooleanLiteral in project trino by trinodb.

the class LiteralEncoder method toExpression.

public Expression toExpression(Session session, Object object, Type type) {
    requireNonNull(type, "type is null");
    if (object instanceof Expression) {
        return (Expression) object;
    }
    if (object == null) {
        if (type.equals(UNKNOWN)) {
            return new NullLiteral();
        }
        return new Cast(new NullLiteral(), toSqlType(type), false, true);
    }
    checkArgument(Primitives.wrap(type.getJavaType()).isInstance(object), "object.getClass (%s) and type.getJavaType (%s) do not agree", object.getClass(), type.getJavaType());
    if (type.equals(TINYINT)) {
        return new GenericLiteral("TINYINT", object.toString());
    }
    if (type.equals(SMALLINT)) {
        return new GenericLiteral("SMALLINT", object.toString());
    }
    if (type.equals(INTEGER)) {
        return new LongLiteral(object.toString());
    }
    if (type.equals(BIGINT)) {
        LongLiteral expression = new LongLiteral(object.toString());
        if (expression.getValue() >= Integer.MIN_VALUE && expression.getValue() <= Integer.MAX_VALUE) {
            return new GenericLiteral("BIGINT", object.toString());
        }
        return new LongLiteral(object.toString());
    }
    if (type.equals(DOUBLE)) {
        Double value = (Double) object;
        if (value.isNaN()) {
            return FunctionCallBuilder.resolve(session, plannerContext.getMetadata()).setName(QualifiedName.of("nan")).build();
        }
        if (value.equals(Double.NEGATIVE_INFINITY)) {
            return ArithmeticUnaryExpression.negative(FunctionCallBuilder.resolve(session, plannerContext.getMetadata()).setName(QualifiedName.of("infinity")).build());
        }
        if (value.equals(Double.POSITIVE_INFINITY)) {
            return FunctionCallBuilder.resolve(session, plannerContext.getMetadata()).setName(QualifiedName.of("infinity")).build();
        }
        return new DoubleLiteral(object.toString());
    }
    if (type.equals(REAL)) {
        Float value = intBitsToFloat(((Long) object).intValue());
        if (value.isNaN()) {
            return new Cast(FunctionCallBuilder.resolve(session, plannerContext.getMetadata()).setName(QualifiedName.of("nan")).build(), toSqlType(REAL));
        }
        if (value.equals(Float.NEGATIVE_INFINITY)) {
            return ArithmeticUnaryExpression.negative(new Cast(FunctionCallBuilder.resolve(session, plannerContext.getMetadata()).setName(QualifiedName.of("infinity")).build(), toSqlType(REAL)));
        }
        if (value.equals(Float.POSITIVE_INFINITY)) {
            return new Cast(FunctionCallBuilder.resolve(session, plannerContext.getMetadata()).setName(QualifiedName.of("infinity")).build(), toSqlType(REAL));
        }
        return new GenericLiteral("REAL", value.toString());
    }
    if (type instanceof DecimalType) {
        String string;
        if (isShortDecimal(type)) {
            string = Decimals.toString((long) object, ((DecimalType) type).getScale());
        } else {
            string = Decimals.toString((Int128) object, ((DecimalType) type).getScale());
        }
        return new Cast(new DecimalLiteral(string), toSqlType(type));
    }
    if (type instanceof VarcharType) {
        VarcharType varcharType = (VarcharType) type;
        Slice value = (Slice) object;
        if (varcharType.isUnbounded()) {
            return new GenericLiteral("VARCHAR", value.toStringUtf8());
        }
        StringLiteral stringLiteral = new StringLiteral(value.toStringUtf8());
        int boundedLength = varcharType.getBoundedLength();
        int valueLength = SliceUtf8.countCodePoints(value);
        if (boundedLength == valueLength) {
            return stringLiteral;
        }
        if (boundedLength > valueLength) {
            return new Cast(stringLiteral, toSqlType(type), false, true);
        }
        throw new IllegalArgumentException(format("Value [%s] does not fit in type %s", value.toStringUtf8(), varcharType));
    }
    if (type instanceof CharType) {
        StringLiteral stringLiteral = new StringLiteral(((Slice) object).toStringUtf8());
        return new Cast(stringLiteral, toSqlType(type), false, true);
    }
    if (type.equals(BOOLEAN)) {
        return new BooleanLiteral(object.toString());
    }
    if (type.equals(DATE)) {
        return new GenericLiteral("DATE", new SqlDate(toIntExact((Long) object)).toString());
    }
    if (type instanceof TimestampType) {
        TimestampType timestampType = (TimestampType) type;
        String representation;
        if (timestampType.isShort()) {
            representation = TimestampToVarcharCast.cast(timestampType.getPrecision(), (Long) object).toStringUtf8();
        } else {
            representation = TimestampToVarcharCast.cast(timestampType.getPrecision(), (LongTimestamp) object).toStringUtf8();
        }
        return new TimestampLiteral(representation);
    }
    if (type instanceof TimestampWithTimeZoneType) {
        TimestampWithTimeZoneType timestampWithTimeZoneType = (TimestampWithTimeZoneType) type;
        String representation;
        if (timestampWithTimeZoneType.isShort()) {
            representation = TimestampWithTimeZoneToVarcharCast.cast(timestampWithTimeZoneType.getPrecision(), (long) object).toStringUtf8();
        } else {
            representation = TimestampWithTimeZoneToVarcharCast.cast(timestampWithTimeZoneType.getPrecision(), (LongTimestampWithTimeZone) object).toStringUtf8();
        }
        if (!object.equals(parseTimestampWithTimeZone(timestampWithTimeZoneType.getPrecision(), representation))) {
        // Certain (point in time, time zone) pairs cannot be represented as a TIMESTAMP literal, as the literal uses local date/time in given time zone.
        // Thus, during DST backwards change by e.g. 1 hour, the local time is "repeated" twice and thus one local date/time logically corresponds to two
        // points in time, leaving one of them non-referencable.
        // TODO (https://github.com/trinodb/trino/issues/5781) consider treating such values as illegal
        } else {
            return new TimestampLiteral(representation);
        }
    }
    // If the stack value is not a simple type, encode the stack value in a block
    if (!type.getJavaType().isPrimitive() && type.getJavaType() != Slice.class && type.getJavaType() != Block.class) {
        object = nativeValueToBlock(type, object);
    }
    if (object instanceof Block) {
        SliceOutput output = new DynamicSliceOutput(toIntExact(((Block) object).getSizeInBytes()));
        BlockSerdeUtil.writeBlock(plannerContext.getBlockEncodingSerde(), output, (Block) object);
        object = output.slice();
    // This if condition will evaluate to true: object instanceof Slice && !type.equals(VARCHAR)
    }
    Type argumentType = typeForMagicLiteral(type);
    Expression argument;
    if (object instanceof Slice) {
        // HACK: we need to serialize VARBINARY in a format that can be embedded in an expression to be
        // able to encode it in the plan that gets sent to workers.
        // We do this by transforming the in-memory varbinary into a call to from_base64(<base64-encoded value>)
        Slice encoded = VarbinaryFunctions.toBase64((Slice) object);
        argument = FunctionCallBuilder.resolve(session, plannerContext.getMetadata()).setName(QualifiedName.of("from_base64")).addArgument(VARCHAR, new StringLiteral(encoded.toStringUtf8())).build();
    } else {
        argument = toExpression(session, object, argumentType);
    }
    ResolvedFunction resolvedFunction = plannerContext.getMetadata().getCoercion(session, QualifiedName.of(LITERAL_FUNCTION_NAME), argumentType, type);
    return FunctionCallBuilder.resolve(session, plannerContext.getMetadata()).setName(resolvedFunction.toQualifiedName()).addArgument(argumentType, argument).build();
}
Also used : TimestampWithTimeZoneToVarcharCast(io.trino.operator.scalar.timestamptz.TimestampWithTimeZoneToVarcharCast) TimestampToVarcharCast(io.trino.operator.scalar.timestamp.TimestampToVarcharCast) Cast(io.trino.sql.tree.Cast) SliceOutput(io.airlift.slice.SliceOutput) DynamicSliceOutput(io.airlift.slice.DynamicSliceOutput) VarcharType(io.trino.spi.type.VarcharType) BooleanLiteral(io.trino.sql.tree.BooleanLiteral) GenericLiteral(io.trino.sql.tree.GenericLiteral) DecimalLiteral(io.trino.sql.tree.DecimalLiteral) TimestampWithTimeZoneType(io.trino.spi.type.TimestampWithTimeZoneType) TimestampType(io.trino.spi.type.TimestampType) DynamicSliceOutput(io.airlift.slice.DynamicSliceOutput) Int128(io.trino.spi.type.Int128) TimestampLiteral(io.trino.sql.tree.TimestampLiteral) LongLiteral(io.trino.sql.tree.LongLiteral) ResolvedFunction(io.trino.metadata.ResolvedFunction) Float.intBitsToFloat(java.lang.Float.intBitsToFloat) TimestampWithTimeZoneType(io.trino.spi.type.TimestampWithTimeZoneType) TypeSignatureTranslator.toSqlType(io.trino.sql.analyzer.TypeSignatureTranslator.toSqlType) DecimalType(io.trino.spi.type.DecimalType) Type(io.trino.spi.type.Type) TimestampType(io.trino.spi.type.TimestampType) VarcharType(io.trino.spi.type.VarcharType) CharType(io.trino.spi.type.CharType) StringLiteral(io.trino.sql.tree.StringLiteral) ArithmeticUnaryExpression(io.trino.sql.tree.ArithmeticUnaryExpression) Expression(io.trino.sql.tree.Expression) Slice(io.airlift.slice.Slice) SqlDate(io.trino.spi.type.SqlDate) DecimalType(io.trino.spi.type.DecimalType) Utils.nativeValueToBlock(io.trino.spi.predicate.Utils.nativeValueToBlock) Block(io.trino.spi.block.Block) DoubleLiteral(io.trino.sql.tree.DoubleLiteral) CharType(io.trino.spi.type.CharType) NullLiteral(io.trino.sql.tree.NullLiteral)

Example 2 with BooleanLiteral

use of io.trino.sql.tree.BooleanLiteral in project trino by trinodb.

the class DynamicFilters method getDescriptor.

public static Optional<Descriptor> getDescriptor(Expression expression) {
    if (!(expression instanceof FunctionCall)) {
        return Optional.empty();
    }
    FunctionCall functionCall = (FunctionCall) expression;
    if (!isDynamicFilterFunction(functionCall)) {
        return Optional.empty();
    }
    List<Expression> arguments = functionCall.getArguments();
    checkArgument(arguments.size() == 4, "invalid arguments count: %s", arguments.size());
    Expression probeSymbol = arguments.get(0);
    Expression operatorExpression = arguments.get(1);
    checkArgument(operatorExpression instanceof StringLiteral, "operatorExpression is expected to be an instance of StringLiteral: %s", operatorExpression.getClass().getSimpleName());
    String operatorExpressionString = ((StringLiteral) operatorExpression).getValue();
    ComparisonExpression.Operator operator = ComparisonExpression.Operator.valueOf(operatorExpressionString);
    Expression idExpression = arguments.get(2);
    checkArgument(idExpression instanceof StringLiteral, "id is expected to be an instance of StringLiteral: %s", idExpression.getClass().getSimpleName());
    String id = ((StringLiteral) idExpression).getValue();
    Expression nullAllowedExpression = arguments.get(3);
    checkArgument(nullAllowedExpression instanceof BooleanLiteral, "nullAllowedExpression is expected to be an instance of BooleanLiteral: %s", nullAllowedExpression.getClass().getSimpleName());
    boolean nullAllowed = ((BooleanLiteral) nullAllowedExpression).getValue();
    return Optional.of(new Descriptor(new DynamicFilterId(id), probeSymbol, operator, nullAllowed));
}
Also used : ComparisonExpression(io.trino.sql.tree.ComparisonExpression) StringLiteral(io.trino.sql.tree.StringLiteral) ComparisonExpression(io.trino.sql.tree.ComparisonExpression) Expression(io.trino.sql.tree.Expression) BooleanLiteral(io.trino.sql.tree.BooleanLiteral) FunctionCall(io.trino.sql.tree.FunctionCall) DynamicFilterId(io.trino.sql.planner.plan.DynamicFilterId)

Example 3 with BooleanLiteral

use of io.trino.sql.tree.BooleanLiteral in project trino by trinodb.

the class TestSqlParser method testListagg.

@Test
public void testListagg() {
    assertExpression("LISTAGG(x) WITHIN GROUP (ORDER BY x)", new FunctionCall(Optional.empty(), QualifiedName.of("LISTAGG"), Optional.empty(), Optional.empty(), Optional.of(new OrderBy(ImmutableList.of(new SortItem(new Identifier("x", false), ASCENDING, UNDEFINED)))), false, Optional.empty(), Optional.empty(), ImmutableList.of(identifier("x"), new StringLiteral(""), new BooleanLiteral("true"), new StringLiteral("..."), new BooleanLiteral("false"))));
    assertExpression("LISTAGG( DISTINCT x) WITHIN GROUP (ORDER BY x)", new FunctionCall(Optional.empty(), QualifiedName.of("LISTAGG"), Optional.empty(), Optional.empty(), Optional.of(new OrderBy(ImmutableList.of(new SortItem(new Identifier("x", false), ASCENDING, UNDEFINED)))), true, Optional.empty(), Optional.empty(), ImmutableList.of(identifier("x"), new StringLiteral(""), new BooleanLiteral("true"), new StringLiteral("..."), new BooleanLiteral("false"))));
    assertExpression("LISTAGG(x, ',') WITHIN GROUP (ORDER BY y)", new FunctionCall(Optional.empty(), QualifiedName.of("LISTAGG"), Optional.empty(), Optional.empty(), Optional.of(new OrderBy(ImmutableList.of(new SortItem(new Identifier("y", false), ASCENDING, UNDEFINED)))), false, Optional.empty(), Optional.empty(), ImmutableList.of(identifier("x"), new StringLiteral(","), new BooleanLiteral("true"), new StringLiteral("..."), new BooleanLiteral("false"))));
    assertExpression("LISTAGG(x, ',' ON OVERFLOW ERROR) WITHIN GROUP (ORDER BY x)", new FunctionCall(Optional.empty(), QualifiedName.of("LISTAGG"), Optional.empty(), Optional.empty(), Optional.of(new OrderBy(ImmutableList.of(new SortItem(new Identifier("x", false), ASCENDING, UNDEFINED)))), false, Optional.empty(), Optional.empty(), ImmutableList.of(identifier("x"), new StringLiteral(","), new BooleanLiteral("true"), new StringLiteral("..."), new BooleanLiteral("false"))));
    assertExpression("LISTAGG(x, ',' ON OVERFLOW TRUNCATE WITH COUNT) WITHIN GROUP (ORDER BY x)", new FunctionCall(Optional.empty(), QualifiedName.of("LISTAGG"), Optional.empty(), Optional.empty(), Optional.of(new OrderBy(ImmutableList.of(new SortItem(new Identifier("x", false), ASCENDING, UNDEFINED)))), false, Optional.empty(), Optional.empty(), ImmutableList.of(identifier("x"), new StringLiteral(","), new BooleanLiteral("false"), new StringLiteral("..."), new BooleanLiteral("true"))));
    assertExpression("LISTAGG(x, ',' ON OVERFLOW TRUNCATE 'HIDDEN' WITHOUT COUNT) WITHIN GROUP (ORDER BY x)", new FunctionCall(Optional.empty(), QualifiedName.of("LISTAGG"), Optional.empty(), Optional.empty(), Optional.of(new OrderBy(ImmutableList.of(new SortItem(new Identifier("x", false), ASCENDING, UNDEFINED)))), false, Optional.empty(), Optional.empty(), ImmutableList.of(identifier("x"), new StringLiteral(","), new BooleanLiteral("false"), new StringLiteral("HIDDEN"), new BooleanLiteral("false"))));
}
Also used : OrderBy(io.trino.sql.tree.OrderBy) SortItem(io.trino.sql.tree.SortItem) QueryUtil.quotedIdentifier(io.trino.sql.QueryUtil.quotedIdentifier) Identifier(io.trino.sql.tree.Identifier) StringLiteral(io.trino.sql.tree.StringLiteral) BooleanLiteral(io.trino.sql.tree.BooleanLiteral) FunctionCall(io.trino.sql.tree.FunctionCall) Test(org.junit.jupiter.api.Test)

Example 4 with BooleanLiteral

use of io.trino.sql.tree.BooleanLiteral in project trino by trinodb.

the class TestSqlParser method testCreateTable.

@Test
public void testCreateTable() {
    assertThat(statement("CREATE TABLE foo (a VARCHAR, b BIGINT COMMENT 'hello world', c IPADDRESS)")).isEqualTo(new CreateTable(location(1, 1), qualifiedName(location(1, 14), "foo"), ImmutableList.of(columnDefinition(location(1, 19), "a", simpleType(location(1, 21), "VARCHAR")), columnDefinition(location(1, 30), "b", simpleType(location(1, 32), "BIGINT"), true, "hello world"), columnDefinition(location(1, 62), "c", simpleType(location(1, 64), "IPADDRESS"))), false, ImmutableList.of(), Optional.empty()));
    assertThat(statement("CREATE TABLE IF NOT EXISTS bar (c TIMESTAMP)")).isEqualTo(new CreateTable(location(1, 1), qualifiedName(location(1, 28), "bar"), ImmutableList.of(columnDefinition(location(1, 33), "c", dateTimeType(location(1, 35), TIMESTAMP, false), true)), true, ImmutableList.of(), Optional.empty()));
    assertThat(statement("CREATE TABLE IF NOT EXISTS bar (c VARCHAR WITH (nullable = true, compression = 'LZ4'))")).describedAs("CREATE TABLE with column properties").isEqualTo(new CreateTable(location(1, 1), qualifiedName(location(1, 28), "bar"), ImmutableList.of(columnDefinition(location(1, 33), "c", simpleType(location(1, 35), "VARCHAR"), true, ImmutableList.of(property(location(1, 49), "nullable", new BooleanLiteral(location(1, 60), "true")), property(location(1, 66), "compression", new StringLiteral(location(1, 80), "LZ4"))))), true, ImmutableList.of(), Optional.empty()));
    // with LIKE
    assertStatement("CREATE TABLE IF NOT EXISTS bar (LIKE like_table)", new CreateTable(QualifiedName.of("bar"), ImmutableList.of(new LikeClause(QualifiedName.of("like_table"), Optional.empty())), true, ImmutableList.of(), Optional.empty()));
    assertThat(statement("CREATE TABLE IF NOT EXISTS bar (c VARCHAR, LIKE like_table)")).ignoringLocation().isEqualTo(new CreateTable(QualifiedName.of("bar"), ImmutableList.of(new ColumnDefinition(identifier("c"), simpleType(location(1, 35), "VARCHAR"), true, emptyList(), Optional.empty()), new LikeClause(QualifiedName.of("like_table"), Optional.empty())), true, ImmutableList.of(), Optional.empty()));
    assertThat(statement("CREATE TABLE IF NOT EXISTS bar (c VARCHAR, LIKE like_table, d BIGINT)")).ignoringLocation().isEqualTo(new CreateTable(QualifiedName.of("bar"), ImmutableList.of(new ColumnDefinition(identifier("c"), simpleType(location(1, 35), "VARCHAR"), true, emptyList(), Optional.empty()), new LikeClause(QualifiedName.of("like_table"), Optional.empty()), new ColumnDefinition(identifier("d"), simpleType(location(1, 63), "BIGINT"), true, emptyList(), Optional.empty())), true, ImmutableList.of(), Optional.empty()));
    assertStatement("CREATE TABLE IF NOT EXISTS bar (LIKE like_table INCLUDING PROPERTIES)", new CreateTable(QualifiedName.of("bar"), ImmutableList.of(new LikeClause(QualifiedName.of("like_table"), Optional.of(LikeClause.PropertiesOption.INCLUDING))), true, ImmutableList.of(), Optional.empty()));
    assertThat(statement("CREATE TABLE IF NOT EXISTS bar (c VARCHAR, LIKE like_table EXCLUDING PROPERTIES)")).ignoringLocation().isEqualTo(new CreateTable(QualifiedName.of("bar"), ImmutableList.of(new ColumnDefinition(identifier("c"), simpleType(location(1, 35), "VARCHAR"), true, emptyList(), Optional.empty()), new LikeClause(QualifiedName.of("like_table"), Optional.of(LikeClause.PropertiesOption.EXCLUDING))), true, ImmutableList.of(), Optional.empty()));
    assertThat(statement("CREATE TABLE IF NOT EXISTS bar (c VARCHAR, LIKE like_table EXCLUDING PROPERTIES) COMMENT 'test'")).ignoringLocation().isEqualTo(new CreateTable(QualifiedName.of("bar"), ImmutableList.of(new ColumnDefinition(identifier("c"), simpleType(location(1, 35), "VARCHAR"), true, emptyList(), Optional.empty()), new LikeClause(QualifiedName.of("like_table"), Optional.of(LikeClause.PropertiesOption.EXCLUDING))), true, ImmutableList.of(), Optional.of("test")));
}
Also used : LikeClause(io.trino.sql.tree.LikeClause) StringLiteral(io.trino.sql.tree.StringLiteral) BooleanLiteral(io.trino.sql.tree.BooleanLiteral) CreateTable(io.trino.sql.tree.CreateTable) ColumnDefinition(io.trino.sql.tree.ColumnDefinition) Test(org.junit.jupiter.api.Test)

Example 5 with BooleanLiteral

use of io.trino.sql.tree.BooleanLiteral in project trino by trinodb.

the class TestSqlParser method testArraySubscript.

@Test
public void testArraySubscript() {
    assertExpression("ARRAY [1, 2][1]", new SubscriptExpression(new ArrayConstructor(ImmutableList.of(new LongLiteral("1"), new LongLiteral("2"))), new LongLiteral("1")));
    assertExpression("CASE WHEN TRUE THEN ARRAY[1,2] END[1]", new SubscriptExpression(new SearchedCaseExpression(ImmutableList.of(new WhenClause(new BooleanLiteral("true"), new ArrayConstructor(ImmutableList.of(new LongLiteral("1"), new LongLiteral("2"))))), Optional.empty()), new LongLiteral("1")));
}
Also used : WhenClause(io.trino.sql.tree.WhenClause) SearchedCaseExpression(io.trino.sql.tree.SearchedCaseExpression) LongLiteral(io.trino.sql.tree.LongLiteral) BooleanLiteral(io.trino.sql.tree.BooleanLiteral) SubscriptExpression(io.trino.sql.tree.SubscriptExpression) ArrayConstructor(io.trino.sql.tree.ArrayConstructor) Test(org.junit.jupiter.api.Test)

Aggregations

BooleanLiteral (io.trino.sql.tree.BooleanLiteral)12 StringLiteral (io.trino.sql.tree.StringLiteral)10 LongLiteral (io.trino.sql.tree.LongLiteral)8 FunctionCall (io.trino.sql.tree.FunctionCall)6 Test (org.junit.jupiter.api.Test)6 ArithmeticBinaryExpression (io.trino.sql.tree.ArithmeticBinaryExpression)4 ArithmeticUnaryExpression (io.trino.sql.tree.ArithmeticUnaryExpression)4 Expression (io.trino.sql.tree.Expression)4 NullLiteral (io.trino.sql.tree.NullLiteral)4 QueryUtil.quotedIdentifier (io.trino.sql.QueryUtil.quotedIdentifier)3 TypeSignatureTranslator.toSqlType (io.trino.sql.analyzer.TypeSignatureTranslator.toSqlType)3 Identifier (io.trino.sql.tree.Identifier)3 ImmutableList (com.google.common.collect.ImmutableList)2 BIGINT (io.trino.spi.type.BigintType.BIGINT)2 RowType (io.trino.spi.type.RowType)2 VARCHAR (io.trino.spi.type.VarcharType.VARCHAR)2 TypeSignatureProvider.fromTypes (io.trino.sql.analyzer.TypeSignatureProvider.fromTypes)2 Symbol (io.trino.sql.planner.Symbol)2 PlanMatchPattern.values (io.trino.sql.planner.assertions.PlanMatchPattern.values)2 BaseRuleTest (io.trino.sql.planner.iterative.rule.test.BaseRuleTest)2