Class RelBuilder

  • Direct Known Subclasses:
    FlinkRelBuilder

    @Enclosing
    public class RelBuilder
    extends Object
    Copied from calcite to workaround CALCITE-4668

    FLINK modifications are at lines

    1. Should be removed after fix of FLINK-29804: Lines 3000 ~ 3003
    • Field Detail

      • cluster

        protected final org.apache.calcite.plan.RelOptCluster cluster
      • relOptSchema

        protected final @Nullable org.apache.calcite.plan.RelOptSchema relOptSchema
    • Constructor Detail

      • RelBuilder

        protected RelBuilder​(@Nullable org.apache.calcite.plan.Context context,
                             org.apache.calcite.plan.RelOptCluster cluster,
                             @Nullable org.apache.calcite.plan.RelOptSchema relOptSchema)
    • Method Detail

      • create

        public static RelBuilder create​(org.apache.calcite.tools.FrameworkConfig config)
        Creates a RelBuilder.
      • let

        public <R> R let​(Function<RelBuilder,​R> consumer)
        Performs an action on this RelBuilder.

        For example, consider the following code:

           RelNode filterAndRename(RelBuilder relBuilder, RelNode rel,
               RexNode condition, List<String> fieldNames) {
             relBuilder.push(rel)
                 .filter(condition);
             if (fieldNames != null) {
               relBuilder.rename(fieldNames);
             }
             return relBuilder
                 .build();

        The pipeline is disrupted by the 'if'. The let method allows you to perform the flow as a single pipeline:

           RelNode filterAndRename(RelBuilder relBuilder, RelNode rel,
               RexNode condition, List<String> fieldNames) {
             return relBuilder.push(rel)
                 .filter(condition)
                 .let(r -> fieldNames == null ? r : r.rename(fieldNames))
                 .build();

        In pipelined cases such as this one, the lambda must return this RelBuilder. But let return values of other types.

      • toString

        public String toString()
        Converts this RelBuilder to a string. The string is the string representation of all of the RelNodes on the stack.
        Overrides:
        toString in class Object
      • getTypeFactory

        public org.apache.calcite.rel.type.RelDataTypeFactory getTypeFactory()
        Returns the type factory.
      • adoptConvention

        public RelBuilder adoptConvention​(org.apache.calcite.plan.Convention convention)
        Returns new RelBuilder that adopts the convention provided. RelNode will be created with such convention if corresponding factory is provided.
      • getRexBuilder

        public org.apache.calcite.rex.RexBuilder getRexBuilder()
        Returns the builder for RexNode expressions.
      • proto

        public static org.apache.calcite.tools.RelBuilderFactory proto​(org.apache.calcite.plan.Context context)
        Creates a RelBuilderFactory, a partially-created RelBuilder. Just add a RelOptCluster and a RelOptSchema
      • proto

        public static org.apache.calcite.tools.RelBuilderFactory proto​(Object... factories)
        Creates a RelBuilderFactory that uses a given set of factories.
      • getCluster

        public org.apache.calcite.plan.RelOptCluster getCluster()
      • getRelOptSchema

        public @Nullable org.apache.calcite.plan.RelOptSchema getRelOptSchema()
      • getScanFactory

        public org.apache.calcite.rel.core.RelFactories.TableScanFactory getScanFactory()
      • push

        public RelBuilder push​(org.apache.calcite.rel.RelNode node)
        Adds a relational expression to be the input to the next relational expression constructed.

        This method is usual when you want to weave in relational expressions that are not supported by the builder. If, while creating such expressions, you need to use previously built expressions as inputs, call build() to pop those inputs.

      • pushAll

        public RelBuilder pushAll​(Iterable<? extends org.apache.calcite.rel.RelNode> nodes)
        Pushes a collection of relational expressions.
      • size

        public int size()
        Returns the size of the stack.
      • build

        public org.apache.calcite.rel.RelNode build()
        Returns the final relational expression.

        Throws if the stack is empty.

      • peek

        public org.apache.calcite.rel.RelNode peek()
        Returns the relational expression at the top of the stack, but does not remove it.
      • peek

        public org.apache.calcite.rel.RelNode peek​(int n)
        Returns the relational expression n positions from the top of the stack, but does not remove it.
      • peek

        public org.apache.calcite.rel.RelNode peek​(int inputCount,
                                                   int inputOrdinal)
        Returns the relational expression n positions from the top of the stack, but does not remove it.
      • with

        public <E> E with​(org.apache.calcite.rel.RelNode r,
                          Function<RelBuilder,​E> fn)
        Evaluates an expression with a relational expression temporarily on the stack.
      • withSimplifier

        public <E> E withSimplifier​(BiFunction<RelBuilder,​org.apache.calcite.rex.RexSimplify,​org.apache.calcite.rex.RexSimplify> simplifierTransform,
                                    Function<RelBuilder,​E> fn)
        Performs an action with a temporary simplifier.
      • withPredicates

        public <E> E withPredicates​(org.apache.calcite.rel.metadata.RelMetadataQuery mq,
                                    Function<RelBuilder,​E> fn)
        Performs an action using predicates of the current node to simplify.
      • literal

        public org.apache.calcite.rex.RexLiteral literal​(@Nullable Object value)
        Creates a literal (constant expression).
      • variable

        public RelBuilder variable​(org.apache.calcite.util.Holder<org.apache.calcite.rex.RexCorrelVariable> v)
        Creates a correlation variable for the current input, and writes it into a Holder.
      • field

        public org.apache.calcite.rex.RexInputRef field​(String fieldName)
        Creates a reference to a field by name.

        Equivalent to field(1, 0, fieldName).

        Parameters:
        fieldName - Field name
      • field

        public org.apache.calcite.rex.RexInputRef field​(int inputCount,
                                                        int inputOrdinal,
                                                        String fieldName)
        Creates a reference to a field of given input relational expression by name.
        Parameters:
        inputCount - Number of inputs
        inputOrdinal - Input ordinal
        fieldName - Field name
      • field

        public org.apache.calcite.rex.RexInputRef field​(int fieldOrdinal)
        Creates a reference to an input field by ordinal.

        Equivalent to field(1, 0, ordinal).

        Parameters:
        fieldOrdinal - Field ordinal
      • field

        public org.apache.calcite.rex.RexInputRef field​(int inputCount,
                                                        int inputOrdinal,
                                                        int fieldOrdinal)
        Creates a reference to a field of a given input relational expression by ordinal.
        Parameters:
        inputCount - Number of inputs
        inputOrdinal - Input ordinal
        fieldOrdinal - Field ordinal within input
      • field

        public org.apache.calcite.rex.RexNode field​(String alias,
                                                    String fieldName)
        Creates a reference to a field of the current record which originated in a relation with a given alias.
      • field

        public org.apache.calcite.rex.RexNode field​(int inputCount,
                                                    String alias,
                                                    String fieldName)
        Creates a reference to a field which originated in a relation with the given alias. Searches for the relation starting at the top of the stack.
      • field

        public org.apache.calcite.rex.RexNode field​(org.apache.calcite.rex.RexNode e,
                                                    String name)
        Returns a reference to a given field of a record-valued expression.
      • fields

        public com.google.common.collect.ImmutableList<org.apache.calcite.rex.RexNode> fields()
        Returns references to the fields of the top input.
      • fields

        public com.google.common.collect.ImmutableList<org.apache.calcite.rex.RexNode> fields​(int inputCount,
                                                                                              int inputOrdinal)
        Returns references to the fields of a given input.
      • fields

        public com.google.common.collect.ImmutableList<org.apache.calcite.rex.RexNode> fields​(org.apache.calcite.rel.RelCollation collation)
        Returns references to fields for a given collation.
      • fields

        public com.google.common.collect.ImmutableList<org.apache.calcite.rex.RexNode> fields​(List<? extends Number> ordinals)
        Returns references to fields for a given list of input ordinals.
      • fields

        public com.google.common.collect.ImmutableList<org.apache.calcite.rex.RexNode> fields​(org.apache.calcite.util.ImmutableBitSet ordinals)
        Returns references to fields for a given bit set of input ordinals.
      • fields

        public com.google.common.collect.ImmutableList<org.apache.calcite.rex.RexNode> fields​(Iterable<String> fieldNames)
        Returns references to fields identified by name.
      • fields

        public com.google.common.collect.ImmutableList<org.apache.calcite.rex.RexNode> fields​(org.apache.calcite.util.mapping.Mappings.TargetMapping mapping)
        Returns references to fields identified by a mapping.
      • dot

        public org.apache.calcite.rex.RexNode dot​(org.apache.calcite.rex.RexNode node,
                                                  String fieldName)
        Creates an access to a field by name.
      • dot

        public org.apache.calcite.rex.RexNode dot​(org.apache.calcite.rex.RexNode node,
                                                  int fieldOrdinal)
        Creates an access to a field by ordinal.
      • call

        public org.apache.calcite.rex.RexNode call​(org.apache.calcite.sql.SqlOperator operator,
                                                   org.apache.calcite.rex.RexNode... operands)
        Creates a call to a scalar operator.
      • call

        public org.apache.calcite.rex.RexNode call​(org.apache.calcite.sql.SqlOperator operator,
                                                   Iterable<? extends org.apache.calcite.rex.RexNode> operands)
        Creates a call to a scalar operator.
      • in

        public org.apache.calcite.rex.RexNode in​(org.apache.calcite.rex.RexNode arg,
                                                 org.apache.calcite.rex.RexNode... ranges)
        Creates an IN predicate with a list of values.

        For example,

        
         b.scan("Emp")
             .filter(b.in(b.field("deptno"), b.literal(10), b.literal(20)))
         
        is equivalent to SQL
        
         SELECT *
         FROM Emp
         WHERE deptno IN (10, 20)
         
      • in

        public org.apache.calcite.rex.RexNode in​(org.apache.calcite.rex.RexNode arg,
                                                 Iterable<? extends org.apache.calcite.rex.RexNode> ranges)
        Creates an IN predicate with a list of values.

        For example,

        
         b.scan("Emps")
             .filter(
                 b.in(b.field("deptno"),
                     Arrays.asList(b.literal(10), b.literal(20))))
         

        is equivalent to the SQL

        
         SELECT *
         FROM Emps
         WHERE deptno IN (10, 20)
         
      • in

        public org.apache.calcite.rex.RexSubQuery in​(org.apache.calcite.rel.RelNode rel,
                                                     Iterable<? extends org.apache.calcite.rex.RexNode> nodes)
        Creates an IN predicate with a sub-query.
      • in

        public org.apache.calcite.rex.RexNode in​(org.apache.calcite.rex.RexNode arg,
                                                 Function<RelBuilder,​org.apache.calcite.rel.RelNode> f)
        Creates an IN predicate with a sub-query.

        For example,

        
         b.scan("Emps")
             .filter(
                 b.in(b.field("deptno"),
                     b2 -> b2.scan("Depts")
                         .filter(
                             b2.eq(b2.field("location"), b2.literal("Boston")))
                         .project(b.field("deptno"))
                         .build()))
         

        is equivalent to the SQL

        
         SELECT *
         FROM Emps
         WHERE deptno IN (SELECT deptno FROM Dept WHERE location = 'Boston')
         
      • some

        public org.apache.calcite.rex.RexSubQuery some​(org.apache.calcite.rex.RexNode node,
                                                       org.apache.calcite.sql.SqlOperator op,
                                                       Function<RelBuilder,​org.apache.calcite.rel.RelNode> f)
        Creates a SOME (or ANY) predicate.

        For example,

        
         b.scan("Emps")
             .filter(
                 b.some(b.field("commission"),
                     SqlStdOperatorTable.GREATER_THAN,
                     b2 -> b2.scan("Emps")
                         .filter(
                             b2.eq(b2.field("job"), b2.literal("Manager")))
                         .project(b2.field("sal"))
                         .build()))
         

        is equivalent to the SQL

        
         SELECT *
         FROM Emps
         WHERE commission > SOME (SELECT sal FROM Emps WHERE job = 'Manager')
         

        or (since SOME and ANY are synonyms) the SQL

        
         SELECT *
         FROM Emps
         WHERE commission > ANY (SELECT sal FROM Emps WHERE job = 'Manager')
         
      • all

        public org.apache.calcite.rex.RexNode all​(org.apache.calcite.rex.RexNode node,
                                                  org.apache.calcite.sql.SqlOperator op,
                                                  Function<RelBuilder,​org.apache.calcite.rel.RelNode> f)
        Creates an ALL predicate.

        For example,

        
         b.scan("Emps")
             .filter(
                 b.all(b.field("commission"),
                     SqlStdOperatorTable.GREATER_THAN,
                     b2 -> b2.scan("Emps")
                         .filter(
                             b2.eq(b2.field("job"), b2.literal("Manager")))
                         .project(b2.field("sal"))
                         .build()))
         

        is equivalent to the SQL

        
         SELECT *
         FROM Emps
         WHERE commission > ALL (SELECT sal FROM Emps WHERE job = 'Manager')
         

        Calcite translates ALL predicates to NOT SOME. The following SQL is equivalent to the previous:

        
         SELECT *
         FROM Emps
         WHERE NOT (commission <= SOME (SELECT sal FROM Emps WHERE job = 'Manager'))
         
      • exists

        public org.apache.calcite.rex.RexSubQuery exists​(Function<RelBuilder,​org.apache.calcite.rel.RelNode> f)
        Creates an EXISTS predicate.

        For example,

        
         b.scan("Depts")
             .filter(
                 b.exists(b2 ->
                     b2.scan("Emps")
                         .filter(
                             b2.eq(b2.field("job"), b2.literal("Manager")))
                         .build()))
         

        is equivalent to the SQL

        
         SELECT *
         FROM Depts
         WHERE EXISTS (SELECT 1 FROM Emps WHERE job = 'Manager')
         
      • unique

        public org.apache.calcite.rex.RexSubQuery unique​(Function<RelBuilder,​org.apache.calcite.rel.RelNode> f)
        Creates a UNIQUE predicate.

        For example,

        
         b.scan("Depts")
             .filter(
                 b.exists(b2 ->
                     b2.scan("Emps")
                         .filter(
                             b2.eq(b2.field("job"), b2.literal("Manager")))
                         .project(b2.field("deptno")
                         .build()))
         

        is equivalent to the SQL

        
         SELECT *
         FROM Depts
         WHERE UNIQUE (SELECT deptno FROM Emps WHERE job = 'Manager')
         
      • scalarQuery

        public org.apache.calcite.rex.RexSubQuery scalarQuery​(Function<RelBuilder,​org.apache.calcite.rel.RelNode> f)
        Creates a scalar sub-query.

        For example,

        
         b.scan("Depts")
             .project(
                 b.field("deptno")
                 b.scalarQuery(b2 ->
                     b2.scan("Emps")
                         .aggregate(
                             b2.eq(b2.field("job"), b2.literal("Manager")))
                         .build()))
         

        is equivalent to the SQL

        
         SELECT deptno, (SELECT MAX(sal) FROM Emps)
         FROM Depts
         
      • arrayQuery

        public org.apache.calcite.rex.RexSubQuery arrayQuery​(Function<RelBuilder,​org.apache.calcite.rel.RelNode> f)
        Creates an ARRAY sub-query.

        For example,

        
         b.scan("Depts")
             .project(
                 b.field("deptno")
                 b.arrayQuery(b2 ->
                     b2.scan("Emps")
                         .build()))
         

        is equivalent to the SQL

        
         SELECT deptno, ARRAY (SELECT * FROM Emps)
         FROM Depts
         
      • multisetQuery

        public org.apache.calcite.rex.RexSubQuery multisetQuery​(Function<RelBuilder,​org.apache.calcite.rel.RelNode> f)
        Creates a MULTISET sub-query.

        For example,

        
         b.scan("Depts")
             .project(
                 b.field("deptno")
                 b.multisetQuery(b2 ->
                     b2.scan("Emps")
                         .build()))
         

        is equivalent to the SQL

        
         SELECT deptno, MULTISET (SELECT * FROM Emps)
         FROM Depts
         
      • mapQuery

        public org.apache.calcite.rex.RexSubQuery mapQuery​(Function<RelBuilder,​org.apache.calcite.rel.RelNode> f)
        Creates a MAP sub-query.

        For example,

        
         b.scan("Depts")
             .project(
                 b.field("deptno")
                 b.multisetQuery(b2 ->
                     b2.scan("Emps")
                         .project(b2.field("empno"), b2.field("job"))
                         .build()))
         

        is equivalent to the SQL

        
         SELECT deptno, MAP (SELECT empno, job FROM Emps)
         FROM Depts
         
      • and

        public org.apache.calcite.rex.RexNode and​(org.apache.calcite.rex.RexNode... operands)
        Creates an AND.
      • and

        public org.apache.calcite.rex.RexNode and​(Iterable<? extends org.apache.calcite.rex.RexNode> operands)
        Creates an AND.

        Simplifies the expression a little: e AND TRUE becomes e; e AND e2 AND NOT e becomes e2.

      • or

        public org.apache.calcite.rex.RexNode or​(org.apache.calcite.rex.RexNode... operands)
        Creates an OR.
      • or

        public org.apache.calcite.rex.RexNode or​(Iterable<? extends org.apache.calcite.rex.RexNode> operands)
        Creates an OR.
      • not

        public org.apache.calcite.rex.RexNode not​(org.apache.calcite.rex.RexNode operand)
        Creates a NOT.
      • equals

        public org.apache.calcite.rex.RexNode equals​(org.apache.calcite.rex.RexNode operand0,
                                                     org.apache.calcite.rex.RexNode operand1)
        Creates an =.
      • greaterThan

        public org.apache.calcite.rex.RexNode greaterThan​(org.apache.calcite.rex.RexNode operand0,
                                                          org.apache.calcite.rex.RexNode operand1)
        Creates a >.
      • greaterThanOrEqual

        public org.apache.calcite.rex.RexNode greaterThanOrEqual​(org.apache.calcite.rex.RexNode operand0,
                                                                 org.apache.calcite.rex.RexNode operand1)
        Creates a >=.
      • lessThan

        public org.apache.calcite.rex.RexNode lessThan​(org.apache.calcite.rex.RexNode operand0,
                                                       org.apache.calcite.rex.RexNode operand1)
        Creates a <.
      • lessThanOrEqual

        public org.apache.calcite.rex.RexNode lessThanOrEqual​(org.apache.calcite.rex.RexNode operand0,
                                                              org.apache.calcite.rex.RexNode operand1)
        Creates a <=.
      • notEquals

        public org.apache.calcite.rex.RexNode notEquals​(org.apache.calcite.rex.RexNode operand0,
                                                        org.apache.calcite.rex.RexNode operand1)
        Creates a <>.
      • isNotDistinctFrom

        public org.apache.calcite.rex.RexNode isNotDistinctFrom​(org.apache.calcite.rex.RexNode operand0,
                                                                org.apache.calcite.rex.RexNode operand1)
        Creates an expression equivalent to "o0 IS NOT DISTINCT FROM o1". It is also equivalent to "o0 = o1 OR (o0 IS NULL AND o1 IS NULL)".
      • isDistinctFrom

        public org.apache.calcite.rex.RexNode isDistinctFrom​(org.apache.calcite.rex.RexNode operand0,
                                                             org.apache.calcite.rex.RexNode operand1)
        Creates an expression equivalent to o0 IS DISTINCT FROM o1. It is also equivalent to "NOT (o0 = o1 OR (o0 IS NULL AND o1 IS NULL)).
      • between

        public org.apache.calcite.rex.RexNode between​(org.apache.calcite.rex.RexNode arg,
                                                      org.apache.calcite.rex.RexNode lower,
                                                      org.apache.calcite.rex.RexNode upper)
        Creates a BETWEEN.
      • isNull

        public org.apache.calcite.rex.RexNode isNull​(org.apache.calcite.rex.RexNode operand)
        Creates ab IS NULL.
      • isNotNull

        public org.apache.calcite.rex.RexNode isNotNull​(org.apache.calcite.rex.RexNode operand)
        Creates an IS NOT NULL.
      • cast

        public org.apache.calcite.rex.RexNode cast​(org.apache.calcite.rex.RexNode expr,
                                                   org.apache.calcite.sql.type.SqlTypeName typeName)
        Creates an expression that casts an expression to a given type.
      • cast

        public org.apache.calcite.rex.RexNode cast​(org.apache.calcite.rex.RexNode expr,
                                                   org.apache.calcite.sql.type.SqlTypeName typeName,
                                                   int precision)
        Creates an expression that casts an expression to a type with a given name and precision or length.
      • cast

        public org.apache.calcite.rex.RexNode cast​(org.apache.calcite.rex.RexNode expr,
                                                   org.apache.calcite.sql.type.SqlTypeName typeName,
                                                   int precision,
                                                   int scale)
        Creates an expression that casts an expression to a type with a given name, precision and scale.
      • alias

        public org.apache.calcite.rex.RexNode alias​(org.apache.calcite.rex.RexNode expr,
                                                    String alias)
        Returns an expression wrapped in an alias.

        This method is idempotent: If the expression is already wrapped in the correct alias, does nothing; if wrapped in an incorrect alias, removes the incorrect alias and applies the correct alias.

        See Also:
        project(org.apache.calcite.rex.RexNode...)
      • desc

        public org.apache.calcite.rex.RexNode desc​(org.apache.calcite.rex.RexNode node)
        Converts a sort expression to descending.
      • nullsLast

        public org.apache.calcite.rex.RexNode nullsLast​(org.apache.calcite.rex.RexNode node)
        Converts a sort expression to nulls last.
      • nullsFirst

        public org.apache.calcite.rex.RexNode nullsFirst​(org.apache.calcite.rex.RexNode node)
        Converts a sort expression to nulls first.
      • groupKey

        public RelBuilder.GroupKey groupKey​(org.apache.calcite.rex.RexNode... nodes)
        Creates a group key.
      • groupKey

        public RelBuilder.GroupKey groupKey​(Iterable<? extends org.apache.calcite.rex.RexNode> nodes,
                                            Iterable<? extends Iterable<? extends org.apache.calcite.rex.RexNode>> nodeLists)
        Creates a group key with grouping sets.
      • groupKey

        public RelBuilder.GroupKey groupKey​(int... fieldOrdinals)
        Creates a group key of fields identified by ordinal.
      • groupKey

        public RelBuilder.GroupKey groupKey​(org.apache.calcite.util.ImmutableBitSet groupSet)
        Creates a group key, identified by field positions in the underlying relational expression.

        This method of creating a group key does not allow you to group on new expressions, only column projections, but is efficient, especially when you are coming from an existing Aggregate.

      • groupKey

        public RelBuilder.GroupKey groupKey​(org.apache.calcite.util.ImmutableBitSet groupSet,
                                            Iterable<? extends org.apache.calcite.util.ImmutableBitSet> groupSets)
        Creates a group key with grouping sets, both identified by field positions in the underlying relational expression.

        This method of creating a group key does not allow you to group on new expressions, only column projections, but is efficient, especially when you are coming from an existing Aggregate.

        It is possible for groupSet to be strict superset of all groupSets. For example, in the pseudo SQL

        
         GROUP BY 0, 1, 2
         GROUPING SETS ((0, 1), 0)
         

        column 2 does not appear in either grouping set. This is not valid SQL. We can approximate in actual SQL by adding an extra grouping set and filtering out using HAVING, as follows:

        
         GROUP BY GROUPING SETS ((0, 1, 2), (0, 1), 0)
         HAVING GROUPING_ID(0, 1, 2) <> 0
         
      • aggregateCall

        @Deprecated
        public RelBuilder.AggCall aggregateCall​(org.apache.calcite.sql.SqlAggFunction aggFunction,
                                                boolean distinct,
                                                org.apache.calcite.rex.RexNode filter,
                                                @Nullable String alias,
                                                org.apache.calcite.rex.RexNode... operands)
        Deprecated.
      • aggregateCall

        @Deprecated
        public RelBuilder.AggCall aggregateCall​(org.apache.calcite.sql.SqlAggFunction aggFunction,
                                                boolean distinct,
                                                boolean approximate,
                                                org.apache.calcite.rex.RexNode filter,
                                                @Nullable String alias,
                                                org.apache.calcite.rex.RexNode... operands)
        Deprecated.
      • aggregateCall

        @Deprecated
        public RelBuilder.AggCall aggregateCall​(org.apache.calcite.sql.SqlAggFunction aggFunction,
                                                boolean distinct,
                                                org.apache.calcite.rex.RexNode filter,
                                                @Nullable String alias,
                                                Iterable<? extends org.apache.calcite.rex.RexNode> operands)
        Deprecated.
      • aggregateCall

        @Deprecated
        public RelBuilder.AggCall aggregateCall​(org.apache.calcite.sql.SqlAggFunction aggFunction,
                                                boolean distinct,
                                                boolean approximate,
                                                org.apache.calcite.rex.RexNode filter,
                                                @Nullable String alias,
                                                Iterable<? extends org.apache.calcite.rex.RexNode> operands)
        Deprecated.
      • aggregateCall

        public RelBuilder.AggCall aggregateCall​(org.apache.calcite.rel.core.AggregateCall a)
        Creates a call to an aggregate function as a copy of an AggregateCall.
      • aggregateCall

        public RelBuilder.AggCall aggregateCall​(org.apache.calcite.rel.core.AggregateCall a,
                                                org.apache.calcite.util.mapping.Mapping mapping)
        Creates a call to an aggregate function as a copy of an AggregateCall, applying a mapping.
      • aggregateCall

        protected RelBuilder.AggCall aggregateCall​(org.apache.calcite.sql.SqlAggFunction aggFunction,
                                                   boolean distinct,
                                                   boolean approximate,
                                                   boolean ignoreNulls,
                                                   @Nullable org.apache.calcite.rex.RexNode filter,
                                                   @Nullable com.google.common.collect.ImmutableList<org.apache.calcite.rex.RexNode> distinctKeys,
                                                   com.google.common.collect.ImmutableList<org.apache.calcite.rex.RexNode> orderKeys,
                                                   @Nullable String alias,
                                                   com.google.common.collect.ImmutableList<org.apache.calcite.rex.RexNode> operands)
        Creates a call to an aggregate function with all applicable operands.
      • count

        public RelBuilder.AggCall count​(org.apache.calcite.rex.RexNode... operands)
        Creates a call to the COUNT aggregate function.
      • count

        public RelBuilder.AggCall count​(Iterable<? extends org.apache.calcite.rex.RexNode> operands)
        Creates a call to the COUNT aggregate function.
      • count

        public RelBuilder.AggCall count​(boolean distinct,
                                        @Nullable String alias,
                                        org.apache.calcite.rex.RexNode... operands)
        Creates a call to the COUNT aggregate function, optionally distinct and with an alias.
      • count

        public RelBuilder.AggCall count​(boolean distinct,
                                        @Nullable String alias,
                                        Iterable<? extends org.apache.calcite.rex.RexNode> operands)
        Creates a call to the COUNT aggregate function, optionally distinct and with an alias.
      • countStar

        public RelBuilder.AggCall countStar​(@Nullable String alias)
        Creates a call to the COUNT(*) aggregate function.
      • sum

        public RelBuilder.AggCall sum​(org.apache.calcite.rex.RexNode operand)
        Creates a call to the SUM aggregate function.
      • sum

        public RelBuilder.AggCall sum​(boolean distinct,
                                      @Nullable String alias,
                                      org.apache.calcite.rex.RexNode operand)
        Creates a call to the SUM aggregate function, optionally distinct and with an alias.
      • avg

        public RelBuilder.AggCall avg​(org.apache.calcite.rex.RexNode operand)
        Creates a call to the AVG aggregate function.
      • avg

        public RelBuilder.AggCall avg​(boolean distinct,
                                      @Nullable String alias,
                                      org.apache.calcite.rex.RexNode operand)
        Creates a call to the AVG aggregate function, optionally distinct and with an alias.
      • min

        public RelBuilder.AggCall min​(org.apache.calcite.rex.RexNode operand)
        Creates a call to the MIN aggregate function.
      • min

        public RelBuilder.AggCall min​(@Nullable String alias,
                                      org.apache.calcite.rex.RexNode operand)
        Creates a call to the MIN aggregate function, optionally with an alias.
      • max

        public RelBuilder.AggCall max​(org.apache.calcite.rex.RexNode operand)
        Creates a call to the MAX aggregate function, optionally with an alias.
      • max

        public RelBuilder.AggCall max​(@Nullable String alias,
                                      org.apache.calcite.rex.RexNode operand)
        Creates a call to the MAX aggregate function.
      • patternField

        public org.apache.calcite.rex.RexNode patternField​(String alpha,
                                                           org.apache.calcite.rel.type.RelDataType type,
                                                           int i)
        Creates a reference to a given field of the pattern.
        Parameters:
        alpha - the pattern name
        type - Type of field
        i - Ordinal of field
        Returns:
        Reference to field of pattern
      • scan

        public RelBuilder scan​(Iterable<String> tableNames)
        Creates a TableScan of the table with a given name.

        Throws if the table does not exist.

        Returns this builder.

        Parameters:
        tableNames - Name of table (can optionally be qualified)
      • scan

        public RelBuilder scan​(String... tableNames)
        Creates a TableScan of the table with a given name.

        Throws if the table does not exist.

        Returns this builder.

        Parameters:
        tableNames - Name of table (can optionally be qualified)
      • snapshot

        public RelBuilder snapshot​(org.apache.calcite.rex.RexNode period)
        Creates a Snapshot of a given snapshot period.

        Returns this builder.

        Parameters:
        period - Name of table (can optionally be qualified)
      • cursor

        public org.apache.calcite.rex.RexNode cursor​(int inputCount,
                                                     int ordinal)
        Creates a RexCall to the CURSOR function by ordinal.
        Parameters:
        inputCount - Number of inputs
        ordinal - The reference to the relational input
        Returns:
        RexCall to CURSOR function
      • functionScan

        public RelBuilder functionScan​(org.apache.calcite.sql.SqlOperator operator,
                                       int inputCount,
                                       org.apache.calcite.rex.RexNode... operands)
        Creates a TableFunctionScan.
      • functionScan

        public RelBuilder functionScan​(org.apache.calcite.sql.SqlOperator operator,
                                       int inputCount,
                                       Iterable<? extends org.apache.calcite.rex.RexNode> operands)
        Creates a TableFunctionScan.
      • filter

        public RelBuilder filter​(org.apache.calcite.rex.RexNode... predicates)
        Creates a Filter of an array of predicates.

        The predicates are combined using AND, and optimized in a similar way to the and(org.apache.calcite.rex.RexNode...) method. If the result is TRUE no filter is created.

      • filter

        public RelBuilder filter​(Iterable<? extends org.apache.calcite.rex.RexNode> predicates)
        Creates a Filter of a list of predicates.

        The predicates are combined using AND, and optimized in a similar way to the and(org.apache.calcite.rex.RexNode...) method. If the result is TRUE no filter is created.

      • filter

        public RelBuilder filter​(Iterable<org.apache.calcite.rel.core.CorrelationId> variablesSet,
                                 org.apache.calcite.rex.RexNode... predicates)
        Creates a Filter of a list of correlation variables and an array of predicates.

        The predicates are combined using AND, and optimized in a similar way to the and(org.apache.calcite.rex.RexNode...) method. If the result is TRUE no filter is created.

      • filter

        public RelBuilder filter​(Iterable<org.apache.calcite.rel.core.CorrelationId> variablesSet,
                                 Iterable<? extends org.apache.calcite.rex.RexNode> predicates)
        Creates a Filter of a list of correlation variables and a list of predicates.

        The predicates are combined using AND, and optimized in a similar way to the and(org.apache.calcite.rex.RexNode...) method. If simplification is on and the result is TRUE, no filter is created.

      • project

        public RelBuilder project​(org.apache.calcite.rex.RexNode... nodes)
        Creates a Project of the given expressions.
      • project

        public RelBuilder project​(Iterable<? extends org.apache.calcite.rex.RexNode> nodes)
        Creates a Project of the given list of expressions.

        Infers names as would project(Iterable, Iterable) if all suggested names were null.

        Parameters:
        nodes - Expressions
      • project

        public RelBuilder project​(Iterable<? extends org.apache.calcite.rex.RexNode> nodes,
                                  Iterable<? extends @Nullable String> fieldNames)
        Creates a Project of the given list of expressions and field names.
        Parameters:
        nodes - Expressions
        fieldNames - field names for expressions
      • project

        public RelBuilder project​(Iterable<? extends org.apache.calcite.rex.RexNode> nodes,
                                  Iterable<? extends @Nullable String> fieldNames,
                                  boolean force)
        Creates a Project of the given list of expressions, using the given names.

        Names are deduced as follows:

        • If the length of fieldNames is greater than the index of the current entry in nodes, and the entry in fieldNames is not null, uses it; otherwise
        • If an expression projects an input field, or is a cast an input field, uses the input field name; otherwise
        • If an expression is a call to SqlStdOperatorTable.AS (see alias(org.apache.calcite.rex.RexNode, java.lang.String)), removes the call but uses the intended alias.

        After the field names have been inferred, makes the field names unique by appending numeric suffixes.

        Parameters:
        nodes - Expressions
        fieldNames - Suggested field names
        force - create project even if it is identity
      • project

        public RelBuilder project​(Iterable<? extends org.apache.calcite.rex.RexNode> nodes,
                                  Iterable<? extends @Nullable String> fieldNames,
                                  boolean force,
                                  Iterable<org.apache.calcite.rel.core.CorrelationId> variablesSet)
        The same with project(Iterable, Iterable, boolean), with additional variablesSet param.
        Parameters:
        nodes - Expressions
        fieldNames - Suggested field names
        force - create project even if it is identity
        variablesSet - Correlating variables that are set when reading a row from the input, and which may be referenced from the projection expressions
      • projectPlus

        public RelBuilder projectPlus​(org.apache.calcite.rex.RexNode... nodes)
        Creates a Project of all original fields, plus the given expressions.
      • projectPlus

        public RelBuilder projectPlus​(Iterable<? extends org.apache.calcite.rex.RexNode> nodes)
        Creates a Project of all original fields, plus the given list of expressions.
      • projectExcept

        public RelBuilder projectExcept​(org.apache.calcite.rex.RexNode... expressions)
        Creates a Project of all original fields, except the given expressions.
        Throws:
        IllegalArgumentException - if the given expressions contain duplicates or there is an expression that does not match an existing field
      • projectExcept

        public RelBuilder projectExcept​(Iterable<org.apache.calcite.rex.RexNode> expressions)
        Creates a Project of all original fields, except the given list of expressions.
        Throws:
        IllegalArgumentException - if the given expressions contain duplicates or there is an expression that does not match an existing field
      • projectNamed

        public RelBuilder projectNamed​(Iterable<? extends org.apache.calcite.rex.RexNode> nodes,
                                       @Nullable Iterable<? extends @Nullable String> fieldNames,
                                       boolean force)
        Creates a Project of the given expressions and field names, and optionally optimizing.

        If fieldNames is null, or if a particular entry in fieldNames is null, derives field names from the input expressions.

        If force is false, and the input is a Project, and the expressions make the trivial projection ($0, $1, ...), modifies the input.

        Parameters:
        nodes - Expressions
        fieldNames - Suggested field names, or null to generate
        force - Whether to create a renaming Project if the projections are trivial
      • projectNamed

        public RelBuilder projectNamed​(Iterable<? extends org.apache.calcite.rex.RexNode> nodes,
                                       @Nullable Iterable<? extends @Nullable String> fieldNames,
                                       boolean force,
                                       Iterable<org.apache.calcite.rel.core.CorrelationId> variablesSet)
        Creates a Project of the given expressions and field names, and optionally optimizing.

        If fieldNames is null, or if a particular entry in fieldNames is null, derives field names from the input expressions.

        If force is false, and the input is a Project, and the expressions make the trivial projection ($0, $1, ...), modifies the input.

        Parameters:
        nodes - Expressions
        fieldNames - Suggested field names, or null to generate
        force - Whether to create a renaming Project if the projections are trivial
        variablesSet - Correlating variables that are set when reading a row from the input, and which may be referenced from the projection expressions
      • uncollect

        public RelBuilder uncollect​(List<String> itemAliases,
                                    boolean withOrdinality)
        Creates an Uncollect with given item aliases.
        Parameters:
        itemAliases - Operand item aliases, never null
        withOrdinality - If withOrdinality, the output contains an extra ORDINALITY column
      • rename

        public RelBuilder rename​(List<? extends @Nullable String> fieldNames)
        Ensures that the field names match those given.

        If all fields have the same name, adds nothing; if any fields do not have the same name, adds a Project.

        Note that the names can be short-lived. Other RelBuilder operations make no guarantees about the field names of the rows they produce.

        Parameters:
        fieldNames - List of desired field names; may contain null values or have fewer fields than the current row type
      • distinct

        public RelBuilder distinct()
        Creates an Aggregate that makes the relational expression distinct on all fields.
      • aggregate

        public RelBuilder aggregate​(RelBuilder.GroupKey groupKey,
                                    List<org.apache.calcite.rel.core.AggregateCall> aggregateCalls)
        Creates an Aggregate with an array of AggregateCalls.
      • union

        public RelBuilder union​(boolean all)
        Creates a Union of the two most recent relational expressions on the stack.
        Parameters:
        all - Whether to create UNION ALL
      • union

        public RelBuilder union​(boolean all,
                                int n)
        Creates a Union of the n most recent relational expressions on the stack.
        Parameters:
        all - Whether to create UNION ALL
        n - Number of inputs to the UNION operator
      • intersect

        public RelBuilder intersect​(boolean all)
        Creates an Intersect of the two most recent relational expressions on the stack.
        Parameters:
        all - Whether to create INTERSECT ALL
      • intersect

        public RelBuilder intersect​(boolean all,
                                    int n)
        Creates an Intersect of the n most recent relational expressions on the stack.
        Parameters:
        all - Whether to create INTERSECT ALL
        n - Number of inputs to the INTERSECT operator
      • minus

        public RelBuilder minus​(boolean all)
        Creates a Minus of the two most recent relational expressions on the stack.
        Parameters:
        all - Whether to create EXCEPT ALL
      • minus

        public RelBuilder minus​(boolean all,
                                int n)
        Creates a Minus of the n most recent relational expressions on the stack.
        Parameters:
        all - Whether to create EXCEPT ALL
      • transientScan

        public RelBuilder transientScan​(String tableName)
        Creates a TableScan on a TransientTable with the given name, using as type the top of the stack's type.
        Parameters:
        tableName - table name
      • transientScan

        public RelBuilder transientScan​(String tableName,
                                        org.apache.calcite.rel.type.RelDataType rowType)
        Creates a TableScan on a TransientTable with the given name and type.
        Parameters:
        tableName - table name
        rowType - row type of the table
      • repeatUnion

        public RelBuilder repeatUnion​(String tableName,
                                      boolean all)
        Creates a RepeatUnion associated to a TransientTable without a maximum number of iterations, i.e. repeatUnion(tableName, all, -1).
        Parameters:
        tableName - name of the TransientTable associated to the RepeatUnion
        all - whether duplicates will be considered or not
      • repeatUnion

        public RelBuilder repeatUnion​(String tableName,
                                      boolean all,
                                      int iterationLimit)
        Creates a RepeatUnion associated to a TransientTable of the two most recent relational expressions on the stack.

        Warning: if these relational expressions are not correctly defined, this operation might lead to an infinite loop.

        The generated RepeatUnion operates as follows:

        • Evaluate its left term once, propagating the results into the TransientTable;
        • Evaluate its right term (which may contain a TableScan on the TransientTable) over and over until it produces no more results (or until an optional maximum number of iterations is reached). On each iteration, the results are propagated into the TransientTable, overwriting the results from the previous one.
        Parameters:
        tableName - Name of the TransientTable associated to the RepeatUnion
        all - Whether duplicates are considered
        iterationLimit - Maximum number of iterations; negative value means no limit
      • join

        public RelBuilder join​(org.apache.calcite.rel.core.JoinRelType joinType,
                               org.apache.calcite.rex.RexNode condition0,
                               org.apache.calcite.rex.RexNode... conditions)
        Creates a Join with an array of conditions.
      • join

        public RelBuilder join​(org.apache.calcite.rel.core.JoinRelType joinType,
                               Iterable<? extends org.apache.calcite.rex.RexNode> conditions)
        Creates a Join with multiple conditions.
      • join

        public RelBuilder join​(org.apache.calcite.rel.core.JoinRelType joinType,
                               org.apache.calcite.rex.RexNode condition)
        Creates a Join with one condition.
      • join

        public RelBuilder join​(org.apache.calcite.rel.core.JoinRelType joinType,
                               org.apache.calcite.rex.RexNode condition,
                               Set<org.apache.calcite.rel.core.CorrelationId> variablesSet)
        Creates a Join with correlating variables.
      • correlate

        public RelBuilder correlate​(org.apache.calcite.rel.core.JoinRelType joinType,
                                    org.apache.calcite.rel.core.CorrelationId correlationId,
                                    org.apache.calcite.rex.RexNode... requiredFields)
        Creates a Correlate with a CorrelationId and an array of fields that are used by correlation.
      • correlate

        public RelBuilder correlate​(org.apache.calcite.rel.core.JoinRelType joinType,
                                    org.apache.calcite.rel.core.CorrelationId correlationId,
                                    Iterable<? extends org.apache.calcite.rex.RexNode> requiredFields)
        Creates a Correlate with a CorrelationId and a list of fields that are used by correlation.
      • join

        public RelBuilder join​(org.apache.calcite.rel.core.JoinRelType joinType,
                               String... fieldNames)
        Creates a Join using USING syntax.

        For each of the field names, both left and right inputs must have a field of that name. Constructs a join condition that the left and right fields are equal.

        Parameters:
        joinType - Join type
        fieldNames - Field names
      • semiJoin

        public RelBuilder semiJoin​(Iterable<? extends org.apache.calcite.rex.RexNode> conditions)
        Creates a Join with JoinRelType.SEMI.

        A semi-join is a form of join that combines two relational expressions according to some condition, and outputs only rows from the left input for which at least one row from the right input matches. It only outputs columns from the left input, and ignores duplicates on the right.

        For example, EMP semi-join DEPT finds all EMP records that do not have a corresponding DEPT record, similar to the following SQL:

         SELECT * FROM EMP
         WHERE EXISTS (SELECT 1 FROM DEPT
             WHERE DEPT.DEPTNO = EMP.DEPTNO)
      • semiJoin

        public RelBuilder semiJoin​(org.apache.calcite.rex.RexNode... conditions)
        Creates a Join with JoinRelType.SEMI.
        See Also:
        semiJoin(Iterable)
      • antiJoin

        public RelBuilder antiJoin​(Iterable<? extends org.apache.calcite.rex.RexNode> conditions)
        Creates an anti-join.

        An anti-join is a form of join that combines two relational expressions according to some condition, but outputs only rows from the left input for which no rows from the right input match.

        For example, EMP anti-join DEPT finds all EMP records that do not have a corresponding DEPT record, similar to the following SQL:

         SELECT * FROM EMP
         WHERE NOT EXISTS (SELECT 1 FROM DEPT
             WHERE DEPT.DEPTNO = EMP.DEPTNO)
      • antiJoin

        public RelBuilder antiJoin​(org.apache.calcite.rex.RexNode... conditions)
        Creates an anti-join.
        See Also:
        antiJoin(Iterable)
      • as

        public RelBuilder as​(String alias)
        Assigns a table alias to the top entry on the stack.
      • values

        public RelBuilder values​(@Nullable String[] fieldNames,
                                 @Nullable Object... values)
        Creates a Values.

        The values array must have the same number of entries as fieldNames, or an integer multiple if you wish to create multiple rows.

        If there are zero rows, or if all values of a any column are null, this method cannot deduce the type of columns. For these cases, call values(Iterable, RelDataType).

        Parameters:
        fieldNames - Field names
        values - Values
      • empty

        public RelBuilder empty()
        Creates a relational expression that reads from an input and throws all of the rows away.

        Note that this method always pops one relational expression from the stack. values, in contrast, does not pop any relational expressions, and always produces a leaf.

        The default implementation creates a Values with the same specified row type and aliases as the input, and ignores the input entirely. But schema-on-query systems such as Drill might override this method to create a relation expression that retains the input, just to read its schema.

      • values

        public RelBuilder values​(org.apache.calcite.rel.type.RelDataType rowType,
                                 Object... columnValues)
        Creates a Values with a specified row type.

        This method can handle cases that values(String[], Object...) cannot, such as all values of a column being null, or there being zero rows.

        Parameters:
        rowType - Row type
        columnValues - Values
      • values

        public RelBuilder values​(Iterable<? extends List<org.apache.calcite.rex.RexLiteral>> tupleList,
                                 org.apache.calcite.rel.type.RelDataType rowType)
        Creates a Values with a specified row type.

        This method can handle cases that values(String[], Object...) cannot, such as all values of a column being null, or there being zero rows.

        Parameters:
        tupleList - Tuple list
        rowType - Row type
      • values

        public RelBuilder values​(org.apache.calcite.rel.type.RelDataType rowType)
        Creates a Values with a specified row type and zero rows.
        Parameters:
        rowType - Row type
      • limit

        public RelBuilder limit​(int offset,
                                int fetch)
        Creates a limit without a sort.
      • exchange

        public RelBuilder exchange​(org.apache.calcite.rel.RelDistribution distribution)
        Creates an Exchange by distribution.
      • sortExchange

        public RelBuilder sortExchange​(org.apache.calcite.rel.RelDistribution distribution,
                                       org.apache.calcite.rel.RelCollation collation)
        Creates a SortExchange by distribution and collation.
      • sort

        public RelBuilder sort​(int... fields)
        Creates a Sort by field ordinals.

        Negative fields mean descending: -1 means field(0) descending, -2 means field(1) descending, etc.

      • sort

        public RelBuilder sort​(org.apache.calcite.rex.RexNode... nodes)
        Creates a Sort by expressions.
      • sort

        public RelBuilder sort​(Iterable<? extends org.apache.calcite.rex.RexNode> nodes)
        Creates a Sort by expressions.
      • sortLimit

        public RelBuilder sortLimit​(int offset,
                                    int fetch,
                                    org.apache.calcite.rex.RexNode... nodes)
        Creates a Sort by expressions, with limit and offset.
      • sort

        public RelBuilder sort​(org.apache.calcite.rel.RelCollation collation)
        Creates a Sort by specifying collations.
      • sortLimit

        public RelBuilder sortLimit​(int offset,
                                    int fetch,
                                    Iterable<? extends org.apache.calcite.rex.RexNode> nodes)
        Creates a Sort by a list of expressions, with limit and offset.
        Parameters:
        offset - Number of rows to skip; non-positive means don't skip any
        fetch - Maximum number of rows to fetch; negative means no limit
        nodes - Sort expressions
      • sortLimit

        public RelBuilder sortLimit​(@Nullable org.apache.calcite.rex.RexNode offsetNode,
                                    @Nullable org.apache.calcite.rex.RexNode fetchNode,
                                    Iterable<? extends org.apache.calcite.rex.RexNode> nodes)
        Creates a Sort by a list of expressions, with limitNode and offsetNode.
        Parameters:
        offsetNode - RexLiteral means number of rows to skip is deterministic, RexDynamicParam means number of rows to skip is dynamic.
        fetchNode - RexLiteral means maximum number of rows to fetch is deterministic, RexDynamicParam mean maximum number is dynamic.
        nodes - Sort expressions
      • convert

        public RelBuilder convert​(org.apache.calcite.rel.type.RelDataType castRowType,
                                  boolean rename)
        Creates a projection that converts the current relational expression's output to a desired row type.

        The desired row type and the row type to be converted must have the same number of fields.

        Parameters:
        castRowType - row type after cast
        rename - if true, use field names from castRowType; if false, preserve field names from rel
      • permute

        public RelBuilder permute​(org.apache.calcite.util.mapping.Mapping mapping)
      • match

        public RelBuilder match​(org.apache.calcite.rex.RexNode pattern,
                                boolean strictStart,
                                boolean strictEnd,
                                Map<String,​org.apache.calcite.rex.RexNode> patternDefinitions,
                                Iterable<? extends org.apache.calcite.rex.RexNode> measureList,
                                org.apache.calcite.rex.RexNode after,
                                Map<String,​? extends SortedSet<String>> subsets,
                                boolean allRows,
                                Iterable<? extends org.apache.calcite.rex.RexNode> partitionKeys,
                                Iterable<? extends org.apache.calcite.rex.RexNode> orderKeys,
                                org.apache.calcite.rex.RexNode interval)
        Creates a Match.
      • pivot

        public RelBuilder pivot​(RelBuilder.GroupKey groupKey,
                                Iterable<? extends RelBuilder.AggCall> aggCalls,
                                Iterable<? extends org.apache.calcite.rex.RexNode> axes,
                                Iterable<? extends Map.Entry<String,​? extends Iterable<? extends org.apache.calcite.rex.RexNode>>> values)
        Creates a Pivot.

        To achieve the same effect as the SQL

        
         SELECT *
         FROM (SELECT mgr, deptno, job, sal FROM emp)
         PIVOT (SUM(sal) AS ss, COUNT(*) AS c
             FOR (job, deptno)
             IN (('CLERK', 10) AS c10, ('MANAGER', 20) AS m20))
         

        use the builder as follows:

        
         RelBuilder b;
         b.scan("EMP");
         final RelBuilder.GroupKey groupKey = b.groupKey("MGR");
         final List<RelBuilder.AggCall> aggCalls =
             Arrays.asList(b.sum(b.field("SAL")).as("SS"),
                 b.count().as("C"));
         final List<RexNode> axes =
             Arrays.asList(b.field("JOB"),
                 b.field("DEPTNO"));
         final ImmutableMap.Builder<String, List<RexNode>> valueMap =
             ImmutableMap.builder();
         valueMap.put("C10",
             Arrays.asList(b.literal("CLERK"), b.literal(10)));
         valueMap.put("M20",
             Arrays.asList(b.literal("MANAGER"), b.literal(20)));
         b.pivot(groupKey, aggCalls, axes, valueMap.build().entrySet());
         

        Note that the SQL uses a sub-query to project away columns (e.g. HIREDATE) that it does not reference, so that they do not appear in the GROUP BY. You do not need to do that in this API, because the groupKey parameter specifies the keys.

        Pivot is implemented by desugaring. The above example becomes the following:

        
         SELECT mgr,
             SUM(sal) FILTER (WHERE job = 'CLERK' AND deptno = 10) AS c10_ss,
             COUNT(*) FILTER (WHERE job = 'CLERK' AND deptno = 10) AS c10_c,
             SUM(sal) FILTER (WHERE job = 'MANAGER' AND deptno = 20) AS m20_ss,
              COUNT(*) FILTER (WHERE job = 'MANAGER' AND deptno = 20) AS m20_c
         FROM emp
         GROUP BY mgr
         
        Parameters:
        groupKey - Key columns
        aggCalls - Aggregate expressions to compute for each value
        axes - Columns to pivot
        values - Values to pivot, and the alias for each column group
        Returns:
        this RelBuilder
      • unpivot

        public RelBuilder unpivot​(boolean includeNulls,
                                  Iterable<String> measureNames,
                                  Iterable<String> axisNames,
                                  Iterable<? extends Map.Entry<? extends List<? extends org.apache.calcite.rex.RexLiteral>,​? extends List<? extends org.apache.calcite.rex.RexNode>>> axisMap)
        Creates an Unpivot.

        To achieve the same effect as the SQL

        
         SELECT *
         FROM (SELECT deptno, job, sal, comm FROM emp)
           UNPIVOT INCLUDE NULLS (remuneration
             FOR remuneration_type IN (comm AS 'commission',
                                       sal AS 'salary'))
         

        use the builder as follows:

        
         RelBuilder b;
         b.scan("EMP");
         final List<String> measureNames = Arrays.asList("REMUNERATION");
         final List<String> axisNames = Arrays.asList("REMUNERATION_TYPE");
         final Map<List<RexLiteral>, List<RexNode>> axisMap =
             ImmutableMap.<List<RexLiteral>, List<RexNode>>builder()
                 .put(Arrays.asList(b.literal("commission")),
                     Arrays.asList(b.field("COMM")))
                 .put(Arrays.asList(b.literal("salary")),
                     Arrays.asList(b.field("SAL")))
                 .build();
         b.unpivot(false, measureNames, axisNames, axisMap);
         

        The query generates two columns: remuneration_type (an axis column) and remuneration (a measure column). Axis columns contain values to indicate the source of the row (in this case, 'salary' if the row came from the sal column, and 'commission' if the row came from the comm column).

        Parameters:
        includeNulls - Whether to include NULL values in the output
        measureNames - Names of columns to be generated to hold pivoted measures
        axisNames - Names of columns to be generated to hold qualifying values
        axisMap - Mapping from the columns that hold measures to the values that the axis columns will hold in the generated rows
        Returns:
        This RelBuilder
      • hints

        public RelBuilder hints​(org.apache.calcite.rel.hint.RelHint... hints)
        Attaches an array of hints to the stack top relational expression.

        The redundant hints would be eliminated.

        Parameters:
        hints - Hints
        Throws:
        AssertionError - if the top relational expression does not implement Hintable
      • hints

        public RelBuilder hints​(Iterable<org.apache.calcite.rel.hint.RelHint> hints)
        Attaches multiple hints to the stack top relational expression.

        The redundant hints would be eliminated.

        Parameters:
        hints - Hints
        Throws:
        AssertionError - if the top relational expression does not implement Hintable
      • clear

        public void clear()
        Clears the stack.

        The builder's state is now the same as when it was created.