Skip to content

Commit

Permalink
update the check of pointer to struct
Browse files Browse the repository at this point in the history
  • Loading branch information
xgfone committed Jan 3, 2025
1 parent 803b41a commit 8bc4183
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 10 deletions.
11 changes: 2 additions & 9 deletions dml_select_row_scanner.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ package sqlx

import (
"database/sql"
"reflect"
"slices"
"time"
)
Expand Down Expand Up @@ -78,19 +77,13 @@ func getrowscap(scanner RowScanner, defaultcap int) int {
}
}

var _timetype = reflect.TypeFor[time.Time]()

func defaultRowScanWrapper(scanner RowScanner, dsts ...any) error {
return scanrow(scanner, dsts...)
}

func scanrow(scanner RowScanner, dsts ...any) (err error) {
if len(dsts) == 1 {
if vt := reflect.TypeOf(dsts[0]); vt.Kind() == reflect.Pointer {
if vt = vt.Elem(); vt.Kind() == reflect.Struct && vt != _timetype {
return scanStruct(scanner, dsts[0])
}
}
if len(dsts) == 1 && IsPointerToStruct(dsts[0]) {
return scanStruct(scanner, dsts[0])
}
return scanner.Scan(dsts...)
}
Expand Down
20 changes: 20 additions & 0 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"reflect"
"strings"
"sync"
"time"
)

// DefaultBufferCap is the default capacity to be allocated for buffer from pool.
Expand All @@ -46,6 +47,25 @@ func tagContainAttr(targ, attr string) bool {
}
}

var _timetype = reflect.TypeFor[time.Time]()

// IsPointerToStruct returns true if v is a pointer to struct, else false.
//
// Notice: struct{} is considered as a struct, but time.Time is not.
func IsPointerToStruct(v any) (ok bool) {
if v == nil {
return
}

if vt := reflect.TypeOf(v); vt.Kind() == reflect.Pointer {
if vt = vt.Elem(); vt.Kind() == reflect.Struct && vt != _timetype {
ok = true
}
}

return
}

// CheckErrNoRows extracts the error sql.ErrNoRows as the bool, which returns
//
// - (true, nil) if err is equal to nil
Expand Down
23 changes: 22 additions & 1 deletion utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@

package sqlx

import "testing"
import (
"testing"
"time"
)

func TestTagContainAttr(t *testing.T) {
if !tagContainAttr("abc", "abc") {
Expand All @@ -37,3 +40,21 @@ func TestTagContainAttr(t *testing.T) {
t.Error("not expect false")
}
}

func TestIsPointerToStruct(t *testing.T) {
if IsPointerToStruct(nil) {
t.Error("expect false, but got true")
}

if v := 123; IsPointerToStruct(&v) {
t.Error("expect false, but got true")
}

if v := (time.Time{}); IsPointerToStruct(&v) {
t.Error("expect false, but got true")
}

if v := (struct{}{}); !IsPointerToStruct(&v) {
t.Error("expect true, but got false")
}
}

0 comments on commit 8bc4183

Please sign in to comment.