-
Notifications
You must be signed in to change notification settings - Fork 1
/
row.go
130 lines (104 loc) · 2.08 KB
/
row.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package sqle
import (
"database/sql"
"errors"
"reflect"
)
var (
ErrMustPointer = errors.New("sqle: dest must be a pointer")
ErrMustSlice = errors.New("sqle: dest must be a slice")
ErrMustStruct = errors.New("sqle: dest must be a struct")
ErrMustNotNilPointer = errors.New("sqle: dest must be not a nil pointer")
ErrTypeNotBindable = errors.New("sqle: dest type is not bindable")
ErrMustStringKey = errors.New("sqle: map key must be string type")
)
type Row struct {
rows *sql.Rows
stmt *Stmt
err error
query string
}
func (r *Row) Close() error {
if r == nil {
return nil
}
if r.stmt != nil {
r.stmt.Reuse()
}
if r.rows == nil {
return nil
}
return r.rows.Close()
}
func (r *Row) Scan(dest ...any) error {
defer r.Close()
if r.err != nil {
return r.err
}
for _, dp := range dest {
if _, ok := dp.(*sql.RawBytes); ok {
return errors.New("sql: RawBytes isn't allowed on Row.Scan")
}
}
if !r.rows.Next() {
if err := r.rows.Err(); err != nil {
return err
}
return sql.ErrNoRows
}
err := r.rows.Scan(dest...)
if err != nil {
return err
}
// Make sure the query can be processed to completion with no errors.
return r.rows.Close()
}
func (r *Row) Err() error {
return r.err
}
func (r *Row) Bind(dest any) error {
defer r.Close()
if r.err != nil {
return r.err
}
v := reflect.ValueOf(dest)
if v.Kind() != reflect.Pointer {
return ErrMustPointer
}
if v.IsNil() {
return ErrMustNotNilPointer
}
var err error
if !r.rows.Next() {
err = r.rows.Err()
if err != nil {
return err
}
return sql.ErrNoRows
}
cols, err := getColumns(r.query, r.rows)
if err != nil {
return err
}
ok, err := scanTo(dest, v, cols, r.rows)
if ok {
return err
}
v = v.Elem()
switch v.Kind() {
case reflect.Struct:
err = scanToStruct(v, cols, r.rows)
if err != nil {
return err
}
case reflect.Map:
err = scanToMap(v, cols, r.rows)
if err != nil {
return err
}
default:
return ErrTypeNotBindable
}
// Make sure the query can be processed to completion with no errors.
return r.rows.Close()
}