Search in sources :

Example 21 with TypeProvider

use of io.trino.sql.planner.TypeProvider in project trino by trinodb.

the class JoinStatsRule method filterByEquiJoinClauses.

private PlanNodeStatsEstimate filterByEquiJoinClauses(PlanNodeStatsEstimate stats, Collection<EquiJoinClause> clauses, Session session, TypeProvider types) {
    checkArgument(!clauses.isEmpty(), "clauses is empty");
    // Join equality clauses are usually correlated. Therefore, we shouldn't treat each join equality
    // clause separately because stats estimates would be way off.
    List<PlanNodeStatsEstimateWithClause> knownEstimates = clauses.stream().map(clause -> {
        ComparisonExpression predicate = new ComparisonExpression(EQUAL, clause.getLeft().toSymbolReference(), clause.getRight().toSymbolReference());
        return new PlanNodeStatsEstimateWithClause(filterStatsCalculator.filterStats(stats, predicate, session, types), clause);
    }).collect(toImmutableList());
    double outputRowCount = estimateCorrelatedConjunctionRowCount(stats, knownEstimates.stream().map(PlanNodeStatsEstimateWithClause::getEstimate).collect(toImmutableList()), getJoinMultiClauseIndependenceFactor(session));
    if (isNaN(outputRowCount)) {
        return PlanNodeStatsEstimate.unknown();
    }
    return normalizer.normalize(new PlanNodeStatsEstimate(outputRowCount, intersectCorrelatedJoinClause(stats, knownEstimates)), types);
}
Also used : UNKNOWN_FILTER_COEFFICIENT(io.trino.cost.FilterStatsCalculator.UNKNOWN_FILTER_COEFFICIENT) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) Sets.difference(com.google.common.collect.Sets.difference) SymbolStatsEstimate.buildFrom(io.trino.cost.SymbolStatsEstimate.buildFrom) NaN(java.lang.Double.NaN) EquiJoinClause(io.trino.sql.planner.plan.JoinNode.EquiJoinClause) PlanNodeStatsEstimateMath.estimateCorrelatedConjunctionRowCount(io.trino.cost.PlanNodeStatsEstimateMath.estimateCorrelatedConjunctionRowCount) Map(java.util.Map) Objects.requireNonNull(java.util.Objects.requireNonNull) SystemSessionProperties.getJoinMultiClauseIndependenceFactor(io.trino.SystemSessionProperties.getJoinMultiClauseIndependenceFactor) JoinNode(io.trino.sql.planner.plan.JoinNode) Patterns.join(io.trino.sql.planner.plan.Patterns.join) Symbol(io.trino.sql.planner.Symbol) Lookup(io.trino.sql.planner.iterative.Lookup) Collection(java.util.Collection) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Math.min(java.lang.Math.min) Comparator.comparingDouble(java.util.Comparator.comparingDouble) ComparisonExpression(io.trino.sql.tree.ComparisonExpression) EQUAL(io.trino.sql.tree.ComparisonExpression.Operator.EQUAL) List(java.util.List) Pattern(io.trino.matching.Pattern) Double.isNaN(java.lang.Double.isNaN) MoreMath.firstNonNaN(io.trino.util.MoreMath.firstNonNaN) TypeProvider(io.trino.sql.planner.TypeProvider) Optional(java.util.Optional) Expression(io.trino.sql.tree.Expression) ExpressionUtils.extractConjuncts(io.trino.sql.ExpressionUtils.extractConjuncts) VisibleForTesting(com.google.common.annotations.VisibleForTesting) MoreMath(io.trino.util.MoreMath) Session(io.trino.Session) ComparisonExpression(io.trino.sql.tree.ComparisonExpression)

Example 22 with TypeProvider

use of io.trino.sql.planner.TypeProvider in project trino by trinodb.

the class StatsNormalizer method normalize.

private PlanNodeStatsEstimate normalize(PlanNodeStatsEstimate stats, Optional<Collection<Symbol>> outputSymbols, TypeProvider types) {
    if (stats.isOutputRowCountUnknown()) {
        return PlanNodeStatsEstimate.unknown();
    }
    PlanNodeStatsEstimate.Builder normalized = PlanNodeStatsEstimate.buildFrom(stats);
    Predicate<Symbol> symbolFilter = outputSymbols.map(ImmutableSet::copyOf).map(set -> (Predicate<Symbol>) set::contains).orElse(symbol -> true);
    for (Symbol symbol : stats.getSymbolsWithKnownStatistics()) {
        if (!symbolFilter.test(symbol)) {
            normalized.removeSymbolStatistics(symbol);
            continue;
        }
        SymbolStatsEstimate symbolStats = stats.getSymbolStatistics(symbol);
        SymbolStatsEstimate normalizedSymbolStats = stats.getOutputRowCount() == 0 ? SymbolStatsEstimate.zero() : normalizeSymbolStats(symbol, symbolStats, stats, types);
        if (normalizedSymbolStats.isUnknown()) {
            normalized.removeSymbolStatistics(symbol);
            continue;
        }
        if (!Objects.equals(normalizedSymbolStats, symbolStats)) {
            normalized.addSymbolStatistics(symbol, normalizedSymbolStats);
        }
    }
    return normalized.build();
}
Also used : Symbol(io.trino.sql.planner.Symbol) ImmutableSet(com.google.common.collect.ImmutableSet) IntegerType(io.trino.spi.type.IntegerType) Predicate(java.util.function.Predicate) Collection(java.util.Collection) DateType(io.trino.spi.type.DateType) Type(io.trino.spi.type.Type) BooleanType(io.trino.spi.type.BooleanType) Math.pow(java.lang.Math.pow) Objects(java.util.Objects) BigintType(io.trino.spi.type.BigintType) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) NaN(java.lang.Double.NaN) Double.isNaN(java.lang.Double.isNaN) Objects.requireNonNull(java.util.Objects.requireNonNull) TypeProvider(io.trino.sql.planner.TypeProvider) Optional(java.util.Optional) Math.floor(java.lang.Math.floor) TinyintType(io.trino.spi.type.TinyintType) SmallintType(io.trino.spi.type.SmallintType) DecimalType(io.trino.spi.type.DecimalType) ImmutableSet(com.google.common.collect.ImmutableSet) Symbol(io.trino.sql.planner.Symbol) Predicate(java.util.function.Predicate)

Example 23 with TypeProvider

use of io.trino.sql.planner.TypeProvider in project trino by trinodb.

the class PropertyDerivations method deriveProperties.

public static ActualProperties deriveProperties(PlanNode node, List<ActualProperties> inputProperties, PlannerContext plannerContext, Session session, TypeProvider types, TypeAnalyzer typeAnalyzer) {
    ActualProperties output = node.accept(new Visitor(plannerContext, session, types, typeAnalyzer), inputProperties);
    output.getNodePartitioning().ifPresent(partitioning -> verify(node.getOutputSymbols().containsAll(partitioning.getColumns()), "Node-level partitioning properties contain columns not present in node's output"));
    verify(node.getOutputSymbols().containsAll(output.getConstants().keySet()), "Node-level constant properties contain columns not present in node's output");
    Set<Symbol> localPropertyColumns = output.getLocalProperties().stream().flatMap(property -> property.getColumns().stream()).collect(Collectors.toSet());
    verify(node.getOutputSymbols().containsAll(localPropertyColumns), "Node-level local properties contain columns not present in node's output");
    return output;
}
Also used : GroupingProperty(io.trino.spi.connector.GroupingProperty) ARBITRARY_DISTRIBUTION(io.trino.sql.planner.SystemPartitioningHandle.ARBITRARY_DISTRIBUTION) IndexSourceNode(io.trino.sql.planner.plan.IndexSourceNode) TableWriterNode(io.trino.sql.planner.plan.TableWriterNode) CorrelatedJoinNode(io.trino.sql.planner.plan.CorrelatedJoinNode) FilterNode(io.trino.sql.planner.plan.FilterNode) PlanNode(io.trino.sql.planner.plan.PlanNode) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) TableDeleteNode(io.trino.sql.planner.plan.TableDeleteNode) ONE(io.trino.sql.tree.PatternRecognitionRelation.RowsPerMatch.ONE) Collectors.toMap(java.util.stream.Collectors.toMap) Map(java.util.Map) LOCAL(io.trino.sql.planner.plan.ExchangeNode.Scope.LOCAL) SpatialJoinNode(io.trino.sql.planner.plan.SpatialJoinNode) OutputNode(io.trino.sql.planner.plan.OutputNode) DeleteNode(io.trino.sql.planner.plan.DeleteNode) WINDOW(io.trino.sql.tree.PatternRecognitionRelation.RowsPerMatch.WINDOW) JoinNode(io.trino.sql.planner.plan.JoinNode) AssignUniqueId(io.trino.sql.planner.plan.AssignUniqueId) TableScanNode(io.trino.sql.planner.plan.TableScanNode) TupleDomain.extractFixedValues(io.trino.spi.predicate.TupleDomain.extractFixedValues) ExplainAnalyzeNode(io.trino.sql.planner.plan.ExplainAnalyzeNode) MarkDistinctNode(io.trino.sql.planner.plan.MarkDistinctNode) Global.partitionedOn(io.trino.sql.planner.optimizations.ActualProperties.Global.partitionedOn) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) EnforceSingleRowNode(io.trino.sql.planner.plan.EnforceSingleRowNode) StatisticsWriterNode(io.trino.sql.planner.plan.StatisticsWriterNode) Collection(java.util.Collection) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ExpressionInterpreter(io.trino.sql.planner.ExpressionInterpreter) IndexJoinNode(io.trino.sql.planner.plan.IndexJoinNode) Set(java.util.Set) PAST_LAST(io.trino.sql.tree.SkipTo.Position.PAST_LAST) SemiJoinNode(io.trino.sql.planner.plan.SemiJoinNode) PatternRecognitionNode(io.trino.sql.planner.plan.PatternRecognitionNode) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) Preconditions.checkState(com.google.common.base.Preconditions.checkState) CoalesceExpression(io.trino.sql.tree.CoalesceExpression) List(java.util.List) GATHER(io.trino.sql.planner.plan.ExchangeNode.Type.GATHER) SymbolReference(io.trino.sql.tree.SymbolReference) FIXED_PASSTHROUGH_DISTRIBUTION(io.trino.sql.planner.SystemPartitioningHandle.FIXED_PASSTHROUGH_DISTRIBUTION) ApplyNode(io.trino.sql.planner.plan.ApplyNode) TopNRankingNode(io.trino.sql.planner.plan.TopNRankingNode) Optional(java.util.Optional) Global.arbitraryPartition(io.trino.sql.planner.optimizations.ActualProperties.Global.arbitraryPartition) ExchangeNode(io.trino.sql.planner.plan.ExchangeNode) Expression(io.trino.sql.tree.Expression) ValuesNode(io.trino.sql.planner.plan.ValuesNode) WindowNode(io.trino.sql.planner.plan.WindowNode) Session(io.trino.Session) PlannerContext(io.trino.sql.PlannerContext) TableExecuteNode(io.trino.sql.planner.plan.TableExecuteNode) Iterables(com.google.common.collect.Iterables) ConstantProperty(io.trino.spi.connector.ConstantProperty) Global(io.trino.sql.planner.optimizations.ActualProperties.Global) NullableValue(io.trino.spi.predicate.NullableValue) LimitNode(io.trino.sql.planner.plan.LimitNode) Type(io.trino.spi.type.Type) NoOpSymbolResolver(io.trino.sql.planner.NoOpSymbolResolver) Global.singleStreamPartition(io.trino.sql.planner.optimizations.ActualProperties.Global.singleStreamPartition) HashMap(java.util.HashMap) TableProperties(io.trino.metadata.TableProperties) SortNode(io.trino.sql.planner.plan.SortNode) ImmutableBiMap(com.google.common.collect.ImmutableBiMap) ImmutableList(com.google.common.collect.ImmutableList) RowNumberNode(io.trino.sql.planner.plan.RowNumberNode) Verify.verify(com.google.common.base.Verify.verify) NodeRef(io.trino.sql.tree.NodeRef) Objects.requireNonNull(java.util.Objects.requireNonNull) SystemSessionProperties(io.trino.SystemSessionProperties) RefreshMaterializedViewNode(io.trino.sql.planner.plan.RefreshMaterializedViewNode) ColumnHandle(io.trino.spi.connector.ColumnHandle) AggregationNode(io.trino.sql.planner.plan.AggregationNode) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) ProjectNode(io.trino.sql.planner.plan.ProjectNode) DomainTranslator(io.trino.sql.planner.DomainTranslator) TablePartitioning(io.trino.metadata.TableProperties.TablePartitioning) Symbol(io.trino.sql.planner.Symbol) Global.coordinatorSingleStreamPartition(io.trino.sql.planner.optimizations.ActualProperties.Global.coordinatorSingleStreamPartition) PlanVisitor(io.trino.sql.planner.plan.PlanVisitor) TopNNode(io.trino.sql.planner.plan.TopNNode) OrderingScheme(io.trino.sql.planner.OrderingScheme) UnnestNode(io.trino.sql.planner.plan.UnnestNode) UpdateNode(io.trino.sql.planner.plan.UpdateNode) Global.streamPartitionedOn(io.trino.sql.planner.optimizations.ActualProperties.Global.streamPartitionedOn) LocalProperty(io.trino.spi.connector.LocalProperty) TypeAnalyzer(io.trino.sql.planner.TypeAnalyzer) REMOTE(io.trino.sql.planner.plan.ExchangeNode.Scope.REMOTE) GroupIdNode(io.trino.sql.planner.plan.GroupIdNode) DistinctLimitNode(io.trino.sql.planner.plan.DistinctLimitNode) TypeProvider(io.trino.sql.planner.TypeProvider) TableFinishNode(io.trino.sql.planner.plan.TableFinishNode) SampleNode(io.trino.sql.planner.plan.SampleNode) PlanVisitor(io.trino.sql.planner.plan.PlanVisitor) Symbol(io.trino.sql.planner.Symbol)

Example 24 with TypeProvider

use of io.trino.sql.planner.TypeProvider in project trino by trinodb.

the class PushdownFilterIntoRowNumber method apply.

@Override
public Result apply(FilterNode node, Captures captures, Context context) {
    Session session = context.getSession();
    TypeProvider types = context.getSymbolAllocator().getTypes();
    DomainTranslator.ExtractionResult extractionResult = DomainTranslator.getExtractionResult(plannerContext, session, node.getPredicate(), types);
    TupleDomain<Symbol> tupleDomain = extractionResult.getTupleDomain();
    RowNumberNode source = captures.get(CHILD);
    Symbol rowNumberSymbol = source.getRowNumberSymbol();
    OptionalInt upperBound = extractUpperBound(tupleDomain, rowNumberSymbol);
    if (upperBound.isEmpty()) {
        return Result.empty();
    }
    if (upperBound.getAsInt() <= 0) {
        return Result.ofPlanNode(new ValuesNode(node.getId(), node.getOutputSymbols(), ImmutableList.of()));
    }
    RowNumberNode merged = mergeLimit(source, upperBound.getAsInt());
    boolean needRewriteSource = !merged.getMaxRowCountPerPartition().equals(source.getMaxRowCountPerPartition());
    if (needRewriteSource) {
        source = merged;
    }
    if (!allRowNumberValuesInDomain(tupleDomain, rowNumberSymbol, source.getMaxRowCountPerPartition().get())) {
        if (needRewriteSource) {
            return Result.ofPlanNode(new FilterNode(node.getId(), source, node.getPredicate()));
        } else {
            return Result.empty();
        }
    }
    TupleDomain<Symbol> newTupleDomain = tupleDomain.filter((symbol, domain) -> !symbol.equals(rowNumberSymbol));
    Expression newPredicate = ExpressionUtils.combineConjuncts(plannerContext.getMetadata(), extractionResult.getRemainingExpression(), new DomainTranslator(plannerContext).toPredicate(session, newTupleDomain));
    if (newPredicate.equals(BooleanLiteral.TRUE_LITERAL)) {
        return Result.ofPlanNode(source);
    }
    if (!newPredicate.equals(node.getPredicate())) {
        return Result.ofPlanNode(new FilterNode(node.getId(), source, newPredicate));
    }
    return Result.empty();
}
Also used : ValuesNode(io.trino.sql.planner.plan.ValuesNode) Expression(io.trino.sql.tree.Expression) Symbol(io.trino.sql.planner.Symbol) FilterNode(io.trino.sql.planner.plan.FilterNode) TypeProvider(io.trino.sql.planner.TypeProvider) DomainTranslator(io.trino.sql.planner.DomainTranslator) RowNumberNode(io.trino.sql.planner.plan.RowNumberNode) OptionalInt(java.util.OptionalInt) Session(io.trino.Session)

Example 25 with TypeProvider

use of io.trino.sql.planner.TypeProvider in project trino by trinodb.

the class TestCostCalculator method calculateCost.

private PlanCostEstimate calculateCost(PlanNode node, CostCalculator costCalculator, StatsCalculator statsCalculator, Map<String, Type> types) {
    TypeProvider typeProvider = TypeProvider.copyOf(types.entrySet().stream().collect(toImmutableMap(entry -> new Symbol(entry.getKey()), Map.Entry::getValue)));
    StatsProvider statsProvider = new CachingStatsProvider(statsCalculator, session, typeProvider);
    CostProvider costProvider = new CachingCostProvider(costCalculator, statsProvider, Optional.empty(), session, typeProvider);
    return costProvider.getCost(node);
}
Also used : Symbol(io.trino.sql.planner.Symbol) TypeProvider(io.trino.sql.planner.TypeProvider)

Aggregations

TypeProvider (io.trino.sql.planner.TypeProvider)29 Symbol (io.trino.sql.planner.Symbol)20 Session (io.trino.Session)15 PlanNode (io.trino.sql.planner.plan.PlanNode)13 Expression (io.trino.sql.tree.Expression)13 Optional (java.util.Optional)13 Map (java.util.Map)10 Objects.requireNonNull (java.util.Objects.requireNonNull)10 ImmutableList.toImmutableList (com.google.common.collect.ImmutableList.toImmutableList)9 ImmutableSet (com.google.common.collect.ImmutableSet)9 List (java.util.List)9 ProjectNode (io.trino.sql.planner.plan.ProjectNode)8 Set (java.util.Set)8 ImmutableList (com.google.common.collect.ImmutableList)6 Pattern (io.trino.matching.Pattern)6 FilterNode (io.trino.sql.planner.plan.FilterNode)6 JoinNode (io.trino.sql.planner.plan.JoinNode)6 SymbolReference (io.trino.sql.tree.SymbolReference)6 Preconditions.checkState (com.google.common.base.Preconditions.checkState)5 Metadata (io.trino.metadata.Metadata)5