-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathmain.go
More file actions
187 lines (163 loc) · 4.14 KB
/
main.go
File metadata and controls
187 lines (163 loc) · 4.14 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
package main
import (
"fmt"
"os"
"path/filepath"
"sort"
"sync/atomic"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/houqp/sqlvet/pkg/cli"
"github.com/houqp/sqlvet/pkg/config"
"github.com/houqp/sqlvet/pkg/schema"
"github.com/houqp/sqlvet/pkg/vet"
)
const version = "1.1.11"
var (
gitCommit = "?"
flagErrFormat = false
flagSortOutput = false
)
// SQLVet includes Everything needed for check actions
type SQLVet struct {
QueryCnt int32
ErrCnt int32
Cfg config.Config
ProjectRoot string
Schema *schema.Db
SortOutput bool
}
func (s *SQLVet) reportError(format string, a ...interface{}) {
cli.Error(format, a...)
atomic.AddInt32(&s.ErrCnt, 1)
}
// Vet performs static analysis
func (s *SQLVet) Vet() {
queries, err := vet.CheckDir(
vet.NewContext(s.Schema.Tables),
s.ProjectRoot,
s.Cfg.BuildFlags,
s.Cfg.SqlFuncMatchers,
)
if err != nil {
cli.Exit(err)
}
// Sort queries by filename and line number if flag is set
if s.SortOutput {
sort.Slice(queries, func(i, j int) bool {
if queries[i].Position.Filename != queries[j].Position.Filename {
return queries[i].Position.Filename < queries[j].Position.Filename
}
return queries[i].Position.Line < queries[j].Position.Line
})
}
for _, q := range queries {
atomic.AddInt32(&s.QueryCnt, 1)
if q.Err == nil {
if cli.Verbose {
cli.Show("query detected at %s", q.Position)
}
continue
}
// an error in the query is detected
if flagErrFormat {
relFilePath, err := filepath.Rel(s.ProjectRoot, q.Position.Filename)
if err != nil {
relFilePath = s.ProjectRoot
}
// format ref: https://github.com/reviewdog/reviewdog#errorformat
cli.Show(
"%s:%d:%d: %v",
relFilePath, q.Position.Line, q.Position.Column, q.Err)
} else {
cli.Bold("%s @ %s", q.Called, q.Position)
if q.Query != "" {
cli.Show("\t%s\n", q.Query)
}
s.reportError("\tERROR: %v", q.Err)
switch q.Err {
case vet.ErrQueryArgUnsafe:
cli.Show("\tHINT: if this is a false positive, annotate with `// sqlvet: ignore` comment")
}
cli.Show("")
}
}
}
// PrintSummary dumps analysis stats into stdout
func (s *SQLVet) PrintSummary() {
cli.Show("Checked %d SQL queries.", s.QueryCnt)
if s.ErrCnt == 0 {
cli.Success("🎉 Everything is awesome!")
} else {
cli.Error("Identified %d errors.", s.ErrCnt)
}
}
// NewSQLVet creates SQLVet for a given project dir
func NewSQLVet(projectRoot string, sortOutput bool) (*SQLVet, error) {
cfg, err := config.Load(projectRoot)
if err != nil {
return nil, err
}
var dbSchema *schema.Db
if cfg.SchemaPath != "" {
dbSchema, err = schema.NewDbSchema(filepath.Join(projectRoot, cfg.SchemaPath))
if err != nil {
return nil, err
}
if !flagErrFormat {
cli.Show("Loaded DB schema from %s", cfg.SchemaPath)
for k, v := range dbSchema.Tables {
cli.Show("\ttable %s with %d columns", k, len(v.Columns))
}
}
} else {
if !flagErrFormat {
cli.Show("[!] No schema specified, will run without table and column validation.")
}
}
return &SQLVet{
Cfg: cfg,
ProjectRoot: projectRoot,
Schema: dbSchema,
SortOutput: sortOutput,
}, nil
}
func main() {
var rootCmd = &cobra.Command{
Use: "sqlvet PATH",
Short: "Go fearless SQL",
Args: cobra.ExactArgs(1),
Version: fmt.Sprintf("%s (%s)", version, gitCommit),
PreRun: func(cmd *cobra.Command, args []string) {
if cli.Verbose {
log.SetLevel(log.DebugLevel)
}
},
Run: func(cmd *cobra.Command, args []string) {
projectRoot := args[0]
s, err := NewSQLVet(projectRoot, flagSortOutput)
if err != nil {
cli.Exit(err)
}
s.Vet()
if !flagErrFormat {
s.PrintSummary()
}
if s.ErrCnt > 0 {
os.Exit(1)
}
},
}
rootCmd.PersistentFlags().BoolVarP(
&cli.Verbose, "verbose", "v", false, "verbose output")
rootCmd.PersistentFlags().BoolVarP(
&flagErrFormat, "errorformat", "e", false,
"output error in errorformat fromat for easier integration")
rootCmd.PersistentFlags().BoolVarP(
&flagSortOutput, "sort", "s", false,
"sort output by filename and line number")
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}