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

support custom types in query result scanning #1599

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
* Fixed potential infinity loop for local dc detection
* Fixed nil pointer dereferenced in a topic listener
* Added support of custom types to row.ScanStruct using sql.Scanner.Scan or UnmarshalYDBValue

## v3.99.2
* Fixed panic when error returned from parsing sql params
Expand Down
30 changes: 30 additions & 0 deletions internal/value/cast.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
package value

import (
"database/sql"
"database/sql/driver"

"github.com/google/uuid"
)

func CastTo(v Value, dst interface{}) error {
if dst == nil {
return errNilDestination
Expand All @@ -10,5 +17,28 @@ func CastTo(v Value, dst interface{}) error {
return nil
}

if _, ok := dst.(*uuid.UUID); ok {
return v.castTo(dst)
}

if scanner, has := dst.(sql.Scanner); has {
dv := new(driver.Value)

err := v.castTo(dv)
if err != nil {
return err
}

return scanner.Scan(*dv)
}

if scanner, has := dst.(Scanner); has {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think special ydb scanner should be preferred over more common sql scanner.

return scanner.UnmarshalYDBValue(v)
}

return v.castTo(dst)
}

type Scanner interface {
UnmarshalYDBValue(value Value) error
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

YDB has scanner interface
already. What about to reuse it?

Copy link
Contributor Author

@4el0ve4ek 4el0ve4ek Feb 3, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thats very cool interface to use! But now there is only one implementation
and i don't find easy way to convert value.Value into scanner.RawValue. So i took an easy way and create new interface)

How do you think, maybe better to create adapter for value.Value which implements scanner.RawValue?

UPD: i think for library would be better if we won't create new interface

}
43 changes: 43 additions & 0 deletions internal/value/cast_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package value

import (
"database/sql/driver"
"errors"
"reflect"
"testing"
"time"
Expand Down Expand Up @@ -32,6 +33,34 @@ func loadLocation(t *testing.T, name string) *time.Location {
return loc
}

type testStringValueScanner string

func (s *testStringValueScanner) UnmarshalYDBValue(v Value) error {
var tmp string

err := CastTo(v, &tmp)
if err != nil {
return err
}

*s = testStringValueScanner(tmp)

return nil
}

type testStringSQLScanner string

func (s *testStringSQLScanner) Scan(value any) error {
ts, ok := value.(string)
if !ok {
return errors.New("can't cast from " + reflect.TypeOf(value).String() + " to string")
}

*s = testStringSQLScanner(ts)

return nil
}

func TestCastTo(t *testing.T) {
testsCases := []struct {
name string
Expand Down Expand Up @@ -428,6 +457,20 @@ func TestCastTo(t *testing.T) {
exp: DateValueFromTime(time.Date(2024, 1, 2, 0, 0, 0, 0, time.UTC)),
err: nil,
},
{
name: xtest.CurrentFileLine(),
value: TextValue("text-string"),
dst: ptr[testStringValueScanner](),
exp: testStringValueScanner("text-string"),
err: nil,
},
{
name: xtest.CurrentFileLine(),
value: TextValue("text-string"),
dst: ptr[testStringSQLScanner](),
exp: testStringSQLScanner("text-string"),
err: nil,
},
}
for _, tt := range testsCases {
t.Run(tt.name, func(t *testing.T) {
Expand Down
12 changes: 6 additions & 6 deletions internal/value/value.go
Original file line number Diff line number Diff line change
Expand Up @@ -1303,7 +1303,7 @@ func (v *listValue) castTo(dst any) error {
inner.Set(newSlice)

for i, item := range v.ListItems() {
if err := item.castTo(inner.Index(i).Addr().Interface()); err != nil {
if err := CastTo(item, inner.Index(i).Addr().Interface()); err != nil {
return xerrors.WithStackTrace(fmt.Errorf(
"%w '%s(%+v)' to '%T' destination",
ErrCannotCast, v.Type().Yql(), v, dstValue,
Expand Down Expand Up @@ -1437,7 +1437,7 @@ func (v *setValue) castTo(dst any) error {
inner.Set(newSlice)

for i, item := range v.items {
if err := item.castTo(inner.Index(i).Addr().Interface()); err != nil {
if err := CastTo(item, inner.Index(i).Addr().Interface()); err != nil {
return xerrors.WithStackTrace(fmt.Errorf(
"%w '%s(%+v)' to '%T' destination",
ErrCannotCast, v.Type().Yql(), v, dstValue,
Expand Down Expand Up @@ -1545,7 +1545,7 @@ func (v *optionalValue) castTo(dst any) error {
return nil
}

if err := v.value.castTo(ptr.Interface()); err != nil {
if err := CastTo(v.value, (ptr.Interface())); err != nil {
return xerrors.WithStackTrace(err)
}

Expand All @@ -1560,7 +1560,7 @@ func (v *optionalValue) castTo(dst any) error {

inner.Set(reflect.New(inner.Type().Elem()))

if err := v.value.castTo(inner.Interface()); err != nil {
if err := CastTo(v.value, inner.Interface()); err != nil {
return xerrors.WithStackTrace(err)
}

Expand Down Expand Up @@ -1641,7 +1641,7 @@ func (v *structValue) castTo(dst any) error {
}

for i, field := range v.fields {
if err := field.V.castTo(inner.Field(i).Addr().Interface()); err != nil {
if err := CastTo(field.V, inner.Field(i).Addr().Interface()); err != nil {
return xerrors.WithStackTrace(fmt.Errorf(
"scan error on struct field name '%s': %w",
field.Name, err,
Expand Down Expand Up @@ -1768,7 +1768,7 @@ func (v *tupleValue) TupleItems() []Value {

func (v *tupleValue) castTo(dst any) error {
if len(v.items) == 1 {
return v.items[0].castTo(dst)
return CastTo(v.items[0], dst)
}

switch dstValue := dst.(type) {
Expand Down
19 changes: 17 additions & 2 deletions tests/integration/query_range_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,17 @@ import (
"github.com/ydb-platform/ydb-go-sdk/v3/internal/value"
"github.com/ydb-platform/ydb-go-sdk/v3/internal/xtest"
"github.com/ydb-platform/ydb-go-sdk/v3/query"
"github.com/ydb-platform/ydb-go-sdk/v3/table/types"
)

type testStringValueScanner struct {
field string
}

func (v *testStringValueScanner) UnmarshalYDBValue(value types.Value) error {
return types.CastTo(value, &v.field)
}

func TestQueryRange(t *testing.T) {
ctx, cancel := context.WithCancel(xtest.Context(t))
defer cancel()
Expand Down Expand Up @@ -84,19 +93,22 @@ func TestQueryRange(t *testing.T) {
p1 string
p2 uint64
p3 time.Duration
p4 testStringValueScanner
)
err := db.Query().Do(ctx, func(ctx context.Context, s query.Session) error {
r, err := s.Query(ctx, `
DECLARE $p1 AS Text;
DECLARE $p2 AS Uint64;
DECLARE $p3 AS Interval;
SELECT $p1, $p2, $p3;
DECLARE $p4 AS Text;
SELECT $p1, $p2, $p3, $p4;
`,
query.WithParameters(
ydb.ParamsBuilder().
Param("$p1").Text("test").
Param("$p2").Uint64(100500000000).
Param("$p3").Interval(time.Duration(100500000000)).
Param("$p4").Text("test2").
Build(),
),
query.WithSyntax(query.SyntaxYQL),
Expand All @@ -112,7 +124,7 @@ func TestQueryRange(t *testing.T) {
if err != nil {
return err
}
err = row.Scan(&p1, &p2, &p3)
err = row.Scan(&p1, &p2, &p3, &p4)
if err != nil {
return err
}
Expand All @@ -126,6 +138,9 @@ func TestQueryRange(t *testing.T) {
if p3 != time.Duration(100500000000) {
return fmt.Errorf("unexpected p3 value: %v", p3)
}
if p4.field != "test2" {
return fmt.Errorf("unexpected p4 value: %v", p4)
}
}
}
return nil
Expand Down
Loading