Search in sources :

Example 11 with TableMetadata

use of io.trino.metadata.TableMetadata in project trino by trinodb.

the class BaseHiveConnectorTest method testFileModifiedTimeHiddenColumn.

@Test(dataProvider = "timestampPrecision")
public void testFileModifiedTimeHiddenColumn(HiveTimestampPrecision precision) {
    long testStartTime = Instant.now().toEpochMilli();
    @Language("SQL") String createTable = "CREATE TABLE test_file_modified_time " + "WITH (" + "partitioned_by = ARRAY['col1']" + ") AS " + "SELECT * FROM (VALUES " + "(0, 0), (3, 0), (6, 0), " + "(1, 1), (4, 1), (7, 1), " + "(2, 2), (5, 2) " + " ) t(col0, col1) ";
    assertUpdate(createTable, 8);
    assertTrue(getQueryRunner().tableExists(getSession(), "test_file_modified_time"));
    TableMetadata tableMetadata = getTableMetadata(catalog, TPCH_SCHEMA, "test_file_modified_time");
    List<String> columnNames = ImmutableList.of("col0", "col1", PATH_COLUMN_NAME, FILE_SIZE_COLUMN_NAME, FILE_MODIFIED_TIME_COLUMN_NAME, PARTITION_COLUMN_NAME);
    List<ColumnMetadata> columnMetadatas = tableMetadata.getColumns();
    assertEquals(columnMetadatas.size(), columnNames.size());
    for (int i = 0; i < columnMetadatas.size(); i++) {
        ColumnMetadata columnMetadata = columnMetadatas.get(i);
        assertEquals(columnMetadata.getName(), columnNames.get(i));
        if (columnMetadata.getName().equals(FILE_MODIFIED_TIME_COLUMN_NAME)) {
            assertTrue(columnMetadata.isHidden());
        }
    }
    assertEquals(getPartitions("test_file_modified_time").size(), 3);
    Session sessionWithTimestampPrecision = withTimestampPrecision(getSession(), precision);
    MaterializedResult results = computeActual(sessionWithTimestampPrecision, format("SELECT *, \"%s\" FROM test_file_modified_time", FILE_MODIFIED_TIME_COLUMN_NAME));
    Map<Integer, Instant> fileModifiedTimeMap = new HashMap<>();
    for (int i = 0; i < results.getRowCount(); i++) {
        MaterializedRow row = results.getMaterializedRows().get(i);
        int col0 = (int) row.getField(0);
        int col1 = (int) row.getField(1);
        Instant fileModifiedTime = ((ZonedDateTime) row.getField(2)).toInstant();
        assertThat(fileModifiedTime.toEpochMilli()).isCloseTo(testStartTime, offset(2000L));
        assertEquals(col0 % 3, col1);
        if (fileModifiedTimeMap.containsKey(col1)) {
            assertEquals(fileModifiedTimeMap.get(col1), fileModifiedTime);
        } else {
            fileModifiedTimeMap.put(col1, fileModifiedTime);
        }
    }
    assertEquals(fileModifiedTimeMap.size(), 3);
    assertUpdate("DROP TABLE test_file_modified_time");
}
Also used : TableMetadata(io.trino.metadata.TableMetadata) ColumnMetadata(io.trino.spi.connector.ColumnMetadata) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) Instant(java.time.Instant) ColumnConstraint(io.trino.sql.planner.planprinter.IoPlanPrinter.ColumnConstraint) Constraint(io.trino.spi.connector.Constraint) Language(org.intellij.lang.annotations.Language) ZonedDateTime(java.time.ZonedDateTime) MaterializedResult(io.trino.testing.MaterializedResult) MaterializedRow(io.trino.testing.MaterializedRow) HiveQueryRunner.createBucketedSession(io.trino.plugin.hive.HiveQueryRunner.createBucketedSession) Session(io.trino.Session) Test(org.testng.annotations.Test) BaseConnectorTest(io.trino.testing.BaseConnectorTest)

Example 12 with TableMetadata

use of io.trino.metadata.TableMetadata in project trino by trinodb.

the class ColumnReference method getAssignedSymbol.

@Override
public Optional<Symbol> getAssignedSymbol(PlanNode node, Session session, Metadata metadata, SymbolAliases symbolAliases) {
    TableHandle tableHandle;
    Map<Symbol, ColumnHandle> assignments;
    if (node instanceof TableScanNode) {
        TableScanNode tableScanNode = (TableScanNode) node;
        tableHandle = tableScanNode.getTable();
        assignments = tableScanNode.getAssignments();
    } else if (node instanceof IndexSourceNode) {
        IndexSourceNode indexSourceNode = (IndexSourceNode) node;
        tableHandle = indexSourceNode.getTableHandle();
        assignments = indexSourceNode.getAssignments();
    } else {
        return Optional.empty();
    }
    TableMetadata tableMetadata = metadata.getTableMetadata(session, tableHandle);
    String actualTableName = tableMetadata.getTable().getTableName();
    // Wrong table -> doesn't match.
    if (!tableName.equalsIgnoreCase(actualTableName)) {
        return Optional.empty();
    }
    Optional<ColumnHandle> columnHandle = getColumnHandle(tableHandle, session, metadata);
    checkState(columnHandle.isPresent(), "Table %s doesn't have column %s. Typo in test?", tableName, columnName);
    return getAssignedSymbol(assignments, columnHandle.get());
}
Also used : TableMetadata(io.trino.metadata.TableMetadata) ColumnHandle(io.trino.spi.connector.ColumnHandle) TableScanNode(io.trino.sql.planner.plan.TableScanNode) Symbol(io.trino.sql.planner.Symbol) IndexSourceNode(io.trino.sql.planner.plan.IndexSourceNode) TableHandle(io.trino.metadata.TableHandle)

Example 13 with TableMetadata

use of io.trino.metadata.TableMetadata in project trino by trinodb.

the class CreateTableTask method internalExecute.

@VisibleForTesting
ListenableFuture<Void> internalExecute(CreateTable statement, Session session, List<Expression> parameters, Consumer<Output> outputConsumer) {
    checkArgument(!statement.getElements().isEmpty(), "no columns for table");
    Map<NodeRef<Parameter>, Expression> parameterLookup = parameterExtractor(statement, parameters);
    QualifiedObjectName tableName = createQualifiedObjectName(session, statement, statement.getName());
    Optional<TableHandle> tableHandle = plannerContext.getMetadata().getTableHandle(session, tableName);
    if (tableHandle.isPresent()) {
        if (!statement.isNotExists()) {
            throw semanticException(TABLE_ALREADY_EXISTS, statement, "Table '%s' already exists", tableName);
        }
        return immediateVoidFuture();
    }
    CatalogName catalogName = getRequiredCatalogHandle(plannerContext.getMetadata(), session, statement, tableName.getCatalogName());
    LinkedHashMap<String, ColumnMetadata> columns = new LinkedHashMap<>();
    Map<String, Object> inheritedProperties = ImmutableMap.of();
    boolean includingProperties = false;
    for (TableElement element : statement.getElements()) {
        if (element instanceof ColumnDefinition) {
            ColumnDefinition column = (ColumnDefinition) element;
            String name = column.getName().getValue().toLowerCase(Locale.ENGLISH);
            Type type;
            try {
                type = plannerContext.getTypeManager().getType(toTypeSignature(column.getType()));
            } catch (TypeNotFoundException e) {
                throw semanticException(TYPE_NOT_FOUND, element, "Unknown type '%s' for column '%s'", column.getType(), column.getName());
            }
            if (type.equals(UNKNOWN)) {
                throw semanticException(COLUMN_TYPE_UNKNOWN, element, "Unknown type '%s' for column '%s'", column.getType(), column.getName());
            }
            if (columns.containsKey(name)) {
                throw semanticException(DUPLICATE_COLUMN_NAME, column, "Column name '%s' specified more than once", column.getName());
            }
            if (!column.isNullable() && !plannerContext.getMetadata().getConnectorCapabilities(session, catalogName).contains(NOT_NULL_COLUMN_CONSTRAINT)) {
                throw semanticException(NOT_SUPPORTED, column, "Catalog '%s' does not support non-null column for column name '%s'", catalogName.getCatalogName(), column.getName());
            }
            Map<String, Object> columnProperties = columnPropertyManager.getProperties(catalogName, column.getProperties(), session, plannerContext, accessControl, parameterLookup, true);
            columns.put(name, ColumnMetadata.builder().setName(name).setType(type).setNullable(column.isNullable()).setComment(column.getComment()).setProperties(columnProperties).build());
        } else if (element instanceof LikeClause) {
            LikeClause likeClause = (LikeClause) element;
            QualifiedObjectName originalLikeTableName = createQualifiedObjectName(session, statement, likeClause.getTableName());
            if (plannerContext.getMetadata().getCatalogHandle(session, originalLikeTableName.getCatalogName()).isEmpty()) {
                throw semanticException(CATALOG_NOT_FOUND, statement, "LIKE table catalog '%s' does not exist", originalLikeTableName.getCatalogName());
            }
            RedirectionAwareTableHandle redirection = plannerContext.getMetadata().getRedirectionAwareTableHandle(session, originalLikeTableName);
            TableHandle likeTable = redirection.getTableHandle().orElseThrow(() -> semanticException(TABLE_NOT_FOUND, statement, "LIKE table '%s' does not exist", originalLikeTableName));
            QualifiedObjectName likeTableName = redirection.getRedirectedTableName().orElse(originalLikeTableName);
            if (!tableName.getCatalogName().equals(likeTableName.getCatalogName())) {
                String message = "CREATE TABLE LIKE across catalogs is not supported";
                if (!originalLikeTableName.equals(likeTableName)) {
                    message += format(". LIKE table '%s' redirected to '%s'.", originalLikeTableName, likeTableName);
                }
                throw semanticException(NOT_SUPPORTED, statement, message);
            }
            TableMetadata likeTableMetadata = plannerContext.getMetadata().getTableMetadata(session, likeTable);
            Optional<LikeClause.PropertiesOption> propertiesOption = likeClause.getPropertiesOption();
            if (propertiesOption.isPresent() && propertiesOption.get() == LikeClause.PropertiesOption.INCLUDING) {
                if (includingProperties) {
                    throw semanticException(NOT_SUPPORTED, statement, "Only one LIKE clause can specify INCLUDING PROPERTIES");
                }
                includingProperties = true;
                inheritedProperties = likeTableMetadata.getMetadata().getProperties();
            }
            try {
                accessControl.checkCanSelectFromColumns(session.toSecurityContext(), likeTableName, likeTableMetadata.getColumns().stream().map(ColumnMetadata::getName).collect(toImmutableSet()));
            } catch (AccessDeniedException e) {
                throw new AccessDeniedException("Cannot reference columns of table " + likeTableName);
            }
            if (propertiesOption.orElse(EXCLUDING) == INCLUDING) {
                try {
                    accessControl.checkCanShowCreateTable(session.toSecurityContext(), likeTableName);
                } catch (AccessDeniedException e) {
                    throw new AccessDeniedException("Cannot reference properties of table " + likeTableName);
                }
            }
            likeTableMetadata.getColumns().stream().filter(column -> !column.isHidden()).forEach(column -> {
                if (columns.containsKey(column.getName().toLowerCase(Locale.ENGLISH))) {
                    throw semanticException(DUPLICATE_COLUMN_NAME, element, "Column name '%s' specified more than once", column.getName());
                }
                columns.put(column.getName().toLowerCase(Locale.ENGLISH), column);
            });
        } else {
            throw new TrinoException(GENERIC_INTERNAL_ERROR, "Invalid TableElement: " + element.getClass().getName());
        }
    }
    Map<String, Object> properties = tablePropertyManager.getProperties(catalogName, statement.getProperties(), session, plannerContext, accessControl, parameterLookup, true);
    accessControl.checkCanCreateTable(session.toSecurityContext(), tableName, properties);
    Set<String> specifiedPropertyKeys = statement.getProperties().stream().map(property -> property.getName().getValue()).collect(toImmutableSet());
    Map<String, Object> finalProperties = combineProperties(specifiedPropertyKeys, properties, inheritedProperties);
    ConnectorTableMetadata tableMetadata = new ConnectorTableMetadata(tableName.asSchemaTableName(), ImmutableList.copyOf(columns.values()), finalProperties, statement.getComment());
    try {
        plannerContext.getMetadata().createTable(session, tableName.getCatalogName(), tableMetadata, statement.isNotExists());
    } catch (TrinoException e) {
        // connectors are not required to handle the ignoreExisting flag
        if (!e.getErrorCode().equals(ALREADY_EXISTS.toErrorCode()) || !statement.isNotExists()) {
            throw e;
        }
    }
    outputConsumer.accept(new Output(tableName.getCatalogName(), tableName.getSchemaName(), tableName.getObjectName(), Optional.of(tableMetadata.getColumns().stream().map(column -> new OutputColumn(new Column(column.getName(), column.getType().toString()), ImmutableSet.of())).collect(toImmutableList()))));
    return immediateVoidFuture();
}
Also used : LikeClause(io.trino.sql.tree.LikeClause) TYPE_NOT_FOUND(io.trino.spi.StandardErrorCode.TYPE_NOT_FOUND) TypeNotFoundException(io.trino.spi.type.TypeNotFoundException) OutputColumn(io.trino.sql.analyzer.OutputColumn) UNKNOWN(io.trino.type.UnknownType.UNKNOWN) ParameterUtils.parameterExtractor(io.trino.sql.ParameterUtils.parameterExtractor) COLUMN_TYPE_UNKNOWN(io.trino.spi.StandardErrorCode.COLUMN_TYPE_UNKNOWN) NOT_SUPPORTED(io.trino.spi.StandardErrorCode.NOT_SUPPORTED) CatalogName(io.trino.connector.CatalogName) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) TABLE_ALREADY_EXISTS(io.trino.spi.StandardErrorCode.TABLE_ALREADY_EXISTS) Locale(java.util.Locale) TABLE_NOT_FOUND(io.trino.spi.StandardErrorCode.TABLE_NOT_FOUND) Map(java.util.Map) ALREADY_EXISTS(io.trino.spi.StandardErrorCode.ALREADY_EXISTS) SemanticExceptions.semanticException(io.trino.sql.analyzer.SemanticExceptions.semanticException) TableElement(io.trino.sql.tree.TableElement) Futures.immediateVoidFuture(com.google.common.util.concurrent.Futures.immediateVoidFuture) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) INCLUDING(io.trino.sql.tree.LikeClause.PropertiesOption.INCLUDING) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) TypeSignatureTranslator.toTypeSignature(io.trino.sql.analyzer.TypeSignatureTranslator.toTypeSignature) Set(java.util.Set) TrinoException(io.trino.spi.TrinoException) String.format(java.lang.String.format) DUPLICATE_COLUMN_NAME(io.trino.spi.StandardErrorCode.DUPLICATE_COLUMN_NAME) TableMetadata(io.trino.metadata.TableMetadata) List(java.util.List) CreateTable(io.trino.sql.tree.CreateTable) AccessControl(io.trino.security.AccessControl) Parameter(io.trino.sql.tree.Parameter) RedirectionAwareTableHandle(io.trino.metadata.RedirectionAwareTableHandle) Optional(java.util.Optional) Expression(io.trino.sql.tree.Expression) ColumnPropertyManager(io.trino.metadata.ColumnPropertyManager) Session(io.trino.Session) PlannerContext(io.trino.sql.PlannerContext) AccessDeniedException(io.trino.spi.security.AccessDeniedException) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) ColumnMetadata(io.trino.spi.connector.ColumnMetadata) Type(io.trino.spi.type.Type) ConnectorTableMetadata(io.trino.spi.connector.ConnectorTableMetadata) HashMap(java.util.HashMap) Inject(javax.inject.Inject) LinkedHashMap(java.util.LinkedHashMap) EXCLUDING(io.trino.sql.tree.LikeClause.PropertiesOption.EXCLUDING) ImmutableList(com.google.common.collect.ImmutableList) MetadataUtil.createQualifiedObjectName(io.trino.metadata.MetadataUtil.createQualifiedObjectName) NodeRef(io.trino.sql.tree.NodeRef) Objects.requireNonNull(java.util.Objects.requireNonNull) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) NOT_NULL_COLUMN_CONSTRAINT(io.trino.spi.connector.ConnectorCapabilities.NOT_NULL_COLUMN_CONSTRAINT) CATALOG_NOT_FOUND(io.trino.spi.StandardErrorCode.CATALOG_NOT_FOUND) MetadataUtil.getRequiredCatalogHandle(io.trino.metadata.MetadataUtil.getRequiredCatalogHandle) GENERIC_INTERNAL_ERROR(io.trino.spi.StandardErrorCode.GENERIC_INTERNAL_ERROR) Consumer(java.util.function.Consumer) LikeClause(io.trino.sql.tree.LikeClause) TableHandle(io.trino.metadata.TableHandle) QualifiedObjectName(io.trino.metadata.QualifiedObjectName) TablePropertyManager(io.trino.metadata.TablePropertyManager) WarningCollector(io.trino.execution.warnings.WarningCollector) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Output(io.trino.sql.analyzer.Output) ColumnDefinition(io.trino.sql.tree.ColumnDefinition) ColumnMetadata(io.trino.spi.connector.ColumnMetadata) AccessDeniedException(io.trino.spi.security.AccessDeniedException) TableElement(io.trino.sql.tree.TableElement) LinkedHashMap(java.util.LinkedHashMap) NodeRef(io.trino.sql.tree.NodeRef) OutputColumn(io.trino.sql.analyzer.OutputColumn) Output(io.trino.sql.analyzer.Output) ConnectorTableMetadata(io.trino.spi.connector.ConnectorTableMetadata) TableMetadata(io.trino.metadata.TableMetadata) ConnectorTableMetadata(io.trino.spi.connector.ConnectorTableMetadata) Optional(java.util.Optional) MetadataUtil.createQualifiedObjectName(io.trino.metadata.MetadataUtil.createQualifiedObjectName) QualifiedObjectName(io.trino.metadata.QualifiedObjectName) ColumnDefinition(io.trino.sql.tree.ColumnDefinition) Type(io.trino.spi.type.Type) Expression(io.trino.sql.tree.Expression) TypeNotFoundException(io.trino.spi.type.TypeNotFoundException) OutputColumn(io.trino.sql.analyzer.OutputColumn) TrinoException(io.trino.spi.TrinoException) RedirectionAwareTableHandle(io.trino.metadata.RedirectionAwareTableHandle) TableHandle(io.trino.metadata.TableHandle) CatalogName(io.trino.connector.CatalogName) RedirectionAwareTableHandle(io.trino.metadata.RedirectionAwareTableHandle) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 14 with TableMetadata

use of io.trino.metadata.TableMetadata in project trino by trinodb.

the class LogicalPlanner method getInsertPlan.

private RelationPlan getInsertPlan(Analysis analysis, Table table, Query query, TableHandle tableHandle, List<ColumnHandle> insertColumns, Optional<TableLayout> newTableLayout, Optional<WriterTarget> materializedViewRefreshWriterTarget) {
    TableMetadata tableMetadata = metadata.getTableMetadata(session, tableHandle);
    Map<NodeRef<LambdaArgumentDeclaration>, Symbol> lambdaDeclarationToSymbolMap = buildLambdaDeclarationToSymbolMap(analysis, symbolAllocator);
    RelationPlanner planner = new RelationPlanner(analysis, symbolAllocator, idAllocator, lambdaDeclarationToSymbolMap, plannerContext, Optional.empty(), session, ImmutableMap.of());
    RelationPlan plan = planner.process(query, null);
    ImmutableList.Builder<Symbol> builder = ImmutableList.builder();
    for (int i = 0; i < plan.getFieldMappings().size(); i++) {
        if (!plan.getDescriptor().getFieldByIndex(i).isHidden()) {
            builder.add(plan.getFieldMappings().get(i));
        }
    }
    List<Symbol> visibleFieldMappings = builder.build();
    Map<String, ColumnHandle> columns = metadata.getColumnHandles(session, tableHandle);
    Assignments.Builder assignments = Assignments.builder();
    boolean supportsMissingColumnsOnInsert = metadata.supportsMissingColumnsOnInsert(session, tableHandle);
    ImmutableList.Builder<ColumnMetadata> insertedColumnsBuilder = ImmutableList.builder();
    for (ColumnMetadata column : tableMetadata.getColumns()) {
        if (column.isHidden()) {
            continue;
        }
        Symbol output = symbolAllocator.newSymbol(column.getName(), column.getType());
        int index = insertColumns.indexOf(columns.get(column.getName()));
        if (index < 0) {
            if (supportsMissingColumnsOnInsert) {
                continue;
            }
            Expression cast = new Cast(new NullLiteral(), toSqlType(column.getType()));
            assignments.put(output, cast);
            insertedColumnsBuilder.add(column);
        } else {
            Symbol input = visibleFieldMappings.get(index);
            Type tableType = column.getType();
            Type queryType = symbolAllocator.getTypes().get(input);
            if (queryType.equals(tableType) || typeCoercion.isTypeOnlyCoercion(queryType, tableType)) {
                assignments.put(output, input.toSymbolReference());
            } else {
                Expression cast = noTruncationCast(input.toSymbolReference(), queryType, tableType);
                assignments.put(output, cast);
            }
            insertedColumnsBuilder.add(column);
        }
    }
    ProjectNode projectNode = new ProjectNode(idAllocator.getNextId(), plan.getRoot(), assignments.build());
    List<ColumnMetadata> insertedColumns = insertedColumnsBuilder.build();
    List<Field> fields = insertedColumns.stream().map(column -> Field.newUnqualified(column.getName(), column.getType())).collect(toImmutableList());
    Scope scope = Scope.builder().withRelationType(RelationId.anonymous(), new RelationType(fields)).build();
    plan = new RelationPlan(projectNode, scope, projectNode.getOutputSymbols(), Optional.empty());
    plan = planner.addRowFilters(table, plan, failIfPredicateIsNotMeet(metadata, session, PERMISSION_DENIED, AccessDeniedException.PREFIX + "Cannot insert row that does not match to a row filter"), node -> {
        Scope accessControlScope = analysis.getAccessControlScope(table);
        // hidden fields are not accessible in insert
        return Scope.builder().like(accessControlScope).withRelationType(accessControlScope.getRelationId(), accessControlScope.getRelationType().withOnlyVisibleFields()).build();
    });
    List<String> insertedTableColumnNames = insertedColumns.stream().map(ColumnMetadata::getName).collect(toImmutableList());
    String catalogName = tableHandle.getCatalogName().getCatalogName();
    TableStatisticsMetadata statisticsMetadata = metadata.getStatisticsCollectionMetadataForWrite(session, catalogName, tableMetadata.getMetadata());
    if (materializedViewRefreshWriterTarget.isPresent()) {
        return createTableWriterPlan(analysis, plan.getRoot(), plan.getFieldMappings(), materializedViewRefreshWriterTarget.get(), insertedTableColumnNames, insertedColumns, newTableLayout, statisticsMetadata);
    }
    InsertReference insertTarget = new InsertReference(tableHandle, insertedTableColumnNames.stream().map(columns::get).collect(toImmutableList()));
    return createTableWriterPlan(analysis, plan.getRoot(), plan.getFieldMappings(), insertTarget, insertedTableColumnNames, insertedColumns, newTableLayout, statisticsMetadata);
}
Also used : Cast(io.trino.sql.tree.Cast) FIXED_HASH_DISTRIBUTION(io.trino.sql.planner.SystemPartitioningHandle.FIXED_HASH_DISTRIBUTION) CostProvider(io.trino.cost.CostProvider) TypeSignatureProvider.fromTypes(io.trino.sql.analyzer.TypeSignatureProvider.fromTypes) Delete(io.trino.sql.tree.Delete) InsertReference(io.trino.sql.planner.plan.TableWriterNode.InsertReference) PlanNode(io.trino.sql.planner.plan.PlanNode) NOT_SUPPORTED(io.trino.spi.StandardErrorCode.NOT_SUPPORTED) LongLiteral(io.trino.sql.tree.LongLiteral) Map(java.util.Map) OutputNode(io.trino.sql.planner.plan.OutputNode) TableScanNode(io.trino.sql.planner.plan.TableScanNode) ExplainAnalyzeNode(io.trino.sql.planner.plan.ExplainAnalyzeNode) ExplainAnalyze(io.trino.sql.tree.ExplainAnalyze) Statement(io.trino.sql.tree.Statement) SystemSessionProperties.isCollectPlanStatisticsForAllQueries(io.trino.SystemSessionProperties.isCollectPlanStatisticsForAllQueries) StatisticsWriterNode(io.trino.sql.planner.plan.StatisticsWriterNode) TableExecute(io.trino.sql.tree.TableExecute) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Assignments(io.trino.sql.planner.plan.Assignments) Set(java.util.Set) PlanSanityChecker(io.trino.sql.planner.sanity.PlanSanityChecker) RelationType(io.trino.sql.analyzer.RelationType) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) PlanBuilder.newPlanBuilder(io.trino.sql.planner.PlanBuilder.newPlanBuilder) CachingStatsProvider(io.trino.cost.CachingStatsProvider) ValuesNode(io.trino.sql.planner.plan.ValuesNode) Session(io.trino.Session) AccessDeniedException(io.trino.spi.security.AccessDeniedException) TableExecuteNode(io.trino.sql.planner.plan.TableExecuteNode) PlanPrinter(io.trino.sql.planner.planprinter.PlanPrinter) QueryPlanner.visibleFields(io.trino.sql.planner.QueryPlanner.visibleFields) CreateReference(io.trino.sql.planner.plan.TableWriterNode.CreateReference) ColumnMetadata(io.trino.spi.connector.ColumnMetadata) LimitNode(io.trino.sql.planner.plan.LimitNode) TableLayout(io.trino.metadata.TableLayout) TypeCoercion(io.trino.type.TypeCoercion) BOOLEAN(io.trino.spi.type.BooleanType.BOOLEAN) ConnectorTableMetadata(io.trino.spi.connector.ConnectorTableMetadata) StatsAndCosts(io.trino.cost.StatsAndCosts) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) VARCHAR(io.trino.spi.type.VarcharType.VARCHAR) MetadataUtil.createQualifiedObjectName(io.trino.metadata.MetadataUtil.createQualifiedObjectName) PlanOptimizer(io.trino.sql.planner.optimizations.PlanOptimizer) NodeRef(io.trino.sql.tree.NodeRef) ColumnHandle(io.trino.spi.connector.ColumnHandle) AggregationNode(io.trino.sql.planner.plan.AggregationNode) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) VARBINARY(io.trino.spi.type.VarbinaryType.VARBINARY) Query(io.trino.sql.tree.Query) StringLiteral(io.trino.sql.tree.StringLiteral) TableStatisticAggregation(io.trino.sql.planner.StatisticsAggregationPlanner.TableStatisticAggregation) AggregationNode.singleGroupingSet(io.trino.sql.planner.plan.AggregationNode.singleGroupingSet) TableHandle(io.trino.metadata.TableHandle) QualifiedObjectName(io.trino.metadata.QualifiedObjectName) CharType(io.trino.spi.type.CharType) Table(io.trino.sql.tree.Table) TableFinishNode(io.trino.sql.planner.plan.TableFinishNode) TableStatisticsMetadata(io.trino.spi.statistics.TableStatisticsMetadata) UnknownType(io.trino.type.UnknownType) RefreshMaterializedView(io.trino.sql.tree.RefreshMaterializedView) TableWriterNode(io.trino.sql.planner.plan.TableWriterNode) OPTIMIZED_AND_VALIDATED(io.trino.sql.planner.LogicalPlanner.Stage.OPTIMIZED_AND_VALIDATED) Scope(io.trino.sql.analyzer.Scope) FilterNode(io.trino.sql.planner.plan.FilterNode) StatsCalculator(io.trino.cost.StatsCalculator) LambdaArgumentDeclaration(io.trino.sql.tree.LambdaArgumentDeclaration) RelationId(io.trino.sql.analyzer.RelationId) DeleteNode(io.trino.sql.planner.plan.DeleteNode) Update(io.trino.sql.tree.Update) INTEGER(io.trino.spi.type.IntegerType.INTEGER) FunctionCall(io.trino.sql.tree.FunctionCall) ImmutableMap(com.google.common.collect.ImmutableMap) ResolvedFunction(io.trino.metadata.ResolvedFunction) TypeSignatureTranslator.toSqlType(io.trino.sql.analyzer.TypeSignatureTranslator.toSqlType) TrinoException(io.trino.spi.TrinoException) ROW_COUNT(io.trino.spi.statistics.TableStatisticType.ROW_COUNT) TableExecuteHandle(io.trino.metadata.TableExecuteHandle) StatsProvider(io.trino.cost.StatsProvider) ComparisonExpression(io.trino.sql.tree.ComparisonExpression) String.format(java.lang.String.format) Preconditions.checkState(com.google.common.base.Preconditions.checkState) CoalesceExpression(io.trino.sql.tree.CoalesceExpression) GenericLiteral(io.trino.sql.tree.GenericLiteral) Objects(java.util.Objects) TableMetadata(io.trino.metadata.TableMetadata) List(java.util.List) IfExpression(io.trino.sql.tree.IfExpression) BIGINT(io.trino.spi.type.BigintType.BIGINT) StandardErrorCode(io.trino.spi.StandardErrorCode) Analyze(io.trino.sql.tree.Analyze) Entry(java.util.Map.Entry) Optional(java.util.Optional) Expression(io.trino.sql.tree.Expression) PlannerContext(io.trino.sql.PlannerContext) Analysis(io.trino.sql.analyzer.Analysis) PERMISSION_DENIED(io.trino.spi.StandardErrorCode.PERMISSION_DENIED) Logger(io.airlift.log.Logger) Type(io.trino.spi.type.Type) CreateTableAsSelect(io.trino.sql.tree.CreateTableAsSelect) HashMap(java.util.HashMap) StatisticAggregations(io.trino.sql.planner.plan.StatisticAggregations) SimpleImmutableEntry(java.util.AbstractMap.SimpleImmutableEntry) OPTIMIZED(io.trino.sql.planner.LogicalPlanner.Stage.OPTIMIZED) Function(java.util.function.Function) Cast(io.trino.sql.tree.Cast) VarcharType(io.trino.spi.type.VarcharType) CachingCostProvider(io.trino.cost.CachingCostProvider) ImmutableList(com.google.common.collect.ImmutableList) Verify.verify(com.google.common.base.Verify.verify) Objects.requireNonNull(java.util.Objects.requireNonNull) RefreshMaterializedViewNode(io.trino.sql.planner.plan.RefreshMaterializedViewNode) NullLiteral(io.trino.sql.tree.NullLiteral) Field(io.trino.sql.analyzer.Field) GREATER_THAN_OR_EQUAL(io.trino.sql.tree.ComparisonExpression.Operator.GREATER_THAN_OR_EQUAL) ProjectNode(io.trino.sql.planner.plan.ProjectNode) DISTRIBUTED_PLAN_SANITY_CHECKER(io.trino.sql.planner.sanity.PlanSanityChecker.DISTRIBUTED_PLAN_SANITY_CHECKER) WriterTarget(io.trino.sql.planner.plan.TableWriterNode.WriterTarget) TRUE_LITERAL(io.trino.sql.tree.BooleanLiteral.TRUE_LITERAL) UpdateNode(io.trino.sql.planner.plan.UpdateNode) QualifiedName(io.trino.sql.tree.QualifiedName) CostCalculator(io.trino.cost.CostCalculator) WarningCollector(io.trino.execution.warnings.WarningCollector) Row(io.trino.sql.tree.Row) Metadata(io.trino.metadata.Metadata) Insert(io.trino.sql.tree.Insert) Streams.zip(com.google.common.collect.Streams.zip) TableStatisticsMetadata(io.trino.spi.statistics.TableStatisticsMetadata) ColumnMetadata(io.trino.spi.connector.ColumnMetadata) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ImmutableList(com.google.common.collect.ImmutableList) Assignments(io.trino.sql.planner.plan.Assignments) InsertReference(io.trino.sql.planner.plan.TableWriterNode.InsertReference) NodeRef(io.trino.sql.tree.NodeRef) Field(io.trino.sql.analyzer.Field) RelationType(io.trino.sql.analyzer.RelationType) ConnectorTableMetadata(io.trino.spi.connector.ConnectorTableMetadata) TableMetadata(io.trino.metadata.TableMetadata) ColumnHandle(io.trino.spi.connector.ColumnHandle) RelationType(io.trino.sql.analyzer.RelationType) CharType(io.trino.spi.type.CharType) UnknownType(io.trino.type.UnknownType) TypeSignatureTranslator.toSqlType(io.trino.sql.analyzer.TypeSignatureTranslator.toSqlType) Type(io.trino.spi.type.Type) VarcharType(io.trino.spi.type.VarcharType) Scope(io.trino.sql.analyzer.Scope) ComparisonExpression(io.trino.sql.tree.ComparisonExpression) CoalesceExpression(io.trino.sql.tree.CoalesceExpression) IfExpression(io.trino.sql.tree.IfExpression) Expression(io.trino.sql.tree.Expression) ProjectNode(io.trino.sql.planner.plan.ProjectNode) NullLiteral(io.trino.sql.tree.NullLiteral)

Example 15 with TableMetadata

use of io.trino.metadata.TableMetadata in project trino by trinodb.

the class LogicalPlanner method createAnalyzePlan.

private RelationPlan createAnalyzePlan(Analysis analysis, Analyze analyzeStatement) {
    TableHandle targetTable = analysis.getAnalyzeTarget().orElseThrow();
    // Plan table scan
    Map<String, ColumnHandle> columnHandles = metadata.getColumnHandles(session, targetTable);
    ImmutableList.Builder<Symbol> tableScanOutputs = ImmutableList.builder();
    ImmutableMap.Builder<Symbol, ColumnHandle> symbolToColumnHandle = ImmutableMap.builder();
    ImmutableMap.Builder<String, Symbol> columnNameToSymbol = ImmutableMap.builder();
    TableMetadata tableMetadata = metadata.getTableMetadata(session, targetTable);
    for (ColumnMetadata column : tableMetadata.getColumns()) {
        Symbol symbol = symbolAllocator.newSymbol(column.getName(), column.getType());
        tableScanOutputs.add(symbol);
        symbolToColumnHandle.put(symbol, columnHandles.get(column.getName()));
        columnNameToSymbol.put(column.getName(), symbol);
    }
    TableStatisticsMetadata tableStatisticsMetadata = metadata.getStatisticsCollectionMetadata(session, targetTable.getCatalogName().getCatalogName(), tableMetadata.getMetadata());
    TableStatisticAggregation tableStatisticAggregation = statisticsAggregationPlanner.createStatisticsAggregation(tableStatisticsMetadata, columnNameToSymbol.buildOrThrow());
    StatisticAggregations statisticAggregations = tableStatisticAggregation.getAggregations();
    List<Symbol> groupingSymbols = statisticAggregations.getGroupingSymbols();
    PlanNode planNode = new StatisticsWriterNode(idAllocator.getNextId(), new AggregationNode(idAllocator.getNextId(), TableScanNode.newInstance(idAllocator.getNextId(), targetTable, tableScanOutputs.build(), symbolToColumnHandle.buildOrThrow(), false, Optional.empty()), statisticAggregations.getAggregations(), singleGroupingSet(groupingSymbols), ImmutableList.of(), AggregationNode.Step.SINGLE, Optional.empty(), Optional.empty()), new StatisticsWriterNode.WriteStatisticsReference(targetTable), symbolAllocator.newSymbol("rows", BIGINT), tableStatisticsMetadata.getTableStatistics().contains(ROW_COUNT), tableStatisticAggregation.getDescriptor());
    return new RelationPlan(planNode, analysis.getScope(analyzeStatement), planNode.getOutputSymbols(), Optional.empty());
}
Also used : ConnectorTableMetadata(io.trino.spi.connector.ConnectorTableMetadata) TableMetadata(io.trino.metadata.TableMetadata) ColumnHandle(io.trino.spi.connector.ColumnHandle) TableStatisticsMetadata(io.trino.spi.statistics.TableStatisticsMetadata) ColumnMetadata(io.trino.spi.connector.ColumnMetadata) TableStatisticAggregation(io.trino.sql.planner.StatisticsAggregationPlanner.TableStatisticAggregation) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ImmutableList(com.google.common.collect.ImmutableList) StatisticsWriterNode(io.trino.sql.planner.plan.StatisticsWriterNode) AggregationNode(io.trino.sql.planner.plan.AggregationNode) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) ImmutableMap(com.google.common.collect.ImmutableMap) StatisticAggregations(io.trino.sql.planner.plan.StatisticAggregations) PlanNode(io.trino.sql.planner.plan.PlanNode) TableHandle(io.trino.metadata.TableHandle)

Aggregations

TableMetadata (io.trino.metadata.TableMetadata)30 Language (org.intellij.lang.annotations.Language)18 ColumnMetadata (io.trino.spi.connector.ColumnMetadata)10 Constraint (io.trino.spi.connector.Constraint)10 ColumnConstraint (io.trino.sql.planner.planprinter.IoPlanPrinter.ColumnConstraint)10 TableHandle (io.trino.metadata.TableHandle)7 BaseConnectorTest (io.trino.testing.BaseConnectorTest)7 MaterializedResult (io.trino.testing.MaterializedResult)7 Test (org.testng.annotations.Test)7 Session (io.trino.Session)6 QualifiedObjectName (io.trino.metadata.QualifiedObjectName)5 MaterializedRow (io.trino.testing.MaterializedRow)5 ImmutableMap (com.google.common.collect.ImmutableMap)4 HiveQueryRunner.createBucketedSession (io.trino.plugin.hive.HiveQueryRunner.createBucketedSession)4 ColumnHandle (io.trino.spi.connector.ColumnHandle)4 ConnectorTableMetadata (io.trino.spi.connector.ConnectorTableMetadata)4 TableScanNode (io.trino.sql.planner.plan.TableScanNode)4 HashMap (java.util.HashMap)4 LinkedHashMap (java.util.LinkedHashMap)4 ImmutableList (com.google.common.collect.ImmutableList)3