Skip to content

Commit

Permalink
feat(bigquery): improve error when reading null values (#6566)
Browse files Browse the repository at this point in the history
Improve error message when reading NULL values from a query and trying to fit into a struct field.

Resolves #2612
  • Loading branch information
alvarowolfx authored Sep 2, 2022
1 parent 6b0ac0c commit e9a94c2
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
4 changes: 4 additions & 0 deletions bigquery/value.go
Original file line number Diff line number Diff line change
Expand Up @@ -455,6 +455,10 @@ func runOps(ops []structLoaderOp, vstruct reflect.Value, values []Value) error {
err = setRepeated(field, values[op.valueIndex].([]Value), op.setFunc)
} else {
err = op.setFunc(field, values[op.valueIndex])
if errors.Is(err, errNoNulls) {
f := vstruct.Type().FieldByIndex(op.fieldIndex)
err = fmt.Errorf("bigquery: NULL cannot be assigned to field `%s` of type %s", f.Name, f.Type.Name())
}
}
if err != nil {
return err
Expand Down
11 changes: 10 additions & 1 deletion bigquery/value_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,11 @@ package bigquery

import (
"encoding/base64"
"errors"
"fmt"
"math"
"math/big"
"reflect"
"testing"
"time"

Expand Down Expand Up @@ -1261,14 +1263,21 @@ func TestStructLoaderErrors(t *testing.T) {
S string
D civil.Date
}
vstruct := reflect.ValueOf(s{}).Type()
fieldNames := []string{"I", "F", "B", "S", "D"}
vals := []Value{int64(0), 0.0, false, "", testDate}
mustLoad(t, &s{}, schema, vals)
for i, e := range vals {
vals[i] = nil
got := load(&s{}, schema, vals)
if got != errNoNulls {
if errors.Is(got, errNoNulls) {
t.Errorf("#%d: got %v, want %v", i, got, errNoNulls)
}
f, _ := vstruct.FieldByName(fieldNames[i])
expectedError := fmt.Sprintf("bigquery: NULL cannot be assigned to field `%s` of type %s", f.Name, f.Type.Name())
if got.Error() != expectedError {
t.Errorf("#%d: got %v, want %v", i, got, expectedError)
}
vals[i] = e
}

Expand Down

0 comments on commit e9a94c2

Please sign in to comment.