Java Code Examples for org.apache.flink.table.types.logical.DecimalType

The following examples show how to use org.apache.flink.table.types.logical.DecimalType. These examples are extracted from open source projects. 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: flink   Source File: FlinkReturnTypes.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
	final RelDataType numType = opBinding.getOperandType(0);
	if (numType.getSqlTypeName() != SqlTypeName.DECIMAL) {
		return numType;
	}
	final BigDecimal lenVal;
	if (opBinding.getOperandCount() == 1) {
		lenVal = BigDecimal.ZERO;
	} else if (opBinding.getOperandCount() == 2) {
		lenVal = getArg1Literal(opBinding); // may return null
	} else {
		throw new AssertionError();
	}
	if (lenVal == null) {
		return numType; //
	}
	// ROUND( decimal(p,s), r )
	final int p = numType.getPrecision();
	final int s = numType.getScale();
	final int r = lenVal.intValueExact();
	DecimalType dt = FlinkTypeSystem.inferRoundType(p, s, r);
	return opBinding.getTypeFactory().createSqlType(
		SqlTypeName.DECIMAL, dt.getPrecision(), dt.getScale());
}
 
Example 2
Source Project: flink   Source File: AvroRowDataDeserializationSchema.java    License: Apache License 2.0 6 votes vote down vote up
private static DeserializationRuntimeConverter createDecimalConverter(DecimalType decimalType) {
	final int precision = decimalType.getPrecision();
	final int scale = decimalType.getScale();
	return avroObject -> {
		final byte[] bytes;
		if (avroObject instanceof GenericFixed) {
			bytes = ((GenericFixed) avroObject).bytes();
		} else if (avroObject instanceof ByteBuffer) {
			ByteBuffer byteBuffer = (ByteBuffer) avroObject;
			bytes = new byte[byteBuffer.remaining()];
			byteBuffer.get(bytes);
		} else {
			bytes = (byte[]) avroObject;
		}
		return DecimalData.fromUnscaledBytes(bytes, precision, scale);
	};
}
 
Example 3
Source Project: bahir-flink   Source File: KuduTableUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static List<ColumnSchema> toKuduConnectorColumns(List<Tuple2<String, DataType>> columns, Collection<String> keyColumns) {
    return columns.stream()
            .map(t -> {
                        ColumnSchema.ColumnSchemaBuilder builder = new ColumnSchema
                                .ColumnSchemaBuilder(t.f0, KuduTypeUtils.toKuduType(t.f1))
                                .key(keyColumns.contains(t.f0))
                                .nullable(!keyColumns.contains(t.f0) && t.f1.getLogicalType().isNullable());
                        if(t.f1.getLogicalType() instanceof DecimalType) {
                            DecimalType decimalType = ((DecimalType) t.f1.getLogicalType());
                            builder.typeAttributes(new ColumnTypeAttributes.ColumnTypeAttributesBuilder()
                                .precision(decimalType.getPrecision())
                                .scale(decimalType.getScale())
                                .build());
                        }
                        return builder.build();
                    }
            ).collect(Collectors.toList());
}
 
Example 4
Source Project: flink   Source File: FlinkReturnTypes.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
	final RelDataType numType = opBinding.getOperandType(0);
	if (numType.getSqlTypeName() != SqlTypeName.DECIMAL) {
		return numType;
	}
	final BigDecimal lenVal;
	if (opBinding.getOperandCount() == 1) {
		lenVal = BigDecimal.ZERO;
	} else if (opBinding.getOperandCount() == 2) {
		lenVal = getArg1Literal(opBinding); // may return null
	} else {
		throw new AssertionError();
	}
	if (lenVal == null) {
		return numType; //
	}
	// ROUND( decimal(p,s), r )
	final int p = numType.getPrecision();
	final int s = numType.getScale();
	final int r = lenVal.intValueExact();
	DecimalType dt = LogicalTypeMerging.findRoundDecimalType(p, s, r);
	return opBinding.getTypeFactory().createSqlType(
		SqlTypeName.DECIMAL, dt.getPrecision(), dt.getScale());
}
 
Example 5
Source Project: flink   Source File: CsvRowDataSerializationSchema.java    License: Apache License 2.0 5 votes vote down vote up
private RowFieldConverter createDecimalRowFieldConverter(DecimalType decimalType) {
	final int precision = decimalType.getPrecision();
	final int scale = decimalType.getScale();
	return (csvMapper, container, row, pos) -> {
		DecimalData decimal = row.getDecimal(pos, precision, scale);
		return convertDecimal(decimal, container);
	};
}
 
Example 6
Source Project: flink   Source File: LogicalTypeGeneralization.java    License: Apache License 2.0 5 votes vote down vote up
private static LogicalType createCommonExactNumericType(LogicalType resultType, LogicalType type) {
	// same EXACT_NUMERIC types
	if (type.equals(resultType)) {
		return resultType;
	}

	final LogicalTypeRoot resultTypeRoot = resultType.getTypeRoot();
	final LogicalTypeRoot typeRoot = type.getTypeRoot();

	// no DECIMAL types involved
	if (resultTypeRoot != DECIMAL && typeRoot != DECIMAL) {
		// type root contains order of precision
		if (getPrecision(type) > getPrecision(resultType)) {
			return type;
		}
		return resultType;
	}

	// determine DECIMAL with precision (p), scale (s) and number of whole digits (d):
	// d = max(p1 - s1, p2 - s2)
	// s <= max(s1, s2)
	// p = s + d
	final int p1 = getPrecision(resultType);
	final int p2 = getPrecision(type);
	final int s1 = getScale(resultType);
	final int s2 = getScale(type);
	final int maxPrecision = DecimalType.MAX_PRECISION;

	int d = Math.max(p1 - s1, p2 - s2);
	d = Math.min(d, maxPrecision);

	int s = Math.max(s1, s2);
	s = Math.min(s, maxPrecision - d);

	final int p = d + s;

	return new DecimalType(p, s);
}
 
Example 7
Source Project: flink   Source File: LogicalTypesTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDistinctType() {
	testAll(
		createDistinctType("Money"),
		"`cat`.`db`.`Money`",
		"`cat`.`db`.`Money`",
		new Class[]{BigDecimal.class},
		new Class[]{BigDecimal.class},
		new LogicalType[]{new DecimalType(10, 2)},
		createDistinctType("Monetary")
	);
}
 
Example 8
Source Project: flink   Source File: LogicalTypesTest.java    License: Apache License 2.0 5 votes vote down vote up
private DistinctType createDistinctType(String typeName) {
	return new DistinctType.Builder(
			ObjectIdentifier.of("cat", "db", typeName),
			new DecimalType(10, 2))
		.setDescription("Money type desc.")
		.build();
}
 
Example 9
Source Project: flink   Source File: AbstractOrcColumnVector.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a orc vector from partition spec value.
 * See hive {@code VectorizedRowBatchCtx#addPartitionColsToBatch}.
 */
private static ColumnVector createHiveVectorFromConstant(
		LogicalType type, Object value, int batchSize) {
	switch (type.getTypeRoot()) {
		case CHAR:
		case VARCHAR:
		case BINARY:
		case VARBINARY:
			return createBytesVector(batchSize, value);
		case BOOLEAN:
			return createLongVector(batchSize, (Boolean) value ? 1 : 0);
		case TINYINT:
		case SMALLINT:
		case INTEGER:
		case BIGINT:
			return createLongVector(batchSize, value);
		case DECIMAL:
			DecimalType decimalType = (DecimalType) type;
			return createDecimalVector(
					batchSize, decimalType.getPrecision(), decimalType.getScale(), value);
		case FLOAT:
		case DOUBLE:
			return createDoubleVector(batchSize, value);
		case DATE:
			if (value instanceof LocalDate) {
				value = Date.valueOf((LocalDate) value);
			}
			return createLongVector(batchSize, dateToInternal((Date) value));
		case TIMESTAMP_WITHOUT_TIME_ZONE:
			return createTimestampVector(batchSize, value);
		default:
			throw new UnsupportedOperationException("Unsupported type: " + type);
	}
}
 
Example 10
Source Project: flink   Source File: SortCodeGeneratorTest.java    License: Apache License 2.0 5 votes vote down vote up
private Object value2(LogicalType type, Random rnd) {
	switch (type.getTypeRoot()) {
		case BOOLEAN:
			return false;
		case TINYINT:
			return (byte) 0;
		case SMALLINT:
			return (short) 0;
		case INTEGER:
			return 0;
		case BIGINT:
			return 0L;
		case FLOAT:
			return 0f;
		case DOUBLE:
			return 0d;
		case VARCHAR:
			return BinaryString.fromString("0");
		case DECIMAL:
			DecimalType decimalType = (DecimalType) type;
			return Decimal.fromBigDecimal(new BigDecimal(0),
					decimalType.getPrecision(), decimalType.getScale());
		case ARRAY:
		case VARBINARY:
			byte[] bytes = new byte[rnd.nextInt(7) + 10];
			rnd.nextBytes(bytes);
			return type instanceof VarBinaryType ? bytes : BinaryArray.fromPrimitiveArray(bytes);
		case ROW:
			RowType rowType = (RowType) type;
			if (rowType.getFields().get(0).getType().getTypeRoot() == INTEGER) {
				return GenericRow.of(rnd.nextInt());
			} else {
				return GenericRow.of(GenericRow.of(new Object[]{null}));
			}
		case ANY:
			return new BinaryGeneric<>(rnd.nextInt(), IntSerializer.INSTANCE);
		default:
			throw new RuntimeException("Not support!");
	}
}
 
Example 11
Source Project: flink   Source File: SortCodeGeneratorTest.java    License: Apache License 2.0 5 votes vote down vote up
private Object value3(LogicalType type, Random rnd) {
	switch (type.getTypeRoot()) {
		case BOOLEAN:
			return true;
		case TINYINT:
			return Byte.MAX_VALUE;
		case SMALLINT:
			return Short.MAX_VALUE;
		case INTEGER:
			return Integer.MAX_VALUE;
		case BIGINT:
			return Long.MAX_VALUE;
		case FLOAT:
			return Float.MAX_VALUE;
		case DOUBLE:
			return Double.MAX_VALUE;
		case VARCHAR:
			return BinaryString.fromString(RandomStringUtils.random(100));
		case DECIMAL:
			DecimalType decimalType = (DecimalType) type;
			return Decimal.fromBigDecimal(new BigDecimal(Integer.MAX_VALUE),
					decimalType.getPrecision(), decimalType.getScale());
		case ARRAY:
		case VARBINARY:
			byte[] bytes = new byte[rnd.nextInt(100) + 100];
			rnd.nextBytes(bytes);
			return type instanceof VarBinaryType ? bytes : BinaryArray.fromPrimitiveArray(bytes);
		case ROW:
			RowType rowType = (RowType) type;
			if (rowType.getFields().get(0).getType().getTypeRoot() == INTEGER) {
				return GenericRow.of(rnd.nextInt());
			} else {
				return GenericRow.of(GenericRow.of(rnd.nextInt()));
			}
		case ANY:
			return new BinaryGeneric<>(rnd.nextInt(), IntSerializer.INSTANCE);
		default:
			throw new RuntimeException("Not support!");
	}
}
 
Example 12
Source Project: iceberg   Source File: FlinkTypeToType.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("checkstyle:CyclomaticComplexity")
@Override
public Type atomic(AtomicDataType type) {
  LogicalType inner = type.getLogicalType();
  if (inner instanceof VarCharType ||
      inner instanceof CharType) {
    return Types.StringType.get();
  } else if (inner instanceof BooleanType) {
    return Types.BooleanType.get();
  } else if (inner instanceof IntType ||
      inner instanceof SmallIntType ||
      inner instanceof TinyIntType) {
    return Types.IntegerType.get();
  } else if (inner instanceof BigIntType) {
    return Types.LongType.get();
  } else if (inner instanceof VarBinaryType) {
    return Types.BinaryType.get();
  } else if (inner instanceof BinaryType) {
    BinaryType binaryType = (BinaryType) inner;
    return Types.FixedType.ofLength(binaryType.getLength());
  } else if (inner instanceof FloatType) {
    return Types.FloatType.get();
  } else if (inner instanceof DoubleType) {
    return Types.DoubleType.get();
  } else if (inner instanceof DateType) {
    return Types.DateType.get();
  } else if (inner instanceof TimeType) {
    return Types.TimeType.get();
  } else if (inner instanceof TimestampType) {
    return Types.TimestampType.withoutZone();
  } else if (inner instanceof LocalZonedTimestampType) {
    return Types.TimestampType.withZone();
  } else if (inner instanceof DecimalType) {
    DecimalType decimalType = (DecimalType) inner;
    return Types.DecimalType.of(decimalType.getPrecision(), decimalType.getScale());
  } else {
    throw new UnsupportedOperationException("Not a supported type: " + type.toString());
  }
}
 
Example 13
Source Project: flink   Source File: PythonTypeUtils.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public FlinkFnApi.Schema.FieldType visit(DecimalType decimalType) {
	FlinkFnApi.Schema.FieldType.Builder builder =
		FlinkFnApi.Schema.FieldType.newBuilder()
			.setTypeName(FlinkFnApi.Schema.TypeName.DECIMAL)
			.setNullable(decimalType.isNullable());

	FlinkFnApi.Schema.DecimalInfo.Builder decimalInfoBuilder =
		FlinkFnApi.Schema.DecimalInfo.newBuilder()
			.setPrecision(decimalType.getPrecision())
			.setScale(decimalType.getScale());
	builder.setDecimalInfo(decimalInfoBuilder);
	return builder.build();
}
 
Example 14
Source Project: flink   Source File: HBaseSerde.java    License: Apache License 2.0 5 votes vote down vote up
private static FieldEncoder createDecimalEncoder(DecimalType decimalType) {
	final int precision = decimalType.getPrecision();
	final int scale = decimalType.getScale();
	return (row, pos) -> {
		BigDecimal decimal = row.getDecimal(pos, precision, scale).toBigDecimal();
		return Bytes.toBytes(decimal);
	};
}
 
Example 15
Source Project: flink   Source File: LegacyDecimalTypeTransformation.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public DataType transform(DataType typeToTransform) {
	LogicalType logicalType = typeToTransform.getLogicalType();
	if (logicalType instanceof LegacyTypeInformationType && logicalType.getTypeRoot() == LogicalTypeRoot.DECIMAL) {
		DataType decimalType = DataTypes
			.DECIMAL(DecimalType.MAX_PRECISION, 18)
			.bridgedTo(typeToTransform.getConversionClass());
		return logicalType.isNullable() ? decimalType : decimalType.notNull();
	}
	return typeToTransform;
}
 
Example 16
Source Project: flink   Source File: LogicalTypeMerging.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Finds the result type of a decimal division operation.
 */
public static DecimalType findDivisionDecimalType(int precision1, int scale1, int precision2, int scale2) {
	// adopted from https://docs.microsoft.com/en-us/sql/t-sql/data-types/precision-scale-and-length-transact-sql
	int scale = Math.max(6, scale1 + precision2 + 1);
	int precision = precision1 - scale1 + scale2 + scale;
	if (precision > DecimalType.MAX_PRECISION) {
		scale = Math.max(6, DecimalType.MAX_PRECISION - (precision - scale));
		precision = DecimalType.MAX_PRECISION;
	}
	return new DecimalType(false, precision, scale);
}
 
Example 17
Source Project: flink   Source File: LogicalTypeMerging.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Finds the result type of a decimal modulo operation.
 */
public static DecimalType findModuloDecimalType(int precision1, int scale1, int precision2, int scale2) {
	// adopted from Calcite
	final int scale = Math.max(scale1, scale2);
	int precision = Math.min(precision1 - scale1, precision2 - scale2) + Math.max(scale1, scale2);
	precision = Math.min(precision, DecimalType.MAX_PRECISION);
	return new DecimalType(false, precision, scale);
}
 
Example 18
Source Project: flink   Source File: LogicalTypeMerging.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Finds the result type of a decimal multiplication operation.
 */
public static DecimalType findMultiplicationDecimalType(int precision1, int scale1, int precision2, int scale2) {
	// adopted from Calcite
	int scale = scale1 + scale2;
	scale = Math.min(scale, DecimalType.MAX_PRECISION);
	int precision = precision1 + precision2;
	precision = Math.min(precision, DecimalType.MAX_PRECISION);
	return new DecimalType(false, precision, scale);
}
 
Example 19
Source Project: flink   Source File: LogicalTypeMerging.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Finds the result type of a decimal addition operation.
 */
public static DecimalType findAdditionDecimalType(int precision1, int scale1, int precision2, int scale2) {
	// adopted from Calcite
	final int scale = Math.max(scale1, scale2);
	int precision = Math.max(precision1 - scale1, precision2 - scale2) + scale + 1;
	precision = Math.min(precision, DecimalType.MAX_PRECISION);
	return new DecimalType(false, precision, scale);
}
 
Example 20
Source Project: flink   Source File: LogicalTypeMerging.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Finds the result type of a decimal rounding operation.
 */
public static DecimalType findRoundDecimalType(int precision, int scale, int round) {
	if (round >= scale) {
		return new DecimalType(false, precision, scale);
	}
	if (round < 0) {
		return new DecimalType(false, Math.min(DecimalType.MAX_PRECISION, 1 + precision - scale), 0);
	}
	// 0 <= r < s
	// NOTE: rounding may increase the digits by 1, therefore we need +1 on precisions.
	return new DecimalType(false, 1 + precision - scale + round, round);
}
 
Example 21
Source Project: flink   Source File: LogicalTypeMerging.java    License: Apache License 2.0 5 votes vote down vote up
private static LogicalType createCommonExactNumericType(LogicalType resultType, LogicalType type) {
	// same EXACT_NUMERIC types
	if (type.equals(resultType)) {
		return resultType;
	}

	final LogicalTypeRoot resultTypeRoot = resultType.getTypeRoot();
	final LogicalTypeRoot typeRoot = type.getTypeRoot();

	// no DECIMAL types involved
	if (resultTypeRoot != DECIMAL && typeRoot != DECIMAL) {
		// type root contains order of precision
		if (getPrecision(type) > getPrecision(resultType)) {
			return type;
		}
		return resultType;
	}

	// determine DECIMAL with precision (p), scale (s) and number of whole digits (d):
	// d = max(p1 - s1, p2 - s2)
	// s <= max(s1, s2)
	// p = s + d
	final int p1 = getPrecision(resultType);
	final int p2 = getPrecision(type);
	final int s1 = getScale(resultType);
	final int s2 = getScale(type);
	final int maxPrecision = DecimalType.MAX_PRECISION;

	int d = Math.max(p1 - s1, p2 - s2);
	d = Math.min(d, maxPrecision);

	int s = Math.max(s1, s2);
	s = Math.min(s, maxPrecision - d);

	final int p = d + s;

	return new DecimalType(p, s);
}
 
Example 22
Source Project: flink   Source File: LogicalTypesTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDecimalType() {
	testAll(
		new DecimalType(10, 2),
		"DECIMAL(10, 2)",
		"DECIMAL(10, 2)",
		new Class[]{BigDecimal.class},
		new Class[]{BigDecimal.class},
		new LogicalType[]{},
		new DecimalType()
	);
}
 
Example 23
Source Project: flink   Source File: FlinkCalciteSqlValidator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void validateLiteral(SqlLiteral literal) {
	if (literal.getTypeName() == DECIMAL) {
		final BigDecimal decimal = literal.getValueAs(BigDecimal.class);
		if (decimal.precision() > DecimalType.MAX_PRECISION) {
			throw newValidationError(
				literal,
				Static.RESOURCE.numberLiteralOutOfRange(decimal.toString()));
		}
	}
	super.validateLiteral(literal);
}
 
Example 24
Source Project: flink   Source File: SumAggFunction.java    License: Apache License 2.0 4 votes vote down vote up
public DecimalSumAggFunction(DecimalType decimalType) {
	this.decimalType = decimalType;
}
 
Example 25
Source Project: flink   Source File: HiveTypeUtil.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public TypeInfo visit(DecimalType decimalType) {
	// Flink and Hive share the same precision and scale range
	// Flink already validates the type so we don't need to validate again here
	return TypeInfoFactory.getDecimalTypeInfo(decimalType.getPrecision(), decimalType.getScale());
}
 
Example 26
Source Project: flink   Source File: SumWithRetractAggFunction.java    License: Apache License 2.0 4 votes vote down vote up
public DecimalSumWithRetractAggFunction(DecimalType decimalType) {
	this.decimalType = decimalType;
}
 
Example 27
Source Project: flink   Source File: BinaryWriter.java    License: Apache License 2.0 4 votes vote down vote up
static void write(BinaryWriter writer, int pos,
		Object o, LogicalType type, TypeSerializer serializer) {
	switch (type.getTypeRoot()) {
		case BOOLEAN:
			writer.writeBoolean(pos, (boolean) o);
			break;
		case TINYINT:
			writer.writeByte(pos, (byte) o);
			break;
		case SMALLINT:
			writer.writeShort(pos, (short) o);
			break;
		case INTEGER:
		case DATE:
		case TIME_WITHOUT_TIME_ZONE:
		case INTERVAL_YEAR_MONTH:
			writer.writeInt(pos, (int) o);
			break;
		case BIGINT:
		case TIMESTAMP_WITHOUT_TIME_ZONE:
		case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
		case INTERVAL_DAY_TIME:
			writer.writeLong(pos, (long) o);
			break;
		case FLOAT:
			writer.writeFloat(pos, (float) o);
			break;
		case DOUBLE:
			writer.writeDouble(pos, (double) o);
			break;
		case CHAR:
		case VARCHAR:
			writer.writeString(pos, (BinaryString) o);
			break;
		case DECIMAL:
			DecimalType decimalType = (DecimalType) type;
			writer.writeDecimal(pos, (Decimal) o, decimalType.getPrecision());
			break;
		case ARRAY:
			writer.writeArray(pos, (BaseArray) o, (BaseArraySerializer) serializer);
			break;
		case MAP:
		case MULTISET:
			writer.writeMap(pos, (BaseMap) o, (BaseMapSerializer) serializer);
			break;
		case ROW:
			writer.writeRow(pos, (BaseRow) o, (BaseRowSerializer) serializer);
			break;
		case ANY:
			writer.writeGeneric(pos, (BinaryGeneric) o);
			break;
		case BINARY:
		case VARBINARY:
			writer.writeBinary(pos, (byte[]) o);
			break;
		default:
			throw new RuntimeException("Not support type: " + type);
	}
}
 
Example 28
Source Project: flink   Source File: CsvRowDataDeserializationSchema.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Creates a runtime converter which assuming input object is not null.
 */
private DeserializationRuntimeConverter createConverter(LogicalType type) {
	switch (type.getTypeRoot()) {
		case NULL:
			return jsonNode -> null;
		case BOOLEAN:
			return this::convertToBoolean;
		case TINYINT:
			return jsonNode -> Byte.parseByte(jsonNode.asText().trim());
		case SMALLINT:
			return jsonNode -> Short.parseShort(jsonNode.asText().trim());
		case INTEGER:
		case INTERVAL_YEAR_MONTH:
			return this::convertToInt;
		case BIGINT:
		case INTERVAL_DAY_TIME:
			return this::convertToLong;
		case DATE:
			return this::convertToDate;
		case TIME_WITHOUT_TIME_ZONE:
			return this::convertToTime;
		case TIMESTAMP_WITH_TIME_ZONE:
		case TIMESTAMP_WITHOUT_TIME_ZONE:
			return this::convertToTimestamp;
		case FLOAT:
			return this::convertToFloat;
		case DOUBLE:
			return this::convertToDouble;
		case CHAR:
		case VARCHAR:
			return this::convertToString;
		case BINARY:
		case VARBINARY:
			return this::convertToBytes;
		case DECIMAL:
			return createDecimalConverter((DecimalType) type);
		case ARRAY:
			return createArrayConverter((ArrayType) type);
		case ROW:
			return createRowConverter((RowType) type, false);
		case MAP:
		case MULTISET:
		case RAW:
		default:
			throw new UnsupportedOperationException("Unsupported type: " + type);
	}
}
 
Example 29
Source Project: flink   Source File: SumAggFunction.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public DataType getResultType() {
	DecimalType sumType = FlinkTypeSystem.inferAggSumType(decimalType.getScale());
	return DataTypes.DECIMAL(sumType.getPrecision(), sumType.getScale());
}
 
Example 30
Source Project: flink   Source File: TypeInfoDataTypeConverter.java    License: Apache License 2.0 4 votes vote down vote up
public static TypeInformation<?> fromDataTypeToTypeInfo(DataType dataType) {
	Class<?> clazz = dataType.getConversionClass();
	if (clazz.isPrimitive()) {
		final TypeInformation<?> foundTypeInfo = primitiveDataTypeTypeInfoMap.get(clazz.getName());
		if (foundTypeInfo != null) {
			return foundTypeInfo;
		}
	}
	LogicalType logicalType = fromDataTypeToLogicalType(dataType);
	switch (logicalType.getTypeRoot()) {
		case DECIMAL:
			DecimalType decimalType = (DecimalType) logicalType;
			return clazz == Decimal.class ?
					new DecimalTypeInfo(decimalType.getPrecision(), decimalType.getScale()) :
					new BigDecimalTypeInfo(decimalType.getPrecision(), decimalType.getScale());
		case CHAR:
		case VARCHAR: // ignore precision
			return clazz == BinaryString.class ?
					BinaryStringTypeInfo.INSTANCE :
					BasicTypeInfo.STRING_TYPE_INFO;
		case BINARY:
		case VARBINARY: // ignore precision
			return PrimitiveArrayTypeInfo.BYTE_PRIMITIVE_ARRAY_TYPE_INFO;
		case INTERVAL_YEAR_MONTH:
			return TimeIntervalTypeInfo.INTERVAL_MONTHS;
		case INTERVAL_DAY_TIME:
			return TimeIntervalTypeInfo.INTERVAL_MILLIS;
		case ARRAY:
			if (dataType instanceof CollectionDataType &&
					!isPrimitive(((CollectionDataType) dataType).getElementDataType().getLogicalType())) {
				return ObjectArrayTypeInfo.getInfoFor(
						fromDataTypeToTypeInfo(((CollectionDataType) dataType).getElementDataType()));
			} else {
				return TypeConversions.fromDataTypeToLegacyInfo(dataType);
			}
		case MAP:
			KeyValueDataType mapType = (KeyValueDataType) dataType;
			return new MapTypeInfo(
					fromDataTypeToTypeInfo(mapType.getKeyDataType()),
					fromDataTypeToTypeInfo(mapType.getValueDataType()));
		case MULTISET:
			return MultisetTypeInfo.getInfoFor(
					fromDataTypeToTypeInfo(((CollectionDataType) dataType).getElementDataType()));
		case ROW:
			if (BaseRow.class.isAssignableFrom(dataType.getConversionClass())) {
				return BaseRowTypeInfo.of((RowType) fromDataTypeToLogicalType(dataType));
			} else if (Row.class == dataType.getConversionClass()) {
				FieldsDataType rowType = (FieldsDataType) dataType;
				RowType logicalRowType = (RowType) logicalType;
				return new RowTypeInfo(
						logicalRowType.getFieldNames().stream()
								.map(name -> rowType.getFieldDataTypes().get(name))
								.map(TypeInfoDataTypeConverter::fromDataTypeToTypeInfo)
								.toArray(TypeInformation[]::new),
						logicalRowType.getFieldNames().toArray(new String[0]));
			} else {
				return TypeConversions.fromDataTypeToLegacyInfo(dataType);
			}
		default:
			return TypeConversions.fromDataTypeToLegacyInfo(dataType);
	}
}