Skip to content

Commit b9c2c3f

Browse files
authored
feat: add getNumber to AggregationResult (#1851) (#1861)
1 parent 055effd commit b9c2c3f

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

google-cloud-datastore/src/main/java/com/google/cloud/datastore/AggregationResult.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,26 @@ public Double getDouble(String alias) {
8484
}
8585
}
8686

87+
/**
88+
* Returns a result value for the given alias.
89+
*
90+
* @param alias A custom alias provided in the query or an autogenerated alias in the form of
91+
* 'property_\d'
92+
* @return An aggregation result value as a {@link Number} for the given alias.
93+
*/
94+
public Number getNumber(String alias) {
95+
Value<?> value = properties.get(alias);
96+
switch (value.getType()) {
97+
case LONG:
98+
return (Long) value.get();
99+
case DOUBLE:
100+
return (Double) value.get();
101+
default:
102+
throw new RuntimeException(
103+
String.format("Unsupported type %s received for alias '%s'.", value.getType(), alias));
104+
}
105+
}
106+
87107
@Override
88108
public boolean equals(Object o) {
89109
if (this == o) {

google-cloud-datastore/src/test/java/com/google/cloud/datastore/AggregationResultTest.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,5 +77,23 @@ public void shouldThrowRuntimeExceptionOnUnknownTypes() {
7777
RuntimeException e2 =
7878
assertThrows(RuntimeException.class, () -> aggregationResult.getDouble("qty_avg"));
7979
assertThat(e2.getMessage()).isEqualTo("Unsupported type BOOLEAN received for alias 'qty_avg'.");
80+
81+
RuntimeException e3 =
82+
assertThrows(RuntimeException.class, () -> aggregationResult.getNumber("qty_avg"));
83+
assertThat(e3.getMessage()).isEqualTo("Unsupported type BOOLEAN received for alias 'qty_avg'.");
84+
}
85+
86+
@Test
87+
public void shouldGetDoubleAggregatedResultValueAsNumber() {
88+
AggregationResult aggregationResult =
89+
new AggregationResult(ImmutableMap.of("qty_avg", DoubleValue.of(45.9322)));
90+
assertThat(aggregationResult.getNumber("qty_avg")).isEqualTo(45.9322);
91+
}
92+
93+
@Test
94+
public void shouldGetLongAggregatedResultValueAsNumber() {
95+
AggregationResult aggregationResult =
96+
new AggregationResult(ImmutableMap.of("count", LongValue.of(50)));
97+
assertThat(aggregationResult.getNumber("count")).isEqualTo(50);
8098
}
8199
}

0 commit comments

Comments
 (0)