-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery_parser.go
More file actions
97 lines (84 loc) · 2.37 KB
/
Copy pathquery_parser.go
File metadata and controls
97 lines (84 loc) · 2.37 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
package unusedsqlc
import (
"bufio"
"fmt"
"os"
"regexp"
"strings"
)
// SQLQuery represents a sqlc query definition found in SQL files.
type SQLQuery struct {
Name string
Filename string
Line int
Type string
}
// QueryParser parses SQL files to find sqlc query definitions.
type QueryParser struct {
config *Config
queryPattern *regexp.Regexp
}
// NewQueryParser creates a new QueryParser with the given configuration.
func NewQueryParser(config *Config) *QueryParser {
if config == nil {
config = DefaultConfig()
}
return &QueryParser{
config: config,
queryPattern: regexp.MustCompile(`^--\s*name:\s+(\w+)\s+:(\w+)`),
}
}
// ParseDirectory parses all SQL files in the directory and returns found queries.
// It first attempts to use sqlc.yaml configuration if present.
func (p *QueryParser) ParseDirectory(dir string) ([]*SQLQuery, error) {
var allQueries []*SQLQuery
// Try to load sqlc.yaml configuration first
if HasSQLCConfig(dir) {
sqlcConfig, err := LoadSQLCConfig(dir)
if err == nil {
// Use query files from sqlc.yaml
queryFiles := sqlcConfig.GetQueryFiles(dir)
for _, file := range queryFiles {
if _, statErr := os.Stat(file); statErr == nil {
fileQueries, parseErr := p.ParseFile(file)
if parseErr == nil {
allQueries = append(allQueries, fileQueries...)
}
}
}
return allQueries, nil
}
}
// If no sqlc.yaml found, return error as this tool is for sqlc projects
return nil, fmt.Errorf("no sqlc.yaml or sqlc.yml found in %s", dir)
}
// ParseFile parses a single SQL file and returns all sqlc queries found.
func (p *QueryParser) ParseFile(filename string) ([]*SQLQuery, error) {
file, err := os.Open(filename)
if err != nil {
return nil, fmt.Errorf("opening file %s: %w", filename, err)
}
defer file.Close()
var queries []*SQLQuery
scanner := bufio.NewScanner(file)
lineNum := 0
for scanner.Scan() {
lineNum++
line := scanner.Text()
line = strings.TrimSpace(line)
const minMatches = 3
if matches := p.queryPattern.FindStringSubmatch(line); len(matches) >= minMatches {
query := &SQLQuery{
Name: matches[1],
Filename: filename,
Line: lineNum,
Type: matches[2],
}
queries = append(queries, query)
}
}
if scanErr := scanner.Err(); scanErr != nil {
return nil, fmt.Errorf("scanning file %s: %w", filename, scanErr)
}
return queries, nil
}