-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscan.go
101 lines (78 loc) · 1.87 KB
/
scan.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
package crud
import (
"database/sql"
"reflect"
"github.com/azer/crud/v2/meta"
)
// Create a scanner for any given interface. This function will be called for
// every target interface passed to DB methods that scans results.
func NewScan(to interface{}) (*Scan, error) {
scan := &Scan{
To: to,
ToPointers: meta.HasPointers(to),
ToStructs: meta.HasAnyStruct(to),
}
if scan.ToStructs {
table, err := NewTable(to)
if err != nil {
return nil, err
}
scan.SQLColumnDict = table.SQLColumnDict()
}
return scan, nil
}
type Scan struct {
To interface{}
ToPointers bool
ToStructs bool
SQLColumnDict map[string]string
}
func (scan *Scan) All(rows *sql.Rows) error {
writeTo := meta.Addressable(scan.To)
for rows.Next() {
record := meta.CreateElement(scan.To)
if err := scan.Scan(rows, record); err != nil {
return err
}
meta.Push(writeTo, record)
}
return nil
}
func (scan *Scan) One(rows *sql.Rows) error {
for rows.Next() {
return scan.Scan(rows, meta.DirectValueOf(scan.To))
}
return sql.ErrNoRows
}
func (scan *Scan) Scan(rows *sql.Rows, record reflect.Value) error {
if scan.ToStructs {
return scan.ScanToStruct(rows, record)
}
if record.Kind() != reflect.Ptr {
return rows.Scan(record.Addr().Interface())
} else {
return rows.Scan(record.Interface())
}
}
func (scan *Scan) ScanToStruct(rows *sql.Rows, record reflect.Value) error {
columns, err := rows.Columns()
if err != nil {
return err
}
values := make([]interface{}, len(columns))
for i, column := range columns {
var field reflect.Value
fieldName := scan.SQLColumnDict[column]
if scan.ToPointers {
field = record.Elem().FieldByName(fieldName)
} else {
field = record.FieldByName(fieldName)
}
if field.IsValid() {
values[i] = field.Addr().Interface()
} else {
values[i] = &values[i]
}
}
return rows.Scan(values...)
}