Search in sources :

Example 16 with NullableValue

use of com.facebook.presto.common.predicate.NullableValue in project presto by prestodb.

the class HiveBucketing method getHiveBucketFilter.

public static Optional<HiveBucketFilter> getHiveBucketFilter(Optional<HiveBucketProperty> hiveBucketProperty, List<Column> dataColumns, TupleDomain<ColumnHandle> effectivePredicate) {
    if (!hiveBucketProperty.isPresent()) {
        return Optional.empty();
    }
    if (!hiveBucketProperty.get().getBucketFunctionType().equals(HIVE_COMPATIBLE)) {
        // bucket filtering is only supported for tables bucketed with HIVE_COMPATIBLE hash function
        return Optional.empty();
    }
    Optional<Map<ColumnHandle, Set<NullableValue>>> bindings = TupleDomain.extractFixedValueSets(effectivePredicate);
    if (!bindings.isPresent()) {
        return Optional.empty();
    }
    Optional<Set<Integer>> buckets = getHiveBuckets(hiveBucketProperty, dataColumns, bindings.get());
    if (buckets.isPresent()) {
        return Optional.of(new HiveBucketFilter(buckets.get()));
    }
    if (!effectivePredicate.getDomains().isPresent()) {
        return Optional.empty();
    }
    Optional<Domain> domain = effectivePredicate.getDomains().get().entrySet().stream().filter(entry -> ((HiveColumnHandle) entry.getKey()).getName().equals(BUCKET_COLUMN_NAME)).findFirst().map(Entry::getValue);
    if (!domain.isPresent()) {
        return Optional.empty();
    }
    ValueSet values = domain.get().getValues();
    ImmutableSet.Builder<Integer> builder = ImmutableSet.builder();
    int bucketCount = hiveBucketProperty.get().getBucketCount();
    for (int i = 0; i < bucketCount; i++) {
        if (values.containsValue((long) i)) {
            builder.add(i);
        }
    }
    return Optional.of(new HiveBucketFilter(builder.build()));
}
Also used : ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) ValueSet(com.facebook.presto.common.predicate.ValueSet) NullableValue(com.facebook.presto.common.predicate.NullableValue) Entry(java.util.Map.Entry) ImmutableSet(com.google.common.collect.ImmutableSet) Domain(com.facebook.presto.common.predicate.Domain) TupleDomain(com.facebook.presto.common.predicate.TupleDomain) Map(java.util.Map) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) ValueSet(com.facebook.presto.common.predicate.ValueSet)

Example 17 with NullableValue

use of com.facebook.presto.common.predicate.NullableValue in project presto by prestodb.

the class MaterializedViewUtils method generateBaseTablePredicates.

public static Map<SchemaTableName, Expression> generateBaseTablePredicates(Map<SchemaTableName, MaterializedViewStatus.MaterializedDataPredicates> predicatesFromBaseTables, Metadata metadata) {
    Map<SchemaTableName, Expression> baseTablePredicates = new HashMap<>();
    for (SchemaTableName baseTable : predicatesFromBaseTables.keySet()) {
        MaterializedViewStatus.MaterializedDataPredicates predicatesInfo = predicatesFromBaseTables.get(baseTable);
        List<String> partitionKeys = predicatesInfo.getColumnNames();
        ImmutableList<Expression> keyExpressions = partitionKeys.stream().map(Identifier::new).collect(toImmutableList());
        List<TupleDomain<String>> predicateDisjuncts = predicatesInfo.getPredicateDisjuncts();
        Expression disjunct = null;
        for (TupleDomain<String> predicateDisjunct : predicateDisjuncts) {
            Expression conjunct = null;
            Iterator<Expression> keyExpressionsIterator = keyExpressions.stream().iterator();
            Map<String, NullableValue> predicateKeyValue = extractFixedValues(predicateDisjunct).orElseThrow(() -> new IllegalStateException("predicateKeyValue is not present!"));
            for (String key : partitionKeys) {
                NullableValue nullableValue = predicateKeyValue.get(key);
                Expression expression;
                if (nullableValue.isNull()) {
                    expression = new IsNullPredicate(keyExpressionsIterator.next());
                } else {
                    LiteralEncoder literalEncoder = new LiteralEncoder(metadata.getBlockEncodingSerde());
                    Expression valueExpression = literalEncoder.toExpression(nullableValue.getValue(), nullableValue.getType(), false);
                    expression = new ComparisonExpression(EQUAL, keyExpressionsIterator.next(), valueExpression);
                }
                conjunct = conjunct == null ? expression : new LogicalBinaryExpression(AND, conjunct, expression);
            }
            disjunct = conjunct == null ? disjunct : disjunct == null ? conjunct : new LogicalBinaryExpression(OR, disjunct, conjunct);
        }
        // If no (fresh) partitions are found for table, that means we should not select from it
        if (disjunct == null) {
            disjunct = FALSE_LITERAL;
        }
        baseTablePredicates.put(baseTable, disjunct);
    }
    return baseTablePredicates;
}
Also used : LogicalBinaryExpression(com.facebook.presto.sql.tree.LogicalBinaryExpression) HashMap(java.util.HashMap) NullableValue(com.facebook.presto.common.predicate.NullableValue) SchemaTableName(com.facebook.presto.spi.SchemaTableName) ComparisonExpression(com.facebook.presto.sql.tree.ComparisonExpression) TupleDomain(com.facebook.presto.common.predicate.TupleDomain) ComparisonExpression(com.facebook.presto.sql.tree.ComparisonExpression) LogicalBinaryExpression(com.facebook.presto.sql.tree.LogicalBinaryExpression) Expression(com.facebook.presto.sql.tree.Expression) LiteralEncoder(com.facebook.presto.sql.planner.LiteralEncoder) IsNullPredicate(com.facebook.presto.sql.tree.IsNullPredicate) MaterializedViewStatus(com.facebook.presto.spi.MaterializedViewStatus)

Example 18 with NullableValue

use of com.facebook.presto.common.predicate.NullableValue in project presto by prestodb.

the class NativeCassandraSession method getPartitions.

@Override
public List<CassandraPartition> getPartitions(CassandraTable table, List<Set<Object>> filterPrefixes) {
    List<CassandraColumnHandle> partitionKeyColumns = table.getPartitionKeyColumns();
    if (filterPrefixes.size() != partitionKeyColumns.size()) {
        return ImmutableList.of(CassandraPartition.UNPARTITIONED);
    }
    Iterable<Row> rows;
    if (getCassandraVersion().compareTo(PARTITION_FETCH_WITH_IN_PREDICATE_VERSION) > 0) {
        log.debug("Using IN predicate to fetch partitions.");
        rows = queryPartitionKeysWithInClauses(table, filterPrefixes);
    } else {
        log.debug("Using combination of partition values to fetch partitions.");
        rows = queryPartitionKeysLegacyWithMultipleQueries(table, filterPrefixes);
    }
    if (rows == null) {
        // just split the whole partition range
        return ImmutableList.of(CassandraPartition.UNPARTITIONED);
    }
    ByteBuffer buffer = ByteBuffer.allocate(1000);
    HashMap<ColumnHandle, NullableValue> map = new HashMap<>();
    Set<String> uniquePartitionIds = new HashSet<>();
    StringBuilder stringBuilder = new StringBuilder();
    boolean isComposite = partitionKeyColumns.size() > 1;
    ImmutableList.Builder<CassandraPartition> partitions = ImmutableList.builder();
    for (Row row : rows) {
        buffer.clear();
        map.clear();
        stringBuilder.setLength(0);
        for (int i = 0; i < partitionKeyColumns.size(); i++) {
            ByteBuffer component = row.getBytesUnsafe(i);
            if (isComposite) {
                // build composite key
                short len = (short) component.limit();
                buffer.putShort(len);
                buffer.put(component);
                buffer.put((byte) 0);
            } else {
                buffer.put(component);
            }
            CassandraColumnHandle columnHandle = partitionKeyColumns.get(i);
            NullableValue keyPart = CassandraType.getColumnValueForPartitionKey(row, i, columnHandle.getCassandraType(), columnHandle.getTypeArguments());
            map.put(columnHandle, keyPart);
            if (i > 0) {
                stringBuilder.append(" AND ");
            }
            stringBuilder.append(CassandraCqlUtils.validColumnName(columnHandle.getName()));
            stringBuilder.append(" = ");
            stringBuilder.append(CassandraType.getColumnValueForCql(row, i, columnHandle.getCassandraType()));
        }
        buffer.flip();
        byte[] key = new byte[buffer.limit()];
        buffer.get(key);
        TupleDomain<ColumnHandle> tupleDomain = TupleDomain.fromFixedValues(map);
        String partitionId = stringBuilder.toString();
        if (uniquePartitionIds.add(partitionId)) {
            partitions.add(new CassandraPartition(key, partitionId, tupleDomain, false));
        }
    }
    return partitions.build();
}
Also used : ColumnHandle(com.facebook.presto.spi.ColumnHandle) HashMap(java.util.HashMap) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ImmutableList(com.google.common.collect.ImmutableList) NullableValue(com.facebook.presto.common.predicate.NullableValue) ByteBuffer(java.nio.ByteBuffer) Row(com.datastax.driver.core.Row) HashSet(java.util.HashSet)

Example 19 with NullableValue

use of com.facebook.presto.common.predicate.NullableValue in project presto by prestodb.

the class HiveMetadata method buildColumnDomain.

private static Domain buildColumnDomain(ColumnHandle column, List<HivePartition> partitions) {
    checkArgument(!partitions.isEmpty(), "partitions cannot be empty");
    boolean hasNull = false;
    Set<Object> nonNullValues = new HashSet<>();
    Type type = null;
    for (HivePartition partition : partitions) {
        NullableValue value = partition.getKeys().get(column);
        if (value == null) {
            throw new PrestoException(HIVE_UNKNOWN_ERROR, format("Partition %s does not have a value for partition column %s", partition, column));
        }
        if (value.isNull()) {
            hasNull = true;
        } else {
            nonNullValues.add(value.getValue());
        }
        if (type == null) {
            type = value.getType();
        }
    }
    if (!nonNullValues.isEmpty()) {
        Domain domain = Domain.multipleValues(type, ImmutableList.copyOf(nonNullValues));
        if (hasNull) {
            return domain.union(Domain.onlyNull(type));
        }
        return domain;
    }
    return Domain.onlyNull(type);
}
Also used : VarcharType.createUnboundedVarcharType(com.facebook.presto.common.type.VarcharType.createUnboundedVarcharType) TableStatisticType(com.facebook.presto.spi.statistics.TableStatisticType) RowType(com.facebook.presto.common.type.RowType) MapType(com.facebook.presto.common.type.MapType) HiveWriteUtils.isWritableType(com.facebook.presto.hive.HiveWriteUtils.isWritableType) Type(com.facebook.presto.common.type.Type) Varchars.isVarcharType(com.facebook.presto.common.type.Varchars.isVarcharType) TypeUtils.isNumericType(com.facebook.presto.common.type.TypeUtils.isNumericType) Chars.isCharType(com.facebook.presto.common.type.Chars.isCharType) ArrayType(com.facebook.presto.common.type.ArrayType) ColumnStatisticType(com.facebook.presto.spi.statistics.ColumnStatisticType) HiveType.toHiveType(com.facebook.presto.hive.HiveType.toHiveType) HiveSessionProperties.isUsePageFileForHiveUnsupportedType(com.facebook.presto.hive.HiveSessionProperties.isUsePageFileForHiveUnsupportedType) PrestoTableType(com.facebook.presto.hive.metastore.PrestoTableType) NullableValue(com.facebook.presto.common.predicate.NullableValue) PrestoException(com.facebook.presto.spi.PrestoException) Domain(com.facebook.presto.common.predicate.Domain) TupleDomain(com.facebook.presto.common.predicate.TupleDomain) HashSet(java.util.HashSet)

Example 20 with NullableValue

use of com.facebook.presto.common.predicate.NullableValue in project presto by prestodb.

the class HivePageSourceProvider method shouldSkipPartition.

private static boolean shouldSkipPartition(TypeManager typeManager, HiveTableLayoutHandle hiveLayout, DateTimeZone hiveStorageTimeZone, HiveSplit hiveSplit, SplitContext splitContext) {
    List<HiveColumnHandle> partitionColumns = hiveLayout.getPartitionColumns();
    List<Type> partitionTypes = partitionColumns.stream().map(column -> typeManager.getType(column.getTypeSignature())).collect(toList());
    List<HivePartitionKey> partitionKeys = hiveSplit.getPartitionKeys();
    if (!splitContext.getDynamicFilterPredicate().isPresent() || hiveSplit.getPartitionKeys().isEmpty() || partitionColumns.isEmpty() || partitionColumns.size() != partitionKeys.size()) {
        return false;
    }
    TupleDomain<ColumnHandle> dynamicFilter = splitContext.getDynamicFilterPredicate().get();
    Map<ColumnHandle, Domain> domains = dynamicFilter.getDomains().get();
    for (int i = 0; i < partitionKeys.size(); i++) {
        Type type = partitionTypes.get(i);
        HivePartitionKey hivePartitionKey = partitionKeys.get(i);
        HiveColumnHandle hiveColumnHandle = partitionColumns.get(i);
        Domain allowedDomain = domains.get(hiveColumnHandle);
        NullableValue value = parsePartitionValue(hivePartitionKey, type, hiveStorageTimeZone);
        if (allowedDomain != null && !allowedDomain.includesNullableValue(value.getValue())) {
            return true;
        }
    }
    return false;
}
Also used : NestedField(com.facebook.presto.common.Subfield.NestedField) RecordPageSource(com.facebook.presto.spi.RecordPageSource) DateTimeZone(org.joda.time.DateTimeZone) LoadingCache(com.google.common.cache.LoadingCache) HiveColumnHandle.isPushedDownSubfield(com.facebook.presto.hive.HiveColumnHandle.isPushedDownSubfield) Maps.uniqueIndex(com.google.common.collect.Maps.uniqueIndex) ConnectorTransactionHandle(com.facebook.presto.spi.connector.ConnectorTransactionHandle) ColumnMapping.toColumnHandles(com.facebook.presto.hive.HivePageSourceProvider.ColumnMapping.toColumnHandles) AGGREGATED(com.facebook.presto.hive.HiveColumnHandle.ColumnType.AGGREGATED) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) SchemaTableName(com.facebook.presto.spi.SchemaTableName) SplitContext(com.facebook.presto.spi.SplitContext) Configuration(org.apache.hadoop.conf.Configuration) Map(java.util.Map) Path(org.apache.hadoop.fs.Path) HiveBucketing.getHiveBucketFilter(com.facebook.presto.hive.HiveBucketing.getHiveBucketFilter) ConnectorPageSourceProvider(com.facebook.presto.spi.connector.ConnectorPageSourceProvider) BucketConversion(com.facebook.presto.hive.HiveSplit.BucketConversion) ImmutableSet(com.google.common.collect.ImmutableSet) HIVE_UNKNOWN_ERROR(com.facebook.presto.hive.HiveErrorCode.HIVE_UNKNOWN_ERROR) NullableValue(com.facebook.presto.common.predicate.NullableValue) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Set(java.util.Set) String.format(java.lang.String.format) Preconditions.checkState(com.google.common.base.Preconditions.checkState) ConnectorSession(com.facebook.presto.spi.ConnectorSession) CacheLoader(com.google.common.cache.CacheLoader) RecordCursor(com.facebook.presto.spi.RecordCursor) DataSize(io.airlift.units.DataSize) List(java.util.List) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) RowExpressionService(com.facebook.presto.spi.relation.RowExpressionService) Optional(java.util.Optional) CacheBuilder(com.google.common.cache.CacheBuilder) HiveCoercer.createCoercer(com.facebook.presto.hive.HiveCoercer.createCoercer) PARTITION_KEY(com.facebook.presto.hive.HiveColumnHandle.ColumnType.PARTITION_KEY) Column(com.facebook.presto.hive.metastore.Column) REGULAR(com.facebook.presto.hive.HiveColumnHandle.ColumnType.REGULAR) ConnectorTableLayoutHandle(com.facebook.presto.spi.ConnectorTableLayoutHandle) PrestoException(com.facebook.presto.spi.PrestoException) OptionalInt(java.util.OptionalInt) Function(java.util.function.Function) HiveSessionProperties.isUseRecordPageSourceForCustomSplit(com.facebook.presto.hive.HiveSessionProperties.isUseRecordPageSourceForCustomSplit) System.identityHashCode(java.lang.System.identityHashCode) Inject(javax.inject.Inject) HashSet(java.util.HashSet) Subfield(com.facebook.presto.common.Subfield) ImmutableList(com.google.common.collect.ImmutableList) TypeManager(com.facebook.presto.common.type.TypeManager) Objects.requireNonNull(java.util.Objects.requireNonNull) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) Type(com.facebook.presto.common.type.Type) RowExpression(com.facebook.presto.spi.relation.RowExpression) Storage(com.facebook.presto.hive.metastore.Storage) Properties(java.util.Properties) PathElement(com.facebook.presto.common.Subfield.PathElement) HiveUtil.getPrefilledColumnValue(com.facebook.presto.hive.HiveUtil.getPrefilledColumnValue) MetastoreUtil.reconstructPartitionSchema(com.facebook.presto.hive.metastore.MetastoreUtil.reconstructPartitionSchema) Iterables.getOnlyElement(com.google.common.collect.Iterables.getOnlyElement) Domain(com.facebook.presto.common.predicate.Domain) TupleDomain(com.facebook.presto.common.predicate.TupleDomain) OPTIMIZED(com.facebook.presto.spi.relation.ExpressionOptimizer.Level.OPTIMIZED) ConnectorSplit(com.facebook.presto.spi.ConnectorSplit) Collectors.toList(java.util.stream.Collectors.toList) ConnectorPageSource(com.facebook.presto.spi.ConnectorPageSource) ColumnHandle(com.facebook.presto.spi.ColumnHandle) SYNTHESIZED(com.facebook.presto.hive.HiveColumnHandle.ColumnType.SYNTHESIZED) HiveUtil.parsePartitionValue(com.facebook.presto.hive.HiveUtil.parsePartitionValue) VisibleForTesting(com.google.common.annotations.VisibleForTesting) MetastoreUtil.getHiveSchema(com.facebook.presto.hive.metastore.MetastoreUtil.getHiveSchema) HiveUtil.shouldUseRecordReaderFromInputFormat(com.facebook.presto.hive.HiveUtil.shouldUseRecordReaderFromInputFormat) ColumnHandle(com.facebook.presto.spi.ColumnHandle) NullableValue(com.facebook.presto.common.predicate.NullableValue) Type(com.facebook.presto.common.type.Type) Domain(com.facebook.presto.common.predicate.Domain) TupleDomain(com.facebook.presto.common.predicate.TupleDomain)

Aggregations

NullableValue (com.facebook.presto.common.predicate.NullableValue)26 ColumnHandle (com.facebook.presto.spi.ColumnHandle)17 TupleDomain (com.facebook.presto.common.predicate.TupleDomain)12 ConnectorSession (com.facebook.presto.spi.ConnectorSession)12 ImmutableList (com.google.common.collect.ImmutableList)9 Map (java.util.Map)9 SchemaTableName (com.facebook.presto.spi.SchemaTableName)8 ImmutableMap (com.google.common.collect.ImmutableMap)8 Optional (java.util.Optional)8 Set (java.util.Set)8 Domain (com.facebook.presto.common.predicate.Domain)7 Type (com.facebook.presto.common.type.Type)7 ConnectorTableHandle (com.facebook.presto.spi.ConnectorTableHandle)7 ConnectorTableLayoutHandle (com.facebook.presto.spi.ConnectorTableLayoutHandle)7 Constraint (com.facebook.presto.spi.Constraint)7 ImmutableList.toImmutableList (com.google.common.collect.ImmutableList.toImmutableList)7 List (java.util.List)7 Objects.requireNonNull (java.util.Objects.requireNonNull)7 PrestoException (com.facebook.presto.spi.PrestoException)6 ImmutableSet (com.google.common.collect.ImmutableSet)6