Class SqlTypeUtil

java.lang.Object
org.apache.calcite.sql.type.SqlTypeUtil

public abstract class SqlTypeUtil extends Object
Contains utility methods used during SQL validation or type derivation.
  • Constructor Details

    • SqlTypeUtil

      public SqlTypeUtil()
  • Method Details

    • isCharTypeComparable

      public static boolean isCharTypeComparable(List<RelDataType> argTypes)
      Checks whether two types or more are char comparable.
      Returns:
      Returns true if all operands are of char type and if they are comparable, i.e. of the same charset and collation of same charset
    • isCharTypeComparable

      public static boolean isCharTypeComparable(SqlCallBinding binding, List<SqlNode> operands, boolean throwOnFailure)
      Returns whether the operands to a call are char type-comparable.
      Parameters:
      binding - Binding of call to operands
      operands - Operands to check for compatibility; usually the operands of the bound call, but not always
      throwOnFailure - Whether to throw an exception on failure
      Returns:
      whether operands are valid
    • deriveCollectionQueryComponentType

      public static RelDataType deriveCollectionQueryComponentType(SqlTypeName collectionType, RelDataType origin)
      Derives component type for ARRAY, MULTISET, MAP when input is sub-query.
      Parameters:
      origin - original component type
      Returns:
      component type
    • deriveAndCollectTypes

      public static List<RelDataType> deriveAndCollectTypes(SqlValidator validator, SqlValidatorScope scope, List<? extends SqlNode> operands)
      Iterates over all operands, derives their types, and collects them into a list.
    • deriveType

      @API(since="1.26", status=EXPERIMENTAL) public static RelDataType deriveType(SqlCallBinding binding)
      Derives type of the call via its binding.
      Parameters:
      binding - binding to derive the type from
      Returns:
      datatype of the call
    • deriveType

      @API(since="1.26", status=EXPERIMENTAL) public static RelDataType deriveType(SqlCallBinding binding, SqlNode node)
      Derives type of the given call under given binding.
      Parameters:
      binding - binding to derive the type from
      node - node type to derive
      Returns:
      datatype of the given node
    • deriveType

      @API(since="1.26", status=EXPERIMENTAL) public static List<RelDataType> deriveType(SqlCallBinding binding, List<? extends SqlNode> nodes)
      Derives types for the list of nodes.
      Parameters:
      binding - binding to derive the type from
      nodes - the list of nodes to derive types from
      Returns:
      the list of types of the given nodes
    • promoteToRowType

      public static RelDataType promoteToRowType(RelDataTypeFactory typeFactory, RelDataType type, @Nullable String fieldName)
      Promotes a type to a row type (does nothing if it already is one).
      Parameters:
      type - type to be promoted
      fieldName - name to give field in row type; null for default of "ROW_VALUE"
      Returns:
      row type
    • makeNullableIfOperandsAre

      public static RelDataType makeNullableIfOperandsAre(SqlValidator validator, SqlValidatorScope scope, SqlCall call, RelDataType type)
      Recreates a given RelDataType with nullability iff any of the operands of a call are nullable.
    • makeNullableIfOperandsAre

      public static RelDataType makeNullableIfOperandsAre(RelDataTypeFactory typeFactory, List<RelDataType> argTypes, RelDataType type)
      Recreates a given RelDataType with nullability iff any of the param argTypes are nullable.
    • allNullable

      public static boolean allNullable(List<RelDataType> types)
      Returns whether all of array of types are nullable.
    • containsNullable

      public static boolean containsNullable(List<RelDataType> types)
      Returns whether one or more of an array of types is nullable.
    • containsNullable

      public static boolean containsNullable(RelDataType type)
      Determines whether a type or any of its fields (if a structured type) are nullable.
    • keepSourceTypeAndTargetNullability

      public static RelDataType keepSourceTypeAndTargetNullability(RelDataType sourceRelDataType, RelDataType targetRelDataType, RelDataTypeFactory typeFactory)
      Creates a RelDataType having the same type of the sourceRelDataType, and the same nullability as the targetRelDataType.
    • isOfSameTypeName

      public static boolean isOfSameTypeName(SqlTypeName typeName, RelDataType type)
      Returns typeName.equals(type.getSqlTypeName()). If typeName.equals(SqlTypeName.Any) true is always returned.
    • isOfSameTypeName

      public static boolean isOfSameTypeName(Collection<SqlTypeName> typeNames, RelDataType type)
      Returns true if any element in typeNames matches type.getSqlTypeName().
      See Also:
    • isDatetime

      public static boolean isDatetime(RelDataType type)
      Returns whether a type is DATE, TIME, or TIMESTAMP.
    • isDate

      public static boolean isDate(RelDataType type)
      Returns whether a type is DATE.
    • isTimestamp

      public static boolean isTimestamp(RelDataType type)
      Returns whether a type is TIMESTAMP.
    • isInterval

      @EnsuresNonNullIf(expression="#1.getIntervalQualifier()", result=true) public static boolean isInterval(RelDataType type)
      Returns whether a type is some kind of INTERVAL.
    • inCharFamily

      @EnsuresNonNullIf(expression="#1.getCharset()",result=true) @EnsuresNonNullIf(expression="#1.getCollation()",result=true) public static boolean inCharFamily(RelDataType type)
      Returns whether a type is in SqlTypeFamily.Character.
    • inCharFamily

      public static boolean inCharFamily(SqlTypeName typeName)
      Returns whether a type name is in SqlTypeFamily.Character.
    • inBooleanFamily

      public static boolean inBooleanFamily(RelDataType type)
      Returns whether a type is in SqlTypeFamily.Boolean.
    • inSameFamily

      public static boolean inSameFamily(RelDataType t1, RelDataType t2)
      Returns whether two types are in same type family.
    • inSameFamilyOrNull

      public static boolean inSameFamilyOrNull(RelDataType t1, RelDataType t2)
      Returns whether two types are in same type family, or one or the other is of type SqlTypeName.NULL.
    • inCharOrBinaryFamilies

      public static boolean inCharOrBinaryFamilies(RelDataType type)
      Returns whether a type family is either character or binary.
    • isLob

      public static boolean isLob(RelDataType type)
      Returns whether a type is a LOB of some kind.
    • isBoundedVariableWidth

      public static boolean isBoundedVariableWidth(RelDataType type)
      Returns whether a type is variable width with bounded precision.
    • isIntType

      public static boolean isIntType(RelDataType type)
      Returns whether a type is one of the integer types.
    • isDecimal

      public static boolean isDecimal(RelDataType type)
      Returns whether a type is DECIMAL.
    • isDouble

      public static boolean isDouble(RelDataType type)
      Returns whether a type is DOUBLE.
    • isBigint

      public static boolean isBigint(RelDataType type)
      Returns whether a type is BIGINT.
    • isExactNumeric

      public static boolean isExactNumeric(RelDataType type)
      Returns whether a type is numeric with exact precision.
    • hasScale

      public static boolean hasScale(RelDataType type)
      Returns whether a type's scale is set.
    • maxValue

      public static long maxValue(RelDataType type)
      Returns the maximum value of an integral type, as a long value.
    • isApproximateNumeric

      public static boolean isApproximateNumeric(RelDataType type)
      Returns whether a type is numeric with approximate precision.
    • isNumeric

      public static boolean isNumeric(RelDataType type)
      Returns whether a type is numeric.
    • isNull

      public static boolean isNull(RelDataType type)
      Returns whether a type is the NULL type.
    • sameNamedType

      public static boolean sameNamedType(RelDataType t1, RelDataType t2)
      Tests whether two types have the same name and structure, possibly with differing modifiers. For example, VARCHAR(1) and VARCHAR(10) are considered the same, while VARCHAR(1) and CHAR(1) are considered different. Likewise, VARCHAR(1) MULTISET and VARCHAR(10) MULTISET are considered the same.
      Returns:
      true if types have same name and structure
    • getMaxByteSize

      public static int getMaxByteSize(RelDataType type)
      Computes the maximum number of bytes required to represent a value of a type having user-defined precision. This computation assumes no overhead such as length indicators and NUL-terminators. Complex types for which multiple representations are possible (e.g. DECIMAL or TIMESTAMP) return 0.
      Parameters:
      type - type for which to compute storage
      Returns:
      maximum bytes, or 0 for a fixed-width type or type with unknown maximum
    • getMinValue

      public static long getMinValue(RelDataType type)
      Returns the minimum unscaled value of a numeric type.
      Parameters:
      type - a numeric type
    • getMaxValue

      public static long getMaxValue(RelDataType type)
      Returns the maximum unscaled value of a numeric type.
      Parameters:
      type - a numeric type
    • isJavaPrimitive

      @Deprecated public static boolean isJavaPrimitive(RelDataType type)
      Deprecated.
      Returns whether a type has a representation as a Java primitive (ignoring nullability).
    • getPrimitiveWrapperJavaClassName

      @Deprecated public static @Nullable String getPrimitiveWrapperJavaClassName(@Nullable RelDataType type)
      Deprecated.
      Returns the class name of the wrapper for the primitive data type.
    • getNumericJavaClassName

      @Deprecated public static @Nullable String getNumericJavaClassName(@Nullable RelDataType type)
      Deprecated.
      Returns the class name of a numeric data type.
    • isMeasure

      public static boolean isMeasure(RelDataType t)
    • canAssignFrom

      public static boolean canAssignFrom(RelDataType toType, RelDataType fromType)
      Tests whether a value can be assigned to a site.
      Parameters:
      toType - type of the target site
      fromType - type of the source value
      Returns:
      true iff assignable
    • areCharacterSetsMismatched

      public static boolean areCharacterSetsMismatched(RelDataType t1, RelDataType t2)
      Determines whether two types both have different character sets. If one or the other type has no character set (e.g. in cast from INT to VARCHAR), that is not a mismatch.
      Parameters:
      t1 - first type
      t2 - second type
      Returns:
      true iff mismatched
    • canCastFrom

      public static boolean canCastFrom(RelDataType toType, RelDataType fromType, boolean coerce)
      Compares two types and returns whether fromType can be cast to toType, using either coercion or assignment.

      REVIEW jvs 17-Dec-2004: the coerce param below shouldn't really be necessary. We're using it as a hack because SqlTypeFactoryImpl.leastRestrictive(java.util.List<org.apache.calcite.rel.type.RelDataType>, org.apache.calcite.sql.type.SqlTypeMappingRule) isn't complete enough yet. Once it is, this param (and the non-coerce rules of SqlTypeAssignmentRule) should go away.

      Parameters:
      toType - target of assignment
      fromType - source of assignment
      coerce - if true, the SQL rules for CAST are used; if false, the rules are similar to Java; e.g. you can't assign short x = (int) y, and you can't assign int x = (String) z.
      Returns:
      whether cast is legal
    • canCastFrom

      public static boolean canCastFrom(RelDataType toType, RelDataType fromType, SqlTypeMappingRule typeMappingRule)
      Compares two types and returns whether fromType can be cast to toType.

      A type mapping rule (i.e. SqlTypeCoercionRule or SqlTypeAssignmentRule) controls what types are allowed to be cast from/to.

      Parameters:
      toType - target of assignment
      fromType - source of assignment
      typeMappingRule - SqlTypeMappingRule
      Returns:
      whether cast is legal
    • flattenRecordType

      public static RelDataType flattenRecordType(RelDataTypeFactory typeFactory, RelDataType recordType, int @Nullable [] flatteningMap)
      Flattens a record type by recursively expanding any fields which are themselves record types. For each record type, a representative null value field is also prepended (with state NULL for a null value and FALSE for non-null), and all component types are asserted to be nullable, since SQL doesn't allow NOT NULL to be specified on attributes.
      Parameters:
      typeFactory - factory which should produced flattened type
      recordType - type with possible nesting
      flatteningMap - if non-null, receives map from unflattened ordinal to flattened ordinal (must have length at least recordType.getFieldList().size())
      Returns:
      flattened equivalent
    • needsNullIndicator

      public static boolean needsNullIndicator(RelDataType recordType)
    • convertTypeToSpec

      public static SqlDataTypeSpec convertTypeToSpec(RelDataType type, @Nullable String charSetName, int maxPrecision, int maxScale)
      Converts an instance of RelDataType to an instance of SqlDataTypeSpec.
      Parameters:
      type - type descriptor
      charSetName - charSet name
      maxPrecision - The max allowed precision.
      maxScale - max allowed scale
      Returns:
      corresponding parse representation
    • convertTypeToSpec

      public static SqlDataTypeSpec convertTypeToSpec(RelDataType type)
      Converts an instance of RelDataType to an instance of SqlDataTypeSpec.
      Parameters:
      type - type descriptor
      Returns:
      corresponding parse representation
    • createMultisetType

      public static RelDataType createMultisetType(RelDataTypeFactory typeFactory, RelDataType type, boolean nullable)
    • createArrayType

      public static RelDataType createArrayType(RelDataTypeFactory typeFactory, RelDataType type, boolean nullable)
    • createMapType

      public static RelDataType createMapType(RelDataTypeFactory typeFactory, RelDataType keyType, RelDataType valueType, boolean nullable)
    • createMapTypeFromRecord

      public static RelDataType createMapTypeFromRecord(RelDataTypeFactory typeFactory, RelDataType type)
      Creates a MAP type from a record type. The record type must have exactly two fields.
    • createRecordTypeFromMap

      public static RelDataType createRecordTypeFromMap(RelDataTypeFactory typeFactory, RelDataType type)
      Creates a ROW type from a map type. The record type will have two fields.
    • addCharsetAndCollation

      public static RelDataType addCharsetAndCollation(RelDataType type, RelDataTypeFactory typeFactory)
      Adds collation and charset to a character type, returns other types unchanged.
      Parameters:
      type - Type
      typeFactory - Type factory
      Returns:
      Type with added charset and collation, or unchanged type if it is not a char type.
    • equalSansNullability

      public static boolean equalSansNullability(RelDataTypeFactory factory, RelDataType type1, RelDataType type2)
      Returns whether two types are equal, ignoring nullability.

      They need not come from the same factory.

      Parameters:
      factory - Type factory
      type1 - First type
      type2 - Second type
      Returns:
      whether types are equal, ignoring nullability
    • equalSansNullability

      public static boolean equalSansNullability(RelDataType type1, RelDataType type2)
      This is a poorman's equalSansNullability(RelDataTypeFactory, RelDataType, RelDataType).

      We assume that "not null" is represented in the type's digest as a trailing "NOT NULL" (case sensitive).

      If you got a type factory, equalSansNullability(RelDataTypeFactory, RelDataType, RelDataType) is preferred.

      Parameters:
      type1 - First type
      type2 - Second type
      Returns:
      true if the types are equal or the only difference is nullability
    • equalAsCollectionSansNullability

      public static boolean equalAsCollectionSansNullability(RelDataTypeFactory factory, RelDataType type1, RelDataType type2)
      Returns whether two collection types are equal, ignoring nullability.

      They need not come from the same factory.

      Parameters:
      factory - Type factory
      type1 - First type
      type2 - Second type
      Returns:
      Whether types are equal, ignoring nullability
    • equalAsMapSansNullability

      public static boolean equalAsMapSansNullability(RelDataTypeFactory factory, RelDataType type1, RelDataType type2)
      Returns whether two map types are equal, ignoring nullability.

      They need not come from the same factory.

      Parameters:
      factory - Type factory
      type1 - First type
      type2 - Second type
      Returns:
      Whether types are equal, ignoring nullability
    • equalAsStructSansNullability

      public static boolean equalAsStructSansNullability(RelDataTypeFactory factory, RelDataType type1, RelDataType type2, @Nullable SqlNameMatcher nameMatcher)
      Returns whether two struct types are equal, ignoring nullability.

      They do not need to come from the same factory.

      Parameters:
      factory - Type factory
      type1 - First type
      type2 - Second type
      nameMatcher - Name matcher used to compare the field names, if null, the field names are also ignored
      Returns:
      Whether types are equal, ignoring nullability
    • findField

      public static int findField(RelDataType type, String fieldName)
      Returns the ordinal of a given field in a record type, or -1 if the field is not found.

      The fieldName is always simple, if the field is nested within a record field, returns index of the outer field instead. i.g. for row type (a int, b (b1 bigint, b2 varchar(20) not null)), returns 1 for both simple name "b1" and "b2".

      Parameters:
      type - Record type
      fieldName - Name of field
      Returns:
      Ordinal of field
    • projectTypes

      public static List<RelDataType> projectTypes(RelDataType rowType, List<? extends Number> requiredFields)
      Selects data types of the specified fields from an input row type. This is useful when identifying data types of a function that is going to operate on inputs that are specified as field ordinals (e.g. aggregate calls).
      Parameters:
      rowType - input row type
      requiredFields - ordinals of the projected fields
      Returns:
      list of data types that are requested by requiredFields
    • createEmptyStructType

      public static RelDataType createEmptyStructType(RelDataTypeFactory typeFactory)
      Records a struct type with no fields.
      Parameters:
      typeFactory - Type factory
      Returns:
      Struct type with no fields
    • isFlat

      public static boolean isFlat(RelDataType type)
      Returns whether a type is flat. It is not flat if it is a record type that has one or more fields that are themselves record types.
    • isComparable

      public static boolean isComparable(RelDataType type1, RelDataType type2)
      Returns whether two types are comparable. They need to be scalar types of the same family, or struct types whose fields are pairwise comparable.
      Parameters:
      type1 - First type
      type2 - Second type
      Returns:
      Whether types are comparable
    • leastRestrictiveForComparison

      public static @Nullable RelDataType leastRestrictiveForComparison(RelDataTypeFactory typeFactory, RelDataType type1, RelDataType type2)
      Returns the least restrictive type T, such that a value of type T can be compared with values of type type1 and type2 using =.
    • family

      protected static RelDataTypeFamily family(RelDataType type)
    • areSameFamily

      public static boolean areSameFamily(Iterable<RelDataType> types)
      Returns whether all types in a collection have the same family, as determined by isSameFamily(RelDataType, RelDataType).
      Parameters:
      types - Types to check
      Returns:
      true if all types are of the same family
    • isUnicode

      public static boolean isUnicode(RelDataType type)
      Checks whether a type represents Unicode character data.
      Parameters:
      type - type to test
      Returns:
      whether type represents Unicode character data
    • maxPrecision

      public static int maxPrecision(int p0, int p1)
      Returns the larger of two precisions, treating RelDataType.PRECISION_NOT_SPECIFIED as infinity.
    • comparePrecision

      public static int comparePrecision(int p0, int p1)
      Returns whether a precision is greater or equal than another, treating RelDataType.PRECISION_NOT_SPECIFIED as infinity.
    • isArray

      public static boolean isArray(RelDataType type)
      Returns whether a type is ARRAY.
    • isRow

      public static boolean isRow(RelDataType type)
      Returns whether a type is ROW.
    • isMap

      public static boolean isMap(RelDataType type)
      Returns whether a type is MAP.
    • isMultiset

      public static boolean isMultiset(RelDataType type)
      Returns whether a type is MULTISET.
    • isCollection

      public static boolean isCollection(RelDataType type)
      Returns whether a type is ARRAY or MULTISET.
    • isCharacter

      public static boolean isCharacter(RelDataType type)
      Returns whether a type is CHARACTER.
    • hasCharactor

      @Deprecated public static boolean hasCharactor(RelDataType type)
      Deprecated.
      Returns whether a type is a CHARACTER or contains a CHARACTER type.
    • hasCharacter

      public static boolean hasCharacter(RelDataType type)
      Returns whether a type is a CHARACTER or contains a CHARACTER type.
    • isString

      public static boolean isString(RelDataType type)
      Returns whether a type is STRING.
    • isBoolean

      public static boolean isBoolean(RelDataType type)
      Returns whether a type is BOOLEAN.
    • isBinary

      public static boolean isBinary(RelDataType type)
      Returns whether a type is BINARY.
    • isAtomic

      public static boolean isAtomic(RelDataType type)
      Returns whether a type is atomic (datetime, numeric, string or BOOLEAN).
    • getMaxPrecisionScaleDecimal

      public static RelDataType getMaxPrecisionScaleDecimal(RelDataTypeFactory factory)
      Returns a DECIMAL type with the maximum precision for the current type system.
    • extractLastNFields

      public static RelDataType extractLastNFields(RelDataTypeFactory typeFactory, RelDataType type, int numToKeep)
      Keeps only the last N fields and returns the new struct type.
    • isValidDecimalValue

      public static boolean isValidDecimalValue(@Nullable BigDecimal value, RelDataType toType)
      Returns whether the decimal value is valid for the type. For example, 1111.11 is not valid for DECIMAL(3, 1) since it overflows.
      Parameters:
      value - Value of literal
      toType - Type of the literal
      Returns:
      whether the value is valid for the type