-
Notifications
You must be signed in to change notification settings - Fork 0
/
resultset.go
78 lines (62 loc) · 1.48 KB
/
resultset.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
package mysqlkebab
import (
"database/sql"
"encoding/json"
"fmt"
)
const resultsetFirstRow uint = 0
type Resultset struct {
pointer uint
columns []string
columnTypes []string
records []Row
err error
debugPrint bool
}
func (r Resultset) Count() int {
return len(r.records)
}
// Bottom returns true if the cursor reached its final row
func (r Resultset) Bottom() bool {
var (
l = len(r.records)
hasRecords = l > 0
lastItem = r.pointer > uint(l)
)
return hasRecords && lastItem
}
// Top returns true if the cursor is set on first item
func (r Resultset) Top() bool {
return len(r.records) > 0 && r.pointer == 0
}
// Next returns true if there's a next item and position the internal cursonr on it
func (r *Resultset) Next() bool {
if r == nil || len(r.records) == 0 || r.pointer >= uint(len(r.records)) {
return false
}
r.pointer++
return true
}
// Row returns the current row, set by the internal pointer/position.
func (r *Resultset) Row() (Row, error) {
if r == nil || len(r.records) == 0 {
return Row{}, fmt.Errorf("there's no current row")
}
if r.Bottom() {
return Row{}, fmt.Errorf("cursor has reached bottom")
}
return r.records[r.pointer-1], nil
}
func (r *Resultset) Rewind() {
r.pointer = resultsetFirstRow
}
func (r Resultset) JSON() (string, error) {
if len(r.records) > 0 {
if str, err := json.Marshal(r.records); err == nil {
return string(str), nil
} else {
return "", err
}
}
return "", sql.ErrNoRows
}