Skip to content

Commit 29c6ce5

Browse files
committed
refactor: change iterator style to be interface instead of just functions
Signed-off-by: Andres Taylor <[email protected]>
1 parent 03b4009 commit 29c6ce5

File tree

1 file changed

+40
-29
lines changed

1 file changed

+40
-29
lines changed

go/data/query_log_parse.go

+40-29
Original file line numberDiff line numberDiff line change
@@ -24,33 +24,54 @@ import (
2424
"sync"
2525
)
2626

27-
type MySQLLogLoader struct{}
27+
type (
28+
MySQLLogLoader struct{}
29+
30+
mysqlLogReaderState struct {
31+
prevQuery string
32+
lineNumber int
33+
queryStart int
34+
scanner *bufio.Scanner
35+
err error
36+
closed bool
37+
mu sync.Mutex
38+
reg *regexp.Regexp
39+
fd *os.File
40+
}
41+
42+
statefulLoader interface {
43+
next() (Query, bool)
44+
close() error
45+
}
46+
47+
errLoader struct {
48+
err error
49+
}
50+
)
51+
52+
var _ statefulLoader = (*errLoader)(nil)
53+
54+
func (e *errLoader) close() error {
55+
return e.err
56+
}
57+
58+
func (e *errLoader) next() (Query, bool) {
59+
return Query{}, false
60+
}
2861

2962
func (MySQLLogLoader) Load(fileName string) ([]Query, error) {
30-
next, stop := MySQLLogLoader{}.Loadit(fileName)
63+
loader := MySQLLogLoader{}.Loadit(fileName)
3164

3265
var queries []Query
3366
for {
34-
query, ok := next()
67+
query, ok := loader.next()
3568
if !ok {
3669
break
3770
}
3871
queries = append(queries, query)
3972
}
4073

41-
return queries, stop()
42-
}
43-
44-
type mysqlLogReaderState struct {
45-
prevQuery string
46-
lineNumber int
47-
queryStart int
48-
scanner *bufio.Scanner
49-
err error
50-
closed bool
51-
mu sync.Mutex
52-
reg *regexp.Regexp
53-
fd *os.File
74+
return queries, loader.close()
5475
}
5576

5677
func (s *mysqlLogReaderState) next() (Query, bool) {
@@ -132,29 +153,19 @@ func (s *mysqlLogReaderState) close() error {
132153
return s.err
133154
}
134155

135-
func (MySQLLogLoader) Loadit(fileName string) (next func() (Query, bool), stop func() error) {
156+
func (MySQLLogLoader) Loadit(fileName string) statefulLoader {
136157
reg := regexp.MustCompile(`^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z)\s+(\d+)\s+(\w+)\s+(.*)`)
137158

138159
fd, err := os.OpenFile(fileName, os.O_RDONLY, 0)
139160
if err != nil {
140-
return errFail(err)
161+
return &errLoader{err}
141162
}
142163

143164
scanner := bufio.NewScanner(fd)
144165

145-
s := &mysqlLogReaderState{
166+
return &mysqlLogReaderState{
146167
scanner: scanner,
147168
reg: reg,
148169
fd: fd,
149170
}
150-
151-
return s.next, s.close
152-
}
153-
154-
func errFail(err error) (next func() (Query, bool), stop func() error) {
155-
return func() (Query, bool) {
156-
return Query{}, false
157-
}, func() error {
158-
return err
159-
}
160171
}

0 commit comments

Comments
 (0)