Skip to content

Commit

Permalink
支持对scan后rows.Err()检查 (#144)
Browse files Browse the repository at this point in the history
  • Loading branch information
winston-ke committed Aug 10, 2023
1 parent dbb2872 commit b1ded9c
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
6 changes: 6 additions & 0 deletions scanner/scanner.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ type Rows interface {
Next() bool

Scan(dest ...interface{}) error

Err() error
}

const (
Expand Down Expand Up @@ -329,6 +331,10 @@ func resolveDataFromRows(rows Rows) ([]map[string]interface{}, error) {
}
result = append(result, mp)
}
err = rows.Err()
if nil != err {
return nil, err
}
return result, nil
}

Expand Down
36 changes: 36 additions & 0 deletions scanner/scanner_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package scanner

import (
"context"
"database/sql"
"encoding/json"
"errors"
Expand Down Expand Up @@ -987,7 +988,9 @@ type fakeRows struct {
idx int
}

var gCtx context.Context = context.Background()
var errCloseForTest = errors.New("just for test")
var errCancelForTest = errors.New("context canceled")

func (r *fakeRows) Close() error {
return errCloseForTest
Expand Down Expand Up @@ -1020,6 +1023,14 @@ func (r *fakeRows) Scan(dt ...interface{}) (err error) {
return nil
}

func (r *fakeRows) Err() error {
err := gCtx.Err()
if err != nil {
return err
}
return nil
}

func TestScanNotSettable(t *testing.T) {
should := require.New(t)
err := Scan(&fakeRows{}, nil)
Expand Down Expand Up @@ -1076,6 +1087,31 @@ func TestScanMock(t *testing.T) {
should.Equal(24, boys[1].Age)
}

func TestScanCtxErr(t *testing.T) {
should := require.New(t)
scannn := &fakeRows{
columns: []string{"name", "age"},
dataset: [][]interface{}{
{"deen", 23},
{"caibirdme", 24},
},
}
type curdBoy struct {
Name string `ddb:"name"`
Age int `ddb:"age"`
}
var boys []curdBoy
defaultTag := DefaultTagName
userDefinedTagName = &defaultTag

var cancle context.CancelFunc
gCtx, cancle = context.WithCancel(gCtx)
cancle()
err := Scan(scannn, &boys)
should.Equal(errCancelForTest.Error(), err.Error())
gCtx = context.Background()
}

func TestScanEmpty(t *testing.T) {
should := require.New(t)
scannn := &fakeRows{}
Expand Down

0 comments on commit b1ded9c

Please sign in to comment.