Search in sources :

Example 6 with PlannerContext

use of io.trino.sql.PlannerContext in project trino by trinodb.

the class TestPushProjectionIntoTableScan method createRule.

private static PushProjectionIntoTableScan createRule(RuleTester tester) {
    PlannerContext plannerContext = tester.getPlannerContext();
    TypeAnalyzer typeAnalyzer = tester.getTypeAnalyzer();
    return new PushProjectionIntoTableScan(plannerContext, typeAnalyzer, new ScalarStatsCalculator(plannerContext, typeAnalyzer));
}
Also used : PlannerContext(io.trino.sql.PlannerContext) ScalarStatsCalculator(io.trino.cost.ScalarStatsCalculator) TypeAnalyzer.createTestingTypeAnalyzer(io.trino.sql.planner.TypeAnalyzer.createTestingTypeAnalyzer) TypeAnalyzer(io.trino.sql.planner.TypeAnalyzer)

Example 7 with PlannerContext

use of io.trino.sql.PlannerContext in project trino by trinodb.

the class CallTask method execute.

@Override
public ListenableFuture<Void> execute(Call call, QueryStateMachine stateMachine, List<Expression> parameters, WarningCollector warningCollector) {
    if (!transactionManager.isAutoCommit(stateMachine.getSession().getRequiredTransactionId())) {
        throw new TrinoException(NOT_SUPPORTED, "Procedures cannot be called within a transaction (use autocommit mode)");
    }
    Session session = stateMachine.getSession();
    QualifiedObjectName procedureName = createQualifiedObjectName(session, call, call.getName());
    CatalogName catalogName = plannerContext.getMetadata().getCatalogHandle(stateMachine.getSession(), procedureName.getCatalogName()).orElseThrow(() -> semanticException(CATALOG_NOT_FOUND, call, "Catalog '%s' does not exist", procedureName.getCatalogName()));
    Procedure procedure = procedureRegistry.resolve(catalogName, procedureName.asSchemaTableName());
    // map declared argument names to positions
    Map<String, Integer> positions = new HashMap<>();
    for (int i = 0; i < procedure.getArguments().size(); i++) {
        positions.put(procedure.getArguments().get(i).getName(), i);
    }
    // per specification, do not allow mixing argument types
    Predicate<CallArgument> hasName = argument -> argument.getName().isPresent();
    boolean anyNamed = call.getArguments().stream().anyMatch(hasName);
    boolean allNamed = call.getArguments().stream().allMatch(hasName);
    if (anyNamed && !allNamed) {
        throw semanticException(INVALID_ARGUMENTS, call, "Named and positional arguments cannot be mixed");
    }
    // get the argument names in call order
    Map<String, CallArgument> names = new LinkedHashMap<>();
    for (int i = 0; i < call.getArguments().size(); i++) {
        CallArgument argument = call.getArguments().get(i);
        if (argument.getName().isPresent()) {
            String name = argument.getName().get().getCanonicalValue();
            if (names.put(name, argument) != null) {
                throw semanticException(INVALID_ARGUMENTS, argument, "Duplicate procedure argument: %s", name);
            }
            if (!positions.containsKey(name)) {
                throw semanticException(INVALID_ARGUMENTS, argument, "Unknown argument name: %s", name);
            }
        } else if (i < procedure.getArguments().size()) {
            names.put(procedure.getArguments().get(i).getName(), argument);
        } else {
            throw semanticException(INVALID_ARGUMENTS, call, "Too many arguments for procedure");
        }
    }
    procedure.getArguments().stream().filter(Argument::isRequired).filter(argument -> !names.containsKey(argument.getName())).map(Argument::getName).findFirst().ifPresent(argument -> {
        throw semanticException(INVALID_ARGUMENTS, call, "Required procedure argument '%s' is missing", argument);
    });
    // get argument values
    Object[] values = new Object[procedure.getArguments().size()];
    Map<NodeRef<Parameter>, Expression> parameterLookup = parameterExtractor(call, parameters);
    for (Entry<String, CallArgument> entry : names.entrySet()) {
        CallArgument callArgument = entry.getValue();
        int index = positions.get(entry.getKey());
        Argument argument = procedure.getArguments().get(index);
        Expression expression = ExpressionTreeRewriter.rewriteWith(new ParameterRewriter(parameterLookup), callArgument.getValue());
        Type type = argument.getType();
        Object value = evaluateConstantExpression(expression, type, plannerContext, session, accessControl, parameterLookup);
        values[index] = toTypeObjectValue(session, type, value);
    }
    // fill values with optional arguments defaults
    for (int i = 0; i < procedure.getArguments().size(); i++) {
        Argument argument = procedure.getArguments().get(i);
        if (!names.containsKey(argument.getName())) {
            verify(argument.isOptional());
            values[i] = toTypeObjectValue(session, argument.getType(), argument.getDefaultValue());
        }
    }
    // validate arguments
    MethodType methodType = procedure.getMethodHandle().type();
    for (int i = 0; i < procedure.getArguments().size(); i++) {
        if ((values[i] == null) && methodType.parameterType(i).isPrimitive()) {
            String name = procedure.getArguments().get(i).getName();
            throw new TrinoException(INVALID_PROCEDURE_ARGUMENT, "Procedure argument cannot be null: " + name);
        }
    }
    // insert session argument
    List<Object> arguments = new ArrayList<>();
    Iterator<Object> valuesIterator = asList(values).iterator();
    for (Class<?> type : methodType.parameterList()) {
        if (ConnectorSession.class.equals(type)) {
            arguments.add(session.toConnectorSession(catalogName));
        } else if (ConnectorAccessControl.class.equals(type)) {
            arguments.add(new InjectedConnectorAccessControl(accessControl, session.toSecurityContext(), catalogName.getCatalogName()));
        } else {
            arguments.add(valuesIterator.next());
        }
    }
    accessControl.checkCanExecuteProcedure(session.toSecurityContext(), procedureName);
    stateMachine.setRoutines(ImmutableList.of(new RoutineInfo(procedureName.getObjectName(), session.getUser())));
    try {
        procedure.getMethodHandle().invokeWithArguments(arguments);
    } catch (Throwable t) {
        if (t instanceof InterruptedException) {
            Thread.currentThread().interrupt();
        }
        throwIfInstanceOf(t, TrinoException.class);
        throw new TrinoException(PROCEDURE_CALL_FAILED, t);
    }
    return immediateVoidFuture();
}
Also used : InjectedConnectorAccessControl(io.trino.security.InjectedConnectorAccessControl) TransactionManager(io.trino.transaction.TransactionManager) ParameterUtils.parameterExtractor(io.trino.sql.ParameterUtils.parameterExtractor) NOT_SUPPORTED(io.trino.spi.StandardErrorCode.NOT_SUPPORTED) CatalogName(io.trino.connector.CatalogName) Arrays.asList(java.util.Arrays.asList) Map(java.util.Map) SemanticExceptions.semanticException(io.trino.sql.analyzer.SemanticExceptions.semanticException) Argument(io.trino.spi.procedure.Procedure.Argument) Futures.immediateVoidFuture(com.google.common.util.concurrent.Futures.immediateVoidFuture) INVALID_ARGUMENTS(io.trino.spi.StandardErrorCode.INVALID_ARGUMENTS) Predicate(java.util.function.Predicate) ExpressionTreeRewriter(io.trino.sql.tree.ExpressionTreeRewriter) ConnectorAccessControl(io.trino.spi.connector.ConnectorAccessControl) TrinoException(io.trino.spi.TrinoException) TypeUtils.writeNativeValue(io.trino.spi.type.TypeUtils.writeNativeValue) List(java.util.List) AccessControl(io.trino.security.AccessControl) Parameter(io.trino.sql.tree.Parameter) Entry(java.util.Map.Entry) Expression(io.trino.sql.tree.Expression) PROCEDURE_CALL_FAILED(io.trino.spi.StandardErrorCode.PROCEDURE_CALL_FAILED) Session(io.trino.Session) PlannerContext(io.trino.sql.PlannerContext) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) ExpressionInterpreter.evaluateConstantExpression(io.trino.sql.planner.ExpressionInterpreter.evaluateConstantExpression) RoutineInfo(io.trino.spi.eventlistener.RoutineInfo) Type(io.trino.spi.type.Type) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) LinkedHashMap(java.util.LinkedHashMap) INVALID_PROCEDURE_ARGUMENT(io.trino.spi.StandardErrorCode.INVALID_PROCEDURE_ARGUMENT) ImmutableList(com.google.common.collect.ImmutableList) Procedure(io.trino.spi.procedure.Procedure) Verify.verify(com.google.common.base.Verify.verify) MetadataUtil.createQualifiedObjectName(io.trino.metadata.MetadataUtil.createQualifiedObjectName) NodeRef(io.trino.sql.tree.NodeRef) Objects.requireNonNull(java.util.Objects.requireNonNull) Iterator(java.util.Iterator) CATALOG_NOT_FOUND(io.trino.spi.StandardErrorCode.CATALOG_NOT_FOUND) ConnectorSession(io.trino.spi.connector.ConnectorSession) Throwables.throwIfInstanceOf(com.google.common.base.Throwables.throwIfInstanceOf) CallArgument(io.trino.sql.tree.CallArgument) Call(io.trino.sql.tree.Call) MethodType(java.lang.invoke.MethodType) QualifiedObjectName(io.trino.metadata.QualifiedObjectName) ProcedureRegistry(io.trino.metadata.ProcedureRegistry) WarningCollector(io.trino.execution.warnings.WarningCollector) BlockBuilder(io.trino.spi.block.BlockBuilder) ParameterRewriter(io.trino.sql.planner.ParameterRewriter) CallArgument(io.trino.sql.tree.CallArgument) Argument(io.trino.spi.procedure.Procedure.Argument) CallArgument(io.trino.sql.tree.CallArgument) ParameterRewriter(io.trino.sql.planner.ParameterRewriter) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) RoutineInfo(io.trino.spi.eventlistener.RoutineInfo) NodeRef(io.trino.sql.tree.NodeRef) Procedure(io.trino.spi.procedure.Procedure) MethodType(java.lang.invoke.MethodType) InjectedConnectorAccessControl(io.trino.security.InjectedConnectorAccessControl) ConnectorAccessControl(io.trino.spi.connector.ConnectorAccessControl) MetadataUtil.createQualifiedObjectName(io.trino.metadata.MetadataUtil.createQualifiedObjectName) QualifiedObjectName(io.trino.metadata.QualifiedObjectName) InjectedConnectorAccessControl(io.trino.security.InjectedConnectorAccessControl) Type(io.trino.spi.type.Type) MethodType(java.lang.invoke.MethodType) Expression(io.trino.sql.tree.Expression) ExpressionInterpreter.evaluateConstantExpression(io.trino.sql.planner.ExpressionInterpreter.evaluateConstantExpression) TrinoException(io.trino.spi.TrinoException) CatalogName(io.trino.connector.CatalogName) Session(io.trino.Session) ConnectorSession(io.trino.spi.connector.ConnectorSession)

Example 8 with PlannerContext

use of io.trino.sql.PlannerContext 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 9 with PlannerContext

use of io.trino.sql.PlannerContext in project trino by trinodb.

the class LocalDynamicFiltersCollector method createDynamicFilter.

// Called during TableScan planning (no need to be synchronized as local planning is single threaded)
public DynamicFilter createDynamicFilter(List<Descriptor> descriptors, Map<Symbol, ColumnHandle> columnsMap, TypeProvider typeProvider, PlannerContext plannerContext) {
    Multimap<DynamicFilterId, Descriptor> descriptorMap = extractSourceSymbols(descriptors);
    // Iterate over dynamic filters that are collected (correspond to one of the futures), and required for filtering (correspond to one of the descriptors).
    // It is possible that some dynamic filters are collected in a different stage - and will not available here.
    // It is also possible that not all local dynamic filters are needed for this specific table scan.
    List<ListenableFuture<TupleDomain<ColumnHandle>>> predicateFutures = descriptorMap.keySet().stream().filter(futures.keySet()::contains).map(filterId -> {
        // Probe-side columns that can be filtered with this dynamic filter resulting domain.
        return Futures.transform(requireNonNull(futures.get(filterId), () -> format("Missing dynamic filter %s", filterId)), // Construct a probe-side predicate by duplicating the resulting domain over the corresponding columns.
        domain -> TupleDomain.withColumnDomains(descriptorMap.get(filterId).stream().collect(toImmutableMap(descriptor -> {
            Symbol probeSymbol = Symbol.from(descriptor.getInput());
            return requireNonNull(columnsMap.get(probeSymbol), () -> format("Missing probe column for %s", probeSymbol));
        }, descriptor -> {
            Type targetType = typeProvider.get(Symbol.from(descriptor.getInput()));
            Domain updatedDomain = descriptor.applyComparison(domain);
            if (!updatedDomain.getType().equals(targetType)) {
                return applySaturatedCasts(plannerContext.getMetadata(), plannerContext.getFunctionManager(), plannerContext.getTypeOperators(), session, updatedDomain, targetType);
            }
            return updatedDomain;
        }))), directExecutor());
    }).collect(toImmutableList());
    Set<ColumnHandle> columnsCovered = descriptorMap.values().stream().map(Descriptor::getInput).map(Symbol::from).map(probeSymbol -> requireNonNull(columnsMap.get(probeSymbol), () -> "Missing probe column for " + probeSymbol)).collect(toImmutableSet());
    return new TableSpecificDynamicFilter(columnsCovered, predicateFutures);
}
Also used : ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Type(io.trino.spi.type.Type) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Multimap(com.google.common.collect.Multimap) SettableFuture(com.google.common.util.concurrent.SettableFuture) DynamicFilterId(io.trino.sql.planner.plan.DynamicFilterId) DynamicFilters.extractSourceSymbols(io.trino.sql.DynamicFilters.extractSourceSymbols) Verify.verify(com.google.common.base.Verify.verify) Descriptor(io.trino.sql.DynamicFilters.Descriptor) Map(java.util.Map) Objects.requireNonNull(java.util.Objects.requireNonNull) ColumnHandle(io.trino.spi.connector.ColumnHandle) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) ImmutableSet(com.google.common.collect.ImmutableSet) Domain(io.trino.spi.predicate.Domain) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Set(java.util.Set) ThreadSafe(javax.annotation.concurrent.ThreadSafe) TupleDomain(io.trino.spi.predicate.TupleDomain) GuardedBy(javax.annotation.concurrent.GuardedBy) String.format(java.lang.String.format) MoreExecutors.directExecutor(com.google.common.util.concurrent.MoreExecutors.directExecutor) Futures(com.google.common.util.concurrent.Futures) List(java.util.List) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) DynamicFilter(io.trino.spi.connector.DynamicFilter) DomainCoercer.applySaturatedCasts(io.trino.sql.planner.DomainCoercer.applySaturatedCasts) MoreFutures.addSuccessCallback(io.airlift.concurrent.MoreFutures.addSuccessCallback) MoreFutures.unmodifiableFuture(io.airlift.concurrent.MoreFutures.unmodifiableFuture) Session(io.trino.Session) PlannerContext(io.trino.sql.PlannerContext) ColumnHandle(io.trino.spi.connector.ColumnHandle) Type(io.trino.spi.type.Type) Descriptor(io.trino.sql.DynamicFilters.Descriptor) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Domain(io.trino.spi.predicate.Domain) TupleDomain(io.trino.spi.predicate.TupleDomain) DynamicFilterId(io.trino.sql.planner.plan.DynamicFilterId)

Example 10 with PlannerContext

use of io.trino.sql.PlannerContext 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)

Aggregations

PlannerContext (io.trino.sql.PlannerContext)28 Session (io.trino.Session)24 Map (java.util.Map)23 List (java.util.List)22 Objects.requireNonNull (java.util.Objects.requireNonNull)22 Optional (java.util.Optional)22 Expression (io.trino.sql.tree.Expression)19 ImmutableList (com.google.common.collect.ImmutableList)18 Set (java.util.Set)18 ImmutableList.toImmutableList (com.google.common.collect.ImmutableList.toImmutableList)16 ImmutableMap (com.google.common.collect.ImmutableMap)15 ColumnHandle (io.trino.spi.connector.ColumnHandle)15 TableHandle (io.trino.metadata.TableHandle)14 PlanNode (io.trino.sql.planner.plan.PlanNode)13 ProjectNode (io.trino.sql.planner.plan.ProjectNode)13 Type (io.trino.spi.type.Type)12 Assignments (io.trino.sql.planner.plan.Assignments)12 ImmutableSet (com.google.common.collect.ImmutableSet)11 QualifiedObjectName (io.trino.metadata.QualifiedObjectName)11 TrinoException (io.trino.spi.TrinoException)11