Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,12 @@ public class BeamBuiltinAggregations {
.put("COUNTIF", typeName -> CountIf.combineFn())
.build();

private static MathContext mc = new MathContext(10, RoundingMode.HALF_UP);
/**
* The precision of a DECIMAL average, the 34 digits of IEEE 754 decimal128. Integer averages are
* divided exactly instead, see {@link Avg#prepareIntegralOutput}.
*/
private static final MathContext DECIMAL_AVG_CONTEXT =
new MathContext(MathContext.DECIMAL128.getPrecision(), RoundingMode.HALF_UP);

public static CombineFn<?, ?, ?> create(String functionName, Schema.FieldType fieldType) {

Expand Down Expand Up @@ -466,7 +471,19 @@ public Coder<KV<Integer, BigDecimal>> getAccumulatorCoder(
}

protected BigDecimal prepareOutput(KV<Integer, BigDecimal> accumulator) {
return accumulator.getValue().divide(new BigDecimal(accumulator.getKey()), mc);
return accumulator
.getValue()
.divide(new BigDecimal(accumulator.getKey()), DECIMAL_AVG_CONTEXT);
}

/**
* Divides the exact sum of integer inputs to an integral average, truncating toward zero as
* integer division does, so the average of any values of an integer type fits that type.
*/
protected BigDecimal prepareIntegralOutput(KV<Integer, BigDecimal> accumulator) {
return accumulator
.getValue()
.divide(new BigDecimal(accumulator.getKey()), 0, RoundingMode.DOWN);
}

@Override
Expand All @@ -478,7 +495,7 @@ protected BigDecimal prepareOutput(KV<Integer, BigDecimal> accumulator) {
static class IntegerAvg extends Avg<Integer> {
@Override
public @Nullable Integer extractOutput(KV<Integer, BigDecimal> accumulator) {
return accumulator.getKey() == 0 ? null : prepareOutput(accumulator).intValue();
return accumulator.getKey() == 0 ? null : prepareIntegralOutput(accumulator).intValueExact();
}

@Override
Expand All @@ -490,7 +507,7 @@ public BigDecimal toBigDecimal(Integer record) {
static class LongAvg extends Avg<Long> {
@Override
public @Nullable Long extractOutput(KV<Integer, BigDecimal> accumulator) {
return accumulator.getKey() == 0 ? null : prepareOutput(accumulator).longValue();
return accumulator.getKey() == 0 ? null : prepareIntegralOutput(accumulator).longValueExact();
}

@Override
Expand All @@ -502,7 +519,9 @@ public BigDecimal toBigDecimal(Long record) {
static class ShortAvg extends Avg<Short> {
@Override
public @Nullable Short extractOutput(KV<Integer, BigDecimal> accumulator) {
return accumulator.getKey() == 0 ? null : prepareOutput(accumulator).shortValue();
return accumulator.getKey() == 0
? null
: prepareIntegralOutput(accumulator).shortValueExact();
}

@Override
Expand All @@ -514,7 +533,7 @@ public BigDecimal toBigDecimal(Short record) {
static class ByteAvg extends Avg<Byte> {
@Override
public @Nullable Byte extractOutput(KV<Integer, BigDecimal> accumulator) {
return accumulator.getKey() == 0 ? null : prepareOutput(accumulator).byteValue();
return accumulator.getKey() == 0 ? null : prepareIntegralOutput(accumulator).byteValueExact();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.sdk.extensions.sql.impl.transform;

import static org.junit.Assert.assertEquals;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import org.apache.beam.sdk.schemas.Schema.FieldType;
import org.apache.beam.sdk.transforms.Combine.CombineFn;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests for the {@code AVG} aggregations in {@link BeamBuiltinAggregations}. */
@RunWith(JUnit4.class)
public class BeamBuiltinAggregationsTest {

@SuppressWarnings("unchecked")
private static <T> T avg(FieldType type, List<T> inputs) {
CombineFn<T, Object, T> fn =
(CombineFn<T, Object, T>) BeamBuiltinAggregations.create("AVG", type);
Object accumulator = fn.createAccumulator();
for (T input : inputs) {
accumulator = fn.addInput(accumulator, input);
}
return fn.extractOutput(accumulator);
}

/** An average of a single row is that row, with no rounding to 10 significant digits (#39751). */
@Test
public void testAverageOfOneRowIsThatRow() {
for (long value : new long[] {Long.MAX_VALUE, Long.MIN_VALUE, 1786500000123L}) {
assertEquals(Long.valueOf(value), avg(FieldType.INT64, Arrays.asList(value)));
}
assertEquals(
Integer.valueOf(Integer.MIN_VALUE), avg(FieldType.INT32, Arrays.asList(Integer.MIN_VALUE)));
assertEquals(
new BigDecimal("123456789.99"),
avg(FieldType.DECIMAL, Arrays.asList(new BigDecimal("123456789.99"))));
}

@Test
public void testIntegerAverageTruncatesTowardZero() {
assertEquals(Integer.valueOf(1), avg(FieldType.INT32, Arrays.asList(1, 2)));
assertEquals(Integer.valueOf(-1), avg(FieldType.INT32, Arrays.asList(-1, -2)));
assertEquals(
Short.valueOf((short) 2), avg(FieldType.INT16, Arrays.asList((short) 2, (short) 3)));
assertEquals(Byte.valueOf((byte) -2), avg(FieldType.BYTE, Arrays.asList((byte) -2, (byte) -3)));
// The sum overflows a long, the average does not.
assertEquals(
Long.valueOf(Long.MAX_VALUE - 1),
avg(FieldType.INT64, Arrays.asList(Long.MAX_VALUE, Long.MAX_VALUE - 1)));
}

@Test
public void testDecimalAverageKeepsPrecision() {
assertEquals(
new BigDecimal("1234567890123.5"),
avg(
FieldType.DECIMAL,
Arrays.asList(new BigDecimal("1234567890123"), new BigDecimal("1234567890124"))));
}

@Test
public void testAverageOfNoRowsIsNull() {
assertEquals(null, avg(FieldType.INT64, Arrays.<Long>asList()));
}
}