Skip to content

Commit 98b74f9

Browse files
committed
rebase & support sql.Scanner iface
1 parent 48ccba7 commit 98b74f9

File tree

3 files changed

+50
-10
lines changed

3 files changed

+50
-10
lines changed

internal/value/cast.go

+16
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
package value
22

3+
import (
4+
"database/sql"
5+
"database/sql/driver"
6+
)
7+
38
func CastTo(v Value, dst interface{}) error {
49
if dst == nil {
510
return errNilDestination
@@ -10,6 +15,17 @@ func CastTo(v Value, dst interface{}) error {
1015
return nil
1116
}
1217

18+
if scanner, has := dst.(sql.Scanner); has {
19+
dv := new(driver.Value)
20+
21+
err := v.castTo(dv)
22+
if err != nil {
23+
return err
24+
}
25+
26+
return scanner.Scan(*dv)
27+
}
28+
1329
if scanner, has := dst.(Scanner); has {
1430
return scanner.UnmarshalYDBValue(v)
1531
}

internal/value/cast_test.go

+33-5
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package value
22

33
import (
44
"database/sql/driver"
5+
"errors"
56
"reflect"
67
"testing"
78
"time"
@@ -32,12 +33,32 @@ func loadLocation(t *testing.T, name string) *time.Location {
3233
return loc
3334
}
3435

35-
type testStringValueScanner struct {
36-
field string
37-
}
36+
type testStringValueScanner string
3837

3938
func (s *testStringValueScanner) UnmarshalYDBValue(v Value) error {
40-
return CastTo(v, &s.field)
39+
var tmp string
40+
41+
err := CastTo(v, &tmp)
42+
if err != nil {
43+
return err
44+
}
45+
46+
*s = testStringValueScanner(tmp)
47+
48+
return nil
49+
}
50+
51+
type testStringSQLScanner string
52+
53+
func (s *testStringSQLScanner) Scan(value any) error {
54+
ts, ok := value.(string)
55+
if !ok {
56+
return errors.New("can't cast from " + reflect.TypeOf(value).String() + " to string")
57+
}
58+
59+
*s = testStringSQLScanner(ts)
60+
61+
return nil
4162
}
4263

4364
func TestCastTo(t *testing.T) {
@@ -440,7 +461,14 @@ func TestCastTo(t *testing.T) {
440461
name: xtest.CurrentFileLine(),
441462
value: TextValue("text-string"),
442463
dst: ptr[testStringValueScanner](),
443-
exp: testStringValueScanner{field: "text-string"},
464+
exp: testStringValueScanner("text-string"),
465+
err: nil,
466+
},
467+
{
468+
name: xtest.CurrentFileLine(),
469+
value: TextValue("text-string"),
470+
dst: ptr[testStringSQLScanner](),
471+
exp: testStringSQLScanner("text-string"),
444472
err: nil,
445473
},
446474
}

internal/value/value.go

+1-5
Original file line numberDiff line numberDiff line change
@@ -2331,12 +2331,8 @@ type uuidValue struct {
23312331

23322332
func (v *uuidValue) castTo(dst any) error {
23332333
switch vv := dst.(type) {
2334-
case *uuid.UUID:
2335-
*vv = v.value
2336-
2337-
return nil
23382334
case *driver.Value:
2339-
*vv = v.value
2335+
*vv = v.value[:]
23402336

23412337
return nil
23422338
case *string:

0 commit comments

Comments
 (0)