Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
feat(spanner/spannertest): support AVG aggregation function (#3286)
Fixes #3285 

Sorry for creating PR without waiting for the response to the above issue 😅
  • Loading branch information
sryoya committed Dec 2, 2020
1 parent 88e5466 commit 4788415
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
37 changes: 37 additions & 0 deletions spanner/spannertest/funcs.go
Expand Up @@ -109,6 +109,43 @@ var aggregateFuncs = map[string]aggregateFunc{
return sum, typ, nil
},
},
"AVG": {
Eval: func(values []interface{}, typ spansql.Type) (interface{}, spansql.Type, error) {
if typ.Array || !(typ.Base == spansql.Int64 || typ.Base == spansql.Float64) {
return nil, spansql.Type{}, fmt.Errorf("AVG only supports arguments of INT64 or FLOAT64 type, not %s", typ.SQL())
}
if typ.Base == spansql.Int64 {
var sum int64
var n float64
for _, v := range values {
if v == nil {
continue
}
sum += v.(int64)
n++
}
if n == 0 {
// "Returns NULL if the input contains only NULLs".
return nil, typ, nil
}
return (float64(sum) / n), float64Type, nil
}
var sum float64
var n float64
for _, v := range values {
if v == nil {
continue
}
sum += v.(float64)
n++
}
if n == 0 {
// "Returns NULL if the input contains only NULLs".
return nil, typ, nil
}
return (sum / n), typ, nil
},
},
}

func evalMinMax(name string, isMin bool, values []interface{}, typ spansql.Type) (interface{}, spansql.Type, error) {
Expand Down
7 changes: 7 additions & 0 deletions spanner/spannertest/integration_test.go
Expand Up @@ -889,6 +889,13 @@ func TestIntegration_ReadsAndQueries(t *testing.T) {
{int64(1), int64(25)}, // Jack(ID=1, Tenure=10), Sam(ID=3, Tenure=9), George(ID=5, Tenure=6)
},
},
{
`SELECT AVG(Height) FROM Staff WHERE ID <= 2`,
nil,
[][]interface{}{
{float64(1.84)},
},
},
{
`SELECT MAX(Name) FROM Staff WHERE Name < @lim`,
map[string]interface{}{"lim": "Teal'c"},
Expand Down
1 change: 1 addition & 0 deletions spanner/spansql/keywords.go
Expand Up @@ -130,6 +130,7 @@ var keywords = map[string]bool{
var funcs = map[string]bool{
// Aggregate functions.
"ARRAY_AGG": true,
"AVG": true,
"BIT_XOR": true,
"COUNT": true,
"MAX": true,
Expand Down

0 comments on commit 4788415

Please sign in to comment.