Class RexBuilder

java.lang.Object
org.apache.calcite.rex.RexBuilder

public class RexBuilder extends Object
Factory for row expressions.

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

  • Field Details

    • 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.
    • typeFactory

      protected final RelDataTypeFactory typeFactory
  • Constructor Details

    • RexBuilder

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

    • identityProjects

      public List<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, 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
    • makeCall

      public RexNode makeCall(RelDataType returnType, SqlOperator op, List<RexNode> exprs)
      Creates a call with a list of arguments and a predetermined type.
    • makeCall

      public RexNode makeCall(SqlOperator op, List<? extends RexNode> exprs)
      Creates a call with an array of arguments.

      If you already know the return type of the call, then makeCall(org.apache.calcite.rel.type.RelDataType, org.apache.calcite.sql.SqlOperator, java.util.List) is preferred.

    • 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, 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, List<AggregateCall> aggCalls, Map<AggregateCall,RexNode> aggCallMapping, IntPredicate isNullable)
      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
      isNullable - Whether input field i is nullable
      Returns:
      Rex expression for the given aggregate call
    • addAggCall

      @Deprecated public RexNode addAggCall(AggregateCall aggCall, int groupCount, List<AggregateCall> aggCalls, Map<AggregateCall,RexNode> aggCallMapping, @Nullable List<RelDataType> aggArgTypes)
      Deprecated.
    • addAggCall

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

      @Deprecated public RexNode makeOver(RelDataType type, SqlAggFunction operator, List<RexNode> exprs, List<RexNode> partitionKeys, com.google.common.collect.ImmutableList<RexFieldCollation> orderKeys, RexWindowBound lowerBound, RexWindowBound upperBound, boolean rows, boolean allowPartial, boolean nullWhenCountZero, boolean distinct)
      Deprecated.
    • makeOver

      public RexNode makeOver(RelDataType type, SqlAggFunction operator, List<RexNode> exprs, List<RexNode> partitionKeys, com.google.common.collect.ImmutableList<RexFieldCollation> orderKeys, RexWindowBound lowerBound, RexWindowBound upperBound, boolean rows, boolean allowPartial, boolean nullWhenCountZero, boolean distinct, boolean ignoreNulls)
      Creates a call to a windowed agg.
    • makeWindow

      public RexWindow makeWindow(List<RexNode> partitionKeys, com.google.common.collect.ImmutableList<RexFieldCollation> orderKeys, RexWindowBound lowerBound, RexWindowBound upperBound, boolean rows)
      Creates a window specification.
      Parameters:
      partitionKeys - Partition keys
      orderKeys - Order keys
      lowerBound - Lower bound
      upperBound - Upper bound
      rows - 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:
      type - Type of variable
      id - Name of variable
      Returns:
      Correlation variable
    • makeNewInvocation

      public RexNode makeNewInvocation(RelDataType type, 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

      @Deprecated public RexNode makeCast(RelDataType type, RexNode exp, boolean matchNullability)
      Deprecated.
    • makeCast

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

      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
      safe - Whether to return NULL if cast fails
      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.
    • multiplyDivide

      public RexNode multiplyDivide(RexNode e, BigDecimal multiplier, 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

      @Deprecated public RexNode makeAbstractCast(RelDataType type, RexNode exp)
      Deprecated.
    • makeAbstractCast

      public RexNode makeAbstractCast(RelDataType type, RexNode exp, boolean safe)
      Creates a call to CAST or SAFE_CAST operator.
      Parameters:
      type - Type to cast to
      exp - Expression being cast
      safe - Whether to return NULL if cast fails
      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:
    • makePatternFieldRef

      public RexPatternFieldRef makePatternFieldRef(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
    • makeLocalRef

      public RexLocalRef makeLocalRef(RelDataType type, int i)
      Create a reference to local variable.
      Parameters:
      type - Type of variable
      i - Ordinal of variable
      Returns:
      Reference to local variable
    • makeFlag

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

      protected RexLiteral makeLiteral(@Nullable Comparable o, RelDataType type, SqlTypeName typeName)
      Internal method to create a call to a literal. Code outside this package should call one of the type-specific methods such as makeDateLiteral(DateString), makeLiteral(boolean), makeLiteral(String).
      Parameters:
      o - Value of literal, must be appropriate for the type
      type - Type of literal
      typeName - SQL type of literal
      Returns:
      Literal
    • makeLiteral

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

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

      public RexLiteral makeBigintLiteral(@Nullable BigDecimal bd)
      Creates a BIGINT literal.
    • makeExactLiteral

      public RexLiteral makeExactLiteral(@Nullable 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(BigDecimal bd)
      Creates a double-precision literal.
    • makeApproxLiteral

      public RexLiteral makeApproxLiteral(@Nullable BigDecimal bd, RelDataType type)
      Creates an approximate numeric literal (double or float).
      Parameters:
      bd - literal value
      type - approximate numeric type
      Returns:
      new literal
    • makeSearchArgumentLiteral

      public RexLiteral makeSearchArgumentLiteral(Sarg s, RelDataType type)
      Creates a search argument literal.
    • makeLiteral

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

      protected RexLiteral makePreciseStringLiteral(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, 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.

    • makeDateLiteral

      @Deprecated public RexLiteral makeDateLiteral(Calendar calendar)
      Deprecated.
    • makeDateLiteral

      public RexLiteral makeDateLiteral(DateString date)
      Creates a Date literal.
    • makeTimeLiteral

      @Deprecated public RexLiteral makeTimeLiteral(Calendar calendar, int precision)
    • 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

      @Deprecated public RexLiteral makeTimestampLiteral(Calendar calendar, int precision)
    • 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(@Nullable 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
    • makeNullLiteral

      @Deprecated public RexNode makeNullLiteral(SqlTypeName typeName, int precision)
    • makeNullLiteral

      @Deprecated public RexNode makeNullLiteral(SqlTypeName typeName)
    • makeIn

      public RexNode makeIn(RexNode arg, List<? extends RexNode> ranges)
      Creates a RexNode representation a SQL "arg IN (point, ...)" expression.

      If all of the expressions are literals, creates a call Sarg literal, "SEARCH(arg, SARG([point0..point0], [point1..point1], ...)"; otherwise creates a disjunction, "arg = point0 OR arg = point1 OR ...".

    • makeBetween

      public RexNode makeBetween(RexNode arg, RexNode lower, RexNode upper)
      Creates a RexNode representation a SQL "arg BETWEEN lower AND upper" expression.

      If the expressions are all literals of compatible type, creates a call to Sarg literal, SEARCH(arg, SARG([lower..upper]); otherwise creates a disjunction, arg >= lower AND arg <= upper.

    • copy

      public RexNode copy(RexNode expr)
      Creates a copy of an expression, which may have been created using a different RexBuilder and/or RelDataTypeFactory, using this RexBuilder.
      Parameters:
      expr - Expression
      Returns:
      Copy of expression
      See Also:
    • makeZeroLiteral

      public RexLiteral 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
    • makeLiteral

      public RexLiteral makeLiteral(@Nullable Object value, RelDataType type)
      Creates a literal of a given type, padding values of constant-width types to match their type, not allowing casts.
      Parameters:
      value - Value
      type - Type
      Returns:
      Simple literal
    • makeLiteral

      public RexNode makeLiteral(@Nullable Object value, RelDataType type, boolean allowCast)
      Creates a literal of a given type, padding values of constant-width types to match their 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
    • makeLiteral

      public RexNode makeLiteral(@Nullable Object value, RelDataType type, boolean allowCast, boolean trim)
      Creates a literal of a given type. The value is assumed to be compatible with the type.

      The trim parameter controls whether to trim values of constant-width types such as CHAR. Consider a call to makeLiteral("foo ", CHAR(5), and note that the value is too short for its type. If trim is true, the value is converted to "foo" and the type to CHAR(3); if trim is false, the value is right-padded with spaces to "foo ", to match the type CHAR(5).

      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
      trim - Whether to trim values and type to the shortest equivalent value; for example whether to convert CHAR(4) 'foo ' to CHAR(3) 'foo'
      Returns:
      Simple literal, or cast simple literal