forked from prashanthpai/sqlcache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
recorder.go
73 lines (60 loc) · 1.27 KB
/
recorder.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
package sqlcache
import (
"database/sql/driver"
"io"
"github.com/prashanthpai/sqlcache/cache"
)
func newRowsRecorder(setter func(item *cache.Item), rows driver.Rows, maxRows int) *rowsRecorder {
return &rowsRecorder{
item: new(cache.Item),
setter: setter,
maxRows: maxRows,
dr: rows,
}
}
type rowsRecorder struct {
item *cache.Item
setter func(item *cache.Item)
gotErr bool
gotEOF bool
maxRowsHit bool
maxRows int
dr driver.Rows
}
func (r *rowsRecorder) Columns() []string {
r.item.Cols = r.dr.Columns()
return r.item.Cols
}
func (r *rowsRecorder) Close() error {
if err := r.dr.Close(); err != nil {
r.gotErr = true
return err
}
// cache only if we've reached EOF without any errors
// and without hitting max rows limit
if r.gotEOF && !r.gotErr && !r.maxRowsHit {
r.setter(r.item)
}
return nil
}
func (r *rowsRecorder) Next(dest []driver.Value) error {
err := r.dr.Next(dest)
if err != nil {
if err == io.EOF {
r.gotEOF = true
} else {
r.gotErr = true
}
}
if r.gotEOF || r.gotErr || r.maxRowsHit {
return err
}
if len(r.item.Rows) == r.maxRows {
r.maxRowsHit = true
return err
}
cpy := make([]driver.Value, len(dest))
copy(cpy, dest)
r.item.Rows = append(r.item.Rows, cpy)
return err
}