Java Code Examples for io.prestosql.spi.type.Type#equals()

The following examples show how to use io.prestosql.spi.type.Type#equals() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PreparedStatementBuilder.java    From presto with Apache License 2.0 6 votes vote down vote up
private static int typeToSqlType(Type type)
{
    if (type.equals(BIGINT)) {
        return Types.BIGINT;
    }
    if (type.equals(DOUBLE)) {
        return Types.DOUBLE;
    }
    if (type.equals(BOOLEAN)) {
        return Types.BOOLEAN;
    }
    if (isVarcharType(type)) {
        return Types.VARCHAR;
    }
    if (type.equals(VARBINARY)) {
        return Types.VARBINARY;
    }
    throw new IllegalArgumentException("Unknown type: " + type);
}
 
Example 2
Source File: TemporalFunction.java    From presto with Apache License 2.0 6 votes vote down vote up
public int getDayFromRange(ShardRange range)
{
    Tuple min = range.getMinTuple();
    Tuple max = range.getMaxTuple();
    checkArgument(getOnlyElement(min.getTypes()).equals(getOnlyElement(max.getTypes())), "type of min and max is not same");

    Type type = getOnlyElement(min.getTypes());
    if (type.equals(DATE)) {
        return (int) getOnlyElement(min.getValues());
    }

    if (type.equals(TIMESTAMP)) {
        long minValue = timeZone.convertUTCToLocal((long) getOnlyElement(min.getValues()));
        long maxValue = timeZone.convertUTCToLocal((long) getOnlyElement(max.getValues()));
        return determineDay(minValue, maxValue);
    }

    throw new IllegalArgumentException("Wrong type for shard range: " + type);
}
 
Example 3
Source File: BenchmarkTransformKey.java    From presto with Apache License 2.0 6 votes vote down vote up
private static Block createChannel(int positionCount, MapType mapType, Type elementType)
{
    BlockBuilder mapBlockBuilder = mapType.createBlockBuilder(null, 1);
    BlockBuilder singleMapBlockWriter = mapBlockBuilder.beginBlockEntry();
    Object value;
    for (int position = 0; position < positionCount; position++) {
        if (elementType.equals(BIGINT)) {
            value = ThreadLocalRandom.current().nextLong();
        }
        else if (elementType.equals(DOUBLE)) {
            value = ThreadLocalRandom.current().nextDouble();
        }
        else {
            throw new UnsupportedOperationException();
        }
        // Use position as the key to avoid collision
        writeNativeValue(elementType, singleMapBlockWriter, position);
        writeNativeValue(elementType, singleMapBlockWriter, value);
    }
    mapBlockBuilder.closeEntry();
    return mapBlockBuilder.build();
}
 
Example 4
Source File: ExpressionAnalyzer.java    From presto with Apache License 2.0 6 votes vote down vote up
@Override
protected Type visitArithmeticUnary(ArithmeticUnaryExpression node, StackableAstVisitorContext<Context> context)
{
    switch (node.getSign()) {
        case PLUS:
            Type type = process(node.getValue(), context);

            if (!type.equals(DOUBLE) && !type.equals(REAL) && !type.equals(BIGINT) && !type.equals(INTEGER) && !type.equals(SMALLINT) && !type.equals(TINYINT)) {
                // TODO: figure out a type-agnostic way of dealing with this. Maybe add a special unary operator
                // that types can chose to implement, or piggyback on the existence of the negation operator
                throw semanticException(TYPE_MISMATCH, node, "Unary '+' operator cannot by applied to %s type", type);
            }
            return setExpressionType(node, type);
        case MINUS:
            return getOperator(context, node, OperatorType.NEGATION, node.getValue());
    }

    throw new UnsupportedOperationException("Unsupported unary operator: " + node.getSign());
}
 
Example 5
Source File: ThriftMetastoreUtil.java    From presto with Apache License 2.0 6 votes vote down vote up
public static Set<ColumnStatisticType> getSupportedColumnStatistics(Type type)
{
    if (type.equals(BOOLEAN)) {
        return ImmutableSet.of(NUMBER_OF_NON_NULL_VALUES, NUMBER_OF_TRUE_VALUES);
    }
    if (isNumericType(type) || type.equals(DATE) || type.equals(TIMESTAMP)) {
        // TODO https://github.com/prestosql/presto/issues/37 support non-legacy TIMESTAMP
        return ImmutableSet.of(MIN_VALUE, MAX_VALUE, NUMBER_OF_DISTINCT_VALUES, NUMBER_OF_NON_NULL_VALUES);
    }
    if (isVarcharType(type) || isCharType(type)) {
        // TODO Collect MIN,MAX once it is used by the optimizer
        return ImmutableSet.of(NUMBER_OF_NON_NULL_VALUES, NUMBER_OF_DISTINCT_VALUES, TOTAL_SIZE_IN_BYTES, MAX_VALUE_SIZE_IN_BYTES);
    }
    if (type.equals(VARBINARY)) {
        return ImmutableSet.of(NUMBER_OF_NON_NULL_VALUES, TOTAL_SIZE_IN_BYTES, MAX_VALUE_SIZE_IN_BYTES);
    }
    if (type instanceof ArrayType || type instanceof RowType || type instanceof MapType) {
        return ImmutableSet.of();
    }
    // Throwing here to make sure this method is updated when a new type is added in Hive connector
    throw new IllegalArgumentException("Unsupported type: " + type);
}
 
Example 6
Source File: ColumnIndexStatsUtils.java    From presto with Apache License 2.0 6 votes vote down vote up
public static JDBCType jdbcType(Type type)
{
    if (type.equals(BOOLEAN)) {
        return JDBCType.BOOLEAN;
    }
    if (type.equals(BIGINT) || type.equals(TIMESTAMP)) {
        return JDBCType.BIGINT;
    }
    if (type.equals(INTEGER)) {
        return JDBCType.INTEGER;
    }
    if (type.equals(DOUBLE)) {
        return JDBCType.DOUBLE;
    }
    if (type.equals(DATE)) {
        return JDBCType.INTEGER;
    }
    if (type instanceof VarcharType) {
        return JDBCType.VARBINARY;
    }
    return null;
}
 
Example 7
Source File: SequencePageBuilder.java    From presto with Apache License 2.0 6 votes vote down vote up
public static Page createSequencePageWithDictionaryBlocks(List<? extends Type> types, int length, int... initialValues)
{
    Block[] blocks = new Block[initialValues.length];
    for (int i = 0; i < blocks.length; i++) {
        Type type = types.get(i);
        int initialValue = initialValues[i];
        if (type.equals(VARCHAR)) {
            blocks[i] = BlockAssertions.createStringDictionaryBlock(initialValue, initialValue + length);
        }
        else if (type.equals(BIGINT)) {
            blocks[i] = BlockAssertions.createLongDictionaryBlock(initialValue, initialValue + length);
        }
        else {
            throw new IllegalStateException("Unsupported type " + type);
        }
    }

    return new Page(blocks);
}
 
Example 8
Source File: OrcFileWriter.java    From presto with Apache License 2.0 5 votes vote down vote up
private static StorageType toStorageType(Type type)
{
    if (type instanceof DecimalType) {
        DecimalType decimalType = (DecimalType) type;
        return StorageType.decimal(decimalType.getPrecision(), decimalType.getScale());
    }
    Class<?> javaType = type.getJavaType();
    if (javaType == boolean.class) {
        return StorageType.BOOLEAN;
    }
    if (javaType == long.class) {
        return StorageType.LONG;
    }
    if (javaType == double.class) {
        return StorageType.DOUBLE;
    }
    if (javaType == Slice.class) {
        if (type instanceof VarcharType) {
            return StorageType.STRING;
        }
        if (type.equals(VarbinaryType.VARBINARY)) {
            return StorageType.BYTES;
        }
    }
    if (isArrayType(type)) {
        return arrayOf(toStorageType(type.getTypeParameters().get(0)));
    }
    if (isMapType(type)) {
        return mapOf(toStorageType(type.getTypeParameters().get(0)), toStorageType(type.getTypeParameters().get(1)));
    }
    throw new PrestoException(NOT_SUPPORTED, "No storage type for type: " + type);
}
 
Example 9
Source File: IonSqlQueryBuilder.java    From presto with Apache License 2.0 5 votes vote down vote up
private static boolean isSupported(Type type)
{
    Type validType = requireNonNull(type, "type is null");
    return validType.equals(BIGINT) ||
            validType.equals(TINYINT) ||
            validType.equals(SMALLINT) ||
            validType.equals(INTEGER) ||
            validType instanceof DecimalType ||
            validType.equals(BOOLEAN) ||
            validType.equals(DATE) ||
            validType instanceof VarcharType;
}
 
Example 10
Source File: ExpressionAnalyzer.java    From presto with Apache License 2.0 5 votes vote down vote up
@Override
protected Type visitBetweenPredicate(BetweenPredicate node, StackableAstVisitorContext<Context> context)
{
    Type valueType = process(node.getValue(), context);
    Type minType = process(node.getMin(), context);
    Type maxType = process(node.getMax(), context);

    Optional<Type> commonType = typeCoercion.getCommonSuperType(valueType, minType)
            .flatMap(type -> typeCoercion.getCommonSuperType(type, maxType));

    if (commonType.isEmpty()) {
        semanticException(TYPE_MISMATCH, node, "Cannot check if %s is BETWEEN %s and %s", valueType, minType, maxType);
    }

    try {
        metadata.resolveOperator(OperatorType.LESS_THAN_OR_EQUAL, List.of(commonType.get(), commonType.get()));
    }
    catch (OperatorNotFoundException e) {
        semanticException(TYPE_MISMATCH, node, "Cannot check if %s is BETWEEN %s and %s", valueType, minType, maxType);
    }

    if (!valueType.equals(commonType.get())) {
        addOrReplaceExpressionCoercion(node.getValue(), valueType, commonType.get());
    }
    if (!minType.equals(commonType.get())) {
        addOrReplaceExpressionCoercion(node.getMin(), minType, commonType.get());
    }
    if (!maxType.equals(commonType.get())) {
        addOrReplaceExpressionCoercion(node.getMax(), maxType, commonType.get());
    }

    return setExpressionType(node, BOOLEAN);
}
 
Example 11
Source File: ExpressionAnalyzer.java    From presto with Apache License 2.0 5 votes vote down vote up
private Type coerceToSingleType(StackableAstVisitorContext<Context> context, Node node, String message, Expression first, Expression second)
{
    Type firstType = UNKNOWN;
    if (first != null) {
        firstType = process(first, context);
    }
    Type secondType = UNKNOWN;
    if (second != null) {
        secondType = process(second, context);
    }

    // coerce types if possible
    Optional<Type> superTypeOptional = typeCoercion.getCommonSuperType(firstType, secondType);
    if (superTypeOptional.isPresent()
            && typeCoercion.canCoerce(firstType, superTypeOptional.get())
            && typeCoercion.canCoerce(secondType, superTypeOptional.get())) {
        Type superType = superTypeOptional.get();
        if (!firstType.equals(superType)) {
            addOrReplaceExpressionCoercion(first, firstType, superType);
        }
        if (!secondType.equals(superType)) {
            addOrReplaceExpressionCoercion(second, secondType, superType);
        }
        return superType;
    }

    throw semanticException(TYPE_MISMATCH, node, message, firstType, secondType);
}
 
Example 12
Source File: AccumuloRecordCursor.java    From presto with Apache License 2.0 5 votes vote down vote up
/**
 * Checks that the given field is one of the provided types.
 *
 * @param field Ordinal of the field
 * @param expected An array of expected types
 * @throws IllegalArgumentException If the given field does not match one of the types
 */
private void checkFieldType(int field, Type... expected)
{
    Type actual = getType(field);
    for (Type type : expected) {
        if (actual.equals(type)) {
            return;
        }
    }

    throw new IllegalArgumentException(format("Expected field %s to be a type of %s but is %s", field, StringUtils.join(expected, ","), actual));
}
 
Example 13
Source File: TpchMetadata.java    From presto with Apache License 2.0 5 votes vote down vote up
private static double toDouble(Object value, Type columnType)
{
    if (value instanceof String && columnType.equals(DATE)) {
        return LocalDate.parse((CharSequence) value).toEpochDay();
    }
    if (columnType.equals(BIGINT) || columnType.equals(INTEGER) || columnType.equals(DATE)) {
        return ((Number) value).longValue();
    }
    if (columnType.equals(DOUBLE)) {
        return ((Number) value).doubleValue();
    }
    throw new IllegalArgumentException("unsupported column type " + columnType);
}
 
Example 14
Source File: RaptorBucketFunction.java    From presto with Apache License 2.0 5 votes vote down vote up
private static HashFunction getHashFunction(Type type)
{
    if (type.equals(BIGINT)) {
        return bigintHashFunction();
    }
    if (type.equals(INTEGER)) {
        return intHashFunction();
    }
    if (isVarcharType(type)) {
        return varcharHashFunction();
    }
    throw new PrestoException(NOT_SUPPORTED, "Bucketing is supported for bigint, integer and varchar, not " + type.getDisplayName());
}
 
Example 15
Source File: RcFileTester.java    From presto with Apache License 2.0 4 votes vote down vote up
private static Object preprocessWriteValueOld(Type type, Object value)
{
    if (value == null) {
        return null;
    }

    if (type.equals(BOOLEAN)) {
        return value;
    }
    if (type.equals(TINYINT)) {
        return ((Number) value).byteValue();
    }
    if (type.equals(SMALLINT)) {
        return ((Number) value).shortValue();
    }
    if (type.equals(INTEGER)) {
        return ((Number) value).intValue();
    }
    if (type.equals(BIGINT)) {
        return ((Number) value).longValue();
    }
    if (type.equals(REAL)) {
        return ((Number) value).floatValue();
    }
    if (type.equals(DOUBLE)) {
        return ((Number) value).doubleValue();
    }
    if (type instanceof VarcharType) {
        return value;
    }
    if (type.equals(VARBINARY)) {
        return ((SqlVarbinary) value).getBytes();
    }
    if (type.equals(DATE)) {
        int days = ((SqlDate) value).getDays();
        LocalDate localDate = LocalDate.ofEpochDay(days);
        ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());

        long millis = zonedDateTime.toEpochSecond() * 1000;
        Date date = new Date(0);
        // mills must be set separately to avoid masking
        date.setTime(millis);
        return date;
    }
    if (type.equals(TIMESTAMP)) {
        long millisUtc = (int) ((SqlTimestamp) value).getMillisUtc();
        return new Timestamp(millisUtc);
    }
    if (type instanceof DecimalType) {
        return HiveDecimal.create(((SqlDecimal) value).toBigDecimal());
    }
    if (type instanceof ArrayType) {
        Type elementType = type.getTypeParameters().get(0);
        return ((List<?>) value).stream()
                .map(element -> preprocessWriteValueOld(elementType, element))
                .collect(toList());
    }
    if (type instanceof MapType) {
        Type keyType = type.getTypeParameters().get(0);
        Type valueType = type.getTypeParameters().get(1);
        Map<Object, Object> newMap = new HashMap<>();
        for (Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
            newMap.put(preprocessWriteValueOld(keyType, entry.getKey()), preprocessWriteValueOld(valueType, entry.getValue()));
        }
        return newMap;
    }
    if (type instanceof RowType) {
        List<?> fieldValues = (List<?>) value;
        List<Type> fieldTypes = type.getTypeParameters();
        List<Object> newStruct = new ArrayList<>();
        for (int fieldId = 0; fieldId < fieldValues.size(); fieldId++) {
            newStruct.add(preprocessWriteValueOld(fieldTypes.get(fieldId), fieldValues.get(fieldId)));
        }
        return newStruct;
    }
    throw new IllegalArgumentException("unsupported type: " + type);
}
 
Example 16
Source File: BigQueryResultPageSource.java    From presto with Apache License 2.0 4 votes vote down vote up
private void appendTo(Type type, Object value, BlockBuilder output)
{
    if (value == null) {
        output.appendNull();
        return;
    }

    Class<?> javaType = type.getJavaType();
    try {
        if (javaType == boolean.class) {
            type.writeBoolean(output, (Boolean) value);
        }
        else if (javaType == long.class) {
            if (type.equals(BIGINT)) {
                type.writeLong(output, ((Number) value).longValue());
            }
            else if (type.equals(INTEGER)) {
                type.writeLong(output, ((Number) value).intValue());
            }
            else if (type.equals(DATE)) {
                type.writeLong(output, ((Number) value).intValue());
            }
            else if (type.equals(TIMESTAMP)) {
                type.writeLong(output, toPrestoTimestamp(((Utf8) value).toString()));
            }
            else if (type.equals(TIME_WITH_TIME_ZONE)) {
                type.writeLong(output, DateTimeEncoding.packDateTimeWithZone(((Long) value).longValue() / 1000, TimeZoneKey.UTC_KEY));
            }
            else if (type.equals(TIMESTAMP_WITH_TIME_ZONE)) {
                type.writeLong(output, DateTimeEncoding.packDateTimeWithZone(((Long) value).longValue() / 1000, TimeZoneKey.UTC_KEY));
            }
            else {
                throw new PrestoException(GENERIC_INTERNAL_ERROR, format("Unhandled type for %s: %s", javaType.getSimpleName(), type));
            }
        }
        else if (javaType == double.class) {
            type.writeDouble(output, ((Number) value).doubleValue());
        }
        else if (javaType == Slice.class) {
            writeSlice(output, type, value);
        }
        else if (javaType == Block.class) {
            writeBlock(output, type, value);
        }
        else {
            throw new PrestoException(GENERIC_INTERNAL_ERROR, format("Unhandled type for %s: %s", javaType.getSimpleName(), type));
        }
    }
    catch (ClassCastException ignore) {
        // returns null instead of raising exception
        output.appendNull();
    }
}
 
Example 17
Source File: HiveWriteUtils.java    From presto with Apache License 2.0 4 votes vote down vote up
public static ObjectInspector getJavaObjectInspector(Type type)
{
    if (type.equals(BooleanType.BOOLEAN)) {
        return javaBooleanObjectInspector;
    }
    if (type.equals(BigintType.BIGINT)) {
        return javaLongObjectInspector;
    }
    if (type.equals(IntegerType.INTEGER)) {
        return javaIntObjectInspector;
    }
    if (type.equals(SmallintType.SMALLINT)) {
        return javaShortObjectInspector;
    }
    if (type.equals(TinyintType.TINYINT)) {
        return javaByteObjectInspector;
    }
    if (type.equals(RealType.REAL)) {
        return javaFloatObjectInspector;
    }
    if (type.equals(DoubleType.DOUBLE)) {
        return javaDoubleObjectInspector;
    }
    if (type instanceof VarcharType) {
        return writableStringObjectInspector;
    }
    if (type instanceof CharType) {
        return writableHiveCharObjectInspector;
    }
    if (type.equals(VarbinaryType.VARBINARY)) {
        return javaByteArrayObjectInspector;
    }
    if (type.equals(DateType.DATE)) {
        return javaDateObjectInspector;
    }
    if (type.equals(TimestampType.TIMESTAMP)) {
        return javaTimestampObjectInspector;
    }
    if (type instanceof DecimalType) {
        DecimalType decimalType = (DecimalType) type;
        return getPrimitiveJavaObjectInspector(new DecimalTypeInfo(decimalType.getPrecision(), decimalType.getScale()));
    }
    if (isArrayType(type)) {
        return ObjectInspectorFactory.getStandardListObjectInspector(getJavaObjectInspector(type.getTypeParameters().get(0)));
    }
    if (isMapType(type)) {
        ObjectInspector keyObjectInspector = getJavaObjectInspector(type.getTypeParameters().get(0));
        ObjectInspector valueObjectInspector = getJavaObjectInspector(type.getTypeParameters().get(1));
        return ObjectInspectorFactory.getStandardMapObjectInspector(keyObjectInspector, valueObjectInspector);
    }
    if (isRowType(type)) {
        return ObjectInspectorFactory.getStandardStructObjectInspector(
                type.getTypeSignature().getParameters().stream()
                        .map(parameter -> parameter.getNamedTypeSignature().getName().get())
                        .collect(toImmutableList()),
                type.getTypeParameters().stream()
                        .map(HiveWriteUtils::getJavaObjectInspector)
                        .collect(toImmutableList()));
    }
    throw new IllegalArgumentException("unsupported type: " + type);
}
 
Example 18
Source File: LexicoderRowSerializer.java    From presto with Apache License 2.0 4 votes vote down vote up
@Override
public byte[] encode(Type type, Object value)
{
    Object toEncode;
    if (Types.isArrayType(type)) {
        toEncode = AccumuloRowSerializer.getArrayFromBlock(Types.getElementType(type), (Block) value);
    }
    else if (Types.isMapType(type)) {
        toEncode = AccumuloRowSerializer.getMapFromBlock(type, (Block) value);
    }
    else if (type.equals(BIGINT) && value instanceof Integer) {
        toEncode = ((Integer) value).longValue();
    }
    else if (type.equals(DATE) && value instanceof Date) {
        toEncode = MILLISECONDS.toDays(((Date) value).getTime());
    }
    else if (type.equals(INTEGER) && value instanceof Integer) {
        toEncode = ((Integer) value).longValue();
    }
    else if (type.equals(REAL) && value instanceof Float) {
        toEncode = ((Float) value).doubleValue();
    }
    else if (type.equals(SMALLINT) && value instanceof Short) {
        toEncode = ((Short) value).longValue();
    }
    else if (type.equals(TIME) && value instanceof Time) {
        toEncode = ((Time) value).getTime();
    }
    else if (type.equals(TIMESTAMP) && value instanceof Timestamp) {
        toEncode = ((Timestamp) value).getTime();
    }
    else if (type.equals(TINYINT) && value instanceof Byte) {
        toEncode = ((Byte) value).longValue();
    }
    else if (type.equals(VARBINARY) && value instanceof Slice) {
        toEncode = ((Slice) value).getBytes();
    }
    else if (type instanceof VarcharType && value instanceof Slice) {
        toEncode = ((Slice) value).toStringUtf8();
    }
    else {
        toEncode = value;
    }

    return getLexicoder(type).encode(toEncode);
}
 
Example 19
Source File: TestRaptorConnector.java    From presto with Apache License 2.0 4 votes vote down vote up
private void assertSplitShard(Type temporalType, String min, String max, String userTimeZone, int expectedSplits)
        throws Exception
{
    ConnectorSession session = TestingConnectorSession.builder()
            .setTimeZoneKey(getTimeZoneKey(userTimeZone))
            .setPropertyMetadata(new RaptorSessionProperties(new StorageManagerConfig()).getSessionProperties())
            .build();

    ConnectorTransactionHandle transaction = connector.beginTransaction(READ_COMMITTED, false);
    connector.getMetadata(transaction).createTable(
            SESSION,
            new ConnectorTableMetadata(
                    new SchemaTableName("test", "test"),
                    ImmutableList.of(new ColumnMetadata("id", BIGINT), new ColumnMetadata("time", temporalType)),
                    ImmutableMap.of(TEMPORAL_COLUMN_PROPERTY, "time")),
            false);
    connector.commit(transaction);

    ConnectorTransactionHandle txn1 = connector.beginTransaction(READ_COMMITTED, false);
    ConnectorTableHandle handle1 = getTableHandle(connector.getMetadata(txn1), "test");
    ConnectorInsertTableHandle insertTableHandle = connector.getMetadata(txn1).beginInsert(session, handle1);
    ConnectorPageSink raptorPageSink = connector.getPageSinkProvider().createPageSink(txn1, session, insertTableHandle);

    Object timestamp1 = null;
    Object timestamp2 = null;
    if (temporalType.equals(TIMESTAMP)) {
        timestamp1 = SqlTimestamp.legacyFromMillis(3, castToLegacyShortTimestamp(TIMESTAMP.getPrecision(), getTimeZoneKey(userTimeZone), min), getTimeZoneKey(userTimeZone));
        timestamp2 = SqlTimestamp.legacyFromMillis(3, castToLegacyShortTimestamp(TIMESTAMP.getPrecision(), getTimeZoneKey(userTimeZone), max), getTimeZoneKey(userTimeZone));
    }
    else if (temporalType.equals(DATE)) {
        timestamp1 = new SqlDate(parseDate(min));
        timestamp2 = new SqlDate(parseDate(max));
    }

    Page inputPage = MaterializedResult.resultBuilder(session, ImmutableList.of(BIGINT, temporalType))
            .row(1L, timestamp1)
            .row(2L, timestamp2)
            .build()
            .toPage();

    raptorPageSink.appendPage(inputPage);

    Collection<Slice> shards = raptorPageSink.finish().get();
    assertEquals(shards.size(), expectedSplits);
    connector.getMetadata(txn1).dropTable(session, handle1);
    connector.commit(txn1);
}
 
Example 20
Source File: StatementAnalyzer.java    From presto with Apache License 2.0 4 votes vote down vote up
@Override
protected Scope visitJoin(Join node, Optional<Scope> scope)
{
    JoinCriteria criteria = node.getCriteria().orElse(null);
    if (criteria instanceof NaturalJoin) {
        throw semanticException(NOT_SUPPORTED, node, "Natural join not supported");
    }

    Scope left = process(node.getLeft(), scope);
    Scope right = process(node.getRight(), isLateralRelation(node.getRight()) ? Optional.of(left) : scope);

    if (isLateralRelation(node.getRight())) {
        if (node.getType() == RIGHT || node.getType() == FULL) {
            Stream<Expression> leftScopeReferences = getReferencesToScope(node.getRight(), analysis, left);
            leftScopeReferences.findFirst().ifPresent(reference -> {
                throw semanticException(INVALID_COLUMN_REFERENCE, reference, "LATERAL reference not allowed in %s JOIN", node.getType().name());
            });
        }
        if (isUnnestRelation(node.getRight())) {
            if (criteria != null) {
                if (!(criteria instanceof JoinOn) || !((JoinOn) criteria).getExpression().equals(TRUE_LITERAL)) {
                    throw semanticException(
                            NOT_SUPPORTED,
                            criteria instanceof JoinOn ? ((JoinOn) criteria).getExpression() : node,
                            "%s JOIN involving UNNEST is only supported with condition ON TRUE",
                            node.getType().name());
                }
            }
        }
        else if (node.getType() == FULL) {
            if (!(criteria instanceof JoinOn) || !((JoinOn) criteria).getExpression().equals(TRUE_LITERAL)) {
                throw semanticException(
                        NOT_SUPPORTED,
                        criteria instanceof JoinOn ? ((JoinOn) criteria).getExpression() : node,
                        "FULL JOIN involving LATERAL relation is only supported with condition ON TRUE");
            }
        }
    }

    if (criteria instanceof JoinUsing) {
        return analyzeJoinUsing(node, ((JoinUsing) criteria).getColumns(), scope, left, right);
    }

    Scope output = createAndAssignScope(node, scope, left.getRelationType().joinWith(right.getRelationType()));

    if (node.getType() == Join.Type.CROSS || node.getType() == Join.Type.IMPLICIT) {
        return output;
    }
    if (criteria instanceof JoinOn) {
        Expression expression = ((JoinOn) criteria).getExpression();

        // Need to register coercions in case when join criteria requires coercion (e.g. join on char(1) = char(2))
        // Correlations are only currently support in the join criteria for INNER joins
        ExpressionAnalysis expressionAnalysis = analyzeExpression(expression, output, node.getType() == INNER ? CorrelationSupport.ALLOWED : CorrelationSupport.DISALLOWED);
        Type clauseType = expressionAnalysis.getType(expression);
        if (!clauseType.equals(BOOLEAN)) {
            if (!clauseType.equals(UNKNOWN)) {
                throw semanticException(TYPE_MISMATCH, expression, "JOIN ON clause must evaluate to a boolean: actual type %s", clauseType);
            }
            // coerce null to boolean
            analysis.addCoercion(expression, BOOLEAN, false);
        }

        verifyNoAggregateWindowOrGroupingFunctions(metadata, expression, "JOIN clause");

        analysis.recordSubqueries(node, expressionAnalysis);
        analysis.setJoinCriteria(node, expression);
    }
    else {
        throw new UnsupportedOperationException("Unsupported join criteria: " + criteria.getClass().getName());
    }

    return output;
}