cockroach: github.com/cockroachdb/cockroach/pkg/sql/opt/norm Index | Files

package norm

import "github.com/cockroachdb/cockroach/pkg/sql/opt/norm"

Index

Package Files

bool_funcs.go comp_funcs.go decorrelate_funcs.go factory.go fold_constants_funcs.go general_funcs.go groupby_funcs.go inline_funcs.go join_funcs.go limit_funcs.go list_sorter.go ordering_funcs.go project_builder.go project_funcs.go project_set_funcs.go prune_cols_funcs.go reject_nulls_funcs.go scalar_funcs.go select_funcs.go set_funcs.go window_funcs.go with_funcs.go

func DerivePruneCols Uses

func DerivePruneCols(e memo.RelExpr) opt.ColSet

DerivePruneCols returns the subset of the given expression's output columns that are candidates for pruning. Each operator has its own custom rule for what columns it allows to be pruned. Note that if an operator allows columns to be pruned, then there must be logic in the PruneCols method to actually prune those columns when requested.

func DeriveRejectNullCols Uses

func DeriveRejectNullCols(in memo.RelExpr) opt.ColSet

DeriveRejectNullCols returns the set of columns that are candidates for NULL rejection filter pushdown. See the Relational.Rule.RejectNullCols comment for more details.

type AppliedRuleFunc Uses

type AppliedRuleFunc func(ruleName opt.RuleName, source, target opt.Expr)

AppliedRuleFunc defines the callback function for the NotifyOnAppliedRule event supported by the optimizer and factory. It is invoked each time an optimization rule (Normalize or Explore) has been applied.

The function is called with the name of the rule and the expressions it affected. For a normalization rule, the source is always nil, and the target is the expression constructed by the replace pattern. For an exploration rule, the source is the expression matched by the rule, and the target is the first expression constructed by the replace pattern. If no expressions were constructed, it is nil. Additional expressions beyond the first can be accessed by following the NextExpr links on the target expression.

type CustomFuncs Uses

type CustomFuncs struct {
    // contains filtered or unexported fields
}

CustomFuncs contains all the custom match and replace functions used by the normalization rules. These are also imported and used by the explorer.

func (*CustomFuncs) AddColToSet Uses

func (c *CustomFuncs) AddColToSet(set opt.ColSet, col opt.ColumnID) opt.ColSet

AddColToSet returns a set containing both the given set and the given column.

func (*CustomFuncs) AddColsToGrouping Uses

func (c *CustomFuncs) AddColsToGrouping(
    private *memo.GroupingPrivate, groupingCols opt.ColSet,
) *memo.GroupingPrivate

AddColsToGrouping returns a new GroupByDef that is a copy of the given GroupingPrivate, except with the given set of grouping columns union'ed with the existing grouping columns.

func (*CustomFuncs) AddColsToPartition Uses

func (c *CustomFuncs) AddColsToPartition(
    priv *memo.WindowPrivate, cols opt.ColSet,
) *memo.WindowPrivate

AddColsToPartition unions the given set of columns with a window private's partition columns.

func (*CustomFuncs) AddConstInts Uses

func (c *CustomFuncs) AddConstInts(first tree.Datum, second tree.Datum) opt.ScalarExpr

AddConstInts adds the numeric constants together and constructs a Const. AddConstInts assumes the sum will not overflow. Call CanAddConstInts on the constants to guarantee this.

func (*CustomFuncs) AggregationOuterCols Uses

func (c *CustomFuncs) AggregationOuterCols(aggregations memo.AggregationsExpr) opt.ColSet

AggregationOuterCols returns the union of all outer columns from the given aggregation expressions.

func (*CustomFuncs) AggsCanBeDecorrelated Uses

func (c *CustomFuncs) AggsCanBeDecorrelated(aggs memo.AggregationsExpr) bool

AggsCanBeDecorrelated returns true if every aggregate satisfies one of the following conditions:

* It is CountRows (because it will be translated into Count),
* It ignores nulls (because nothing extra must be done for it)
* It gives NULL on no input (because this is how we translate non-null
  ignoring aggregates)

TODO(justin): we can lift the third condition if we have a function that gives the correct "on empty" value for a given aggregate.

func (*CustomFuncs) AllArePrefixSafe Uses

func (c *CustomFuncs) AllArePrefixSafe(fns memo.WindowsExpr) bool

AllArePrefixSafe returns whether every window function in the list satisfies the "prefix-safe" property.

Being prefix-safe means that the computation of a window function on a given row does not depend on any of the rows that come after it. It's also precisely the property that lets us push limit operators below window functions:

(Limit (Window $input) n) = (Window (Limit $input n))

Note that the frame affects whether a given window function is prefix-safe or not. rank() is prefix-safe under any frame, but avg():

* is not prefix-safe under RANGE BETWEEN UNBOUNDED PRECEDING TO CURRENT ROW
  (the default), because we might cut off mid-peer group. If we can
  guarantee that the ordering is over a key, then this becomes safe.
* is not prefix-safe under ROWS BETWEEN UNBOUNDED PRECEDING TO UNBOUNDED
  FOLLOWING, because it needs to look at the entire partition.
* is prefix-safe under ROWS BETWEEN UNBOUNDED PRECEDING TO CURRENT ROW,
  because it only needs to look at the rows up to any given row.

(We don't currently handle this case).

This function is best-effort. It's OK to report a function not as prefix-safe, even if it is.

func (*CustomFuncs) AllowNullArgs Uses

func (c *CustomFuncs) AllowNullArgs(op opt.Operator, left, right opt.ScalarExpr) bool

AllowNullArgs returns true if the binary operator with the given inputs allows one of those inputs to be null. If not, then the binary operator will simply be replaced by null.

func (*CustomFuncs) AnyType Uses

func (c *CustomFuncs) AnyType() *types.T

AnyType returns the wildcard Any type.

func (*CustomFuncs) AppendAggCols Uses

func (c *CustomFuncs) AppendAggCols(
    aggs memo.AggregationsExpr, aggOp opt.Operator, cols opt.ColSet,
) memo.AggregationsExpr

AppendAggCols constructs a new Aggregations operator containing the aggregate functions from an existing Aggregations operator plus an additional set of aggregate functions, one for each column in the given set. The new functions are of the given aggregate operator type.

func (*CustomFuncs) AppendAggCols2 Uses

func (c *CustomFuncs) AppendAggCols2(
    aggs memo.AggregationsExpr,
    aggOp opt.Operator,
    cols opt.ColSet,
    aggOp2 opt.Operator,
    cols2 opt.ColSet,
) memo.AggregationsExpr

AppendAggCols2 constructs a new Aggregations operator containing the aggregate functions from an existing Aggregations operator plus an additional set of aggregate functions, one for each column in the given set. The new functions are of the given aggregate operator type.

func (*CustomFuncs) AreFiltersSorted Uses

func (c *CustomFuncs) AreFiltersSorted(f memo.FiltersExpr) bool

AreFiltersSorted determines whether the expressions in a FiltersExpr are ordered by their expression IDs.

func (*CustomFuncs) AreProjectionsCorrelated Uses

func (c *CustomFuncs) AreProjectionsCorrelated(
    projections memo.ProjectionsExpr, cols opt.ColSet,
) bool

AreProjectionsCorrelated returns true if any element in the projections references any of the given columns.

func (*CustomFuncs) AreValuesDistinct Uses

func (c *CustomFuncs) AreValuesDistinct(
    input memo.RelExpr, groupingCols opt.ColSet, nullsAreDistinct bool,
) bool

AreValuesDistinct returns true if a constant Values operator input contains only rows that are already distinct with respect to the given grouping columns. The Values operator can be wrapped by Select, Project, and/or LeftJoin operators.

If nullsAreDistinct is true, then NULL values are treated as not equal to one another, and therefore rows containing a NULL value in any grouping column are always distinct.

func (*CustomFuncs) ArrayType Uses

func (c *CustomFuncs) ArrayType(inCol opt.ColumnID) *types.T

ArrayType returns the type of the given column wrapped in an array.

func (*CustomFuncs) BinaryType Uses

func (c *CustomFuncs) BinaryType(op opt.Operator, left, right opt.ScalarExpr) *types.T

BinaryType returns the type of the binary overload for the given operator and operands.

func (*CustomFuncs) BoolType Uses

func (c *CustomFuncs) BoolType() *types.T

BoolType returns the boolean SQL type.

func (*CustomFuncs) CanAddConstInts Uses

func (c *CustomFuncs) CanAddConstInts(first tree.Datum, second tree.Datum) bool

CanAddConstInts returns true if the addition of the two integers overflows.

func (*CustomFuncs) CanConsolidateFilters Uses

func (c *CustomFuncs) CanConsolidateFilters(filters memo.FiltersExpr) bool

CanConsolidateFilters returns true if there are at least two different filter conditions that contain the same variable, where the conditions have tight constraints and contain a single variable. For example, CanConsolidateFilters returns true with filters {x > 5, x < 10}, but false with {x > 5, y < 10} and {x > 5, x = y}.

func (*CustomFuncs) CanConstructBinary Uses

func (c *CustomFuncs) CanConstructBinary(op opt.Operator, left, right opt.ScalarExpr) bool

CanConstructBinary returns true if (op left right) has a valid binary op overload and is therefore legal to construct. For example, while (Minus <date> <int>) is valid, (Minus <int> <date>) is not.

func (*CustomFuncs) CanConstructValuesFromZips Uses

func (c *CustomFuncs) CanConstructValuesFromZips(zip memo.ZipExpr) bool

CanConstructValuesFromZips takes in an input ZipExpr and returns true if the ProjectSet to which the zip belongs can be converted to an InnerJoinApply with a Values operator on the right input.

func (*CustomFuncs) CanEliminateJoinUnderGroupByLeft Uses

func (c *CustomFuncs) CanEliminateJoinUnderGroupByLeft(
    joinExpr memo.RelExpr, aggs memo.AggregationsExpr,
) bool

CanEliminateJoinUnderGroupByLeft returns true if the given join can be eliminated and replaced by its left input. It should be called only when the join is under a grouping operator that is only using columns from the join's left input.

func (*CustomFuncs) CanEliminateJoinUnderGroupByRight Uses

func (c *CustomFuncs) CanEliminateJoinUnderGroupByRight(
    joinExpr memo.RelExpr, aggs memo.AggregationsExpr,
) bool

CanEliminateJoinUnderGroupByRight returns true if the given join can be eliminated and replaced by its right input. It should be called only when the join is under a grouping operator that is only using columns from the join's right input.

func (*CustomFuncs) CanExtractJoinEquality Uses

func (c *CustomFuncs) CanExtractJoinEquality(
    a, b opt.ScalarExpr, leftCols, rightCols opt.ColSet,
) bool

CanExtractJoinEquality returns true if:

- one of a, b is bound by the left columns;
- the other is bound by the right columns;
- a and b are not "bare" variables;
- a and b contain no correlated subqueries;
- neither a or b are constants.

Such an equality can be converted to a column equality by pushing down expressions as projections.

func (*CustomFuncs) CanFoldOperator Uses

func (c *CustomFuncs) CanFoldOperator(v tree.Volatility) bool

CanFoldOperator returns true if we should fold an operator with the given volatility. This depends on the foldingVolatility setting of the factory (which can be either VolatilityImmutable or VolatilityStable).

func (*CustomFuncs) CanHaveZeroRows Uses

func (c *CustomFuncs) CanHaveZeroRows(input memo.RelExpr) bool

CanHaveZeroRows returns true if the input expression might return zero rows.

func (*CustomFuncs) CanInline Uses

func (c *CustomFuncs) CanInline(scalar opt.ScalarExpr) bool

CanInline returns true if the given expression consists only of "simple" operators like Variable, Const, Eq, and Plus. These operators are assumed to be relatively inexpensive to evaluate, and therefore potentially evaluating them multiple times is not a big concern.

func (*CustomFuncs) CanInlineConstVar Uses

func (c *CustomFuncs) CanInlineConstVar(f memo.FiltersExpr) bool

CanInlineConstVar returns true if there is an opportunity in the filters to inline a variable restricted to be a constant, as in:

SELECT * FROM foo WHERE a = 4 AND a IN (1, 2, 3, 4).

=>

SELECT * FROM foo WHERE a = 4 AND 4 IN (1, 2, 3, 4).

func (*CustomFuncs) CanInlineProjections Uses

func (c *CustomFuncs) CanInlineProjections(projections memo.ProjectionsExpr) bool

CanInlineProjections returns true if all projection expressions can be inlined. See CanInline for details.

func (*CustomFuncs) CanInlineWith Uses

func (c *CustomFuncs) CanInlineWith(binding, expr memo.RelExpr, private *memo.WithPrivate) bool

CanInlineWith returns whether or not it's valid to inline binding in expr. This is the case when materialize is explicitly set to false, or when: 1. binding has no volatile expressions (because once it's inlined, there's no

guarantee it will be executed fully), and

2. binding is referenced at most once in expr.

func (*CustomFuncs) CanMapJoinOpEqualities Uses

func (c *CustomFuncs) CanMapJoinOpEqualities(
    filters memo.FiltersExpr, leftCols, rightCols opt.ColSet,
) bool

CanMapJoinOpEqualities checks whether it is possible to map equality conditions in a join to use different variables so that the number of conditions crossing both sides of a join are minimized. See canMapJoinOpEquivalenceGroup for details.

func (*CustomFuncs) CanMapJoinOpFilter Uses

func (c *CustomFuncs) CanMapJoinOpFilter(
    src *memo.FiltersItem, dstCols opt.ColSet, equivFD props.FuncDepSet,
) bool

CanMapJoinOpFilter returns true if it is possible to map a boolean expression src, which is a conjunct in the given filters expression, to use the output columns of the relational expression dst.

In order for one column to map to another, the two columns must be equivalent. This happens when there is an equality predicate such as a.x=b.x in the ON or WHERE clause. Additionally, the two columns must be of the same type (see GetEquivColsWithEquivType for details). CanMapJoinOpFilter checks that for each column in src, there is at least one equivalent column in dst.

For example, consider this query:

SELECT * FROM a INNER JOIN b ON a.x=b.x AND a.x + b.y = 5

Since there is an equality predicate on a.x=b.x, it is possible to map a.x + b.y = 5 to b.x + b.y = 5, and that allows the filter to be pushed down to the right side of the join. In this case, CanMapJoinOpFilter returns true when src is a.x + b.y = 5 and dst is (Scan b), but false when src is a.x + b.y = 5 and dst is (Scan a).

If src has a correlated subquery, CanMapJoinOpFilter returns false.

func (*CustomFuncs) CanMapOnSetOp Uses

func (c *CustomFuncs) CanMapOnSetOp(src *memo.FiltersItem) bool

CanMapOnSetOp determines whether the filter can be mapped to either side of a set operator.

func (*CustomFuncs) CanMergeAggs Uses

func (c *CustomFuncs) CanMergeAggs(innerAggs, outerAggs memo.AggregationsExpr) bool

CanMergeAggs returns true if the given inner and outer AggregationsExprs can be replaced with a single equivalent AggregationsExpr.

func (*CustomFuncs) CanMergeProjections Uses

func (c *CustomFuncs) CanMergeProjections(outer, inner memo.ProjectionsExpr) bool

CanMergeProjections returns true if the outer Projections operator never references any of the inner Projections columns. If true, then the outer does not depend on the inner, and the two can be merged into a single set.

func (*CustomFuncs) CanPruneAggCols Uses

func (c *CustomFuncs) CanPruneAggCols(target memo.AggregationsExpr, neededCols opt.ColSet) bool

CanPruneAggCols returns true if one or more of the target aggregations is not referenced and can be eliminated.

func (*CustomFuncs) CanPruneCols Uses

func (c *CustomFuncs) CanPruneCols(target memo.RelExpr, neededCols opt.ColSet) bool

CanPruneCols returns true if the target expression has extra columns that are not needed at this level of the tree, and can be eliminated by one of the PruneCols rules. CanPruneCols uses the PruneCols property to determine the set of columns which can be pruned, and subtracts the given set of additional needed columns from that. See the props.Relational.Rule.PruneCols comment for more details.

func (*CustomFuncs) CanPruneMutationFetchCols Uses

func (c *CustomFuncs) CanPruneMutationFetchCols(
    private *memo.MutationPrivate, neededCols opt.ColSet,
) bool

CanPruneMutationFetchCols returns true if there are any FetchCols that are not in the set of needed columns. Those extra FetchCols can be pruned.

func (*CustomFuncs) CanPruneMutationReturnCols Uses

func (c *CustomFuncs) CanPruneMutationReturnCols(
    private *memo.MutationPrivate, needed opt.ColSet,
) bool

CanPruneMutationReturnCols checks whether the mutation's return columns can be pruned. This is the pre-condition for the PruneMutationReturnCols rule.

func (*CustomFuncs) CanPruneWindows Uses

func (c *CustomFuncs) CanPruneWindows(needed opt.ColSet, windows memo.WindowsExpr) bool

CanPruneWindows is true if the list of window functions contains a column which is not included in needed, meaning that it can be pruned.

func (*CustomFuncs) CanPushColumnRemappingIntoValues Uses

func (c *CustomFuncs) CanPushColumnRemappingIntoValues(
    projections memo.ProjectionsExpr, passthrough opt.ColSet, values memo.RelExpr,
) bool

CanPushColumnRemappingIntoValues returns true if there is at least one ProjectionsItem for which the following conditions hold:

1. The ProjectionsItem remaps an output column from the given ValuesExpr.

2. The Values output column being remapped is not in the passthrough set.

func (*CustomFuncs) CanRemoveAggDistinctForKeys Uses

func (c *CustomFuncs) CanRemoveAggDistinctForKeys(
    input memo.RelExpr, private *memo.GroupingPrivate, agg opt.ScalarExpr,
) bool

CanRemoveAggDistinctForKeys returns true if the given aggregate function where its input column, together with the grouping columns, form a key. In this case, the wrapper AggDistinct can be removed.

func (*CustomFuncs) CanSimplifyExplainOrdering Uses

func (c *CustomFuncs) CanSimplifyExplainOrdering(
    in memo.RelExpr, private *memo.ExplainPrivate,
) bool

CanSimplifyExplainOrdering returns true if the ordering required by the Explain operator can be made less restrictive, so that the input operator has more ordering choices.

func (*CustomFuncs) CanSimplifyGroupingOrdering Uses

func (c *CustomFuncs) CanSimplifyGroupingOrdering(
    in memo.RelExpr, private *memo.GroupingPrivate,
) bool

CanSimplifyGroupingOrdering returns true if the ordering required by the grouping operator can be made less restrictive, so that the input operator has more ordering choices.

func (*CustomFuncs) CanSimplifyLimitOffsetOrdering Uses

func (c *CustomFuncs) CanSimplifyLimitOffsetOrdering(
    in memo.RelExpr, ordering physical.OrderingChoice,
) bool

CanSimplifyLimitOffsetOrdering returns true if the ordering required by the Limit or Offset operator can be made less restrictive, so that the input operator has more ordering choices.

func (*CustomFuncs) CanSimplifyOrdinalityOrdering Uses

func (c *CustomFuncs) CanSimplifyOrdinalityOrdering(
    in memo.RelExpr, private *memo.OrdinalityPrivate,
) bool

CanSimplifyOrdinalityOrdering returns true if the ordering required by the Ordinality operator can be made less restrictive, so that the input operator has more ordering choices.

func (*CustomFuncs) CanSimplifyWindowOrdering Uses

func (c *CustomFuncs) CanSimplifyWindowOrdering(in memo.RelExpr, private *memo.WindowPrivate) bool

CanSimplifyWindowOrdering is true if the intra-partition ordering used by the window function can be made less restrictive.

func (*CustomFuncs) CanUnnestJSONFromValues Uses

func (c *CustomFuncs) CanUnnestJSONFromValues(
    relExpr memo.RelExpr, projections memo.ProjectionsExpr, jsonCol opt.ColumnID,
) bool

CanUnnestJSONFromValues returns true if the Values operator has a single column containing JSON expressions that can be unfolded into multiple columns. This is the case if:

1. The projections don't directly reference the JSON itself. Only fields
   within the JSON object can be referenced.
2. All JSON keys referenced by the projections are present in the first row.
3. All JSON keys present in the first row are present in all other rows.

CanUnnestJSONFromValues should only be called if the Values operator has a single column and at least one row.

Note: technically we only need to check that the JSON fields referenced by the projections exist in all the rows. For simplicity, we instead check that (1) all references exist in the first row and (2) that all keys from the first row also exist in all other rows.

func (*CustomFuncs) CanUnnestTuplesFromValues Uses

func (c *CustomFuncs) CanUnnestTuplesFromValues(expr memo.RelExpr) bool

CanUnnestTuplesFromValues returns true if the given single-column Values operator has tuples that can be unfolded into multiple columns. This is the case if:

	1. The single output column is of type tuple.
	2. All tuples in the single column are either TupleExpr's or ConstExpr's
    that wrap DTuples, as opposed to dynamically generated tuples.

func (*CustomFuncs) CanaryColSet Uses

func (c *CustomFuncs) CanaryColSet(canaryCol opt.ColumnID) opt.ColSet

CanaryColSet returns a singleton set containing the canary column if set, otherwise the empty set.

func (*CustomFuncs) CandidateKey Uses

func (c *CustomFuncs) CandidateKey(input memo.RelExpr) (key opt.ColSet, ok bool)

CandidateKey returns the candidate key columns from the given input expression. If there is no candidate key, CandidateKey returns ok=false.

func (*CustomFuncs) CastToCollatedString Uses

func (c *CustomFuncs) CastToCollatedString(str opt.ScalarExpr, locale string) opt.ScalarExpr

CastToCollatedString returns the given string or collated string as a collated string constant with the given locale.

func (*CustomFuncs) ColsAreConst Uses

func (c *CustomFuncs) ColsAreConst(cols opt.ColSet, input memo.RelExpr) bool

ColsAreConst returns true if the given columns have the same values for all rows in the given input expression.

func (*CustomFuncs) ColsAreDeterminedBy Uses

func (c *CustomFuncs) ColsAreDeterminedBy(cols, in opt.ColSet, input memo.RelExpr) bool

ColsAreDeterminedBy returns true if the given columns are functionally determined by the "in" ColSet according to the functional dependencies of the input expression.

func (*CustomFuncs) ColsAreEmpty Uses

func (c *CustomFuncs) ColsAreEmpty(cols opt.ColSet) bool

ColsAreEmpty returns true if the given column set is empty.

func (*CustomFuncs) ColsAreEqual Uses

func (c *CustomFuncs) ColsAreEqual(left, right opt.ColSet) bool

ColsAreEqual returns true if left and right contain the same set of columns.

func (*CustomFuncs) ColsAreLenOne Uses

func (c *CustomFuncs) ColsAreLenOne(cols opt.ColSet) bool

ColsAreLenOne returns true if the input ColSet has exactly one column.

func (*CustomFuncs) ColsAreStrictKey Uses

func (c *CustomFuncs) ColsAreStrictKey(cols opt.ColSet, input memo.RelExpr) bool

ColsAreStrictKey returns true if the given columns form a strict key for the given input expression. A strict key means that any two rows will have unique key column values. Nulls are treated as equal to one another (i.e. no duplicate nulls allowed). Having a strict key means that the set of key column values uniquely determine the values of all other columns in the relation.

func (*CustomFuncs) ColsAreSubset Uses

func (c *CustomFuncs) ColsAreSubset(left, right opt.ColSet) bool

ColsAreSubset returns true if the left columns are a subset of the right columns.

func (*CustomFuncs) ColsIntersect Uses

func (c *CustomFuncs) ColsIntersect(left, right opt.ColSet) bool

ColsIntersect returns true if at least one column appears in both the left and right sets.

func (*CustomFuncs) CommuteInequality Uses

func (c *CustomFuncs) CommuteInequality(
    op opt.Operator, left, right opt.ScalarExpr,
) opt.ScalarExpr

CommuteInequality swaps the operands of an inequality comparison expression, changing the operator to compensate:

5 < x

to:

x > 5

func (*CustomFuncs) CommuteJoinFlags Uses

func (c *CustomFuncs) CommuteJoinFlags(p *memo.JoinPrivate) *memo.JoinPrivate

CommuteJoinFlags returns a join private for the commuted join (where the left and right sides are swapped). It adjusts any join flags that are specific to one side.

func (*CustomFuncs) ConcatFilters Uses

func (c *CustomFuncs) ConcatFilters(left, right memo.FiltersExpr) memo.FiltersExpr

ConcatFilters creates a new Filters operator that contains conditions from both the left and right boolean filter expressions.

func (*CustomFuncs) ConcatLeftDeepAnds Uses

func (c *CustomFuncs) ConcatLeftDeepAnds(left, right opt.ScalarExpr) opt.ScalarExpr

ConcatLeftDeepAnds concatenates any left-deep And expressions in the right expression with any left-deep And expressions in the left expression. The result is a combined left-deep And expression. Note that NormalizeNestedAnds has already guaranteed that both inputs will already be left-deep.

func (*CustomFuncs) ConsolidateFilters Uses

func (c *CustomFuncs) ConsolidateFilters(filters memo.FiltersExpr) memo.FiltersExpr

ConsolidateFilters consolidates filter conditions that contain the same variable, where the conditions have tight constraints and contain a single variable. The consolidated filters are combined with a tree of nested And operations, and wrapped with a Range expression.

See the ConsolidateSelectFilters rule for more details about why this is necessary.

func (*CustomFuncs) ConstructAnyCondition Uses

func (c *CustomFuncs) ConstructAnyCondition(
    input memo.RelExpr, scalar opt.ScalarExpr, private *memo.SubqueryPrivate,
) opt.ScalarExpr

ConstructAnyCondition builds an expression that compares the given scalar expression with the first (and only) column of the input rowset, using the given comparison operator.

func (*CustomFuncs) ConstructApplyJoin Uses

func (c *CustomFuncs) ConstructApplyJoin(
    joinOp opt.Operator, left, right memo.RelExpr, on memo.FiltersExpr, private *memo.JoinPrivate,
) memo.RelExpr

ConstructApplyJoin constructs the apply join operator that corresponds to the given join operator type.

func (*CustomFuncs) ConstructBinary Uses

func (c *CustomFuncs) ConstructBinary(op opt.Operator, left, right opt.ScalarExpr) opt.ScalarExpr

ConstructBinary builds a dynamic binary expression, given the binary operator's type and its two arguments.

func (*CustomFuncs) ConstructEmptyValues Uses

func (c *CustomFuncs) ConstructEmptyValues(cols opt.ColSet) memo.RelExpr

ConstructEmptyValues constructs a Values expression with no rows.

func (*CustomFuncs) ConstructNoColsRow Uses

func (c *CustomFuncs) ConstructNoColsRow() memo.RelExpr

ConstructNoColsRow returns a Values operator having a single row with zero columns.

func (*CustomFuncs) ConstructNonApplyJoin Uses

func (c *CustomFuncs) ConstructNonApplyJoin(
    joinOp opt.Operator, left, right memo.RelExpr, on memo.FiltersExpr, private *memo.JoinPrivate,
) memo.RelExpr

ConstructNonApplyJoin constructs the non-apply join operator that corresponds to the given join operator type.

func (*CustomFuncs) ConstructNonLeftJoin Uses

func (c *CustomFuncs) ConstructNonLeftJoin(
    joinOp opt.Operator, left, right memo.RelExpr, on memo.FiltersExpr, private *memo.JoinPrivate,
) memo.RelExpr

ConstructNonLeftJoin maps a left join to an inner join and a full join to a right join when it can be proved that the right side of the join always produces at least one row for every row on the left.

func (*CustomFuncs) ConstructProjectionFromDistinctOn Uses

func (c *CustomFuncs) ConstructProjectionFromDistinctOn(
    input memo.RelExpr, groupingCols opt.ColSet, aggs memo.AggregationsExpr,
) memo.RelExpr

ConstructProjectionFromDistinctOn converts a DistinctOn to a projection; this is correct when input groupings have at most one row (i.e. the input is already distinct). Note that DistinctOn can only have aggregations of type FirstAgg or ConstAgg.

func (*CustomFuncs) ConstructSortedUniqueList Uses

func (c *CustomFuncs) ConstructSortedUniqueList(
    list memo.ScalarListExpr,
) (memo.ScalarListExpr, *types.T)

ConstructSortedUniqueList sorts the given list and removes duplicates, and returns the resulting list. See the comment for listSorter.compare for comparison rule details.

func (*CustomFuncs) ConstructValuesFromZips Uses

func (c *CustomFuncs) ConstructValuesFromZips(zip memo.ZipExpr) memo.RelExpr

ConstructValuesFromZips constructs a Values operator with the elements from the given ArrayExpr(s) or the ConstExpr(s) that wrap a DArray or DJSON in the given ZipExpr.

The functions contained in the ZipExpr must be unnest, json_array_elements or jsonb_array_elements functions with a single parameter each. The parameters of the unnest functions must be either ArrayExprs or ConstExprs wrapping DArrays. The parameters of the json_array_elements functions must be ConstExprs wrapping DJSON datums.

func (*CustomFuncs) ConvertConstArrayToTuple Uses

func (c *CustomFuncs) ConvertConstArrayToTuple(scalar opt.ScalarExpr) opt.ScalarExpr

ConvertConstArrayToTuple converts a constant ARRAY datum to the equivalent homogeneous tuple, so ARRAY[1, 2, 3] becomes (1, 2, 3).

func (*CustomFuncs) DerefOrderingChoice Uses

func (c *CustomFuncs) DerefOrderingChoice(result *physical.OrderingChoice) physical.OrderingChoice

DerefOrderingChoice returns an OrderingChoice from a pointer.

func (*CustomFuncs) DifferenceCols Uses

func (c *CustomFuncs) DifferenceCols(left, right opt.ColSet) opt.ColSet

DifferenceCols returns the difference of the left and right column sets.

func (*CustomFuncs) DuplicateScanPrivate Uses

func (c *CustomFuncs) DuplicateScanPrivate(sp *memo.ScanPrivate) *memo.ScanPrivate

DuplicateScanPrivate constructs a new ScanPrivate with new table and column IDs. Only the Index, Flags and Locking fields are copied from the old ScanPrivate, so the new ScanPrivate will not have constraints even if the old one did.

func (*CustomFuncs) EmptyJoinPrivate Uses

func (c *CustomFuncs) EmptyJoinPrivate() *memo.JoinPrivate

EmptyJoinPrivate returns an unset JoinPrivate.

func (*CustomFuncs) EmptyOrdering Uses

func (c *CustomFuncs) EmptyOrdering() physical.OrderingChoice

EmptyOrdering returns a pseudo-choice that does not require any ordering.

func (*CustomFuncs) EnsureAggsCanIgnoreNulls Uses

func (c *CustomFuncs) EnsureAggsCanIgnoreNulls(
    in memo.RelExpr, aggs memo.AggregationsExpr,
) memo.AggregationsExpr

EnsureAggsCanIgnoreNulls scans the aggregate list to aggregation functions that don't ignore nulls but can be remapped so that they do:

- CountRows functions are are converted to Count functions that operate
  over a not-null column from the given input expression. The
  EnsureNotNullIfNeeded method should already have been called in order
  to guarantee such a column exists.
- ConstAgg is remapped to ConstNotNullAgg.
- Other aggregates that can use a canary column to detect nulls.

See the TryDecorrelateScalarGroupBy rule comment for more details.

func (*CustomFuncs) EnsureCanary Uses

func (c *CustomFuncs) EnsureCanary(in memo.RelExpr, canaryCol opt.ColumnID) memo.RelExpr

EnsureCanary makes sure that if canaryCol is set, it is projected by the input expression.

See the TryDecorrelateScalarGroupBy rule comment for more details.

func (*CustomFuncs) EnsureCanaryCol Uses

func (c *CustomFuncs) EnsureCanaryCol(in memo.RelExpr, aggs memo.AggregationsExpr) opt.ColumnID

EnsureCanaryCol checks whether an aggregation which cannot ignore nulls exists. If one does, it then checks if there are any non-null columns in the input. If there is not one, it synthesizes a new True constant column that is not-null. This becomes a kind of "canary" column that other expressions can inspect, since any null value in this column indicates that the row was added by an outer join as part of null extending.

EnsureCanaryCol returns the input expression, possibly wrapped in a new Project if a new column was synthesized.

See the TryDecorrelateScalarGroupBy rule comment for more details.

func (*CustomFuncs) EnsureKey Uses

func (c *CustomFuncs) EnsureKey(in memo.RelExpr) memo.RelExpr

EnsureKey finds the shortest strong key for the input expression. If no strong key exists and the input expression is a scan, EnsureKey returns a new Scan with the preexisting primary key for the table. If the input is not a Scan, EnsureKey wraps the input in an Ordinality operator, which provides a key column by uniquely numbering the rows. EnsureKey returns the input expression (perhaps augmented with a key column(s) or wrapped by Ordinality).

func (*CustomFuncs) EqualsNumber Uses

func (c *CustomFuncs) EqualsNumber(datum tree.Datum, value int64) bool

EqualsNumber returns true if the given numeric value (decimal, float, or integer) is equal to the given integer value.

func (*CustomFuncs) EqualsString Uses

func (c *CustomFuncs) EqualsString(left string, right string) bool

EqualsString returns true if the given strings are equal. This function is useful in matching expressions that have string fields.

For example, NormalizeCmpTimeZoneFunction uses this function implicitly to match a specific function, like so:

(Function $args:* (FunctionPrivate "timezone"))

func (*CustomFuncs) ErrorOnDup Uses

func (c *CustomFuncs) ErrorOnDup(private *memo.GroupingPrivate) string

ErrorOnDup returns the error text contained by the given GroupingPrivate.

func (*CustomFuncs) ExprIsNeverNull Uses

func (c *CustomFuncs) ExprIsNeverNull(e opt.ScalarExpr, notNullCols opt.ColSet) bool

ExprIsNeverNull returns true if we can prove that the given scalar expression is always non-NULL. Any variables that refer to columns in the notNullCols set are assumed to be non-NULL. See memo.ExprIsNeverNull.

func (*CustomFuncs) ExtractAggInputColumns Uses

func (c *CustomFuncs) ExtractAggInputColumns(e opt.ScalarExpr) opt.ColSet

ExtractAggInputColumns returns the set of columns the aggregate depends on.

func (*CustomFuncs) ExtractBoundConditions Uses

func (c *CustomFuncs) ExtractBoundConditions(
    filters memo.FiltersExpr, cols opt.ColSet,
) memo.FiltersExpr

ExtractBoundConditions returns a new list containing only those expressions from the given list that are fully bound by the given columns (i.e. all outer references are to one of these columns). For example:

(InnerJoin
  (Scan a)
  (Scan b)
  (Filters [
    (Eq (Variable a.x) (Variable b.x))
    (Gt (Variable a.x) (Const 1))
  ])
)

Calling ExtractBoundConditions with the filter conditions list and the output columns of (Scan a) would extract the (Gt) expression, since its outer references only reference columns from a.

func (*CustomFuncs) ExtractDeterminedConditions Uses

func (c *CustomFuncs) ExtractDeterminedConditions(
    filters memo.FiltersExpr, cols opt.ColSet, input memo.RelExpr,
) memo.FiltersExpr

ExtractDeterminedConditions returns a new list of filters containing only those expressions from the given list which are bound by columns which are functionally determined by the given columns.

func (*CustomFuncs) ExtractGroupingOrdering Uses

func (c *CustomFuncs) ExtractGroupingOrdering(
    private *memo.GroupingPrivate,
) physical.OrderingChoice

ExtractGroupingOrdering returns the ordering associated with the input GroupingPrivate.

func (*CustomFuncs) ExtractJoinEquality Uses

func (c *CustomFuncs) ExtractJoinEquality(
    joinOp opt.Operator,
    left, right memo.RelExpr,
    filters memo.FiltersExpr,
    item *memo.FiltersItem,
    private *memo.JoinPrivate,
) memo.RelExpr

ExtractJoinEquality takes an equality FiltersItem that was identified via a call to CanExtractJoinEquality, and converts it to an equality on "bare" variables, by pushing down more complicated expressions as projections. See the ExtractJoinEqualities rule.

func (*CustomFuncs) ExtractRedundantConjunct Uses

func (c *CustomFuncs) ExtractRedundantConjunct(
    conjunct, left, right opt.ScalarExpr,
) opt.ScalarExpr

ExtractRedundantConjunct extracts a redundant conjunct from an Or expression, and returns an And of the conjunct with the remaining Or expression (a logically equivalent expression). For example:

(A AND B) OR (A AND C)  =>  A AND (B OR C)

If extracting the conjunct from one of the OR conditions would result in an empty condition, the conjunct itself is returned (a logically equivalent expression). For example:

A OR (A AND B)  =>  A

These transformations are useful for finding a conjunct that can be pushed down in the query tree. For example, if the redundant conjunct A is fully bound by one side of a join, it can be pushed through the join, even if B and C cannot.

func (*CustomFuncs) ExtractUnboundConditions Uses

func (c *CustomFuncs) ExtractUnboundConditions(
    filters memo.FiltersExpr, cols opt.ColSet,
) memo.FiltersExpr

ExtractUnboundConditions is the opposite of ExtractBoundConditions. Instead of extracting expressions that are bound by the given columns, it extracts list expressions that have at least one outer reference that is *not* bound by the given columns (i.e. it has a "free" variable).

func (*CustomFuncs) ExtractUndeterminedConditions Uses

func (c *CustomFuncs) ExtractUndeterminedConditions(
    filters memo.FiltersExpr, cols opt.ColSet, input memo.RelExpr,
) memo.FiltersExpr

ExtractUndeterminedConditions is the opposite of ExtractDeterminedConditions.

func (*CustomFuncs) FilterHasCorrelatedSubquery Uses

func (c *CustomFuncs) FilterHasCorrelatedSubquery(filters memo.FiltersExpr) bool

FilterHasCorrelatedSubquery returns true if any of the filter conditions contain a correlated subquery.

func (*CustomFuncs) FilterOuterCols Uses

func (c *CustomFuncs) FilterOuterCols(filters memo.FiltersExpr) opt.ColSet

FilterOuterCols returns the union of all outer columns from the given filter conditions.

func (*CustomFuncs) FiltersBoundBy Uses

func (c *CustomFuncs) FiltersBoundBy(filters memo.FiltersExpr, cols opt.ColSet) bool

FiltersBoundBy returns true if all outer references in any of the filter conditions are bound by the given columns. For example:

(InnerJoin
  (Scan a)
  (Scan b)
  $filters:[ (FiltersItem (Eq (Variable a.x) (Const 1))) ]
)

The $filters expression is fully bound by the output columns of the (Scan a) expression because all of its outer references are satisfied by the columns produced by the Scan.

func (*CustomFuncs) FindInlinableConstants Uses

func (c *CustomFuncs) FindInlinableConstants(input memo.RelExpr) opt.ColSet

FindInlinableConstants returns the set of input columns that are synthesized constant value expressions: ConstOp, TrueOp, FalseOp, or NullOp. Constant value expressions can often be inlined into referencing expressions. Only Project and Values operators synthesize constant value expressions.

func (*CustomFuncs) FindRedundantConjunct Uses

func (c *CustomFuncs) FindRedundantConjunct(left, right opt.ScalarExpr) opt.ScalarExpr

FindRedundantConjunct takes the left and right operands of an Or operator as input. It examines each conjunct from the left expression and determines whether it appears as a conjunct in the right expression. If so, it returns the matching conjunct. Otherwise, it returns nil. For example:

A OR A                               =>  A
B OR A                               =>  nil
A OR (A AND B)                       =>  A
(A AND B) OR (A AND C)               =>  A
(A AND B AND C) OR (A AND (D OR E))  =>  A

Once a redundant conjunct has been found, it is extracted via a call to the ExtractRedundantConjunct function. Redundant conjuncts are extracted from multiple nested Or operators by repeated application of these functions.

func (*CustomFuncs) FirstScalarListExpr Uses

func (c *CustomFuncs) FirstScalarListExpr(list memo.ScalarListExpr) opt.ScalarExpr

FirstScalarListExpr returns the first ScalarExpr in the given list.

func (*CustomFuncs) FoldArray Uses

func (c *CustomFuncs) FoldArray(elems memo.ScalarListExpr, typ *types.T) opt.ScalarExpr

FoldArray evaluates an Array expression with constant inputs. It returns the array as a Const datum with type TArray.

func (*CustomFuncs) FoldBinary Uses

func (c *CustomFuncs) FoldBinary(op opt.Operator, left, right opt.ScalarExpr) opt.ScalarExpr

FoldBinary evaluates a binary expression with constant inputs. It returns a constant expression as long as it finds an appropriate overload function for the given operator and input types, and the evaluation causes no error.

func (*CustomFuncs) FoldCast Uses

func (c *CustomFuncs) FoldCast(input opt.ScalarExpr, typ *types.T) opt.ScalarExpr

FoldCast evaluates a cast expression with a constant input. It returns a constant expression as long as the evaluation causes no error.

func (*CustomFuncs) FoldColumnAccess Uses

func (c *CustomFuncs) FoldColumnAccess(input opt.ScalarExpr, idx memo.TupleOrdinal) opt.ScalarExpr

FoldColumnAccess tries to evaluate a tuple column access operator with a constant tuple input (though tuple field values do not need to be constant). It returns the referenced tuple field value, or nil if folding is not possible or results in an error.

func (*CustomFuncs) FoldComparison Uses

func (c *CustomFuncs) FoldComparison(op opt.Operator, left, right opt.ScalarExpr) opt.ScalarExpr

FoldComparison evaluates a comparison expression with constant inputs. It returns a constant expression as long as it finds an appropriate overload function for the given operator and input types, and the evaluation causes no error.

func (*CustomFuncs) FoldFunction Uses

func (c *CustomFuncs) FoldFunction(
    args memo.ScalarListExpr, private *memo.FunctionPrivate,
) opt.ScalarExpr

FoldFunction evaluates a function expression with constant inputs. It returns a constant expression as long as the function is contained in the FoldFunctionAllowlist, and the evaluation causes no error.

func (*CustomFuncs) FoldIndirection Uses

func (c *CustomFuncs) FoldIndirection(input, index opt.ScalarExpr) opt.ScalarExpr

FoldIndirection evaluates an array indirection operator with constant inputs. It returns the referenced array element as a constant value, or nil if the evaluation results in an error.

func (*CustomFuncs) FoldJSONFieldAccess Uses

func (c *CustomFuncs) FoldJSONFieldAccess(
    projections memo.ProjectionsExpr,
    newCols opt.ColList,
    oldColID opt.ColumnID,
    oldInput memo.RelExpr,
) memo.ProjectionsExpr

FoldJSONFieldAccess constructs a new ProjectionsExpr from the old one with any FetchVal operators that refer to the original JSON column (oldColID) replaced by new Variables wrapping columns from the output of the given ValuesExpr. Example:

SELECT j->'a' AS j_a FROM ...

=>

SELECT j_a FROM ...

func (*CustomFuncs) FoldNullBinary Uses

func (c *CustomFuncs) FoldNullBinary(op opt.Operator, left, right opt.ScalarExpr) opt.ScalarExpr

FoldNullBinary replaces the binary operator with a typed null value having the same type as the binary operator would have.

func (*CustomFuncs) FoldNullUnary Uses

func (c *CustomFuncs) FoldNullUnary(op opt.Operator, input opt.ScalarExpr) opt.ScalarExpr

FoldNullUnary replaces the unary operator with a typed null value having the same type as the unary operator would have.

func (*CustomFuncs) FoldTupleColumnAccess Uses

func (c *CustomFuncs) FoldTupleColumnAccess(
    projections memo.ProjectionsExpr, valuesCols opt.ColList, oldColID opt.ColumnID,
) memo.ProjectionsExpr

FoldTupleColumnAccess constructs a new ProjectionsExpr from the old one with any ColumnAccess operators that refer to the original tuple column (oldColID) replaced by new columns from the output of the given ValuesExpr.

func (*CustomFuncs) FoldUnary Uses

func (c *CustomFuncs) FoldUnary(op opt.Operator, input opt.ScalarExpr) opt.ScalarExpr

FoldUnary evaluates a unary expression with a constant input. It returns a constant expression as long as it finds an appropriate overload function for the given operator and input type, and the evaluation causes no error.

func (*CustomFuncs) GetEquivColsWithEquivType Uses

func (c *CustomFuncs) GetEquivColsWithEquivType(
    col opt.ColumnID, equivFD props.FuncDepSet,
) opt.ColSet

GetEquivColsWithEquivType uses the given FuncDepSet to find columns that are equivalent to col, and returns only those columns that also have the same type as col. This function is used when inferring new filters based on equivalent columns, because operations that are valid with one type may be invalid with a different type.

In addition, if col has a composite key encoding, we cannot guarantee that it will be exactly equal to other "equivalent" columns, so in that case we return a set containing only col. This is a conservative measure to ensure that we don't infer filters incorrectly. For example, consider this query:

SELECT * FROM
  (VALUES (1.0)) AS t1(x),
  (VALUES (1.00)) AS t2(y)
WHERE x=y AND x::text = '1.0';

It should return the following result:

  x  |  y
-----+------
 1.0 | 1.00

But if we use the equality predicate x=y to map x to y and infer an additional filter y::text = '1.0', the query would return nothing.

TODO(rytaft): In the future, we may want to allow the mapping if the filter involves a comparison operator, such as x < 5.

func (*CustomFuncs) GetEquivFD Uses

func (c *CustomFuncs) GetEquivFD(
    filters memo.FiltersExpr, left, right memo.RelExpr,
) (equivFD props.FuncDepSet)

GetEquivFD gets a FuncDepSet with all equivalence dependencies from filters, left and right.

func (*CustomFuncs) GetNullRejectedCols Uses

func (c *CustomFuncs) GetNullRejectedCols(filters memo.FiltersExpr) opt.ColSet

GetNullRejectedCols returns the set of columns which are null-rejected by the given FiltersExpr.

func (*CustomFuncs) GroupingAndConstCols Uses

func (c *CustomFuncs) GroupingAndConstCols(
    grouping *memo.GroupingPrivate, aggs memo.AggregationsExpr,
) opt.ColSet

GroupingAndConstCols returns the grouping columns and ConstAgg columns (for which the input and output column IDs match). A filter on these columns can be pushed through a GroupBy.

func (*CustomFuncs) GroupingCols Uses

func (c *CustomFuncs) GroupingCols(grouping *memo.GroupingPrivate) opt.ColSet

GroupingCols returns the grouping columns from the given grouping private.

func (*CustomFuncs) GroupingInputOrdering Uses

func (c *CustomFuncs) GroupingInputOrdering(private *memo.GroupingPrivate) physical.OrderingChoice

GroupingInputOrdering returns the Ordering in the private.

func (*CustomFuncs) GroupingOutputCols Uses

func (c *CustomFuncs) GroupingOutputCols(
    grouping *memo.GroupingPrivate, aggs memo.AggregationsExpr,
) opt.ColSet

GroupingOutputCols returns the output columns of a GroupBy, ScalarGroupBy, or DistinctOn expression.

func (*CustomFuncs) HasAllNonNullElements Uses

func (c *CustomFuncs) HasAllNonNullElements(input opt.ScalarExpr) bool

HasAllNonNullElements returns true if the input tuple has all constant, non-null elements, or if the tuple is empty (has 0 elements). Note that it only returns true if all elements are known to be non-null. For example, given the tuple (1, x), it will return false because x is not guaranteed to be non-null.

func (*CustomFuncs) HasAllNullElements Uses

func (c *CustomFuncs) HasAllNullElements(input opt.ScalarExpr) bool

HasAllNullElements returns true if the input tuple has only constant, null elements, or if the tuple is empty (has 0 elements). Note that it only returns true if all elements are known to be null. For example, given the tuple (NULL, x), it will return false because x is not guaranteed to be null.

func (*CustomFuncs) HasColType Uses

func (c *CustomFuncs) HasColType(scalar opt.ScalarExpr, dstTyp *types.T) bool

HasColType returns true if the given scalar expression has a static type that's identical to the requested coltype.

func (*CustomFuncs) HasDuplicateRefs Uses

func (c *CustomFuncs) HasDuplicateRefs(
    projections memo.ProjectionsExpr, passthrough opt.ColSet, targetCols opt.ColSet,
) bool

HasDuplicateRefs returns true if the target projection expressions or passthrough columns reference any column in the given target set more than one time, or if the projection expressions contain a correlated subquery. For example:

SELECT x+1, x+2, y FROM a

HasDuplicateRefs would be true, since the x column is referenced twice.

Correlated subqueries are disallowed since it introduces additional complexity for a case that's not too important for inlining. Also, skipping correlated subqueries minimizes expensive searching in deep trees.

func (*CustomFuncs) HasHoistableSubquery Uses

func (c *CustomFuncs) HasHoistableSubquery(scalar opt.ScalarExpr) bool

HasHoistableSubquery returns true if the given scalar expression contains a subquery within its subtree that has at least one outer column, and if that subquery needs to be hoisted up into its parent query as part of query decorrelation.

func (*CustomFuncs) HasNoDirectTupleReferences Uses

func (c *CustomFuncs) HasNoDirectTupleReferences(
    projections memo.ProjectionsExpr, tupleCol opt.ColumnID,
) bool

HasNoDirectTupleReferences ensures that the input ProjectionsExpr contains no direct references to the tuple represented by the given ColumnID.

func (*CustomFuncs) HasNoGroupingCols Uses

func (c *CustomFuncs) HasNoGroupingCols(private *memo.GroupingPrivate) bool

HasNoGroupingCols returns true if the GroupingCols in the private are empty.

func (*CustomFuncs) HasNonNullElement Uses

func (c *CustomFuncs) HasNonNullElement(input opt.ScalarExpr) bool

HasNonNullElement returns true if the input tuple has at least one constant, non-null element. Note that it only returns true if one element is known to be non-null. For example, given the tuple (NULL, x), it will return false because x is not guaranteed to be non-null.

func (*CustomFuncs) HasNullElement Uses

func (c *CustomFuncs) HasNullElement(input opt.ScalarExpr) bool

HasNullElement returns true if the input tuple has at least one constant, null element. Note that it only returns true if one element is known to be null. For example, given the tuple (1, x), it will return false because x is not guaranteed to be null.

func (*CustomFuncs) HasNullRejectingFilter Uses

func (c *CustomFuncs) HasNullRejectingFilter(
    filters memo.FiltersExpr, nullRejectCols opt.ColSet,
) bool

HasNullRejectingFilter returns true if the filter causes some of the columns in nullRejectCols to be non-null. For example, if nullRejectCols = (x, z), filters such as x < 5, x = y, and z IS NOT NULL all satisfy this property.

func (*CustomFuncs) HasOneRow Uses

func (c *CustomFuncs) HasOneRow(input memo.RelExpr) bool

HasOneRow returns true if the input expression always returns exactly one row.

func (*CustomFuncs) HasOuterCols Uses

func (c *CustomFuncs) HasOuterCols(input opt.Expr) bool

HasOuterCols returns true if the input expression has at least one outer column, or in other words, a reference to a variable that is not bound within its own scope. For example:

SELECT * FROM a WHERE EXISTS(SELECT * FROM b WHERE b.x = a.x)

The a.x variable in the EXISTS subquery references a column outside the scope of the subquery. It is an "outer column" for the subquery (see the comment on RelationalProps.OuterCols for more details).

func (*CustomFuncs) HasStrictKey Uses

func (c *CustomFuncs) HasStrictKey(input memo.RelExpr) bool

HasStrictKey returns true if the input expression has one or more columns that form a strict key (see comment for ColsAreStrictKey for definition).

func (*CustomFuncs) HasZeroOrOneRow Uses

func (c *CustomFuncs) HasZeroOrOneRow(input memo.RelExpr) bool

HasZeroOrOneRow returns true if the input expression returns at most one row.

func (*CustomFuncs) HasZeroRows Uses

func (c *CustomFuncs) HasZeroRows(input memo.RelExpr) bool

HasZeroRows returns true if the input expression never returns any rows.

func (*CustomFuncs) HoistJoinSubquery Uses

func (c *CustomFuncs) HoistJoinSubquery(
    op opt.Operator, left, right memo.RelExpr, on memo.FiltersExpr, private *memo.JoinPrivate,
) memo.RelExpr

HoistJoinSubquery searches the Join operator's filter for correlated subqueries. Any found queries are hoisted into LeftJoinApply or InnerJoinApply operators, depending on subquery cardinality:

SELECT y, z
FROM xy
FULL JOIN yz
ON (SELECT u FROM uv WHERE u=x LIMIT 1) IS NULL
=>
SELECT y, z
FROM xy
FULL JOIN LATERAL
(
  SELECT *
  FROM yz
  LEFT JOIN LATERAL (SELECT u FROM uv WHERE u=x LIMIT 1)
  ON True
)
ON u IS NULL

func (*CustomFuncs) HoistProjectSetSubquery Uses

func (c *CustomFuncs) HoistProjectSetSubquery(input memo.RelExpr, zip memo.ZipExpr) memo.RelExpr

HoistProjectSetSubquery searches the ProjectSet operator's functions for correlated subqueries. Any found queries are hoisted into LeftJoinApply or InnerJoinApply operators, depending on subquery cardinality:

SELECT generate_series
FROM xy
INNER JOIN LATERAL ROWS FROM
(
  generate_series(1, (SELECT v FROM uv WHERE u=x))
)
=>
SELECT generate_series
FROM xy
ROWS FROM
(
  SELECT generate_series
  FROM (VALUES ())
  LEFT JOIN LATERAL (SELECT v FROM uv WHERE u=x)
  ON True
  INNER JOIN LATERAL ROWS FROM (generate_series(1, v))
  ON True
)

func (*CustomFuncs) HoistProjectSubquery Uses

func (c *CustomFuncs) HoistProjectSubquery(
    input memo.RelExpr, projections memo.ProjectionsExpr, passthrough opt.ColSet,
) memo.RelExpr

HoistProjectSubquery searches the Project operator's projections for correlated subqueries. Any found queries are hoisted into LeftJoinApply or InnerJoinApply operators, depending on subquery cardinality:

SELECT (SELECT max(u) FROM uv WHERE u=x) AS max FROM xy
=>
SELECT max
FROM xy
INNER JOIN LATERAL (SELECT max(u) FROM uv WHERE u=x)
ON True

func (*CustomFuncs) HoistSelectSubquery Uses

func (c *CustomFuncs) HoistSelectSubquery(
    input memo.RelExpr, filters memo.FiltersExpr,
) memo.RelExpr

HoistSelectSubquery searches the Select operator's filter for correlated subqueries. Any found queries are hoisted into LeftJoinApply or InnerJoinApply operators, depending on subquery cardinality:

SELECT * FROM xy WHERE (SELECT u FROM uv WHERE u=x LIMIT 1) IS NULL
=>
SELECT xy.*
FROM xy
LEFT JOIN LATERAL (SELECT u FROM uv WHERE u=x LIMIT 1)
ON True
WHERE u IS NULL

func (*CustomFuncs) HoistValuesSubquery Uses

func (c *CustomFuncs) HoistValuesSubquery(
    rows memo.ScalarListExpr, private *memo.ValuesPrivate,
) memo.RelExpr

HoistValuesSubquery searches the Values operator's projections for correlated subqueries. Any found queries are hoisted into LeftJoinApply or InnerJoinApply operators, depending on subquery cardinality:

SELECT (VALUES (SELECT u FROM uv WHERE u=x LIMIT 1)) FROM xy
=>
SELECT
(
  SELECT vals.*
  FROM (VALUES ())
  LEFT JOIN LATERAL (SELECT u FROM uv WHERE u=x LIMIT 1)
  ON True
  INNER JOIN LATERAL (VALUES (u)) vals
  ON True
)
FROM xy

The dummy VALUES clause with a singleton empty row is added to the tree in order to use the hoister, which requires an initial input query. While a right join would be slightly better here, this is such a fringe case that it's not worth the extra code complication.

func (*CustomFuncs) Init Uses

func (c *CustomFuncs) Init(f *Factory)

Init initializes a new CustomFuncs with the given factory.

func (*CustomFuncs) InlineConstVar Uses

func (c *CustomFuncs) InlineConstVar(f memo.FiltersExpr) memo.FiltersExpr

InlineConstVar performs the inlining detected by CanInlineConstVar.

func (*CustomFuncs) InlineFilterConstants Uses

func (c *CustomFuncs) InlineFilterConstants(
    filters memo.FiltersExpr, input memo.RelExpr, constCols opt.ColSet,
) memo.FiltersExpr

InlineFilterConstants recursively searches each filter expression and replaces any references to input columns that are constant. It returns a new Filters list containing the replaced expressions.

func (*CustomFuncs) InlineProjectProject Uses

func (c *CustomFuncs) InlineProjectProject(
    input memo.RelExpr, projections memo.ProjectionsExpr, passthrough opt.ColSet,
) memo.RelExpr

InlineProjectProject searches the projection expressions for any variable references to columns from the given input (which must be a Project operator). Each variable is replaced by the corresponding inlined projection expression.

func (*CustomFuncs) InlineProjectionConstants Uses

func (c *CustomFuncs) InlineProjectionConstants(
    projections memo.ProjectionsExpr, input memo.RelExpr, constCols opt.ColSet,
) memo.ProjectionsExpr

InlineProjectionConstants recursively searches each projection expression and replaces any references to input columns that are constant. It returns a new Projections list containing the replaced expressions.

func (*CustomFuncs) InlineSelectProject Uses

func (c *CustomFuncs) InlineSelectProject(
    filters memo.FiltersExpr, projections memo.ProjectionsExpr,
) memo.FiltersExpr

InlineSelectProject searches the filter conditions for any variable references to columns from the given projections expression. Each variable is replaced by the corresponding inlined projection expression.

func (*CustomFuncs) InlineValues Uses

func (c *CustomFuncs) InlineValues(v memo.RelExpr) *memo.TupleExpr

InlineValues converts a Values operator to a tuple. If there are multiple columns, the result is a tuple of tuples.

func (*CustomFuncs) InlineWith Uses

func (c *CustomFuncs) InlineWith(binding, input memo.RelExpr, priv *memo.WithPrivate) memo.RelExpr

InlineWith replaces all references to the With expression in input (via WithScans) with its definition.

func (*CustomFuncs) IntConst Uses

func (c *CustomFuncs) IntConst(d *tree.DInt) opt.ScalarExpr

IntConst constructs a Const holding a DInt.

func (*CustomFuncs) IntersectionCols Uses

func (c *CustomFuncs) IntersectionCols(left, right opt.ColSet) opt.ColSet

IntersectionCols returns the intersection of the left and right column sets.

func (*CustomFuncs) IsAdditiveType Uses

func (c *CustomFuncs) IsAdditiveType(typ *types.T) bool

IsAdditiveType returns true if the given type supports addition and subtraction in the natural way. This differs from "has a +/- Numeric implementation" because JSON has an implementation for "- INT" which doesn't obey x - 0 = x. Additive types include all numeric types as well as timestamps and dates.

func (*CustomFuncs) IsBoundBy Uses

func (c *CustomFuncs) IsBoundBy(src opt.Expr, cols opt.ColSet) bool

IsBoundBy returns true if all outer references in the source expression are bound by the given columns. For example:

(InnerJoin
  (Scan a)
  (Scan b)
  [ ... $item:(FiltersItem (Eq (Variable a.x) (Const 1))) ... ]
)

The $item expression is fully bound by the output columns of the (Scan a) expression because all of its outer references are satisfied by the columns produced by the Scan.

func (*CustomFuncs) IsColNotNull Uses

func (c *CustomFuncs) IsColNotNull(col opt.ColumnID, input memo.RelExpr) bool

IsColNotNull returns true if the given input column is never null.

func (*CustomFuncs) IsColNotNull2 Uses

func (c *CustomFuncs) IsColNotNull2(col opt.ColumnID, left, right memo.RelExpr) bool

IsColNotNull2 returns true if the given column is part of the left or right expressions' set of not-null columns.

func (*CustomFuncs) IsConstArray Uses

func (c *CustomFuncs) IsConstArray(scalar opt.ScalarExpr) bool

IsConstArray returns true if the expression is a constant array.

func (*CustomFuncs) IsConstJSON Uses

func (c *CustomFuncs) IsConstJSON(expr opt.ScalarExpr) bool

IsConstJSON returns true if the given ScalarExpr is a ConstExpr that wraps a DJSON datum.

func (*CustomFuncs) IsConstValueEqual Uses

func (c *CustomFuncs) IsConstValueEqual(const1, const2 opt.ScalarExpr) bool

IsConstValueEqual returns whether const1 and const2 are equal.

func (*CustomFuncs) IsConstValueOrTuple Uses

func (c *CustomFuncs) IsConstValueOrTuple(input opt.ScalarExpr) bool

IsConstValueOrTuple returns true if the input is a constant or a tuple of constants.

func (*CustomFuncs) IsContradiction Uses

func (c *CustomFuncs) IsContradiction(item *memo.FiltersItem) bool

IsContradiction returns true if the given filter item contains a contradiction constraint.

func (*CustomFuncs) IsCorrelated Uses

func (c *CustomFuncs) IsCorrelated(src memo.RelExpr, cols opt.ColSet) bool

IsCorrelated returns true if any variable in the source expression references a column from the given set of output columns. For example:

(InnerJoin
  (Scan a)
  (Scan b)
  [ ... (FiltersItem $item:(Eq (Variable a.x) (Const 1))) ... ]
)

The $item expression is correlated with the (Scan a) expression because it references one of its columns. But the $item expression is not correlated with the (Scan b) expression.

func (*CustomFuncs) IsFilterFalse Uses

func (c *CustomFuncs) IsFilterFalse(filters memo.FiltersExpr) bool

IsFilterFalse returns true if the filters always evaluate to false. The only case that's checked is the fully normalized case, when the list contains a single False condition.

func (*CustomFuncs) IsGreaterThan Uses

func (c *CustomFuncs) IsGreaterThan(first, second tree.Datum) bool

IsGreaterThan returns true if the first datum compares as greater than the second.

func (*CustomFuncs) IsJSONScalar Uses

func (c *CustomFuncs) IsJSONScalar(value opt.ScalarExpr) bool

IsJSONScalar returns if the JSON value is a number, string, true, false, or null.

func (*CustomFuncs) IsLimited Uses

func (c *CustomFuncs) IsLimited(sub *memo.SubqueryPrivate) bool

IsLimited indicates whether a limit was pushed under the subquery already. See e.g. the rule IntroduceExistsLimit.

func (*CustomFuncs) IsListOfConstants Uses

func (c *CustomFuncs) IsListOfConstants(elems memo.ScalarListExpr) bool

IsListOfConstants returns true if elems is a list of constant values or tuples.

func (*CustomFuncs) IsPositiveInt Uses

func (c *CustomFuncs) IsPositiveInt(datum tree.Datum) bool

IsPositiveInt is true if the given Datum value is greater than zero.

func (*CustomFuncs) IsSameOrdering Uses

func (c *CustomFuncs) IsSameOrdering(first, other physical.OrderingChoice) bool

IsSameOrdering evaluates whether the two orderings are equal.

func (*CustomFuncs) IsStaticArray Uses

func (c *CustomFuncs) IsStaticArray(scalar opt.ScalarExpr) bool

IsStaticArray returns true if the expression is either a ConstExpr that wraps a DArray or an ArrayExpr. The complete set of expressions within a static array can be determined during planning:

ARRAY[1,2]
ARRAY[x,y]

By contrast, expressions within a dynamic array can only be determined at run-time:

SELECT (SELECT array_agg(x) FROM xy)

Here, the length of the array is only known at run-time.

func (*CustomFuncs) IsStaticTuple Uses

func (c *CustomFuncs) IsStaticTuple(expr opt.ScalarExpr) bool

IsStaticTuple returns true if the given ScalarExpr is either a TupleExpr or a ConstExpr wrapping a DTuple. Expressions within a static tuple can be determined during planning:

(1, 2)
(x, y)

By contrast, expressions within a dynamic tuple can only be determined at run-time:

SELECT (SELECT (x, y) FROM xy)

Here, if there are 0 rows in xy, the tuple value will be NULL. Or, if there is more than one row in xy, a dynamic error will be raised.

func (*CustomFuncs) IsString Uses

func (c *CustomFuncs) IsString(scalar opt.ScalarExpr) bool

IsString returns true if the given scalar expression is of type String.

func (*CustomFuncs) IsTimestamp Uses

func (c *CustomFuncs) IsTimestamp(scalar opt.ScalarExpr) bool

IsTimestamp returns true if the given scalar expression is of type Timestamp.

func (*CustomFuncs) IsTimestampTZ Uses

func (c *CustomFuncs) IsTimestampTZ(scalar opt.ScalarExpr) bool

IsTimestampTZ returns true if the given scalar expression is of type TimestampTZ.

func (*CustomFuncs) IsTupleOfVars Uses

func (c *CustomFuncs) IsTupleOfVars(tuple opt.ScalarExpr, cols opt.ColList) bool

IsTupleOfVars returns true if the given tuple contains Variables corresponding to the given columns (in the same order).

func (*CustomFuncs) IsUnorderedGrouping Uses

func (c *CustomFuncs) IsUnorderedGrouping(grouping *memo.GroupingPrivate) bool

IsUnorderedGrouping returns true if the given grouping ordering is not specified.

func (*CustomFuncs) IsUnsimplifiableOr Uses

func (c *CustomFuncs) IsUnsimplifiableOr(item *memo.FiltersItem) bool

IsUnsimplifiableOr returns true if this is an OR where neither side is NULL. SimplifyFilters simplifies ORs with a NULL on one side to its other side. However other ORs don't simplify. This function is used to prevent infinite recursion during ConstructFilterItem in SimplifyFilters. This function must be kept in sync with SimplifyFilters.

func (*CustomFuncs) IsZipCorrelated Uses

func (c *CustomFuncs) IsZipCorrelated(zip memo.ZipExpr, cols opt.ColSet) bool

IsZipCorrelated returns true if any element in the zip references any of the given columns.

func (*CustomFuncs) JoinDoesNotDuplicateLeftRows Uses

func (c *CustomFuncs) JoinDoesNotDuplicateLeftRows(join memo.RelExpr) bool

JoinDoesNotDuplicateLeftRows returns true if the given InnerJoin, LeftJoin or FullJoin is guaranteed not to output any given row from its left input more than once.

func (*CustomFuncs) JoinDoesNotDuplicateRightRows Uses

func (c *CustomFuncs) JoinDoesNotDuplicateRightRows(join memo.RelExpr) bool

JoinDoesNotDuplicateRightRows returns true if the given InnerJoin, LeftJoin or FullJoin is guaranteed not to output any given row from its right input more than once.

func (*CustomFuncs) JoinFiltersMatchAllLeftRows Uses

func (c *CustomFuncs) JoinFiltersMatchAllLeftRows(
    left, right memo.RelExpr, on memo.FiltersExpr,
) bool

JoinFiltersMatchAllLeftRows returns true when each row in the given join's left input matches at least one row from the right input, according to the join filters.

func (*CustomFuncs) JoinPreservesLeftRows Uses

func (c *CustomFuncs) JoinPreservesLeftRows(join memo.RelExpr) bool

JoinPreservesLeftRows returns true if the given InnerJoin, LeftJoin or FullJoin is guaranteed to output every row from its left input at least once.

func (*CustomFuncs) JoinPreservesRightRows Uses

func (c *CustomFuncs) JoinPreservesRightRows(join memo.RelExpr) bool

JoinPreservesRightRows returns true if the given InnerJoin, LeftJoin or FullJoin is guaranteed to output every row from its right input at least once.

func (*CustomFuncs) KeyCols Uses

func (c *CustomFuncs) KeyCols(in memo.RelExpr) opt.ColSet

KeyCols returns a column set consisting of the columns that make up the candidate key for the input expression (a key must be present).

func (*CustomFuncs) LimitGeMaxRows Uses

func (c *CustomFuncs) LimitGeMaxRows(limit tree.Datum, input memo.RelExpr) bool

LimitGeMaxRows returns true if the given constant limit value is greater than or equal to the max number of rows returned by the input expression.

func (*CustomFuncs) MakeAggCols Uses

func (c *CustomFuncs) MakeAggCols(aggOp opt.Operator, cols opt.ColSet) memo.AggregationsExpr

MakeAggCols constructs a new Aggregations operator containing an aggregate function of the given operator type for each of column in the given set. For example, for ConstAggOp and columns (1,2), this expression is returned:

(Aggregations
  [(ConstAgg (Variable 1)) (ConstAgg (Variable 2))]
  [1,2]
)

func (*CustomFuncs) MakeAggCols2 Uses

func (c *CustomFuncs) MakeAggCols2(
    aggOp opt.Operator, cols opt.ColSet, aggOp2 opt.Operator, cols2 opt.ColSet,
) memo.AggregationsExpr

MakeAggCols2 is similar to MakeAggCols, except that it allows two different sets of aggregate functions to be added to the resulting Aggregations operator, with one set appended to the other, like this:

(Aggregations
  [(ConstAgg (Variable 1)) (ConstAgg (Variable 2)) (FirstAgg (Variable 3))]
  [1,2,3]
)

func (*CustomFuncs) MakeArrayAggCol Uses

func (c *CustomFuncs) MakeArrayAggCol(typ *types.T) opt.ColumnID

MakeArrayAggCol returns a ColumnID with the given type and an "array_agg" label.

func (*CustomFuncs) MakeColsForUnnestJSON Uses

func (c *CustomFuncs) MakeColsForUnnestJSON(input memo.RelExpr, jsonCol opt.ColumnID) opt.ColList

MakeColsForUnnestJSON creates a new column for each key in the first row of the given ValuesExpr, and returns a ColList with those columns. The columns will be in the same order as the corresponding keys from the first row.

func (*CustomFuncs) MakeColsForUnnestTuples Uses

func (c *CustomFuncs) MakeColsForUnnestTuples(tupleColID opt.ColumnID) opt.ColList

MakeColsForUnnestTuples takes in the ColumnID of a tuple column and adds new columns to metadata corresponding to each field in the tuple. A ColList containing these new columns is returned.

func (*CustomFuncs) MakeEmptyColSet Uses

func (c *CustomFuncs) MakeEmptyColSet() opt.ColSet

MakeEmptyColSet returns a column set with no columns in it.

func (*CustomFuncs) MakeErrorOnDupGrouping Uses

func (c *CustomFuncs) MakeErrorOnDupGrouping(
    groupingCols opt.ColSet, ordering physical.OrderingChoice, errorText string,
) *memo.GroupingPrivate

MakeErrorOnDupGrouping constructs a new GroupingPrivate using the given grouping columns, OrderingChoice, and ErrorOnDup text. NullsAreDistinct will be false.

func (*CustomFuncs) MakeGrouping Uses

func (c *CustomFuncs) MakeGrouping(
    groupingCols opt.ColSet, ordering physical.OrderingChoice,
) *memo.GroupingPrivate

MakeGrouping constructs a new GroupingPrivate using the given grouping columns and OrderingChoice. ErrorOnDup will be empty and NullsAreDistinct will be false.

func (*CustomFuncs) MakeLimited Uses

func (c *CustomFuncs) MakeLimited(sub *memo.SubqueryPrivate) *memo.SubqueryPrivate

MakeLimited specifies that the subquery has a limit set already. This prevents e.g. the rule IntroduceExistsLimit from applying twice.

func (*CustomFuncs) MakeNullRejectFilters Uses

func (c *CustomFuncs) MakeNullRejectFilters(nullRejectCols opt.ColSet) memo.FiltersExpr

MakeNullRejectFilters returns a FiltersExpr with a "col IS NOT NULL" conjunct for each column in the given ColSet.

func (*CustomFuncs) MakeSegmentedOrdering Uses

func (c *CustomFuncs) MakeSegmentedOrdering(
    input memo.RelExpr,
    prefix opt.ColSet,
    ordering physical.OrderingChoice,
    limitOrdering physical.OrderingChoice,
) *physical.OrderingChoice

MakeSegmentedOrdering returns an ordering choice which satisfies both limitOrdering and the ordering required by a window function. Returns nil if no such ordering exists. See OrderingChoice.PrefixIntersection for more details.

func (*CustomFuncs) MakeSingleKeyJSONObject Uses

func (c *CustomFuncs) MakeSingleKeyJSONObject(key, value opt.ScalarExpr) opt.ScalarExpr

MakeSingleKeyJSONObject returns a JSON object with one entry, mapping key to value.

func (*CustomFuncs) MakeTimeZoneFunction Uses

func (c *CustomFuncs) MakeTimeZoneFunction(zone opt.ScalarExpr, ts opt.ScalarExpr) opt.ScalarExpr

MakeTimeZoneFunction constructs a new timezone() function with the given zone and timestamp as arguments. The type of the function result is TIMESTAMPTZ if ts is of type TIMESTAMP, or TIMESTAMP if is of type TIMESTAMPTZ.

func (*CustomFuncs) MakeUnorderedSubquery Uses

func (c *CustomFuncs) MakeUnorderedSubquery() *memo.SubqueryPrivate

MakeUnorderedSubquery returns a SubqueryPrivate that specifies no ordering.

func (*CustomFuncs) MapJoinOpEqualities Uses

func (c *CustomFuncs) MapJoinOpEqualities(
    filters memo.FiltersExpr, leftCols, rightCols opt.ColSet,
) memo.FiltersExpr

MapJoinOpEqualities maps all variable equality conditions in filters to use columns in either leftCols or rightCols where possible. See canMapJoinOpEquivalenceGroup and mapJoinOpEquivalenceGroup for more info.

func (*CustomFuncs) MapJoinOpFilter Uses

func (c *CustomFuncs) MapJoinOpFilter(
    src *memo.FiltersItem, dstCols opt.ColSet, equivFD props.FuncDepSet,
) opt.ScalarExpr

MapJoinOpFilter maps a boolean expression src, which is a conjunct in the given filters expression, to use the output columns of the relational expression dst.

MapJoinOpFilter assumes that CanMapJoinOpFilter has already returned true, and therefore a mapping is possible (see comment above CanMapJoinOpFilter for details).

For each column in src that is not also in dst, MapJoinOpFilter replaces it with an equivalent column in dst. If there are multiple equivalent columns in dst, it chooses one arbitrarily. MapJoinOpFilter does not replace any columns in subqueries, since we know there are no correlated subqueries (otherwise CanMapJoinOpFilter would have returned false).

For example, consider this query:

SELECT * FROM a INNER JOIN b ON a.x=b.x AND a.x + b.y = 5

If MapJoinOpFilter is called with src as a.x + b.y = 5 and dst as (Scan b), it returns b.x + b.y = 5. MapJoinOpFilter should not be called with the equality predicate a.x = b.x, because it would just return the tautology b.x = b.x.

func (*CustomFuncs) MapSetOpFilterLeft Uses

func (c *CustomFuncs) MapSetOpFilterLeft(
    filter *memo.FiltersItem, set *memo.SetPrivate,
) opt.ScalarExpr

MapSetOpFilterLeft maps the filter onto the left expression by replacing the out columns of the filter with the appropriate corresponding columns in the left side of the operator. Useful for pushing filters to relations the set operation is composed of.

func (*CustomFuncs) MapSetOpFilterRight Uses

func (c *CustomFuncs) MapSetOpFilterRight(
    filter *memo.FiltersItem, set *memo.SetPrivate,
) opt.ScalarExpr

MapSetOpFilterRight maps the filter onto the right expression by replacing the out columns of the filter with the appropriate corresponding columns in the right side of the operator. Useful for pushing filters to relations the set operation is composed of.

func (*CustomFuncs) MergeAggs Uses

func (c *CustomFuncs) MergeAggs(innerAggs, outerAggs memo.AggregationsExpr) memo.AggregationsExpr

MergeAggs returns an AggregationsExpr that is equivalent to the two given AggregationsExprs. MergeAggs will panic if CanMergeAggs is false.

func (*CustomFuncs) MergeProjectWithValues Uses

func (c *CustomFuncs) MergeProjectWithValues(
    projections memo.ProjectionsExpr, passthrough opt.ColSet, input memo.RelExpr,
) memo.RelExpr

MergeProjectWithValues merges a Project operator with its input Values operator. This is only possible in certain circumstances, which are described in the MergeProjectWithValues rule comment.

Values columns that are part of the Project passthrough columns are retained in the final Values operator, and Project synthesized columns are added to it. Any unreferenced Values columns are discarded. For example:

SELECT column1, 3 FROM (VALUES (1, 2))
=>
(VALUES (1, 3))

func (*CustomFuncs) MergeProjections Uses

func (c *CustomFuncs) MergeProjections(
    outer, inner memo.ProjectionsExpr, passthrough opt.ColSet,
) memo.ProjectionsExpr

MergeProjections concatenates the synthesized columns from the outer Projections operator, and the synthesized columns from the inner Projections operator that are passed through by the outer. Note that the outer synthesized columns must never contain references to the inner synthesized columns; this can be verified by first calling CanMergeProjections.

func (*CustomFuncs) MutationTable Uses

func (c *CustomFuncs) MutationTable(private *memo.MutationPrivate) opt.TableID

MutationTable returns the table upon which the mutation is applied. CHECK

func (*CustomFuncs) NeedSortedUniqueList Uses

func (c *CustomFuncs) NeedSortedUniqueList(list memo.ScalarListExpr) bool

NeedSortedUniqueList returns true if the given list is composed entirely of constant values that are either not in sorted order or have duplicates. If true, then ConstructSortedUniqueList needs to be called on the list to normalize it.

func (*CustomFuncs) NeededColMapLeft Uses

func (c *CustomFuncs) NeededColMapLeft(needed opt.ColSet, set *memo.SetPrivate) opt.ColSet

NeededColMapLeft returns the subset of a SetPrivate's LeftCols that corresponds to the needed subset of OutCols. This is useful for pruning columns in set operations.

func (*CustomFuncs) NeededColMapRight Uses

func (c *CustomFuncs) NeededColMapRight(needed opt.ColSet, set *memo.SetPrivate) opt.ColSet

NeededColMapRight returns the subset of a SetPrivate's RightCols that corresponds to the needed subset of OutCols. This is useful for pruning columns in set operations.

func (*CustomFuncs) NeededExplainCols Uses

func (c *CustomFuncs) NeededExplainCols(private *memo.ExplainPrivate) opt.ColSet

NeededExplainCols returns the columns needed by Explain's required physical properties.

func (*CustomFuncs) NeededGroupingCols Uses

func (c *CustomFuncs) NeededGroupingCols(private *memo.GroupingPrivate) opt.ColSet

NeededGroupingCols returns the columns needed by a grouping operator's grouping columns or requested ordering.

func (*CustomFuncs) NeededMutationCols Uses

func (c *CustomFuncs) NeededMutationCols(
    private *memo.MutationPrivate, checks memo.FKChecksExpr,
) opt.ColSet

NeededMutationCols returns the columns needed by a mutation operator. Note that this function makes no attempt to determine the minimal set of columns needed by the mutation private; it simply returns the input columns that are referenced by it. Other rules filter the FetchCols, CheckCols, etc. and can in turn trigger the PruneMutationInputCols rule.

func (*CustomFuncs) NeededMutationFetchCols Uses

func (c *CustomFuncs) NeededMutationFetchCols(
    op opt.Operator, private *memo.MutationPrivate,
) opt.ColSet

NeededMutationFetchCols returns the set of FetchCols needed by the given mutation operator. FetchCols are existing values that are fetched from the store and are then used to construct keys and values for update or delete KV operations.

func (*CustomFuncs) NeededOrdinalityCols Uses

func (c *CustomFuncs) NeededOrdinalityCols(private *memo.OrdinalityPrivate) opt.ColSet

NeededOrdinalityCols returns the columns needed by a Ordinality operator's requested ordering.

func (*CustomFuncs) NeededWindowCols Uses

func (c *CustomFuncs) NeededWindowCols(windows memo.WindowsExpr, p *memo.WindowPrivate) opt.ColSet

NeededWindowCols is the set of columns that the window function needs to execute.

func (*CustomFuncs) NegateComparison Uses

func (c *CustomFuncs) NegateComparison(
    cmp opt.Operator, left, right opt.ScalarExpr,
) opt.ScalarExpr

NegateComparison negates a comparison op like:

a.x = 5

to:

a.x <> 5

func (*CustomFuncs) NoJoinHints Uses

func (c *CustomFuncs) NoJoinHints(p *memo.JoinPrivate) bool

NoJoinHints returns true if no hints were specified for this join.

func (*CustomFuncs) NonKeyCols Uses

func (c *CustomFuncs) NonKeyCols(in memo.RelExpr) opt.ColSet

NonKeyCols returns a column set consisting of the output columns of the given input, minus the columns that make up its candidate key (which it must have).

func (*CustomFuncs) NormalizeTupleEquality Uses

func (c *CustomFuncs) NormalizeTupleEquality(left, right memo.ScalarListExpr) opt.ScalarExpr

NormalizeTupleEquality remaps the elements of two tuples compared for equality, like this:

(a, b, c) = (x, y, z)

into this:

(a = x) AND (b = y) AND (c = z)

func (*CustomFuncs) NotNullCols Uses

func (c *CustomFuncs) NotNullCols(input memo.RelExpr) opt.ColSet

NotNullCols returns the set of columns returned by the input expression that are guaranteed to never be NULL.

func (*CustomFuncs) NullRejectAggVar Uses

func (c *CustomFuncs) NullRejectAggVar(
    aggs memo.AggregationsExpr, nullRejectCols opt.ColSet,
) *memo.VariableExpr

NullRejectAggVar scans through the list of aggregate functions and returns the Variable input of the first aggregate that is not ConstAgg. Such an aggregate must exist, since this is only called if at least one eligible null-rejection column was identified by the deriveGroupByRejectNullCols method (see its comment for more details).

func (*CustomFuncs) NullRejectProjections Uses

func (c *CustomFuncs) NullRejectProjections(
    projections memo.ProjectionsExpr, nullRejectCols, inputNullRejectCols opt.ColSet,
) opt.ScalarExpr

NullRejectProjections returns a Variable for the first eligible input column of the first projection that is referenced by nullRejectCols. A column is only null-rejected if:

1. It is in the RejectNullCols ColSet of the input expression (null
   rejection has been requested)

2. A NULL in the column implies that the projection will also be NULL.

NullRejectProjections panics if no such projection is found.

func (*CustomFuncs) NullsAreDistinct Uses

func (c *CustomFuncs) NullsAreDistinct(private *memo.GroupingPrivate) bool

NullsAreDistinct returns true if a distinct operator with the given GroupingPrivate treats NULL values as not equal to one another (i.e. distinct). UpsertDistinctOp and EnsureUpsertDistinctOp treat NULL values as distinct, whereas DistinctOp does not.

func (*CustomFuncs) OpsAreSame Uses

func (c *CustomFuncs) OpsAreSame(left, right opt.Operator) bool

OpsAreSame returns true if the two operators are the same.

func (*CustomFuncs) OrderingCanProjectCols Uses

func (c *CustomFuncs) OrderingCanProjectCols(
    ordering physical.OrderingChoice, cols opt.ColSet,
) bool

OrderingCanProjectCols returns true if the given OrderingChoice can be expressed using only the given columns. Or in other words, at least one column from every ordering group is a member of the given ColSet.

func (*CustomFuncs) OrderingCols Uses

func (c *CustomFuncs) OrderingCols(ordering physical.OrderingChoice) opt.ColSet

OrderingCols returns all non-optional columns that are part of the given OrderingChoice.

func (*CustomFuncs) OrderingImplies Uses

func (c *CustomFuncs) OrderingImplies(first, second physical.OrderingChoice) bool

OrderingImplies returns true if the first OrderingChoice implies the second.

func (*CustomFuncs) OrderingIntersection Uses

func (c *CustomFuncs) OrderingIntersection(
    ordering1, ordering2 physical.OrderingChoice,
) physical.OrderingChoice

OrderingIntersection returns the intersection of two orderings. Should only be called if it is known that an intersection exists. See OrderingChoice.Intersection for more information.

func (*CustomFuncs) OrderingIntersects Uses

func (c *CustomFuncs) OrderingIntersects(ordering1, ordering2 physical.OrderingChoice) bool

OrderingIntersects returns true if <ordering1> and <ordering2> have an intersection. See OrderingChoice.Intersection for more information.

func (*CustomFuncs) OrderingSucceeded Uses

func (c *CustomFuncs) OrderingSucceeded(result *physical.OrderingChoice) bool

OrderingSucceeded returns true if an OrderingChoice is not nil.

func (*CustomFuncs) OrdinalityOrdering Uses

func (c *CustomFuncs) OrdinalityOrdering(private *memo.OrdinalityPrivate) physical.OrderingChoice

OrdinalityOrdering returns an ordinality operator's ordering choice.

func (*CustomFuncs) OuterCols Uses

func (c *CustomFuncs) OuterCols(e opt.Expr) opt.ColSet

OuterCols returns the set of outer columns associated with the given expression, whether it be a relational or scalar operator.

func (*CustomFuncs) OutputCols Uses

func (c *CustomFuncs) OutputCols(input memo.RelExpr) opt.ColSet

OutputCols returns the set of columns returned by the input expression.

func (*CustomFuncs) OutputCols2 Uses

func (c *CustomFuncs) OutputCols2(left, right memo.RelExpr) opt.ColSet

OutputCols2 returns the union of columns returned by the left and right expressions.

func (*CustomFuncs) PrimaryKeyCols Uses

func (c *CustomFuncs) PrimaryKeyCols(table opt.TableID) opt.ColSet

PrimaryKeyCols returns the key columns of the primary key of the table.

func (*CustomFuncs) ProjectColMapLeft Uses

func (c *CustomFuncs) ProjectColMapLeft(set *memo.SetPrivate) memo.ProjectionsExpr

ProjectColMapLeft returns a Projections operator that maps the left side columns in a SetPrivate to the output columns in it. Useful for replacing set operations with simpler constructs.

func (*CustomFuncs) ProjectColMapRight Uses

func (c *CustomFuncs) ProjectColMapRight(set *memo.SetPrivate) memo.ProjectionsExpr

ProjectColMapRight returns a Project operator that maps the right side columns in a SetPrivate to the output columns in it. Useful for replacing set operations with simpler constructs.

func (*CustomFuncs) ProjectExtraCol Uses

func (c *CustomFuncs) ProjectExtraCol(
    in memo.RelExpr, extra opt.ScalarExpr, extraID opt.ColumnID,
) memo.RelExpr

ProjectExtraCol constructs a new Project operator that passes through all columns in the given "in" expression, and then adds the given "extra" expression as an additional column.

func (*CustomFuncs) ProjectPassthroughLeft Uses

func (c *CustomFuncs) ProjectPassthroughLeft(set *memo.SetPrivate) opt.ColSet

ProjectPassthroughLeft returns a ColSet that contains the columns that can be passed-through from the left side in a SetPrivate when eliminating a set operation, like in EliminateUnionAllLeft. Columns in both the output ColList and the left ColList should be passed-through.

func (*CustomFuncs) ProjectPassthroughRight Uses

func (c *CustomFuncs) ProjectPassthroughRight(set *memo.SetPrivate) opt.ColSet

ProjectPassthroughRight returns a ColSet that contains the columns that can be passed-through from the right side in a SetPrivate when eliminating a set operation, like in EliminateUnionAllRight. Columns in both the output ColList and the right ColList should be passed-through.

func (*CustomFuncs) ProjectionCols Uses

func (c *CustomFuncs) ProjectionCols(projections memo.ProjectionsExpr) opt.ColSet

ProjectionCols returns the ids of the columns synthesized by the given Projections operator.

func (*CustomFuncs) ProjectionOuterCols Uses

func (c *CustomFuncs) ProjectionOuterCols(projections memo.ProjectionsExpr) opt.ColSet

ProjectionOuterCols returns the union of all outer columns from the given projection expressions.

func (*CustomFuncs) PruneAggCols Uses

func (c *CustomFuncs) PruneAggCols(
    target memo.AggregationsExpr, neededCols opt.ColSet,
) memo.AggregationsExpr

PruneAggCols creates a new AggregationsExpr that discards columns that are not referenced by the neededCols set.

func (*CustomFuncs) PruneCols Uses

func (c *CustomFuncs) PruneCols(target memo.RelExpr, neededCols opt.ColSet) memo.RelExpr

PruneCols creates an expression that discards any outputs columns of the target expression that are not used. If the target expression type supports column filtering (like Scan, Values, Projections, etc.), then create a new instance of that operator that does the filtering. Otherwise, construct a Project operator that wraps the operator and does the filtering. The new Project operator will be pushed down the tree until it merges with another operator that supports column filtering.

func (*CustomFuncs) PruneMutationFetchCols Uses

func (c *CustomFuncs) PruneMutationFetchCols(
    private *memo.MutationPrivate, neededCols opt.ColSet,
) *memo.MutationPrivate

PruneMutationFetchCols rewrites the given mutation private to no longer reference FetchCols that are not part of the neededCols set. The caller must have already done the analysis to prove that these columns are not needed, by calling CanPruneMutationFetchCols.

func (*CustomFuncs) PruneMutationReturnCols Uses

func (c *CustomFuncs) PruneMutationReturnCols(
    private *memo.MutationPrivate, needed opt.ColSet,
) *memo.MutationPrivate

PruneMutationReturnCols rewrites the given mutation private to no longer keep ReturnCols that are not referenced by the RETURNING clause or are not part of the primary key. The caller must have already done the analysis to prove that such columns exist, by calling CanPruneMutationReturnCols.

func (*CustomFuncs) PruneOrdering Uses

func (c *CustomFuncs) PruneOrdering(
    ordering physical.OrderingChoice, needed opt.ColSet,
) physical.OrderingChoice

PruneOrdering removes any columns referenced by an OrderingChoice that are not part of the needed column set. Should only be called if OrderingCanProjectCols is true.

func (*CustomFuncs) PruneOrderingGroupBy Uses

func (c *CustomFuncs) PruneOrderingGroupBy(
    private *memo.GroupingPrivate, neededCols opt.ColSet,
) *memo.GroupingPrivate

PruneOrderingGroupBy removes any columns referenced by the Ordering inside a GroupingPrivate which are not part of the neededCols set.

func (*CustomFuncs) PruneOrderingOrdinality Uses

func (c *CustomFuncs) PruneOrderingOrdinality(
    private *memo.OrdinalityPrivate, neededCols opt.ColSet,
) *memo.OrdinalityPrivate

PruneOrderingOrdinality removes any columns referenced by the Ordering inside a OrdinalityPrivate which are not part of the neededCols set.

func (*CustomFuncs) PruneSetPrivate Uses

func (c *CustomFuncs) PruneSetPrivate(needed opt.ColSet, set *memo.SetPrivate) *memo.SetPrivate

PruneSetPrivate returns a SetPrivate based on the given SetPrivate, but with unneeded input and output columns discarded.

func (*CustomFuncs) PruneWindows Uses

func (c *CustomFuncs) PruneWindows(needed opt.ColSet, windows memo.WindowsExpr) memo.WindowsExpr

PruneWindows restricts windows to only the columns which appear in needed. If we eliminate all the window functions, EliminateWindow will trigger and remove the expression entirely.

func (*CustomFuncs) PushColumnRemappingIntoValues Uses

func (c *CustomFuncs) PushColumnRemappingIntoValues(
    oldInput memo.RelExpr, oldProjections memo.ProjectionsExpr, oldPassthrough opt.ColSet,
) memo.RelExpr

PushColumnRemappingIntoValues folds ProjectionsItems into the passthrough set if all they do is remap output columns from the ValuesExpr input. The Values output columns are replaced by the corresponding columns from the folded ProjectionsItems.

Example: project

├── columns: x:2!null
├── values
│    ├── columns: column1:1!null
│    ├── cardinality: [2 - 2]
│    ├── (1,)
│    └── (2,)
└── projections
     └── column1:1 [as=x:2, outer=(1)]

=> project

├── columns: x:2!null
└── values
     ├── columns: x:2!null
     ├── cardinality: [2 - 2]
     ├── (1,)
     └── (2,)

This allows other rules to fire. In the above example, EliminateProject can now remove the Project altogether.

func (*CustomFuncs) RedundantCols Uses

func (c *CustomFuncs) RedundantCols(input memo.RelExpr, cols opt.ColSet) opt.ColSet

RedundantCols returns the subset of the given columns that are functionally determined by the remaining columns. In many contexts (such as if they are grouping columns), these columns can be dropped. The input expression's functional dependencies are used to make the decision.

func (*CustomFuncs) RejectNullCols Uses

func (c *CustomFuncs) RejectNullCols(in memo.RelExpr) opt.ColSet

RejectNullCols returns the set of columns that are candidates for NULL rejection filter pushdown. See the Relational.Rule.RejectNullCols comment for more details.

func (*CustomFuncs) RemapCols Uses

func (c *CustomFuncs) RemapCols(scalar opt.ScalarExpr, colMap opt.ColMap) opt.ScalarExpr

RemapCols remaps columns IDs in the input ScalarExpr by replacing occurrences of the keys of colMap with the corresponding values. If column IDs are encountered in the input ScalarExpr that are not keys in colMap, they are not remapped.

func (*CustomFuncs) RemoveFiltersItem Uses

func (c *CustomFuncs) RemoveFiltersItem(
    filters memo.FiltersExpr, search *memo.FiltersItem,
) memo.FiltersExpr

RemoveFiltersItem returns a new list that is a copy of the given list, except that it does not contain the given search item. If the list contains the item multiple times, then only the first instance is removed. If the list does not contain the item, then the method panics.

func (*CustomFuncs) RemoveGroupingCols Uses

func (c *CustomFuncs) RemoveGroupingCols(
    private *memo.GroupingPrivate, cols opt.ColSet,
) *memo.GroupingPrivate

RemoveGroupingCols returns a new grouping private struct with the given columns removed from the grouping column set.

func (*CustomFuncs) RemoveWindowPartitionCols Uses

func (c *CustomFuncs) RemoveWindowPartitionCols(
    private *memo.WindowPrivate, cols opt.ColSet,
) *memo.WindowPrivate

RemoveWindowPartitionCols returns a new window private struct with the given columns removed from the window partition column set.

func (*CustomFuncs) ReplaceAggregationsItem Uses

func (c *CustomFuncs) ReplaceAggregationsItem(
    aggs memo.AggregationsExpr, search *memo.AggregationsItem, replace opt.ScalarExpr,
) memo.AggregationsExpr

ReplaceAggregationsItem returns a new list that is a copy of the given list, except that the given search item has been replaced by the given replace item. If the list contains the search item multiple times, then only the first instance is replaced. If the list does not contain the item, then the method panics.

func (*CustomFuncs) ReplaceFiltersItem Uses

func (c *CustomFuncs) ReplaceFiltersItem(
    filters memo.FiltersExpr, search *memo.FiltersItem, replace opt.ScalarExpr,
) memo.FiltersExpr

ReplaceFiltersItem returns a new list that is a copy of the given list, except that the given search item has been replaced by the given replace item. If the list contains the search item multiple times, then only the first instance is replaced. If the list does not contain the item, then the method panics.

func (*CustomFuncs) SecondScalarListExpr Uses

func (c *CustomFuncs) SecondScalarListExpr(list memo.ScalarListExpr) opt.ScalarExpr

SecondScalarListExpr returns the second ScalarExpr in the given list.

func (*CustomFuncs) SimplifyCoalesce Uses

func (c *CustomFuncs) SimplifyCoalesce(args memo.ScalarListExpr) opt.ScalarExpr

SimplifyCoalesce discards any leading null operands, and then if the next operand is a constant, replaces with that constant.

func (*CustomFuncs) SimplifyExplainOrdering Uses

func (c *CustomFuncs) SimplifyExplainOrdering(
    in memo.RelExpr, private *memo.ExplainPrivate,
) *memo.ExplainPrivate

SimplifyExplainOrdering makes the ordering required by the Explain operator less restrictive by removing optional columns, adding equivalent columns, and removing redundant columns.

func (*CustomFuncs) SimplifyFilters Uses

func (c *CustomFuncs) SimplifyFilters(filters memo.FiltersExpr) memo.FiltersExpr

SimplifyFilters removes True operands from a FiltersExpr, and normalizes any False or Null condition to a single False condition. Null values map to False because FiltersExpr are only used by Select and Join, both of which treat a Null filter conjunct exactly as if it were false.

SimplifyFilters also "flattens" any And operator child by merging its conditions into a new FiltersExpr list. If, after simplification, no operands remain, then SimplifyFilters returns an empty FiltersExpr.

This method assumes that the NormalizeNestedAnds rule has already run and ensured a left deep And tree. If not (maybe because it's a testing scenario), then this rule may rematch, but it should still make forward progress).

func (*CustomFuncs) SimplifyGroupingOrdering Uses

func (c *CustomFuncs) SimplifyGroupingOrdering(
    in memo.RelExpr, private *memo.GroupingPrivate,
) *memo.GroupingPrivate

SimplifyGroupingOrdering makes the ordering required by the grouping operator less restrictive by removing optional columns, adding equivalent columns, and removing redundant columns.

func (*CustomFuncs) SimplifyLimitOffsetOrdering Uses

func (c *CustomFuncs) SimplifyLimitOffsetOrdering(
    input memo.RelExpr, ordering physical.OrderingChoice,
) physical.OrderingChoice

SimplifyLimitOffsetOrdering makes the ordering required by the Limit or Offset operator less restrictive by removing optional columns, adding equivalent columns, and removing redundant columns.

func (*CustomFuncs) SimplifyNotNullEquality Uses

func (c *CustomFuncs) SimplifyNotNullEquality(
    eq opt.ScalarExpr, testOp, constOp opt.Operator,
) opt.ScalarExpr

SimplifyNotNullEquality simplifies an expression of the following form:

(Is | IsNot (Eq) (True | False | Null))

in the case where the Eq expression is guaranteed to never result in null. The testOp argument must be IsOp or IsNotOp, and the constOp argument must be TrueOp, FalseOp, or NullOp.

func (*CustomFuncs) SimplifyOrdinalityOrdering Uses

func (c *CustomFuncs) SimplifyOrdinalityOrdering(
    in memo.RelExpr, private *memo.OrdinalityPrivate,
) *memo.OrdinalityPrivate

SimplifyOrdinalityOrdering makes the ordering required by the Ordinality operator less restrictive by removing optional columns, adding equivalent columns, and removing redundant columns.

func (*CustomFuncs) SimplifyWhens Uses

func (c *CustomFuncs) SimplifyWhens(
    condition opt.ScalarExpr, whens memo.ScalarListExpr, orElse opt.ScalarExpr,
) opt.ScalarExpr

SimplifyWhens removes known unreachable WHEN cases and constructs a new CASE statement. Any known true condition is converted to the ELSE. If only the ELSE remains, its expression is returned. condition must be a ConstValue.

func (*CustomFuncs) SimplifyWindowOrdering Uses

func (c *CustomFuncs) SimplifyWindowOrdering(
    in memo.RelExpr, private *memo.WindowPrivate,
) *memo.WindowPrivate

SimplifyWindowOrdering makes the intra-partition ordering used by the window function less restrictive.

func (*CustomFuncs) SingleColFromSet Uses

func (c *CustomFuncs) SingleColFromSet(s opt.ColSet) opt.ColumnID

SingleColFromSet returns the single column in s. Panics if s does not contain exactly one column.

func (*CustomFuncs) SortFilters Uses

func (c *CustomFuncs) SortFilters(f memo.FiltersExpr) memo.FiltersExpr

SortFilters sorts a filter list by the IDs of the expressions. This has the effect of canonicalizing FiltersExprs which may have the same filters, but in a different order.

func (*CustomFuncs) SubqueryCmp Uses

func (c *CustomFuncs) SubqueryCmp(sub *memo.SubqueryPrivate) opt.Operator

SubqueryCmp returns the comparison operation from a SubqueryPrivate.

func (*CustomFuncs) SubqueryOrdering Uses

func (c *CustomFuncs) SubqueryOrdering(sub *memo.SubqueryPrivate) physical.OrderingChoice

SubqueryOrdering returns the ordering property on a SubqueryPrivate.

func (*CustomFuncs) SubqueryRequestedCol Uses

func (c *CustomFuncs) SubqueryRequestedCol(sub *memo.SubqueryPrivate) opt.ColumnID

SubqueryRequestedCol returns the requested column from a SubqueryPrivate. This function should only be used with ArrayFlatten expressions.

func (*CustomFuncs) Succeeded Uses

func (c *CustomFuncs) Succeeded(result opt.Expr) bool

Succeeded returns true if a result expression is not nil.

func (*CustomFuncs) TranslateNonIgnoreAggs Uses

func (c *CustomFuncs) TranslateNonIgnoreAggs(
    newIn memo.RelExpr,
    newAggs memo.AggregationsExpr,
    oldIn memo.RelExpr,
    oldAggs memo.AggregationsExpr,
    canaryCol opt.ColumnID,
) memo.RelExpr

TranslateNonIgnoreAggs checks if any of the aggregates being decorrelated are unable to ignore nulls. If that is the case, it inserts projections which check a "canary" aggregation that determines if an expression actually had any things grouped into it or not.

func (*CustomFuncs) TypeOf Uses

func (c *CustomFuncs) TypeOf(e opt.ScalarExpr) *types.T

TypeOf returns the type of the expression.

func (*CustomFuncs) UnifyComparison Uses

func (c *CustomFuncs) UnifyComparison(left, right opt.ScalarExpr) opt.ScalarExpr

UnifyComparison attempts to convert a constant expression to the type of the variable expression, if that conversion can round-trip and is monotonic.

func (*CustomFuncs) UnionCols Uses

func (c *CustomFuncs) UnionCols(left, right opt.ColSet) opt.ColSet

UnionCols returns the union of the left and right column sets.

func (*CustomFuncs) UnionCols3 Uses

func (c *CustomFuncs) UnionCols3(cols1, cols2, cols3 opt.ColSet) opt.ColSet

UnionCols3 returns the union of the three column sets.

func (*CustomFuncs) UnionCols4 Uses

func (c *CustomFuncs) UnionCols4(cols1, cols2, cols3, cols4 opt.ColSet) opt.ColSet

UnionCols4 returns the union of the four column sets.

func (*CustomFuncs) UnnestJSONFromValues Uses

func (c *CustomFuncs) UnnestJSONFromValues(expr memo.RelExpr, newCols opt.ColList) memo.RelExpr

UnnestJSONFromValues takes in a Values operator that has a single column of JSON expressions and a ColList with columns corresponding to each JSON key in the first row of the ValuesExpr. It returns a new Values operator with the json fields expanded out into the Values rows.

func (*CustomFuncs) UnnestTuplesFromValues Uses

func (c *CustomFuncs) UnnestTuplesFromValues(
    expr memo.RelExpr, valuesCols opt.ColList,
) memo.RelExpr

UnnestTuplesFromValues takes in a Values operator that has a single column of tuples and a ColList corresponding to each tuple field. It returns a new Values operator with the tuple expanded out into the Values rows. For example, these rows:

((1, 2),)
((3, 4),)

would be unnested as:

(1, 2)
(3, 4)

func (*CustomFuncs) ValuesCols Uses

func (c *CustomFuncs) ValuesCols(valuesPrivate *memo.ValuesPrivate) opt.ColList

ValuesCols returns the Cols field of the ValuesPrivate struct.

func (*CustomFuncs) VarsAreSame Uses

func (c *CustomFuncs) VarsAreSame(left, right opt.ScalarExpr) bool

VarsAreSame returns true if the two variables are the same.

func (*CustomFuncs) WindowOrdering Uses

func (c *CustomFuncs) WindowOrdering(private *memo.WindowPrivate) physical.OrderingChoice

WindowOrdering returns the ordering used by the window function.

func (*CustomFuncs) WindowPartition Uses

func (c *CustomFuncs) WindowPartition(priv *memo.WindowPrivate) opt.ColSet

WindowPartition returns the set of columns that the window function uses to partition.

func (*CustomFuncs) WrapsJSONArray Uses

func (c *CustomFuncs) WrapsJSONArray(expr opt.ScalarExpr) bool

WrapsJSONArray returns true if the given ScalarExpr is a ConstExpr that wraps a DJSON datum that contains a JSON array.

func (*CustomFuncs) ZipOuterCols Uses

func (c *CustomFuncs) ZipOuterCols(zip memo.ZipExpr) opt.ColSet

ZipOuterCols returns the union of all outer columns from the given zip expressions.

type Factory Uses

type Factory struct {
    // contains filtered or unexported fields
}

Factory constructs a normalized expression tree within the memo. As each kind of expression is constructed by the factory, it transitively runs normalization transformations defined for that expression type. This may result in the construction of a different type of expression than what was requested. If, after normalization, the expression is already part of the memo, then construction is a no-op. Otherwise, a new memo group is created, with the normalized expression as its first and only expression.

Factory is largely auto-generated by optgen. The generated code can be found in factory.og.go. The factory.go file contains helper functions that are invoked by normalization patterns. While most patterns are specified in the Optgen DSL, the factory always calls the `onConstruct` method as its last step, in order to allow any custom manual code to execute.

func (*Factory) AssignPlaceholders Uses

func (f *Factory) AssignPlaceholders(from *memo.Memo) (err error)

AssignPlaceholders is used just before execution of a prepared Memo. It makes a copy of the given memo, but with any placeholder values replaced by their assigned values. This can trigger additional normalization rules that can substantially rewrite the tree. Once all placeholders are assigned, the exploration phase can begin.

func (*Factory) ConstructConstVal Uses

func (f *Factory) ConstructConstVal(d tree.Datum, t *types.T) opt.ScalarExpr

ConstructConstVal constructs one of the constant value operators from the given datum value. While most constants are represented with Const, there are special-case operators for True, False, and Null, to make matching easier. Null operators require the static type to be specified, so that rewrites do not change it.

func (*Factory) ConstructJoin Uses

func (f *Factory) ConstructJoin(
    joinOp opt.Operator, left, right memo.RelExpr, on memo.FiltersExpr, private *memo.JoinPrivate,
) memo.RelExpr

ConstructJoin constructs the join operator that corresponds to the given join operator type.

func (*Factory) ConstructZeroValues Uses

func (f *Factory) ConstructZeroValues() memo.RelExpr

ConstructZeroValues constructs a Values operator with zero rows and zero columns. It is used to create a dummy input for operators like CreateTable.

func (*Factory) CopyAndReplace Uses

func (f *Factory) CopyAndReplace(
    from memo.RelExpr, fromProps *physical.Required, replace ReplaceFunc,
)

CopyAndReplace builds this factory's memo by constructing a copy of a subtree that is part of another memo. That memo's metadata is copied to this factory's memo so that tables and columns referenced by the copied memo can keep the same ids. The copied subtree becomes the root of the destination memo, having the given physical properties.

The "replace" callback function allows the caller to override the default traversal and cloning behavior with custom logic. It is called for each node in the "from" subtree, and has the choice of constructing an arbitrary replacement node, or delegating to the default behavior by calling CopyAndReplaceDefault, which constructs a copy of the source operator using children returned by recursive calls to the replace callback. Note that if a non-leaf replacement node is constructed, its inputs must be copied using CopyAndReplaceDefault.

Sample usage:

var replaceFn ReplaceFunc
replaceFn = func(e opt.Expr) opt.Expr {
  if e.Op() == opt.PlaceholderOp {
    return f.ConstructConst(evalPlaceholder(e))
  }

  // Copy e, calling replaceFn on its inputs recursively.
  return f.CopyAndReplaceDefault(e, replaceFn)
}

f.CopyAndReplace(from, fromProps, replaceFn)

NOTE: Callers must take care to always create brand new copies of non- singleton source nodes rather than referencing existing nodes. The source memo should always be treated as immutable, and the destination memo must be completely independent of it once CopyAndReplace has completed.

func (*Factory) CustomFuncs Uses

func (f *Factory) CustomFuncs() *CustomFuncs

CustomFuncs returns the set of custom functions used by normalization rules.

func (*Factory) DetachMemo Uses

func (f *Factory) DetachMemo() *memo.Memo

DetachMemo extracts the memo from the optimizer, and then re-initializes the factory so that its reuse will not impact the detached memo. This method is used to extract a read-only memo during the PREPARE phase.

Before extracting the memo, DetachMemo first clears all column statistics in the memo. This is used to free up the potentially large amount of memory used by histograms. This does not affect the quality of the plan used at execution time, since the stats are just recalculated anyway when placeholders are assigned. If there are no placeholders, there is no need for column statistics, since the memo is already fully optimized.

func (*Factory) DisableOptimizations Uses

func (f *Factory) DisableOptimizations()

DisableOptimizations disables all transformation rules. The unaltered input expression tree becomes the output expression tree (because no transforms are applied).

func (*Factory) FoldingControl Uses

func (f *Factory) FoldingControl() *FoldingControl

FoldingControl returns the FoldingControl instance for this factory.

func (*Factory) Init Uses

func (f *Factory) Init(evalCtx *tree.EvalContext, catalog cat.Catalog)

Init initializes a Factory structure with a new, blank memo structure inside. This must be called before the factory can be used (or reused).

By default, a factory only constant-folds immutable operators; this can be changed using FoldingControl().AllowStableFolds().

func (*Factory) Memo Uses

func (f *Factory) Memo() *memo.Memo

Memo returns the memo structure that the factory is operating upon.

func (*Factory) Metadata Uses

func (f *Factory) Metadata() *opt.Metadata

Metadata returns the query-specific metadata, which includes information about the columns and tables used in this particular query.

func (*Factory) NormalizePartialIndexPredicate Uses

func (f *Factory) NormalizePartialIndexPredicate(pred memo.FiltersExpr) memo.FiltersExpr

NormalizePartialIndexPredicate performs specific normalization functions to normalize a partial index predicate. The goal is to mimic the normalizations performed on filters with Selects as closely as possible. If a partial index predicate and query filter are normalized differently, proving implication can be difficult or impossible.

func (*Factory) NotifyOnAppliedRule Uses

func (f *Factory) NotifyOnAppliedRule(appliedRule AppliedRuleFunc)

NotifyOnAppliedRule sets a callback function which is invoked each time a normalize rule has been applied by the factory. If appliedRule is nil, then no further notifications are sent.

func (*Factory) NotifyOnMatchedRule Uses

func (f *Factory) NotifyOnMatchedRule(matchedRule MatchedRuleFunc)

NotifyOnMatchedRule sets a callback function which is invoked each time a normalize rule has been matched by the factory. If matchedRule is nil, then no further notifications are sent, and all rules are applied by default. In addition, callers can invoke the DisableOptimizations convenience method to disable all rules.

type FoldingControl Uses

type FoldingControl struct {
    // contains filtered or unexported fields
}

FoldingControl is used to control whether normalization rules allow constant folding of VolatilityStable operators.

FoldingControl can be initialized in either "allow stable folds" or "disallow stable folds" state.

For a query with placeholders, we don't want to fold stable operators when building the reusable normalized expression; we want to fold them at AssignPlaceholder time.

For a query without placeholders, we build and optimize the expression allowing stable folds; we need to know if any stable folds occurred so we can prevent caching the resulting plan.

Examples illustrating the various cases:

1) Prepare and execute query with placeholders

   SELECT * FROM t WHERE time > now() - $1

   During prepare, we disable stable folds, so the now() call is not folded.
   At execution time, we enable stable folds before running
   AssignPlaceholders; when the expression is recreated, now() will be
   folded, along with the subtraction. If we have an index on time, we will
   use it.

2) Prepare and execute query without placeholders

   SELECT * FROM t WHERE time > now() - '1 minute'::INTERVAL

   During prepare, we disable stable folds. After building the expression,
   we check if we actually prevented any stable folds; in this case we did.
   Because of that, we don't fully optimize the memo at prepare time. At
   execution time we will take the same path as in example 1, running
   AssignPlaceholders with stable folds enabled. We don't have any
   placeholders here, but AssignPlaceholders will nevertheless recreate the
   expression, allowing folding to happen.

3) Execute query without placeholders

   SELECT * FROM t WHERE time > now() - '1 minute'::INTERVAL

   To execute a query that is not prepared in advance, we build the
   expression with stable folds enabled. Afterwards, we check if we actually
   had any stable folds, in which case we don't put the resulting plan in
   the plan cache. In the future, we may want to detect queries that are
   re-executed frequently and cache a non-folded version like in the prepare
   case.

func (*FoldingControl) AllowStableFolds Uses

func (fc *FoldingControl) AllowStableFolds()

AllowStableFolds initializes the FoldingControl in "allow stable folds" state.

func (*FoldingControl) DisallowStableFolds Uses

func (fc *FoldingControl) DisallowStableFolds()

DisallowStableFolds initializes the FoldingControl in "disallow stable folds" state.

func (*FoldingControl) PermittedStableFold Uses

func (fc *FoldingControl) PermittedStableFold() bool

PermittedStableFold returns true if we allowed a stable fold; can only be called if AllowStableFolds() was called.

Note that this does not guarantee that folding actually occurred - it is possible for folding to fail (e.g. due to the operator hitting an error).

func (*FoldingControl) PreventedStableFold Uses

func (fc *FoldingControl) PreventedStableFold() bool

PreventedStableFold returns true if we disallowed a stable fold; can only be called if DisallowStableFolds() was called.

func (*FoldingControl) TemporarilyDisallowStableFolds Uses

func (fc *FoldingControl) TemporarilyDisallowStableFolds(fn func())

TemporarilyDisallowStableFolds disallows stable folds, runs the given function, and restores the original FoldingControl state.

This is used when building expressions like computed column expressions and we want to be able to check whether the expression contains stable operators.

type MatchedRuleFunc Uses

type MatchedRuleFunc func(ruleName opt.RuleName) bool

MatchedRuleFunc defines the callback function for the NotifyOnMatchedRule event supported by the optimizer and factory. It is invoked each time an optimization rule (Normalize or Explore) has been matched. The name of the matched rule is passed as a parameter. If the function returns false, then the rule is not applied (i.e. skipped).

type ReplaceFunc Uses

type ReplaceFunc func(e opt.Expr) opt.Expr

ReplaceFunc is the callback function passed to the Factory.Replace method. It is called with each child of the expression passed to Replace. See the Replace method for more details.

Package norm imports 23 packages (graph) and is imported by 13 packages. Updated 2020-08-13. Refresh now. Tools for package owners.