/
scanner.go
56 lines (44 loc) · 1022 Bytes
/
scanner.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
package sqlexec
import (
"bufio"
"io"
"regexp"
"strings"
)
var nameRgxp = regexp.MustCompile("^\\s*--\\s*name:\\s*(\\S+)")
// Scanner loads a SQL statements for given SQL Script
type Scanner struct{}
// Scan scans a reader for SQL commands that have name tag
func (s *Scanner) Scan(reader io.Reader) map[string]string {
queries := make(map[string]string)
scanner := bufio.NewScanner(reader)
name := ""
for scanner.Scan() {
line := scanner.Text()
if tag := s.tag(line); tag != "" {
name = tag
} else if name != "" {
s.add(name, queries, line)
}
}
return queries
}
func (s *Scanner) tag(line string) string {
matches := nameRgxp.FindStringSubmatch(line)
if matches == nil {
return ""
}
return matches[1]
}
func (s *Scanner) add(name string, queries map[string]string, line string) {
current := queries[name]
line = strings.Trim(line, " \t")
if len(line) == 0 {
return
}
if len(current) > 0 {
current = current + "\n"
}
current = current + line
queries[name] = current
}