This repository has been archived by the owner on Jan 8, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
scan.go
130 lines (103 loc) · 2.44 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
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 gomodel
import "database/sql"
type (
// Store defines the interface to store data from databqase rows
Store interface {
// Init will be called twice, first to allocate initial data space, second to specified
// the final row count
// Init initial the data store with size rows, if size is not enough,
// Realloc will be called
Init(size int)
// Final indicate the last found rows
Final(size int)
// Ptrs should store pointers of data store at given index to the ptr parameter
Ptrs(index int, ptrs []interface{})
// Realloc will occurred if the initial size is not enough, only occured
// when call the All method of Scanner.
// The return value shold be the new size of Store.
// If don't want to continue, just return a non-positive number.
Realloc(currSize int) (latest int)
}
// Scanner scan database rows to data Store when Error is nil, if the Rows is
// empty, sql.ErrNoRows was returned, the Rows will always be be Closed
Scanner struct {
Error error
Rows *sql.Rows
Stmt Stmt
}
)
func (sc Scanner) Close() {
stmt := sc.Stmt
sc.Stmt = nil
if stmt != nil {
stmt.Close()
}
}
func _rowCount(c int) int {
const DEFAULT_ROW_COUNT = 10
if c >= 0 {
return c
}
return DEFAULT_ROW_COUNT
}
const (
_SCAN_ALL = true
_SCAN_LIMIT = !_SCAN_ALL
)
func (sc Scanner) multiple(s Store, count int, scanType bool) error {
if sc.Error != nil {
return sc.Error
}
defer sc.Close()
var (
index int
ptrs []interface{}
err error
)
rows := sc.Rows
defer rows.Close()
for rows.Next() && (index < count || scanType == _SCAN_ALL) {
if index == 0 {
cols, _ := rows.Columns()
s.Init(count)
ptrs = make([]interface{}, len(cols))
}
if index == count {
if count = s.Realloc(count); count <= 0 {
break // don't continue
}
}
s.Ptrs(index, ptrs)
if err = rows.Scan(ptrs...); err != nil {
return err
}
index++
}
if index == 0 {
err = sql.ErrNoRows
} else {
s.Final(index)
}
return err
}
func (sc Scanner) All(s Store, initsize int) error {
return sc.multiple(s, _rowCount(initsize), _SCAN_ALL)
}
func (sc Scanner) Limit(s Store, rowCount int) error {
return sc.multiple(s, _rowCount(rowCount), _SCAN_LIMIT)
}
func (sc Scanner) One(ptrs ...interface{}) error {
if sc.Error != nil {
return sc.Error
}
defer sc.Close()
rows := sc.Rows
defer rows.Close()
var err error
if rows.Next() {
err = rows.Scan(ptrs...)
} else {
err = sql.ErrNoRows
}
return err
}