Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ public TableStatisticAggregation createStatisticsAggregation(TableStatisticsMeta
for (ColumnStatisticMetadata columnStatisticMetadata : statisticsMetadata.getColumnStatistics()) {
String columnName = columnStatisticMetadata.getColumnName();
Symbol inputSymbol = columnToSymbolMap.get(columnName);
verifyNotNull(inputSymbol, "inputSymbol is null");
verifyNotNull(inputSymbol, "no symbol for [%s] column, these columns exist: %s", columnName, columnToSymbolMap.keySet());
Type inputType = symbolAllocator.getTypes().get(inputSymbol);
verifyNotNull(inputType, "inputType is null for symbol: %s", inputSymbol);
ColumnStatisticsAggregation aggregation;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
@DefunctConfig("delta.experimental.ignore-checkpoint-write-failures")
public class DeltaLakeConfig
{
public static final String EXTENDED_STATISTICS_ENABLED = "delta.extended-statistics.enabled";
public static final String VACUUM_MIN_RETENTION = "delta.vacuum.min-retention";

// Runtime.getRuntime().maxMemory() is not 100% stable and may return slightly different value over JVM lifetime. We use
Expand All @@ -66,6 +67,7 @@ public class DeltaLakeConfig
private Duration dynamicFilteringWaitTimeout = new Duration(0, SECONDS);
private boolean tableStatisticsEnabled = true;
private boolean extendedStatisticsEnabled = true;
private boolean collectExtendedStatisticsColumnStatisticsOnWrite = true;
private HiveCompressionCodec compressionCodec = HiveCompressionCodec.SNAPPY;
private long perTransactionMetastoreCacheMaximumSize = 1000;
private boolean deleteSchemaLocationsFallback;
Expand Down Expand Up @@ -321,14 +323,27 @@ public boolean isExtendedStatisticsEnabled()
return extendedStatisticsEnabled;
}

@Config("delta.extended-statistics.enabled")
@Config(EXTENDED_STATISTICS_ENABLED)
@ConfigDescription("Use extended statistics collected by ANALYZE")
public DeltaLakeConfig setExtendedStatisticsEnabled(boolean extendedStatisticsEnabled)
{
this.extendedStatisticsEnabled = extendedStatisticsEnabled;
return this;
}

public boolean isCollectExtendedStatisticsColumnStatisticsOnWrite()
{
return collectExtendedStatisticsColumnStatisticsOnWrite;
}

@Config("delta.extended-statistics.collect-on-write")
@ConfigDescription("Enables automatic column level extended statistics collection on write")
public DeltaLakeConfig setCollectExtendedStatisticsColumnStatisticsOnWrite(boolean collectExtendedStatisticsColumnStatisticsOnWrite)
{
this.collectExtendedStatisticsColumnStatisticsOnWrite = collectExtendedStatisticsColumnStatisticsOnWrite;
return this;
}

@NotNull
public HiveCompressionCodec getCompressionCodec()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.OptionalLong;
Expand All @@ -150,6 +151,7 @@
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.MoreCollectors.toOptional;
import static io.trino.plugin.deltalake.DeltaLakeColumnHandle.FILE_MODIFIED_TIME_COLUMN_NAME;
import static io.trino.plugin.deltalake.DeltaLakeColumnHandle.MERGE_ROW_ID_TYPE;
import static io.trino.plugin.deltalake.DeltaLakeColumnHandle.ROW_ID_COLUMN_NAME;
Expand All @@ -162,6 +164,7 @@
import static io.trino.plugin.deltalake.DeltaLakeColumnType.SYNTHESIZED;
import static io.trino.plugin.deltalake.DeltaLakeErrorCode.DELTA_LAKE_BAD_WRITE;
import static io.trino.plugin.deltalake.DeltaLakeErrorCode.DELTA_LAKE_INVALID_SCHEMA;
import static io.trino.plugin.deltalake.DeltaLakeSessionProperties.isCollectExtendedStatisticsColumnStatisticsOnWrite;
import static io.trino.plugin.deltalake.DeltaLakeSessionProperties.isExtendedStatisticsEnabled;
import static io.trino.plugin.deltalake.DeltaLakeSessionProperties.isTableStatisticsEnabled;
import static io.trino.plugin.deltalake.DeltaLakeTableProperties.CHECKPOINT_INTERVAL_PROPERTY;
Expand Down Expand Up @@ -987,6 +990,15 @@ public Optional<ConnectorOutputMetadata> finishCreateTable(
handle.getComment());
appendAddFileEntries(transactionLogWriter, dataFileInfos, handle.getPartitionedBy(), true);
transactionLogWriter.flush();

if (isCollectExtendedStatisticsColumnStatisticsOnWrite(session) && !computedStatistics.isEmpty()) {
updateTableStatistics(
session,
Optional.empty(),
location,
computedStatistics);
}

PrincipalPrivileges principalPrivileges = buildInitialPrivilegeSet(table.getOwner().orElseThrow());

try {
Expand Down Expand Up @@ -1092,7 +1104,7 @@ public void setColumnComment(ConnectorSession session, ConnectorTableHandle tabl
ImmutableMap.Builder<String, String> columnComments = ImmutableMap.builder();
columnComments.putAll(getColumnComments(deltaLakeTableHandle.getMetadataEntry()).entrySet().stream()
.filter(e -> !e.getKey().equals(deltaLakeColumnHandle.getName()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
.collect(Collectors.toMap(Entry::getKey, Entry::getValue)));
comment.ifPresent(s -> columnComments.put(deltaLakeColumnHandle.getName(), s));

TransactionLogWriter transactionLogWriter = transactionLogWriterFactory.newWriter(session, deltaLakeTableHandle.getLocation());
Expand Down Expand Up @@ -2148,7 +2160,7 @@ public Optional<ConstraintApplicationResult<ConnectorTableHandle>> applyFilter(C

ImmutableMap.Builder<DeltaLakeColumnHandle, Domain> enforceableDomains = ImmutableMap.builder();
ImmutableMap.Builder<DeltaLakeColumnHandle, Domain> unenforceableDomains = ImmutableMap.builder();
for (Map.Entry<ColumnHandle, Domain> domainEntry : constraintDomains.entrySet()) {
for (Entry<ColumnHandle, Domain> domainEntry : constraintDomains.entrySet()) {
DeltaLakeColumnHandle column = (DeltaLakeColumnHandle) domainEntry.getKey();
if (!partitionColumns.contains(column)) {
unenforceableDomains.put(column, domainEntry.getValue());
Expand Down Expand Up @@ -2234,9 +2246,10 @@ public Optional<TableScanRedirectApplicationResult> applyTableScanRedirect(Conne
public ConnectorAnalyzeMetadata getStatisticsCollectionMetadata(ConnectorSession session, ConnectorTableHandle tableHandle, Map<String, Object> analyzeProperties)
{
if (!isExtendedStatisticsEnabled(session)) {
throw new TrinoException(
NOT_SUPPORTED,
"ANALYZE not supported if extended statistics are disabled. Enable via delta.extended-statistics.enabled config property or extended_statistics_enabled session property.");
throw new TrinoException(NOT_SUPPORTED, format(
"ANALYZE not supported if extended statistics are disabled. Enable via %s config property or %s session property.",
DeltaLakeConfig.EXTENDED_STATISTICS_ENABLED,
DeltaLakeSessionProperties.EXTENDED_STATISTICS_ENABLED));
}

DeltaLakeTableHandle handle = (DeltaLakeTableHandle) tableHandle;
Expand All @@ -2256,6 +2269,9 @@ public ConnectorAnalyzeMetadata getStatisticsCollectionMetadata(ConnectorSession
alreadyAnalyzedModifiedTimeMax.orElse(Instant.ofEpochMilli(0))));
}

Set<String> allColumnNames = extractColumnMetadata(metadata, typeManager).stream()
.map(ColumnMetadata::getName)
.collect(toImmutableSet());
Optional<Set<String>> analyzeColumnNames = DeltaLakeAnalyzeProperties.getColumnNames(analyzeProperties);
if (analyzeColumnNames.isPresent()) {
Set<String> columnNames = analyzeColumnNames.get();
Expand All @@ -2264,9 +2280,6 @@ public ConnectorAnalyzeMetadata getStatisticsCollectionMetadata(ConnectorSession
throw new TrinoException(INVALID_ANALYZE_PROPERTY, "Cannot specify empty list of columns for analysis");
}

Set<String> allColumnNames = extractColumnMetadata(metadata, typeManager).stream()
.map(ColumnMetadata::getName)
.collect(toImmutableSet());
if (!allColumnNames.containsAll(columnNames)) {
throw new TrinoException(
INVALID_ANALYZE_PROPERTY,
Expand Down Expand Up @@ -2299,31 +2312,61 @@ public ConnectorAnalyzeMetadata getStatisticsCollectionMetadata(ConnectorSession
handle.getReadVersion(),
false);

TableStatisticsMetadata statisticsMetadata = getStatisticsCollectionMetadata(
statistics,
extractColumnMetadata(metadata, typeManager),
analyzeColumnNames.orElse(allColumnNames),
true);

return new ConnectorAnalyzeMetadata(newHandle, statisticsMetadata);
}

@Override
public TableStatisticsMetadata getStatisticsCollectionMetadataForWrite(ConnectorSession session, ConnectorTableMetadata tableMetadata)
{
if (!isCollectExtendedStatisticsColumnStatisticsOnWrite(session)) {
return TableStatisticsMetadata.empty();
}

Set<String> allColumnNames = tableMetadata.getColumns().stream()
.map(ColumnMetadata::getName)
.collect(toImmutableSet());

return getStatisticsCollectionMetadata(
Optional.empty(), // TODO what about INSERT to an existing table
tableMetadata.getColumns(),
allColumnNames,
false);
}

private TableStatisticsMetadata getStatisticsCollectionMetadata(
Optional<ExtendedStatistics> existingStatistics,
List<ColumnMetadata> tableColumns,
Set<String> analyzeColumnNames,
boolean includeMaxFileModifiedTime)
{
ImmutableSet.Builder<ColumnStatisticMetadata> columnStatistics = ImmutableSet.builder();
extractColumnMetadata(metadata, typeManager).stream()
tableColumns.stream()
.filter(DeltaLakeMetadata::shouldCollectExtendedStatistics)
.filter(columnMetadata ->
analyzeColumnNames
.map(columnNames -> columnNames.contains(columnMetadata.getName()))
.orElse(true))
.filter(columnMetadata -> analyzeColumnNames.contains(columnMetadata.getName()))
.forEach(columnMetadata -> {
if (!(columnMetadata.getType() instanceof FixedWidthType)) {
if (statistics.isEmpty() || totalSizeStatisticsExists(statistics.get().getColumnStatistics(), columnMetadata.getName())) {
if (existingStatistics.isEmpty() || totalSizeStatisticsExists(existingStatistics.get().getColumnStatistics(), columnMetadata.getName())) {
columnStatistics.add(new ColumnStatisticMetadata(columnMetadata.getName(), TOTAL_SIZE_IN_BYTES));
}
}
columnStatistics.add(new ColumnStatisticMetadata(columnMetadata.getName(), NUMBER_OF_DISTINCT_VALUES_SUMMARY));
});

// collect max(file modification time) for sake of incremental ANALYZE
columnStatistics.add(new ColumnStatisticMetadata(FILE_MODIFIED_TIME_COLUMN_NAME, MAX_VALUE));
if (includeMaxFileModifiedTime) {
// collect max(file modification time) for sake of incremental ANALYZE
columnStatistics.add(new ColumnStatisticMetadata(FILE_MODIFIED_TIME_COLUMN_NAME, MAX_VALUE));
}

TableStatisticsMetadata statisticsMetadata = new TableStatisticsMetadata(
return new TableStatisticsMetadata(
columnStatistics.build(),
ImmutableSet.of(),
ImmutableList.of());

return new ConnectorAnalyzeMetadata(newHandle, statisticsMetadata);
}

private static boolean shouldCollectExtendedStatistics(ColumnMetadata columnMetadata)
Expand Down Expand Up @@ -2356,6 +2399,15 @@ public void finishStatisticsCollection(ConnectorSession session, ConnectorTableH
DeltaLakeTableHandle tableHandle = (DeltaLakeTableHandle) table;
AnalyzeHandle analyzeHandle = tableHandle.getAnalyzeHandle().orElseThrow(() -> new IllegalArgumentException("analyzeHandle not set"));
String location = metastore.getTableLocation(tableHandle.getSchemaTableName(), session);
updateTableStatistics(
session,
Optional.of(analyzeHandle),
location,
computedStatistics);
}

private void updateTableStatistics(ConnectorSession session, Optional<AnalyzeHandle> analyzeHandle, String location, Collection<ComputedStatistics> computedStatistics)
{
Optional<ExtendedStatistics> oldStatistics = statisticsAccess.readExtendedStatistics(session, location);

// more elaborate logic for handling statistics model evaluation may need to be introduced in the future
Expand All @@ -2369,17 +2421,17 @@ public void finishStatisticsCollection(ConnectorSession session, ConnectorTableH
.orElseGet(ImmutableMap::of);
Map<String, DeltaLakeColumnStatistics> newColumnStatistics = toDeltaLakeColumnStatistics(computedStatistics);

Map<String, DeltaLakeColumnStatistics> mergedColumnStatistics = new HashMap<>();

// only keep stats for existing columns
Set<String> newColumns = newColumnStatistics.keySet();
oldColumnStatistics.entrySet().stream()
.filter(entry -> newColumns.contains(entry.getKey()))
.forEach(entry -> mergedColumnStatistics.put(entry.getKey(), entry.getValue()));

newColumnStatistics.forEach((columnName, columnStatistics) -> {
mergedColumnStatistics.merge(columnName, columnStatistics, DeltaLakeColumnStatistics::update);
});
Map<String, DeltaLakeColumnStatistics> mergedColumnStatistics = newColumnStatistics.entrySet().stream()
.collect(toImmutableMap(
Entry::getKey,
entry -> {
String columnName = entry.getKey();
DeltaLakeColumnStatistics newStats = entry.getValue();
DeltaLakeColumnStatistics oldStats = oldColumnStatistics.get(columnName);
return oldStats == null
? newStats
: oldStats.update(newStats);
}));

Optional<Instant> maxFileModificationTime = getMaxFileModificationTime(computedStatistics);
// We do not want to hinder our future calls to ANALYZE if one of the files we analyzed have modification time far in the future.
Expand All @@ -2393,18 +2445,17 @@ public void finishStatisticsCollection(ConnectorSession session, ConnectorTableH
finalAlreadyAnalyzedModifiedTimeMax = Comparators.max(oldStatistics.get().getAlreadyAnalyzedModifiedTimeMax(), finalAlreadyAnalyzedModifiedTimeMax);
}

if (analyzeHandle.getColumns().isPresent() && !mergedColumnStatistics.keySet().equals(analyzeHandle.getColumns().get())) {
// sanity validation
throw new IllegalStateException(
format("Unexpected columns in in mergedColumnStatistics %s; expected %s",
mergedColumnStatistics.keySet(),
analyzeHandle.getColumns().get()));
}
analyzeHandle.flatMap(AnalyzeHandle::getColumns).ifPresent(analyzeColumns -> {
if (!mergedColumnStatistics.keySet().equals(analyzeColumns)) {
// sanity validation
throw new IllegalStateException(format("Unexpected columns in in mergedColumnStatistics %s; expected %s", mergedColumnStatistics.keySet(), analyzeColumns));
}
});

ExtendedStatistics mergedExtendedStatistics = new ExtendedStatistics(
finalAlreadyAnalyzedModifiedTimeMax,
mergedColumnStatistics,
analyzeHandle.getColumns());
analyzeHandle.flatMap(AnalyzeHandle::getColumns));

statisticsAccess.updateExtendedStatistics(session, location, mergedExtendedStatistics);
}
Expand Down Expand Up @@ -2513,7 +2564,7 @@ private static Map<String, DeltaLakeColumnStatistics> toDeltaLakeColumnStatistic
// Only statistics for whole table are collected
ComputedStatistics singleStatistics = Iterables.getOnlyElement(computedStatistics);
return createColumnToComputedStatisticsMap(singleStatistics.getColumnStatistics()).entrySet().stream()
.collect(toImmutableMap(Map.Entry::getKey, entry -> createDeltaLakeColumnStatistics(entry.getValue())));
.collect(toImmutableMap(Entry::getKey, entry -> createDeltaLakeColumnStatistics(entry.getValue())));
}

private static Map<String, Map<ColumnStatisticType, Block>> createColumnToComputedStatisticsMap(Map<ColumnStatisticMetadata, Block> computedStatistics)
Expand Down Expand Up @@ -2576,8 +2627,8 @@ private static Optional<Instant> getMaxFileModificationTime(Collection<ComputedS
}
return Optional.of(Instant.ofEpochMilli(unpackMillisUtc(TimestampWithTimeZoneType.TIMESTAMP_TZ_MILLIS.getLong(entry.getValue(), 0))));
})
.findFirst()
.orElseThrow();
.collect(toOptional())
.flatMap(identity());
}

public DeltaLakeMetastore getMetastore()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@ public final class DeltaLakeSessionProperties
private static final String TIMESTAMP_PRECISION = "timestamp_precision";
private static final String DYNAMIC_FILTERING_WAIT_TIMEOUT = "dynamic_filtering_wait_timeout";
private static final String TABLE_STATISTICS_ENABLED = "statistics_enabled";
private static final String EXTENDED_STATISTICS_ENABLED = "extended_statistics_enabled";
public static final String EXTENDED_STATISTICS_ENABLED = "extended_statistics_enabled";
public static final String COLLECT_EXTENDED_STATISTICS_ON_WRITE = "collect_extended_statistics_on_write";

private final List<PropertyMetadata<?>> sessionProperties;

Expand Down Expand Up @@ -140,6 +141,11 @@ public DeltaLakeSessionProperties(
"Use extended statistics collected by ANALYZE",
deltaLakeConfig.isExtendedStatisticsEnabled(),
false),
booleanProperty(
COLLECT_EXTENDED_STATISTICS_ON_WRITE,
"Enables automatic column level extended statistics collection on write",
deltaLakeConfig.isCollectExtendedStatisticsColumnStatisticsOnWrite(),
false),
enumProperty(
COMPRESSION_CODEC,
"Compression codec to use when writing new data files",
Expand Down Expand Up @@ -219,6 +225,11 @@ public static boolean isExtendedStatisticsEnabled(ConnectorSession session)
return session.getProperty(EXTENDED_STATISTICS_ENABLED, Boolean.class);
}

public static boolean isCollectExtendedStatisticsColumnStatisticsOnWrite(ConnectorSession session)
{
return session.getProperty(COLLECT_EXTENDED_STATISTICS_ON_WRITE, Boolean.class);
}

public static HiveCompressionCodec getCompressionCodec(ConnectorSession session)
{
return session.getProperty(COMPRESSION_CODEC, HiveCompressionCodec.class);
Expand Down
Loading