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

The following examples show how to use org.apache.calcite.rel.type.RelDataType#isNullable() . 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: calcite   File: SqlJsonObjectFunction.java    License: Apache License 2.0 6 votes vote down vote up
@Override public boolean checkOperandTypes(SqlCallBinding callBinding,
    boolean throwOnFailure) {
  final int count = callBinding.getOperandCount();
  for (int i = 1; i < count; i += 2) {
    RelDataType nameType = callBinding.getOperandType(i);
    if (!SqlTypeUtil.inCharFamily(nameType)) {
      if (throwOnFailure) {
        throw callBinding.newError(RESOURCE.expectedCharacter());
      }
      return false;
    }
    if (nameType.isNullable()) {
      if (throwOnFailure) {
        throw callBinding.newError(
            RESOURCE.argumentMustNotBeNull(
                callBinding.operand(i).toString()));
      }
      return false;
    }
  }
  return true;
}
 
Example 2
Source Project: Bats   File: SqlJsonObjectFunction.java    License: Apache License 2.0 6 votes vote down vote up
@Override public boolean checkOperandTypes(SqlCallBinding callBinding,
    boolean throwOnFailure) {
  final int count = callBinding.getOperandCount();
  for (int i = 1; i < count; i += 2) {
    RelDataType nameType = callBinding.getOperandType(i);
    if (!SqlTypeUtil.inCharFamily(nameType)) {
      if (throwOnFailure) {
        throw callBinding.newError(RESOURCE.expectedCharacter());
      }
      return false;
    }
    if (nameType.isNullable()) {
      if (throwOnFailure) {
        throw callBinding.newError(
            RESOURCE.argumentMustNotBeNull(
                callBinding.operand(i).toString()));
      }
      return false;
    }
  }
  return true;
}
 
Example 3
Source Project: Bats   File: SqlDotOperator.java    License: Apache License 2.0 6 votes vote down vote up
@Override public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
  final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
  final RelDataType recordType = opBinding.getOperandType(0);
  switch (recordType.getSqlTypeName()) {
  case ROW:
    final String fieldName =
        opBinding.getOperandLiteralValue(1, String.class);
    final RelDataType type = opBinding.getOperandType(0)
        .getField(fieldName, false, false)
        .getType();
    if (recordType.isNullable()) {
      return typeFactory.createTypeWithNullability(type, true);
    } else {
      return type;
    }
  default:
    throw new AssertionError();
  }
}
 
Example 4
Source Project: calcite   File: SqlDotOperator.java    License: Apache License 2.0 6 votes vote down vote up
@Override public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
  final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
  final RelDataType recordType = opBinding.getOperandType(0);
  switch (recordType.getSqlTypeName()) {
  case ROW:
    final String fieldName =
        opBinding.getOperandLiteralValue(1, String.class);
    final RelDataType type = opBinding.getOperandType(0)
        .getField(fieldName, false, false)
        .getType();
    if (recordType.isNullable()) {
      return typeFactory.createTypeWithNullability(type, true);
    } else {
      return type;
    }
  default:
    throw new AssertionError();
  }
}
 
Example 5
private static List<FieldType> getFields(RelNode relNode) {
    RelDataType rowType = relNode.getRowType();
    List<RelDataTypeField> fieldList = rowType.getFieldList();
    ArrayList<FieldType> fieldSchemas = new ArrayList<>(fieldList.size());
    for (RelDataTypeField relDataTypeField : fieldList) {
        String name = relDataTypeField.getName();
        RelDataType type = relDataTypeField.getType();
        SqlTypeName sqlTypeName = type.getSqlTypeName();
        boolean nullable = type.isNullable();
        Integer precision = null;
        Integer scale = null;
        if (sqlTypeName.allowsPrec()) {
            precision = type.getPrecision();
        }
        if (sqlTypeName.allowsScale()) {
            scale = type.getScale();
        }
        fieldSchemas.add(new FieldType(name, ExprExplain.type(sqlTypeName), nullable, precision, scale));
    }
    return fieldSchemas;
}
 
Example 6
Source Project: dremio-oss   File: TypeInferenceUtils.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
  final RelDataTypeFactory factory = opBinding.getTypeFactory();

  boolean isNullable = true;
  int precision = 0;
  for(RelDataType relDataType : opBinding.collectOperandTypes()) {
    if(!relDataType.isNullable()) {
      isNullable = false;
    }

    // If the underlying columns cannot offer information regarding the precision (i.e., the length) of the VarChar,
    // Dremio uses the largest to represent it
    if(relDataType.getPrecision() == TypeHelper.VARCHAR_DEFAULT_CAST_LEN
        || relDataType.getPrecision() == RelDataType.PRECISION_NOT_SPECIFIED) {
      precision = TypeHelper.VARCHAR_DEFAULT_CAST_LEN;
    } else {
      precision += relDataType.getPrecision();
    }
  }

  return factory.createTypeWithNullability(
      factory.createSqlType(SqlTypeName.VARCHAR, precision),
      isNullable);
}
 
Example 7
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 8
Source Project: Bats   File: RelStructuredTypeFlattener.java    License: Apache License 2.0 5 votes vote down vote up
private RexNode restructure(RelDataType structuredType) {
    // Access null indicator for entire structure.
    RexInputRef nullIndicator = RexInputRef.of(iRestructureInput++, flattenedRootType.getFieldList());

    // Use NEW to put flattened data back together into a structure.
    List<RexNode> inputExprs = restructureFields(structuredType);
    RexNode newInvocation = rexBuilder.makeNewInvocation(structuredType, inputExprs);

    if (!structuredType.isNullable()) {
        // Optimize away the null test.
        return newInvocation;
    }

    // Construct a CASE expression to handle the structure-level null
    // indicator.
    RexNode[] caseOperands = new RexNode[3];

    // WHEN StructuredType.Indicator IS NULL
    caseOperands[0] = rexBuilder.makeCall(SqlStdOperatorTable.IS_NULL, nullIndicator);

    // THEN CAST(NULL AS StructuredType)
    caseOperands[1] = rexBuilder.makeCast(structuredType, rexBuilder.constantNull());

    // ELSE NEW StructuredType(inputs...) END
    caseOperands[2] = newInvocation;

    return rexBuilder.makeCall(SqlStdOperatorTable.CASE, caseOperands);
}
 
Example 9
Source Project: calcite   File: EnumUtils.java    License: Apache License 2.0 5 votes vote down vote up
static Type toInternal(RelDataType type, boolean forceNotNull) {
  switch (type.getSqlTypeName()) {
  case DATE:
  case TIME:
    return type.isNullable() && !forceNotNull ? Integer.class : int.class;
  case TIMESTAMP:
    return type.isNullable() && !forceNotNull ? Long.class : long.class;
  default:
    return null; // we don't care; use the default storage type
  }
}
 
Example 10
Source Project: Flink-CEPplus   File: SqlValidatorImpl.java    License: Apache License 2.0 5 votes vote down vote up
/** Moves fields according to the permutation. */
public void permute(List<SqlNode> selectItems,
	List<Map.Entry<String, RelDataType>> fields) {
	if (trivial) {
		return;
	}

	final List<SqlNode> oldSelectItems = ImmutableList.copyOf(selectItems);
	selectItems.clear();
	final List<Map.Entry<String, RelDataType>> oldFields =
		ImmutableList.copyOf(fields);
	fields.clear();
	for (ImmutableIntList source : sources) {
		final int p0 = source.get(0);
		Map.Entry<String, RelDataType> field = oldFields.get(p0);
		final String name = field.getKey();
		RelDataType type = field.getValue();
		SqlNode selectItem = oldSelectItems.get(p0);
		for (int p1 : Util.skip(source)) {
			final Map.Entry<String, RelDataType> field1 = oldFields.get(p1);
			final SqlNode selectItem1 = oldSelectItems.get(p1);
			final RelDataType type1 = field1.getValue();
			// output is nullable only if both inputs are
			final boolean nullable = type.isNullable() && type1.isNullable();
			final RelDataType type2 =
				SqlTypeUtil.leastRestrictiveForComparison(typeFactory, type,
					type1);
			selectItem =
				SqlStdOperatorTable.AS.createCall(SqlParserPos.ZERO,
					SqlStdOperatorTable.COALESCE.createCall(SqlParserPos.ZERO,
						maybeCast(selectItem, type, type2),
						maybeCast(selectItem1, type1, type2)),
					new SqlIdentifier(name, SqlParserPos.ZERO));
			type = typeFactory.createTypeWithNullability(type2, nullable);
		}
		fields.add(Pair.of(name, type));
		selectItems.add(selectItem);
	}
}
 
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: quark   File: PlanExecutor.java    License: Apache License 2.0 5 votes vote down vote up
private ColumnMetaData metaData(JavaTypeFactory typeFactory, int ordinal,
                                String fieldName, RelDataType type, RelDataType fieldType,
                                List<String> origins) {
  final ColumnMetaData.AvaticaType avaticaType =
      avaticaType(typeFactory, type, fieldType);
  return new ColumnMetaData(
      ordinal,
      false,
      true,
      false,
      false,
      type.isNullable()
          ? DatabaseMetaData.columnNullable
          : DatabaseMetaData.columnNoNulls,
      true,
      type.getPrecision(),
      fieldName,
      origin(origins, 0),
      origin(origins, 2),
      getPrecision(type),
      getScale(type),
      origin(origins, 1),
      null,
      avaticaType,
      true,
      false,
      false,
      avaticaType.columnClassName());
}
 
Example 13
Source Project: Bats   File: RelOptUtil.java    License: Apache License 2.0 5 votes vote down vote up
void accept(RelDataType type) {
    if (type.isStruct()) {
        final List<RelDataTypeField> fields = type.getFieldList();

        // RECORD (
        // I INTEGER NOT NULL,
        // J VARCHAR(240))
        pw.println("RECORD (");
        String prevIndent = indent;
        this.indent = indent + extraIndent;
        acceptFields(fields);
        this.indent = prevIndent;
        pw.print(")");
        if (!type.isNullable()) {
            pw.print(" NOT NULL");
        }
    } else if (type instanceof MultisetSqlType) {
        // E.g. "INTEGER NOT NULL MULTISET NOT NULL"
        accept(type.getComponentType());
        pw.print(" MULTISET");
        if (!type.isNullable()) {
            pw.print(" NOT NULL");
        }
    } else {
        // E.g. "INTEGER" E.g. "VARCHAR(240) CHARACTER SET "ISO-8859-1"
        // COLLATE "ISO-8859-1$en_US$primary" NOT NULL"
        pw.print(type.getFullTypeString());
    }
}
 
Example 14
Source Project: Bats   File: RexBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a reference to all the fields in the row.
 *
 * <p>For example, if the input row has type <code>T{f0,f1,f2,f3,f4}</code>
 * then <code>makeRangeReference(T{f0,f1,f2,f3,f4}, S{f3,f4}, 3)</code> is
 * an expression which yields the last 2 fields.
 *
 * @param type     Type of the resulting range record.
 * @param offset   Index of first field.
 * @param nullable Whether the record is nullable.
 */
public RexRangeRef makeRangeReference(
    RelDataType type,
    int offset,
    boolean nullable) {
  if (nullable && !type.isNullable()) {
    type =
        typeFactory.createTypeWithNullability(
            type,
            nullable);
  }
  return rexFactory.makeRangeReference(type, offset);
}
 
Example 15
/**
 * Converts arguments from {@link org.apache.calcite.sql.SqlNode} to
 * java object format.
 *
 * @param typeFactory type factory used to convert the arguments
 * @param operandList input arguments
 * @param function target function to get parameter types from
 * @param opName name of the operator to use in error message
 * @param failOnNonLiteral true when conversion should fail on non-literal
 * @return converted list of arguments
 */
public static List<Object> convertArguments(RelDataTypeFactory typeFactory,
    List<SqlNode> operandList, Function function,
    SqlIdentifier opName,
    boolean failOnNonLiteral) {
  List<Object> arguments = new ArrayList<>(operandList.size());
  // Construct a list of arguments, if they are all constants.
  for (Pair<FunctionParameter, SqlNode> pair
      : Pair.zip(function.getParameters(), operandList)) {
    try {
      final Object o = getValue(pair.right);
      final Object o2 = coerce(o, pair.left.getType(typeFactory));
      arguments.add(o2);
    } catch (NonLiteralException e) {
      if (failOnNonLiteral) {
        throw new IllegalArgumentException("All arguments of call to macro "
            + opName + " should be literal. Actual argument #"
            + pair.left.getOrdinal() + " (" + pair.left.getName()
            + ") is not literal: " + pair.right);
      }
      final RelDataType type = pair.left.getType(typeFactory);
      final Object value;
      if (type.isNullable()) {
        value = null;
      } else {
        value = 0L;
      }
      arguments.add(value);
    }
  }
  return arguments;
}
 
Example 16
Source Project: Bats   File: View.java    License: Apache License 2.0 5 votes vote down vote up
public Field(String name, RelDataType dataType) {
  this.name = name;
  this.type = dataType.getSqlTypeName();
  this.isNullable = dataType.isNullable();
  this.intervalQualifier = dataType.getIntervalQualifier();
  switch (dataType.getSqlTypeName()) {
    case CHAR:
    case BINARY:
    case VARBINARY:
    case VARCHAR:
      this.precision = dataType.getPrecision();
      break;
    case DECIMAL:
      this.precision = dataType.getPrecision();
      this.scale = dataType.getScale();
      break;
    case INTERVAL_YEAR:
    case INTERVAL_YEAR_MONTH:
    case INTERVAL_MONTH:
    case INTERVAL_DAY:
    case INTERVAL_DAY_HOUR:
    case INTERVAL_DAY_MINUTE:
    case INTERVAL_DAY_SECOND:
    case INTERVAL_HOUR:
    case INTERVAL_HOUR_MINUTE:
    case INTERVAL_HOUR_SECOND:
    case INTERVAL_MINUTE:
    case INTERVAL_MINUTE_SECOND:
    case INTERVAL_SECOND:
      this.precision = dataType.getIntervalQualifier().getStartPrecisionPreservingDefault();
      break;
    case MAP:
      keyType = new Field(dataType.getKeyType());
      valueType = new Field(dataType.getValueType());
      break;
  }
}
 
Example 17
Source Project: calcite   File: RexToTestCodeShuttle.java    License: Apache License 2.0 5 votes vote down vote up
@Override public String visitFieldAccess(RexFieldAccess fieldAccess) {
  StringBuilder sb = new StringBuilder();
  sb.append("v");
  RelDataType type = fieldAccess.getType();
  appendSqlType(sb, type);
  if (!type.isNullable()) {
    sb.append("NotNull");
  }
  sb.append("(");
  sb.append(fieldAccess.getField().getIndex() % 10);
  sb.append(")");
  return sb.toString();
}
 
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: Bats   File: TypeInferenceUtils.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
  RelDataTypeFactory factory = opBinding.getTypeFactory();
  // operands count ond order is checked at parsing stage
  RelDataType inputType = opBinding.getOperandType(2);
  boolean isNullable = inputType.isNullable() || opBinding.getOperandType(1).isNullable();

  SqlTypeName inputTypeName = inputType.getSqlTypeName();

  TimeUnit qualifier = ((SqlLiteral) ((SqlCallBinding) opBinding).operand(0)).getValueAs(TimeUnit.class);

  SqlTypeName sqlTypeName;

  // follow up with type inference of reduced expression
  switch (qualifier) {
    case DAY:
    case WEEK:
    case MONTH:
    case QUARTER:
    case YEAR:
    case NANOSECOND:  // NANOSECOND is not supported by Calcite SqlTimestampAddFunction.
                      // Once it is fixed, NANOSECOND should be moved to the group below.
      sqlTypeName = inputTypeName;
      break;
    case MICROSECOND:
    case MILLISECOND:
      // precision should be specified for MICROSECOND and MILLISECOND
      return factory.createTypeWithNullability(
          factory.createSqlType(SqlTypeName.TIMESTAMP, 3),
          isNullable);
    case SECOND:
    case MINUTE:
    case HOUR:
      if (inputTypeName == SqlTypeName.TIME) {
        sqlTypeName = SqlTypeName.TIME;
      } else {
        sqlTypeName = SqlTypeName.TIMESTAMP;
      }
      break;
    default:
      sqlTypeName = SqlTypeName.ANY;
  }

  // preserves precision of input type if it was specified
  if (inputType.getSqlTypeName().allowsPrecNoScale()) {
    RelDataType type = factory.createSqlType(sqlTypeName, inputType.getPrecision());
    return factory.createTypeWithNullability(type, isNullable);
  }
  return createCalciteTypeWithNullability(
      opBinding.getTypeFactory(),
      sqlTypeName,
      isNullable);
}
 
Example 20
Source Project: calcite   File: RexBuilder.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Creates a literal whose value is NULL, with a particular type.
 *
 * <p>The typing is necessary because RexNodes are strictly typed. For
 * example, in the Rex world the <code>NULL</code> parameter to <code>
 * SUBSTRING(NULL FROM 2 FOR 4)</code> must have a valid VARCHAR type so
 * that the result type can be determined.
 *
 * @param type Type to cast NULL to
 * @return NULL literal of given type
 */
public RexLiteral makeNullLiteral(RelDataType type) {
  if (!type.isNullable()) {
    type = typeFactory.createTypeWithNullability(type, true);
  }
  return (RexLiteral) makeCast(type, constantNull);
}