Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(spanner/spannertest): support AVG aggregation function #3286

Merged
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)
},
},
{
dsymonds marked this conversation as resolved.
Show resolved Hide resolved
`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