-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathparse.go
More file actions
241 lines (212 loc) · 5.72 KB
/
parse.go
File metadata and controls
241 lines (212 loc) · 5.72 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
230
231
232
233
234
235
236
237
238
239
240
241
package compiler
import (
"context"
"errors"
"fmt"
"strings"
"github.com/sqlc-dev/sqlc/internal/debug"
"github.com/sqlc-dev/sqlc/internal/metadata"
"github.com/sqlc-dev/sqlc/internal/opts"
"github.com/sqlc-dev/sqlc/internal/source"
"github.com/sqlc-dev/sqlc/internal/sql/ast"
"github.com/sqlc-dev/sqlc/internal/sql/astutils"
"github.com/sqlc-dev/sqlc/internal/sql/validate"
)
func (c *Compiler) parseQuery(stmt ast.Node, src string, o opts.Parser) (*Query, error) {
ctx := context.Background()
if o.Debug.DumpAST {
debug.Dump(stmt)
}
// validate sqlc-specific syntax
if err := validate.SqlcFunctions(stmt); err != nil {
return nil, err
}
// rewrite queries to remove sqlc.* functions
raw, ok := stmt.(*ast.RawStmt)
if !ok {
return nil, errors.New("node is not a statement")
}
rawSQL, err := source.Pluck(src, raw.StmtLocation, raw.StmtLen)
if err != nil {
return nil, err
}
if rawSQL == "" {
return nil, errors.New("missing semicolon at end of file")
}
name, cmd, err := metadata.ParseQueryNameAndType(rawSQL, metadata.CommentSyntax(c.parser.CommentSyntax()))
if err != nil {
return nil, err
}
if name == "" {
return nil, nil
}
if err := validate.Cmd(raw.Stmt, name, cmd); err != nil {
return nil, err
}
md := metadata.Metadata{
Name: name,
Cmd: cmd,
}
// TODO eventually can use this for name and type/cmd parsing too
cleanedComments, err := source.CleanedComments(rawSQL, c.parser.CommentSyntax())
if err != nil {
return nil, err
}
md.Params, md.Flags, md.RuleSkiplist, err = metadata.ParseCommentFlags(cleanedComments)
if err != nil {
return nil, err
}
var anlys *analysis
if c.databaseOnlyMode && c.expander != nil {
// In database-only mode, use the expander for star expansion
// and rely entirely on the database analyzer for type resolution
expandedQuery, err := c.expander.Expand(ctx, rawSQL)
if err != nil {
return nil, fmt.Errorf("star expansion failed: %w", err)
}
// Parse named parameters from the expanded query
expandedStmts, err := c.parser.Parse(strings.NewReader(expandedQuery))
if err != nil {
return nil, fmt.Errorf("parsing expanded query failed: %w", err)
}
if len(expandedStmts) == 0 {
return nil, errors.New("no statements in expanded query")
}
expandedRaw := expandedStmts[0].Raw
// Use the analyzer to get type information from the database
result, err := c.analyzer.Analyze(ctx, expandedRaw, expandedQuery, c.schema, nil)
if err != nil {
return nil, err
}
// Convert the analyzer result to the internal analysis format
var cols []*Column
for _, col := range result.Columns {
cols = append(cols, convertColumn(col))
}
var params []Parameter
for _, p := range result.Params {
params = append(params, Parameter{
Number: int(p.Number),
Column: convertColumn(p.Column),
})
}
// Determine the target table if applicable
var table *ast.TableName
switch n := expandedRaw.Stmt.(type) {
case *ast.InsertStmt:
table, _ = ParseTableName(n.Relation)
case *ast.UpdateStmt:
if n.Relations != nil && len(n.Relations.Items) > 0 {
if rv, ok := n.Relations.Items[0].(*ast.RangeVar); ok {
table, _ = ParseTableName(rv)
}
}
case *ast.DeleteStmt:
if n.Relations != nil && len(n.Relations.Items) > 0 {
if rv, ok := n.Relations.Items[0].(*ast.RangeVar); ok {
table, _ = ParseTableName(rv)
}
}
}
anlys = &analysis{
Table: table,
Columns: cols,
Parameters: params,
Query: expandedQuery,
}
} else if c.analyzer != nil {
inference, _ := c.inferQuery(raw, rawSQL)
if inference == nil {
inference = &analysis{}
}
if inference.Query == "" {
inference.Query = rawSQL
}
result, err := c.analyzer.Analyze(ctx, raw, inference.Query, c.schema, inference.Named)
if err != nil {
return nil, err
}
// If the query uses star expansion, verify that it was edited. If not,
// return an error.
stars := astutils.Search(raw, func(node ast.Node) bool {
_, ok := node.(*ast.A_Star)
return ok
})
hasStars := len(stars.Items) > 0
unchanged := inference.Query == rawSQL
if unchanged && hasStars {
return nil, fmt.Errorf("star expansion failed for query")
}
// FOOTGUN: combineAnalysis mutates inference
anlys = combineAnalysis(inference, result)
} else {
anlys, err = c.analyzeQuery(raw, rawSQL)
if err != nil {
return nil, err
}
}
expanded := anlys.Query
// If the query string was edited, make sure the syntax is valid
if expanded != rawSQL {
if _, err := c.parser.Parse(strings.NewReader(expanded)); err != nil {
return nil, fmt.Errorf("edited query syntax is invalid: %w", err)
}
}
trimmed, comments, err := source.StripComments(expanded)
if err != nil {
return nil, err
}
md.Comments = comments
q := &Query{
RawStmt: raw,
Metadata: md,
Params: anlys.Parameters,
Columns: anlys.Columns,
SQL: trimmed,
}
switch raw.Stmt.(type) {
case *ast.InsertStmt:
q.InsertIntoTable = anlys.Table
case *ast.UpdateStmt:
q.UpdateTable = anlys.Table
case *ast.DeleteStmt:
q.DeleteFromTable = anlys.Table
}
return q, nil
}
func rangeVars(root ast.Node) []*ast.RangeVar {
var vars []*ast.RangeVar
find := astutils.VisitorFunc(func(node ast.Node) {
switch n := node.(type) {
case *ast.RangeVar:
vars = append(vars, n)
}
})
astutils.Walk(find, root)
return vars
}
func uniqueParamRefs(in []paramRef, dollar bool) []paramRef {
m := make(map[int]bool, len(in))
o := make([]paramRef, 0, len(in))
for _, v := range in {
if !m[v.ref.Number] {
m[v.ref.Number] = true
if v.ref.Number != 0 {
o = append(o, v)
}
}
}
if !dollar {
start := 1
for _, v := range in {
if v.ref.Number == 0 {
for m[start] {
start++
}
v.ref.Number = start
o = append(o, v)
}
}
}
return o
}