This repository was archived by the owner on Mar 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathexecinquery.go
72 lines (62 loc) · 1.61 KB
/
execinquery.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
package execinquery
import (
"go/ast"
"strings"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
)
const doc = "execinquery is a linter about query string checker in Query function which reads your Go src files and warning it finds"
// Analyzer is checking database/sql pkg Query's function
var Analyzer = &analysis.Analyzer{
Name: "sqlint",
Doc: doc,
Run: run,
Requires: []*analysis.Analyzer{
inspect.Analyzer,
},
}
func run(pass *analysis.Pass) (interface{}, error) {
inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
inspect.Preorder(nil, func(n ast.Node) {
switch n := n.(type) {
case *ast.CallExpr:
selector, ok := n.Fun.(*ast.SelectorExpr)
if !ok {
break
}
if !strings.Contains(selector.Sel.Name, "Query") {
break
}
var i int
if strings.Contains(selector.Sel.Name, "Context") {
i = 1
}
var s string
switch arg := n.Args[i].(type) {
case *ast.BasicLit:
s = strings.Replace(arg.Value, "\"", "", -1)
case *ast.Ident:
stmt, ok := arg.Obj.Decl.(*ast.AssignStmt)
if !ok {
break
}
for _, stmt := range stmt.Rhs {
basicLit, ok := stmt.(*ast.BasicLit)
if !ok {
continue
}
s = strings.Replace(basicLit.Value, "\"", "", -1)
}
default:
break
}
if strings.HasPrefix(strings.ToLower(s), "select") {
break
}
s = strings.ToTitle(strings.Split(s, " ")[0])
pass.Reportf(n.Fun.Pos(), "It's better to use Execute method instead of %s method to execute `%s` query", selector.Sel.Name, s)
}
})
return nil, nil
}