forked from johnwilson/restapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
qm.go
131 lines (104 loc) · 2.06 KB
/
qm.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
131
package plugins
import (
"bufio"
"fmt"
"io"
"os"
"regexp"
"strings"
"github.com/vulcangz/restapi/system"
)
type QM struct {
qm *QueryManager
}
func (qp *QM) Init(a *system.Application) error {
qm := newQueryManager()
// get config
fp := a.Config.Get("sqlqueries.path").(string)
f, err := os.Open(fp)
defer f.Close()
if err != nil {
return fmt.Errorf("query manager: sql file loading failed:\n%s", err)
}
// load queries
qm.Load(f)
qp.qm = qm
return nil
}
func (qp *QM) Get() interface{} {
return qp.qm
}
func (qp *QM) Close() error {
return nil
}
type QueryManager struct {
queries map[string]string
}
func newQueryManager() *QueryManager {
qm := new(QueryManager)
qm.queries = map[string]string{}
return qm
}
func (qm *QueryManager) Load(r io.Reader) {
scanner := SQLScanner{}
q := scanner.Run(bufio.NewScanner(r))
for k, v := range q {
qm.queries[k] = v
}
}
func (qm *QueryManager) Get(name string) string {
q, ok := qm.queries[name]
if !ok {
return ""
}
return q
}
type SQLScanner struct {
line string
queries map[string]string
current string
}
type stateFn func(*SQLScanner) stateFn
func getTag(line string) string {
re := regexp.MustCompile("^\\s*--\\s*name:\\s*(\\S+)")
matches := re.FindStringSubmatch(line)
if matches == nil {
return ""
}
return matches[1]
}
func initialState(s *SQLScanner) stateFn {
if tag := getTag(s.line); len(tag) > 0 {
s.current = tag
return queryState
}
return initialState
}
func queryState(s *SQLScanner) stateFn {
if tag := getTag(s.line); len(tag) > 0 {
s.current = tag
} else {
s.appendQueryLine()
}
return queryState
}
func (s *SQLScanner) appendQueryLine() {
current := s.queries[s.current]
line := strings.Trim(s.line, " \t")
if len(line) == 0 {
return
}
if len(current) > 0 {
current = current + "\n"
}
current = current + line
s.queries[s.current] = current
}
func (s *SQLScanner) Run(io *bufio.Scanner) map[string]string {
s.queries = make(map[string]string)
for state := initialState; io.Scan(); {
s.line = io.Text()
state = state(s)
}
return s.queries
}