Class RexBuilder


  • public class RexBuilder
    extends java.lang.Object
    Factory for row expressions.

    Some common literal values (NULL, TRUE, FALSE, 0, 1, '') are cached.

    • Field Detail

      • GET_OPERATOR

        public static final SqlSpecialOperator GET_OPERATOR
        Special operator that accesses an unadvertised field of an input record. This operator cannot be used in SQL queries; it is introduced temporarily during sql-to-rel translation, then replaced during the process that trims unwanted fields.
      • INT_MIN

        private static final java.math.BigDecimal INT_MIN
        The smallest valid int value, as a BigDecimal.
      • INT_MAX

        private static final java.math.BigDecimal INT_MAX
        The largest valid int value, as a BigDecimal.
      • booleanTrue

        private final RexLiteral booleanTrue
      • booleanFalse

        private final RexLiteral booleanFalse
      • constantNull

        private final RexLiteral constantNull
    • Constructor Detail

      • RexBuilder

        public RexBuilder​(RelDataTypeFactory typeFactory)
        Creates a RexBuilder.
        Parameters:
        typeFactory - Type factory
    • Method Detail

      • identityProjects

        public java.util.List<? extends RexNode> identityProjects​(RelDataType rowType)
        Creates a list of RexInputRef expressions, projecting the fields of a given record type.
      • getTypeFactory

        public RelDataTypeFactory getTypeFactory()
        Returns this RexBuilder's type factory
        Returns:
        type factory
      • getOpTab

        public SqlStdOperatorTable getOpTab()
        Returns this RexBuilder's operator table
        Returns:
        operator table
      • makeFieldAccess

        public RexNode makeFieldAccess​(RexNode expr,
                                       java.lang.String fieldName,
                                       boolean caseSensitive)
        Creates an expression accessing a given named field from a record.

        NOTE: Be careful choosing the value of caseSensitive. If the field name was supplied by an end-user (e.g. as a column alias in SQL), use your session's case-sensitivity setting. Only hard-code true if you are sure that the field name is internally generated. Hard-coding false is almost certainly wrong.

        Parameters:
        expr - Expression yielding a record
        fieldName - Name of field in record
        caseSensitive - Whether match is case-sensitive
        Returns:
        Expression accessing a given named field
      • makeFieldAccess

        public RexNode makeFieldAccess​(RexNode expr,
                                       int i)
        Creates an expression accessing a field with a given ordinal from a record.
        Parameters:
        expr - Expression yielding a record
        i - Ordinal of field
        Returns:
        Expression accessing given field
      • makeFieldAccessInternal

        private RexNode makeFieldAccessInternal​(RexNode expr,
                                                RelDataTypeField field)
        Creates an expression accessing a given field from a record.
        Parameters:
        expr - Expression yielding a record
        field - Field
        Returns:
        Expression accessing given field
      • makeCall

        public final RexNode makeCall​(SqlOperator op,
                                      RexNode... exprs)
        Creates a call with a list of arguments.

        Equivalent to makeCall(op, exprList.toArray(new RexNode[exprList.size()])).

      • deriveReturnType

        public RelDataType deriveReturnType​(SqlOperator op,
                                            java.util.List<? extends RexNode> exprs)
        Derives the return type of a call to an operator.
        Parameters:
        op - the operator being called
        exprs - actual operands
        Returns:
        derived type
      • addAggCall

        public RexNode addAggCall​(AggregateCall aggCall,
                                  int groupCount,
                                  java.util.List<AggregateCall> aggCalls,
                                  java.util.Map<AggregateCall,​RexNode> aggCallMapping,
                                  java.util.List<RelDataType> aggArgTypes)
        Creates a reference to an aggregate call, checking for repeated calls.

        Argument types help to optimize for repeated aggregates. For instance count(42) is equivalent to count(*).

        Parameters:
        aggCall - aggregate call to be added
        groupCount - number of groups in the aggregate relation
        aggCalls - destination list of aggregate calls
        aggCallMapping - the dictionary of already added calls
        aggArgTypes - Argument types, not null
        Returns:
        Rex expression for the given aggregate call
      • addAggCall

        @Deprecated
        public RexNode addAggCall​(AggregateCall aggCall,
                                  int groupCount,
                                  boolean indicator,
                                  java.util.List<AggregateCall> aggCalls,
                                  java.util.Map<AggregateCall,​RexNode> aggCallMapping,
                                  java.util.List<RelDataType> aggArgTypes)
        Deprecated.
        Creates a reference to an aggregate call, checking for repeated calls.
      • nullableArgs

        private static java.util.List<java.lang.Integer> nullableArgs​(java.util.List<java.lang.Integer> list0,
                                                                      java.util.List<RelDataType> types)
      • makeWindow

        public RexWindow makeWindow​(java.util.List<RexNode> partitionKeys,
                                    com.google.common.collect.ImmutableList<RexFieldCollation> orderKeys,
                                    RexWindowBound lowerBound,
                                    RexWindowBound upperBound,
                                    boolean isRows)
        Creates a window specification.
        Parameters:
        partitionKeys - Partition keys
        orderKeys - Order keys
        lowerBound - Lower bound
        upperBound - Upper bound
        isRows - Whether physical. True if row-based, false if range-based
        Returns:
        window specification
      • constantNull

        @Deprecated
        public RexLiteral constantNull()
        Deprecated.
        Use makeNullLiteral(RelDataType), which produces a NULL of the correct type
        Creates a constant for the SQL NULL value.
      • makeCorrel

        public RexNode makeCorrel​(RelDataType type,
                                  CorrelationId id)
        Creates an expression referencing a correlation variable.
        Parameters:
        id - Name of variable
        type - Type of variable
        Returns:
        Correlation variable
      • makeNewInvocation

        public RexNode makeNewInvocation​(RelDataType type,
                                         java.util.List<RexNode> exprs)
        Creates an invocation of the NEW operator.
        Parameters:
        type - Type to be instantiated
        exprs - Arguments to NEW operator
        Returns:
        Expression invoking NEW operator
      • makeCast

        public RexNode makeCast​(RelDataType type,
                                RexNode exp)
        Creates a call to the CAST operator.
        Parameters:
        type - Type to cast to
        exp - Expression being cast
        Returns:
        Call to CAST operator
      • makeCast

        public RexNode makeCast​(RelDataType type,
                                RexNode exp,
                                boolean matchNullability)
        Creates a call to the CAST operator, expanding if possible, and optionally also preserving nullability.

        Tries to expand the cast, and therefore the result may be something other than a RexCall to the CAST operator, such as a RexLiteral.

        Parameters:
        type - Type to cast to
        exp - Expression being cast
        matchNullability - Whether to ensure the result has the same nullability as type
        Returns:
        Call to CAST operator
      • baseUnit

        protected static org.apache.calcite.avatica.util.TimeUnit baseUnit​(SqlTypeName unit)
        Returns the lowest granularity unit for the given unit. YEAR and MONTH intervals are stored as months; HOUR, MINUTE, SECOND intervals are stored as milliseconds.
      • canRemoveCastFromLiteral

        boolean canRemoveCastFromLiteral​(RelDataType toType,
                                         java.lang.Comparable value,
                                         SqlTypeName fromTypeName)
      • multiplyDivide

        public RexNode multiplyDivide​(RexNode e,
                                      java.math.BigDecimal multiplier,
                                      java.math.BigDecimal divider)
      • encodeIntervalOrDecimal

        public RexNode encodeIntervalOrDecimal​(RexNode value,
                                               RelDataType type,
                                               boolean checkOverflow)
        Casts a decimal's integer representation to a decimal node. If the expression is not the expected integer type, then it is casted first.

        An overflow check may be requested to ensure the internal value does not exceed the maximum value of the decimal type.

        Parameters:
        value - integer representation of decimal
        type - type integer will be reinterpreted as
        checkOverflow - indicates whether an overflow check is required when reinterpreting this particular value as the decimal type. A check usually not required for arithmetic, but is often required for rounding and explicit casts.
        Returns:
        the integer reinterpreted as an opaque decimal type
      • decodeIntervalOrDecimal

        public RexNode decodeIntervalOrDecimal​(RexNode node)
        Retrieves an interval or decimal node's integer representation
        Parameters:
        node - the interval or decimal value as an opaque type
        Returns:
        an integer representation of the decimal value
      • makeAbstractCast

        public RexNode makeAbstractCast​(RelDataType type,
                                        RexNode exp)
        Creates a call to the CAST operator.
        Parameters:
        type - Type to cast to
        exp - Expression being cast
        Returns:
        Call to CAST operator
      • makeReinterpretCast

        public RexNode makeReinterpretCast​(RelDataType type,
                                           RexNode exp,
                                           RexNode checkOverflow)
        Makes a reinterpret cast.
        Parameters:
        type - type returned by the cast
        exp - expression to be casted
        checkOverflow - whether an overflow check is required
        Returns:
        a RexCall with two operands and a special return type
      • makeNotNull

        public RexNode makeNotNull​(RexNode exp)
        Makes a cast of a value to NOT NULL; no-op if the type already has NOT NULL.
      • makeRangeReference

        public RexNode makeRangeReference​(RelNode input)
        Creates a reference to all the fields in the row. That is, the whole row as a single record object.
        Parameters:
        input - Input relational expression
      • makeRangeReference

        public RexRangeRef makeRangeReference​(RelDataType type,
                                              int offset,
                                              boolean nullable)
        Creates a reference to all the fields in the row.

        For example, if the input row has type T{f0,f1,f2,f3,f4} then makeRangeReference(T{f0,f1,f2,f3,f4}, S{f3,f4}, 3) is an expression which yields the last 2 fields.

        Parameters:
        type - Type of the resulting range record.
        offset - Index of first field.
        nullable - Whether the record is nullable.
      • makeInputRef

        public RexInputRef makeInputRef​(RelDataType type,
                                        int i)
        Creates a reference to a given field of the input record.
        Parameters:
        type - Type of field
        i - Ordinal of field
        Returns:
        Reference to field
      • makeInputRef

        public RexInputRef makeInputRef​(RelNode input,
                                        int i)
        Creates a reference to a given field of the input relational expression.
        Parameters:
        input - Input relational expression
        i - Ordinal of field
        Returns:
        Reference to field
        See Also:
        identityProjects(RelDataType)
      • makePatternFieldRef

        public RexPatternFieldRef makePatternFieldRef​(java.lang.String alpha,
                                                      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
      • makeFlag

        public RexLiteral makeFlag​(java.lang.Enum flag)
        Creates a literal representing a flag.
        Parameters:
        flag - Flag value
      • makeLiteral

        public RexLiteral makeLiteral​(boolean b)
        Creates a boolean literal.
      • makeExactLiteral

        public RexLiteral makeExactLiteral​(java.math.BigDecimal bd)
        Creates a numeric literal.
      • makeBigintLiteral

        public RexLiteral makeBigintLiteral​(java.math.BigDecimal bd)
        Creates a BIGINT literal.
      • makeExactLiteral

        public RexLiteral makeExactLiteral​(java.math.BigDecimal bd,
                                           RelDataType type)
        Creates a numeric literal.
      • makeBinaryLiteral

        public RexLiteral makeBinaryLiteral​(org.apache.calcite.avatica.util.ByteString byteString)
        Creates a byte array literal.
      • makeApproxLiteral

        public RexLiteral makeApproxLiteral​(java.math.BigDecimal bd)
        Creates a double-precision literal.
      • makeApproxLiteral

        public RexLiteral makeApproxLiteral​(java.math.BigDecimal bd,
                                            RelDataType type)
        Creates an approximate numeric literal (double or float).
        Parameters:
        bd - literal value
        type - approximate numeric type
        Returns:
        new literal
      • makeLiteral

        public RexLiteral makeLiteral​(java.lang.String s)
        Creates a character string literal.
      • makePreciseStringLiteral

        protected RexLiteral makePreciseStringLiteral​(java.lang.String s)
        Creates a character string literal with type CHAR and default charset and collation.
        Parameters:
        s - String value
        Returns:
        Character string literal
      • makePreciseStringLiteral

        protected RexLiteral makePreciseStringLiteral​(org.apache.calcite.avatica.util.ByteString value,
                                                      java.lang.String charsetName,
                                                      SqlCollation collation)
        Creates a character string literal with type CHAR.
        Parameters:
        value - String value in bytes
        charsetName - SQL-level charset name
        collation - Sql collation
        Returns:
        String literal
      • ensureType

        public RexNode ensureType​(RelDataType type,
                                  RexNode node,
                                  boolean matchNullability)
        Ensures expression is interpreted as a specified type. The returned expression may be wrapped with a cast.
        Parameters:
        type - desired type
        node - expression
        matchNullability - whether to correct nullability of specified type to match the expression; this usually should be true, except for explicit casts which can override default nullability
        Returns:
        a casted expression or the original expression
      • matchNullability

        public RelDataType matchNullability​(RelDataType type,
                                            RexNode value)
        Ensures that a type's nullability matches a value's nullability.
      • makeCharLiteral

        public RexLiteral makeCharLiteral​(NlsString str)
        Creates a character string literal from an NlsString.

        If the string's charset and collation are not set, uses the system defaults.

      • makeTimeLiteral

        public RexLiteral makeTimeLiteral​(TimeString time,
                                          int precision)
        Creates a Time literal.
      • makeTimeWithLocalTimeZoneLiteral

        public RexLiteral makeTimeWithLocalTimeZoneLiteral​(TimeString time,
                                                           int precision)
        Creates a Time with local time-zone literal.
      • makeTimestampLiteral

        public RexLiteral makeTimestampLiteral​(TimestampString timestamp,
                                               int precision)
        Creates a Timestamp literal.
      • makeTimestampWithLocalTimeZoneLiteral

        public RexLiteral makeTimestampWithLocalTimeZoneLiteral​(TimestampString timestamp,
                                                                int precision)
        Creates a Timestamp with local time-zone literal.
      • makeIntervalLiteral

        public RexLiteral makeIntervalLiteral​(SqlIntervalQualifier intervalQualifier)
        Creates a literal representing an interval type, for example YEAR TO MONTH or DOW.
      • makeIntervalLiteral

        public RexLiteral makeIntervalLiteral​(java.math.BigDecimal v,
                                              SqlIntervalQualifier intervalQualifier)
        Creates a literal representing an interval value, for example INTERVAL '3-7' YEAR TO MONTH.
      • makeDynamicParam

        public RexDynamicParam makeDynamicParam​(RelDataType type,
                                                int index)
        Creates a reference to a dynamic parameter
        Parameters:
        type - Type of dynamic parameter
        index - Index of dynamic parameter
        Returns:
        Expression referencing dynamic parameter
      • makeNullLiteral

        public RexLiteral makeNullLiteral​(RelDataType type)
        Creates a literal whose value is NULL, with a particular type.

        The typing is necessary because RexNodes are strictly typed. For example, in the Rex world the NULL parameter to SUBSTRING(NULL FROM 2 FOR 4) must have a valid VARCHAR type so that the result type can be determined.

        Parameters:
        type - Type to cast NULL to
        Returns:
        NULL literal of given type
      • makeZeroLiteral

        public RexNode makeZeroLiteral​(RelDataType type)
        Creates a literal of the default value for the given type.

        This value is:

        • 0 for numeric types;
        • FALSE for BOOLEAN;
        • The epoch for TIMESTAMP and DATE;
        • Midnight for TIME;
        • The empty string for string types (CHAR, BINARY, VARCHAR, VARBINARY).
        Parameters:
        type - Type
        Returns:
        Simple literal, or cast simple literal
      • zeroValue

        private static java.lang.Comparable zeroValue​(RelDataType type)
      • makeLiteral

        public RexNode makeLiteral​(java.lang.Object value,
                                   RelDataType type,
                                   boolean allowCast)
        Creates a literal of a given type. The value is assumed to be compatible with the type.
        Parameters:
        value - Value
        type - Type
        allowCast - Whether to allow a cast. If false, value is always a RexLiteral but may not be the exact type
        Returns:
        Simple literal, or cast simple literal
      • guessType

        private RelDataType guessType​(java.lang.Object value)
      • padRight

        private static NlsString padRight​(NlsString s,
                                          int length)
        Returns an NlsString with spaces to make it at least a given length.
      • padRight

        private static java.lang.String padRight​(java.lang.String s,
                                                 int length)
        Returns a string padded with spaces to make it at least a given length.
      • padRight

        private static org.apache.calcite.avatica.util.ByteString padRight​(org.apache.calcite.avatica.util.ByteString s,
                                                                           int length)
        Returns a byte-string padded with zero bytes to make it at least a given length,