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

fix: driver.Valuer method was being ignored #289

Merged
merged 1 commit into from
Aug 29, 2024
Merged
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
12 changes: 8 additions & 4 deletions driver.go
Original file line number Diff line number Diff line change
Expand Up @@ -748,13 +748,11 @@ func (c *conn) IsValid() bool {
return !c.closed
}

// checkIsValidType returns true for types that do not need extra conversion
// for spanner.
func checkIsValidType(v driver.Value) bool {
switch v.(type) {
default:
// google-cloud-go/spanner knows how to deal with these
if isStructOrArrayOfStructValue(v) || isAnArrayOfProtoColumn(v) {
return true
}
return false
case nil:
case sql.NullInt64:
Expand Down Expand Up @@ -851,6 +849,12 @@ func (c *conn) CheckNamedValue(value *driver.NamedValue) error {
return nil
}
}

// google-cloud-go/spanner knows how to deal with these
if isStructOrArrayOfStructValue(value.Value) || isAnArrayOfProtoColumn(value.Value) {
return nil
}

return spanner.ToSpannerError(status.Errorf(codes.InvalidArgument, "unsupported value type: %T", value.Value))
}

Expand Down
49 changes: 49 additions & 0 deletions driver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -467,3 +467,52 @@ func TestConn_GetCommitTimestampAfterAutocommitQuery(t *testing.T) {
t.Fatalf("error code mismatch\n Got: %v\nWant: %v", g, w)
}
}

func TestConn_CheckNamedValue(t *testing.T) {
c := &conn{}

type Person struct {
Name string
Age int64
}

tests := []struct {
in any
want any
}{
// basic types should stay unchanged
{in: int64(256), want: int64(256)},
// driver.Valuer types should call .Value func
{in: &ValuerPerson{Name: "hello", Age: 123}, want: "hello"},
// structs should be sent to spanner
{in: &Person{Name: "hello", Age: 123}, want: &Person{Name: "hello", Age: 123}},
}

for _, test := range tests {
value := &driver.NamedValue{
Ordinal: 1,
Value: test.in,
}

err := c.CheckNamedValue(value)
if err != nil {
t.Errorf("expected no error, got: %v", err)
continue
}

if diff := cmp.Diff(test.want, value.Value); diff != "" {
t.Errorf("wrong result, got %#v expected %#v:\n%v", value.Value, test.want, diff)
}
}
}

// ValuerPerson implements driver.Valuer
type ValuerPerson struct {
Name string
Age int64
}

// Value implements conversion func for database.
func (p *ValuerPerson) Value() (driver.Value, error) {
return p.Name, nil
}
Loading