Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Push down version filter in the Delta $history table #16192

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 @@ -54,8 +54,8 @@ public Connector create(String catalogName, Map<String, String> config, Connecto
Class<?> moduleClass = classLoader.loadClass(Module.class.getName());
Object moduleInstance = classLoader.loadClass(module.getName()).getConstructor().newInstance();
return (Connector) classLoader.loadClass(InternalDeltaLakeConnectorFactory.class.getName())
.getMethod("createConnector", String.class, Map.class, ConnectorContext.class, Optional.class, moduleClass)
.invoke(null, catalogName, config, context, Optional.empty(), moduleInstance);
.getMethod("createConnector", String.class, Map.class, ConnectorContext.class, Optional.class, Optional.class, moduleClass)
.invoke(null, catalogName, config, context, Optional.empty(), Optional.empty(), moduleInstance);
}
catch (InvocationTargetException e) {
Throwable targetException = e.getTargetException();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,47 +14,75 @@
package io.trino.plugin.deltalake;

import com.google.common.collect.ImmutableList;
import io.trino.filesystem.TrinoFileSystem;
import io.trino.filesystem.TrinoFileSystemFactory;
import io.trino.plugin.deltalake.metastore.DeltaLakeMetastore;
import io.trino.plugin.deltalake.transactionlog.CommitInfoEntry;
import io.trino.plugin.deltalake.util.PageListBuilder;
import io.trino.spi.Page;
import io.trino.plugin.deltalake.transactionlog.DeltaLakeTransactionLogEntry;
import io.trino.plugin.deltalake.transactionlog.DeltaLakeTransactionLogIterator;
import io.trino.spi.block.BlockBuilder;
import io.trino.spi.connector.ColumnMetadata;
import io.trino.spi.connector.ConnectorPageSource;
import io.trino.spi.connector.ConnectorSession;
import io.trino.spi.connector.ConnectorTableMetadata;
import io.trino.spi.connector.ConnectorTransactionHandle;
import io.trino.spi.connector.FixedPageSource;
import io.trino.spi.connector.InMemoryRecordSet;
import io.trino.spi.connector.RecordCursor;
import io.trino.spi.connector.SchemaTableName;
import io.trino.spi.connector.SystemTable;
import io.trino.spi.predicate.Domain;
import io.trino.spi.predicate.Range;
import io.trino.spi.predicate.TupleDomain;
import io.trino.spi.type.TimeZoneKey;
import io.trino.spi.type.Type;
import io.trino.spi.type.TypeManager;
import org.apache.hadoop.fs.Path;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

import static com.google.common.base.Verify.verify;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.Streams.stream;
import static io.trino.spi.type.BigintType.BIGINT;
import static io.trino.spi.type.BooleanType.BOOLEAN;
import static io.trino.spi.type.DateTimeEncoding.packDateTimeWithZone;
import static io.trino.spi.type.TimestampWithTimeZoneType.TIMESTAMP_TZ_MILLIS;
import static io.trino.spi.type.TypeSignature.mapType;
import static io.trino.spi.type.VarcharType.VARCHAR;
import static java.util.Comparator.comparingLong;
import static java.util.Objects.requireNonNull;

public class DeltaLakeHistoryTable
implements SystemTable
{
private static final int VERSION_COLUMN_INDEX = 0;
private final SchemaTableName tableName;
private final ConnectorTableMetadata tableMetadata;
private final List<CommitInfoEntry> commitInfoEntries;
private final List<Type> types;
private final TrinoFileSystemFactory fileSystemFactory;
private final DeltaLakeMetastore metastore;

public DeltaLakeHistoryTable(SchemaTableName tableName, List<CommitInfoEntry> commitInfoEntries, TypeManager typeManager)
private final Type varcharToVarcharMapType;

public DeltaLakeHistoryTable(
SchemaTableName tableName,
TrinoFileSystemFactory fileSystemFactory,
DeltaLakeMetastore metastore,
TypeManager typeManager)
{
this.tableName = requireNonNull(tableName, "tableName is null");
requireNonNull(typeManager, "typeManager is null");
this.commitInfoEntries = ImmutableList.copyOf(requireNonNull(commitInfoEntries, "commitInfoEntries is null")).stream()
.sorted(comparingLong(CommitInfoEntry::getVersion).reversed())
.collect(toImmutableList());
this.fileSystemFactory = requireNonNull(fileSystemFactory, "fileSystemFactory is null");
this.metastore = requireNonNull(metastore, "metastore is null");

SchemaTableName systemTableName = new SchemaTableName(
tableName.getSchemaName(),
new DeltaLakeTableName(tableName.getTableName(), DeltaLakeTableType.HISTORY).getTableNameWithType());
tableMetadata = new ConnectorTableMetadata(
requireNonNull(tableName, "tableName is null"),
systemTableName,
findinpath marked this conversation as resolved.
Show resolved Hide resolved
ImmutableList.<ColumnMetadata>builder()
.add(new ColumnMetadata("version", BIGINT))
.add(new ColumnMetadata("timestamp", TIMESTAMP_TZ_MILLIS))
Expand All @@ -68,6 +96,10 @@ public DeltaLakeHistoryTable(SchemaTableName tableName, List<CommitInfoEntry> co
.add(new ColumnMetadata("is_blind_append", BOOLEAN))
//TODO add support for operationMetrics, userMetadata, engineInfo
.build());
types = tableMetadata.getColumns().stream()
.map(ColumnMetadata::getType)
.collect(toImmutableList());
varcharToVarcharMapType = typeManager.getType(mapType(VARCHAR.getTypeSignature(), VARCHAR.getTypeSignature()));
}

@Override
Expand All @@ -83,51 +115,108 @@ public ConnectorTableMetadata getTableMetadata()
}

@Override
public ConnectorPageSource pageSource(ConnectorTransactionHandle transactionHandle, ConnectorSession session, TupleDomain<Integer> constraint)
public RecordCursor cursor(ConnectorTransactionHandle transactionHandle, ConnectorSession session, TupleDomain<Integer> constraint)
{
if (commitInfoEntries.isEmpty()) {
return new FixedPageSource(ImmutableList.of());
}
return new FixedPageSource(buildPages(session));
VersionRange versionRange = extractVersionRange(constraint);
TimeZoneKey timeZoneKey = session.getTimeZoneKey();
TrinoFileSystem fileSystem = fileSystemFactory.create(session);
Iterable<List<Object>> records = () ->
stream(new DeltaLakeTransactionLogIterator(
fileSystem,
new Path(metastore.getTableLocation(tableName, session)),
versionRange.startVersion,
versionRange.endVersion))
.flatMap(Collection::stream)
.map(DeltaLakeTransactionLogEntry::getCommitInfo)
.filter(Objects::nonNull)
.map(commitInfoEntry -> getRecord(commitInfoEntry, timeZoneKey))
.iterator();

return new InMemoryRecordSet(types, records).cursor();
}

private List<Page> buildPages(ConnectorSession session)
private List<Object> getRecord(CommitInfoEntry commitInfoEntry, TimeZoneKey timeZoneKey)
{
PageListBuilder pagesBuilder = PageListBuilder.forTable(tableMetadata);
TimeZoneKey timeZoneKey = session.getTimeZoneKey();
List<Object> columns = new ArrayList<>();
columns.add(commitInfoEntry.getVersion());
columns.add(packDateTimeWithZone(commitInfoEntry.getTimestamp(), timeZoneKey));
columns.add(commitInfoEntry.getUserId());
columns.add(commitInfoEntry.getUserName());
columns.add(commitInfoEntry.getOperation());
if (commitInfoEntry.getOperationParameters() == null) {
columns.add(null);
}
else {
columns.add(toVarcharVarcharMapBlock(commitInfoEntry.getOperationParameters()));
}
columns.add(commitInfoEntry.getClusterId());
columns.add(commitInfoEntry.getReadVersion());
columns.add(commitInfoEntry.getIsolationLevel());
columns.add(commitInfoEntry.isBlindAppend().orElse(null));

commitInfoEntries.forEach(commitInfoEntry -> {
pagesBuilder.beginRow();
return columns;
}

pagesBuilder.appendBigint(commitInfoEntry.getVersion());
pagesBuilder.appendTimestampTzMillis(commitInfoEntry.getTimestamp(), timeZoneKey);
write(commitInfoEntry.getUserId(), pagesBuilder);
write(commitInfoEntry.getUserName(), pagesBuilder);
write(commitInfoEntry.getOperation(), pagesBuilder);
if (commitInfoEntry.getOperationParameters() == null) {
pagesBuilder.appendNull();
private Object toVarcharVarcharMapBlock(Map<String, String> values)
{
BlockBuilder blockBuilder = varcharToVarcharMapType.createBlockBuilder(null, 1);
BlockBuilder singleMapBlockBuilder = blockBuilder.beginBlockEntry();
values.forEach((key, value) -> {
VARCHAR.writeString(singleMapBlockBuilder, key);
VARCHAR.writeString(singleMapBlockBuilder, value);
});
blockBuilder.closeEntry();
return varcharToVarcharMapType.getObject(blockBuilder, 0);
}

private static VersionRange extractVersionRange(TupleDomain<Integer> constraint)
{
Domain versionDomain = constraint.getDomains()
.map(map -> map.get(VERSION_COLUMN_INDEX))
.orElse(Domain.all(BIGINT));
Optional<Long> startVersion = Optional.empty();
Optional<Long> endVersion = Optional.empty();
if (versionDomain.isAll() || versionDomain.isNone()) {
return new VersionRange(startVersion, endVersion);
}
List<Range> orderedRanges = versionDomain.getValues().getRanges().getOrderedRanges();
if (orderedRanges.size() == 1) {
// Opt for a rather pragmatical choice of extracting the version range
// only when dealing with a single range
Range range = orderedRanges.get(0);
if (range.isSingleValue()) {
long version = (long) range.getLowBoundedValue();
startVersion = Optional.of(version);
endVersion = Optional.of(version);
}
else {
pagesBuilder.appendVarcharVarcharMap(commitInfoEntry.getOperationParameters());
if (!range.isLowUnbounded()) {
long version = (long) range.getLowBoundedValue();
if (!range.isLowInclusive()) {
version++;
}
startVersion = Optional.of(version);
}
if (!range.isHighUnbounded()) {
long version = (long) range.getHighBoundedValue();
if (!range.isHighInclusive()) {
version--;
}
endVersion = Optional.of(version);
}
}
write(commitInfoEntry.getClusterId(), pagesBuilder);
pagesBuilder.appendBigint(commitInfoEntry.getReadVersion());
write(commitInfoEntry.getIsolationLevel(), pagesBuilder);
commitInfoEntry.isBlindAppend().ifPresentOrElse(pagesBuilder::appendBoolean, pagesBuilder::appendNull);

pagesBuilder.endRow();
});

return pagesBuilder.build();
}
return new VersionRange(startVersion, endVersion);
}

private static void write(String value, PageListBuilder pagesBuilder)
private record VersionRange(Optional<Long> startVersion, Optional<Long> endVersion)
{
if (value == null) {
pagesBuilder.appendNull();
}
else {
pagesBuilder.appendVarchar(value);
@SuppressWarnings("UnusedVariable") // TODO: Remove once https://github.com/google/error-prone/issues/2713 is fixed
private VersionRange
{
requireNonNull(startVersion, "startVersion is null");
requireNonNull(endVersion, "endVersion is null");
verify(startVersion.orElse(0L) <= endVersion.orElse(startVersion.orElse(0L)), "startVersion is greater than endVersion");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like a duplicate code from DeltaLakeTransactionLogEntryIterator? we can extract into a method verifyVersion?

}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,12 @@
import io.trino.plugin.deltalake.transactionlog.AddFileEntry;
import io.trino.plugin.deltalake.transactionlog.CdfFileEntry;
import io.trino.plugin.deltalake.transactionlog.CommitInfoEntry;
import io.trino.plugin.deltalake.transactionlog.DeltaLakeTransactionLogEntry;
import io.trino.plugin.deltalake.transactionlog.MetadataEntry;
import io.trino.plugin.deltalake.transactionlog.MetadataEntry.Format;
import io.trino.plugin.deltalake.transactionlog.ProtocolEntry;
import io.trino.plugin.deltalake.transactionlog.RemoveFileEntry;
import io.trino.plugin.deltalake.transactionlog.TableSnapshot;
import io.trino.plugin.deltalake.transactionlog.checkpoint.CheckpointWriterManager;
import io.trino.plugin.deltalake.transactionlog.checkpoint.TransactionLogTail;
import io.trino.plugin.deltalake.transactionlog.statistics.DeltaLakeFileStatistics;
import io.trino.plugin.deltalake.transactionlog.writer.TransactionConflictException;
import io.trino.plugin.deltalake.transactionlog.writer.TransactionLogWriter;
Expand Down Expand Up @@ -140,7 +138,6 @@
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.OptionalLong;
Expand Down Expand Up @@ -2480,12 +2477,12 @@ private Optional<SystemTable> getRawSystemTable(ConnectorSession session, Schema
return Optional.empty();
}
DeltaLakeTableName deltaLakeTableName = new DeltaLakeTableName(name, tableType.get());
SchemaTableName systemTableName = new SchemaTableName(tableName.getSchemaName(), deltaLakeTableName.getTableNameWithType());
return switch (deltaLakeTableName.getTableType()) {
case DATA -> Optional.empty(); // Handled above
case HISTORY -> Optional.of(new DeltaLakeHistoryTable(
systemTableName,
getCommitInfoEntries(tableHandle.getSchemaTableName(), session),
tableHandle.getSchemaTableName(),
fileSystemFactory,
metastore,
typeManager));
};
}
Expand Down Expand Up @@ -2566,23 +2563,6 @@ public DeltaLakeMetastore getMetastore()
return metastore;
}

private List<CommitInfoEntry> getCommitInfoEntries(SchemaTableName table, ConnectorSession session)
{
TrinoFileSystem fileSystem = fileSystemFactory.create(session);
try {
return TransactionLogTail.loadNewTail(fileSystem, new Path(metastore.getTableLocation(table, session)), Optional.empty()).getFileEntries().stream()
.map(DeltaLakeTransactionLogEntry::getCommitInfo)
.filter(Objects::nonNull)
.collect(toImmutableList());
}
catch (TrinoException e) {
throw e;
}
catch (IOException | RuntimeException e) {
throw new TrinoException(DELTA_LAKE_INVALID_SCHEMA, "Error getting commit info entries for " + table, e);
}
}

private static ColumnMetadata getColumnMetadata(DeltaLakeColumnHandle column, @Nullable String comment, boolean nullability)
{
return ColumnMetadata.builder()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import io.airlift.bootstrap.LifeCycleManager;
import io.airlift.event.client.EventModule;
import io.airlift.json.JsonModule;
import io.trino.filesystem.TrinoFileSystemFactory;
import io.trino.filesystem.hdfs.HdfsFileSystemModule;
import io.trino.hdfs.HdfsModule;
import io.trino.hdfs.authentication.HdfsAuthenticationModule;
Expand Down Expand Up @@ -73,6 +74,7 @@ public static Connector createConnector(
Map<String, String> config,
ConnectorContext context,
Optional<Module> metastoreModule,
Optional<TrinoFileSystemFactory> fileSystemFactory,
Module module)
{
ClassLoader classLoader = InternalDeltaLakeConnectorFactory.class.getClassLoader();
Expand All @@ -91,7 +93,6 @@ public static Connector createConnector(
new HiveGcsModule(),
new DeltaLakeGcsModule(),
new HdfsAuthenticationModule(),
new HdfsFileSystemModule(),
new CatalogNameModule(catalogName),
metastoreModule.orElse(new DeltaLakeMetastoreModule()),
new DeltaLakeModule(),
Expand All @@ -103,6 +104,9 @@ public static Connector createConnector(
binder.bind(PageIndexerFactory.class).toInstance(context.getPageIndexerFactory());
binder.bind(CatalogName.class).toInstance(new CatalogName(catalogName));
newSetBinder(binder, EventListener.class);
fileSystemFactory.ifPresentOrElse(
factory -> binder.bind(TrinoFileSystemFactory.class).toInstance(factory),
() -> binder.install(new HdfsFileSystemModule()));
},
module);

Expand Down
Loading