-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.go
More file actions
229 lines (202 loc) · 5.36 KB
/
parser.go
File metadata and controls
229 lines (202 loc) · 5.36 KB
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
package sqlproc
import (
"bufio"
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
)
// ReturnKind indicates the expected result cardinality.
type ReturnKind string
const (
// ReturnOne indicates the procedure returns a single row.
ReturnOne ReturnKind = ":one"
// ReturnMany indicates the procedure returns multiple rows.
ReturnMany ReturnKind = ":many"
// ReturnExec indicates the procedure does not return rows.
ReturnExec ReturnKind = ":exec"
)
// Procedure represents a parsed stored procedure/function.
type Procedure struct {
Name string
SQLName string
File string
SQL string
Kind ReturnKind
Params []Param
Returns []Column
}
// Param describes a single procedure parameter.
type Param struct {
Name string
DBType string
}
// Column describes a column returned by the procedure.
type Column struct {
Name string
DBType string
}
// Parser parses SQL files containing stored procedures.
type Parser struct {
namePattern *regexp.Regexp
paramPattern *regexp.Regexp
returnsPattern *regexp.Regexp
funcPattern *regexp.Regexp
}
// NewParser creates a new Parser.
func NewParser() *Parser {
return &Parser{
namePattern: regexp.MustCompile(`--\s*name:\s*([A-Za-z0-9_]+)\s*(:(one|many|exec))`),
paramPattern: regexp.MustCompile(`--\s*param:\s*([A-Za-z0-9_]+)\s+(.+)`),
returnsPattern: regexp.MustCompile(`--\s*returns:\s*(.+)`),
funcPattern: regexp.MustCompile(`(?is)create\s+(or\s+replace\s+)?function\s+([A-Za-z0-9_\."]+)`),
}
}
// ParseFiles parses a list of SQL files.
func (p *Parser) ParseFiles(files []string) ([]*Procedure, error) {
var procedures []*Procedure
for _, file := range files {
proc, err := p.ParseFile(file)
if err != nil {
return nil, err
}
procedures = append(procedures, proc)
}
return procedures, nil
}
// ParseFile parses a single SQL file and extracts metadata plus SQL body.
func (p *Parser) ParseFile(path string) (*Procedure, error) {
fd, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("open SQL file: %w", err)
}
defer fd.Close()
proc := &Procedure{
File: path,
Params: make([]Param, 0),
Returns: make([]Column, 0),
}
scanner := bufio.NewScanner(fd)
var sqlLines []string
for scanner.Scan() {
line := scanner.Text()
trimmed := strings.TrimSpace(line)
if matches := p.namePattern.FindStringSubmatch(line); matches != nil {
proc.Name = matches[1]
proc.Kind = ReturnKind(matches[2])
continue
}
if matches := p.paramPattern.FindStringSubmatch(line); matches != nil {
proc.Params = append(proc.Params, Param{
Name: matches[1],
DBType: normalizeType(matches[2]),
})
continue
}
if matches := p.returnsPattern.FindStringSubmatch(line); matches != nil {
cols := p.parseColumns(matches[1])
proc.Returns = append(proc.Returns, cols...)
continue
}
if !strings.HasPrefix(trimmed, "--") {
sqlLines = append(sqlLines, line)
}
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("scan SQL file: %w", err)
}
proc.SQL = strings.TrimSpace(strings.Join(sqlLines, "\n"))
proc.SQLName = p.extractSQLName(proc.SQL)
if proc.SQLName == "" {
proc.SQLName = proc.Name
}
if err := proc.Validate(); err != nil {
return nil, fmt.Errorf("invalid procedure %s: %w", path, err)
}
return proc, nil
}
func (p *Parser) parseColumns(def string) []Column {
var columns []Column
for _, part := range strings.Split(def, ",") {
part = strings.TrimSpace(part)
if part == "" {
continue
}
segments := strings.Fields(part)
if len(segments) < 2 {
continue
}
name := segments[0]
dbType := normalizeType(strings.Join(segments[1:], " "))
columns = append(columns, Column{Name: name, DBType: dbType})
}
return columns
}
// CollectSQLFiles walks a directory and returns all .sql files.
func CollectSQLFiles(root string) ([]string, error) {
info, err := os.Stat(root)
if err != nil {
return nil, fmt.Errorf("stat path: %w", err)
}
if !info.IsDir() {
return []string{root}, nil
}
var files []string
err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
if strings.EqualFold(filepath.Ext(path), ".sql") {
files = append(files, path)
}
return nil
})
if err != nil {
return nil, fmt.Errorf("walk sql dir: %w", err)
}
return files, nil
}
func (p *Parser) extractSQLName(sql string) string {
if sql == "" || p.funcPattern == nil {
return ""
}
match := p.funcPattern.FindStringSubmatch(sql)
if len(match) < 3 {
return ""
}
name := strings.TrimSpace(match[2])
name = strings.TrimSuffix(name, "(")
if strings.HasPrefix(name, `"`) && strings.HasSuffix(name, `"`) && len(name) >= 2 {
name = strings.Trim(name, `"`)
}
return name
}
// Validate ensures required metadata is present.
func (p *Procedure) Validate() error {
if p.Name == "" {
return errors.New("missing -- name metadata")
}
switch p.Kind {
case ReturnOne, ReturnMany, ReturnExec:
default:
return fmt.Errorf("unknown return kind %q", p.Kind)
}
if p.SQLName == "" {
return errors.New("unable to determine SQL function name")
}
if p.Kind != ReturnExec && len(p.Returns) == 0 {
return errors.New("returning procedure must declare -- returns columns")
}
if p.SQL == "" {
return errors.New("procedure SQL body is empty")
}
return nil
}
func normalizeType(dbType string) string {
return strings.TrimSpace(strings.ToLower(dbType))
}