Java Code Examples for org.apache.calcite.rel.type.RelDataType#equals()

The following examples show how to use org.apache.calcite.rel.type.RelDataType#equals() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: Bats   File: SqlTypeUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns whether two types are equal, ignoring nullability.
 *
 * <p>They need not come from the same factory.
 *
 * @param factory Type factory
 * @param type1   First type
 * @param type2   Second type
 * @return whether types are equal, ignoring nullability
 */
public static boolean equalSansNullability(
    RelDataTypeFactory factory,
    RelDataType type1,
    RelDataType type2) {
  if (type1.equals(type2)) {
    return true;
  }

  if (type1.isNullable() == type2.isNullable()) {
    // If types have the same nullability and they weren't equal above,
    // they must be different.
    return false;
  }
  return type1.equals(
      factory.createTypeWithNullability(type2, type1.isNullable()));
}
 
Example 2
Source Project: Bats   File: RexUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Generates a cast for a row type.
 *
 * @param rexBuilder RexBuilder to use for constructing casts
 * @param lhsRowType target row type
 * @param rhsExps    expressions to be cast
 * @return cast expressions
 */
public static List<RexNode> generateCastExpressions(RexBuilder rexBuilder, RelDataType lhsRowType,
        List<RexNode> rhsExps) {
    List<RelDataTypeField> lhsFields = lhsRowType.getFieldList();
    List<RexNode> castExps = new ArrayList<>();
    for (Pair<RelDataTypeField, RexNode> pair : Pair.zip(lhsFields, rhsExps, true)) {
        RelDataTypeField lhsField = pair.left;
        RelDataType lhsType = lhsField.getType();
        final RexNode rhsExp = pair.right;
        RelDataType rhsType = rhsExp.getType();
        if (lhsType.equals(rhsType)) {
            castExps.add(rhsExp);
        } else {
            castExps.add(rexBuilder.makeCast(lhsType, rhsExp));
        }
    }
    return castExps;
}
 
Example 3
Source Project: calcite   File: RexUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Generates a cast for a row type.
 *
 * @param rexBuilder RexBuilder to use for constructing casts
 * @param lhsRowType target row type
 * @param rhsExps    expressions to be cast
 * @return cast expressions
 */
public static List<RexNode> generateCastExpressions(
    RexBuilder rexBuilder,
    RelDataType lhsRowType,
    List<RexNode> rhsExps) {
  List<RelDataTypeField> lhsFields = lhsRowType.getFieldList();
  List<RexNode> castExps = new ArrayList<>();
  for (Pair<RelDataTypeField, RexNode> pair
      : Pair.zip(lhsFields, rhsExps, true)) {
    RelDataTypeField lhsField = pair.left;
    RelDataType lhsType = lhsField.getType();
    final RexNode rhsExp = pair.right;
    RelDataType rhsType = rhsExp.getType();
    if (lhsType.equals(rhsType)) {
      castExps.add(rhsExp);
    } else {
      castExps.add(rexBuilder.makeCast(lhsType, rhsExp));
    }
  }
  return castExps;
}
 
Example 4
Source Project: calcite   File: SqlTypeUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns whether two types are equal, ignoring nullability.
 *
 * <p>They need not come from the same factory.
 *
 * @param factory Type factory
 * @param type1   First type
 * @param type2   Second type
 * @return whether types are equal, ignoring nullability
 */
public static boolean equalSansNullability(
    RelDataTypeFactory factory,
    RelDataType type1,
    RelDataType type2) {
  if (type1.equals(type2)) {
    return true;
  }

  if (type1.isNullable() == type2.isNullable()) {
    // If types have the same nullability and they weren't equal above,
    // they must be different.
    return false;
  }
  return type1.equals(
      factory.createTypeWithNullability(type2, type1.isNullable()));
}
 
Example 5
Source Project: calcite   File: RelOptUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns whether two types are equal using 'equals'.
 *
 * @param desc1 Description of first type
 * @param type1 First type
 * @param desc2 Description of second type
 * @param type2 Second type
 * @param litmus What to do if an error is detected (types are not equal)
 * @return Whether the types are equal
 */
public static boolean eq(
    final String desc1,
    RelDataType type1,
    final String desc2,
    RelDataType type2,
    Litmus litmus) {
  // if any one of the types is ANY return true
  if (type1.getSqlTypeName() == SqlTypeName.ANY
      || type2.getSqlTypeName() == SqlTypeName.ANY) {
    return litmus.succeed();
  }

  if (!type1.equals(type2)) {
    return litmus.fail("type mismatch:\n{}:\n{}\n{}:\n{}",
        desc1, type1.getFullTypeString(),
        desc2, type2.getFullTypeString());
  }
  return litmus.succeed();
}
 
Example 6
Source Project: Bats   File: ReduceExpressionsRule.java    License: Apache License 2.0 5 votes vote down vote up
private void reduceCasts(RexCall outerCast) {
  List<RexNode> operands = outerCast.getOperands();
  if (operands.size() != 1) {
    return;
  }
  RelDataType outerCastType = outerCast.getType();
  RelDataType operandType = operands.get(0).getType();
  if (operandType.equals(outerCastType)) {
    removableCasts.add(outerCast);
    return;
  }

  // See if the reduction
  // CAST((CAST x AS type) AS type NOT NULL)
  // -> CAST(x AS type NOT NULL)
  // applies.  TODO jvs 15-Dec-2008:  consider
  // similar cases for precision changes.
  if (!(operands.get(0) instanceof RexCall)) {
    return;
  }
  RexCall innerCast = (RexCall) operands.get(0);
  if (innerCast.getOperator() != SqlStdOperatorTable.CAST) {
    return;
  }
  if (innerCast.getOperands().size() != 1) {
    return;
  }
  RelDataType outerTypeNullable =
      typeFactory.createTypeWithNullability(outerCastType, true);
  RelDataType innerTypeNullable =
      typeFactory.createTypeWithNullability(operandType, true);
  if (outerTypeNullable != innerTypeNullable) {
    return;
  }
  if (operandType.isNullable()) {
    removableCasts.add(innerCast);
  }
}
 
Example 7
Source Project: Bats   File: TableNamespace.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Ensures that extended columns that have the same name as a base column also
 * have the same data-type.
 */
private void checkExtendedColumnTypes(SqlNodeList extendList) {
  final List<RelDataTypeField> extendedFields =
      SqlValidatorUtil.getExtendedColumns(
          validator.getTypeFactory(), table, extendList);
  final List<RelDataTypeField> baseFields =
      getBaseRowType().getFieldList();
  final Map<String, Integer> nameToIndex =
      SqlValidatorUtil.mapNameToIndex(baseFields);

  for (final RelDataTypeField extendedField : extendedFields) {
    final String extFieldName = extendedField.getName();
    if (nameToIndex.containsKey(extFieldName)) {
      final Integer baseIndex = nameToIndex.get(extFieldName);
      final RelDataType baseType = baseFields.get(baseIndex).getType();
      final RelDataType extType = extendedField.getType();

      if (!extType.equals(baseType)) {
        // Get the extended column node that failed validation.
        final SqlNode extColNode =
            Iterables.find(extendList.getList(),
                sqlNode -> sqlNode instanceof SqlIdentifier
                    && Util.last(((SqlIdentifier) sqlNode).names).equals(
                        extendedField.getName()));

        throw validator.getValidationErrorFunction().apply(extColNode,
            RESOURCE.typeNotAssignable(
                baseFields.get(baseIndex).getName(), baseType.getFullTypeString(),
                extendedField.getName(), extType.getFullTypeString()));
      }
    }
  }
}
 
Example 8
Source Project: Bats   File: RelOptUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean areRowTypesEqual(RelDataType rowType1, RelDataType rowType2, boolean compareNames) {
    if (rowType1 == rowType2) {
        return true;
    }
    if (compareNames) {
        // if types are not identity-equal, then either the names or
        // the types must be different
        return false;
    }
    if (rowType2.getFieldCount() != rowType1.getFieldCount()) {
        return false;
    }
    final List<RelDataTypeField> f1 = rowType1.getFieldList();
    final List<RelDataTypeField> f2 = rowType2.getFieldList();
    for (Pair<RelDataTypeField, RelDataTypeField> pair : Pair.zip(f1, f2)) {
        final RelDataType type1 = pair.left.getType();
        final RelDataType type2 = pair.right.getType();
        // If one of the types is ANY comparison should succeed
        if (type1.getSqlTypeName() == SqlTypeName.ANY || type2.getSqlTypeName() == SqlTypeName.ANY) {
            continue;
        }
        if (!type1.equals(type2)) {
            return false;
        }
    }
    return true;
}
 
Example 9
Source Project: Flink-CEPplus   File: SqlValidatorImpl.java    License: Apache License 2.0 5 votes vote down vote up
private SqlNode maybeCast(SqlNode node, RelDataType currentType,
	RelDataType desiredType) {
	return currentType.equals(desiredType)
		|| (currentType.isNullable() != desiredType.isNullable()
			    && typeFactory.createTypeWithNullability(currentType,
		desiredType.isNullable()).equals(desiredType))
		? node
		: SqlStdOperatorTable.CAST.createCall(SqlParserPos.ZERO,
		node, SqlTypeUtil.convertTypeToSpec(desiredType));
}
 
Example 10
Source Project: calcite   File: RexUtil.java    License: Apache License 2.0 5 votes vote down vote up
@Override public RexNode visitInputRef(RexInputRef ref) {
  final RelDataType rightType = typeList.get(ref.getIndex());
  final RelDataType refType = ref.getType();
  if (refType.equals(rightType)) {
    return ref;
  }
  final RelDataType refType2 =
      rexBuilder.getTypeFactory().createTypeWithNullability(refType,
          rightType.isNullable());
  if (refType2.equals(rightType)) {
    return new RexInputRef(ref.getIndex(), refType2);
  }
  throw new AssertionError("mismatched type " + ref + " " + rightType);
}
 
Example 11
Source Project: flink   File: SqlValidatorImpl.java    License: Apache License 2.0 5 votes vote down vote up
private SqlNode maybeCast(SqlNode node, RelDataType currentType,
	RelDataType desiredType) {
	return currentType.equals(desiredType)
		|| (currentType.isNullable() != desiredType.isNullable()
			    && typeFactory.createTypeWithNullability(currentType,
		desiredType.isNullable()).equals(desiredType))
		? node
		: SqlStdOperatorTable.CAST.createCall(SqlParserPos.ZERO,
		node, SqlTypeUtil.convertTypeToSpec(desiredType));
}
 
Example 12
Source Project: flink   File: SqlValidatorImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Saves the type of a {@link SqlNode}, now that it has been validated.
 *
 * <p>Unlike the base class method, this method is not deprecated.
 * It is available from within Calcite, but is not part of the public API.
 *
 * @param node A SQL parse tree node, never null
 * @param type Its type; must not be null
 */
@SuppressWarnings("deprecation")
public final void setValidatedNodeType(SqlNode node, RelDataType type) {
	Objects.requireNonNull(type);
	Objects.requireNonNull(node);
	if (type.equals(unknownType)) {
		// don't set anything until we know what it is, and don't overwrite
		// a known type with the unknown type
		return;
	}
	nodeToTypeMap.put(node, type);
}
 
Example 13
Source Project: calcite   File: TypeCoercionTest.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean contains(List<RelDataType> types, RelDataType type) {
  for (RelDataType type1 : types) {
    if (type1.equals(type)
        || type1.getSqlTypeName().getFamily() == type.getSqlTypeName().getFamily()) {
      return true;
    }
  }
  return false;
}
 
Example 14
Source Project: dremio-oss   File: MoreRelOptUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that two data types match.
 * @param dataType1          data type for comparison
 * @param dataType2          data type for comparison
 * @param sqlTypeNameOnly    boolean for only SqlTypeName match
 *
 * @return boolean indicating that data types are equivalent
 */
public static boolean areDataTypesEqual(
  RelDataType dataType1,
  RelDataType dataType2,
  boolean sqlTypeNameOnly) {
  if (sqlTypeNameOnly) {
    return dataType1.getSqlTypeName().equals(dataType2.getSqlTypeName());
  }
  return dataType1.equals(dataType2);
}
 
Example 15
Source Project: calcite   File: TableNamespace.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Ensures that extended columns that have the same name as a base column also
 * have the same data-type.
 */
private void checkExtendedColumnTypes(SqlNodeList extendList) {
  final List<RelDataTypeField> extendedFields =
      SqlValidatorUtil.getExtendedColumns(validator, table, extendList);
  final List<RelDataTypeField> baseFields =
      getBaseRowType().getFieldList();
  final Map<String, Integer> nameToIndex =
      SqlValidatorUtil.mapNameToIndex(baseFields);

  for (final RelDataTypeField extendedField : extendedFields) {
    final String extFieldName = extendedField.getName();
    if (nameToIndex.containsKey(extFieldName)) {
      final Integer baseIndex = nameToIndex.get(extFieldName);
      final RelDataType baseType = baseFields.get(baseIndex).getType();
      final RelDataType extType = extendedField.getType();

      if (!extType.equals(baseType)) {
        // Get the extended column node that failed validation.
        final SqlNode extColNode =
            Iterables.find(extendList.getList(),
                sqlNode -> sqlNode instanceof SqlIdentifier
                    && Util.last(((SqlIdentifier) sqlNode).names).equals(
                        extendedField.getName()));

        throw validator.getValidationErrorFunction().apply(extColNode,
            RESOURCE.typeNotAssignable(
                baseFields.get(baseIndex).getName(), baseType.getFullTypeString(),
                extendedField.getName(), extType.getFullTypeString()));
      }
    }
  }
}
 
Example 16
Source Project: calcite   File: RelOptUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean areRowTypesEqual(
    RelDataType rowType1,
    RelDataType rowType2,
    boolean compareNames) {
  if (rowType1 == rowType2) {
    return true;
  }
  if (compareNames) {
    // if types are not identity-equal, then either the names or
    // the types must be different
    return false;
  }
  if (rowType2.getFieldCount() != rowType1.getFieldCount()) {
    return false;
  }
  final List<RelDataTypeField> f1 = rowType1.getFieldList();
  final List<RelDataTypeField> f2 = rowType2.getFieldList();
  for (Pair<RelDataTypeField, RelDataTypeField> pair : Pair.zip(f1, f2)) {
    final RelDataType type1 = pair.left.getType();
    final RelDataType type2 = pair.right.getType();
    // If one of the types is ANY comparison should succeed
    if (type1.getSqlTypeName() == SqlTypeName.ANY
        || type2.getSqlTypeName() == SqlTypeName.ANY) {
      continue;
    }
    if (!type1.equals(type2)) {
      return false;
    }
  }
  return true;
}
 
Example 17
Source Project: Bats   File: RelMdColumnUniqueness.java    License: Apache License 2.0 4 votes vote down vote up
public Boolean areColumnsUnique(Project rel, RelMetadataQuery mq,
    ImmutableBitSet columns, boolean ignoreNulls) {
  // LogicalProject maps a set of rows to a different set;
  // Without knowledge of the mapping function(whether it
  // preserves uniqueness), it is only safe to derive uniqueness
  // info from the child of a project when the mapping is f(a) => a.
  //
  // Also need to map the input column set to the corresponding child
  // references

  List<RexNode> projExprs = rel.getProjects();
  ImmutableBitSet.Builder childColumns = ImmutableBitSet.builder();
  for (int bit : columns) {
    RexNode projExpr = projExprs.get(bit);
    if (projExpr instanceof RexInputRef) {
      childColumns.set(((RexInputRef) projExpr).getIndex());
    } else if (projExpr instanceof RexCall && ignoreNulls) {
      // If the expression is a cast such that the types are the same
      // except for the nullability, then if we're ignoring nulls,
      // it doesn't matter whether the underlying column reference
      // is nullable.  Check that the types are the same by making a
      // nullable copy of both types and then comparing them.
      RexCall call = (RexCall) projExpr;
      if (call.getOperator() != SqlStdOperatorTable.CAST) {
        continue;
      }
      RexNode castOperand = call.getOperands().get(0);
      if (!(castOperand instanceof RexInputRef)) {
        continue;
      }
      RelDataTypeFactory typeFactory =
          rel.getCluster().getTypeFactory();
      RelDataType castType =
          typeFactory.createTypeWithNullability(
              projExpr.getType(), true);
      RelDataType origType = typeFactory.createTypeWithNullability(
          castOperand.getType(),
          true);
      if (castType.equals(origType)) {
        childColumns.set(((RexInputRef) castOperand).getIndex());
      }
    } else {
      // If the expression will not influence uniqueness of the
      // projection, then skip it.
      continue;
    }
  }

  // If no columns can affect uniqueness, then return unknown
  if (childColumns.cardinality() == 0) {
    return null;
  }

  return mq.areColumnsUnique(rel.getInput(), childColumns.build(),
      ignoreNulls);
}
 
Example 18
Source Project: Bats   File: RexSimplify.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Return if the new type is the same and at most narrows the nullability.
 */
private boolean sameTypeOrNarrowsNullability(RelDataType oldType, RelDataType newType) {
    return oldType.equals(newType)
            || (SqlTypeUtil.equalSansNullability(rexBuilder.typeFactory, oldType, newType) && oldType.isNullable());
}
 
Example 19
Source Project: calcite   File: RelMdColumnUniqueness.java    License: Apache License 2.0 4 votes vote down vote up
private Boolean areProjectColumnsUnique(
    SingleRel rel, RelMetadataQuery mq,
    ImmutableBitSet columns, boolean ignoreNulls, List<RexNode> projExprs) {
  RelDataTypeFactory typeFactory = rel.getCluster().getTypeFactory();
  ImmutableBitSet.Builder childColumns = ImmutableBitSet.builder();
  for (int bit : columns) {
    RexNode projExpr = projExprs.get(bit);
    if (projExpr instanceof RexInputRef) {
      childColumns.set(((RexInputRef) projExpr).getIndex());
    } else if (projExpr instanceof RexCall && ignoreNulls) {
      // If the expression is a cast such that the types are the same
      // except for the nullability, then if we're ignoring nulls,
      // it doesn't matter whether the underlying column reference
      // is nullable.  Check that the types are the same by making a
      // nullable copy of both types and then comparing them.
      RexCall call = (RexCall) projExpr;
      if (call.getOperator() != SqlStdOperatorTable.CAST) {
        continue;
      }
      RexNode castOperand = call.getOperands().get(0);
      if (!(castOperand instanceof RexInputRef)) {
        continue;
      }
      RelDataType castType =
          typeFactory.createTypeWithNullability(
              projExpr.getType(), true);
      RelDataType origType = typeFactory.createTypeWithNullability(
          castOperand.getType(),
          true);
      if (castType.equals(origType)) {
        childColumns.set(((RexInputRef) castOperand).getIndex());
      }
    } else {
      // If the expression will not influence uniqueness of the
      // projection, then skip it.
      continue;
    }
  }

  // If no columns can affect uniqueness, then return unknown
  if (childColumns.cardinality() == 0) {
    return null;
  }

  return mq.areColumnsUnique(rel.getInput(), childColumns.build(),
      ignoreNulls);
}
 
Example 20
/**
 * Checks whether conversion of input {@code TableScan} instance to target
 * {@code TableScan} may be omitted.
 *
 * @param projectRelDataType project rel data type
 * @param scan               TableScan to be checked
 * @return true if specified {@code TableScan} has the same row type as specified.
 */
protected boolean skipScanConversion(RelDataType projectRelDataType, TableScan scan) {
  return projectRelDataType.equals(scan.getRowType());
}